├── .eslintrc.js
├── .gitattributes
├── .github
├── dependabot.yml
└── workflows
│ ├── lint.yml
│ └── test.yml
├── .gitignore
├── Dockerfile
├── LICENSE
├── Procfile
├── README.md
├── app.json
├── index.js
├── lib
├── authorization.js
├── meta.js
├── pdf
│ ├── completion-trigger.js
│ └── print-options.js
├── render.js
└── server.js
├── package.json
├── sample.html
├── test
├── helper.js
└── lib
│ ├── authorization-test.js
│ ├── meta-test.js
│ ├── pdf
│ ├── completion-trigger-test.js
│ └── print-options-test.js
│ ├── render-test.js
│ └── server-test.js
└── yarn.lock
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | "extends": "standard",
3 | "rules": {
4 | "key-spacing": ["error", { "align": "value" }],
5 | "space-before-function-paren": 0,
6 | "no-multi-spaces": 0
7 | },
8 | 'globals': {
9 | 'td': 'readonly',
10 | 'server': 'readonly'
11 | }
12 | };
13 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.html linguist-detectable=false
2 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | updates:
3 | - package-ecosystem: npm
4 | directory: "/"
5 | schedule:
6 | interval: daily
7 | time: "12:00"
8 | open-pull-requests-limit: 10
9 | ignore:
10 | - dependency-name: y18n
11 | versions:
12 | - 4.0.1
13 | - 4.0.2
14 | - dependency-name: jsdom
15 | versions:
16 | - 16.5.0
17 | - 16.5.1
18 | - 16.5.2
19 | - dependency-name: eslint
20 | versions:
21 | - 7.18.0
22 | - 7.19.0
23 |
--------------------------------------------------------------------------------
/.github/workflows/lint.yml:
--------------------------------------------------------------------------------
1 | name: Lint
2 |
3 | on: push
4 |
5 | concurrency:
6 | group: lint-${{ github.ref }}
7 | cancel-in-progress: true
8 |
9 | jobs:
10 | eslint:
11 | runs-on: ubuntu-latest
12 | steps:
13 | - uses: actions/checkout@v2
14 | - uses: actions/setup-node@v3
15 | with:
16 | node-version: 16.14.2
17 | cache: 'yarn'
18 | - name: Install modules
19 | run: yarn
20 | - name: Run ESLint
21 | run: yarn run eslint lib/* lib/pdf/* --ext .js
22 |
23 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: Test
2 |
3 | on: push
4 |
5 | concurrency:
6 | group: test-${{ github.ref }}
7 | cancel-in-progress: true
8 |
9 | jobs:
10 | test:
11 | runs-on: ubuntu-latest
12 | steps:
13 | - uses: actions/checkout@v2
14 | - uses: actions/cache@v2
15 | with:
16 | path: |
17 | node_modules
18 | */*/node_modules
19 | key: ${{ runner.os }}-node-${{ hashFiles('yarn.lock') }}
20 | restore-keys: |
21 | ${{ runner.os }}-node-${{ hashFiles('yarn.lock') }}
22 | ${{ runner.os }}-node-
23 | - name: Install dependencies
24 | run: yarn --frozen-lockfile
25 | - name: Test
26 | run: npm test
27 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
2 | coverage/
3 | .envrc
4 | .nyc*
5 | personal.Procfile
6 | example.pdf
7 | yarn-error.log
8 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM gcr.io/zenika-hub/alpine-chrome:with-node
2 |
3 | # Create app directory
4 | WORKDIR /usr/src/app
5 |
6 | # Install app dependencies
7 | COPY package.json yarn.lock ./
8 | RUN yarn install --production=true
9 |
10 | # Bundle app source
11 | COPY . .
12 |
13 | CMD [ "node", "index.js" ]
14 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU LESSER GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 |
9 | This version of the GNU Lesser General Public License incorporates
10 | the terms and conditions of version 3 of the GNU General Public
11 | License, supplemented by the additional permissions listed below.
12 |
13 | 0. Additional Definitions.
14 |
15 | As used herein, "this License" refers to version 3 of the GNU Lesser
16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU
17 | General Public License.
18 |
19 | "The Library" refers to a covered work governed by this License,
20 | other than an Application or a Combined Work as defined below.
21 |
22 | An "Application" is any work that makes use of an interface provided
23 | by the Library, but which is not otherwise based on the Library.
24 | Defining a subclass of a class defined by the Library is deemed a mode
25 | of using an interface provided by the Library.
26 |
27 | A "Combined Work" is a work produced by combining or linking an
28 | Application with the Library. The particular version of the Library
29 | with which the Combined Work was made is also called the "Linked
30 | Version".
31 |
32 | The "Minimal Corresponding Source" for a Combined Work means the
33 | Corresponding Source for the Combined Work, excluding any source code
34 | for portions of the Combined Work that, considered in isolation, are
35 | based on the Application, and not on the Linked Version.
36 |
37 | The "Corresponding Application Code" for a Combined Work means the
38 | object code and/or source code for the Application, including any data
39 | and utility programs needed for reproducing the Combined Work from the
40 | Application, but excluding the System Libraries of the Combined Work.
41 |
42 | 1. Exception to Section 3 of the GNU GPL.
43 |
44 | You may convey a covered work under sections 3 and 4 of this License
45 | without being bound by section 3 of the GNU GPL.
46 |
47 | 2. Conveying Modified Versions.
48 |
49 | If you modify a copy of the Library, and, in your modifications, a
50 | facility refers to a function or data to be supplied by an Application
51 | that uses the facility (other than as an argument passed when the
52 | facility is invoked), then you may convey a copy of the modified
53 | version:
54 |
55 | a) under this License, provided that you make a good faith effort to
56 | ensure that, in the event an Application does not supply the
57 | function or data, the facility still operates, and performs
58 | whatever part of its purpose remains meaningful, or
59 |
60 | b) under the GNU GPL, with none of the additional permissions of
61 | this License applicable to that copy.
62 |
63 | 3. Object Code Incorporating Material from Library Header Files.
64 |
65 | The object code form of an Application may incorporate material from
66 | a header file that is part of the Library. You may convey such object
67 | code under terms of your choice, provided that, if the incorporated
68 | material is not limited to numerical parameters, data structure
69 | layouts and accessors, or small macros, inline functions and templates
70 | (ten or fewer lines in length), you do both of the following:
71 |
72 | a) Give prominent notice with each copy of the object code that the
73 | Library is used in it and that the Library and its use are
74 | covered by this License.
75 |
76 | b) Accompany the object code with a copy of the GNU GPL and this license
77 | document.
78 |
79 | 4. Combined Works.
80 |
81 | You may convey a Combined Work under terms of your choice that,
82 | taken together, effectively do not restrict modification of the
83 | portions of the Library contained in the Combined Work and reverse
84 | engineering for debugging such modifications, if you also do each of
85 | the following:
86 |
87 | a) Give prominent notice with each copy of the Combined Work that
88 | the Library is used in it and that the Library and its use are
89 | covered by this License.
90 |
91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license
92 | document.
93 |
94 | c) For a Combined Work that displays copyright notices during
95 | execution, include the copyright notice for the Library among
96 | these notices, as well as a reference directing the user to the
97 | copies of the GNU GPL and this license document.
98 |
99 | d) Do one of the following:
100 |
101 | 0) Convey the Minimal Corresponding Source under the terms of this
102 | License, and the Corresponding Application Code in a form
103 | suitable for, and under terms that permit, the user to
104 | recombine or relink the Application with a modified version of
105 | the Linked Version to produce a modified Combined Work, in the
106 | manner specified by section 6 of the GNU GPL for conveying
107 | Corresponding Source.
108 |
109 | 1) Use a suitable shared library mechanism for linking with the
110 | Library. A suitable mechanism is one that (a) uses at run time
111 | a copy of the Library already present on the user's computer
112 | system, and (b) will operate properly with a modified version
113 | of the Library that is interface-compatible with the Linked
114 | Version.
115 |
116 | e) Provide Installation Information, but only if you would otherwise
117 | be required to provide such information under section 6 of the
118 | GNU GPL, and only to the extent that such information is
119 | necessary to install and execute a modified version of the
120 | Combined Work produced by recombining or relinking the
121 | Application with a modified version of the Linked Version. (If
122 | you use option 4d0, the Installation Information must accompany
123 | the Minimal Corresponding Source and Corresponding Application
124 | Code. If you use option 4d1, you must provide the Installation
125 | Information in the manner specified by section 6 of the GNU GPL
126 | for conveying Corresponding Source.)
127 |
128 | 5. Combined Libraries.
129 |
130 | You may place library facilities that are a work based on the
131 | Library side by side in a single library together with other library
132 | facilities that are not Applications and are not covered by this
133 | License, and convey such a combined library under terms of your
134 | choice, if you do both of the following:
135 |
136 | a) Accompany the combined library with a copy of the same work based
137 | on the Library, uncombined with any other library facilities,
138 | conveyed under the terms of this License.
139 |
140 | b) Give prominent notice with the combined library that part of it
141 | is a work based on the Library, and explaining where to find the
142 | accompanying uncombined form of the same work.
143 |
144 | 6. Revised Versions of the GNU Lesser General Public License.
145 |
146 | The Free Software Foundation may publish revised and/or new versions
147 | of the GNU Lesser General Public License from time to time. Such new
148 | versions will be similar in spirit to the present version, but may
149 | differ in detail to address new problems or concerns.
150 |
151 | Each version is given a distinguishing version number. If the
152 | Library as you received it specifies that a certain numbered version
153 | of the GNU Lesser General Public License "or any later version"
154 | applies to it, you have the option of following the terms and
155 | conditions either of that published version or of any later version
156 | published by the Free Software Foundation. If the Library as you
157 | received it does not specify a version number of the GNU Lesser
158 | General Public License, you may choose any version of the GNU Lesser
159 | General Public License ever published by the Free Software Foundation.
160 |
161 | If the Library as you received it specifies that a proxy can decide
162 | whether future versions of the GNU Lesser General Public License shall
163 | apply, that proxy's public statement of acceptance of any version is
164 | permanent authorization for you to choose that version for the
165 | Library.
166 |
--------------------------------------------------------------------------------
/Procfile:
--------------------------------------------------------------------------------
1 | web: node index.js
2 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # BreezyPDF Lite: HTML to PDF generation as a Service
2 | ### Submit a slug of HTML, get a Google Chrome rendered PDF back.
3 | [](https://travis-ci.org/danielwestendorf/breezy-pdf-lite) [](https://www.codetriage.com/danielwestendorf/breezy-pdf-lite)
4 |
5 | [](https://heroku.com/deploy)
6 |
7 | A quick to stand up HTML to PDF service powered by headless Google Chrome. Deploy with one click and start generating PDF's from your web application or command line.
8 |
9 | ### Getting Started
10 |
11 | ##### 1. Submit HTML to be converted
12 | This is done with a `POST` request the the web server. We'll use some example HTML for this example.
13 | ```sh
14 | curl -X POST -H 'Authorization: Bearer PRIVATE_TOKEN_DEFINED_IN_SERVER_ENVIRONMENT' \
15 | http://url-of-your-breezy-pdf-lite-server/render/html \
16 | -d "`curl https://raw.githubusercontent.com/danielwestendorf/breezy-pdf-lite/master/sample.html`" \
17 | -o example.pdf
18 | ```
19 |
20 | This will create the PDF in the current directory by the name of `example.pdf`.
21 |
22 | ##### 2. Configure with `meta` tags (optional)
23 | All configuration for the rendering of your PDF can be configured by meta tags within the HTML you submit. Simply insert the needed meta tag into the head or body of the HTML.
24 |
25 | ```html
26 |
27 | ```
28 |
29 | | Tag name | Default Value | Description |
30 | | ------------- |:-------------: | ----- |
31 | | breezy-pdf-filename | output.pdf | Name of the pdf |
32 | | breezy-pdf-width | 8.5 | PDF page width in inches |
33 | | breezy-pdf-height | 11 | PDF page height in inches |
34 | | breezy-pdf-cssPageSize | false | Use page size defined by CSS |
35 | | breezy-pdf-marginTop | 0.4 | Top margin |
36 | | breezy-pdf-marginRight | 0.4 | Right margin |
37 | | breezy-pdf-marginBottom | 0.4 | Bottom margin |
38 | | breezy-pdf-marginLeft | 0.4 | Left margin |
39 | | breezy-pdf-landscape | false | Print in landscape mode |
40 | | breezy-pdf-scale | 1 | Scale the viewport before converting to pdf |
41 | | breezy-pdf-displayBackground| false | Render the background in the HTML is included in the PDF |
42 |
43 | View the all the configuration options and their documentation [here](https://docs.breezypdf.com/metadata).
44 |
45 | ##### 2.a Header and Footer Templates
46 | Configure the HTML template to be included at the top and bottom of every page. Include elements with the classes of date, title, pageNumber, and totalPages to have values inserted at render time. At this time, any images must be DataURI encoded and styles must be specified within the template. Defaults to no HTML.
47 |
48 | | CSS class | Description |
49 | | --------- | ----------- |
50 | | date | Formatted render date displayed in UTC |
51 | | title | Title of the document specified by the title tag |
52 | | pageNumber| The count of the current page in the PDF |
53 | | totalPages| The total count of pages in the PDF |
54 |
55 | ##### 2.b Completion Triggers
56 | Notify the rendering engine when your rich content has completed loading and the PDF is ready to be rendered. Most typically used when complex JavaScript needs to be evaluated. The default completion trigger is a timer of 5000ms. If multiple completion triggers, the first trigger used will be adopted based on the order in which they're specified here.
57 |
58 | ###### Callback
59 | A JavaScript function in the global namespace which will be defined by the renderer. Your code will be invoke this callback when the document is ready for PDF rendering. Optional timeout can be specified in ms, defaulting to 5000ms.
60 |
61 | ```html
62 |
63 |
64 | ```
65 | ```js
66 | function() {
67 | // My hard working JS here
68 | window.myWorkHereIsDoneCallback();
69 | }
70 | ```
71 |
72 | ###### Event
73 | A JavaScript event which will be dispatched on an element when the document is ready for PDF rendering. Optional CSS element selector can be specified, defaulting to document. Optional timeout can be specified in ms, defaulting to 5000ms.
74 |
75 | ```html
76 |
77 |
78 |
79 | ```
80 |
81 | ```js
82 | var event = new CustomEvent('myCustomEvent');
83 | var element = document.getElementBydId('myContainer');
84 |
85 | element.dispatchEvent(event);
86 | ```
87 |
88 | ###### Element
89 | The CSS selector of an element which will be inserted into the document when the document is ready for PDF rendering. Optional timeout can be specified in ms, defaulting to 5000ms.
90 |
91 | ```html
92 |
93 |
94 | ```
95 |
96 | ```js
97 | function() {
98 | // My hard working JS here
99 | var lastPage = document.getElementById('#last-page');
100 | var lastElement = document.createElement('div');
101 |
102 | lastElement.id = 'last-element';
103 |
104 | lastPage.appendChild(lastElement);
105 | }
106 | ```
107 |
108 | ###### Variable
109 | The variable in the global namespace which will be defined when the document is ready for PDF rendering. Optional timeout can be specified in ms, defaulting to 5000ms.
110 |
111 | ```html
112 |
113 | ```
114 |
115 | ```js
116 | function() {
117 | // My hard working JS here
118 | window.myWorkHereIsDoneVariable = true;
119 | }
120 | ```
121 |
122 | ###### Timer
123 | The predefined amount of time to wait before the document is rendered to PDF. Timer should be specified in ms, defaulting to 5000ms.
124 |
125 | ```html
126 |
127 | ```
128 |
129 |
130 | ### Deployment
131 |
132 | #### Heroku
133 | [](https://heroku.com/deploy)
134 |
135 | 1. Deploy to Heroku with one-click.
136 |
137 | ### Clients
138 |
139 | - [Ruby/Rack/Rails](https://github.com/danielwestendorf/breezy_pdf_lite-ruby)
140 | - [PHP](https://github.com/jitendra-1217/breezy-pdf-lite-php)
141 | - [Node.js](https://github.com/danielwestendorf/breezy-pdf-lite-client-js)
142 | - [Browserside JS](https://github.com/danielwestendorf/breezy-pdf-lite/issues/5)
143 | - [Java](https://github.com/danielwestendorf/breezy-pdf-lite/issues/6)
144 | - [Swift](https://github.com/danielwestendorf/breezy-pdf-lite/issues/7)
145 | - [Python](https://github.com/danielwestendorf/breezy-pdf-lite/issues/8)
146 | - [Go](https://github.com/danielwestendorf/breezy-pdf-lite/issues/10)
147 |
148 | #### Docker
149 |
150 | `docker run -it -p 5002:5002 -e "DEBUG=breezy-pdf-lite:*" -e "PORT=5002" -e "PRIVATE_TOKEN=YOURSUPERSECRETTOKEN" danielwestendorf/breezy-pdf-lite:latest`
151 |
152 | #### Non-Heroku
153 |
154 | 1. Install node & yarn
155 | 2. `yarn install`
156 | 4. Set the Environment variables specified below
157 | 5. Start the web process `node index.js`
158 |
159 | ### Configuration
160 | Set the Environment/Heroku Config Vars
161 |
162 | | ENV Variable | Default Value | Description |
163 | | ------------- |:-------------: | ----- |
164 | | PRIVATE_TOKEN | generated secret | A private key for accessing the API. |
165 |
166 |
167 |
168 | Set `DEBUG` Config var to `breezy-pdf-lite:*` to get debugged output.
169 |
170 |
171 | ### Run Tests
172 |
173 | `$ /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --interpreter none --headless --disable-gpu --disable-translate --disable-extensions --disable-background-networking --safebrowsing-disable-auto-update --disable-sync --metrics-recording-only --disable-default-apps --no-first-run --mute-audio --hide-scrollbars --remote-debugging-port=9222`
174 |
175 | `$ npm test`
176 |
--------------------------------------------------------------------------------
/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "BreezyPDF Lite",
3 | "description": "Submit an HTML string, get a PDF back, rendered by Google Chrome. Built by BreezyPDF.com",
4 | "keywords": [
5 | "pdf",
6 | "chrome",
7 | "service",
8 | "heroku",
9 | "html2pdf"
10 | ],
11 | "scripts": {
12 | },
13 | "stack": "heroku-18",
14 | "repository": "https://github.com/danielwestendorf/breezy-pdf-lite",
15 | "env": {
16 | "PRIVATE_TOKEN": {
17 | "description": "A secret key for submitting tokens to the API.",
18 | "generator": "secret"
19 | },
20 | "NODE_ENV": {
21 | "description": "node env",
22 | "value": "production"
23 | }
24 | },
25 | "addons": [
26 | ],
27 | "image": "heroku/nodejs",
28 | "buildpacks": [
29 | {
30 | "url": "https://github.com/heroku/heroku-buildpack-google-chrome"
31 | },
32 | {
33 | "url": "https://github.com/heroku/heroku-buildpack-nodejs"
34 | }
35 | ]
36 | }
37 |
--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------
1 | const ChromeLauncher = require('chrome-launcher')
2 | const Server = require('./lib/server')
3 |
4 | const webServer = new Server({
5 | port: process.env.PORT || 5001,
6 | privateToken: process.env.PRIVATE_TOKEN
7 | })
8 |
9 | console.log('Starting Google Chrome')
10 |
11 | ChromeLauncher.launch({
12 | chromePath: '/usr/bin/chromium-browser',
13 | chromeFlags: ['--headless', '--disable-gpu', '--disable-dev-shm-usage', '--no-sandbox', '--hide-scrollbars'],
14 | port: 9222,
15 | startingUrl: (process.env.STARTING_URL || 'about:blank')
16 | }).then((chrome) => {
17 | console.log(`Chrome debugging port running on ${chrome.port}`)
18 |
19 | chrome.process.on('close', (code) => {
20 | console.error(`Chrome process closed with code ${code}`)
21 | process.exit(code)
22 | })
23 |
24 | webServer.start()
25 | }).catch((error) => {
26 | console.error(error)
27 | console.error('Exiting')
28 |
29 | process.exit(1)
30 | })
31 |
--------------------------------------------------------------------------------
/lib/authorization.js:
--------------------------------------------------------------------------------
1 | const debug = require('debug')
2 |
3 | module.exports = (options) => {
4 | this.log = debug('breezy-pdf-lite:authorization')
5 | this.options = options
6 |
7 | return (req, res, next) => {
8 | if (!this.options.privateToken) {
9 | return next()
10 | }
11 |
12 | this.log('Validating Private Token...')
13 | const authHeader = String(req.get('Authorization'))
14 |
15 | if (authHeader.replace(/Bearer (.*)$/i, '$1') !== this.options.privateToken) {
16 | this.log('Invalid Private Token')
17 |
18 | res.status(401).send('Invalid Private Token')
19 | } else {
20 | this.log('Valid Private Token')
21 | next()
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/lib/meta.js:
--------------------------------------------------------------------------------
1 | const { JSDOM } = require('jsdom')
2 |
3 | module.exports = (htmlString) => {
4 | const meta = {}
5 | const dom = new JSDOM(htmlString)
6 |
7 | const metaTags = dom.window.document.querySelectorAll('meta[name^="breezy-pdf-"]')
8 |
9 | for (var i = 0; i < metaTags.length; i++) {
10 | const tag = metaTags[i]
11 | const name = tag.name.replace(/^breezy-pdf-/, '')
12 |
13 | meta[name] = tag.content
14 | }
15 |
16 | return meta
17 | }
18 |
--------------------------------------------------------------------------------
/lib/pdf/completion-trigger.js:
--------------------------------------------------------------------------------
1 | const htmlPdf = require('html-pdf-chrome')
2 | const debug = require('debug')
3 |
4 | module.exports = class CompletionTrigger {
5 | constructor(options) {
6 | this.options = options || {}
7 |
8 | this.log = debug(options.log || 'breezy-pdf-lite:pdf:completion-triggers')
9 | }
10 |
11 | build() {
12 | if (this.options.callback) {
13 | return this.buildCallbackTrigger()
14 | } else if (this.options.event) {
15 | return this.buildEventTrigger()
16 | } else if (this.options.element) {
17 | return this.buildElementTrigger()
18 | } else if (this.options.variable) {
19 | return this.buildVariableTrigger()
20 | } else {
21 | return this.buildTimerTrigger()
22 | }
23 | }
24 |
25 | // Private
26 |
27 | buildCallbackTrigger() {
28 | const callback = this.options.callback || 'breezyPdf'
29 | const timeout = parseInt(this.options.timeout) || 5000
30 |
31 | this.log(`Callback trigger specified: callback=${callback} timeout=${timeout}`)
32 | return new htmlPdf.CompletionTrigger.Callback(callback, timeout)
33 | }
34 |
35 | buildElementTrigger() {
36 | const element = this.options.element || 'footer'
37 | const timeout = parseInt(this.options.timeout) || 5000
38 |
39 | this.log(`Element trigger specified: element=${element} timeout=${timeout}`)
40 | return new htmlPdf.CompletionTrigger.Element(element, timeout)
41 | }
42 |
43 | buildEventTrigger() {
44 | const event = this.options.event || 'load'
45 | const element = this.options.element || 'document'
46 | const timeout = parseInt(this.options.timeout) || 5000
47 |
48 | this.log(`Event trigger specified: event=${event} element=${element} timeout=${timeout}`)
49 | return new htmlPdf.CompletionTrigger.Event(event, element, timeout)
50 | }
51 |
52 | buildVariableTrigger() {
53 | const variable = this.options.variable || 'breezyPDF'
54 | const timeout = parseInt(this.options.timeout) || 5000
55 |
56 | this.log(`Variable trigger specified: variable=${variable} timeout=${timeout}`)
57 | return new htmlPdf.CompletionTrigger.Variable(variable, timeout)
58 | }
59 |
60 | buildTimerTrigger() {
61 | const timer = parseInt(this.options.timer) || 5000
62 |
63 | this.log(`Timer trigger specified: timeout=${timer}`)
64 | return new htmlPdf.CompletionTrigger.Timer(timer)
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/lib/pdf/print-options.js:
--------------------------------------------------------------------------------
1 | const debug = require('debug')
2 |
3 | module.exports = class PrintOptions {
4 | constructor(options) {
5 | this.options = options || {}
6 | this.log = debug(options.log || 'breezy-pdf-lite:pdf:print-options')
7 | }
8 |
9 | build() {
10 | const options = {
11 | preferCSSPageSize: this.truthy(this.options.cssPageSize) || false,
12 | paperWidth: this.floatOrDefault(this.options.width, 8.5),
13 | paperHeight: this.floatOrDefault(this.options.height, 11),
14 | marginTop: this.floatOrDefault(this.options.marginTop, 0.4),
15 | marginBottom: this.floatOrDefault(this.options.marginBottom, 0.4),
16 | marginLeft: this.floatOrDefault(this.options.marginLeft, 0.4),
17 | marginRight: this.floatOrDefault(this.options.marginRight, 0.4),
18 | landscape: this.truthy(this.options.landscape) || false,
19 | scale: this.floatOrDefault(this.options.scale, 1),
20 | printBackground: this.truthy(this.options.displayBackground) || false,
21 | pageRanges: this.options.pageRanges || '',
22 |
23 | headerTemplate: this.options.headerTemplate,
24 | footerTemplate: this.options.footerTemplate,
25 |
26 | ignoreInvalidPageRanges: true,
27 | displayHeaderFooter: (this.options.headerTemplate !== undefined || this.options.footerTemplate !== undefined)
28 |
29 | }
30 |
31 | this.log(`Rendering with options: ${options}`)
32 |
33 | return options
34 | }
35 |
36 | // Private
37 |
38 | truthy(val) {
39 | switch (typeof val) {
40 | case 'boolean':
41 | return val
42 | case 'string':
43 | return val === 'true'
44 | case 'number':
45 | return val === 1
46 | }
47 | }
48 |
49 | floatOrDefault(val, defaultVal) {
50 | if (val !== undefined) {
51 | return parseFloat(val)
52 | } else {
53 | return defaultVal
54 | }
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/lib/render.js:
--------------------------------------------------------------------------------
1 | const htmlPdf = require('html-pdf-chrome')
2 | const debug = require('debug')
3 | const uuid = require('uuid')
4 | const meta = require('./meta')
5 | const PrintOptions = require('./pdf/print-options')
6 | const CompletionTrigger = require('./pdf/completion-trigger')
7 |
8 | module.exports = class Render {
9 | constructor(htmlString, options) {
10 | this.htmlString = htmlString
11 | this.options = options || {}
12 |
13 | this.log = debug(this.options.log || 'breezy-pdf-lite:pdf')
14 | }
15 |
16 | toPdf() {
17 | const renderOptions = {
18 | completionTrigger: this.completionTrigger(),
19 | printOptions: this.printOptions(),
20 | host: 'localhost',
21 | port: 9222
22 | }
23 |
24 | this.log(`Generating PDF for HTML string with options: ${JSON.stringify(renderOptions)}`)
25 |
26 | return htmlPdf.create(this.htmlString, renderOptions)
27 | }
28 |
29 | meta() {
30 | if (this.metadata === undefined) {
31 | this.metadata = meta(this.htmlString)
32 | }
33 |
34 | return this.metadata
35 | }
36 |
37 | filename() {
38 | return `${(this.meta().filename || uuid()).split('.')[0]}.pdf`
39 | }
40 |
41 | printOptions() {
42 | return new PrintOptions(this.meta()).build()
43 | }
44 |
45 | completionTrigger() {
46 | return new CompletionTrigger(this.meta()).build()
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/lib/server.js:
--------------------------------------------------------------------------------
1 | const express = require('express')
2 | const bodyParser = require('body-parser')
3 | const debug = require('debug')
4 | const Authorization = require('./authorization')
5 | const Render = require('./render')
6 |
7 | module.exports = class Server {
8 | constructor(options) {
9 | this.options = options || {
10 | port: 5001,
11 | privateToken: process.env.PRIVATE_TOKEN
12 | }
13 |
14 | this.app = express()
15 | this.log = debug(this.options.log || 'breezy-pdf-lite:server')
16 | }
17 |
18 | start() {
19 | this.log('Starting server...')
20 |
21 | const authenticatedApp = express()
22 | const unauthenticated = (_req, res, _next) => {
23 | res.status(200).send('OK')
24 | }
25 |
26 | this.app.use('/health', unauthenticated)
27 |
28 | // Add middlware
29 | authenticatedApp.use(Authorization({privateToken: this.options.privateToken}))
30 | authenticatedApp.post('/html', async (req, res) => {
31 | res.setTimeout(240000, () => { this.log('Request timedout after 240000ms') })
32 | this.log('Attempting to render HTML')
33 | let pdf
34 | const renderer = new Render(req.body)
35 | try {
36 | pdf = await renderer.toPdf()
37 | res.status(201)
38 | .set('Content-Disposition', `attachment; filename="${renderer.filename()}"`)
39 | .send(pdf.toBuffer())
40 | } catch (error) {
41 | this.log(error)
42 | res.status(500).send('Encountered an error while generating PDF. Check the server logs for more details')
43 | }
44 | })
45 |
46 | this.app.use(bodyParser.text({
47 | type: '*/*',
48 | limit: '50mb',
49 | parameterLimit: 100000,
50 | extended: true
51 | }))
52 |
53 | this.app.get('/', (req, res) => res.send('OK'))
54 | this.app.use('/render', authenticatedApp)
55 |
56 | this.app.listen(this.options.port, () => {
57 | console.log(`Listening for requests at http://localhost:${this.options.port}...`)
58 | })
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "breezy-pdf-lite",
3 | "version": "0.0.1",
4 | "description": "Render HTML to a PDF with Google Chrome, via an HTTP request",
5 | "main": "index.js",
6 | "author": "Daniel Westendorf",
7 | "license": "GPL-3.0-or-later",
8 | "dependencies": {
9 | "body-parser": "^1.20.2",
10 | "chrome-launcher": "^0.15.2",
11 | "debug": "^4.3.1",
12 | "express": "^4.18.2",
13 | "html-pdf-chrome": "^0.8.4",
14 | "jsdom": "^22.1.0"
15 | },
16 | "devDependencies": {
17 | "coveralls": "^3.1.0",
18 | "eslint": "^8.42.0",
19 | "eslint-config-standard": "^11.0.0",
20 | "eslint-plugin-import": "^2.27.5",
21 | "eslint-plugin-node": "^11.1.0",
22 | "eslint-plugin-promise": "^6.1.1",
23 | "eslint-plugin-standard": "^5.0.0",
24 | "istanbul": "^0.4.5",
25 | "node-fetch": "^3.3.1",
26 | "nyc": "^15.1.0",
27 | "teenytest": "^6.0.5",
28 | "testdouble": "^3.18.0"
29 | },
30 | "scripts": {
31 | "test": "teenytest 'test/**/*-test.js' --helper test/helper.js",
32 | "lint": "./node_modules/.bin/eslint lib/* test/* *.js",
33 | "testncov": "nyc --reporter=lcov --reporter=text teenytest 'test/**/*-test.js' --helper test/helper.js && ./node_modules/.bin/eslint *.js, **/**.js"
34 | },
35 | "teenytest": {
36 | "timeout": 10000
37 | },
38 | "nyc": {
39 | "exclude": [
40 | "index.js"
41 | ],
42 | "include": [
43 | "lib/**/*.js"
44 | ]
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/sample.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |