【问题标题】:vue html to pdf without html2canvasvue html到pdf没有html2canvas
【发布时间】:2021-08-26 04:12:39
【问题描述】:

我目前需要从 HTML 或 Vue 组件创建一个 pdf 文件。
我已经尝试过jsPDFhtml2pdfvue-html2pdf,但看起来这些库使用 html2canvas,这意味着它会在几秒钟内冻结 UI(取决于 HTML 结构)并且无法在 Web Worker 中运行。
所以我的问题是:如何在不使用 html2canvas 或使用网络工作者的情况下从 HTML 生成 pdf 以避免冻结 UI

我相信这是可以实现的,因为 reactjs 有 react-pdf 可以在不使用画布的情况下创建 pdf

【问题讨论】:

  • 你可以试试pdfmake:github.com/bpampuch/pdfmake。看起来它使用 pdfkit,就像 react-pdf 一样
  • @CuongNgocLe pdfmake 不是将 HTML 完全转换为 pdf,它使用表格布局非常困难,用户界面复杂。 react-pdf 貌似在使用 pdfkit 之前有一堆类,我不擅长 react 所以不太明白他们在做什么

标签: javascript reactjs vue.js pdf vuejs2


【解决方案1】:

我不知道这是否会对您的问题有所帮助,但 in this link 解释了一种无需使用第三方库即可打印 pdf 的方法。它使用窗口的打印属性。

【讨论】:

  • 它确实在创建 pdf,但我无法从主窗口检索 pdf
  • 我想创建 pdf 文件来预览但我不想下载它,比如创建一个 blob 以在网络上查看
【解决方案2】:

您可以使用javascriptjquery 进行打印

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>html2pdf</title>
  </head>
  <body>
    <div id="page">
      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Numquam id, ex
      facere perferendis eligendi corporis provident ipsam, ea porro debitis
      natus aut nulla, ipsa atque aliquam architecto est dolorem impedit!
    </div>
    <button id="btn">print content</button>

    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
      referrerpolicy="no-referrer"
    ></script>
    <script>
      $('#btn').click(function () {
        var divContents = $('#page').html()
        var printWindow = window.open('', '_self', 'height=400,width=800')
        printWindow.document.write('<html><head><title>html2pdf</title>')
        
        printWindow.document.write('</head><body>')
        printWindow.document.write(divContents)
        printWindow.document.write('</body></html>')
        printWindow.document.close()
        printWindow.print()
      })
    </script>
  </body>
</html>

您还可以在页面中添加样式 css 通过在head 标签之间添加这一行,如果html 文件和css 文件在同一文件夹中

printWindow.document.write('<link rel="stylesheet" href="style.css" />')

【讨论】:

  • 但这不会创建 PDF。它只是打开一个打印对话框。
  • @tony19 是对的,您的解决方案不会创建文件(Blob),它会打开打印对话框进行下载
  • 是的,它会打开一个对话框,但您可以打印该 pdf
猜你喜欢
  • 2018-05-11
  • 2021-07-23
  • 1970-01-01
  • 2019-07-09
  • 2018-05-20
  • 2021-12-26
  • 2020-04-22
  • 2013-09-15
相关资源
最近更新 更多