11

Does anyone know if it's possible to import a full SVG into a PDFKit document? I can see from the docs that it has full SVG support, and there are methods for drawing paths etc, but I cannot see a method for importing a full SVG document.

2 Answers 2

19

While searching for an answer to this question, I found a small open-source library that does the trick: SVG-to-PDFKit.

If implementing your own interface is not convenient, this one is pretty easy to use (code sample from the Readme):

PDFDocument.prototype.addSVG = function(svg, x, y, options) {
  return SVGtoPDF(this, svg, x, y, options), this;
};
doc.addSVG(svg, x, y, options);

The parameters are as such:

doc [PDFDocument] = the PDF document created with PDFKit

svg [SVGElement or string] = the SVG object or XML code

x, y [number] = the position where the SVG will be added

Check out the demo here.

4

Unfortunately, as of V0.7 (Nov 2014), PDFKit does not support drawing SVG content to the PDF. Hovever, most of the building blocks are there (features covering most SVG presentations attributes + an SVG path parser), so implementing this would be a matter of traversing your SVG document tree from the root, keeping track of the transformation and attribute state (in case of inherited values) and drawing the SVG graphics primitives (including paths) you encounter. Of course some things like symbol definitions and filters would be more complicated to implement, but for basic geometry & styling this should not take longer than a few hours to implement given the features provided by PDFKit.

3
  • In the end I decided to go with using an API for my conversions, I am using CloudConvert who seem to be great so far. If anyone still needs this support in PDFKit, then like you say it doesn't sound like it would be overly complicated to add the feature and do a pull request.
    – jcvandan
    Nov 4, 2014 at 10:05
  • I;m trying to build an interface between SVG and PDFKit, however I ran into a problem when using tranformations. The transformation matrix in pdf scales weirdly, can't find why... however when using scale, rotate... it works fine, will look into it, will let you know if I manage to make it work seamlessly
    – Jo Colina
    Jul 23, 2015 at 13:49
  • 1
    I tried to recreate my SVG in PDF using PDFKit, and finally i did it. save() and restore() methods becomes handy - firstly I saved state, then I copied every layer with transorm matrix calling restore() at the end. Note transform method, which is not documented in PDFKit, but it works (there are 6 vars - m11, m12, m21, m22, x, y) Dec 17, 2015 at 21:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.