繁体   English   中英

如何下载带有SVG的HTML作为PDF?

[英]How to download an HTML with SVGs as a PDF?

我有一个带有一些SVG的页面,我想从中生成一个PDF。 对于这个范围,我使用Open Saucer和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将其添加到pdf的临时模板中。 然后我用jsoup清理html转换为xhtml,我用Flying Saucer转换它并将它发送到http响应。

我得到的是仅带文字的pdf。 转换为图像的SVG不存在。

我还在这个SO答案中添加了-Djava.protocol.handler.pkgs=org.xhtmlrenderer.protocols ,但没有。 我怀疑问题是图像的src不是data:image/png例如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();
    });
}

作为替代方案,您可以使用作为pdf转换器

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

结果很完美。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM