美文网首页
JS - HTML 转 PDF 并下载

JS - HTML 转 PDF 并下载

作者: iseerain | 来源:发表于2022-06-26 01:54 被阅读0次

    支持页面边距

    
    import html2canvas from 'html2canvas';
    import JsPDF from 'jspdf';
    
    const [PDF_WIDTH, PDF_HEIGHT] = [595.28, 841.89];
    
    export function downloadPdf(element, filename, options) {
        if (!element) return;
    
        let marginX = (options && (options.marginX || options.margin)) || 0;
        let marginY = (options && (options.marginY || options.margin)) || 0;
    
        return html2canvas(element, {
            allowTaint: true,
            useCORS: true,
        }).then(canvas => {
            let [contentWidth, contentHeight] = [canvas.width, canvas.height];
            let [realPdfWidth, realPdfHeight] = [PDF_WIDTH - marginX * 2, PDF_HEIGHT - marginY * 2];
    
            let singlePageContentHeight = Math.ceil((contentWidth / realPdfWidth) * realPdfHeight);
            let pageCount = Math.ceil(contentHeight / singlePageContentHeight);
    
            let pdf = new JsPDF({
                orientation: 'p',
                unit: 'px',
                format: [PDF_WIDTH, PDF_HEIGHT],
                compress: true,
            });
    
            if (pageCount < 2) {
                pdf.addImage(canvas.toDataURL(), 'JPEG', marginX, marginY, realPdfWidth, realPdfHeight);
            } else {
                for (let i = 0; i < pageCount; i++) {
                    if (i > 0) {
                        pdf.addPage();
                    }
    
                    let singlePageImgData = canvas
                        .getContext('2d')
                        .getImageData(0, i * singlePageContentHeight, contentWidth, singlePageContentHeight);
    
                    let tempCanvas = document.createElement('canvas');
                    tempCanvas.width = contentWidth;
                    tempCanvas.height = singlePageContentHeight;
                    tempCanvas.getContext('2d').putImageData(singlePageImgData, 0, 0);
    
                    pdf.addImage(tempCanvas.toDataURL(), 'JPEG', marginX, marginY, realPdfWidth, realPdfHeight);
                }
            }
    
            let res = pdf.save(filename);
    
            return res;
        });
    }
    
    

    使用

    
    // margin default 0;
    downloadPdf(elementObject, 'file.pdf'');
    或
    downloadPdf(elementObject, 'file.pdf', { margin: 30 });
    或
    downloadPdf(elementObject, 'file.pdf', { marginX: 30 , marginY: 20});
    
    

    相关文章

      网友评论

          本文标题:JS - HTML 转 PDF 并下载

          本文链接:https://www.haomeiwen.com/subject/ypmwvrtx.html