Generate pdf from HTML in div using Javascript

前端 未结 12 982
你的背包
你的背包 2020-11-22 06:10

I have the following html code:



    
        

don\'t print th

相关标签:
12条回答
  • 2020-11-22 06:40

    This is the simple solution. This works for me.You can use the javascript print concept and simple save this as pdf.

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script type="text/javascript">
            $("#btnPrint").live("click", function () {
                var divContents = $("#dvContainer").html();
                var printWindow = window.open('', '', 'height=400,width=800');
                printWindow.document.write('<html><head><title>DIV Contents</title>');
                printWindow.document.write('</head><body >');
                printWindow.document.write(divContents);
                printWindow.document.write('</body></html>');
                printWindow.document.close();
                printWindow.print();
            });
        </script>
    </head>
    <body>
        <form id="form1">
        <div id="dvContainer">
            This content needs to be printed.
        </div>
        <input type="button" value="Print Div Contents" id="btnPrint" />
        </form>
    </body>
    </html>
    
    0 讨论(0)
  • 2020-11-22 06:43

    You can use autoPrint() and set output to 'dataurlnewwindow' like this:

    function printPDF() {
        var printDoc = new jsPDF();
        printDoc.fromHTML($('#pdf').get(0), 10, 10, {'width': 180});
        printDoc.autoPrint();
        printDoc.output("dataurlnewwindow"); // this opens a new popup,  after this the PDF opens the print window view but there are browser inconsistencies with how this is handled
    }
    
    0 讨论(0)
  • 2020-11-22 06:44

    i use jspdf and html2canvas for css rendering and i export content of specific div as this is my code

    $(document).ready(function () {
        let btn=$('#c-oreder-preview');
        btn.text('download');
        btn.on('click',()=> {
    
            $('#c-invoice').modal('show');
            setTimeout(function () {
                html2canvas(document.querySelector("#c-print")).then(canvas => {
                    //$("#previewBeforeDownload").html(canvas);
                    var imgData = canvas.toDataURL("image/jpeg",1);
                    var pdf = new jsPDF("p", "mm", "a4");
                    var pageWidth = pdf.internal.pageSize.getWidth();
                    var pageHeight = pdf.internal.pageSize.getHeight();
                    var imageWidth = canvas.width;
                    var imageHeight = canvas.height;
    
                    var ratio = imageWidth/imageHeight >= pageWidth/pageHeight ? pageWidth/imageWidth : pageHeight/imageHeight;
                    //pdf = new jsPDF(this.state.orientation, undefined, format);
                    pdf.addImage(imgData, 'JPEG', 0, 0, imageWidth * ratio, imageHeight * ratio);
                    pdf.save("invoice.pdf");
                    //$("#previewBeforeDownload").hide();
                    $('#c-invoice').modal('hide');
                });
            },500);
    
            });
    });
    
    0 讨论(0)
  • 2020-11-22 06:51

    if you need to downloadable pdf of a specific page just add button like this

    <h4 onclick="window.print();"> Print </h4>
    

    use window.print() to print your all page not just a div

    0 讨论(0)
  • 2020-11-22 06:51

    Use pdfMake.js and this Gist.

    (I found the Gist here along with a link to the package html-to-pdfmake, which I end up not using for now.)

    After npm install pdfmake and saving the Gist in htmlToPdf.js I use it like this:

    const pdfMakeX = require('pdfmake/build/pdfmake.js');
    const pdfFontsX = require('pdfmake-unicode/dist/pdfmake-unicode.js');
    pdfMakeX.vfs = pdfFontsX.pdfMake.vfs;
    import * as pdfMake from 'pdfmake/build/pdfmake';
    import htmlToPdf from './htmlToPdf.js';
    
    var docDef = htmlToPdf(`<b>Sample</b>`);
    pdfMake.createPdf({content:docDef}).download('sample.pdf');
    

    Remarks:

    • My use case is to create the relevant html from a markdown document (with markdown-it) and subsequently generating the pdf, and uploading its binary content (which I can get with pdfMake's getBuffer() function), all from the browser. The generated pdf turns out to be nicer for this kind of html than with other solutions I have tried.
    • I am dissatisfied with the results I got from jsPDF.fromHTML() suggested in the accepted answer, as that solution gets easily confused by special characters in my HTML that apparently are interpreted as a sort of markup and totally mess up the resulting PDF.
    • Using canvas based solutions (like the deprecated jsPDF.from_html() function, not to be confused with the one from the accepted answer) is not an option for me since I want the text in the generated PDF to be pasteable, whereas canvas based solutions generate bitmap based PDFs.
    • Direct markdown to pdf converters like md-to-pdf are server side only and would not work for me.
    • Using the printing functionality of the browser would not work for me as I do not want to display the generated PDF but upload its binary content.
    0 讨论(0)
  • 2020-11-22 06:51

    To capture div as PDF you can use https://grabz.it solution. It's got a JavaScript API which is easy and flexible and will allow you to capture the contents of a single HTML element such as a div or a span

    In order to implement it you will need to first get an app key and secret and download the (free) SDK.

    And now an example.

    Let's say you have the HTML:

    <div id="features">
        <h4>Acme Camera</h4>
        <label>Price</label>$399<br />
        <label>Rating</label>4.5 out of 5
    </div>
    <p>Cras ut velit sed purus porttitor aliquam. Nulla tristique magna ac libero tempor, ac vestibulum felisvulput ate. Nam ut velit eget
    risus porttitor tristique at ac diam. Sed nisi risus, rutrum a metus suscipit, euismod tristique nulla. Etiam venenatis rutrum risus at
    blandit. In hac habitasse platea dictumst. Suspendisse potenti. Phasellus eget vehicula felis.</p>
    

    To capture what is under the features id you will need to:

    //add the sdk
    <script type="text/javascript" src="grabzit.min.js"></script>
    <script type="text/javascript">
    //login with your key and secret. 
    GrabzIt("KEY", "SECRET").ConvertURL("http://www.example.com/my-page.html",
    {"target": "#features", "format": "pdf"}).Create();
    </script>
    

    Please note the target: #feature. #feature is you CSS selector, like in the previous example. Now, when the page is loaded an image screenshot will now be created in the same location as the script tag, which will contain all of the contents of the features div and nothing else.

    The are other configuration and customization you can do to the div-screenshot mechanism, please check them out here

    0 讨论(0)
提交回复
热议问题