I use pdflib
and it works perfectly for me. But I can't get it to write a message on all the pages of the PDF.
How can I make it so that, if I upload a 7 pages PDF, the message appears on all 7 pages. And if I upload a 5 pages PDF, it appears on all 5 pages.
And I tried using if
but I didn't get it in the end.
<script>
const {
degrees,
PDFDocument,
rgb,
StandardFonts
} = PDFLib
modifyPdf();
async function modifyPdf() {
// Fetch an existing PDF document
const url = '<?php echo $pdf;?>'
const existingPdfBytes = await fetch(url).then(res => res.arrayBuffer())
// Load a PDFDocument from the existing PDF bytes
const pdfDoc = await PDFDocument.load(existingPdfBytes)
// Embed the Helvetica font
const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica)
// Get the first page of the document
const pages = pdfDoc.getPages()
const firstPage = pages[0]
// Get the width and height of the first page
const {
width,
height
} = firstPage.getSize()
// Draw a string of text diagonally across the first page
firstPage.drawText('Firmado por <?php echo $usuarionombre;?>, en fecha <?php echo $fechafirma;?>!', {
x: 12,
y: height / 2 - 300,
size: 12,
font: helveticaFont,
color: rgb(0.95, 0.1, 0.1),
rotate: degrees(90),
//original ajustes.
// x: 5,
//y: height / 2 + 300,
//size: 12,
//font: helveticaFont,
//color: rgb(0.95, 0.1, 0.1),
//rotate: degrees(-90),
})
// Serialize the PDFDocument to bytes (a Uint8Array)
const pdfBytes = await pdfDoc.save()
// esto es para descargar el pdf
//download(pdfBytes, "pdf-lib_modification_example.pdf", "application/pdf");
// This step is only necessary if you don't already have a Buffer Object
var blob = new Blob([pdfBytes])
var reader = new FileReader();
reader.onload = function(event) {
var base64 = event.target.result
var res = base64.replace("data:application/octet-stream;base64,", "");
var sites = ['data:application/pdf;base64, ' + res]
document.getElementById('myIframe').src = sites[Math.floor(Math.random() * sites.length)];
};
reader.readAsDataURL(blob);
}
</script>
Not sure if it is the "diagonal message" that you are trying to write on all pages but if so, instead of only getting the first page with const firstPage = pages[0]
you should iterate on all pages
to use drawText()
on each page.
// Get document pages
const pages = pdfDoc.getPages()
// Iterate every pages
pages.forEach(page => {
// Get the width and height of the page
const {
width,
height
} = page.getSize()
// Draw a string of text diagonally across the page
page.drawText('Firmado por <?php echo $usuarionombre;?>, en fecha <?php echo $fechafirma;?>!', {
x: 12,
y: height / 2 - 300,
size: 12,
font: helveticaFont,
color: rgb(0.95, 0.1, 0.1),
rotate: degrees(90),
})
})