我正在尝试创建一个 pdf,但我有一些 SVG 图片。我找到了关于这个问题的信息,但我只需要使用 JavaScript,也就是说,没有 jQuery。
我在这里找到了 jsPDF:https ://github.com/MrRio/jsPDF
有插件jspdf.plugin.sillysvgrenderer.js(在同一个文件夹中),我们可以在其中找到在文件夹test中创建的 PDF 示例。
但是当我尝试自己生成 PDF 时,它不起作用,我不明白为什么。
你知道怎么做吗?
我正在尝试创建一个 pdf,但我有一些 SVG 图片。我找到了关于这个问题的信息,但我只需要使用 JavaScript,也就是说,没有 jQuery。
我在这里找到了 jsPDF:https ://github.com/MrRio/jsPDF
有插件jspdf.plugin.sillysvgrenderer.js(在同一个文件夹中),我们可以在其中找到在文件夹test中创建的 PDF 示例。
但是当我尝试自己生成 PDF 时,它不起作用,我不明白为什么。
你知道怎么做吗?
我得到了这个插件,但只有来自测试的 SVG 文件和我在文档中看到只支持 PATH :(
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');
});
}
要考虑的另一点是,您必须在服务器上运行所有示例。否则您可能看不到任何结果,可能是因为安全性
尝试使用 canvg将 SVG 转换为 Canvas。然后使用 . 将画布转换为 base64 字符串.toDataURL()
。
更详细的答案在这里https://stackoverflow.com/a/35788928/2090459
在此处查看演示http://jsfiddle.net/Purushoth/hvs91vpq/
Canvg 回购:https ://github.com/gabelerner/canvg
我修改了这个: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;
现在有svg2pdf.js,它使用了jsPDF 的一个分支。它的创建是为了解决这个确切的任务:将 SVG 导出为 PDF。
同时,jsPDF 还添加了一个演示,展示了如何使用 canvg 和 jsPDF canvas implementation导出 SVG 。
这两种解决方案有不同的优点和缺点,因此您可能想同时尝试一下,看看其中一种是否适合您的需求。
可以使用jsPDF自带的canvas插件,用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 的元素上设置width
and属性,以便 canvg 正确呈现它(或者至少在我看来是这样)。height
<svg/>