Add Attachments (pdf-lib)

Add JPEG and PDF attachments to 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 create a document and attach a JPEG image and PDF file with <code>pdf-lib</code></p>
    <button onclick="addAttachments()">Create PDF</button>
    <p class="small">(Your browser will download the resulting file)</p>
  </body>

  <script>
    const { PDFDocument, rgb } = PDFLib

    async function addAttachments() {
			// Define attachment URLs
      const jpgUrl = 'https://pdf-lib.js.org/assets/cat_riding_unicorn.jpg'
      const pdfUrl = 'https://pdf-lib.js.org/assets/us_constitution.pdf';

			// Fetch attachments
      const jpgAttachmentBytes = await fetch(jpgUrl).then(res => res.arrayBuffer())
      const pdfAttachmentBytes = await fetch(pdfUrl).then(res => res.arrayBuffer())
  

      // Create a new PDFDocument
      const pdfDoc = await PDFDocument.create()

      // Add the JPG attachment
      await pdfDoc.attach(jpgAttachmentBytes, 'cat_riding_unicorn.jpg', {
        mimeType: 'image/jpeg',
        description: 'Cool cat riding a unicorn! ๐Ÿฆ„๐Ÿˆ๐Ÿ•ถ๏ธ',
        creationDate: new Date('2019/12/01'),
        modificationDate: new Date('2020/04/19'),
      })

      // Add the PDF attachment
      await pdfDoc.attach(pdfAttachmentBytes, 'us_constitution.pdf', {
        mimeType: 'application/pdf',
        description: 'Constitution of the United States ๐Ÿ‡บ๐Ÿ‡ธ๐Ÿฆ…',
        creationDate: new Date('1787/09/17'),
        modificationDate: new Date('1992/05/07'),
      })

      // Add a page with some text
      const page = pdfDoc.addPage();
      page.drawText('This PDF has two attachments', { x: 135, y: 415 })

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

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

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