【问题标题】:How to make a Convert To PDF button in HTML如何在 HTML 中制作转换为 PDF 按钮
【发布时间】:2018-11-12 09:13:06
【问题描述】:

我尝试制作一个按钮,将我的 HTML 页面转换为 PDF 并下载它,但我无法让它工作。例如,如果这是页面:

function download() {
      print()
}
<html>
    <body>
    <h2>Page Content</h2>
    <br>
    <p>The page content will go <span style="color:red;">here...</span></p>
    <br><br>
    <button onclick="download()">Download Page</button><br>
     ^ The above button uses the <code>print()</code> function. However, this prompts the user with a print page, instead of asking to download.
    </body>
</html>
我得到的最接近的是添加一个运行print() 函数的按钮,但是它要求用户打印页面,而不是下载它。 有谁知道如何将 HTML 页面转换为 pdf 以供下载?

【问题讨论】:

  • 请添加更多工作细节,似乎有一些 js 库可以做到这一点。您尝试过其中任何一个吗?

标签: javascript html pdf


【解决方案1】:

首先,您创建一个 php 文件(或您想使用的任何技术)将 html 转换为 pdf(对于那些没有完成此步骤的人,wkHtmlToPdf 非常适合)。

下一步是可选的,但建议:
您创建一个读取文件的download.php,并将其回显到屏幕上,with the proper headers。该文件可以被保护(现在或以后),例如,您可能希望用户登录特定文件。现在可以轻松添加。

现在你在你的 html 模板中链接到它:&lt;a href="/download.php?file=123"&gt;download&lt;/a&gt;。因为download.php 将标头发送到浏览器(说“嗨,我是 PDF,下载我”)浏览器知道如何处理它。
如果您想跳过 download.php,我再次不推荐,直接链接到convertToPdf.php 并让输出结果而不是存储它。

【讨论】:

    【解决方案2】:

    选项 1:print() 方法打印当前窗口的内容。

        <button onclick="window.print()">Download page</button>
    

    选项 2:使用一些服务器端技术将 html 转换为 dpf,如 Martijn 答案。

    选项 3:使用 jsPDF 库在客户端处理。看看https://rawgit.com/MrRio/jsPDF/master/,那里有很多例子。

        function download() {
          var doc = new jsPDF();
    
          // All units are in the set measurement for the document
          // This can be changed to "pt" (points), "mm" (Default), "cm", "in"
          doc.fromHTML($('body').get(0), 15, 15, {
            'width': 170, 
          });
          doc.save();
        }
    

    &lt;button onclick="download()"&gt;Download page&lt;/button&gt;

    【讨论】:

      猜你喜欢
      • 2018-11-03
      • 2012-01-29
      • 1970-01-01
      • 2017-08-11
      • 2012-01-12
      • 2011-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多