在 html2canvas/jspdf 中添加边距

问题描述 投票:0回答:2

我使用html2canvas和jspdf将多页网页导出为pdf。 但是,生成的 pdf 中没有边距。 如何使用 html2canvas 或 jspdf 添加边距。

html2canvas(document.body, {
    scale: 0.8,
    logging: true,
    allowTaint: false,
    backgroundColor: null
}).then(function(canvas) {
    // Export the canvas to its data URI representation
    var base64image = canvas.toDataURL("image/jpeg");
    console.log('Report Image URL: ' + base64image);

    var imgWidth = 295; 
    var pageHeight = 210;  
    var imgHeight = canvas.height * imgWidth / canvas.width;
    var heightLeft = imgHeight;    
    var doc = new jsPDF("l", "mm", "a4"); // landscape
    var position = 0;

    var width = doc.internal.pageSize.getWidth();
    var height = doc.internal.pageSize.getHeight();    
    doc.addImage(base64image,'JPEG', 0, position, imgWidth, imgHeight);
    heightLeft -= pageHeight;

    while (heightLeft >= 0) {
        position = heightLeft - imgHeight;
        doc.addPage();
        doc.addImage(base64image,'JPEG', 0, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;
    }

    doc.save('test.pdf');
});
html2canvas
2个回答
6
投票

如果是多页则不起作用。 2 页之间没有间隙。 以下是我修改后的代码:

html2canvas(document.body, {
    scale: 0.8,
    logging: true,
    allowTaint: false,
    backgroundColor: null
}).then(function(canvas) {
    // Export the canvas to its data URI representation
    var base64image = canvas.toDataURL("image/jpeg");
    console.log('Report Image URL: ' + base64image);

    var imgWidth = 295; 
    var pageHeight = 210;  
    var imgHeight = canvas.height * imgWidth / canvas.width;
    var heightLeft = imgHeight;    
    var doc = new jsPDF("l", "mm", "a4"); // landscape
    var position = 0;

    /* addImage explained below:
        param 1 -> image in code format
        param 2 -> type of the image. SVG not supported. needs to be either PNG or JPEG.
        all params are specified in integer
        param 3 -> X axis margin from left
        param 4 -> Y axis margin from top
        param 5 -> width of the image
        param 6 -> height of the image
    */   

    var width = doc.internal.pageSize.getWidth();
    var height = doc.internal.pageSize.getHeight();    
    doc.addImage(base64image,'JPEG', 10, 10, imgWidth-17, imgHeight);
    heightLeft -= pageHeight;

    while (heightLeft >= 0) {
        position = heightLeft - imgHeight;
        doc.addPage();
        doc.addImage(base64image,'JPEG', 10, position, imgWidth-17, imgHeight);
        heightLeft -= pageHeight;
    }

    doc.save('test.pdf');
});

0
投票
//for react
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';

const PdfGenerator = ({
    elementId,
    fileName = 'document.pdf',
    headerText = '',
    imgWidth = 190,
    pageHeight = 297,
}) => {
    const input = document.getElementById(elementId);
    if (!input) {
        console.error(`Element with ID "${elementId}" not found.`);
        return;
    }

    // Set different bottom margin based on screen resolution
    const bottomMargin = window.innerWidth < 500 ? 40 : 20; // Change to desired margin for small screens

    html2canvas(input, { useCORS: true, scale: 1.5 }).then((canvas) => {
        const imgHeight = (canvas.height * imgWidth) / canvas.width;
        const pdf = new jsPDF();

        let heightLeft = imgHeight;
        let position = 0;
        let pageNumber = 1; // Initialize page number
        let totalPages = Math.ceil(heightLeft / (pageHeight - bottomMargin)); // Calculate total pages

        while (heightLeft > 0) {
            // Calculate remaining page height, excluding bottom margin for content only
            const pageContentHeight = pageHeight - bottomMargin;

            // Slice the content for the current page
            const canvasPage = canvas.getContext('2d').getImageData(0, position, canvas.width, Math.min(canvas.height, pageContentHeight * (canvas.width / imgWidth)));
            const pageCanvas = document.createElement('canvas');
            pageCanvas.width = canvas.width;
            pageCanvas.height = Math.min(canvas.height - position, pageContentHeight * (canvas.width / imgWidth));
            pageCanvas.getContext('2d').putImageData(canvasPage, 0, 0);
            const imgData = pageCanvas.toDataURL('image/png');

            if (position === 0) {
                // First page
                pdf.addImage(imgData, 'PNG', 10, 5, imgWidth, pageCanvas.height * (imgWidth / canvas.width));
            } else {
                // New pages
                pdf.addPage();
                pdf.setFontSize(10);

                if (headerText) {
                    const pageWidth = pdf.internal.pageSize.getWidth();
                    const textWidth = pdf.getTextWidth(headerText);
                    const textX = (pageWidth - textWidth) / 2;
                    pdf.text(headerText, textX, 15);
                }

                pdf.addImage(imgData, 'PNG', 10, 25, imgWidth, pageCanvas.height * (imgWidth / canvas.width));
            }

            // Add footer with page number at the very bottom of the page
            if (totalPages > 1) {
                const footerText = `Page ${pageNumber}`;
                const pageWidth = pdf.internal.pageSize.getWidth();
                const footerX = pageWidth - pdf.getTextWidth(footerText) - 10; // Align to the right with some padding
                pdf.setFontSize(10);
                pdf.text(footerText, footerX, pageHeight - 10); // Position at the bottom without margin
            }

            heightLeft -= pageContentHeight;
            position += pageContentHeight * (canvas.width / imgWidth);
            pageNumber++; // Increment page number
        }

        pdf.save(fileName);
    });
};

export default PdfGenerator;

// UseCase
// const exportPDF = () => {
//     PdfGenerator({
//       elementId: 'report', //which id want to print
//       fileName: 'Electricity resource report.pdf',
//       headerText: 'Electricity resource report'
//     })`enter code here`
//   };
© www.soinside.com 2019 - 2024. All rights reserved.