How to Build a JavaScript PDF Editor with pdf-lib
Tags: webdev, javascript, pdf, opensource
Published: 2024-05-29 09:57:24

PDF-lib is an open-source and free JavaScript library for creating, editing, and modifying PDF documents, which is commonly used in Web development projects. In this post, you will learn how to use this [open source PDF library](https://www.compdf.com/blog/open-source-pdf-libraries-vs-compdfkit) to build a JavaScript PDF editor from installation to specific features. Meanwhile, we introduce a great [pdf-lib alternative](https://compdf.com/) for those seeking advanced PDF manipulation capabilities.
 
## Build a JavaScript PDF Editor with pdf-lib
 
### 1. Get Start
After installing pdf-lib using npm, you can quickly start by saving the following codes as an HTML file and loading it in your browser.

```
<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>
``` 

### 2. Code Sample: Create Document
Once you have successfully initialized pdf-lib in your Web application, you can utilize it to integrate the functionality to create PDF documents with the below example.

```
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib'

async function createPdf() {
  const pdfDoc = await PDFDocument.create()
  const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman)

  const page = pdfDoc.addPage()
  const { width, height } = page.getSize()
  const fontSize = 30
  page.drawText('Creating PDFs in JavaScript is awesome!', {
    x: 50,
    y: height - 4 * fontSize,
    size: fontSize,
    font: timesRomanFont,
    color: rgb(0, 0.53, 0.71),
  })

  const pdfBytes = await pdfDoc.save()
}
```

It is obvious that pdf-lib is an easy-to-integrate PDF library for building a PDF editor with JavaScript. However, due to its open-source nature, it may not fully meet the needs of developers seeking advanced PDF functionalities like watermarks, document comparison, and comprehensive technical support. Fortunately, ComPDFKit Web PDF SDK exceeds pdf-lib's capabilities, making it a superior alternative. Our JavaScript PDF library supports Standalone deployment powered by WebAssembly or Server-backed deployment with Docker based on your needs. 

 

## Build a JavaScript PDF Editor with ComPDFKit for Web
 
### Step 1. Install ComPDFKit Web PDF SDK
There are two ways to download ComPDFKit Web SDK. You can contact our sales team to obtain the local package. Or install our WebViewer from npm on your own and add it as a project dependency. 

```
npm i @compdfkit_pdf_sdk/webviewer --save
```

### Step 2. Integrate ComPDFKit Web PDF Library to Build JavaScript PDF Editor

 
#### Mannually Integrate ComPDFKit PDF Library for Web
If you downloaded the local ComPDFKit Web package, it is available to create a JavaScript PDF editor by Vanilla JavaScript and Vue, please respectively follow the steps below to integrate it manually.
 

##### Integrate into a Vanilla JavaScript Project
1. Create index.html

```
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ComPDFKit Web Viewer</title>
</head>
<!-- Import WebViewer as a script tag -->
<script src='@compdfkit/webviewer.global.js'></script>
<body>
  <div id="app" style="width: 100%; height: 100vh;"></div>
</body>
</html>
```

2. Add script tag and initialize ComPDFKitViewer for Web in JavaScript

```
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ComPDFKit Web Viewer</title>
</head>
<!-- Import WebViewer as a script tag -->
<script src='@compdfkit/webviewer.global.js'></script>
<body>
  <div id="app" style="width: 100%; height: 100vh;"></div>

  <script>
    let docViewer = null;

    ComPDFKitViewer.init({
      pdfUrl: '/webviewer/example/developer_guide_web.pdf',
      license: 'Input your license here'
    }, document.getElementById('app')).then((core) => {
      docViewer = core.docViewer;

      docViewer.addEvent('documentloaded', async () => {
        console.log('document loaded');
      })
    })
  </script>
</body>
</html>
```

3. Set a server environment To show in the localhost, we need to set a server environment;
```
npm install -g http-server
```
4. Serve your website

```
http-server -a localhost -p 8080
``` 

Open http://localhost:8080 on your browser. Then you will be able to see the PDF file you want to display.

 
##### Integrate into a Vue Project

1. Add ComPDFKit for Web Package

​- Add the "@compdfkit" folder in the lib directory to the root directory or assets directory of your project. This will serve as the entry point for the ComPDFKit for Web and will be imported into your project.
- Add the "webviewer" folder that contains the required static resource files to run the ComPDFKit Web demo, to your project’s static resource folder.


2. Display a PDF Document
- Import the “webviewer.js” file in the "@compdfkit" folder into your project.
- Initialize the ComPDFKit for Web in your project by calling `ComPDFKitViewer.init()`.
- Pass the PDF address you want to display and your license key into the init function.

```
// Import the JS file of ComPDFKit Web Demo.
import ComPDFKitViewer from "/@compdfkit/webviewer";

const viewer = document.getElementById('webviewer');
ComPDFKitViewer.init({
  pdfUrl: 'Your PDF Url',
  license: 'Input your license here'
}, viewer)
.then((core) => {
  const docViewer = core.docViewer;
  docViewer.addEvent('documentloaded', () => {
    console.log('ComPDFKit Web Demo');
  })
})
``` 

Note: You need to contact ComPDFKit team to get the license.

4. Once your project is running, you will be able to see the PDF file you want to display.
 

#### Build JavaScript PDF Editor by Integrating via NPM

1. Copy Assets to Your Static Folder
These assets need to be served in your application. Copy the ComPDFKit for Web library's assets to the static directory in your project’s root folder.

The folder you need to copy is `node_modules/@compdfkit_pdf_sdk/webviewer/dist`.

```
cp -r ./node_modules/@compdfkit_pdf_sdk/webviewer/dist ./public/webviewer
```

2. Import and Initial the WebViewer

```
import WebViewer from '@compdfkit_pdf_sdk/webviewer'

const element = document.getElementById('viewer');

WebViewer({
  pdfUrl: 'URL of your PDF File' // the path of your document
  license: 'Input your license here'
}, element).then((instance) => {
  // Call APIs here
})
```

3. Apply the License Key
Get a free 30-day license by providing some information about your project to start testing.

### Step 3. Code Samples: Save a Document
ComPDFKit provides various code examples for developers to integrate different PDF features in a JavaScript PDF editor. Here is an example of saving a PDF document.

```
  // Import the JS file of ComPDFKit Web Demo.
import ComPDFKitViewer from "/@compdfkit/webviewer";

const viewer = document.getElementById('webviewer');
ComPDFKitViewer.init({
  pdfUrl: 'Your PDF Url',
  license: 'Input your license here'
}, viewer)
.then((core) => {
  const docViewer = core.docViewer;
  docViewer.addEvent('documentloaded',async () => {
    console.log('ComPDFKit Web Demo');

    const docStream = await docViewer.download()
    const docBlob = new Blob([docStream], { type: 'application/pdf' })
  })
})
```

## Bottom Line
pdf-lib is a popular and well-performing PDF library for building a JavaScript PDF viewer. For advanced PDF functions like PDF data extraction, OCR, etc., ComPDFKit PDF SDK for Web is more recommended. Not only does it provide detailed development guides, but also guarantees one-on-one technical support even though you are testing. Before integrating ComPDFKit Web PDF library into your projects using the 30-day free trial licenses, it is welcome to visit our online tools and Web Demo to process PDF files to experience how ComPDFKit performs.