1

I need to render PDF files dynamically in a Django web app.

I understand there are 2 options :

  1. Render an html template file then convert it to a PDF file.
    I used xhtml2pdf Python library.
    The issue is that the template I want to use has bootstrap and it isn't supported by xhtml2pdf. Actually no javascript is supported and the generated PDFs are horrible.
    I have to write the html / css myself which I don't want to.
    How to solve this problem ?
    Is there an alternative library ?

  2. Convert a webpage into a PDF file directly

1 Answers1

-1

I had that problem too. I solved this problem with html2canvas and jspdf.

Here's my code. And use it by modifying it to suit you.

// on click 
<script src="{% static '/js/html2canvas.min.js' %}"></script>
<script src="{% static '/js/jspdf.min.js' %}"></script>

<script>
const page = document.getElementById('element that you want to make pdf')

$('#{{save_btn_id}}').click(function () {
  html2canvas(page).then(async function (canvas) { 
    // convert canvas to image
    let imgData = canvas.toDataURL('image/png');

    let imgWidth = 190; // image width (mm)
    let pageHeight = imgWidth * 1.414; 
    let imgHeight = canvas.height * imgWidth / canvas.width;
    let heightLeft = imgHeight;
    let margin = 10; 
    let doc = new jsPDF('p', 'mm');
    let position = 0;

    doc.addImage(imgData, 'PNG', margin, position, imgWidth, imgHeight);
    heightLeft -= pageHeight;

    // if page > 1
    while (heightLeft >= 20) {
      position = heightLeft - imgHeight;
      doc.addPage();
      doc.addImage(imgData, 'PNG', margin, position, imgWidth, imgHeight);
      heightLeft -= pageHeight;
    }

    
    doc.save('{{file_name}}-{{docNum}}.pdf');
})
</script>
seokmin-kang
  • 189
  • 4
  • Okay, so you don't even use an html template ? And what exactly is a "page" ? – Ilyes Hamdi May 16 '22 at 19:00
  • I use html template. this is the last code of html file. and the "page" is the area you want to extract. for example, you want to generate the whole. page = document.body; if you want to generate one table. page = document.getElementById('table id'); – seokmin-kang May 17 '22 at 00:56
  • It is better to refer to another answer. like this https://stackoverflow.com/questions/66519144/export-pdf-with-jspdf-and-html2canvas – seokmin-kang May 17 '22 at 01:03