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

后端 未结 2 1163
清酒与你
清酒与你 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.

    0 讨论(0)
  • 2020-12-05 14:45

    Firefox has an API method for that: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/saveAsPDF

    browser.tabs.saveAsPDF({})
      .then((status) => {
        console.log('PDF file status: ' + status);
      });
    

    However, it seems to be available only for Browser Extensions, not to be invoked from a web page.

    I'm still looking for a public API for that...

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