Code Monkey home page Code Monkey logo

electron-pdf's Introduction

Electron-PDF

NPM version Build status Downloads js-standard-style

Electron-PDF is a powerful command-line tool that leverages Electron to generate PDF files from URLs, HTML, or Markdown files.

Table of Contents

Version Compatibility

Starting from version 4.0.x, the master branch of Electron-PDF will always align with the latest Electron version.

Semantic Versioning is followed, and the version numbers correspond to Electron versions as follows:

  • electron-pdf 25.0.x (master) => electron=25.4.0, node=16.15.0, chrome=114.0.5735.248
  • electron-pdf 20.0.x => electron=20.0.2, node=16.15.0, chrome=104.0.5112.81
  • electron-pdf 15.0.x => electron=15.1.1, node=16.5.0, chrome=94.0.4606.61
  • electron-pdf 10.0.x => electron=10.1.3, node=12.16.3, chrome=85.0.4183.121
  • electron-pdf 7.0.x => electron 7.x (Chromium 78, Node 12.8.1)
  • electron-pdf 4.0.x => electron 4.x (Chromium 69, Node 10.11.0)
  • electron-pdf 1.3.x => electron 1.6.x (Chromium 56, Node 7.4)
  • electron-pdf 1.2.x => electron 1.4.x (Chromium 53, Node 6.5)

Please note that the choice of Chromium version affects the functionality you can utilize. Choose the version that aligns with your needs.

Installation

Install Electron-PDF via npm:

npm install electron-pdf

If you're installing as root using system-level npm (rather than a user-level install like with NVM), use the following command:

sudo npm install electron-pdf -g --unsafe-perm

Please see the npm docs for more information.

For GNU/Linux installations without a graphical environment, you need to install xvfb and set up a virtual display:

sudo apt-get install xvfb # or equivalent
export DISPLAY=':99.0'
Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &
electron-pdf ...

A Docker machine example is available here.

Node.js Usage

Electron-PDF can be integrated into your application or used as a rendering engine for a PDF service. Below are examples of usage.

Application Setup

In your package.json:

"scripts": {
  "start": "DEBUG=electronpdf:* electron index.js",
  "watch": "DEBUG=electronpdf:* nodemon --exec electron index.js"
}

Using Electron-PDF

const ElectronPDF = require('electron-pdf')
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.json())

const exporter = new ElectronPDF()
exporter.on('charged', () => {
  app.listen(port, hostname, () => {
    console.log(`Export Server running at http://${hostname}:${port}`)
  })
})
exporter.start()

Handling Multiple Export Jobs

app.post('/pdfexport', (req, res) => {
  const jobOptions = {
  /*
    r.results[] will contain the following based on inMemory
    false: the fully qualified path to a PDF file on disk
    true: The Buffer Object as returned by Electron
    Note: the default is false, this can not be set using the CLI
  */
    inMemory: false // Set inMemory to true for Buffer export
  }
  const options = {
    pageSize: "A4"
  }
  
  exporter.createJob(source, target, options, jobOptions).then(job => {
    job.on('job-complete', r => {
      console.log('pdf files:', r.results)
      // Process the PDF file(s) here
    })
    job.render()
  })
})

Using In-Memory Buffer

If you set the inMemory setting to true, you must also set closeWindow=false or you will get a segmentation fault anytime the window is closed before the buffer is sent on the response. You then need to invoke job.destroy to close the window.

const jobOptions = { inMemory: true, closeWindow: false }
exporter.createJob(source, target, options, jobOptions).then(job => {
  job.on('job-complete', r => {
    // Send the Buffer here
    process.nextTick(() => { job.destroy() })
  })
})

Events

Electron-PDF emits events to provide insights into its operations. A full documentation of events is a work in progress.

