简体   繁体   中英

Rendering HTML to PDF with images included Django

I have a django app where users would print some pages which include images as a part of Data processing.

I tried jsPDF but it didn't render my images and I ended up with just text

$(document).ready(function() {
  $("#pdfDownloader").click(function() {

    var doc = new jsPDF('p', 'pt', 'a4', true);

    doc.fromHTML($('#renderMe').get(0), 15, 15, {
      'width': 500
    }, function (dispose) {
    doc.save('thisMotion.pdf');
    });
  });
})

This was my code and it didn't render the images so do I need to change anything?

is using a Django view would solve this and is there any alternatives to xhtml2pdf as with this I need to include my CSS in the HTML file ?

fromHTML is used to get text from the HTML to form a PDF. Try using html2canvas js library instead.

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.5.0-beta4/html2canvas.min.js"></script>

You can create a canvas image and add it to the PDF with code like this,

$(document).ready(function() {
  $("#pdfDownloader").click(function() {

html2canvas($("#renderMe")).then(canvas => {  
      const contentDataURL = canvas.toDataURL('image/png')  
      let pdf = new jspdf('p', 'pt', 'a4', true); // A4 size page of PDF  
      var positionX = 0;  
      var positionY = 0;
      pdf.addImage(contentDataURL, 'PNG', positionY, positionY, undefined, undefined)  
      pdf.save('thisMotion.pdf'); // Generated PDF   
    });

});
})

This will get you a PDF just like the HTML rendered on screen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM