'How to use bootstrap with xhtml2pdf?
I need to render PDF files dynamically in a Django web app.
I understand there are 2 options :
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 ?Convert a webpage into a PDF file directly
Solution 1:[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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |