简体   繁体   English

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

[英]How to converted SVG Files into PDF in JSPDF using javascript

I struggled to converted SVG Files into PDF using JSPDF. 我努力使用JSPDF将SVG文件转换为PDF。 Here i Worked in following code. 我在这里工作在下面的代码。

 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');
    });

I get this script from this SO Answer .Its results only blank PDF .When i console.log(doc) before output it will shown results.But it will not results in PDF ... 我从这个SO Answers得到这个脚本。它的结果只有空白的PDF 。当我在输出之前输出console.log(doc)时会显示结果。但是不会导致PDF ...

And I also i working in SVGELEMENTOPDF function from this GITHUB URL and I worked in this code also. 我也从这个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

But I can`t achieved it..And kindly advise me... How to solve this problem in JSPDF 但是我没有做到。.请给我...如何在JSPDF中解决这个问题

What worked for me was to: 对我有用的是:

  1. Use svgCrowbar to serialize the SVG 使用svgCrowbar序列化SVG

     var uri = svgCrowbar(eGraph); 
  2. Write the serialized SVG to a PNG dataURI using canvas 使用画布将序列化的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. Use jsPDF.addImage() to embed that PNG into the PDF 使用jsPDF.addImage()将PNG嵌入到PDF中

Using this method I was able to embed multiple dynamically generated SVGs into a single PDF. 使用这种方法,我能够将多个动态生成的SVG嵌入到单个PDF中。 I'm not 100% happy with the outcome as the images on the PDF look distorted, but it might be that I need to do more tweaking of the jsPDF settings to get everything to look crisp. 由于PDF上的图像看起来失真,我对结果不满意100%,但这可能是我需要对jsPDF设置进行更多调整,以使所有内容看起来更加清晰。

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

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