Generate pdf from HTML in div using Javascript

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

I have the following html code:



    
        

don\'t print th

12条回答
  •  深忆病人
    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(`Sample`);
    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.

提交回复
热议问题