>

html 페이지가 있습니다. 버튼이있는 곳 에서이 버튼을 클릭 할 때마다 html2canvas를 사용하여 전체 HTML 페이지를 데이터 이미지로 변환하고 jsPDF 라이브러리를 사용하여 PDF로 배치합니다. 사용중인 자바 스크립트는

$("#printButton").click(function(){
html2canvas([document.getElementById('form1')], {
        onrendered: function (canvas) {
            var imageData = canvas.toDataURL('image/jpeg',1.0); 
           var doc = new jsPDF('landscape');
           doc.addImage(imageData,'JPEG',5,20,200,150);
           doc.save('Test.pdf');
     }
    });
});

이미지를 첫 페이지에만 표시합니다. 그러나 html 페이지 크기가 더 커질 때마다 이미지 데이터를 잘라서 PDF로 두 페이지에 배치하고 싶습니다. 이 문제를 해결하도록 도와주세요.

  • 답변 # 1

    완벽한 답변은 아니지만 여전히 작동합니다

                   $("#btnSaveAsPDF").click(function () {
                    html2canvas($("#tblSaveAsPdf_canvas"), {
                    onrendered: function (canvas) {
                    var imageData = canvas.toDataURL("image/jpeg");
                    var image = new Image();
                    image = Canvas2Image.convertToJPEG(canvas);
                    var doc = new jsPDF();
                    doc.addImage(imageData, 'JPEG', 12, 10);
                    var croppingYPosition = 1095;
                    count = (image.height) / 1095;
                    for (var i =1; i < count; i++) {
                            doc.addPage();
                            var sourceX = 0;
                            var sourceY = croppingYPosition;
                            var sourceWidth = image.width;
                            var sourceHeight = 1095;
                            var destWidth = sourceWidth;
                            var destHeight = sourceHeight;
                            var destX = 0;
                            var destY = 0;
                            var canvas1 = document.createElement('canvas');
                            canvas1.setAttribute('height', destHeight);
                            canvas1.setAttribute('width', destWidth);                         
                            var ctx = canvas1.getContext("2d");
                            ctx.drawImage(image, sourceX, 
                                                 sourceY,
                                                 sourceWidth,
                                                 sourceHeight, 
                                                 destX, 
                                                 destY, 
                                                 destWidth, 
                                                 destHeight);
                            var image2 = new Image();
                            image2 = Canvas2Image.convertToJPEG(canvas1);
                            image2Data = image2.src;
                            doc.addImage(image2Data, 'JPEG', 12, 10);
                            croppingYPosition += destHeight;              
                        }                  
                    var d = new Date().toISOString().slice(0, 19).replace(/-/g, "");
                    filename = 'report_' + d + '.pdf';
                    doc.save(filename);
                }
            });
        });
    
    

  • 답변 # 2

    코드를 업데이트했습니다. 자른 이미지의 끝에 검은 색 배경없이 여러 페이지 및보다 정확한 자르기를 사용할 수 있습니다.

    코드

    $('#pdf').on('click', function(){
        html2canvas(document.body, {
            onpreloaded: function(){
                  $("#barra").hide(); 
            },
            onrendered: function(canvas) {
                $("#page").hide();
                var imgData = canvas.toDataURL('image/jpeg');              
                options = {
                    orientation: "0",
                    unit: "mm",
                    format: "a4"
                };
                var doc = new jsPDF(options, '', '', '');
                doc.addImage(imgData, 'jpeg', 10, 10, 190, 0);
                var corte = 1620; // configura tamanho do corte
                var image = new Image();
                image = Canvas2Image.convertToJPEG(canvas);
                var croppingYPosition = corte;
                var count = (image.height)/corte;
    
                for (var i =1; i < count; i++) {
                        doc.addPage();
                        var sourceX = 0;
                        var sourceY = croppingYPosition;
                        var sourceWidth = image.width;
                        var sourceHeight = corte;
                        var destWidth = sourceWidth;
                        var destHeight = sourceHeight;
                        var destX = 0;
                        var destY = 0;
                        var canvas1 = canvas;
                        canvas1.setAttribute('height', (image.height)-(corte*i));
                        canvas1.setAttribute('width', destWidth);                         
                        var ctx = canvas1.getContext("2d");
                        ctx.drawImage(image, sourceX, 
                                             sourceY,
                                             sourceWidth,
                                             sourceHeight, 
                                             destX, 
                                             destY, 
                                             destWidth, 
                                             destHeight);
                        var image2 = new Image();
                        image2 = Canvas2Image.convertToJPEG(canvas1);
                        image2Data = image2.src;
                        doc.addImage(image2Data, 'JPEG', 10, 10, 190, 0);
                        croppingYPosition += destHeight;              
                    }     
    
                doc.save('sample-file.pdf');
                $('canvas').remove();
                $('canvas1').remove();
                $("#page").show();
                $("#barra").show();
            }
        });
    });
    
    

  • 답변 # 3

    html2canvas($('#wrap')[0]).then(canvas => {
            try {
                contentH = $('#wrap').height();
                var img = canvas.toDataURL("image/png", 1.0);
                $w = $actw = canvas.width;
                $h = $acth = canvas.height;
                var pdf = new jsPDF("p", "mm", "a4");
                var width = $maxw = pdf.internal.pageSize.width;
                var height = $maxh = pdf.internal.pageSize.height;
                if (!$maxw) $maxw = width;
                if (!$maxh) $maxh = height;
                if ($w > $maxw) {
                    $w = $maxw;
                    $h = Math.round($acth / $actw * $maxw);
                }
                pdf.addImage(img, 'JPEG', 0, 0, $w, $h);
                $count = Math.ceil($h) / Math.ceil($maxh);
                $count = Math.ceil($count);
                for (var i = 1; i <= $count; i++) {
                    position = - $maxh * i
                    alert(position);
                    pdf.addPage(img, 'JPEG', 0, 0, $w, $h);
                    pdf.addImage(img, 'JPEG', 0, position, $w, $h);
                }
                pdf.save("cart.pdf");
            } catch (e) {
                alert("Error description: " + e.message);
            }
        });
    
    

  • 답변 # 4

    여러 페이지에 긴 이미지를 넣으려면 다음과 같이 나왔습니다 :

    var img = new Image();
    img.onload = function(){
        while (croppingYPosition < image.height) {
            var sourceX = 0;
            var sourceY = croppingYPosition;
            var sourceWidth = image.width;
            var sourceHeight = maxHeight;
            var leftToCropHeight = image.height - croppingYPosition;
            if (leftToCropHeight < maxHeight) {
                sourceHeight = leftToCropHeight;
            }
            var destWidth = sourceWidth;
            var destHeight = sourceHeight;
            var destX = 0;
            var destY = 0;
            var canvas = document.createElement('canvas');
            canvas.setAttribute('height', destHeight);
            canvas.setAttribute('width', destWidth);
            var ctx = canvas.getContext('2d');
            ctx.drawImage(img, 
                            sourceX,
                            sourceY,
                            sourceWidth,
                            sourceHeight,
                            destX,
                            destY,
                            destWidth,
                            destHeight);
            croppedImages.push(CanvasToJPEGConversionService.toJPEG(canvas));
            croppingYPosition += destHeight;
        }
        retur croppedImages;
    };
    img.src = image.dataURL;
    
    

    기본적으로 dataURL (자른 이미지)이 포함 된 객체 배열을 얻습니다.

  • 답변 # 5

    이 솔루션을 사용하면 이것이 도움이되기를 바랍니다.

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

관련 자료

  • 이전 ios - 신속한 다중 상속을 수행하는 방법은 무엇입니까?
  • 다음 mqtt - python을 사용하여 paho에서 초당 메시지를 늘리는 방법