Read PDF Metadata (pdf-lib)

Read a PDF document's metadata with pdf-lib.

by Hopding

HTML

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

  <body>
    <p>Click the button to read a PDF document's metadata with <code>pdf-lib</code></p>
    <button onclick="readPdfMetadata()">Read PDF Metadata</button>
    <ul id="metadata-list"></ul>
  </body>

  <script>
    const { PDFDocument } = PDFLib

    async function readPdfMetadata() {
    	// Fetch PDF
      const pdfUrl = 'https://pdf-lib.js.org/assets/with_cropbox.pdf';
      const pdfBytes = await fetch(pdfUrl).then((res) => res.arrayBuffer());

      // Load the PDF document without updating its existing metadata
      const pdfDoc = await PDFDocument.load(pdfBytes, { 
        updateMetadata: false 
      })

			// Read all available metadata fields      
      const title = pdfDoc.getTitle();
      const author = pdfDoc.getAuthor();
      const subject = pdfDoc.getSubject();
      const creator = pdfDoc.getCreator();
      const keywords = pdfDoc.getKeywords();
      const producer = pdfDoc.getProducer();
      const creationDate = pdfDoc.getCreationDate();
      const modificationDate = pdfDoc.getModificationDate();
      
			// Display all available metadata fields   
      document.getElementById('metadata-list').innerHTML = `
        <li>
          Document: <a href="${pdfUrl}" target="_blank">${pdfUrl}</a>
        </li>
        <li>Title: ${title}</li>
        <li>Author: ${author}</li>
        <li>Creator: ${creator}</li>
        <li>Keywords: ${keywords}</li>
        <li>Producer: ${producer}</li>
        <li>Creation Date: ${creationDate.toISOString()}</li>
        <li>Modification Date: ${modificationDate.toISOString()}</li>
      `;
    }
  </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;
}