Hopding / pdf-lib

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

Copying pages multiple times does not work in Chrome, but does in Safari #1486

Open totope8236 opened 1 year ago

totope8236 commented 1 year ago

What were you trying to do?

Hi,

I have a template document that I am trying to copy multiple times into a target document (the one I am creating). In other words, I want to use page 1 of my template as the background of all the odd pages in the final doc, and page 2 for all the even pages.

My current implementation works in Safari, but nothing shows up in chrome (it does not render at all). What am I doing wrong?

How did you attempt to do it?

` async function copy_document(src, destination){ var l = src.getPages().length; for (var i =0; i<l; i++){ await destination.addPage((await destination.copyPages(src, [i]))[0]); } }

async function createPdf() { // LOAD TEMPLATE const url = 'http://christophecaron.ca/consultation.pdf' const existingPdfBytes = await fetch(url).then(res => res.arrayBuffer()); const template = await PDFLib.PDFDocument.load(existingPdfBytes);

const pdfDoc = await PDFLib.PDFDocument.create();

//copying 2 times
await copy_document(template, pdfDoc);

await copy_document(template, pdfDoc);

// adding text as a test. // FONT const timesRomanFont = await pdfDoc.embedFont(PDFLib.StandardFonts.TimesRoman);

const pages = pdfDoc.getPages() const firstPage = pages[3]; const { width, height } = firstPage.getSize(); const fontSize = 12; firstPage.drawText('Creating PDFs in JavaScript is awesome!', { x: 53, y: 381, size: fontSize, font: timesRomanFont, color: PDFLib.rgb(0, 0, 0), });

// ADD DATE TO BOTTOM OF PAGE

firstPage.drawText(moment().format("YYYY     MM        DD      HH  mm"), {
    x: 86,
    y: 72,
    size: 12,
    font: timesRomanFont,
    color: PDFLib.rgb(0, 0, 0),
});

// drawing the pdf on the page. const pdfBytes = await pdfDoc.save(); const pdfDataUri = await pdfDoc.saveAsBase64({ dataUri: true }); document.getElementById('pdf').src = pdfDataUri; }

`

What actually happened?

Nothing shows up in chrome.

What did you expect to happen?

I expected to have a 4-page document consisting of the template one copied twice.

How can we reproduce the issue?

Use code above

Version

last

What environment are you running pdf-lib in?

Browser

Checklist

Additional Notes

No response