|
| 1 | +/*adding req PDFDocument module of pdf-lib and file systems lib, |
| 2 | +need to be downloaded in json package before implementing the code*/ |
| 3 | + |
| 4 | +const {PDFDocument} = require('pdf-lib'); |
| 5 | +const fileSys = require('fs'); |
| 6 | + |
| 7 | + |
| 8 | +// to catch and log errors |
| 9 | +mainFun().catch(errors => console.log(errors)); |
| 10 | + |
| 11 | + |
| 12 | +//async main_fun is declared |
| 13 | +async function mainFun(){ |
| 14 | + |
| 15 | + // an empty pdf is created using create() function of file systems |
| 16 | + const emptyPdf = await PDFDocument.create(); |
| 17 | + |
| 18 | + |
| 19 | + /*adding first pdf using readFileSync function of file systems |
| 20 | + await is used to make it wait while pdf1 is loading*/ |
| 21 | + |
| 22 | + const pdf1 = await PDFDocument.load(fileSys.readFileSync('./Hello.pdf')); |
| 23 | + |
| 24 | + |
| 25 | + /*adding second pdf |
| 26 | + await is used to make it wait while pdf2 is loading*/ |
| 27 | + |
| 28 | + const pdf2 = await PDFDocument.load(fileSys.readFileSync('./World.pdf')); |
| 29 | + |
| 30 | + |
| 31 | + /* pages of pdf1 are copied to empty pdf |
| 32 | + |
| 33 | + getPagesIndices() function of file systems is used to get number of pages in pdf1 |
| 34 | + to use it as range in for loop while traversing*/ |
| 35 | + const pagePdf1 = await emptyPdf.copyPages(pdf1, pdf1.getPageIndices()); |
| 36 | + |
| 37 | + |
| 38 | + |
| 39 | + //for loop is used to traverse pdf within its index to add pages to emptyPdf |
| 40 | + for (const page of pagePdf1) |
| 41 | + { |
| 42 | + |
| 43 | + //pages added using addPge() fun of file systems |
| 44 | + emptyPdf.addPage(page); |
| 45 | + } |
| 46 | + |
| 47 | + |
| 48 | +/* pages of pdf2 are copied to empty pdf |
| 49 | + |
| 50 | + getPagesIndices() function of file systems is used to get number of pages in pdf2 |
| 51 | + to use it as range in for loop while traversing*/ |
| 52 | + |
| 53 | + const pagePdf2 = await emptyPdf.copyPages(pdf2, pdf2.getPageIndices()); |
| 54 | + |
| 55 | + |
| 56 | + //for loop is used to traverse pdf within its index to add pages to emptyPdf |
| 57 | + for(const page of pagePdf2){ |
| 58 | + |
| 59 | + //pages added using addPge() fun of file systems |
| 60 | + emptyPdf.addPage(page); |
| 61 | + } |
| 62 | + |
| 63 | + |
| 64 | + /*using writerFileSync(), function of file sys |
| 65 | + contents of emptyPdf are wtitten over FinalMergePdf |
| 66 | +
|
| 67 | + save(): to save the pdf, final pdf will appear but won't process otherwise*/ |
| 68 | + |
| 69 | + fileSys.writeFileSync('./FinalMergedPdf.pdf', await emptyPdf.save()); |
| 70 | + |
| 71 | +} |
| 72 | + |
0 commit comments