是否可以使用JavaScript或jquery将HTML页面保存为PDF?

时间:2011-08-01 09:39:23

标签: javascript jquery jquery-ui

是否可以使用JavaScript或jquery将HTML页面保存为PDF?

详细信息:

我生成了一个包含表格的HTML页面。它有一个按钮'另存为PDF'。如果用户单击该按钮,则该HTML页面必须转换为PDF文件。

是否可以使用JavaScript或jquery?

13 个答案:

答案 0 :(得分:23)

,使用jspdf创建pdf文件。

然后,您可以将其转换为数据URI并将下载链接注入DOM

然而,您需要自己编写HTML到pdf转换。

只需使用打印机友好版本的页面,让用户选择打印页面的方式。

编辑:显然它的支持度很低

所以答案是编写自己的PDF编写器或者让现有的PDF编写器为您(在服务器上)执行此操作。

答案 1 :(得分:11)

Ya很容易用javascript做。希望这段代码对你有用。

您需要JSpdf library

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

    <p>a pararaph</p>
</div>
<div id="editor"></div>
<button id="cmd">Generate PDF</button>

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

    // This code is collected but useful, click below to jsfiddle link.
</script>

jsfiddle link here

答案 2 :(得分:5)

以下是我将如何做到这一点,它的想法不是防弹设计,你需要修改它

  • 用户点击另存为PDF按钮
  • 使用ajax
  • 向服务器发送呼叫
  • 服务器响应使用HTML生成的PDF的URL,我非常熟练地使用了Apache FOP
  • 处理ajax响应的js执行location.href指向JS发送的URL,并且一旦加载该URL,它就会使用内容处置标头作为附件发送文件,强制用户下载文件。

答案 3 :(得分:5)

你可以使用Phantomjs。下载here并使用以下示例测试html-&gt; pdf转换功能https://github.com/ariya/phantomjs/blob/master/examples/rasterize.js

示例代码:

phantomjs.exe examples/rasterize.js http://www.w3.org/Style/CSS/Test/CSS3/Selectors/current/xhtml/index.html sample.pdf

答案 4 :(得分:4)

这可能是一个迟到的答案,但这是最好的: https://github.com/eKoopmans/html2pdf

纯粹的javascript实现。 允许您按ID指定单个元素并进行转换。

答案 5 :(得分:2)

简而言之:不。 第一个问题是访问文件系统,由于安全原因,在大多数浏览器中默认设置为no。现代浏览器有时支持数据库形式的简约存储,或者您可以要求用户启用文件访问。

如果您有权访问文件系统,那么保存为HTML并不困难(请参阅JS文档中的文件对象) - 但PDF并不那么容易。 PDF是一种非常先进的文件格式,真的不适合Javascript。它要求您以Javascript不直接支持的数据类型(如单词和四边形)编写信息。您还需要预定义必须保存到文件的字典查找系统。我确信有人可以使它工作,但所花费的精力和时间将更好地用于学习C ++或Delphi。

如果用户为您提供非限制访问

,则应该可以进行HTML导出

答案 6 :(得分:2)

我使用jsPDFdom-to-image库将HTML导出为PDF。

我在这里张贴有关谁​​关注的内容。

$('#downloadPDF').click(function () {
    domtoimage.toPng(document.getElementById('content2'))
      .then(function (blob) {
          var pdf = new jsPDF('l', 'pt', [$('#content2').width(), $('#content2').height()]);
          pdf.addImage(blob, 'PNG', 0, 0, $('#content2').width(), $('#content2').height());
          pdf.save("test.pdf");
      });
});

演示:https://jsfiddle.net/viethien/md03wb21/27/

答案 7 :(得分:1)

使用JavaScript将HTML转换为PDf还有另一种非常明显且简单的方法:使用在线API。如果您在用户离线时不需要进行转换,这将正常工作。

FreeHtmlToPdf.com是一个有很好API的选项。我确定您可以找到替代方案(例如PdfMage,它们显然拥有自己的API但不会共享其协议)。

对于FreeHtmlToPdf API,您可以这样:

var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "http://freehtmltopdf.com");

var hiddenField = document.createElement("input");
hiddenField.setAttribute("name", "html");
hiddenField.setAttribute("value", "<html><body>Hi there!</body></html>");
form.appendChild(hiddenField);

hiddenField = document.createElement("input");
hiddenField.setAttribute("name", "baseurl");
hiddenField.setAttribute("value", "http://localhost");
form.appendChild(hiddenField);

hiddenField = document.createElement("input");
hiddenField.setAttribute("name", "convert");
hiddenField.setAttribute("value", "");
form.appendChild(hiddenField);

document.body.appendChild(form);
form.submit();

答案 8 :(得分:1)

是。例如,您可以使用https://grabz.it之前的解决方案。

它有一个Javascript API,可以用不同的方式来抓取和操作屏幕截图。要在您的应用中使用它,您需要先获得免费的Javascript SDK app key and secretdownload

所以,让我们看一个使用它的简单例子:

//first include the grabzit.min.js library in the web page
<script src="grabzit.min.js"></script>
//include the code below to add the screenshot to the body tag    
<script>
//use secret key to sign in. replace the url.
GrabzIt("Sign in to view your Application Key").ConvertURL("http://www.google.com").Create();
</script>

然后只需等待一会儿,图片就会自动显示在页面底部,而无需重新加载页面。

