Pages

Friday, 1 May 2020

electron-pdf

A command line tool to generate PDF from URL, HTML or Markdown files.

NPM version build status Downloads js-standard-style
A command line tool to generate PDF from URL, HTML or Markdown files with electron.
I have a blog post explain why PDF Generation On The Web
Production ready? See it in action for the Myanmar Election!

Install

npm install electron-pdf
Note: If you're installing electron-pdf as root using the system level npm (vs a user-level install like with NVM) then you may need to run the following command instead:
sudo npm install electron-pdf -g --unsafe-perm
Please see the npm docs for more information.
For gnu/linux installations without a graphical environment:
$ sudo apt-get install xvfb # or equivalent
$ export DISPLAY=':99.0'
$ Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &
$ electron-pdf ...
There is also an example docker machine here.

Node Usage

Electron PDF can be used inside of an application, or more commonly as the engine for a pdf rendering service. For instance, to handle http requests using Express. The following snippets show you how you can get started.

The application must run in an Electron process

In package.json
"start": "DEBUG=electronpdf:* electron index.js",
"watch": "DEBUG=electronpdf:* nodemon --exec electron index.js"

Command Line Usage

For Ad-hoc conversions, Electron PDF comes with support for a CLI.

To generate a PDF from a HTML file

$ electron-pdf index.html ~/Desktop/index.pdf

To generate a PDF from a Markdown file

$ electron-pdf index.md ~/Desktop/index.pdf

To generate a PDF from a Markdown file with custom CSS (defaults to Github markdown style)

$ electron-pdf index.html ~/Desktop/index.pdf -c my-awesome-css.css

To generate a PDF from a URL

$ electron-pdf https://fraserxu.me ~/Desktop/fraserxu.pdf

Rendering Options

Electron PDF gives you complete control of how the BrowserWindow should be configured, and when the window contents should be captured.

To specify browser options

The BrowserWindow supports many options which you may define by passing a JSON Object to the --browserConfig option.
Some common use cases may include:
  • height and width - electron-pdf calculates the browser height and width based off of the dimensions of PDF page size multiplied by the HTML standard of 96 pixels/inch. So only set these values if you need to override this behavior
  • show - to display the browser window during generation
$ electron-pdf https://fraserxu.me ~/Desktop/fraserxu.pdf --browserConfig '{"show":true}'

To generate a PDF after the an async task in the HTML

electron-pdf ./index.html ~/Desktop/README.pdf -e

All Available Options

Electron PDF exposes the printToPDF settings (i.e. pageSize, orientation, margins, etc.) available from the Electron API. See the following options for usage.

  A command line tool to generate PDF from URL, HTML or Markdown files

  Options
    --help                     Show this help
    --version                  Current version of package
    
    -i | --input               String - The path to the HTML file or url
    -o | --output              String - The path of the output PDF
    
    -b | --printBackground     Boolean - Whether to print CSS backgrounds.
    
    --acceptLanguage           String - A valid value for the 'Accept-Language' http request header
    
    --browserConfig            String - A valid JSON String that will be parsed into the options passed to electron.BrowserWindow
    
    -c | --css                 String - The path to custom CSS (can be specified more than once)
    
    -d | --disableCache        Disable HTTP caching
                                 false - default
    
    -e | --waitForJSEvent      String - The name of the event to wait before PDF creation
                                 'view-ready' - default
    
    -l | --landscape           Boolean - true for landscape, false for portrait (don't pass a string on the CLI, just the `-l` flag)
                                 false - default
    
    -m | --marginsType         Integer - Specify the type of margins to use
                                 0 - default margins
                                 1 - no margins (electron-pdf default setting)
                                 2 - minimum margins
    
    --noprint                  Boolean - Do not run printToPDF, useful if the page downloads a file that needs captured instead of a PDF.  
                                         The Electron `win.webContents.session.on('will-download')` event will be implemented 
                                         and the file saved to the location provided in `--output`.
                                         Currently only supports a single import url.
                                         The page is responsible for initiating the download itself.
    
    -p | --pageSize            String - Can be A3, A4, A5, Legal, Letter, Tabloid or an Object containing height and width in microns
                                 "A4" - default
    
    -r | --requestHeaders      String - A valid JSON String that will be parsed into an Object where each key/value pair is: : 
                                 Example: '{"Authorization": "Bearer token", "X-Custom-Header": "Hello World"}'  
    
    -s | --printSelectionOnly  Boolean - Whether to print selection only
                                 false - default
                                 
    -t | --trustRemoteContent  Boolean - Whether to trust remote content loaded in the Electron webview.  False by default.
    --type                     String - The type of export, will dictate the output file type.  'png': PNG image, anything else: PDF File
    
    -w | --outputWait          Integer – Time to wait (in MS) between page load and PDF creation.  
                                         If used in conjunction with -e this will override the default timeout of 10 seconds    
    --ignoreCertificateErrors  Boolean - If true, all certificate errors thrown by Electron will be ignored.  This can be used to accept self-signed and untrusted certificates.  You should be aware of the security implications of setting this flag.
                             false - default
Find more information on Electron Security here.

Debugging

Sentry

If you have a Sentry account and setup a new app to get a new DSN, you can set a SENTRY_DSN environment variable which will activate sentry logs. See lib/sentry.js for implementation details.
This will allow you to easily see/monitor errors that are occuring inside of the Chromium renderer (browser window). It also automatically integrates with Electron's Crash Reporter

CLI Usage

You can see some additional logging (if you're getting errors or unexpected output) by setting DEBUG=electron* For example: DEBUG=electron* electron-pdf -l
  Usage
    $ electron-pdf  
    $ electron-pdf   -l

  Examples
    $ electron-pdf http://fraserxu.me ~/Desktop/fraserxu.pdf
    $ electron-pdf ./index.html ~/Desktop/index.pdf
    $ electron-pdf ./README.md ~/Desktop/README.pdf -l
    $ electron-pdf ./README.md ~/Desktop/README.pdf -l -c my-awesome-css.css

Inspired by electron-mocha

Other Formats

Want to use the same options, but export to PNG or snapshot the rendered HTML? Just set the output filename to end in .png or .html instead!
  Examples
    $ electron-pdf http://fraserxu.me ~/Desktop/fraserxu.pdf
    $ electron-pdf http://fraserxu.me ~/Desktop/fraserxu.html
    $ electron-pdf http://fraserxu.me ~/Desktop/fraserxu.png

Extensions

If you need powerpoint support, pdf-powerpoint picks up where Electron PDF leaves off by converting each page in the PDF to a PNG and placing them on individual slides.

No comments:

Post a Comment