javascript - 如何使用 JavaScript 从 HTML 生成 PDF?

标签 javascript pdf

我想从 HTML 生成 PDF。我试过的库是 print.js, jsPDF

使用 print.js 我有 HTML 并试图将其转换为 PDF 并且它成功了,但是 PDF 只是 HTML,没有 CSS。但这不适合我。 Sample example

<table id="printJS-form">
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td>Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
</table>


<button type="button" onclick="printJS('printJS-form', 'html')">
    Print Form
</button>

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}

最接近成功的是 jsPDF,这次我使用所有 CSS 创建图像,然后从该图像生成 PDF。但这里的问题是生成的 PDF 只是图像,我丢失了 PDF 中的所有元数据。 Sample example

<body>
  <div id="printJS-form">

   <h3 id='head-color'>Test heading</h3>
   <button id='print-btn'>Start print process</button>
  </div>
</body>

$('#print-btn').click(()=>{
   var pdf = new jsPDF();
    pdf.addHTML(document.body,function() {
    pdf.save('web.pdf');
 });
})

#head-color{
  color: blue;
}

我尝试并真正希望能在这里实现的另一件事是 “onbeforeprint” 事件,因为它对我来说似乎更干净。在调用 window.print() 之前,“onbeforeprint” 事件被激活。 如果 “onbeforeprint”,PDF 已经生成我想以某种方式访问​​它。但我无法弄清楚它是如何以及是否完全可能的。 Sample example

<html>
<body onbeforeprint="myFunction()">

<h1>Try to print this document</h1>
<p><b>Tip:</b> Keyboard shortcuts, such as Ctrl+P sets the page to print.</p>
<p><b>Note:</b> The onbeforeprint event is not supported in Safari and Opera.</p>
<button type="button" onclick="printWindow()">
    Print Form
</button>
<script>
function myFunction() {
// get blob pdf
  alert("You are about to print this document!");
}
function printWindow() {
 window.print();
}
</script>

</body>
</html>

最后我要问

有没有一种方法,使用 print.js 或 jsPDF,不仅可以获取 html,还可以获取 css?

我可以从 “onbeforeprint” 事件或任何其他 javascript 事件获取二进制 PDF 吗?

最佳答案

我想你可以使用 Puppeteer生成pdf。我没有尝试过,但这里有一些链接可以证明这种方法:

关于javascript - 如何使用 JavaScript 从 HTML 生成 PDF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56881586/

相关文章:

node.js - 如何在Nodejs中将word文档转换为pdf

java - 如何使用 PDFBox 的 PDFPagePanel 查看 PDF 文档

javascript - 如何通过ajax发送自动生成的pdf文件

c# - 如何将 PDF 从 Web API 发送到 MVC 应用程序以供直接下载

javascript - 是否可以在 Mozilla 中将网站设置为主页?

javascript - CSS - 给定元素之后的样式元素

javascript - 在javascript中内部对象文字之间使用函数

javascript - 点击事件的条件是否适用于否定语句?

javascript - ASP.NET 文档.getElementById ('<%=Control.ClientID%>' );返回空

c# - 如何从特定矩形区域内的 pdf 文档中提取文本?