15 Jul 2010

jsPDF

jsPDF

jsPDF is an open-source library written by our lead developer, James, for generating PDF documents using nothing but Javascript. You can use it in a Firefox extension, in Server Side Javascript and with Data URIs in some browsers.

Download Source

More examples and features to come.

New! Example of jsPDF using Downloadify, this makes it work in all major browsers.


Simple Two-page Text Document

var doc = new jsPDF();
doc.text(20, 20, 'Hello world!');
doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');
doc.addPage();
doc.text(20, 20, 'Do you like that?');

// Output as Data URI
doc.output('datauri');

Run Code

Different font sizes

var doc = new jsPDF();
doc.setFontSize(22);
doc.text(20, 20, 'This is a title');

doc.setFontSize(16);
doc.text(20, 30, 'This is some normal sized text underneath.');	

// Output as Data URI
doc.output('datauri');

Run Code

Adding metadata

var doc = new jsPDF();
doc.text(20, 20, 'This PDF has a title, subject, author, keywords and a creator.');

// Optional - set properties on the document
doc.setProperties({
	title: 'Title',
	subject: 'This is the subject',
	author: 'James Hall',
	keywords: 'generated, javascript, web 2.0, ajax',
	creator: 'MEEE'
});

// Output as Data URI
doc.output('datauri');

Run Code

Example of user input

var name = prompt('What is your name?');
var multiplier = prompt('Enter a number:');
multiplier = parseInt(multiplier);

var doc = new jsPDF();
doc.setFontSize(22);
doc.text(20, 20, 'Questions');
doc.setFontSize(16);
doc.text(20, 30, 'This belongs to: ' + name);

for(var i = 1; i <= 12; i ++) {
	doc.text(20, 30 + (i * 10), i + ' x ' + multiplier + ' = ___');
}

doc.addPage();
doc.setFontSize(22);
doc.text(20, 20, 'Answers');
doc.setFontSize(16);

for(var i = 1; i <= 12; i ++) {
	doc.text(20, 30 + (i * 10), i + ' x ' + multiplier + ' = ' + (i * multiplier));
}
doc.output('datauri');

Run Code

3 Responses to “jsPDF”

  1. Ivan Barroso says:

    Hi folks,

    Good work…

    Can this work with an input of type URL?
    The idea is to pass an URL of a webpage and generate a PDF.

    Tanks

  2. Tyson Cadenhead says:

    This works like a charm in Google Chrome, but when I tried it in Firefox 3.6.8, it didn’t display the pdf. Is that a known issue?

  3. James Hall says:

    Hi Tyson,

    Some browsers have issues with the Data URI. It works in Firefox with Adobe Reader installed as a plugin.

    The Downloadify output option will work in everything:

    http://wiki.github.com/MrRio/jsPDF/jspdf-using-downloadify

    Cheers,
    James

Leave a Reply