HTML to PDF with Node.js

前端 未结 12 1891
终归单人心
终归单人心 2020-11-27 09:20

I\'m looking to create a printable pdf version of my website webpages. Something like express.render() only render the page as pdf

12条回答
  •  抹茶落季
    2020-11-27 09:44

    Create PDF from External URL

    Here's an adaptation of the previous answers which utilizes html-pdf, but also combines it with requestify so it works with an external URL:

    Install your dependencies

    npm i -S html-pdf requestify
    

    Then, create the script:

    //MakePDF.js
    
    var pdf = require('html-pdf');
    var requestify = require('requestify');
    var externalURL= 'http://www.google.com';
    
    requestify.get(externalURL).then(function (response) {
       // Get the raw HTML response body
       var html = response.body; 
       var config = {format: 'A4'}; // or format: 'letter' - see https://github.com/marcbachmann/node-html-pdf#options
    
    // Create the PDF
       pdf.create(html, config).toFile('pathtooutput/generated.pdf', function (err, res) {
          if (err) return console.log(err);
          console.log(res); // { filename: '/pathtooutput/generated.pdf' }
       });
    });
    

    Then you just run from the command line:

    node MakePDF.js
    

    Watch your beautify pixel perfect PDF be created for you (for free!)

提交回复
热议问题