0

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.

Lakshitha Kanchana
  • 844
  • 2
  • 12
  • 32

1 Answers1

0

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/pdf-lib@1.17.1/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>
Lakshitha Kanchana
  • 844
  • 2
  • 12
  • 32
  • Here key is to note "PDFLib." part. We can access all the PDFLib functions as PDFLib.PDFDocument.create() or PDFLib.StandardFonts.TimesRoman or PDFLib.rgb(0, 0.53, 0.71) etc – Lakshitha Kanchana Dec 30 '22 at 05:47