cesarvr / pdf-generator

Cordova plugin to generate pdf in the client-side
MIT License
107 stars 61 forks source link

How to display variable from javascript into the pdf #22

Closed edwardpress closed 6 years ago

edwardpress commented 7 years ago

This is the code I attempted to run

var orderID = 12345; var rando = "abc"

window.onload = function() {

        document.getElementById('contact-number').innerHTML = orderID;
        document.getElementById('things').innerHTML = rando;

    }

    document.addEventListener('deviceready', () => {

        //generate the pdf.
        cordova.plugins.pdf.htmlToPDF({
                data: "<html> <h1>  Hello World  </h1> <h1> Order Number at <span id='contact-number'></span></h1> <h1> Random Variable </h1> <span id='things'></span></html>",

            },
            (sucess) => console.log('sucess: ', sucess),
            (error) => console.log('error:', error));
    });

Span id = "things" and span id contact-number returns nothing

cesarvr commented 7 years ago

You need to pre-process the HTML with a template engine like underscore template and then for example just doing:

<your html and styles>.......<span id='things'><%=rando%></span>.......<your html and styles>,

Compile it and then feed the result to the htmlToPDF::data method, look at the underscore web page for a more concrete documentation on how to use the compiler.

edwardpress commented 7 years ago

Thanks for the direction. I have attempted to install underscoreJS in ionic 2 and if I were to modify the code to such

    var rando = "ABC"
    var stuff= _.template('<p>Hello  World <%=rando %></p>');

}

document.addEventListener('deviceready', () => {

    //generate the pdf.
    cordova.plugins.pdf.htmlToPDF({
            data: "stuff",

        },
        (sucess) => console.log('sucess: ', sucess),
        (error) => console.log('error:', error));
});

Is this the correct way?

cesarvr commented 7 years ago

yeah, thats the way , you just need to take the quotes out of data: "stuff" , you can also practice in the chrome to check if the compilation is successful , then just pass the value of the variable to the method.