2

I currently need to create a pdf file from HTML or Vue component.
I have tried jsPDF, html2pdf, vue-html2pdf but it looks like these libraries using html2canvas which mean it's freeze UI in few seconds (depends on HTML structure) and can't run inside web worker.
So my questions: how to generate pdf from HTML without using html2canvas or using web worker to avoid freeze UI

I believe this can be achieved because reactjs have react-pdf which create pdf without using canvas

Chinh Nguyen
  • 1,246
  • 1
  • 7
  • 16
  • You can try pdfmake: https://github.com/bpampuch/pdfmake. Look like it use pdfkit, just like react-pdf – Cuong Le Ngoc Jun 13 '21 at 14:02
  • @CuongNgocLe pdfmake is not convert HTML to pdf entirely, it uses table layout so very difficult with complicated UI. react-pdf look like have a bunch of class before using pdfkit, I'm not good at react so I don't quite understand what they are doing – Chinh Nguyen Jun 13 '21 at 16:12

2 Answers2

2

I don't know if this will help your problem but in this link a way to printing a pdf without using third party libraries is explained. It uses print property of the window.

canozsoy
  • 71
  • 1
  • 2
0

you can use javascript and jquery to print it

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

you can also add style css to the page by add this line between head tag, if html file and css file in same folder

printWindow.document.write('<link rel="stylesheet" href="style.css" />')
Mhammed Talhaouy
  • 1,129
  • 10
  • 14