DEV Community

Marcin Wosinek
Marcin Wosinek

Posted on • Originally published at how-to.dev

How to create PDF in browser JS

In this article, I will share my experience with PDF libraries in browser-js & recommend pdf-lib.

How I got here

Pdf manipulation is a perfect task to include in js-bundler benchmarks. It happens among real-world requirements; the output is obviously either correct or broken, and you need a heavy library to get the job done. In some of my previous articles:

I needed some easy-to-use library, that I can integrate fast & focus on the rest of the task. First I got to PDFKit, but at the time it was building smooth in webpack 5, and it felt like setting my benchmark code will be really painful. Luckily, later I started my search from scratch and got to PDF-LIB. With this library, the integration was smooth and it worked perfectly out of the box.

Examples

The library documentation has a nice set of examples. Their hello word example:

<html>
  <head>
    <meta charset="utf-8" />
    <script src="https://unpkg.com/pdf-lib"></script>
  </head>

  <body>
    <iframe id="pdf" style="width: 100%; height: 100%;"></iframe>
  </body>

  <script>
    createPdf();
    async function createPdf() {
      const pdfDoc = await PDFLib.PDFDocument.create();
      const page = pdfDoc.addPage([350, 400]);
      page.moveTo(110, 200);
      page.drawText('Hello World!');
      const pdfDataUri = await pdfDoc.saveAsBase64({ dataUri: true });
      document.getElementById('pdf').src = pdfDataUri;
    }
  </script>
</html>
Enter fullscreen mode Exit fullscreen mode

is what I used as base code in my benchmarks, and you can see it in action here:
https://marcin-wosinek.github.io/esbuild-loader-pdf-lib/

Summary

My way of getting into PDF creation was nonstandard, but PDF-LIB was very smooth to integrate. I'm not sure how it compares with the others in more advanced tasks, but PDF manipulation can get complicated on its own so I appreciate that the library doesn't give headaches on the setup. What are your experience with PDF libraries in javascript?

Top comments (0)