Getting Started with PDFKit

    Creating a document

    Creating a PDFKit document is quite simple. Just require the modulein your CoffeeScript or JavaScript source file and create an instance of thePDFDocument class.

    1. PDFDocument = require 'pdfkit'
    2. doc = new PDFDocument

    PDFDocument instances are readable Node streams. They don't get saved anywhere automatically,but you can call the pipe method to send the output of the PDF document to anotherwritable Node stream as it is being written. When you're done with your document, callthe end method to finalize it. Here is an example showing how to pipe to a file or an HTTP response.

    The write and output methods found in PDFKit before version 0.5 are now deprecated.

    As of version 0.6, PDFKit can be used in the browser as well as in Node! There are two ways to use PDFKit in the browser. The first is to use ,which is a Node module packager for the browser with the familiar require syntax. The second is to usea prebuilt version of PDFKit, which you can download from Github.

    Using PDFKit in the browser is exactly the same as using it in Node, except you'll want to pipe the output to a destination supported in the browser, such as a . Blobs can be usedto generate a URL to allow display of generated PDFs directly in the browser via an iframe, or they canbe used to upload the PDF to a server, or trigger a download in the user's browser.

    To get a Blob from a PDFDocument, you should pipe it to a blob-stream,which is a module that generates a Blob from any Node-style stream. The following example uses Browserify to load PDFKit and blob-stream, but if you're not using Browserify, you can load them in whatever way you'd like (e.g. script tags).

    1. # require dependencies
    2. PDFDocument = require 'pdfkit'
    3. blobStream = require 'blob-stream'
    4. # create a document the same way as above
    5. doc = new PDFDocument
    6. # pipe the document to a blob
    7. stream = doc.pipe(blobStream())
    8. # get a blob when you're done
    9. doc.end()
    10. stream.on 'finish', ->
    11. blob = stream.toBlob('application/pdf')
    12. # or get a blob URL for display in the browser
    13. url = stream.toBlobURL('application/pdf')
    14. iframe.src = url

    You can see an interactive in-browser demo of PDFKit .

    Adding pages

    The first page of a PDFKit document is added for you automatically when youcreate the document unless you provide autoFirstPage: false. Subsequent pages must be added by you. Luckily, it isquite simple!

    To add some content every time a page is created, either by calling addPage() or automatically, you can use the pageAdded event.

    1. doc.on 'pageAdded', ->
    2. doc.text "Page Title"

    You can also set some options for the page, such as it's size and orientation.

    The layout property can be either portrait (the default) or landscape.The size property can be either an array specifying [width, height] in PDFpoints (72 per inch), or a string specifying a predefined size. Alist of the predefined paper sizes can be seen . Thedefault is letter.

    Passing a page options object to the PDFDocument constructor willset the default paper size and layout for every page in the document, which isthen overridden by individual options passed to the addPage method.

    You can set the page margins in two ways. The first is by setting the margin property (singular) to a number, which applies that margin to all edges. Theother way is to set the margins property (plural) to an object with top,bottom, left, and right values. The default is a 1 inch (72 point) marginon all sides.

    For example:

    PDFKit has a bufferPages option in versions v0.7.0 and later that allows you to control whenpages are flushed to the output file yourself rather than letting PDFKit handle that for you. To useit, just pass as an option to the PDFDocument constructor. Then, you can calldoc.switchToPage(pageNumber) to switch to a previous page (page numbers start at 0).

    When you're ready to flush the buffered pages to the output file, call flushPages.This method is automatically called by doc.end(), so if you just want to buffer all pages in the document, younever need to call it. Finally, there is a bufferedPageRange method, which returns the rangeof pages that are currently buffered. Here is a small example that shows how you might add page numbers to a document.

    1. # create a document, and enable bufferPages mode
    2. doc = new PDFDocument
    3. bufferPages: true
    4. # add some content...
    5. doc.addPage()
    6. # ...
    7. # see the range of buffered pages
    8. range = doc.bufferedPageRange() # => { start: 0, count: 2 }
    9. for i in [range.start...range.start + range.count]
    10. doc.switchToPage(i)
    11. doc.text "Page #{i + 1} of #{range.count}"
    12. # manually flush pages that have been buffered
    13. doc.flushPages()
    14. # or, if you are at the end of the document anyway,
    15. # doc.end() will call it for you automatically.
    16. doc.end()

    Setting document metadata

    PDF documents can have various metadata associated with them, such as thetitle, or author of the document. You can add that information by adding it tothe doc.info object, or by passing an info object into the document atcreation time.

    Here is a list of all of the properties you can add to the document metadata.According to the PDF spec, each property must have it's first lettercapitalized.

    • Title - the title of the document
    • Author - the name of the author
    • Subject - the subject of the document
    • Keywords - keywords associated with the document
    • CreationDate - the date the document was created (added automatically by PDFKit)

    Once you've created a instance, you can add content to thedocument. Check out the other sections described in this document tolearn about each type of content you can add.

    That's the basics! Now let's move on to PDFKit's powerful vector graphicsabilities.

    Next