简体   繁体   English

pdf-lib 在前端合并 pdf

[英]pdf-lib merge pdfs on frontend

I'm trying to merge two pdf files on frontend using javascript and pdf-lib library.我正在尝试使用 javascript 和 pdf-lib 库在前端合并两个 pdf 文件。 I found this snippet pdf-lib in github repository:我在github存储库中找到了这个片段pdf-lib:

async function mergePdfs(pdfsToMerge: string[]) {
  const mergedPdf = await PDFDocument.create();
  for (const pdfCopyDoc of pdfsToMerge) {
    const pdfBytes = fs.readFileSync(pdfCopyDoc);
    const pdf = await PDFDocument.load(pdfBytes);
    const copiedPages = await mergedPdf.copyPages(pdf, pdf.getPageIndices());
    copiedPages.forEach((page) => {
      mergedPdf.addPage(page);
    });
  }
  const mergedPdfFile = await mergedPdf.save();
  return mergedPdfFile;
}

But as I see this snipped is for nodejs (there's no fs.readfilesync in browser javascript).但正如我所见,这是针对 nodejs 的(浏览器 javascript 中没有fs.readfilesync )。 So I have 2 questions:所以我有两个问题:

  1. what should I put in pdfsToMerge(string: []) ?我应该在pdfsToMerge(string: [])放什么? I have variables containing urls to pdf1 and pdf我有包含 pdf1 和 pdf url 的变量
  2. Also I have two variables containing base64 code of these pdfs.我还有两个变量包含这些 pdf 的base64代码。 How can I use this snippet not using fs.readfilesync like in nodejs but on frontend?我如何使用这个片段中不使用fs.readfilesync中的NodeJS但前端样?

Many thanks in advance!提前谢谢了!

The PDFDocument.load() method will accept base64 strings as the parameter so you don't need to do transform those at all. PDFDocument.load()方法将接受 base64 字符串作为参数,因此您根本不需要对它们进行转换。

As for your variables storing url paths to pdf documents, you can use fetch instead of node's file system.至于存储 pdf 文档的 url 路径的变量,您可以使用 fetch 而不是节点的文件系统。 As described in the pdf-lib docs, you can store the ArrayBuffer and pass that into PDFDocument.load() like so:如 pdf-lib 文档中所述,您可以存储 ArrayBuffer 并将其传递到PDFDocument.load()如下所示:

const url = 'https://pdf-lib.js.org/assets/with_update_sections.pdf'
const arrayBuffer = await fetch(url).then(res => res.arrayBuffer())
const pdfDoc = await PDFDocument.load(arrayBuffer)

Your version number should be newest pdf-lib你的版本号应该是最新的 pdf-lib

THen sequence of events matters.那么事件的顺序很重要。 Here is function i use must be in order of event I use is with data or emtpy to get filled or non filled pdf files这是我使用的功能必须按照我使用的事件顺序是数据或空以获取填充或未填充的 pdf 文件

async  copyPages(sale: Sale, url1, urlArray, isWithData, isEmptyForm) {
this.pdfService.getIsEmpty().subscribe(data => { isEmptyForm = data; });
this.pdfService.getIsWithData().subscribe(data => { isWithData = data; });
console.log(urlArray);
let donorBytes = [];
let donorBytesFInal = [];
let donorPage = [];
let donorDoc = [];
/**
 * first page get bytes from url
 * then load data
 * then convert the data bytes to pdfDocument 
 * later in routine this firstDonorDoc pages are inserted not added
 */
let firstDonorPdfBytes = await fetch(url1).then(res => res.arrayBuffer());
await this.loadDataTodocument(firstDonorPdfBytes, sale, isWithData, 
isEmptyForm).then(data => {
  firstDonorPdfBytes = data;
});

/**
 * load first document
 */
const firstDonorPdfDoc = await PDFDocument.load(firstDonorPdfBytes);

/**
 * load url array convert to bytes, send bytes to populate textfields with 
data
 */
for (let i = 0; i < urlArray.length; ++i) {
  console.log(urlArray.length);
  donorBytes[i] =  await fetch(urlArray[i].url).then(res => 
res.arrayBuffer());
}

/* Insert data to donorBytes and create DonorBytesFinal array with data */
// tslint:disable-next-line:prefer-for-of
for (let i = 0; i < donorBytes.length; ++i) {
await  this.loadDataTodocument(donorBytes[i], sale, isWithData, 
isEmptyForm).then(data 
 => {
    donorBytesFInal.push(data);
  });
}
//  console.log(donorBytesFInal);
/*
convert donor bytes to PdfDocument after bytes include data re 
 donorBytesFInal
*/
for (let i = 0; i < donorBytesFInal.length; ++i) {
  donorDoc[i] = await PDFDocument.load(donorBytesFInal[i]);
}
/* create out put document **/
const pdfDoc = await PDFDocument.create();

/**
 * copay first page... not in array
 */
const [firstDonorPage] = await pdfDoc.copyPages(firstDonorPdfDoc, [0]);

/**
 * copy all array pages of singular docuemnts output pdfdoc. Notices these 
 are insertpages nto addpage
 */
for (let i = 0; i < donorBytes.length; ++i) {
  [donorPage[i]] = await pdfDoc.copyPages(donorDoc[i], [0]);
  pdfDoc.insertPage(0, donorPage[i]);
}

/** first page is an ADDpage not an insert */
pdfDoc.addPage(firstDonorPage);

/** create tyes for 64 and 8 and update globally */
const u8 = await pdfDoc.save();
const n64 = await pdfDoc.saveAsBase64();
this.pdfService.changeUint8ByteArray(u8);
this.pdfService.changeBase64Array(n64);
const pdfBytes = u8;
 /** redundant empty urlarray */
urlArray = [];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM