Giter VIP home page Giter VIP logo

pdfkit's Introduction

PDFKit

A JavaScript PDF generation library for Node and the browser.

Description

PDFKit is a PDF document generation library for Node and the browser that makes creating complex, multi-page, printable documents easy. The API embraces chainability, and includes both low level functions as well as abstractions for higher level functionality. The PDFKit API is designed to be simple, so generating complex documents is often as simple as a few function calls.

Check out some of the documentation and examples to see for yourself! You can also read the guide as a self-generated PDF with example output displayed inline. If you'd like to see how it was generated, check out the README in the docs folder.

You can also try out an interactive in-browser demo of PDFKit here.

Installation

Installation uses the npm package manager. Just type the following command after installing npm.

npm install pdfkit

Features

  • Vector graphics
    • HTML5 canvas-like API
    • Path operations
    • SVG path parser for easy path creation
    • Transformations
    • Linear and radial gradients
  • Text
    • Line wrapping (with soft hyphen recognition)
    • Text alignments
    • Bulleted lists
  • Font embedding
    • Supports TrueType (.ttf), OpenType (.otf), WOFF, WOFF2, TrueType Collections (.ttc), and Datafork TrueType (.dfont) fonts
    • Font subsetting
    • See fontkit for more details on advanced glyph layout support.
  • Image embedding
    • Supports JPEG and PNG files (including indexed PNGs, and PNGs with transparency)
  • Annotations
    • Links
    • Notes
    • Highlights
    • Underlines
    • etc.
  • AcroForms
  • Outlines
  • PDF security
    • Encryption
    • Access privileges (printing, copying, modifying, annotating, form filling, content accessibility, document assembly)
  • Accessibility support (marked content, logical structure, Tagged PDF, PDF/UA)

Coming soon!

  • Patterns fills
  • Higher level APIs for creating tables and laying out content
  • More performance optimizations
  • Even more awesomeness, perhaps written by you! Please fork this repository and send me pull requests.

Example

const PDFDocument = require('pdfkit');
const fs = require('fs');

// Create a document
const doc = new PDFDocument();

// Pipe its output somewhere, like to a file or HTTP response
// See below for browser usage
doc.pipe(fs.createWriteStream('output.pdf'));

// Embed a font, set the font size, and render some text
doc
  .font('fonts/PalatinoBold.ttf')
  .fontSize(25)
  .text('Some text with an embedded font!', 100, 100);

// Add an image, constrain it to a given size, and center it vertically and horizontally
doc.image('path/to/image.png', {
  fit: [250, 300],
  align: 'center',
  valign: 'center'
});

// Add another page
doc
  .addPage()
  .fontSize(25)
  .text('Here is some vector graphics...', 100, 100);

// Draw a triangle
doc
  .save()
  .moveTo(100, 150)
  .lineTo(100, 250)
  .lineTo(200, 250)
  .fill('#FF3300');

// Apply some transforms and render an SVG path with the 'even-odd' fill rule
doc
  .scale(0.6)
  .translate(470, -380)
  .path('M 250,75 L 323,301 131,161 369,161 177,301 z')
  .fill('red', 'even-odd')
  .restore();

// Add some text with annotations
doc
  .addPage()
  .fillColor('blue')
  .text('Here is a link!', 100, 100)
  .underline(100, 100, 160, 27, { color: '#0000FF' })
  .link(100, 100, 160, 27, 'http://google.com/');

// Finalize PDF file
doc.end();

The PDF output from this example (with a few additions) shows the power of PDFKit — producing complex documents with a very small amount of code. For more, see the demo folder and the PDFKit programming guide.

Browser Usage

There are three ways to use PDFKit in the browser:

In addition to PDFKit, you'll need somewhere to stream the output to. HTML5 has a Blob object which can be used to store binary data, and get URLs to this data in order to display PDF output inside an iframe, or upload to a server, etc. In order to get a Blob from the output of PDFKit, you can use the blob-stream module.

The following example uses Browserify or webpack to load PDFKit and blob-stream. See here and here for examples of prebuilt version usage.

// require dependencies
const PDFDocument = require('pdfkit');
const blobStream = require('blob-stream');

// create a document the same way as above
const doc = new PDFDocument();

