我有一个带有一些SVG的页面,我想从中生成一个PDF。对于这个范围我使用Flying Saucer with OpenPDF,我使用以下方法将SVG转换为图像:
var $body_clone = $('#pdf_container').clone();
var $svgs = $body_clone.find('svg');
var $svg;
var xml;
var data;
var $img;
for (var i=0; i<$svgs.length; i++) {
var $svg = $svgs.eq(i);
xml = new XMLSerializer().serializeToString($svg[0]);
data = "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(xml)));
$img = $(new Image());
$img.attr('src', data);
$img.width($svg.outerWidth(true));
$img.height($svg.outerHeight(true));
$svg.replaceWith($img[0].outerHTML);
}
我尝试删除clone()
和提交它的工作原理:SVG在页面中被替换为(丑陋的)图像。
恢复clone()
和表单提交,我在服务器上发送$body_clone
的html,使用Mustache
将其添加到pdfs的临时模板中。然后我用jsoup
清理html转换为xhtml,我用Flying Saucer转换它并将其发送到http响应。
我得到的是仅带文字的pdf。转换为图像的SVG不存在。
我也按照-Djava.protocol.handler.pkgs=org.xhtmlrenderer.protocols
的建议添加了SO answer,但没有。我怀疑问题是src
的图像不是data:image/png
,例如,但data:image/svg+xml
。
无论如何,我试图用浏览器(Firefox)打印整个页面,以PDF格式打印到文件(Lubuntu)。不仅显示图像,而且它们是完美的。 Lubuntu使用什么来打印到pdf?可以将它用作外部转换器吗?如果没有,它是如何工作的,有一种方法可以模拟打印到文件?
我最终以这种方式使用SaveSvgAsPng:
function downloadPdf() {
"use strict";
// get the graphics global container
var $body_clone = $('#pdf_container');
// get the SVGs
var $svgs = $('.graph_container svg');
var $svg;
var promises = [];
for (var i=0; i<$svgs.length; i++) {
$svg = $svgs.eq(i);
// convert the SVGs to images srcs
promises.push(svgAsPngUri($svg[0]));
}
$.when.apply(null, promises).then(function() {
var img_scrs = Array.prototype.slice.call(arguments);
var $img;
for (var i=0; i<$svgs.length; i++) {
$svg = $svgs.eq(i);
$img = $(new Image());
$img.attr("src", img_scrs[i]);
// substitute the SVGs with the image
$svg.replaceWith(imgs[i]);
}
var $body_clone = $('#pdf_container');
var body = $body_clone[0].outerHTML;
$('#pdfBody').val(body);
// send to the server the HTML of the container of all images
$('#pdfForm').submit();
// get all images
var $imgs = $('.graph_container img:not(.waiting)');
var $img;
for (var i=0; i<$imgs.length; i++) {
$img = $imgs.eq(i);
// replace image with empty svg
$img.replaceWith('<svg></svg>');
}
// repopulate the graphs as you did at the page load
grafic();
});
}
作为替代方案,您可以使用chromium作为pdf converter:
chromium-browser --headless --print-to-pdf=path/to/file.pdf https://example.com
要么
chromium-browser --headless --print-to-pdf=path/to/file.pdf file:/path/to/file.html
结果很完美。