{"id":13583314,"url":"https://github.com/fraserxu/electron-pdf","last_synced_at":"2025-05-15T03:07:49.185Z","repository":{"id":36737154,"uuid":"41043749","full_name":"fraserxu/electron-pdf","owner":"fraserxu","description":"📄 A command line tool to generate PDF from URL, HTML or Markdown files.","archived":false,"fork":false,"pushed_at":"2023-08-11T19:37:48.000Z","size":753,"stargazers_count":1242,"open_issues_count":61,"forks_count":137,"subscribers_count":26,"default_branch":"master","last_synced_at":"2025-04-14T03:09:02.778Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fraserxu.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2015-08-19T15:47:51.000Z","updated_at":"2025-04-05T10:58:26.000Z","dependencies_parsed_at":"2024-01-02T21:20:09.130Z","dependency_job_id":"c91e0c0b-ba66-4fc0-865e-f99a487eebe9","html_url":"https://github.com/fraserxu/electron-pdf","commit_stats":null,"previous_names":[],"tags_count":42,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fraserxu%2Felectron-pdf","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fraserxu%2Felectron-pdf/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fraserxu%2Felectron-pdf/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fraserxu%2Felectron-pdf/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fraserxu","download_url":"https://codeload.github.com/fraserxu/electron-pdf/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254254246,"owners_count":22039856,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-01T15:03:23.672Z","updated_at":"2025-05-15T03:07:44.176Z","avatar_url":"https://github.com/fraserxu.png","language":"JavaScript","funding_links":[],"categories":["JAVASCRIPT","JavaScript","四、快速构建应用的工具","Tools"],"sub_categories":["4. 网络与文件处理","Using Electron"],"readme":"## Electron-PDF\n\n[![NPM version][npm-image]][npm-url]\n[![Build status][travis-image]][travis-url]\n[![Downloads][downloads-image]][downloads-url]\n[![js-standard-style][standard-image]][standard-url]\n\nElectron-PDF is a powerful command-line tool that leverages [Electron](https://www.electronjs.org/) to generate PDF files from URLs, HTML, or Markdown files.\n\n## Table of Contents\n\n- [Electron-PDF](#electron-pdf)\n- [Version Compatibility](#version-compatibility)\n- [Installation](#installation)\n- [Node.js Usage](#nodejs-usage)\n  - [Application Setup](#application-setup)\n  - [Using Electron-PDF](#using-electron-pdf)\n  - [Handling Multiple Export Jobs](#handling-multiple-export-jobs)\n  - [Using In-Memory Buffer](#using-in-memory-buffer)\n- [Events](#events)\n- [Environment Variables](#environment-variables)\n- [Command Line Usage](#command-line-usage)\n- [Rendering Options](#rendering-options)\n  - [To specify browser options](#to-specify-browser-options)\n  - [Observing your own event](#observing-your-own-event)\n- [All Available Options](#all-available-options)\n- [Debugging](#debugging)\n  - [Sentry](#sentry)\n  - [CLI Usage](#cli-usage)\n  - [Other Formats](#other-formats)\n  - [Extensions](#extensions)\n- [License](#license)\n\n### Version Compatibility\n\nStarting from version 4.0.x, the master branch of Electron-PDF will always align with the latest Electron version.\n\nSemantic Versioning is followed, and the version numbers correspond to Electron versions as follows:\n\n- electron-pdf 25.0.x (master) =\u003e electron=25.4.0, node=16.15.0, chrome=114.0.5735.248\n- electron-pdf 20.0.x =\u003e electron=20.0.2, node=16.15.0, chrome=104.0.5112.81\n- electron-pdf 15.0.x =\u003e electron=15.1.1, node=16.5.0, chrome=94.0.4606.61\n- electron-pdf 10.0.x =\u003e  electron=10.1.3, node=12.16.3, chrome=85.0.4183.121\n- electron-pdf 7.0.x  =\u003e  electron 7.x (Chromium 78, Node 12.8.1)\n- electron-pdf 4.0.x  =\u003e  electron 4.x (Chromium 69, Node 10.11.0)\n- electron-pdf 1.3.x  =\u003e  electron 1.6.x (Chromium 56, Node 7.4)\n- electron-pdf 1.2.x  =\u003e  electron 1.4.x (Chromium 53, Node 6.5)\n\nPlease note that the choice of Chromium version affects the functionality you can utilize. Choose the version that aligns with your needs.\n\n### Installation\n\nInstall Electron-PDF via npm:\n\n```bash\nnpm install electron-pdf\n```\n\nIf you're installing as root using system-level npm (rather than a user-level install like with NVM), use the following command:\n\n```bash\nsudo npm install electron-pdf -g --unsafe-perm\n```\nPlease see [the npm docs](https://docs.npmjs.com/misc/config#unsafe-perm) for more information.\n\nFor GNU/Linux installations without a graphical environment, you need to install xvfb and set up a virtual display:\n\n```bash\nsudo apt-get install xvfb # or equivalent\nexport DISPLAY=':99.0'\nXvfb :99 -screen 0 1024x768x24 \u003e /dev/null 2\u003e\u00261 \u0026\nelectron-pdf ...\n```\n\nA Docker machine example is available [here](https://github.com/fraserxu/docker-tape-run).\n\n### Node.js Usage\n\nElectron-PDF can be integrated into your application or used as a rendering engine for a PDF service. Below are examples of usage.\n\n#### Application Setup\n\nIn your `package.json`:\n\n```json\n\"scripts\": {\n  \"start\": \"DEBUG=electronpdf:* electron index.js\",\n  \"watch\": \"DEBUG=electronpdf:* nodemon --exec electron index.js\"\n}\n```\n\n#### Using Electron-PDF\n\n```javascript\nconst ElectronPDF = require('electron-pdf')\nconst express = require('express')\nconst bodyParser = require('body-parser')\nconst app = express()\napp.use(bodyParser.json())\n\nconst exporter = new ElectronPDF()\nexporter.on('charged', () =\u003e {\n  app.listen(port, hostname, () =\u003e {\n    console.log(`Export Server running at http://${hostname}:${port}`)\n  })\n})\nexporter.start()\n```\n\n#### Handling Multiple Export Jobs\n\n```javascript\napp.post('/pdfexport', (req, res) =\u003e {\n  const jobOptions = {\n  /*\n    r.results[] will contain the following based on inMemory\n    false: the fully qualified path to a PDF file on disk\n    true: The Buffer Object as returned by Electron\n    Note: the default is false, this can not be set using the CLI\n  */\n    inMemory: false // Set inMemory to true for Buffer export\n  }\n  const options = {\n    pageSize: \"A4\"\n  }\n  \n  exporter.createJob(source, target, options, jobOptions).then(job =\u003e {\n    job.on('job-complete', r =\u003e {\n      console.log('pdf files:', r.results)\n      // Process the PDF file(s) here\n    })\n    job.render()\n  })\n})\n```\n\n#### Using In-Memory Buffer\n\nIf you set the `inMemory` setting to true, you must also set `closeWindow=false`\nor you will get a segmentation fault anytime the window is closed before the buffer \nis sent on the response.  You then need to invoke `job.destroy` to close the window.\n\n\n```javascript\nconst jobOptions = { inMemory: true, closeWindow: false }\nexporter.createJob(source, target, options, jobOptions).then(job =\u003e {\n  job.on('job-complete', r =\u003e {\n    // Send the Buffer here\n    process.nextTick(() =\u003e { job.destroy() })\n  })\n})\n```\n\n### Events\n\nElectron-PDF emits events to provide insights into its operations. A full documentation of events is a work in progress.\n\n### Environment Variables\n\n- `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`\n- `ELECTRONPDF_WINDOW_CLEANUP_INTERVAL`: Interval to check for hung windows, in milliseconds default: `30 seconds`\n- `ELECTRONPDF_WINDOW_LIFE_THRESHOLD`: How long a window can remain open before it is terminated, in milliseconds default: `5 minutes`\n- `ELECTRONPDF_PNG_CAPTURE_DELAY`: Delay before invoking `WebContents.capturePage` for PNG exports default: `100ms`\n\n### Command Line Usage\n\nElectron-PDF provides a versatile command-line interface (CLI) for various conversions and exports.\n\n#### Generate a PDF from an HTML file\n\n```bash\n$ electron-pdf index.html ~/Desktop/index.pdf\n```\n\n#### Generate a PDF from a Markdown file\n\n```bash\n$ electron-pdf index.md ~/Desktop/index.pdf\n```\n\n#### Generate a PDF from a Markdown file with custom CSS\n\n```bash\n$ electron-pdf index.html ~/Desktop/index.pdf -c my-awesome-css.css\n```\n\n#### Generate a PDF from a URL\n\n```bash\n$ electron-pdf https://fraserxu.me ~/Desktop/fraserxu.pdf\n```\n\nRendering Options\n-----\nElectron PDF gives you complete control of how the BrowserWindow should be configured, and when \nthe window contents should be captured.\n\n### To specify browser options\n\nThe [BrowserWindow supports many options](https://github.com/electron/electron/blob/master/docs/api/browser-window.md#new-browserwindowoptions) which you\n may define by passing a JSON Object to the `--browserConfig` option.\n \nSome common use cases may include:\n\n* `height` and `width` - electron-pdf calculates the browser height and width based off of the \ndimensions of PDF page size multiplied by the HTML standard of 96 pixels/inch.  So only set these\n values if you need to override this behavior\n* `show` - to display the browser window during generation\n\n```\n$ electron-pdf https://fraserxu.me ~/Desktop/fraserxu.pdf --browserConfig '{\"show\":true}'\n```\n\n### To generate a PDF after the an async task in the HTML\n\n```\nelectron-pdf ./index.html ~/Desktop/README.pdf -e\n```\n\nIn your application, at the point which the view is ready for rendering\n\n```javascript\ndocument.body.dispatchEvent(new Event('view-ready'))\n```\n\n**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.  \n\nIf you are finding that the [event is not effective](https://github.com/fraserxu/electron-pdf/issues/169) 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:\n\n```javascript\n  var eventEmitInterval = setInterval(function () {\n    document.body.dispatchEvent(new Event('view-ready'))\n  }, 25)\n\n  document.body.addEventListener('view-ready-acknowledged', function(){\n    clearInterval(eventEmitInterval)\n  })\n```\n\nWhen 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`\n\n#### Observing your own event\n\nIf the page you are rending is under your control, and you wish to modify the behavior\nof the rendering process you can use a [CustomEvent](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent)\nand an observer that will be triggered after the view is ready but before it is captured.\n\n##### your-page.html\n\n```javascript\ndocument.body.dispatchEvent(new CustomEvent('view-ready', { detail: {layout: landscape} }))\n```\n\n##### your-exporter.js\nYou are required to provide a function that accepts the `detail` object from \nthe CustomEvent and returns a Promise.  You may optionally fulfill the promise with \nand object that will amend/override any of the contextual attributes assigned to resource (url)\ncurrently being exported.\n\nAs an example, suppose you wanted to change the orientation of the PDF,\nand capture the output as PNG instead of a PDF.\n\n```javascript\njob.observeReadyEvent( (detail) =\u003e {\n    return new Promise( (resolve,reject) =\u003e {\n      const context = {}\n      if( detail \u0026\u0026 detail.landscape ){\n        job.changeArgValue('landscape', true)\n        context.type = 'png'\n      }\n      resolve(context)\n    })\n})\n```\n\nNote: Future versions of the library will only allow you to provide context overrides, \nand not allow you to change job level attributes.\n\n\nAll Available Options\n-----\n\nElectron PDF exposes the printToPDF settings (i.e. pageSize, orientation, margins, etc.) \navailable from the Electron API.  See the following options for usage.\n\n```\n\n  A command line tool to generate PDF from URL, HTML or Markdown files\n\n  Options\n    --help                     Show this help\n    --version                  Current version of package\n    \n    -i | --input               String - The path to the HTML file or url\n    -o | --output              String - The path of the output PDF\n    \n    -b | --printBackground     Boolean - Whether to print CSS backgrounds.\n    \n    --acceptLanguage           String - A valid value for the 'Accept-Language' http request header\n    \n    --browserConfig            String - A valid JSON String that will be parsed into the options passed to electron.BrowserWindow\n    \n    -c | --css                 String - The path to custom CSS (can be specified more than once)\n    \n    -d | --disableCache        Boolean - Disable HTTP caching\n                                 false - default\n    \n    -e | --waitForJSEvent      String - The name of the event to wait before PDF creation\n                                 'view-ready' - default\n    \n    -l | --landscape           Boolean - true for landscape, false for portrait (don't pass a string on the CLI, just the `-l` flag)\n                                 false - default\n    \n    -m | --marginsType         Integer - Specify the type of margins to use\n                                 0 - default margins\n                                 1 - no margins (electron-pdf default setting)\n                                 2 - minimum margins\n    \n    --noprint                  Boolean - Do not run printToPDF, useful if the page downloads a file that needs captured instead of a PDF.  \n                                         The Electron `win.webContents.session.on('will-download')` event will be implemented \n                                         and the file saved to the location provided in `--output`.\n                                         Currently only supports a single import url.\n                                         The page is responsible for initiating the download itself.\n    \n    -p | --pageSize            String - Can be A3, A4, A5, Legal, Letter, Tabloid or an Object containing height and width in microns\n                                 \"A4\" - default\n    \n    -r | --requestHeaders      String - A valid JSON String that will be parsed into an Object where each key/value pair is: \u003cheaderName\u003e: \u003cheaderValue\u003e\n                                 Example: '{\"Authorization\": \"Bearer token\", \"X-Custom-Header\": \"Hello World\"}'  \n    \n    -s | --printSelectionOnly  Boolean - Whether to print selection only\n                                 false - default\n                                 \n    -t | --trustRemoteContent  Boolean - Whether to trust remote content loaded in the Electron webview.  False by default.\n    --type                     String - The type of export, will dictate the output file type.  'png': PNG image, anything else: PDF File\n    \n    -w | --outputWait          Integer – Time to wait (in MS) between page load and PDF creation.  \n                                         If used in conjunction with -e this will override the default timeout of 10 seconds    \n    --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.\n                             false - default\n```\n\nFind more information on [Electron Security here](https://github.com/electron/electron/blob/master/docs/tutorial/security.md).\n\nDebugging\n-----\n\n## Sentry\nIf you have a [Sentry](https://sentry.io) account and setup a new app to get a new DSN, you can set a `SENTRY_DSN` environment variable which will activate sentry logs.\nSee `lib/sentry.js` for implementation details.\n\nThis will allow you to easily see/monitor errors that are occuring inside of the Chromium renderer (browser window).\nIt also automatically integrates with Electron's [Crash Reporter](https://electronjs.org/docs/api/crash-reporter)\n\n\nCLI Usage\n-----    \n\nYou can see some additional logging (if you're getting errors or unexpected output) by setting `DEBUG=electron*`\nFor example: `DEBUG=electron* electron-pdf \u003cinput\u003e \u003coutput\u003e -l`\n\n```\n  Usage\n    $ electron-pdf \u003cinput\u003e \u003coutput\u003e\n    $ electron-pdf \u003cinput\u003e \u003coutput\u003e -l\n\n  Examples\n    $ electron-pdf http://fraserxu.me ~/Desktop/fraserxu.pdf\n    $ electron-pdf ./index.html ~/Desktop/index.pdf\n    $ electron-pdf ./README.md ~/Desktop/README.pdf -l\n    $ electron-pdf ./README.md ~/Desktop/README.pdf -l -c my-awesome-css.css\n```\n\nInspired by [electron-mocha](https://github.com/jprichardson/electron-mocha)\n\n### Other Formats\n\nWant to use the same options, but export to PNG or snapshot the rendered HTML?\nJust set the output filename to end in .png or .html instead!\n\n```\n  Examples\n    $ electron-pdf http://fraserxu.me ~/Desktop/fraserxu.pdf\n    $ electron-pdf http://fraserxu.me ~/Desktop/fraserxu.html\n    $ electron-pdf http://fraserxu.me ~/Desktop/fraserxu.png\n```\n\n### Extensions\n\nIf you need powerpoint support, [pdf-powerpoint](https://www.npmjs.com/package/pdf-powerpoint) \npicks up where Electron PDF leaves off by converting each page in the PDF to a PNG and placing \nthem on individual slides.\n\n\n### License\n\nMIT\n\n[npm-image]: https://img.shields.io/npm/v/electron-pdf.svg?style=flat-square\n[npm-url]: https://npmjs.org/package/electron-pdf\n[travis-image]: https://img.shields.io/travis/fraserxu/electron-pdf/master.svg?style=flat-square\n[travis-url]: https://travis-ci.org/fraserxu/electron-pdf\n[downloads-image]: https://img.shields.io/npm/dm/electron-pdf.svg?style=flat-square\n[downloads-url]: https://npmjs.org/package/electron-pdf\n[standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square\n[standard-url]: https://github.com/feross/standard\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffraserxu%2Felectron-pdf","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffraserxu%2Felectron-pdf","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffraserxu%2Felectron-pdf/lists"}