sodcalculator

10 Tech How-To

Generate PDFs in JavaScript in the Browser

Guide 10-53427 · Updated · Step by step

This guide shows you how to generate PDF files directly in the browser using JavaScript, without needing a server. You’ll learn to create a PDF from scratch, add text and images, and let the user download the file. By the end, you’ll have a working script you can adapt for invoices, reports, or any other document.

What You’ll Need

  • A modern web browser (Chrome, Firefox, Edge, Safari)
  • A basic understanding of HTML and JavaScript
  • A code editor or online playground (like CodePen or JSFiddle)
  • Internet access to load the PDF library from a CDN

Step-by-Step

  1. Set up your HTML file.

    Create a new HTML file and add a button that will trigger the PDF generation. Also include a <script> tag to load the jsPDF library from a CDN. Here’s a minimal structure:

    <!DOCTYPE html>
    <html>
    <head>
      <title>PDF Generator</title>
    </head>
    <body>
      <button id="generate">Generate PDF</button>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
      <script src="app.js"></script>
    </body>
    </html>
  2. Create your JavaScript file.

    In a separate file (or inside a <script> tag), start by adding an event listener to the button:

    document.getElementById('generate').addEventListener('click', function() {
      // PDF generation code goes here
    });
  3. Initialize jsPDF.

    Inside the event listener, create a new instance of jsPDF. You can specify orientation, unit, and format. The default is portrait, millimeters, and A4:

    const { jsPDF } = window.jspdf;
    const doc = new jsPDF();
  4. Add text to the PDF.

    Use the text() method to add text. The first argument is the string, the second and third are x and y coordinates (in the unit you set). For example, to add a title at the top:

    doc.text('Hello World', 10, 10);
  5. Add a new page (optional).

    If your content exceeds one page, you can add a new page with doc.addPage(). This will move the cursor to the top of a fresh page:

    doc.addPage();
    doc.text('Page 2 content', 10, 10);
  6. Add an image (optional).

    You can add an image using addImage(). The image must be a data URL or a canvas element. For example, to add a canvas drawing:

    const canvas = document.createElement('canvas');
    canvas.width = 200;
    canvas.height = 200;
    const ctx = canvas.getContext('2d');
    ctx.fillStyle = 'blue';
    ctx.fillRect(0, 0, 200, 200);
    const imgData = canvas.toDataURL('image/png');
    doc.addImage(imgData, 'PNG', 10, 20, 50, 50);
  7. Save the PDF.

    Finally, use the save() method to trigger a download. The argument is the filename:

    doc.save('my-document.pdf');
  8. Test it.

    Open your HTML file in a browser and click the button. The PDF should download. If not, check the browser console (F12) for errors.

Common Mistakes

  • Forgetting to load the library: The script tag for jsPDF must come before your code that uses it. If you get an error like “jsPDF is not defined”, the library isn’t loaded.
  • Using wrong coordinates: jsPDF uses a coordinate system where (0,0) is the top-left corner. Units are in millimeters by default. If you’re used to pixels, things will look tiny or off-page.
  • Not converting canvas to data URL: When adding a canvas, you must call toDataURL() to get a string that jsPDF can use. Passing the canvas directly won’t work.
  • Overwriting the document: If you call new jsPDF() inside a loop, you’ll create a new document each time, losing previous content. Create one instance and reuse it.
  • Ignoring page breaks: jsPDF doesn’t automatically add page breaks. If your content goes beyond the page height (297mm for A4), it will be cut off. You need to check the Y position and call addPage() manually.

Tips

  • Use a monospace font for alignment: When generating text-based documents like invoices, using a monospace font (e.g., “Courier”) makes it easier to align columns.
  • Set font size and style: Use doc.setFontSize(size) and doc.setFont(style) (e.g., ‘bold’, ‘italic’) to format your text.
  • Add a footer with page numbers: You can loop through pages and add a page number at the bottom of each. For example: for (let i = 1; i <= doc.getNumberOfPages(); i++) { doc.setPage(i); doc.text('Page ' + i, 10, 290); }
  • Use doc.splitTextToSize() for wrapping: Long text will not wrap automatically. Use const lines = doc.splitTextToSize(text, maxWidth); and then loop through the lines to print them.
  • Test in multiple browsers: PDF generation may behave slightly differently across browsers. Always test in Chrome, Firefox, and Safari.

Troubleshooting

  • PDF downloads but is blank: Check if you added any content. If you only called save() without text() or addImage(), the PDF will be blank.
  • Text is cut off at the bottom: Your content is exceeding the page height. Add a check: if (y > 280) { doc.addPage(); y = 20; } and reset the Y coordinate.
  • Images appear black or distorted: Ensure the image is in a supported format (PNG, JPEG) and that you’re using the correct data URL. Also, check the width and height parameters.
  • Script errors in console: Open the browser’s developer console (F12) and look for red errors. Common ones include “Cannot read property ‘text’ of undefined” which means the jsPDF object wasn’t created properly.
  • PDF doesn’t download in some browsers: Some browsers (especially on mobile) may block automatic downloads. Consider opening the PDF in a new tab instead: doc.output('dataurlnewwindow').

Frequently Asked Questions

Can I generate a PDF without any library?

Yes, you can manually create a PDF file by constructing the PDF syntax as a string and saving it as a blob. However, this is complex and error-prone. Using a library like jsPDF is much simpler and more reliable.

Can I add HTML elements to the PDF?

jsPDF has an html() method that can convert HTML to PDF, but it requires html2canvas and often has layout limitations. It’s better to manually add text and images for precise control.

Can I generate a PDF from a canvas with high resolution?

Yes, you can increase the canvas resolution by scaling it. For example, set canvas.width to 2x the desired width, then use doc.addImage() with the appropriate dimensions.

How do I add a table to the PDF?

jsPDF doesn’t have a built-in table method. You can draw lines and text manually, or use the jspdf-autotable plugin, which creates styled tables easily.

Can I generate a PDF in the background without user interaction?

Yes, you can call the same functions on page load, but browsers may block the download if it’s not user-initiated. You can still generate and display the PDF in a new tab or embed it in an iframe.

Is jsPDF free to use?

Yes, jsPDF is open-source under the MIT license, so it’s free for commercial and personal use.

Related

General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.

More in this bed

The whole Tech How-To bed →