How to Merge Two PDF Files Using jsPDF

巧了我就是萌 提交于 2020-12-07 04:55:14

问题


I'd like to know how to merge two (or more) PDF files into one single file using jsPDF and then show it using the browser's pdf viewer of the user.

My requirement is to make easier the process of printing a group of documents, instead of printing one by one just merge them all and print one single file.

I've looked at this other question here in Stack Overflow but that didn't help me too much because in this case they are creating the pdf from HTML content, and in my case i have to merge a set of pdf files together. Merge two PDF's generated with jsPDF into one document

I could get my PDF files from an url or also getting the raw content from them (the base64 code) so I was wondering if there's a way of using this library to do it. If so I only need to know what methods to use or maybe a link to the documentation (i've also seen documentation but nothing found)

Thankyou very much for your answers, any help would be appreciated. Regards!


回答1:


You can turn your jsPDF document into an array buffer (check here)

const doc = new jsPDF('p', 'mm', 'a4');
...
const arrayBuffer = doc.output('arraybuffer');

and then use the solution given here

async mergePdfs(pdfsToMerges: ArrayBuffer[]) {
  const mergedPdf = await PDFDocument.create();
  const actions = pdfsToMerges.map(async pdfBuffer => {
  const pdf = await PDFDocument.load(pdfBuffer);
  const copiedPages = await mergedPdf.copyPages(pdf, pdf.getPageIndices());
  copiedPages.forEach((page) => {
    // console.log('page', page.getWidth(), page.getHeight());
    // page.setWidth(210);
    mergedPdf.addPage(page);
    });
  });
  await Promise.all(actions);
  const mergedPdfFile = await mergedPdf.save();
  return mergedPdfFile;
}


来源:https://stackoverflow.com/questions/60234692/how-to-merge-two-pdf-files-using-jspdf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!