How to use Hopding / pdf-lib with pure javascript? (Without using a package manager)

1.3k Views Asked by At

How can I use Hopding/pdf-lib with pure javascript without using node or any other package manager?

I have noticed that they have mentioned supporting pure JavaScript. But not mentioned how?

enter image description here

I searched and I found the answer myself, it took long. So I decided to put it here so that anyone can refer it faster.

1

There are 1 best solutions below

1
On

You can use the UMD Module as mentioned in their GitHub page. Here are some of the useful information I extracted from their GitHub page.

UMD Module

You can also download pdf-lib as a UMD module from unpkg or jsDelivr. The UMD builds have been compiled to ES5, so they should work in any modern browser. UMD builds are useful if you aren't using a package manager or module bundler. For example, you can use them directly in the tag of an HTML page.

The following builds are available:

NOTE: if you are using the CDN scripts in production, you should include a specific version number in the URL, for example:

Example:

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

  <body>
    <div style="display: flex; width: 100%; height: 100%; flex-direction: column; overflow: hidden;">
        <iframe id="pdf" style="flex-grow: 1; border: none; margin: 0; padding: 0;"></iframe>
    </div>
  </body>
  <script type="text/javascript" src="https://unpkg.com/[email protected]/dist/pdf-lib.min.js"></script>
  <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>