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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6896592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:39:56  来源:igfitidea点击:

Is it possible to save HTML page as PDF using JavaScript or jquery?

javascriptjqueryjquery-ui

提问by ram

Is it possible to save HTML page as PDF using JavaScript or jquery?

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

In Detail:

详细:

I generated one HTML Page which contains a table . It has one button 'save as PDF'. If user clicks that button then that HTML page has to convert as PDF file.

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

Is it possible using JavaScript or jquery?

是否可以使用 JavaScript 或 jquery?

回答by Raynos

Yes, Use jspdfTo create a pdf file.

是的,使用jspdf来创建 pdf 文件。

You can then turn it into a data URI and inject a download link into the DOM

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

You will however need to write the HTML to pdf conversion yourself.

但是,您需要自己编写 HTML 到 pdf 的转换。

Just use printer friendly versions of your page and let the user choose how he wants to print the page.

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

Edit:Apparently it has minimal support

编辑:显然它的支持最少

So the answer is write your own PDF writer or get a existing PDF writer to do it for you (on the server).

因此,答案是编写您自己的 PDF 编写器或让现有的 PDF 编写器为您完成(在服务器上)。

回答by Blackjoker

Ya its very easy to do with javascript. Hope this code is useful to you.

雅它很容易做到与 javascript。希望此代码对您有用。

You'll need the JSpdf library.

您将需要JSpdf 库

<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

jsfiddle 链接在这里

回答by Billcountry

This might be a late answer but this is the best around: https://github.com/eKoopmans/html2pdf

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

Pure javascript implementation. Allows you to specify just a single element by ID and convert it.

纯 JavaScript 实现。允许您仅通过 ID 指定单个元素并对其进行转换。

回答by Hien Nguyen

I used jsPDFand dom-to-imagelibrary to export HTML to PDF.

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

I post here as reference to whom concern.

我在这里发帖作为参考。

$('#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");
      });
});

Demo: https://jsfiddle.net/viethien/md03wb21/27/

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

回答by Kumar

Here is how I would do it, its an idea not bulletproof design, you need to modify it

这是我会怎么做,它的想法不是防弹设计,你需要修改它

  • The user clicks the save as PDF button
  • The server is sent a call using ajax
  • The server responds with a URL for PDF generated using HTML, I have used Apache FOP very succssfully
  • The js handling the ajax response does a location.href to point the URL send by JS and as soon as that URL loads, it sends the file using content disposition header as attachment forcing user to download the file.
  • 用户单击另存为 PDF 按钮
  • 使用ajax向服务器发送呼叫
  • 服务器以使用 HTML 生成的 PDF 的 URL 进行响应,我非常成功地使用了 Apache FOP
  • 处理 ajax 响应的 js 执行 location.href 以指向 JS 发送的 URL,一旦该 URL 加载,它就会使用内容处置标头作为附件发送文件,迫使用户下载文件。

回答by singh1469

You can use Phantomjs. Download hereand use the following example to test the html->pdf conversion feature https://github.com/ariya/phantomjs/blob/master/examples/rasterize.js

您可以使用 Phantomjs。在此处下载并使用以下示例测试 html->pdf 转换功能https://github.com/ariya/phantomjs/blob/master/examples/rasterize.js

Example code:

示例代码:

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

回答by Andre Borges

There is another very obvious way to convert HTML to PDf using JavaScript: use an online API for that. This will work fine if you don't need to do the conversion when the user is offline.

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

PdfMageis one option that has a nice API and offers free accounts. I'm sure you can find many alternatives (for example, here)

PdfMage是一种具有良好 API 并提供免费帐户的选项。我相信你可以找到很多替代品(例如,这里

For PdfMage API you'd have something like this:

对于 PdfMage API,你会有这样的东西:

 $.ajax({
    url: "https://pdfmage.org/pdf-api/v1/process",
    type: "POST",
    crossDomain: true,
    data: { Html:"<html><body>Hi there!</body></html>" },
    dataType: "json",
    headers: {
        "X-Api-Key": "your-key-here" // not very secure, but a valid option for non-public domains/intranet
    },
    success: function (response) {
        window.location = response.Data.DownloadUrl;
    },
    error: function (xhr, status) {
        alert("error");
    }
});

回答by Jon Lennart Aasenden

In short: no. The first problem is access to the filesystem, which in most browsers is set to no by default due to security reasons. Modern browsers sometimes support minimalistic storage in the form of a database, or you can ask the user to enable file access.

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

If you have access to the filesystem then saving as HTML is not that hard (see the file object in the JS documentation) - but PDF is not so easy. PDF is a quite advanced file-format that really is ill suited for Javascript. It requires you to write information in datatypes not directly supported by Javascript, such as words and quads. You also need to pre-define a dictionary lookup system that must be saved to the file. Im sure someone could make it work, but the effort and time involved would be better spent learning C++ or Delphi.

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

HTML export however should be possible if the user gives you non restricted access

但是,如果用户为您提供不受限制的访问权限,则应该可以导出 HTML

回答by Johnny

Yes. For example you can use the solution by https://grabz.it.

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

It's got a Javascript API which can be used in different ways to grab and manipulate the screenshot. In order to use it in your app you will need to first get an app key and secretand downloadthe free Javascript SDK.

它有一个 Javascript API,可以以不同的方式使用它来抓取和操作屏幕截图。为了在您的应用程序中使用它,您首先需要获得一个应用程序密钥和秘密,然后下载免费的 Javascript SDK。

So, let's see a simple example for using it:

因此,让我们看一个使用它的简单示例:

//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>

Then simply wait a short while and the image will automatically appear at the bottom of the page, without you needing to reload the page.

然后只需稍等片刻,图像就会自动出现在页面底部,而无需重新加载页面。

That's the simplest one. For more examples with image manipulation, attaching screenshots to elements and etc check the documentation.

这是最简单的一种。有关图像处理、将屏幕截图附加到元素等的更多示例,请查看文档

回答by Santanu

$('#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>[email protected]</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>