这是最简单的一个。有关图像处理的更多示例,将屏幕截图附加到元素等,请检查documentation

答案 9 :(得分:1)

$('#cmd2').click(function() {
  	var options = {
		//'width': 800,
  	};
  	var pdf = new jsPDF('p', 'pt', 'a4');
  	pdf.addHTML($("#content2"), -1, 220, options, function() {
    	pdf.save('admit_card.pdf');
  	});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>

<div id="content2" style="background: #fff;border-bottom: 1px solid #ffffff;">
                    	<div class="tokenDet" style="padding: 15px;border: 1px solid #000;width: 80%;margin: 0 auto;position: relative;overflow: hidden;">
                        	<div class="title" style="text-align: center;border-bottom: 1px solid #000;margin-bottom: 15px;">
                            	<h2>Entrance Exam Hall Ticket</h2>
                            </div>
                            <div class="parentdiv" style="display: inline-block;width: 100%;position: relative;">
                            	<div class="innerdiv" style="width: 80%;float: left;">
                            		<div class="restDet">
                                        <div class="div">
                                            <div class="label" style="width: 30%;float: left;">
                                                <strong>Name</strong>
                                            </div>
                                            <div class="data" style="width: 70%;display: inline-block;">
                                                <span>Santanu Patra</span>
                                            </div>
                                            <div class="label" style="width: 30%;float: left;">
                                                <strong>D.O.B.</strong>
                                            </div>
                                            <div class="data" style="width: 70%;display: inline-block;">
                                                <span>17th April, 1995</span>
                                            </div>
                                            <div class="label" style="width: 30%;float: left;">
                                                <strong>Address</strong>
                                            </div>
                                            <div class="data" style="width: 70%;display: inline-block;">
                                                <span>P.S. Srijan Corporate Park, Saltlake, Sector 5, Kolkata-91</span>
                                            </div>
                                            <div class="label" style="width: 30%;float: left;">
                                                <strong>Contact Number</strong>
                                            </div>
                                            <div class="data" style="width: 70%;display: inline-block;">
                                                <span>9874563210</span>
                                            </div>
                                            <div class="label" style="width: 30%;float: left;">
                                                <strong>Email Id</strong>
                                            </div>
                                            <div class="data" style="width: 70%;display: inline-block;">
                                                <span>santanu@macallied.com</span>
                                            </div>
                                            <div class="label" style="width: 30%;float: left;">
                                                <strong>Parent(s) Name</strong>
                                            </div>
                                            <div class="data" style="width: 70%;display: inline-block;">
                                                <span>S. Patra</span><br /><span>7896541230</span>
                                            </div>
                                            <div class="label" style="width: 30%;float: left;">
                                                <strong>Exam Center</strong>
                                            </div>
                                            <div class="data" style="width: 70%;display: inline-block;">
                                                <span>Institute of Engineering & Management</span>
                                            </div>
                                            <div class="label" style="width: 30%;float: left;">
                                                <strong>Hall Number</strong>
                                            </div>
                                            <div class="data" style="width: 70%;display: inline-block;">
                                                <span>COM-32</span>
                                            </div>
                                        </div>
                                    </div>
                            	</div>
                                <div class="sideDiv" style="width: 20%;float: left;">
                                	<div class="atts" style="float: left;width: 100%;">
                                    	<div class="photo" style="width: 115px;height: 150px;float: right;">
                                        	<img src="images/candidateImg.gif" style="width: 100%;"/>
                                        </div>
                                        <div class="sign" style="position: absolute;bottom: 0;right: 0;border-top: 1px dashed #000;left: 80%;text-align: right;">
                                        	<small>Self Attested</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <button class="btn btn-info" id="cmd2">Download Token</button>

答案 10 :(得分:0)

将html转换为pdf服务器端更加容易和可靠。我们正在使用Google Puppeteer。它可以通过包装器很好地维护您选择的任何服务器端语言。 Puppeteer使用无头的Chrome生成屏幕截图和/或PDF文件。它将为您省去很多麻烦,尤其是当您需要生成包含表格,图像,图形,多页等的复杂PDF文件时

https://developers.google.com/web/tools/puppeteer/

答案 11 :(得分:0)

有类似的问题,无法使用 jspdf,因为我的旧代码包含多个表,其中包含多个 colspan。在 Jspdf thead > th's must match tbody > tr > td

我最终使用了对我有用的 html2pdf 包

在您的文件中添加库

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.8.1/html2pdf.bundle.min.js" integrity="sha512-vDKWohFHe2vkVWXHp3tKvIxxXg0pJxeid5eo+UjdjME3DBFBn2F8yWOE0XmiFcFbXxrEOR1JriWEno5Ckpn15A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

获取您要保存为 pdf 的内容

var pdf_content = document.getElementById("pdf_body");

将选项或配置添加到您的文件

var options = {
      margin:       1,
      filename:     'isolates.pdf',
      image:        { type: 'jpeg', quality: 0.98 },
      html2canvas:  { scale: 2 },
      jsPDF:        { unit: 'in', format: 'letter', orientation: 'portrait' }
    };

保存文件

html2pdf(pdf_content, options);

答案 12 :(得分:-5)

我认为不,因为JavaScript无法写入磁盘 您应该将页面发送到服务器并生成pdf文件,然后客户端将下载它