我正在尝试创建一个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时,它不起作用,我不明白为什么。
你知道怎么做吗?
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');
});
}
另一个需要考虑的问题是,你必须在服务器上运行所有的示例。否则,由于安全原因,你可能无法看到任何结果。
.toDataURL()
将画布转换为base64字符串。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
});
width
和height
属性应设置在<svg/>
元素上,以便canvg正确渲染它(或者至少对我来说是这样)。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;