# How to create PDF in browser JS

In this article, I will share my experience with PDF libraries in browser-js & recommend [pdf-lib](https://pdf-lib.js.org/).

# 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:
* [How to lazy load in webpack 5](https://how-to.dev/how-to-lazy-load-library-in-webpack-5) 
* [How to speed up webpack with esbuild-loader](https://how-to.dev/how-to-speed-up-webpack-with-esbuild-loader)

I needed some easy-to-use library, that I can integrate fast & focus on the rest of the task. First I got to [PDFKit](https://www.npmjs.com/package/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](https://pdf-lib.js.org/). 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](https://pdf-lib.js.org/#examples). Their hello word example:
```html
<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>
```

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?
