Exporting PDF with jspdf not rendering CSS

后端 未结 5 1768
深忆病人
深忆病人 2020-11-27 18:13

I am using jspdf.debug.js to export different data from a website but there are a few problems, I can\'t get it to render the CSS in the exported PDF and if I have an image

相关标签:
5条回答
  • 2020-11-27 18:52

    To remove black background only add background-color: white; to the style of

    0 讨论(0)
  • 2020-11-27 18:58

    As I know jsPDF is not working with CSS and the same issue I was facing.

    To solve this issue, I used Html2Canvas. Just Add HTML2Canvas JS and then use pdf.addHTML() instead of pdf.fromHTML().

    Here's my code (no other code):

     var pdf = new jsPDF('p', 'pt', 'letter');
     pdf.addHTML($('#ElementYouWantToConvertToPdf')[0], function () {
         pdf.save('Test.pdf');
     });
    

    Best of Luck!

    Edit: Refer to this line in case you didn't find .addHTML()

    0 讨论(0)
  • 2020-11-27 19:04

    jspdf does not work with css but it can work along with html2canvas. You can use jspdf along with html2canvas.

    include these two files in script on your page :

    <script type="text/javascript" src="html2canvas.js"></script>
      <script type="text/javascript" src="jspdf.min.js"></script>
      <script type="text/javascript">
      function genPDF()
      {
       html2canvas(document.body,{
       onrendered:function(canvas){
    
       var img=canvas.toDataURL("image/png");
       var doc = new jsPDF();
       doc.addImage(img,'JPEG',20,20);
       doc.save('test.pdf');
       }
    
       });
    
      }
      </script>
    

    You need to download script files such as https://github.com/niklasvh/html2canvas/releases https://cdnjs.com/libraries/jspdf

    make clickable button on page so that it will generate pdf and it will be seen same as that of original html page.

    <a href="javascript:genPDF()">Download PDF</a>  
    

    It will work perfectly.

    0 讨论(0)
  • 2020-11-27 19:05

    Slight change to @rejesh-yadav wonderful answer.

    html2canvas now returns a promise.

    html2canvas(document.body).then(function (canvas) {
        var img = canvas.toDataURL("image/png");
        var doc = new jsPDF();
        doc.addImage(img, 'JPEG', 10, 10);
        doc.save('test.pdf');        
    });
    

    Hope this helps some!

    0 讨论(0)
  • 2020-11-27 19:11

    You can get the example of css implemented html to pdf conversion using jspdf on following link: JSFiddle Link

    This is sample code for the jspdf html to pdf download.

    $('#print-btn').click(() => {
        var pdf = new jsPDF('p','pt','a4');
        pdf.addHTML(document.body,function() {
            pdf.save('web.pdf');
        });
    })
    
    0 讨论(0)
提交回复
热议问题