How to Generate a PDF with JavaScript?

Tutorials | HTML to PDF JavaScript · How to · ComPDFKit API Sat. 09 Dec. 2023

The internet abounds with a variety of templates for invoices, financial forms, and application forms, often displayed in HTML format on web pages. When you need to download these templates, they are typically converted into PDF files. Interestingly, this conversion process frequently utilizes JavaScript to generate PDF documents.

 

This article will give detailed integration steps to guide you on how to generate PDF files in JavaScript by html2pdf and the ComPDFKit API — That is to convert HTML to PDF. By the end of this piece, you'll be able to discern the advantages of using the ComPDFKit API to convert HTML to PDF.



Generate a PDF in JavaScript with html2pdf

 

html2pdf converts any webpage or element into a printable PDF entirely client-side using html2canvas and jsPDFjs.

 

Install html2pdf

 

Download the html2pdf javascript from GitHub. After you’ve downloaded the javascript, add a script tag to your HTML file:

<script src="html2pdf.bundle.min.js"></script>

 

Using html2pdf

 

Follow the code to convert an HTML to a PDF by html2pdf.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>HTML-to-PDF Example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <!-- html2pdf CDN link -->
    <script src="./html2pdf.bundle.min.js"></script>
  </head>
  <body>
    <button id="convert-button">Convert HTML to PDF</button>
    <div id="element-to-pdf">
      HTML to PDF
    </div>
    <script>
      const button = document.getElementById('convert-button');

      function convertToPDF() {
        
        const element = document.getElementById('element-to-pdf');
        // Convert the element and save the PDF.
        html2pdf().from(element).save();
      }

      button.addEventListener('click', convertToPDF);
    </script>
  </body>
</html>

 

Download an Invoice HTML as a PDF

 

As you can see in the code above, you can render the invoice template to the div element. Then use the convertToPDF() function to download the invoice as a PDF.



Generate a PDF in JavaScript with ComPDFKit API

 

Leverage the ComPDFKit API for seamless conversion of HTML content into PDF format within your JavaScript application by creating a ComPDFKit account. Access your license conveniently from the ComPDFKit dashboard and enjoy the benefit of processing up to 1,000 files for free every month.

 

Register ComPDFKit API

 

To begin issuing API requests, click here to sign up.

 

Call ComPDFKit API

 

1. Authentication

try {
  const response = await  fetch('https://api-server.compdf.com/server/v1/oauth/token', {
    method: 'POST',
    headers: { 
      'Content-Type': 'application/json'
    },
    data : JSON.stringify({
      publicKey: 'Your publicKey',
      secretKey: 'Your secretKey'
    })
  })
  // accessToken
  const accessToken = response.data.data.accessToken
} catch (error) {
  console.log(error)
}

 

2. Create Task

try {
  const response = await  fetch('https://api-server.compdf.com/server/v1/task/?language=2', {
    method: 'get',
    headers: { 
      'Authorization': `Bearer ${accessToken}` // accessToken which was obtained from the previous step
    }
  })
  // taskId
  const taskId = response.data.data.taskId
} catch (error) {
  console.log(error);
}

 

3. Upload Files

const url = 'https://api-server.compdf.com/server/v1/file/upload'

const formData = new FormData();
data.append('file', 'The file you upload'); // File
data.append('taskId', 'taskId'); // taskId obtained in the previous step
data.append('password', ''); // file password

try {
  const response = await fetch('https://api-server.compdf.com/server/v1/file/upload', {
    method: 'POST',
    headers: { 
      'Authorization': `Bearer ${accessToken}` // accessToken which was obtained from the Authentication step
    },
    data: formData
 })
  // fileKey
  const fileKey = response.data.data.fileKey
} catch (error) {
  console.log(error);
}

 

4. Process Files

try {
  // taskId you obtained from the Create task
  const response = await fetch(`https://api-server.compdf.com/server/v1/execute/start?taskId=${taskId}`, {
    method: 'GET',
    headers: { 
      'Authorization': `Bearer ${accessToken}` // accessToken which was obtained from the Authentication step
    },
  })
} catch (error) {
  console.log(error);
}

 

5. Get Task Information

try {
  // taskId you obtained from the Create task
  const response = fetch(`https://api-server.compdf.com/server/v1/task/taskInfo?taskId=${taskId}&language=2`, {
    method: 'GET',
    headers: { 
      'Authorization': `Bearer ${accessToken}` // accessToken which was obtained from the Authentication step
    },
  })
  const fileInfoDTOList = response.data.data.fileInfoDTOList
} catch (error) {
  console.log(error);
}

// The converted file information can be obtained in fileInfoDTOList

 

Download an Invoice HTML as a PDF

 

You provided an invoice template to download as a PDF. After the conversion is completed, you can obtain the converted link in fileInfoDTOList and download it.

 

Download an Invoice HTML as a PDF by ComPDFKit API



Why ComPDFKit API

 

ComPDFKit is a PDF API service that handles this conversion efficiently. Here’s why ComPDFKit API can be more advantageous for your project:

 

         - Flexibility: The ComPDFKit API offers outstanding flexibility, allowing developers to integrate PDF conversion into their applications seamlessly. Unlike libraries that may require specific environments or dependencies, the API can be called from any platform or programming language that supports HTTP requests. This means developers can use it in a wide array of contexts, including web, mobile, and desktop applications.

         - Ease of Use: Implementing a library can be time-consuming and may require additional setup, configuration, and maintenance. ComPDFKit API simplifies this process. After a quick setup, developers can make simple API calls, offloading the complex conversion process to the API's backend, which has been optimized for this specific task.

         - Scalilabity: As your application grows, your need capabilities may be more than converting HTML to PDF. ComPDFKit API empowers your programs with converting PDFs to/from .docx, .xlsx, .pptx, .txt, .rtf, .html, .csv, .png, .jpg, .json, etc. 

         - Quality and Consistency: ComPDFKit API prioritizes high-fidelity rendering, ensuring that the converted PDFs maintain the quality and layout of the original HTML content. This can be harder to achieve with libraries, especially across different environments and with complex web pages.

         - Security: Data security is paramount, especially when dealing with sensitive documents. ComPDFKit API ensures that data is transferred securely over HTTPS and that your information is handled according to industry-standard security practices.


ComPDFKit API provides 1000 file conversions per month for free. Just register and get your free conversion API requests. You can also try our free online demo to convert an HTML to a PDF.

Ready to Get Started?

Download our all-in-one ComPDFKit for free and run it to your project within minutes!