How to get table row image in PDF using jsPDF?

elina picture elina · Nov 7, 2016 · Viewed 7.2k times · Source

i have a html table with images.When i was trying to convert as PDF Only data are coming.Image not displaying in PDF.

How to get table td images in pdf ?

enter image description here

Contract Title Contains a Checkbox image.But is not coming in pdf ?

my pdf code :

function fnExportDIVToPDF() {

     var pdf = new jsPDF('l', 'pt', 'a2');
    pdf.setFontSize(8);
    source = $('#divReport')[0];
    specialElementHandlers = {
   '#bypassme': function (element, renderer) {
    return true
        }
    };
    margins = {
        top: 30, bottom: 40, left: 10, width: 1300};

    pdf.fromHTML(
            source, margins.left, margins.top, {
                'elementHandlers': specialElementHandlers},

    function (dispose) {

        pdf.save('Report.pdf');
    }
    , margins);
}

Div:

<div id="divReport">

                        <div width="100%">
                            <p><span id="oHeadingSummary" class="rptheader"></span></p>

                        </div>

                        <table class="table table-striped rpttable" border="1" cellspacing="0" id="oReportContractDetailsByCA" width="100%">
                            <colgroup>...    <col width="10%">
                            </colgroup></table>

Autogenerate table i added a image :

    function GenerateTable(data) {
    document.getElementById('divExport').style.display = "";
    if (i == 0) {
        $('#oReportContractDetailsByCA').append("<tr style='background-color:" + bkColor + ";'><td><img src='../../../_layouts/15/1033/IMAGES/eContracts/checked-checkbox-512.jpg'></img></td></tr>")
    }

Answer

Simon Bengtsson picture Simon Bengtsson · Nov 7, 2016

You can use the didDrawCell hook to add any content to a cell.

https://codepen.io/someatoms/pen/vLYXWB

function generate() {
  var doc = new jsPDF();

  doc.autoTable({
    html: '#mytable',
    bodyStyles: {minCellHeight: 15},
    didDrawCell: function(data) {
      if (data.column.index === 5 && data.cell.section === 'body') {
         var td = data.cell.raw;
         // Assuming the td cells have an img element with a data url set (<td><img src="data:image/jpeg;base64,/9j/4AAQ..."></td>)
         var img = td.getElementsByTagName('img')[0];
         var dim = data.cell.height - data.cell.padding('vertical');
         var textPos = data.cell.textPos;
         doc.addImage(img.src, textPos.x,  textPos.y, dim, dim);
      }
    }
  });

  doc.save("table.pdf");
}