Closed samezyane closed 2 years ago
Hello @samezyane!
I think the best way to solve this problem would be to support cloning/copying PDFPage
objects. And I certainly agree that this would be a useful feature to provide.
Until this feature lands in pdf-lib
, I've created a workaround you can use in https://github.com/Hopding/pdf-lib/issues/47#issuecomment-569315318. Please take a look at the full example, but here's the gist of it:
/* Copies a PDFPage object */
const copyPage = (originalPage) => { ... };
const pdfDoc = await PDFDocument.create();
const donorDoc = await PDFDocument.load(...);
const [page1] = await pdfDoc.copyPages(donorDoc, [0]);
const page2 = copyPage(page1);
const page3 = copyPage(page1);
pdfDoc.addPage(page1);
pdfDoc.addPage(page2);
pdfDoc.addPage(page3);
// Do page-specific rendering here...
I hope this helps. Please let me know if you have any additional questions!
Added this to the roadmap for tracking: https://github.com/Hopding/pdf-lib/discussions/998.
Library can really benefit from a hardcopy/clone functionality. I hit a similar bug today while trying to write some text on to the pdf and got it spread over multiple copied pages.
Hi,
I have an SVG backgound image that repeats in many pages, what I have done so far is the following:
const pdfDoc = await PDFDocument.create()
const imgPdfDoc = await PDFDocument.load(base64of('pdfFromSvg.pdf'))
const [imgPage] = await pdfDoc.copyPages(imgPdfDoc, [0])
const pdfPage = pdfDoc.insertPage(idx, imgPage)
do the specific rendering on the newly inserted 'pdfPage'
I think that there is room to enhance the performance if there is a 'copyPage' version of 'copyPages' that copy a single page from a source pdf and that returns multiple instances of the same page,
const pdfDoc = await PDFDocument.create()
const imgPdfDoc = await PDFDocument.load(base64of('pdfFromSvg.pdf'))
const imgPages = await pdfDoc.copyPage(imgPdfDoc, 0, N)
// copy the first page and return an array of N pagesconst pdfPage = pdfDoc.insertPage(idx, imgPages[idx])
do the specific rendering on the newly inserted 'pdfPage'
By inserting the same page, my tests show that for a backround image that repeats 70 times:
Regards,
Saeed