如何使用jsPDF从SVG轻松创建PDF?

如何使用jsPDF从SVG轻松创建PDF?,pdf,svg,jspdf,Pdf,Svg,Jspdf,我正在尝试创建pdf,但我有一些SVG图片。我找到了关于这个问题的信息,但我只需要使用JavaScript,也就是说,没有jQuery 我在这里找到了jsPDF: 还有pluginjspdf.plugin.sillysvgrender.js(在同一个文件夹中),我们可以在这里找到在文件夹测试中创建的PDF示例 但是当我试图自己生成PDF时,它不起作用,我不明白为什么 你知道怎么做吗 我让这个插件正常工作,但只有使用测试中的SVG文件,以及我在文档中看到的仅支持路径:( github上已经存在这个

我正在尝试创建pdf,但我有一些SVG图片。我找到了关于这个问题的信息,但我只需要使用JavaScript,也就是说,没有jQuery

我在这里找到了jsPDF:

还有pluginjspdf.plugin.sillysvgrender.js(在同一个文件夹中),我们可以在这里找到在文件夹测试中创建的PDF示例

但是当我试图自己生成PDF时,它不起作用,我不明白为什么


你知道怎么做吗

我让这个插件正常工作,但只有使用测试中的SVG文件,以及我在文档中看到的仅支持路径:(

github上已经存在这个问题

如果路径没有问题,这里是我的代码(或多或少是测试代码):


另一个要考虑的问题,你必须在服务器上运行所有的例子。否则,你可能看不到任何结果,可能是因为安全性

< P> > <强> Cuvg ,以便将SVG隐藏到画布中。然后使用<代码> ToDATOLL()/<代码> /< 更详细的答案在这里

在这里查看演示

Canvg Repo:

现在有jsPDF的哪些用途。 创建它就是为了解决这个确切的任务:将SVG导出为PDF

同时,jsPDF还添加了一个演示,演示如何导出SVG


这两种解决方案有不同的优点和缺点,因此您可能希望尝试这两种方法,看看其中一种是否适合您的需要。

您可以使用jsPDF附带的画布插件在带有canvg的PDF上渲染SVG。我必须在jsPDF画布实现上设置一些虚拟属性,并禁用交互式/动画canvg的功能使其能够正常工作而不会出现错误:

var jsPdfDoc = new jsPDF({
    // ... options ...
});

// ... whatever ...

// hack to make the jspdf canvas work with canvg
jsPdfDoc.canvas.childNodes = {}; 
jsPdfDoc.context2d.canvas = jsPdfDoc.canvas;
jsPdfDoc.context2d.font = undefined;

// use the canvg render the SVG onto the 
// PDF via the jsPDF canvas plugin.
canvg(jsPdfDoc.canvas, svgSource, {
    ignoreMouse: true,
    ignoreAnimation: true,
    ignoreDimensions: true,
    ignoreClear: true
});
在我看来,这似乎是一个比jsPDF的SVG插件好得多的解决方案,因为canvg对SVG功能的支持要好得多。请注意,应该在SVG的
元素上设置
宽度
高度
属性,以便canvg正确地呈现它(或者至少在我看来是这样)。

我修改了以下内容:


请注意,这意味着SVG在集成到PDF之前会转换为位图,因此您将失去矢量格式(通常更轻,分辨率独立)的好处。是@jcaron.jsPDF不支持SVG导出。如果您愿意,可以尝试PDFkit。请检查此示例
var jsPdfDoc = new jsPDF({
    // ... options ...
});

// ... whatever ...

// hack to make the jspdf canvas work with canvg
jsPdfDoc.canvas.childNodes = {}; 
jsPdfDoc.context2d.canvas = jsPdfDoc.canvas;
jsPdfDoc.context2d.font = undefined;

// use the canvg render the SVG onto the 
// PDF via the jsPDF canvas plugin.
canvg(jsPdfDoc.canvas, svgSource, {
    ignoreMouse: true,
    ignoreAnimation: true,
    ignoreDimensions: true,
    ignoreClear: true
});
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;