Generate PDF from Javascript using jsPDF

  •        0
  

We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.



We show lot of data in our web applications, it will be awesome if we quickly download specific part of PDF rather than printing it. It will be easy to share for different stakeholders and also for focussed meetings. In web application development, download to PDF means, we need to develop backend api specifically and then link it in frontend which takes longer development cylce. Instead it would be really great, if there is way to download what we see in the user interface quickly with few lines of Javascript, similar to export options in word processing application. 

jsPDF is a library written in Javascript. It helps to convert frontend html content, image, charts or a tabular data to directly export to pdf. It also provides advanced support of adding watermark, embedding fonts, adding forms, encryption and password protection also. It is licensed under MIT. It has very good documentation.

Setup:

In this blog, we will see how jsPDF can be used with plain html, which will be webpacked to have the download option in the frontend page. Create a npm project by using npm init, then install jsPdf, html2canvas. Also supporting dependenceis like webpack, webpack-cli and html-webpack-plugin. In the JsPDF documentation, they have given ways for integrating jsPdf with Angular, Vue and React.

npm install jsPdf --save 

npm install html2canvas

You can also load it via CDN

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.0/jspdf.umd.min.js"></script>

 

Create PDF with text content

To load the jsPDF, use require jspdf and get the jsPDF class. Then create a instance of the object, will create a pdf object reference. 

const { jsPDF } = require("jspdf");
const doc = new jsPDF();

Now we can write the text using text() method. Pass the text with x and y co-ordinates to write the text into the pdf object.  

doc.text("jsPdf Tutorial - Sample PDF", 10, 10);

To save the PDF, pass the output file name as argument to save method.

doc.save("sampletutorial.pdf");

Creating the pdf from the client, we can hook it, on click of the button or on click of the URL. 

<button id="downloadpdf">Download</button>

function downloadContent() {
	const { jsPDF } = require("jspdf");
	doc.text("jsPdf Tutorial - Sample PDF", 10, 10);
	doc.save("sampletutorial.pdf");
}

 

Add a link to the PDF content

Now lets add a text with hyperlink in the pdf object. It can be done with textWithLink() method which takes the text, origin and the url. So when click on the text it will redirect to the URL. We can change the color of the text by changing the text color of the pdf object to blue, so it appears as a hyperlink text.

doc.setTextColor("0645AD");
doc.textWithLink("Hyper link text: FindBestOpenSource", 10, 25, {
    url: "https://www.findbestopensource.com/",
});

 

HTML content to PDF

Generate the html content to PDF object can be done, by using html() method. Below is the HTML content element which has header, paragraph text and numbering list. It is done by html plugin which is seamlessly integrated with the jsPdf library, which works by just using the method.

<div id="content">
	<h2>H2 Header</h2>
	<p>It is a paragraph text</p>
	<ul style="padding-left: 10px;"><span>Sample numbering list</span>
		<li>First item</li>
		<li>Second item</li>
		<li>Third item</li>
	</ul>
</div

Now get the HTML DOM element and provide it to html() method. This will convert all the html element in the same way how it renders in browser and adds as a content to PDF instance. In the callback function, pdf document object comes as arugment which has the html content converted in it. Now we just need to save the content to PDF.

let element = document.getElementById("content");
doc.html(element, {
       margin: 30,
       callback: function (doc) {
            doc.save("sampletutorial.pdf");
       }
});

Create Scatter Chart:

We can create the simple chart on the canvas element by plotting the context ellipse and fill with different x and y coordinates with plain javascript. 

function createChart() {
    const canvas = document.getElementById("myCanvas");
    canvas.style.background = "floralwhite";
    const ctx = canvas.getContext("2d");
    canvas.height = canvas.width;
    ctx.transform(1, 0, 0, -1, 0, canvas.height)

    const xArray = [50,60,70,80,90,100,110,120,130,140,150];
    const yArray = [7,8,8,9,9,9,10,11,14,14,15];

    ctx.fillStyle = "red";
    for (let i = 0; i < xArray.length-1; i++) {
        let x = xArray[i]*400/150;
        let y = yArray[i]*400/15;
        ctx.beginPath();
        ctx.ellipse(x, y, 3, 3, 0, 0, Math.PI * 2);
        ctx.fill();
    }
}

