将html div转换为pdf [关闭]

I have a sort of bill generated in my web page which gets displayed in a div id "bill". I want that when the user clicks print, everything that is displayed in the "bill" div gets converted to pdf and it opens up automatically in another web page(tab) so that the user can print it? Can anyone help me with the code for it?

You can do it using jsPDF

Sample usage:

HTML:

<div id="bill">
     <h3>Hello, this is a H3 tag</h3>

    <p>a pararaph</p>
</div>
<div id="editor"></div>
<button id="cmd">generate PDF</button>

JavaScript:

var doc = new jsPDF();
var specialElementHandlers = {
    '#editor': function (element, renderer) {
        return true;
    }
};

    $('#cmd').click(function () {
        doc.fromHTML($('#bill').html(), 15, 15, {
            'width': 170,
                'elementHandlers': specialElementHandlers
        });
        doc.save('sample-file.pdf');
    });

DEMO

I sugest you use a PDF Utitlity to generate the pdf server side.

https://stackoverflow.com/questions/6118635/what-is-the-best-pdf-open-source-library-for-java

you can use open the page in a new window and write the bianary to the http response

You can also use a Javascript library called jsPDF for generating PDF files purely in client-side JavaScript.