Fill Form (pdf-lib)

Fill form fields in a PDF document with pdf-lib

by Hopding

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 fill form fields in an existing PDF document with <code>pdf-lib</code></p>
    <button onclick="fillForm()">Fill PDF</button>
    <p class="small">(Your browser will download the resulting file)</p>
  </body>

  <script>
    const { PDFDocument } = PDFLib

    async function fillForm() {
    	// Fetch the PDF with form fields
      const formUrl = 'https://pdf-lib.js.org/assets/dod_character.pdf'
      const formPdfBytes = await fetch(formUrl).then(res => res.arrayBuffer())

			// Fetch the Mario image
      const marioUrl = 'https://pdf-lib.js.org/assets/small_mario.png'
      const marioImageBytes = await fetch(marioUrl).then(res => res.arrayBuffer())

			// Fetch the emblem image
      const emblemUrl = 'https://pdf-lib.js.org/assets/mario_emblem.png'
      const emblemImageBytes = await fetch(emblemUrl).then(res => res.arrayBuffer())

      // Load a PDF with form fields
      const pdfDoc = await PDFDocument.load(formPdfBytes)

      // Embed the Mario and emblem images
      const marioImage = await pdfDoc.embedPng(marioImageBytes)
      const emblemImage = await pdfDoc.embedPng(emblemImageBytes)

      // Get the form containing all the fields
      const form = pdfDoc.getForm()

      // Get all fields in the PDF by their names
      const nameField = form.getTextField('CharacterName 2')
      const ageField = form.getTextField('Age')
      const heightField = form.getTextField('Height')
      const weightField = form.getTextField('Weight')
      const eyesField = form.getTextField('Eyes')
      const skinField = form.getTextField('Skin')
      const hairField = form.getTextField('Hair')

      const alliesField = form.getTextField('Allies')
      const factionField = form.getTextField('FactionName')
      const backstoryField =...

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;
}