Skip to content

bhagatapoorva/canvas2pdf

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

24 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Canvas2PDF

Canvas2PDF exports an HTML canvas to PDF. In other words, this library lets you build a PDF document using the canvas API.

How it works

We create a mock 2d canvas context. Use the canvas context like you would on a normal canvas. As you call methods, we use PDFKit to generate a PDF document.

Browser Usage

//Create a new PDF canvas context.
var ctx = new canvas2pdf.PdfContext(blobStream());

//draw your canvas like you would normally
ctx.fillStyle='yellow';
ctx.fillRect(100,100,100,100);
// more canvas drawing, etc...

//convert your PDF to a Blob and save to file
ctx.stream.on('finish', function () {
    var blob = ctx.stream.toBlob('application/pdf');
    saveAs(blob, 'example.pdf', true);
});
ctx.end();

Node Usage

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

const file = fs.createWriteStream('example.pdf')
//Create a new PDF canvas context.
const ctx = new canvas2pdf.PdfContext(file)

//draw your canvas like you would normally
ctx.fillStyle = 'yellow'
ctx.fillRect(100, 100, 100, 100)
// more canvas drawing, etc...

ctx.stream.on('finish', function () {
  file.end()
})
ctx.end()

Dependencies

Using with node.js

canvas2pdf works with node.js. Note that neither a DOM or canvas library is needed.

Interactive Browser Demo

Open Demo

Notes

  • Inspired by Canvas2Svg
  • Calling fill and then stroke consecutively only executes fill
  • Some canvas 2d context methods are not implemented yet (e.g. setTransform and arcTo)
  • Does not require you to convert the canvas to img and then the img to pdf, unlike the other proposed solutions which embed an image in a PDF document.

Status

Build Status

License

MIT

Developer Dependencies

  • Ghostscript and GraphicsMagick are required for running tests

About

Export your HTML canvas to PDF

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 97.7%
  • CSS 1.5%
  • HTML 0.8%