Hopding / pdf-lib

Create and modify PDF documents in any JavaScript environment
https://pdf-lib.js.org
MIT License
6.78k stars 647 forks source link

[Feature Request]: Clone pages #169

Closed samezyane closed 2 years ago

samezyane commented 5 years ago

Hi,

I have an SVG backgound image that repeats in many pages, what I have done so far is the following:

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,

By inserting the same page, my tests show that for a backround image that repeats 70 times:

Regards,

Saeed

Hopding commented 4 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!

Hopding commented 2 years ago

Added this to the roadmap for tracking: https://github.com/Hopding/pdf-lib/discussions/998.

mericaliyigit commented 4 months ago

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.