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

12

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

我在这里找到了jsPDF:https://github.com/MrRio/jsPDF

这里有一个插件jspdf.plugin.sillysvgrenderer.js(在同一个文件夹中),我们可以在test文件夹中找到一个PDF文件的示例。

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

你知道怎么做吗?

5个回答

3
我已经使这个插件工作了,但只有来自测试和文档中看到的SVG文件才支持路径:(
Github上已有此问题https://github.com/MrRio/jsPDF/issues/384 如果路径可以,请看下面是我的代码(更多或更少是测试代码):
function demoSvgDocument() {
    var doc = new jsPDF();
    var test = $.get('013_sillysvgrenderer.svg', function(svgText){
        var svgAsText = new XMLSerializer().serializeToString(svgText.documentElement);
        doc.addSVG(svgAsText, 20, 20, doc.internal.pageSize.width - 20*2)

        // Save the PDF
        doc.save('TestSVG.pdf');
    });
}       

另一个需要考虑的问题是,你必须在服务器上运行所有的示例。否则,由于安全原因,你可能无法看到任何结果。


未捕获的类型错误:doc.addSVG不是一个函数。 - Sardar Faisal
2
@SardarFaisal addSVG目前已不再存在,现在改为addSvgAsImage。 - Owais Ahmed

3

9
请注意,这意味着在将SVG集成到PDF中之前,它将被转换为位图,因此您将失去矢量格式的优势(通常较轻且分辨率无关)。 - jcaron
1
是的@jcaron。jsPDF不支持SVG导出。如果您想尝试,可以使用PDFkit。请查看此示例http://pdfkit.org/demo/browser.html。 - Purushoth

1
你可以使用jsPDF自带的canvas插件,在PDF上使用canvg渲染SVG。为了使其正常工作,我不得不在jsPDF canvas实现上设置一些虚拟属性,并禁用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的widthheight属性应设置在<svg/>元素上,以便canvg正确渲染它(或者至少对我来说是这样)。

1
现在有svg2pdf.js,它使用jsPDF的一个分支。它被创建来解决这个确切的任务:将SVG导出为PDF。
同时,jsPDF也添加了一个演示,展示如何可能使用canvg和jsPDF画布实现导出SVG 这两个解决方案各有优劣,因此您可能希望尝试两种方法,看看哪种更适合您的需求。

1
我从这里修改了这个内容: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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接