// pipe the document to a blob
const stream = doc.pipe(blobStream());

// add your content to the document here, as usual

// get a blob when you are done
doc.end();
stream.on('finish', function() {
  // get a blob you can do whatever you like with
  const blob = stream.toBlob('application/pdf');

  // or get a blob URL for display in the browser
  const url = stream.toBlobURL('application/pdf');
  iframe.src = url;
});

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

Note that in order to Browserify a project using PDFKit, you need to install the brfs module with npm, which is used to load built-in font data into the package. It is listed as a devDependency in PDFKit's package.json, so it isn't installed by default for Node users. If you forget to install it, Browserify will print an error message.

Documentation

For complete API documentation and more examples, see the PDFKit website.

License

PDFKit is available under the MIT license.

pdfkit's People

Contributors

adrift2000 avatar alafr avatar andreiaugustin avatar blikblum avatar dariusk avatar devongovett avatar ef4 avatar helmuthb avatar insightfuls avatar jakubdatawrapper avatar jpravetz avatar koooge avatar liborm85 avatar m3ssman avatar malyngo avatar mike-koder avatar mishoo avatar mistify-readonly avatar pretzelfisch avatar rcbiczok avatar ricobrase avatar rokkie avatar ryanwersal avatar ryjones avatar smatheis avatar vincentguinaudeau avatar weswam avatar wildhoney avatar yelouafi avatar zesik avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pdfkit's Issues

converting not-English is not works.

in my case, Korean lanuage.
I write simple test for converting text.
English is ok. but Korean is not...
if you need fonts, I will send Korean fonts to you.

Feature: Support Acroforms

I'd love to use pdfkit to read an existing PDF in, get a list of form fields (text fields), populate them with data and write a new document out.

Thanks.

PDFKit works with Mongrel but not Passenger or Thin

Here is the error message that I get when I use Passenger to run my Ruby on Rails app and try to create a PDF page. I am using PDFKit Middleware.

wkhtmltopdf runs fine on the command line, and it also runs fine when I launch my Rails app using script/server.

/usr/local/bin/wkhtmltopdf: error while loading shared libraries: libQtSvg.so.4: cannot open shared object file: No such file or directory
/!\ FAILSAFE /!\ Sun Aug 07 13:30:38 -0500 2011
Status: 500 Internal Server Error
Broken pipe
/usr/lib/ruby/gems/1.8/gems/pdfkit-0.5.2/lib/pdfkit/pdfkit.rb:65:in write' /usr/lib/ruby/gems/1.8/gems/pdfkit-0.5.2/lib/pdfkit/pdfkit.rb:65:inputs'
/usr/lib/ruby/gems/1.8/gems/pdfkit-0.5.2/lib/pdfkit/pdfkit.rb:65:in to_pdf' /usr/lib/ruby/gems/1.8/gems/pdfkit-0.5.2/lib/pdfkit/pdfkit.rb:64:inpopen'
/usr/lib/ruby/gems/1.8/gems/pdfkit-0.5.2/lib/pdfkit/pdfkit.rb:64:in to_pdf' /usr/lib/ruby/gems/1.8/gems/pdfkit-0.5.2/lib/pdfkit/middleware.rb:21:incall'

Please help - PDFKit is amazing - thanks for your work on it!
Don

Cannot find module './zlib_bindings'

node v0.6.1
pdfkit v0.1.6

Code:

var pdf = require('pdfkit');

Error log:

Error: Cannot find module './zlib_bindings'
    at Function._resolveFilename (module.js:334:11)
    at Function._load (module.js:279:25)
    at Module.require (module.js:357:17)
    at require (module.js:368:17)
    at Object.<anonymous> (/home/user/share/test_pdfkit/node_modules/pdfkit/node_modules/flate/lib/zlib.js:1:80)
    at Module._compile (module.js:432:26)
    at Object..js (module.js:450:10)
    at Module.load (module.js:351:31)
    at Function._load (module.js:310:12)
    at Module.require (module.js:357:17)

problem with text

when i try to do this

doc.text('?') it gives the following error:

