Embedding SVG in PDF (exporting SVG to PDF using JS)
Asked Answered
A

6

42

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.

Arrant answered 6/5, 2011 at 15:8 Comment(0)
W
38

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

Whitfield answered 4/8, 2014 at 12:49 Comment(4)
One question. 1. Open pdfkit.org/demo/browser.html. 2. Open Chrome Inspect Window. 3. Click "Toggle Device Toolbar" icon on the top menu. 4. Refresh the page. 5. I CANNOT see the pdf on the right window in the mobile view. 6. Do anyone know why the mobile view is not rendering the PDF. ? Is it this PDFKit specific or general problem with opening pdf on mobile ?Intellectualism
PDFKit in conjunction with github.com/alafr/SVG-to-PDFKit seems to be the way to go.Cupola
cant convert html to pdf directlyPrevenient
It doesn't support the image tag!?Salade
A
7

I'll reply to my own question. I ended up using DocRaptor that can be called client-side from JavaScript. This technically solves my problem, even though it is a non-free solution. If I the answer could be a server-side-solution, I could use wkhtmltopdf as proposed by Mic.

Arrant answered 9/5, 2011 at 12:55 Comment(2)
Thanks for the link to DocRaptor. If you go the route of hosting something, you can use WKHTMLTOPDF, as it is free and open sourcedSingles
Added your answer and removed Prince XML as an alternative, thanks!Arrant
A
7

jsPDF has a plugin for that: svgToPdf:

https://github.com/ahwolf/jsPDF/blob/master/jspdf.plugin.svgToPdf.js

I haven't tried it, but this could allow discarding the use of an external API and/or having to rely on a server-side solution.

Akins answered 6/5, 2013 at 10:17 Comment(1)
I'm currently trying this approach but I only seem to get a blank pdf from it. Do you know of any examples out there that use this plugin?Insessorial
S
4

Did you try WKHTMLTOPDF? It's a free tool based on webkit.
We wrote a small tutorial here.

On a Mac, with Safari or Chrome, you can save an HTML page with embedded SVG to a PDF.
Since these browsers use WKHTMLTOPDF internally, may be this will work for you as well.

Singles answered 6/5, 2011 at 15:57 Comment(3)
I'm asking for a client-side solution here. However, you are right in that I've not specified what browser support I'm going for. So I've now edited my answer to include thatArrant
I, unfortunately, still can't make wkhtmltopdf work. It only produces blank pages for me.Darleen
@art-solopov, times have changed, as mentionned above, you could switch to pdfkit: pdfkit.org/docs/vector.htmlSingles
C
2

Minimal example using pdfkit, svg-to-pdfkit and blob-stream, that downloads an SVG DOM element as a PDF.

  1. Import packages in your index.html.
<script src="https://cdn.jsdelivr.net/npm/[email protected]/js/pdfkit.standalone.js"></script>
<script src="https://bundle.run/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/source.js"></script>
  1. Run this function, where svg is an SVG DOM element, or SVG string.
function downloadPDF(svg, outFileName) {
    let doc = new PDFDocument({compress: false});
    SVGtoPDF(doc, svg, 0, 0);
    let stream = doc.pipe(blobStream());
    stream.on('finish', () => {
      let blob = stream.toBlob('application/pdf');
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = outFileName + ".pdf";
      link.click();
    });
    doc.end();
}
Coly answered 8/4, 2021 at 11:3 Comment(4)
shapes are correct but all color and text is blacked out.Nonfeasance
@Nonfeasance hmmm.. can't reproduce. What browser and version? Anyone else getting this?Coly
I created a minimal example here and linked to your answer in the post #72061801Nonfeasance
Thanks! it works as I needed except cyrillic symbols from svg is not shown on pdf. Do you have any clue how to get them shown?Swifter
G
-1

EVO HTML to PDF Converter has support for converting the SVG embedded in HTML to PDF. You can see an example for this feature here : http://www.evopdf.com/demo/HTML_to_PDF/HTML5_Features/SVG_to_PDF.aspx . The sample code for this is:

// Create a HTML to PDF converter object with default settings
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();

// Convert the HTML page with SVG to a PDF document in a memory buffer
byte[] outPdfBuffer = htmlToPdfConverter.ConvertUrl(urlHtmlWithSVG);

// Send the PDF as response to browser

// Set response content type
Response.AddHeader("Content-Type", "application/pdf");

// Instruct the browser to open the PDF file as an attachment or inline
Response.AddHeader("Content-Disposition", String.Format("attachment; filename=SVG_to_PDF.pdf; size={0}", outPdfBuffer.Length.ToString()));

// Write the PDF document buffer to HTTP response
Response.BinaryWrite(outPdfBuffer);

// End the HTTP response and stop the current page processing
Response.End();
Georgiannageorgianne answered 20/10, 2015 at 7:11 Comment(2)
EVO pdf doesn't fit the svg image on entire pdf page. There is lot of blank space on all the sides of the image. I have tried all the option like FitWidth, FitHeight, StretchToFit etc. But couldn't solve the issue.Social
I'm experiencing the same issue as ArpitGupta where the layout around the SVG is completely wrong when using @Georgiannageorgianne I have a container div wrapping an SVG and I'm using flexbox to vertically & horizontally center the container. When converted to PDF, the layout/alignment is the same as if I completely remove the flexbox styles.Thurgau

© 2022 - 2024 — McMap. All rights reserved.