HTML to PDF with Node.js

前端 未结 12 1862
终归单人心
终归单人心 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:57

    In my view, the best way to do this is via an API so that you do not add a large and complex dependency into your app that runs unmanaged code, that needs to be frequently updated.

    Here is a simple way to do this, which is free for 800 requests/month:

    var CloudmersiveConvertApiClient = require('cloudmersive-convert-api-client');
    var defaultClient = CloudmersiveConvertApiClient.ApiClient.instance;
    
    // Configure API key authorization: Apikey
    var Apikey = defaultClient.authentications['Apikey'];
    Apikey.apiKey = 'YOUR API KEY';
    
    
    
    var apiInstance = new CloudmersiveConvertApiClient.ConvertWebApi();
    
    var input = new CloudmersiveConvertApiClient.HtmlToPdfRequest(); // HtmlToPdfRequest | HTML to PDF request parameters
    input.Html = "<b>Hello, world!</b>";
    
    
    var callback = function(error, data, response) {
      if (error) {
        console.error(error);
      } else {
        console.log('API called successfully. Returned data: ' + data);
      }
    };
    apiInstance.convertWebHtmlToPdf(input, callback);
    

    With the above approach you can also install the API on-premises or on your own infrastructure if you prefer.

    0 讨论(0)
  • 2020-11-27 10:01

    Package

    I used html-pdf

    Easy to use and allows not only to save pdf as file, but also pipe pdf content to a WriteStream (so I could stream it directly to Google Storage to save there my reports).

    Using css + images

    It takes css into account. The only problem I faced - it ignored my images. The solution I found was to replace url in src attrribute value by base64, e.g.

    <img src="data:image/png;base64,iVBOR...kSuQmCC">

    You can do it with your code or to use one of online converters, e.g. https://www.base64-image.de/

    Compile valid html code from html fragment + css

    1. I had to get a fragment of my html document (I just appiled .html() method on jQuery selector).
    2. Then I've read the content of the relevant css file.

    Using this two values (stored in variables html and css accordingly) I've compiled a valid html code using Template string

    var htmlContent = `
    <!DOCTYPE html>
    <html>
      <head>
        <style>
          ${css}
        </style>
      </head>
      <body id=direct-sellers-bill>
        ${html}
      </body>
    </html>`
    

    and passed it to create method of html-pdf.

    0 讨论(0)
  • 2020-11-27 10:04

    Try to use Puppeteer to create PDF from HTML

    Example from here https://github.com/chuongtrh/html_to_pdf

    Or https://github.com/GoogleChrome/puppeteer

    0 讨论(0)
  • 2020-11-27 10:04

    You can also use pdf node creator package

    Package URL - https://www.npmjs.com/package/pdf-creator-node

    0 讨论(0)
  • 2020-11-27 10:05

    Extending upon Mustafa's answer.

    A) Install http://phantomjs.org/ and then

    B) install the phantom node module https://github.com/amir20/phantomjs-node

    C) Here is an example of rendering a pdf

    var phantom = require('phantom');   
    
    phantom.create().then(function(ph) {
        ph.createPage().then(function(page) {
            page.open("http://www.google.com").then(function(status) {
                page.render('google.pdf').then(function() {
                    console.log('Page Rendered');
                    ph.exit();
                });
            });
        });
    });
    

    Output of the PDF:

    EDIT: Silent printing that PDF

    java -jar pdfbox-app-2.0.2.jar PrintPDF -silentPrint C:\print_mypdf.pdf

    0 讨论(0)
  • 2020-11-27 10:05

    For those who don't want to install PhantomJS along with an instance of Chrome/Firefox on their server - or because the PhantomJS project is currently suspended, here's an alternative.

    You can externalize the conversions to APIs to do the job. Many exists and varies but what you'll get is a reliable service with up-to-date features (I'm thinking CSS3, Web fonts, SVG, Canvas compatible).

    For instance, with PDFShift (disclaimer, I'm the founder), you can do this simply by using the request package:

    const request = require('request')
    request.post(
        'https://api.pdfshift.io/v2/convert/',
        {
            'auth': {'user': 'your_api_key'},
            'json': {'source': 'https://www.google.com'},
            'encoding': null
        },
        (error, response, body) => {
            if (response === undefined) {
                return reject({'message': 'Invalid response from the server.', 'code': 0, 'response': response})
            }
            if (response.statusCode == 200) {
                // Do what you want with `body`, that contains the binary PDF
                // Like returning it to the client - or saving it as a file locally or on AWS S3
                return True
            }
    
            // Handle any errors that might have occured
        }
    );
    
    0 讨论(0)
提交回复
热议问题