导出到Pdf angular 6

时间:2019-03-08 17:28:02

标签: javascript angular angular6 jspdf html-to-pdf

我想使用角度6将HTML页面导出为pdf。 我写了下面的代码转换为pdf

let dataPdf = document.getElementById('contentToPrint');
const pdf = new jspdf('p', 'pt', 'a4');
pdf.addHTML(document.getElementById('contentToPrint'),()=>{
    pdf.save('web.pdf');
});

出现以下错误:

core.js:12301 ERROR Error: Supplied Data is not a valid base64-String jsPDF.convertStringToImageData 
    at Object.x.convertStringToImageData (jspdf.min.js:50)
    at Object.x.addImage (jspdf.min.js:50)
    at Object.<anonymous> (jspdf.min.js:188)
    at Object.options.complete (html2canvas.js:2711)
    at start (html2canvas.js:2215)
    at Object._html2canvas.Preload (html2canvas.js:2488)
    at html2canvas.js:2719
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
    at Object.onInvokeTask (core.js:13842)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420)

3 个答案:

答案 0 :(得分:1)

您需要将图像转换为base64。

如果图像是静态的,则可以在此处进行转换: https://www.base64-image.de/
如果图像是动态的: Converting an image to base64 in angular 2

将图像转换为base64字符串后,可以将其传递给jsPDf,如下所示:

pdf.addHTML('your base64 string);

答案 1 :(得分:1)

我正面临类似的问题。

您似乎需要将DOM元素转换为PNG。拥有它后,必须将其转换为base64字符串,并使用pdf.addImage()

添加

您可以使用html2canvas将DOM元素转换为图像。

编辑

let dataPdf = document.getElementById('contentToPrint');
const pdf = new jspdf('p', 'pt', 'a4');
 html2canvas(dataPdf).then((canvas) => {
   let img = canvas.toDataURL('image/png');
   pdf.addImage(img, 'png', 40, 90, 515, 600); //sizings here
   pdf.save('web.pdf');
 }

答案 2 :(得分:0)

您可以这样做

import html2canvas from 'html2canvas';

var data = document.getElementById('ELEMENT_ID');
        html2canvas(data).then(canvas => {
            var imgWidth = 208;
            var pageHeight = 295;
            var imgHeight = canvas.height * imgWidth / canvas.width;
            var heightLeft = imgHeight;

            const contentDataURL = canvas.toDataURL('image/png')
            let pdf = new jspdf('p', 'mm', 'a4'); // A4 size page of PDF  
            var position = 0;
            pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight)
            //save file with specific name
            pdf.save("Wallet.pdf");
        });