打开由JSPDF Image Canvas生成的PDF时出错

时间:2016-12-01 00:20:18

标签: jspdf

我正在使用以下javascript来拍摄页面的画布并将其转换为PDF,但是当它保存文件时......我无法以PDF格式打开文件我收到以下错误“处理时出错Page。有一个PRoblem阅读本文档(110)“我可以在浏览器中打开相同的文件,但不能在我的计算机上打开

 function exportPDF() {
     var pdf = new jsPDF('l','px'),
     source = $('body')[0];
     var canvasToImage = function(canvas){
     var img = new Image();
     var dataURL = canvas.toDataURL('image/png');
     img.src = dataURL;
     return img;
};
var canvasShiftImage = function(oldCanvas,shiftAmt){
    shiftAmt = parseInt(shiftAmt) || 0;
    if(!shiftAmt){ return oldCanvas; }

    var newCanvas = document.createElement('canvas');
    newCanvas.height = oldCanvas.height - shiftAmt;
    newCanvas.width = oldCanvas.width;
    var ctx = newCanvas.getContext('2d');

    var img = canvasToImage(oldCanvas);
    ctx.drawImage(img,0, shiftAmt, img.width, img.height, 0, 0, img.width, img.height);

    return newCanvas;
};


var canvasToImageSuccess = function(canvas){
    var pdf = new jsPDF('l','px'),
        pdfInternals = pdf.internal,
        pdfPageSize = pdfInternals.pageSize,
        pdfScaleFactor = pdfInternals.scaleFactor,
        pdfPageWidth = pdfPageSize.width,
        pdfPageHeight = pdfPageSize.height,
        totalPdfHeight = 0,
        htmlPageHeight = canvas.height,
        htmlScaleFactor = canvas.width / (pdfPageWidth * pdfScaleFactor),
        safetyNet = 0;

    while(totalPdfHeight < htmlPageHeight && safetyNet < 15){
        var newCanvas = canvasShiftImage(canvas, totalPdfHeight);
        pdf.addImage(newCanvas, 'png', 0, 0, pdfPageWidth, 0, null, 'NONE');

        totalPdfHeight += (pdfPageHeight * pdfScaleFactor * htmlScaleFactor);

        if(totalPdfHeight < htmlPageHeight){
            pdf.addPage();
        }
        safetyNet++;
    }

    pdf.save(address.innerHTML  + 'test.PDF');
};

html2canvas(source, {
    onrendered: function(canvas){
        canvasToImageSuccess(canvas);
    }
});

1 个答案:

答案 0 :(得分:0)

请按照以下git链接

的回答

https://github.com/MrRio/jsPDF/issues/862