-
Notifications
You must be signed in to change notification settings - Fork 55
/
index.js
70 lines (63 loc) · 1.65 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import fs from 'fs/promises'
import PDFMergerBase from './PDFMergerBase.js'
/**
* @typedef {import('fs/promises').PathLike} PathLike
*/
/**
* @typedef {import(./PDFMergerBase).PdfInput | Buffer | String | PathLike | string} PdfInput
*/
export default class PDFMerger extends PDFMergerBase {
/**
* Returns a Uint8Array of the input.
*
* If input is a string, it is treated as an Filepath
* If the file does not exist, it is treated as an URL.
*
* @async
* @protected
* @override
* @param {PdfInput} input
* @returns {Uint8Array}
*/
async _getInputAsUint8Array (input) {
if (input instanceof Buffer) {
return input
}
// strings can be a path to a (local) files or a external URL
if (typeof input === 'string' || input instanceof String) {
try {
await fs.access(input)
return await fs.readFile(input)
} catch (e) {
try {
Boolean(new URL(input))
input = new URL(input)
} catch (e) {
throw new Error(`The provided string "${input}" is neither a valid file-path nor a valid URL!`)
}
}
}
return await super._getInputAsUint8Array(input)
}
/**
* Return the merged PDF as a Buffer.
*
* @async
* @returns {Promise<Buffer>}
*/
async saveAsBuffer () {
const uInt8Array = await this._saveAsUint8Array()
return Buffer.from(uInt8Array)
}
/**
* Save the merged PDF to the given path.
*
* @async
* @param {string | PathLike} fileName
* @returns {Promise<void>}
*/
async save (fileName) {
const pdfBytes = await this._saveAsUint8Array()
await fs.writeFile(fileName, pdfBytes)
}
}