Search code examples
javascripthtmljspdf

Using jsPDF to export a Div in my website into a PDF format report but can't get the right format


as what the title says, I'm using jsPDF to export a div section in my website to be exported as a PDF document.

These are my codes

<script>
function exportToPDF() {
    var pdf = new jsPDF('l', 'pt', 'a4');
    // source can be HTML-formatted string, or a reference
    // to an actual DOM element from which the text will be scraped.
    source = $('#tab_cm')[0];

    // we support special element handlers. Register them with jQuery-style 
    // ID selector for either ID or node name. ("#iAmID", "div", "span" 
    etc.)
    // There is no support for any other type of selectors 
    // (class, of compound) at this time.
    specialElementHandlers = {
        // element with id of "bypass" - jQuery style selector
        '#bypassme': function (element, renderer) {
            // true = "handled elsewhere, bypass text extraction"
            return true
        }
    };
    margins = {
        top: 30,
        bottom: 60,
        left: 30,
        width: 500
    };
    // all coords and widths are in jsPDF instance's declared units
    // 'inches' in this case
    pdf.fromHTML(
        source, // 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
        },

        function (dispose) {
            // dispose: object with X, Y of the last line add to the PDF 
            //          this allow the insertion of new lines after html
            pdf.save(pdfName);
        }, margins
    );
}
</script>

My Div section looks like this: https://drive.google.com/file/d/0B2mHDe7wmRSfU2Q0UjM4QV9Sc2c/view?usp=sharing

But it looks like this once exported https://drive.google.com/file/d/0B2mHDe7wmRSfMndIVGZUQ2FHLW8/view?usp=sharing

As you can see I don't know how to properly align those texts inside the table of my exported PDF.

Thank you in advance for your help!


Solution

  • jspdf don't support css, so it can be hard to get the right format. You can make an image of your html, and then add it to pdf. See this answer: https://stackoverflow.com/a/43064789/7751910