Modify Document (pdf-lib)

Modify an existing PDF document with pdf-lib

by Rapha Souza

HTML

<html>
  <head>
    <meta charset="utf-8" />
    <script src="https://unpkg.com/[email protected]"></script>
    <script src="https://unpkg.com/[email protected]"></script>
  </head>

  <body>
    <p>Click the button to modify an existing PDF document with <code>pdf-lib</code></p>
    <button onclick="modifyPdf()">Modify PDF</button>
    <p class="small">(Your browser will download the resulting file)</p>
  </body>

  <script>

    function modifyPdf() {
     const { degrees, PDFDocument, rgb, StandardFonts } = PDFLib
      import { PageSizes } from 'pdf-lib'
    
    // Fetch an existing PDF document
    const url = 'https://pdf-lib.js.org/assets/with_update_sections.pdf'
    const existingPdfBytes = await fetch(url).then(res => res.arrayBuffer())

    const newPage3 = pdfDoc.addPage([500, 750])
    // Load a PDFDocument from the existing PDF bytes
    const pdfDoc1 = await PDFDocument.create()
    const pdfDoc2 = await PDFDocument.load(existingPdfBytes)

    const [existingPage] = await pdfDoc1.copyPages(pdfDoc2, [0])
    pdfDoc1.addPage(existingPage)


    // Serialize the PDFDocument to bytes (a Uint8Array)
    const pdfBytes = await pdfDoc.save()

    // Trigger the browser to download the PDF document
    download(pdfBytes, "pdf-lib_modification_example.pdf", "application/pdf");




}
  </script>
</html>

CSS

body {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

p {
  font-family: helvetica;
  font-size: 24px;
  text-align: center;
  margin: 25px;
}

.small {
  font-family: helvetica;
  font-size: 18px;
  text-align: center;
  margin: 25px;
}

button {
  background-color: #008CBA;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  font-size: 16px;
}