Draw SVG Paths (pdf-lib)

Draw SVG paths 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 draw SVG paths with <code>pdf-lib</code></p>
    <button onclick="drawSvgPaths()">Create PDF</button>
    <p class="small">(Your browser will download the resulting file)</p>
  </body>

  <script>
    const { PDFDocument, rgb } = PDFLib

    async function drawSvgPaths() {
      // SVG path for a wavy line
      const svgPath =
        'M 0,20 L 100,160 Q 130,200 150,120 C 190,-40 200,200 300,150 L 400,90'

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

      // Add a blank page to the document
      const page = pdfDoc.addPage()
      page.moveTo(100, page.getHeight() - 5)

      // Draw the SVG path as a black line
      page.moveDown(25)
      page.drawSvgPath(svgPath)

      // Draw the SVG path as a thick green line
      page.moveDown(200)
      page.drawSvgPath(svgPath, { borderColor: rgb(0, 1, 0), borderWidth: 5 })

      // Draw the SVG path and fill it with red
      page.moveDown(200)
      page.drawSvgPath(svgPath, { color: rgb(1, 0, 0) })

      // Draw the SVG path at 50% of its original size
      page.moveDown(200)
      page.drawSvgPath(svgPath, { scale: 0.5 })

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

			// Trigger the browser to download the PDF document
      download(pdfBytes, "pdf-lib_creation_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;
}