Now get the canvas element, then directly do the doc.addImage(canvas) but background will have dark background. To get the floral white background of the chart, it is better to use html2canvas method which will convert the exact chart element with the background into a canvas html element, which can be added as image to the pdf object with expected format and co-ordinates.

const canvas = document.getElementById("myCanvas");
const canvaselement = await html2canvas(canvas, {useCORS: true, allowTaint: true});
doc.addImage(canvaselement, 'png', 10, 130);

Insert Pages to the PDF:

Now if we want to put the content in a new page, it can be done using insertPage method with the page number. 

doc.insertPage(2);

This example has been made as webpack project, it will generate the assets in dist folder with index.html. If we open, it looks like the below html page. This project is available in the github

By clicking, download PDF, it downloads the PDF content with html content and chart objects. 

References:

https://parall.ax/products/jspdf

https://github.com/parallax/jsPDF

http://raw.githack.com/MrRio/jsPDF/master/docs/

https://github.com/nagappan080810/jspdftutorial


   

Nagappan is a techie-geek and a full-stack senior developer having 10+ years of experience in both front-end and back-end. He has experience on front-end web technologies like HTML, CSS, JAVASCRIPT, Angular and expert in Java and related frameworks like Spring, Struts, EJB and RESTEasy framework. He hold bachelors degree in computer science and he is very passionate in learning new technologies.

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter



Related Articles

Read and Write PDF using OpenPDF

  • java pdf openpdf create-pdf

OpenPDF is based on a fork of iText version 4. iText is a widely used PDF library but they changed their license and moved to AGPL. In this article, we can see how to read and write to PDF, How to extract text from PDF and How to create password protected PDF.

Read More


LogicalDOC - Open Source DMS

  • dms document-management-system

LogicalDOC is both a document management and a collaboration system. The software is loaded with many functions and allows organizing, indexing, retrieving, controlling and distributing important business documents securely and safely for any organization and individual.

Read More


8 Best Open Source Searchengines built on top of Lucene

  • lucene solr searchengine elasticsearch

Lucene is most powerful and widely used Search engine. Here is the list of 7 search engines which is built on top of Lucene. You could imagine how powerful they are.

Read More


Push Notifications using Angular

  • angular push-notifications notifications

Notifications is a message pushed to user's device passively. Browser supports notifications and push API that allows to send message asynchronously to the user. Messages are sent with the help of service workers, it runs as background tasks to receive and relay the messages to the desktop if the application is not opened. It uses web push protocol to register the server and send message to the application. Once user opt-in for the updates, it is effective way of re-engaging users with customized content.

Read More


JHipster - Generate simple web application code using Spring Boot and Angular

  • jhipster spring-boot angular web-application

JHipster is one of the full-stack web app development platform to generate, develop and deploy. It provides the front end technologies options of React, Angular, Vue mixed with bootstrap and font awesome icons. Last released version is JHipster 6.0.1. It is licensed under Apache 2 license.

Read More



Generate Thumbnail in Java using Thumbnailator library 

  • thumbnail image-processing java

In our work there will be situation where we need to resize the image, generate thumbnails and so on. Users need to have little bit of image processing knowledge to achieve it. We have Java ImageIO APIs to achieve these functionalities. As said, we need to be aware of or spend time in learning these APIs. To help us, Thumbnailator library provides easy fluent style API and generates thumbnail in simple three lines of code.

Read More


Holistic usage guide for OpenSSL

  • openssl security certificate tools

OpenSSL is a general purpose cryptographty toolkit that provides an open source implementation of Transport Layer Security(TLS) and Secure Socket Layer(SSL) protocols. It is written in C,assembly and Perl language but wrappers are available in all languages. This article explains about OpenSSL commands.

Read More


LucidWorks Vs SearchBlox - Enterprise Search Solution

  • lucene solr searchblox lucidworks enterprise-search

Enterprise search software should be capable to search the data available in the entire organization or personnel desktop. The data could be in File system, Web or in Database. It should search contents of Emails, file formats like doc, xls, ppt, pdf and lot more. There are many commercial products available but LucidWorks and SearchBlox are best and free.

Read More


Lucene Vs Solr

  • searchengine lucene solr

Lucene is a search library built in Java. Solr is a web application built on top of Lucene. Certainly Solr = Lucene + Added features. Often there would a question, when to choose Solr and when to choose Lucene.

Read More


Angular Service Workers Usage Guide

  • angular service-worker offline-app

