如何使用javascript在JSPDF中将SVG文件转换为PDF

时间:2015-01-09 08:42:48

标签: javascript html svg pdf-generation jspdf

我努力使用JSPDF将SVG文件转换为PDF。在这里,我使用以下代码。

 var doc = new jsPDF();
    var test = $.get('amChart.svg', function(svgText){
    //  console.log(svgText);
        var svgAsText = new XMLSerializer().serializeToString(svgText.documentElement);
        console.log(svgAsText);
        doc.addSVG(svgAsText, 20, 20, doc.internal.pageSize.width - 20*2)
//console.log(doc);
        // Save the PDF
  doc.output('datauri');
    });

我从此SO Answer获取此脚本。其结果仅空白PDF 。当我console.log(doc)输出之前它将显示结果。但它不会导致 PDF ...

我也在这个GITHUB URL SVGELEMENTOPDF 函数中工作,我也在这个代码中工作。

// I recommend to keep the svg visible as a preview
var svg = $('#container > svg').get(0);
// you should set the format dynamically, write [width, height] instead of 'a4'
var pdf = new jsPDF('p', 'pt', 'a4');
svgElementToPdf(svg, pdf, {
    scale: 72/96, // this is the ratio of px to pt units
    removeInvalid: true // this removes elements that could not be translated to pdf from the source svg
});
pdf.output('datauri'); // use output() to get the jsPDF buffer

但是我无法实现它......并建议我......如何在 JSPDF中解决这个问题

1 个答案:

答案 0 :(得分:1)

对我有用的是:

  1. 使用svgCrowbar序列化SVG

    var uri = svgCrowbar(eGraph);
    
  2. 使用画布

    将序列化SVG写入PNG dataURI
    // Create image object which will enable the graph to be saved (via canvas)
    var image = new Image();
    image.onload = function () {
        // Create canvas 
        var canvas = document.createElement('canvas');
        canvas.width = image.width;
        canvas.height = image.height;
        var context = canvas.getContext('2d');
        context.drawImage(image, 0, 0);
    
        // Save DataURI for later use
        window.sitescriptdata.dataURI[id] = canvas.toDataURL('image/png');
        window.sitescriptdata.numDataURIsLoaded++;        
    
        ...
    
    };
    image.src = uri;
    
  3. 使用jsPDF.addImage()将该PNG嵌入PDF

  4. 使用这种方法,我能够将多个动态生成的SVG嵌入到单个PDF中。我对结果并不十分满意,因为PDF上的图像看起来很扭曲,但可能是我需要对jsPDF设置进行更多调整以使所有内容看起来都清晰。