Environment Variables

  • ELECTRONPDF_RENDERER_MAX_MEMORY: Specify the --max-old-space-size option for each Electron renderer process (browser window) default: 75% of total system memory up to 8GB
  • ELECTRONPDF_WINDOW_CLEANUP_INTERVAL: Interval to check for hung windows, in milliseconds default: 30 seconds
  • ELECTRONPDF_WINDOW_LIFE_THRESHOLD: How long a window can remain open before it is terminated, in milliseconds default: 5 minutes
  • ELECTRONPDF_PNG_CAPTURE_DELAY: Delay before invoking WebContents.capturePage for PNG exports default: 100ms

Command Line Usage

Electron-PDF provides a versatile command-line interface (CLI) for various conversions and exports.

Generate a PDF from an HTML file

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

Generate a PDF from a Markdown file

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

Generate a PDF from a Markdown file with custom CSS

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

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

In your application, at the point which the view is ready for rendering

document.body.dispatchEvent(new Event('view-ready'))

Warning: It is possible that your application will be ready and emit the event before the main electron process has had a chance execute the javascript in the renderer process which listens for this event.

If you are finding that the event is not effective and your page waits until the full timeout has occurred, then you should use setInterval to emit the event until it is acknowledged like so:

  var eventEmitInterval = setInterval(function () {
    document.body.dispatchEvent(new Event('view-ready'))
  }, 25)

  document.body.addEventListener('view-ready-acknowledged', function(){
    clearInterval(eventEmitInterval)
  })

When the main process first receives your ready event it will emit a single acknowlegement on document.body with whatever event name you are using suffixed with -acknowledged. So the default would be view-ready-acknowledged

Observing your own event

If the page you are rending is under your control, and you wish to modify the behavior of the rendering process you can use a CustomEvent and an observer that will be triggered after the view is ready but before it is captured.

your-page.html
document.body.dispatchEvent(new CustomEvent('view-ready', { detail: {layout: landscape} }))
your-exporter.js

You are required to provide a function that accepts the detail object from the CustomEvent and returns a Promise. You may optionally fulfill the promise with and object that will amend/override any of the contextual attributes assigned to resource (url) currently being exported.

As an example, suppose you wanted to change the orientation of the PDF, and capture the output as PNG instead of a PDF.

job.observeReadyEvent( (detail) => {
    return new Promise( (resolve,reject) => {
      const context = {}
      if( detail && detail.landscape ){
        job.changeArgValue('landscape', true)
        context.type = 'png'
      }
      resolve(context)
    })
})

Note: Future versions of the library will only allow you to provide context overrides, and not allow you to change job level attributes.

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        Boolean - 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: <headerName>: <headerValue>
                                 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 <input> <output> -l

  Usage
    $ electron-pdf <input> <output>
    $ electron-pdf <input> <output> -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.

License

MIT

electron-pdf's People

Contributors

adstage-david avatar alexgoldstone avatar amrtn avatar aroldogoulart avatar bruceczk avatar chentsulin avatar chesles avatar codecounselor avatar danieldiekmeier avatar dependabot[bot] avatar fraserxu avatar gerbus avatar greenkeeperio-bot avatar hartman avatar henryqdineen avatar icidasset avatar jeroencoumans avatar jerryorr avatar jstumpp avatar l3o avatar marco-sulla avatar maxdow avatar nosnickid avatar reggino avatar riezebosch avatar rmoriz avatar rriclet avatar snowrunescape avatar sterlinghirsh avatar trevordowdle avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

electron-pdf's Issues

"failed to get a service for display 3" on MacOS X, while running electron-pdf

I am running the following:

node_modules/.bin/electron-pdf ./document.html ./out.pdf

on doing so I get:

