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:
- https://unpkg.com/pdf-lib/dist/pdf-lib.js
- https://unpkg.com/pdf-lib/dist/pdf-lib.min.js
- https://cdn.jsdelivr.net/npm/pdf-lib/dist/pdf-lib.js
- https://cdn.jsdelivr.net/npm/pdf-lib/dist/pdf-lib.min.js
NOTE: if you are using the CDN scripts in production, you should include a specific version number in the URL, for example:
- https://unpkg.com/[email protected]/dist/pdf-lib.min.js
- https://cdn.jsdelivr.net/npm/[email protected]/dist/pdf-lib.min.js
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>
Answer from Lakshitha Kanchana on Stack OverflowVideos
You have to set GlobalWorkerOptions.workerSrc to /build/pdf.worker(.min).js of same version:
pdfjsLib.GlobalWorkerOptions.workerSrc =
"https://cdn.jsdelivr.net/npm/[email protected]/build/pdf.worker.min.js";
pdfjsLib.getDocument('./ahmed.pdf').promise.then(doc => {
console.log(`This document has ${doc._pdfInfo.numPages} pages.");
});
And, as @Pasi has mentioned, you have to promisify .getDocument() by chaining .promise on it. Without it, there is no .then().
See the "Hello World with document load error handling" example on this page to get started: https://mozilla.github.io/pdf.js/examples/
(Your snippet is missing .promise after getDocument() and setting the workerSrc property)
» npm install pdf-lib