jquery 使用JavaScript将HTML页面中的div下载为PDF

ezykj2lf  于 5个月前  发布在  jQuery
关注(0)|答案(6)|浏览(80)

我有一个ID为“content”的内容div。在内容div中,我有一些图表和一些表格。我想在用户点击下载按钮时将该div下载为PDF。有没有一种方法可以使用JavaScript或jQuery?

olmpazwi

olmpazwi1#

您可以使用jsPDF来执行此操作

HTML:

<div id="content">
     <h3>Hello, this is a H3 tag</h3>

    <p>A paragraph</p>
</div>
<div id="editor"></div>
<button id="cmd">generate PDF</button>

字符串

JavaScript:

var doc = new jsPDF();
var specialElementHandlers = {
    '#editor': function (element, renderer) {
        return true;
    }
};

$('#cmd').click(function () {
    doc.fromHTML($('#content').html(), 15, 15, {
        'width': 170,
            'elementHandlers': specialElementHandlers
    });
    doc.save('sample-file.pdf');
});

mxg2im7a

mxg2im7a2#

<div class='html-content'>....</div>中的内容可以下载为pdf格式,样式使用jspdfhtml2canvas
您需要同时引用这两个js库,

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>

字符串
然后调用下面的函数,

//Create PDf from HTML...
function CreatePDFfromHTML() {
    var HTML_Width = $(".html-content").width();
    var HTML_Height = $(".html-content").height();
    var top_left_margin = 15;
    var PDF_Width = HTML_Width + (top_left_margin * 2);
    var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
    var canvas_image_width = HTML_Width;
    var canvas_image_height = HTML_Height;

    var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;

    html2canvas($(".html-content")[0]).then(function (canvas) {
        var imgData = canvas.toDataURL("image/jpeg", 1.0);
        var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
        pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height);
        for (var i = 1; i <= totalPDFPages; i++) { 
            pdf.addPage(PDF_Width, PDF_Height);
            pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height*i)+(top_left_margin*4),canvas_image_width,canvas_image_height);
        }
        pdf.save("Your_PDF_Name.pdf");
        $(".html-content").hide();
    });
}


参考:pdf genration from html canvas and jspdf
也许这会帮助某人。

6tqwzwtp

6tqwzwtp3#

您的解决方案需要一些Ajax方法来将html传递给具有html to pdf工具的后端服务器,然后将生成的pdf输出返回给浏览器。
首先设置客户端代码,我们将jQuery代码设置为

var options = {
    "url": "/pdf/generate/convert_to_pdf.php",
    "data": "data=" + $("#content").html(),
    "type": "post",
};
$.ajax(options);

字符串
然后从html2pdf生成脚本中截取数据(来自互联网的某个地方)。
convert_to_pdf.php看起来像这样:

<?php
    $html = $_POST['data'];
    $pdf = html2pdf($html);
    
    header("Content-Type: application/pdf"); //check this is the proper header for pdf
    header("Content-Disposition: attachment; filename='some.pdf';");
    echo $pdf;
?>

sqserrrh

sqserrrh4#

AFAIK没有原生的jquery函数可以完成此操作。最好的选择是在服务器上处理转换。如何执行此操作取决于您使用的语言(.net,php等)。您可以将div的内容传递给处理转换的函数,该函数将向用户返回PDF。

3phpmpom

3phpmpom5#

是的,可以在JS中将div捕获为PDF。您可以检查https://grabz.it提供的解决方案。他们有漂亮而干净的JavaScript API,可以让您捕获单个HTML元素的内容,例如div或span。
所以,哟使用它,你将需要和应用程序+密钥和免费的SDK .它的用法如下:
假设你有一个HTML:

<div id="features">
    <h4>Acme Camera</h4>
    <label>Price</label>$399<br />
    <label>Rating</label>4.5 out of 5
</div>
<p>Cras ut velit sed purus porttitor aliquam. Nulla tristique magna ac libero tempor, ac vestibulum felisvulput ate. Nam ut velit eget
risus porttitor tristique at ac diam. Sed nisi risus, rutrum a metus suscipit, euismod tristique nulla. Etiam venenatis rutrum risus at
blandit. In hac habitasse platea dictumst. Suspendisse potenti. Phasellus eget vehicula felis.</p>

字符串
要捕获features id下的内容,您需要:

//add the sdk
<script type="text/javascript" src="grabzit.min.js"></script>
<script type="text/javascript">
//login with your key and secret. 
GrabzIt("KEY", "SECRET").ConvertURL("http://www.example.com/my-page.html",
{"target": "#features", "format": "pdf"}).Create();
</script>


您需要将http://www.example.com/my-page.html替换为您的目标URL和#feature
现在,当页面加载时,一个图像截图将在与脚本标签相同的位置创建,它将包含features div的所有内容,而没有其他内容。
还有其他配置和定制你可以做的div截图机制,请检查出来here

5cnsuln7

5cnsuln76#

我想我会补充我的两分钱,因为这里的一些答案已经超过10年了,并且有一些显著的性能瓶颈。
使用@Vishnu S的答案并进行一些小的修改,我们从每页910.52 ms减少到每页112.49 ms。减少了超过87%

// SEE: https://www.npmjs.com/package/html-to-image
import { toJpeg } from "html-to-image";

// The dimensions of a single A4 page; what we're basing the PDF document on.
const A4_MARGIN_PX         = 40;
const A4_CONTENT_WIDTH_PX  = 640;
const A4_CONTENT_HEIGHT_PX = A4_CONTENT_WIDTH_PX * A4_PORTRAIT_RATIO;
const A4_TOTAL_WIDTH_PX    = A4_CONTENT_WIDTH_PX  + (A4_MARGIN_PX * 2);
const A4_TOTAL_HEIGHT_PX   = A4_CONTENT_HEIGHT_PX + (A4_MARGIN_PX * 2);

// Will return a data URI string.
const htmlToPdf = async (element: HTMLElement): Promise<string> => {
    const elementBounds = element.getBoundingClientRect();

    const pdfBounds = [A4_TOTAL_WIDTH_PX, A4_TOTAL_HEIGHT_PX];
    const pdf = new jsPDF("portrait", "px", pdfBounds);
     
    // These settings are optional, but I've found they help with file size and retina display support.
    const pdfAsImage = await toJpeg(element, { 
        quality:    0.95,
        pixelRatio: 2,
    });

    const totalPages = Math.ceil(elementBounds.height / A4_CONTENT_HEIGHT_PX);

    for(let pageNum = 0; pageNum < totalPages; pageNum++){
        // Add a page as long as it's not the first page, as jsPDF does this automatically.
        // This will focus the added page, as a side-effect.
        if(pageNum > 0) pdf.addPage(pdfBounds);

        pdf.addImage(
            pdfAsImage,
            "jpg",
            
            // Reposition the image based on the page number.
            A4_MARGIN_PX,
            A4_MARGIN_PX - (pageNum * (A4_CONTENT_HEIGHT_PX + (A4_MARGIN_PX * 2))),

            A4_CONTENT_WIDTH_PX,
            elementBounds.height
        );
    }

    return pdf.output("datauristring");
};

字符串

相关问题