/Library/Caches/com.apple.xbs/Sources/AppleGVA/AppleGVA-10.0.41/Sources/Slices/Driver/AVD_loader.cpp: failed to get a service for display 3 
/Library/Caches/com.apple.xbs/Sources/AppleGVA/AppleGVA-10.0.41/Sources/Slices/Driver/AVD_loader.cpp: failed to get a service for display 4 
/Library/Caches/com.apple.xbs/Sources/AppleGVA/AppleGVA-10.0.41/Sources/Slices/Driver/AVD_loader.cpp: failed to get a service for display 5 
/Library/Caches/com.apple.xbs/Sources/AppleGVA/AppleGVA-10.0.41/Sources/Slices/Driver/AVD_loader.cpp: failed to get a service for display 6 

Any ideas?

Running on MacOS X 10.12, with Node 6.7.0 and electron-pdf 0.13.0

CustomEvent observer for render event (waitForJSEvent)

Some applications may contain certain display logic that results in the page layout changing from an primary layout (i.e. portrait) to a secondary one (i.e. landscape).

Electron PDF should support this by allowing clients to register an observer for the CustomEvent.detail object when listening to the IPC channel from the browser.

The observer will be invoked before the page is captured

The API must also contain a new function to allow arguments set during construction to be updated with new values.

Not working on Linux/Ubuntu 16.04

I have installed electron-pdf via npm as specified in the README file. But when I run electron-pdf --help I get this error:

`internal/child_process.js:298
throw errnoException(err, 'spawn');
^

Error: spawn EACCES
at exports._errnoException (util.js:870:11)
at ChildProcess.spawn (internal/child_process.js:298:11)
at exports.spawn (child_process.js:362:9)
at Object. (/usr/local/lib/node_modules/electron-pdf/cli.js:10:16)
at Module._compile (module.js:410:26)
at Object.Module._extensions..js (module.js:417:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:442:10)
at startup (node.js:136:18)
`

remove all console.log in favor of debug and emitters

  1. Implement debug with a electronpdf: (info-error) and electronpdf:debug prefixes so that clients can enable logging as needed.
  2. For noteworthy events, add more even emitters that provide contextual information (i.e. timings) so clients can implement monitoring hooks

Cannot read property 'once' of undefined

When start the project by express.

