How to display an image in two pages in PDF using jsPDF?

前端 未结 6 1326
庸人自扰
庸人自扰 2020-12-14 05:03

I have a html page. In which I have a button , whenerever I click this button it will convert the entire html page into data image using html2canvas and placed it into PDF u

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-14 05:37

    I Came out with this solution hope this will help you:

    PDFConverter.prototype.exportToPDF = function (divID, filename, pdfHeight) {
    
    html2canvas($('#' + divID), {                                       //Plugin:html2canvas.min.js,Takes html and convert to canvas.
    
        onrendered: function (canvas) {
            var doc = new jsPDF();                                    //Plugin:jspdf.min.js Using to export html to pdf file
            var HtmltoPdfPageHeight;
            if (pdfHeight)
                HtmltoPdfPageHeight = pdfHeight;
            var image = new Image();
            image = Canvas2Image.convertToJPEG(canvas);
    
            var croppingYPosition;
            var count = Math.ceil((image.height) / HtmltoPdfPageHeight);
    
    
            for (var i = 1; i <= count; i++) {
    
                if (i == 1) 
                    croppingYPosition = 0;
                else 
                    doc.addPage();
    
    
                var sourceX = 0;
                var sourceY = croppingYPosition;
    
                var croppingImageHeight = (image.height - (HtmltoPdfPageHeight * (i-1))) > HtmltoPdfPageHeight ? HtmltoPdfPageHeight : (image.height - (HtmltoPdfPageHeight * (i-1)));
                var destX = 0;
                var destY = 0;
                var croppedCanvas = document.createElement('canvas'); //Canvas using to resize main canvas
                croppedCanvas.setAttribute('height', croppingImageHeight);
                croppedCanvas.setAttribute('width', image.width);
                var ctx = croppedCanvas.getContext("2d");
                ctx.drawImage(image, sourceX,                                //drawImage(img, startX, startY, originalW, originalH, destX, destY, destW, destH);
                                     sourceY,
                                     image.width,
                                     HtmltoPdfPageHeight,
                                     destX,
                                     destY,
                                     image.width,
                                     HtmltoPdfPageHeight);
                var imageToAddatPdf = new Image(); //Final image exporting in pdf page
                imageToAddatPdf = Canvas2Image.convertToJPEG(croppedCanvas);
                doc.addImage(imageToAddatPdf.src, 'JPEG', 10, 10, 185, 0);
                croppingYPosition += HtmltoPdfPageHeight;
            }
    
            doc.save(filename + '.pdf');
    
    
    
        }
     });
    };
    

提交回复
热议问题