/Users/NeCkEr/.node_libraries/.npm/pdfkit/0.1.5/package/lib/mixins/text.coffee:178
wrap.extraSpace = (options.wordSpacing || 0) * (words.length - 1) + (opt
^
TypeError: Cannot read property 'length' of null

roundRect function

It might be really convenient to have a roundRect function - like the ReportLabs pdf canvas has.

Of course if is possible to do find a workaround using lines and bezier curves at the corners. But a simpler helper function would be great..

Setting lineWidth = -1 causes Adobe Reader issues

I found that (accidentally!) setting lineWidth = -1 on PDFDocument before drawing shapes results in Adobe Reader not loading the PDF file.

Might be worth a gate to prevent other people accidentally doing the same thing ;-)

Support for asian languages

As the current version (0.1.5), it is able to put asian (zh-tw in my case) language characters in a text, with proper (not default) font file supplied. That is really good!

Unfortunately the texts cannot be correctly wrapped. So the paragraph will display in a single line and go right all the way outside the page boundary. If we five paragraphs, for example, then there will be five lines of text. No matter how many characters each paragraph have.

I think it is a little bit difficult to very correctly wrap Chinese texts. But I guess there might be some work around not too difficult.

Image coordinate bug when specifying 0 for x or y

When using the image function to draw an image, if you specify 0 for x or y, either as parameters or in the options object, the method will fall back to using @x and @y, because the number 0 equates to false in Javascript truth.

Specifically, the lines I'm referring to are found at https://github.com/devongovett/pdfkit/blob/master/lib/mixins/images.coffee#L13 and https://github.com/devongovett/pdfkit/blob/master/lib/mixins/images.coffee#L14 at the time of this writing.

I'm not too fluent with coffeescript, so I don't know if there is an easy way to resolve this without resorting to checking if the variables are undefined.

paths problem

down in loca.coffee and other files there's

Data = require '../../Data'

but this doesn't seem to be the right path... shouldn't it be ../data ? causes a failure on requiring pdfkit itself...

Development documentation

Can you provide some documentation that how does it work for developers? Actually on the part converting javascript objects to pdf. I found it confusing.

Thanks

Could we have an arc function?

Enhancement request:

It would be great if pdfkit could support an arc function like HTML5 Canvas.

From the canvas spec:

void arc(double x, double y, double radius, double startAngle, double endAngle, optional boolean anticlockwise);

Currently it doesn't appear possible to draw arcs using pdfkit....

Thanks!

utf8 support?

Is there support for utf8?
I will try do:

doc.text('Бла бла бла', 0, 0);
doc.write('test.pdf');

in the resulting document, I see it => ;0 1;0 1;0

Repeated characters

There is a bug where pdfkit doubles a character.

For example, if I write:

doc.text("Tel (787) 760-3000");

I get different results:

Tel (787))760-3000

or

Tel (787) 760--3000

or

Tel (787) 760-300000

I haven't been able to pinpoint how to fix this. But I found that if I write a dash before the one in between the numbers:

doc.text("Tel - (787) 760-3000");

It doesn't double the dashes, it doubles the parenthesis.

Very confusing. Thanks!

tables

I have an idea for it. We can pass a two-dimensional array of texts, to a method with presentation options like the following:

doc.table([
  ["cell11"],["cell21"],["cell31"],
  ["cell12"],["cell22"],["cell32"],
  ["cell13"],["cell23"],["cell33"]
  ],{
    width:20,
    height:40,
    x:30,
    y:40
});

Then in the module we make rectangles and texts for each cell.

using raw JS doesn't seem to work

the file (test.js) has one line:

var PDFDocument = require ('pdfkit');

and it throws this error:

/mydir/node_modules/pdfkit/lib/document.coffee:1

^

node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^
SyntaxError: Unexpected token ILLEGAL
at Module._compile (module.js:402:25)
at Object..js (module.js:413:10)
at Module.load (module.js:339:31)
at Function._load (module.js:298:12)
at require (module.js:351:19)
at Object. (/mydir/test.js:1:81)
at Module._compile (module.js:407:26)
at Object..js (module.js:413:10)
at Module.load (module.js:339:31)
at Function._load (module.js:298:12)

Reference.coffee throws exception

From line 33 of Reference.coffee:

data = @stream.join '\n'
if @stream

...

This throws an exception if stream is null. Swapping the lines fixes the bug:

    if @stream
        data = @stream.join '\n'

Can't justify TTF