/Users/lxxyx/Desktop/own/yun-type/node_modules/electron-pdf/lib/index.js:32
electronApp.once('ready', () => {
^

TypeError: Cannot read property 'once' of undefined
at PDFExporter.start (/Users/lxxyx/Desktop/own/yun-type/node_modules/electron-pdf/lib/index.js:32:16)
at Object. (/Users/lxxyx/Desktop/own/yun-type/js_server/app.js:22:10)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3

import * as express from 'express'
import * as bodyParser from 'body-parser'
const ElectronPDF = require('electron-pdf')

const app = express()
app.use(bodyParser.json())

const exporter = new ElectronPDF()

app.post('/pdfexport', (req, res) => {
    const source:string = req.body.source
    exporter.createJob(source, './')
    .then((job) => {
        job.render()
        job.on('job-complete', (r) => {
            console.log('pdf files:', r.results)
        })
    })
})

exporter.on('charged', () => {
    //Only start the express server once the exporter is ready
    app.listen(3000)
})

exporter.start()

How can I set the exact margins?

It seems that I can only determine the margin type (0, 1 or 2)
But in chrome it is OK to set them, and I want to have control on them (such as margin-left, margin-right, margin-top and margin-bottom).

basic auth

Wow, electron-pdf has evolved greatly. I'm using basic auth on my server and would like to have the option to pass a username and password to electron-pdf. I could do http://user:[email protected] but a paramter looks cleaner.

Running generation just waits

I’m trying to create PDF from simple text file but when I run electron-pdf, my terminal process just waits and I can only exit it with Ctrl+C.

I’m not using global installation, but running it with npm script which access’ local installation of electron-pdf.

Is this a known issue?

How to use electron-pdf (CLI) with Apache + php 7.1

Hi,
I've created an application in cakephp and I need to make pdfs of certain pages.
My question is, how can I implement electron-pdf using functions like shell_exec() in php, for example I tried to do shell_exec("electron-pdf http://www.google.cl google.pdf") but it returns nothing (neither errors or success messages) :c

Somebody can help me?

Error everytime I run electron-pdf

I get ths error everytime I run electron-pdf :

App threw an error when running [TypeError: Cannot read property 'on' of undefined]
A JavaScript error occurred in the main process
Uncaught Exception:
TypeError: Cannot read property 'on' of undefined
    at Object.<anonymous> (/usr/lib/node_modules/electron-pdf/index.js:27:4)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Object.<anonymous> (/usr/lib/node_modules/electron-pdf/node_modules/electron-prebuilt/dist/resources/default_app/main.js:252:23)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)

Even when running electron-pdf without any paramters, I get this error (but I get the manual printed in the console fine after that).
When trying to convert a html file, I get only this error and no output file is written.

Nothing critical for me, I just thought I should report this.

Print css is not working

adding css in html
<link rel="stylesheet" type="text/css" href="test.css" media="print">

Here is css file content

@page {
   size: 8.5in 11in;    
   margin: 70pt 60pt 70pt;
}

When run electron-pdf http://localhost/test.html test.pdf, print css is not getting applied

Support In Memory Output

Allow an option to be set on the job that does not write PDF files to the filesystem but returns the buffer object instead

Support exports to PowerPoint (Experimental)

Requirements

When the output file has a .ppt or .pptx extension

  • First render the url as a pdf and capture an image of each page.
    • Sending to PDF honors CSS page breaks, and automatically breaks tables and includes the table headers on each subsequent page. This is more straight forward than trying to manipulate the view and capture images.
  • Scale the image to fit on the slide, maintain the aspect ratio
  • If multiple input URLs are passed, append them to the presentation in the order they were passed
  • If a URL results in multiple pages in the PDF document, insert one page per slide.
  • Return the powerpoint document location or buffer, then delete all intermediate (pdf,png) files

Risks

Options for PDF to PNG conversion

  1. Load PDF inside of Electron browser window and capture images
  2. Do it with node libraries that rely on *nix packages

Blank Output

I started using electron-pdf on version 0.6. It never worked for be because of issue #11.

Now that I can get it to start the output of my pdfs are blank. I tried my own project and google.com. All i get is a single page white PDF

Support multiple URLs at once

  • If electron-pdf is used as a node module allow the input type to be an array or URLs in addition to a single URL.
  • The urls should be loaded in the same browser window to take advantage of caching
  • Response Format
    • The callback object should be an array of file locations on the local filesystem.
    • The caller is responsible for cleaning up any generated files
    • Optionally, investigate supporting in memory buffers or streams

Column CSS support

When printing a page with a div that is rendered as columns using CSS, the resulting PDF file does not render the columns. However, opening the html file in Chrome, it renders the columns and using the print dialogue to print to PDF also retains the columns. Is there an option for electron-pdf that I'm missing or any recommendations to handle this? Examples can be provided if needed.

As a side note, I appreciate that it does render CSS page-break-before/after/inside nicely. Thanks for your great writeup in your blog post as well as releasing this tool!

CSS option

As far as I can tell the CSS option is ignored. When set it gets added to the opts Object https://github.com/fraserxu/electron-pdf/blob/master/index.js#L70 which then later on is passed to win.printToPDF https://github.com/fraserxu/electron-pdf/blob/master/index.js#L108. webContents.printToPDF does not support the css option though. What it does support is webContents.insertCSS(css) https://github.com/atom/electron/blob/master/docs/api/web-contents.md#webcontentsinsertcsscss which should be used instead

Issues using pageSize

Trying to print out at a specific size and am struggling.

electron-pdf http://localhost:8000/index.html ~/Desktop/document.pdf --printBackground --marginType 1 --landscape --pageSize '{width: 800, height: 600}'

Which returns the error:

Error: Does not support pageSize with {width: 800, height: 600}
    at EventEmitter.webContents.printToPDF (/usr/local/lib/node_modules/electron-prebuilt/dist/Electron.app/Contents/Resources/electron.asar/browser/api/web-contents.js:218:25)
    at EventEmitter.<anonymous> (/usr/local/lib/node_modules/electron-pdf/index.js:90:21)
    at emitOne (events.js:96:13)
    at EventEmitter.emit (events.js:188:7)

Can you share an example of how I should be formatting the width and height?

Send raw html instead of url or path

Hi,

is it possible to send html data as a source instead of an url ?

To do something like this :

app.post('/pdfexport', function(req,res){
     //in memory mode
    exporter.createJob(req.body, target, options, jobOptions).then( job => {
      // 
    })  
})

Electron capturePage needs a delay or capturePage Images may not have all content

The problem is that when capturePage is used to export a PNG image, the contents of the page have been found to be partially missing in some cases.

Someone made an attempt to add a view-painted event to webContents in place of a timeout but it proved not to work and it was removed.
The history is captured here: electron/electron#6622

This task is to add a small 100ms timeout before invoking capturePage when a PNG is being exported.

If a client is using the waitForJSEvent option they can also insert a timeout before emitting the ready event.

Allow the delay to be overridden with a ELECTRONPDF_PNG_CAPTURE_DELAY env property

Double output on --help

I started using electron-pdf on version 0.6. It never worked for be because of issue #11 . Now that that is fixed I have noticed the --help output is doubled.

~/P/cv ❯❯❯ electron-pdf --help
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
  -c | --css                 String - The path to custom CSS
  -b | --printBackground     Boolean - Whether to print CSS backgrounds.
                               false - true
  -s | --printSelectionOnly  Boolean - Whether to print selection only
                               false - default
  -l | --landscape           Boolean - true for landscape, false for portrait.
                               false - default
  -m | --marginType          Integer - Specify the type of margins to use
                               0 - default
                               1 - none
                               2 - minimum

Usage
  $ electron-pdf <input> <output>
  $ electron-pdf <input> <output> -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
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
  -c | --css                 String - The path to custom CSS
  -b | --printBackground     Boolean - Whether to print CSS backgrounds.
                               false - true
  -s | --printSelectionOnly  Boolean - Whether to print selection only
                               false - default
  -l | --landscape           Boolean - true for landscape, false for portrait.
                               false - default
  -m | --marginType          Integer - Specify the type of margins to use
                               0 - default
                               1 - none
                               2 - minimum

Usage
  $ electron-pdf <input> <output>
  $ electron-pdf <input> <output> -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

`.1` is always appended in the output path

Thanks for the great app! ✨

I have a problem: the output path becomes <specified-path>.1. For instance:

electron-pdf path/to/RESULTS.md pdfs/results.pdf -c pdfs/assets/gh-markdown.css

Generates pdfs/results.pdf.1, but it actually contains the Markdown code, not the interpreted MD code.

Any ideas? Looks like a bug.

no concurrency support when using session cookies

Need to create a new (in-memory) session for every window that is created, otherwise concurrent requests will use the cookies applied to the single session created by the main process.

    // This creates a new session for every browser window, otherwise the same
    // default session is used from the main process which would break support
    // for concurrency
    // see http://electron.atom.io/docs/api/browser-window/#new-browserwindowoptions options.partition
    if( args.cookies ){
      defaultOpts.webPreferences.partition = uuid()
    }

trap download events for non HTML content (e.g. PDF, Word, Powerpoint, etc.)

Currently it fails if the electron app detects it cannot handle the mimetype of the given URL.
A fix is to listen for the 'will-download' event and cancel it instead of prompting the user (which we can't in a headless environment):

win.webContents.session.on('will-download', (event, item, webContents) => {
event.preventDefault();
console.error('will-download',item.getMimeType());
app.quit();
});

Error running command line example

Following the README.md file, I run electron-pdf https://fraserxu.me ~/Desktop/fraserxu.pdf and I got the error showing below:

fs.js:549
  return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
                 ^

Error: ENOENT: no such file or directory, open '/usr/local/lib/node_modules/electron-pdf/node_modules/electron/path.txt'
    at Error (native)
    at Object.fs.openSync (fs.js:549:18)
    at Object.fs.readFileSync (fs.js:397:15)
    at Object.<anonymous> (/usr/local/lib/node_modules/electron-pdf/node_modules/electron/index.js:4:42)
    at Module._compile (module.js:410:26)
    at Object.Module._extensions..js (module.js:417:10)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Module.require (module.js:354:17)
    at require (internal/module.js:12:17)

Improve Memory Management

Things can go wrong and jobs can terminate abruptly. If the caller does not get a reference to the job back or does not invoke job.destroy() windows can remain open indefinitely. This results in memory leaks as the process continues to run.

Windows that remain open beyond a specified threshold should be automatically terminated. Subsequently, the owning job should also be freed up for garbage collection.

There should be a new event that clients can observe when this happens

Not working for Ubuntu

Using Ubuntu non-GUI.

electron-pdf template.html template2.pdf
/var/br-nodeapps/pdf-to-html/node_modules/electron-pdf/node_modules/electron-prebuilt/dist/electron: error while loading shared libraries: libnss3.so: cannot open shared object file: No such file or directory

I installed like directed in the instructions with all the xvfb, etc.

Add printDelay

I was having a requirement to add printDelay as many charts are involved in my url which takes time to load.

Add support for cookies

I am using electron-pdf for an application that requires authentication. Its a Java web application that is using cookies (i.e. JSESSIONID). Electron allows you to set cookies on the Browser Window session like so:

win.webContents.session.cookies.set(cookie, function(err){
    if(err){
      console.log(err)
    }
  })

I am currently thinking about a couple of different options:

  1. Add an option to allow headers - this would allow any caller to set not just the cookie but any other header they wish to be applied. Could be more generally useful, and support other authentication mechanisms like JWT.
  2. Add an option that allows a list of cookies, each cookie needs:
    • url - could be derived from the hostname if not provided
    • name - required
    • value - required

I will likely work on a PR for option 2 first

Wait for AJAX calls to complete

Was wondering how you can set things up to wait for AJAX calls on the page to complete, so that all content has been properly loaded prior to printing?

TypeError: Incorrect value for stdio stream: inherit

binggg@BINGGG-PC ~
$ electron-pdf --help

child_process.js:901
      throw new TypeError('Incorrect value for stdio stream: ' + stdio);
            ^
TypeError: Incorrect value for stdio stream: inherit
    at child_process.js:901:13
    at Array.reduce (native)
    at ChildProcess.spawn (child_process.js:856:17)
    at exports.spawn (child_process.js:715:9)
    at runElectron (c:\Users\binggg\AppData\Roaming\npm\node_modules\electron-pdf\cli.js:24:18)
    at c:\Users\binggg\AppData\Roaming\npm\node_modules\electron-pdf\cli.js:17:28
    at c:\Users\binggg\AppData\Roaming\npm\node_modules\electron-pdf\node_modules\which\which.js:81:18
    at Object.oncomplete (fs.js:107:15)

Add electron as a dependency?

Currently you have to install electron separately if you want to use this package, I'm thinking to add electron as dependency so that user don't have to install it by himself.

The only concern is that the file size of the module will increase dramatically.

Margins not working correctly on markdown files

I'm trying to convert this markdown file test.md to pdf:

# CHAOS Manifesto 2013

**CHAOS Manifesto 2013: Think Big, Act Small** es un subconjunto de la versión
online de CHAOS Chronicles, conocido como el CHAOS Knowledge Center (CKC). Esta
version del **CHAOS Manifesto** se enfoca en proyectos pequeños y esta basado en
CKC versión 40-12. Este reporte esta compuesto de 12 secciones principales. Las
secciones 2 a 11 cubren los factores del éxito CHAOS para proyectos pequeños.
Esta investigación se ha realizado recogiendo datos de ambientes tecnológicos y
proyectos de desarrolle de software reales desde 1985. La investigación cubre 18
años de datos sobre porque los proyectos alcanzan el éxito o el fracaso.

## Los factores del éxito

El informe recopila 10 factores más comunes para el éxito de un proyecto y les 
asigna un puntaje de acuerdo a su porcentaje de frecuencia. 

| Factores del éxito | Puntaje |
|---|---|
| Soporte de administración ejecutiva  | 20 |
| Participación del usuario | 15 |
| Optimización | 15 |
| Recursos hábiles | 13 |
| Experiencia en administración de proyectos | 12 |
| Proceso ágil | 10 |
| Objetivos de negocio claros | 6 |
| Madurez emocional | 5 |
| Ejecución | 3 |
| Herramientas e infraestructura | 1 |

El principal factor aquí es el **auspiciante ejecutivo**. Este es el mayor
responsable del éxito o fracaso del proyecto. En segundo lugar esta la
**participación del usuario**. Los datos muestran claramente que los proyectos que
no involucran al usuario se desempeñan muy mal. La **optimización** ocupa el tercer
puesto, lo cual nos indica que un proyecto con pequeña carga laboral y entrega
rápida es mucho menos propensa a fracasar. Cabe recalcar que estos tres factores
tiene el 50% de los puntos totales.

Los factores menos importantes son la madurez, ejecución y herramientas e
infraestructura. Las herramientas ayudan, pero las organizaciones deben de
procurar no depender mucho de estas para poder alcanzar el éxito. Los controles
y procedimientos financieros son parte de la ejecución y tampoco son tan
importantes. La madurez tiene que ver con el ecosistema. Si el ecosistema es
saludable, rinde proyectos con mejor desempeño.

Los factores con puntajes intermedio son:

- **Recursos hábiles:** El éxito del proyecto depende principalmente de los
  integrantes del equipo. Si ellos son muy hábiles en sus roles, es mucho
  más probable que el proyecto salga bien. Esto es mucho más significativo en
  proyectos pequeños con pocos miembros.

- **Experiencia en administración de proyectos:** La experiencia en
  administración es esencial para controlar el progreso de pequeños proyectos y
  la colaboración de los interesados y los miembros del equipo. 

- **Metodologías ágiles:** Estas metodologías se enfocan más en la 
  participación del usuario, soporte ejecutivo y otros factores de éxito. 
  Brinda un control más estricto y ordenado del progreso de proyecto.Divide el
  proyecto en pequeñas tareas que deben de ser validadas por el usuario para
  poder continuar con la siguiente.

- **Objetivos de negocio claros:** Esto no es tan importante en proyectos
  pequeños como en los grandes. Sin embargo, el proyecto pequeño también tiene
  que tener en mente un objetivo de negocio, aunque sea menos evidente. Todas
  las estrategias empleadas deben de reflejar este objetivo.

End of Document

The command I use is:

electron-pdf test.md test.pdf

In the output file, the top margin of the first page is correct:

screenshot from 2016-12-10 14-35-27

However, the bottom margin of the first page and the top margin of the second page are not. The page breaks abruptly.

screenshot from 2016-12-10 14-38-42

Are there any command line arguments that can fix this?

throws error

I've just installed and probably I'm doing it wrong:

~ electron-pdf http://localhost:9393/some/doc test.pdf
App threw an error when running [SyntaxError: Unexpected token =]
A JavaScript error occurred in the main process
Uncaught Exception:
SyntaxError: Unexpected token =
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:413:25)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/home/me/.nvm/versions/node/v4.2.1/lib/node_modules/electron-pdf/index.js:7:13)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)

Any idea what's going on here?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.