Embedding SVG in PDF (exporting SVG to PDF using JS)

Simeon picture Simeon · May 6, 2011 · Viewed 61.6k times · Source

The starting points: I don't have a server that can provide anything but static files. And I have an SVG element (dynamically created) in my <body> that I want to export to a vector format, preferrably PDF or SVG.

I started looking at using the already existing lib jsPDF along with downloadify. It worked fine. Unfortunately, this does not support SVG, only text.

I've read about the PDF format's possiblities to embed SVG images, and it seems to have been enabled since Acrobat Reader 5 (along with the ImageViewer plugin). But it doesn't work. I've tried with 3 different PDF readers without success.

Does this mean that PDFs has dropped SVG embedding support? I haven't found anything on this.

I have two questions; can this be solved? And if yes, what are the specifications for embedding SVG inside of a PDF? With that info, I can build that support in jsPDF myself.

The browser support demands are Safari, Chrome and Firefox. The versions that supports SVG.

Answer

Florian Ledermann picture Florian Ledermann · Aug 4, 2014

For anyone looking for a JS-only solution: PDFKit seems to be the superior solution to generate PDF from JS these days, and it supports all SVG geometry primitives (including interpreting path geometry strings) out of the box. All that would be needed to render existing SVG content would be a DOM-walker that keeps track of CSS styling and inheritance, if you do not require complex stuff like symbols etc.

I wasn't successful with the sketchy SVG support of the jsPDF/svgToPdf combo mentioned in the other answer, and the source code of these two didn't look very well-crafted and complete to me.

Edit: Usage example JSFiddle