When I set the align option to justify on an embedded TTF font, the text will still be left aligned. I have tried with three different fonts, but this one will probably be good enough for testing.

Sorry I haven't investigated the problem further before posting this issue.

Encoding f issue

Difficult problem to understand and to explain.
When I write the text "une forêt" the pdf has "une fforêt" (2 f).
After hours looking for the problem, I discovered that my f was encoded "" on class Subset. String.fromCharCode(@unicodes['f']) === ""
On mixin "text" function _escape replace \ by \ ... I don't know /understand why but removing this replace fix my problem and I have no time to investigate deeper..

Footer question

Is there anyway to add a footer section to all pages? because i want to add pageNumbers(ex: page 1 of 5) to all pages... and because my content is dynamic i can't hardcode the number total of pages because i cant predict how many pages the document will have...

Thanks in advance.

website content has hard coded width on the class main

When using the window side by side with another the text it truncated because the website doesn't allow wrapping when the main can't be 800px. Just commenting that out makes the page more readable. 1/2 of a HD 1920 px screen is 960 and with your 250px sidebar I need at least 1050 to read the page.

TypeError: Cannot read property 'length' of null

/Users/rcameron/node_modules/pdfkit/lib/mixins/line_wrapper.coffee:63
len = words.length;
^
TypeError: Cannot read property 'length' of null
at LineWrapper.wrap (/Users/rcameron/node_modules/pdfkit/lib/mixins/line_wrapper.coffee:63:20)
at PDFDocument.text (/Users/rcameron/node_modules/pdfkit/lib/mixins/text.coffee:46:17)
at /Users/rcameron/pdfMaker/node-test.js:90:8
at IncomingMessage. (/Users/rcameron/pdfMaker/node-test.js:61:4)
at IncomingMessage.emit (events.js:81:20)
at HTTPParser.onMessageComplete (http.js:133:23)
at CleartextStream.ondata (http.js:1231:22)
at CleartextStream._push (tls.js:303:27)
at SecurePair.cycle (tls.js:577:20)
at EncryptedStream.write (tls.js:96:13)

I am seeing this issue when adding text via the doc.text method. I changed the pdfkit module to test if words was null before testing length on line 54 of line_wrapper.coffee.

if !!text.match(WORD_RE)
words = text.match(WORD_RE)

This solved the issue.

Feature Request

PDFKit is a great tool that we want to see it even better.

Couple of things that might be worth looking into:

  • Stamping external vector content - Lets say we have some logo in a vector format stored either in a PDF, PS or EPS file. It would be great if we can stamp it on a pre-defined location either on one or all pages so that the vector content can be included without rasterization.
  • Backgrounds - It would be slim if we can define a one page external PDF that on its own can contain any type of content (vector, images, text) that could be even produced in a 3-rd party app such as AI and used as a background for the PDF generated from PDFKit. A lot of PDF documents have the same layout and design for all pages so it would be a lot easier if we can just apply the dynamic content on a predefined section of the page (page minus header and footer for example) and pull the background from a pre-existing PDF design.

I am not sure if these are already in but I would like to mentioned them anyway:

  • The ability to define regions or boxes to populate with content and place them on one or all pages at a certain location. In that context a special case would be headers and footers that would even contain calculated values such as page numbers.
  • A clear way to mark a page break within the HTML.

PDFDocument.text function could be friendlier

PDFDocument.text appears to throw an exception when passed a number to draw, instead of a string, e.g., document.text(23, 10, 10);

It might be nicer to call toString() on the first argument?

Swiching back to previous pages?

Is there any way to do this? For example we have made 3 pages, we write something on the 3rd page, and then write something else on the 2nd.

Problems with zlib

When trying to write PDF document I get following error:


TypeError: Object # has no method 'deflate' at 
PDFReference.finalize (/usr/local/lib/node/.npm/pdfkit/0.1.5/package/lib/reference.coffee:54:33)


Here's the line in reference.coffee:


data = new Buffer(data.charCodeAt(i) for i in [0...data.length])
compressedData = zlib.deflate(data)

I've checked object zlib and it has the method 'deflate' but it named 'Deflate' now (with capitalised first letter).
Versions: [email protected], [email protected]

document.write callback

The document.write function should allow a callback function to be passed through to fs.writeFile.

