Search code examples
javascriptpdfjspdf

jspdf - specialElementHandlers to alter element


I want to generate a PDF from HTML, but the PDF sometimes contains different text. So I am trying to use the "specialElementHandlers" to alter some elements, before adding them to the PDF.

htmlToPDF(){
    var pdf = new jsPDF('p', 'pt', 'letter');
    var source = $('#HTMLtoPDF')[0];
    var specialElementHandlers = {
        '#bypassme': function(element, renderer) {
            return true
        },
        '#changeme': function (element, renderer) {
            return <h2>different text</h2>
        }
    };

Right now, I am trying to do something like this, but it won't work (at least the "changeme" part, the "bypassme" works flawlessly).

I'd highly appreciate any kind of help.


Solution

  • If you want to alter before adding it to the id, you have to return "false" in the specialElementHandler and change the element itself. E.G.:

    '#changeme': function (element, renderer) {
                element.innerHTML = "<div>New Text</div>";
                return false;
    

    Notice that you have to copy the elemnts for your pdf before. Otherwise you will also change the element on the website itself.

    const html = source.outerHTML;
    
        pdf.fromHTML (
            html // HTML string or DOM elem ref.
            , margins.left // x coord
            , margins.top // y coord
            , {
                'width': margins.width // max width of content on PDF
                , 'elementHandlers': specialElementHandlers
            },
    ...