Issue with fromhtml method in jspdf lib

2.1k Views Asked by At

I need to convert html to pdf and I found jspdf lib. But I ran into a ropblem. If <p> tag contains some text inside like this: text<br /><br />text it not works. I have a following error in console:

Uncaught TypeError: Cannot read property '1' of undefined
at Renderer.renderParagraph (from_html.js:967)
at Renderer.setBlockBoundary (from_html.js:1018)
at DrillForContent (from_html.js:529)
at DrillForContent (from_html.js:497)
at from_html.js:669
at done (from_html.js:539)
at loadImgs (from_html.js:569)
at process (from_html.js:667)
at Object.jsPDFAPI.fromHTML (from_html.js:1105)
at saveDocument (index.js:17)

In script imports I have next modules:

  • jquery.min.js
  • jspdf.min.js
  • split_text_to_size.js
  • from_html.js
  • standard_fonts_metrics.js

HTML:

<div id="blank">
     <p>some text<br /><br />another text</p>   
</div>
<button onclick="saveDocument();">Save PDF</button>

JavaScript:

function saveDocument() {
    var pdf = new jsPDF();
    var content = $('#blank').html();
    pdf.fromHTML(content, 15, 15, {
        'width': 170
    });
    pdf.save('document.pdf');
}

I don't now how to fix it?

3

There are 3 best solutions below

0
Monarth Sarvaiya On BEST ANSWER

you have to use separate <p> tag:

<p>some text</p><br /><br />
<p>another text</p>   
0
Amer On

End up using https://www.npmjs.com/package/html2pdf-fix-jspdf which is typically a wrapper on jspdf.

Separate p tags was not possible in my case and I tried all possible solutions for this. Like using

and \r\n but nothing works in my case.

Just sharing as it might be helpful

1
RähMÿ ÃtHÅš On

in my case, i used: replace(/<br>/ig, '<p><br></p>'); it worked

var htmlContent = $('#response-container').html();
htmlContent = htmlContent.replace(/<br>/ig, '<p><br></p>');

doc.fromHTML(htmlContent, 15, 15, {
  'width': 170,
  'elementHandlers': specialElementHandlers
});

doc.save('sample-file.pdf');