Home » Creating Dynamic PDFs with jsPDF in JavaScript

Creating Dynamic PDFs with jsPDF in JavaScript

jsPDF

In today’s digital world, PDFs are a commonly used format for documents and reports. One of the key features of a PDF is the ability to have fixed headers and footers, which provide essential information such as page numbers, author names, and the title of the document.

However, when it comes to dynamic content, it becomes a challenge to handle the pagination and add headers and footers on each page.

This blog post will look at how to generate a PDF with fixed headers and footers, and dynamic body content using the JavaScript library jsPDF.

We will go through the process step by step and explain how it works and its benefits and limitations.

Use this technique to create professional-looking PDFs with fixed headers, footers, and dynamic body content for documents such as invoices, reports, and resumes with minimal effort.


First, fixed headers and footers provide essential information about the document, such as page numbers, author names, and the title of the document. They make it easy for the reader to navigate the document and understand its structure. This is especially important for long documents or reports that span multiple pages.

Second, dynamic body content is important for generating PDFs that need to display information that changes frequently. For example, invoices, reports, resumes, or any other document that needs to be updated with new data.

Having a program that can handle dynamic body content eliminates the need to manually update the PDF every time the data changes.

Lastly, this functionality can be useful for businesses and organizations that need to generate and share reports, invoices, or other types of documents on a regular basis.

Automating the process of generating PDFs saves time, and resources, and ensures that all documents have a consistent look and feel.

In short, this functionality allows saving professional looking pdfs with minimal effort, adding essential information in the header and footer, and handling dynamic data in the body content. This makes it a powerful tool for creating several types of documents.


Let’s see how it works:

1. Include the jsPDF library from a CDN in the page head to utilize the library’s functions and methods without downloading and hosting it yourself.

// adding jsPDF cdn link
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>

2. Instantiating a new object of the jsPDF method.

 // Create a new PDF document
    var doc = new jsPDF();

3. Sets the header by defining a variable header with the text “This is the header which is fixed” and sets the font size to 12. It then uses the text() method of the doc object to add the header to the PDF, positioning it at the coordinates (10, 10) on the page.

Sets the footer in a comparable way to the header, but positioning it at the coordinate (10, doc.internal.pageSize.height - 10) on the page, which is the height of the page minus 10.

// Set the header
   var header = "This is the fixed header";
   doc.setFontSize(12);
   doc.text(header, 10, 10)

// Set the footer
   var footer = "This is the fixed footer";
   doc.setFontSize(12);
   doc.text(footer, 10, doc.internal.pageSize.height - 10);

4. Creates an array called bodyContent which contains the dynamic body content and sets the font size for the dynamic body content to 10.

// Set the dynamic body content
const bodyContent = ['Line 1 of body content', 'Line 2 of body content', 'Line 3 of body content', 'Line 4 of body content', 'Line 5 of body content', 'Line 6 of body content', 'Line 7 of body content', 'Line 8 of body content', 'Line 9 of body content', 'Line 10 of body content'];

doc.setFontSize(10);
let y = 20;

5. Use forEach loop to iterate through the bodyContent array. For each element in the array, it uses the text() method of the doc object to add the element to the PDF at the position (10, y), where y is a variable that starts at 20.

It checks if the value of y (which represents the y-coordinate on the page) is greater than or equal to doc.internal.pageSize.height - 20. If it is, the script creates a new page and sets the font size to 12. Then it adds the header and footer to the new page and sets the value of y to 20.

        bodyContent.forEach(function (element, index) {
                doc.text(element, 10, y);
                y += 10;
                if (y >= doc.internal.pageSize.height - 20) {
                    doc.setFontSize(12);
                    doc.addPage();
                    doc.text(header, 10, 10);
                    doc.text(footer, 10, doc.internal.pageSize.height - 10);
                    y = 20;
                }
        });

6. Finally, it saves the PDF by calling the save() method of the doc object, passing in the filename “example.pdf”.

// Save the PDF
   doc.save("example.pdf");

Full example to understand in a better way:

<!DOCTYPE html>
<html>

<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
    <script>
        function generatePDF() {
            // Create a new PDF document
            var doc = new jsPDF();

            // Set the header
            var header = "This is the fixed header";
            doc.setFontSize(12);
            doc.text(header, 10, 10);

            // Set the footer
            var footer = "This is the fixed footer";
            doc.setFontSize(12);
            doc.text(footer, 10, doc.internal.pageSize.height - 10);

            // Set the dynamic body content
            const bodyContent = ['Line 1 of body content', 'Line 2 of body content', 'Line 3 of body content', 'Line 4 of body content', 'Line 5 of body content', 'Line 6 of body content', 'Line 7 of body content', 'Line 8 of body content', 'Line 9 of body content', 'Line 10 of body content'];

            doc.setFontSize(10);

            let y = 20;

            bodyContent.forEach(function (element, index) {
                doc.text(element, 10, y);
                y += 10;
                if (y >= doc.internal.pageSize.height - 20) {
                    doc.setFontSize(12);
                    doc.addPage();
                    doc.text(header, 10, 10);
                    doc.text(footer, 10, doc.internal.pageSize.height - 10);
                    y = 20;
                }
            });

            // Save the PDF
            doc.save("example.pdf");
        }
    </script>
</head>

<body>
    <button onclick="generatePDF()">Generate PDF</button>
</body>

</html>

Benefits of Converting Dynamic PDFs with jsPDF are:

  • Generate professional-looking PDFs with fixed headers and footers and dynamic body content for documents like invoices, reports, and resumes with ease using this technique. It’s perfect for any document that requires these elements.
  • It eliminates the need to manually update the PDF every time the data changes.
  • It saves time and resources by automating the process of generating PDFs.
  • It ensures that all documents have a consistent look and feel.
  • The jsPDF library provides many features and functionalities to create a pdf document, which can be used to create more advanced pdfs.
  • The program is lightweight and easy to integrate into web pages, which makes it a powerful tool for creating several types of documents.

Conclusion:

The jsPDF program is great for creating PDFs with fixed headers, footers, and dynamic content. However, it does have limitations, such as not supporting more advanced features like images and tables. 🤔

To use the program, you’ll need a web server, or a local development environment set up.

💻 Give it a try and see how it works! 🎉

If you want to learn more about jsPDF, check out its documentation for all its features and functionalities.

📚 You can also explore other libraries like pdfmake and pdfkit for creating PDFs with JavaScript. 🔍

One thought on “Creating Dynamic PDFs with jsPDF in JavaScript

  1. Good day very nice blog!! Man .. Excellent .. Superb .. I’ll bookmark your web site and take the feeds additionally…I’m happy to find so many helpful info right here within the publish, we need work out extra strategies on this regard, thank you for sharing. . . . . .

Leave a Reply

Your email address will not be published. Required fields are marked *