Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSPDF addHTML not showing background image

I have a simple HTML page with a header section having a background image.

After converting the page to Html to pdf using jspdf all content displays expect background image.

see this fiddel https://jsfiddle.net/rmtest/30augcvj/2/

html

<body id="pdf">
    <!-- header section -->
     <div class="section-header" id="main_d">
         <h1>
            data
        </h1>
     </div>
</body>

css

.section-header{
//background-color:red;
  background-image: url("https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSkxORFDMPY7v_DGrlgBxnFBHtwifP9Uz28Y5-8TcNpdTwILs3E");
  background-repeat: no-repeat;
  max-height: 200px;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}

js

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js" integrity="sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/" crossorigin="anonymous"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<script>

    var pdf = new jsPDF('1', 'pt', 'a4');
    pdf.addHTML($('#pdf')[0], function () {
       // pdf.output("dataurlnewwindow");
   pdf.save('Test.pdf');
 });


</script>
like image 931
rahul.m Avatar asked Nov 28 '19 10:11

rahul.m


1 Answers

To answer this question, I first tried to use a newer version of html2canvas (1.0.0-rc.5) to see if the feature of adding a background image was available. Despite several attempts, I was unlucky. Here is a solution of mine (which is more correctly defined as a workaround):

Since the only property taken into account by the library is the background-color, we can not directly put an image in the css. At this point a solution would be to insert the image into jsPDF directly and write the title or other text on top of it.

This solution is only possible and convenient if the header is almost always the same.

var imgData = 'data:image/jpeg;base64,'+ Base64.encode('your-image.jpeg');
doc.addImage(imgData, 'JPEG', 15, 40, 180, 160);

and then the rest of the content can be added via addHTML, keeping in consideration the coordinates of the text with respect to those of the image.

like image 115
Lykos94 Avatar answered Oct 05 '22 13:10

Lykos94