Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create easily a PDF from an SVG with jsPDF?

Tags:

pdf

svg

jspdf

I'm trying to create a pdf but I have some SVG pictures. I found information about this problem, but I just have to use JavaScript, that's to say, no jQuery.

I found jsPDF here : https://github.com/MrRio/jsPDF

There is the plugin jspdf.plugin.sillysvgrenderer.js (in the same folder) and where we can find an exemple of PDF created in the folder test.

But when I try to generate the PDF on my own, it doesn't work and I don't understand why.

Do you know how to do it?

like image 528
azn0viet Avatar asked Apr 28 '14 12:04

azn0viet


People also ask

Is SVG or PDF better for printing?

PDF files were designed originally to accommodate print and as well as electronic and, for me have been far more consistent. SVG is lightweight and a web standard, PDF is an Adobe standard. As far as “standard” goes, both have their issues, but overall I prefer the smaller file sizes of the SVG files.

Are SVG vector files?

What is an SVG file? Scalable Vector Graphics (SVG) is a web-friendly vector file format. As opposed to pixel-based raster files like JPEGs, vector files store images via mathematical formulas based on points and lines on a grid.


1 Answers

I modified this from: https://medium.com/@benjamin.black/using-blob-from-svg-text-as-image-source-2a8947af7a8e

var yourSVG = document.getElementsByTagName('svg')[0];
//or use document.getElementById('yourSvgId'); etc.

yourSVG.setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns', 'http://www.w3.org/2000/svg');
yourSVG.setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:xlink', 'http://www.w3.org/1999/xlink');

var serializer = new XMLSerializer();
var serialSVG = serializer.serializeToString(yourSVG);

var svg = serialSVG;

var blob = new Blob([svg], {type: 'image/svg+xml'}); 
var url = URL.createObjectURL(blob);
var image = document.createElement('img');

// image.addEventListener('load', () => URL.revokeObjectURL(url), {once: true});    
//changed above line using babel to code below;

image.addEventListener('load', function () {
    return URL.revokeObjectURL(url);
    }, { once: true });

image.src = url;

//Then just use your pdf.addImage() function as usual;
like image 135
Mr. J Avatar answered Oct 24 '22 15:10

Mr. J