Web developers come across scenarios like web application completely breaks when workstation goes offline. Likewise to get into our application, every time we need to open a browser and then access it. Instead if it is in app, it will be easy to access for end-user. Push notifications similar to email client need to be done through web application. All these are addressed by a magic called service worker.

Read More


10 sites to get the large data set or data corpus for free

  • search test-data large-data-set data-corpus dataset

You may require GBs of data to do performance or load testing. How your app behaves when there is loads of data. You need to know the capacity of your application. This is the frequently asked question from the sales team "The customer is having 100GB of data and he wants to know whether our product will handle this? If so how much RAM / Disk storage required?". This article has pointers to the large data corpus.

Read More


JWT Authentication using Auth0 Library

  • java jwt authentication security

Json Web Token shortly called as JWT becomes defacto standard for authenticating REST API. In a traditional web application, once the user login credentials are validated, loggedin user object will be stored in session. Till user logs out, session will remain and user can work on the web application without any issues. Rest world is stateless, it is difficult to identify whether the user is already authenticated. One way is to use authenticate every API but that would be too expensive task as the client has to provide credentials in every API. Another approach is to use token.

Read More


Apache OpenNLP - Document Classification

  • opennlp natural-language-processing nlp document-classification

Apache OpenNLP is a library for natural language processing using machine learning. In this article, we will explore document/text classification by training with sample data and then execute to get its results. We will use plain training model as one example and then training using Navie Bayes Algorithm.

Read More


10 Free services for your Website / Blog. Just plug it.

  • free website blog free-service free-resources

Each website / blog delivers useful content or service to its users. But website themselves requires some service to monitor and increase its presence. Here are few free services which could be used by Website / Blog. This will be very much helpful for small business owners.

Read More


mkcert - No config certificate authority tool

  • certificate ssl security cert go go-lang

Mkcert is go-lang project, which is super easy tool to setup certificate authority without any configuration. Using certificates are inevitable these days, data should be transferred in a secure communication channel. Buying a certificate is expensive and mostly companies buy certificates only for production systems. In Dev setup, if we use self-signed certificate then there will be trust errors. mkcert automatically creates and installs a local CA in the system root store, and generates locally-trusted certificates.

Read More


COVID19 Stats using Angular Material Design

  • angular material-design covid covid-stats

Material design is inspired from the real world building architecture language. It is an adaptable system of guidelines, components, and tools that support the best practices of user interface design. Backed by open-source code, Material streamlines collaboration between designers and developers, and helps teams quickly build beautiful products. In this article, we will build COVID stats using Angular Material design.

Read More


LetsEncrypt certificate using ZeroSSL tools

  • ssl-certificate certificate security

Let’s Encrypt is a free, automated, and open Certificate Authority. It uses ACME protocol to validate your domain. If you have complete control over your domain, you can get a certificate for free. In order to provide secure access to your public network like HTTPS, LDAPS etc you need a certificate from a Certificate Authority. The cost of the certificate range from 10$ to 100$. If you want a wildcard certificate then it may cost more. The certificate is valid for one year and you need to pay and renew every year. Let's Encrypt comes for the rescue. You can create and renew certificate for few.

Read More


How Bitcoin works? A simple introduction.

Bitcoin is an open source digital currency which could be transferred in a P2P payment network. It is decentralized and it is not controlled by any central authority or banks. It is transferred from person to person and no authority will be aware of your transaction. Its quite different from PayPal or Banks.

Read More


Identicon - Get unique avatar for your website users

  • identicon avatar icon gravatar

Users login in to the Websites, Blogs, Forum and adding their content, comments, asking or answering the questions etc. If user has added his photo then it will get displayed besides his content but not everyone provides his photo image to the sites. Most of the sites used to display a common avatar image for those who have not provided their image. When we read the content, it may be odd to see the same image representation for all users. Identicon comes for the rescue.

Read More


Introduction to Light 4J Microservices Framework

  • light4j microservice java programming framework

Light 4j is fast, lightweight, secure and cloud native microservices platform written in Java 8. It is based on pure HTTP server without Java EE platform. It is hosted by server UnderTow. Light-4j and related frameworks are released under the Apache 2.0 license.

Read More







We have large collection of open source products. Follow the tags from Tag Cloud >>


Open source products are scattered around the web. Please provide information about the open source projects you own / you use. Add Projects.