How to use the browser's (chrome/firefox) HTML/CSS/JS rendering engine to produce PDF?

后端 未结 2 1189
清酒与你
清酒与你 2020-12-05 14:20

There are nice projects that generate pdf from html/css/js files

  1. http://wkhtmltopdf.org/ (open source)
  2. https://code.google.com/p/flying-saucer/ (open
2条回答
  •  广开言路
    2020-12-05 14:36

    I'm not an expert but PhamtomJS seems to be the right tool for the job. I'm not sure though about what headless browser it uses underneath (I guess it is chrome/chromium)

    var page = require('webpage').create();
    page.open('http://github.com/', function() {
         var s = page.evaluate(function() {
             var body = document.body,
                 html = document.documentElement;
    
            var height = Math.max( body.scrollHeight, body.offsetHeight, 
                html.clientHeight, html.scrollHeight, html.offsetHeight );
            var width = Math.max( body.scrollWidth, body.offsetWidth, 
                html.clientWidth, html.scrollWidth, html.offsetWidth );
            return {width: width, height: height}
        });
    
        console.log(JSON.stringify(s));
    
        // so it fit ins a single page
        page.paperSize = {
            width: "1980px",
            height: s.height + "px",
            margin: {
                top: '50px',
                left: '20px'
            }
        };
    
        page.render('github.pdf');
        phantom.exit();
    });
    

    Hope it helps.

提交回复
热议问题