Otherwise one doesn't know when the file has actually been written..

Nice library!

code nit in object.coffee

All the returns in PDFobject::convert could be removed for clarity, and, in fact, one branch (Dates) doesn't even use one.

Use of CMYK color values renders invalid PDF

When I use cmyk color values ( e.g. .strokeColor([0,0,0,100]), the PDF is created successfully, but is not readable by any PDF viewer, even if I only use CMYK colors. CMYK colors were introduced by this commit: 6a9d2f8

I think there has to be a document-wide property that defines the correct color space (something like DeviceCMYK).

osx system helvetica neue error

using this

doc.registerFont('Helvetica Neue', '/System/Library/Fonts/HelveticaNeue.dfont', 'Helvetica Neue')

leads to the following error:

TypeError: Cannot read property 'named' of undefined
    at DFont.getNamedFont (/Users/adrien/Playground/CV/node_modules/pdfkit/lib/font/dfont.coffee:71:28)
    at Function.fromDFont (/Users/adrien/Playground/CV/node_modules/pdfkit/lib/font/ttf.coffee:26:32)
    at new PDFFont (/Users/adrien/Playground/CV/node_modules/pdfkit/lib/font.coffee:32:28)
    at PDFDocument.font (/Users/adrien/Playground/CV/node_modules/pdfkit/lib/mixins/fonts.coffee:33:20)
    at Object.<anonymous> (/Users/adrien/Playground/CV/cv.coffee:8:7)
    at Object.<anonymous> (/Users/adrien/Playground/CV/cv.coffee:9:4)
    at Module._compile (module.js:402:26)
    at Object.run (/usr/local/lib/node_modules/coffee-script/lib/coffee-script.js:57:25)
    at /usr/local/lib/node_modules/coffee-script/lib/command.js:147:29
    at /usr/local/lib/node_modules/coffee-script/lib/command.js:115:26

Blank Document

In Javascript, not coffee:

PDFDocument = require('pdfkit');
doc = new PDFDocument();

        // register and use a font, set the font size, and render some text
        doc.registerFont('hn', __dirname + '/public/fonts/HelveticaNeue.ttf');
        doc.registerFont('hnl', __dirname + '/public/fonts/HelveticaNeueLt.ttf');
        doc.font('hn')
           .fontSize(25)
           .text('Some text with an embedded font!', 100, 100);

        // Add another page
        doc.addPage()
           .fontSize(25)
           .text('Here is some vector graphics...', 100, 100);

        // Write the PDF file to disk
        doc.write('output.pdf');

Where's the problem?

Page Orietation

Hi!

Currently I am using PDFKit and i have a good results.
So, I'm trying to find something about how to change the page orientation of the document. Can you help me? some tip ?

I `m working with ruby on rails

thanks for attention

Fillipe Norton

List texts don't wrap

I working on a document with some lists of which the text is wider than the page. It would be nice if we could supply a width to the list for wrapping.

Abbreviations in the end of a line

Found a bug, don't know if the future update will fix it, but if you have an abbreviation, e.g. R.E.B.E.L.S., and it's on the of a line it separates the abbreviation instead of leaving it all together, e.g. R.E.B. \n E.L. .

Did the example make sense?

Thanks!

Rotating on 90 and 270 degrees don't work

Example for this:

var coffee  = require('coffee-script'),
pdfkit  = require('pdfkit'),
pdfdoc = new pdfkit;

pdfdoc.rotate(90, {origin:[20,20]})
pdfdoc.text('hi',20,20)

pdfdoc.write('test.pdf');

But if instead of 90 we use 90.0001, it works(90.00001 or smaller doesn't work). Same thing goes for 270 degrees.

Interactive features, a few questions?

Is there a way to have text in a left column (pane) that controls what is visible on the right? I'd like to be able to click on something on the left and have the visibility of images on the right change. Even more specifically, I'd like to have images overlayed and control which overlays are present. The overlays would ideally be any pdf content, but could be limited to PNGs.

Can these features be implemented in pdfkit, and if not, are they possible at all in the PDF format?

Also, does every PDF reader, such as those on the mobile devices iPhone and Android support such interactivity?

I'm sorry to ask so many questions, but I've googled PDF for hours and I can't really figure out what is possible.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.