├── .eslintrc.js ├── .github ├── FUNDING.yml └── workflows │ ├── ci.yml │ └── codeql-analysis.yml ├── .gitignore ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── babel.config.js ├── jest.config.js ├── jest.setup.js ├── package.json ├── src ├── index.ts ├── main.integration.spec.ts ├── main.ts ├── main.unit.spec.ts ├── models │ ├── Screenshot.spec.ts │ └── Screenshot.ts ├── screenshot.spec.ts ├── screenshot.ts └── types.ts ├── tsconfig.json └── yarn.lock /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | parser: "@typescript-eslint/parser", 4 | plugins: ["@typescript-eslint"], 5 | extends: ["eslint:recommended", "plugin:@typescript-eslint/recommended"], 6 | }; 7 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [frinyvonnick] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: [push, pull_request] 3 | 4 | jobs: 5 | test: 6 | runs-on: ubuntu-latest 7 | env: 8 | CI: true 9 | 10 | steps: 11 | - uses: actions/checkout@v1 12 | - uses: actions/setup-node@v1 13 | with: 14 | node-version: 18 15 | - run: yarn install --frozen-lockfile 16 | - run: yarn build 17 | - run: yarn lint 18 | - run: yarn test 19 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | name: "CodeQL" 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | pull_request: 7 | # The branches below must be a subset of the branches above 8 | branches: [master] 9 | schedule: 10 | - cron: '0 13 * * 2' 11 | 12 | jobs: 13 | analyze: 14 | name: Analyze 15 | runs-on: ubuntu-latest 16 | 17 | strategy: 18 | fail-fast: false 19 | matrix: 20 | # Override automatic language detection by changing the below list 21 | # Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python'] 22 | language: ['javascript'] 23 | # Learn more... 24 | # https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection 25 | 26 | steps: 27 | - name: Checkout repository 28 | uses: actions/checkout@v2 29 | with: 30 | # We must fetch at least the immediate parents so that if this is 31 | # a pull request then we can checkout the head. 32 | fetch-depth: 2 33 | 34 | # If this run was triggered by a pull request event, then checkout 35 | # the head of the pull request instead of the merge commit. 36 | - run: git checkout HEAD^2 37 | if: ${{ github.event_name == 'pull_request' }} 38 | 39 | # Initializes the CodeQL tools for scanning. 40 | - name: Initialize CodeQL 41 | uses: github/codeql-action/init@v1 42 | with: 43 | languages: ${{ matrix.language }} 44 | # If you wish to specify custom queries, you can do so here or in a config file. 45 | # By default, queries listed here will override any specified in a config file. 46 | # Prefix the list here with "+" to use these queries and those in the config file. 47 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 48 | 49 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 50 | # If this step fails, then you should remove it and run the build manually (see below) 51 | - name: Autobuild 52 | uses: github/codeql-action/autobuild@v1 53 | 54 | # ℹ️ Command-line programs to run using the OS shell. 55 | # 📚 https://git.io/JvXDl 56 | 57 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 58 | # and modify them (or add more) to build your code if your project 59 | # uses a compiled language 60 | 61 | #- run: | 62 | # make bootstrap 63 | # make release 64 | 65 | - name: Perform CodeQL Analysis 66 | uses: github/codeql-action/analyze@v1 67 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # next.js build output 61 | 62 | .next 63 | 64 | # Tesseract.js 65 | 66 | eng.traineddata 67 | 68 | .DS_Store 69 | 70 | dist 71 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | 4 | ## 5.0.0 (2024-09-03) 5 | 6 | ### Changed 7 | 8 | - ⬆️ upgrade dependencies according to package.json [[70f3f56](https://github.com/frinyvonnick/node-html-to-image/commit/70f3f562d6e5b56403018d18f36aa1ae0a2dcdd0)] 9 | - ⬆️ Bump semver from 5.7.1 to 5.7.2 ([#205](https://github.com/frinyvonnick/node-html-to-image/issues/205)) [[64955f9](https://github.com/frinyvonnick/node-html-to-image/commit/64955f9f9f1f6f6c2d56fd0d631f8d995d3d12f4)] 10 | - ⬆️ Bump word-wrap from 1.2.3 to 1.2.4 ([#207](https://github.com/frinyvonnick/node-html-to-image/issues/207)) [[5db0d38](https://github.com/frinyvonnick/node-html-to-image/commit/5db0d384055bdd4ba64cc2c010bd61d2c1c9b45e)] 11 | 12 | ### Miscellaneous 13 | 14 | - :arrow-up: upgrade puppeteer to 23.2.2 [[2c05eaf](https://github.com/frinyvonnick/node-html-to-image/commit/2c05eaf015844065726e9c93302ad5d345a83830)] 15 | - :arrow-up: upgrade puppeteer to 22.8.2 [[d8800c6](https://github.com/frinyvonnick/node-html-to-image/commit/d8800c6d7f5bd81c5de46672295d0696443335a6)] 16 | - 📝 Update sample code in README ([#204](https://github.com/frinyvonnick/node-html-to-image/issues/204)) [[5ac5bc8](https://github.com/frinyvonnick/node-html-to-image/commit/5ac5bc8fc25456704b85ef2eb664008f06e490d6)] 17 | 18 | 19 | 20 | ## 4.0.0 (2023-08-04) 21 | 22 | ### Changed 23 | 24 | - ⬆️ Upgrade dependencies (puppeteer@21.0.1 , handlebars@4.7.8) ([#209](https://github.com/frinyvonnick/node-html-to-image/issues/209)) [[6fc5cac](https://github.com/frinyvonnick/node-html-to-image/commit/6fc5cac18df21b35c2eb6216fa6e3d7e681ba969)] 25 | 26 | 27 | 28 | ## 3.4.0 (2023-08-01) 29 | 30 | ### Added 31 | 32 | - ✨ Add timeout option ([#189](https://github.com/frinyvonnick/node-html-to-image/issues/189)) [[20110bc](https://github.com/frinyvonnick/node-html-to-image/commit/20110bc38d42e2d9cc71ac8f16fb847fbb863622)] 33 | 34 | ### Changed 35 | 36 | - ⬆️ Bump json5 from 2.2.1 to 2.2.3 ([#185](https://github.com/frinyvonnick/node-html-to-image/issues/185)) [[7486250](https://github.com/frinyvonnick/node-html-to-image/commit/748625068ebfa165a37769a1af49f9a99ad0d9cb)] 37 | 38 | 39 | 40 | ## 3.3.0 (2022-08-31) 41 | 42 | ### Added 43 | 44 | - ✨ Add puppeteer object property to use different libraries ([#173](https://github.com/frinyvonnick/node-html-to-image/issues/173)) [[e9aa9d2](https://github.com/frinyvonnick/node-html-to-image/commit/e9aa9d27992ef7a36df5b0411e1ef3ede1501442)] 45 | - ✨ Add new option to register handlebars helpers ([#145](https://github.com/frinyvonnick/node-html-to-image/issues/145)) [[a2ab82a](https://github.com/frinyvonnick/node-html-to-image/commit/a2ab82afe46c9e8c2ab41d267760520267c59839)] 46 | 47 | ### Changed 48 | 49 | - ⬆️ Bump jpeg-js from 0.4.3 to 0.4.4 ([#170](https://github.com/frinyvonnick/node-html-to-image/issues/170)) [[bbe0b86](https://github.com/frinyvonnick/node-html-to-image/commit/bbe0b865b24a9b9ae242e175081667eb0be5d275)] 50 | - ⬆️ Bump minimist from 1.2.5 to 1.2.6 ([#166](https://github.com/frinyvonnick/node-html-to-image/issues/166)) [[8ee87d2](https://github.com/frinyvonnick/node-html-to-image/commit/8ee87d22cbfd5c47b30d870a8dfd9703d581d538)] 51 | 52 | 53 | 54 | ## 3.2.4 (2022-02-15) 55 | 56 | ### Changed 57 | 58 | - ⬆️ Upgrade gitmoji-changelog to v2.3.0 [[d5aae40](https://github.com/frinyvonnick/node-html-to-image/commit/d5aae4017d1a7cfa25ec2efb8e263ca3c927da46)] 59 | 60 | ### Fixed 61 | 62 | - 🐛 Fix typings for `puppeteerArgs` ([#163](https://github.com/frinyvonnick/node-html-to-image/issues/163)) [[e206ee6](https://github.com/frinyvonnick/node-html-to-image/commit/e206ee669d95020026d8d98d12ac97156529f31e)] 63 | 64 | 65 | 66 | ## 3.2.3 (2022-02-11) 67 | 68 | ### Changed 69 | 70 | - 🔧 Add forceConsistentCasingInFileNames in compilerOptions ([#161](https://github.com/frinyvonnick/node-html-to-image/issues/161)) [[2212e35](https://github.com/frinyvonnick/node-html-to-image/commit/2212e354e028f6fec80e564ab290d4b707220be7)] 71 | 72 | 73 | 74 | ## 3.2.2 (2022-02-09) 75 | 76 | ### Changed 77 | 78 | - 🔧 Generate d.ts file [[66a4199](https://github.com/frinyvonnick/node-html-to-image/commit/66a41997944913f5368adab7c0e491025827d6a4)] 79 | 80 | ### Miscellaneous 81 | 82 | - 📝 Update Typescript section of README [[054fc88](https://github.com/frinyvonnick/node-html-to-image/commit/054fc883f3743cba178979f1eb2647938fbf5131)] 83 | 84 | 85 | 86 | ## 3.2.1 (2022-02-08) 87 | 88 | ### Added 89 | 90 | - ✅ Add a test to guarantee buffers order ([#157](https://github.com/frinyvonnick/node-html-to-image/issues/157)) [[1a9bf4f](https://github.com/frinyvonnick/node-html-to-image/commit/1a9bf4fbf03768ea054b74c89b2ab3bc9a495ec4)] 91 | - 👷‍♂️ Add Typescript build to CI [[c6d4fa3](https://github.com/frinyvonnick/node-html-to-image/commit/c6d4fa36b520166fd3b861ed47f1963009db33b3)] 92 | - ➕ Move to TypeScript ([#141](https://github.com/frinyvonnick/node-html-to-image/issues/141)) [[d1d08cd](https://github.com/frinyvonnick/node-html-to-image/commit/d1d08cdca309d1e6fa130c4b2b0de3942cd44615)] 93 | 94 | ### Changed 95 | 96 | - ⬆️ Bump tar from 4.4.13 to 4.4.19 ([#126](https://github.com/frinyvonnick/node-html-to-image/issues/126)) [[ab7cce1](https://github.com/frinyvonnick/node-html-to-image/commit/ab7cce1100b10c6ba23c42999fc1d6f72fe0c2a2)] 97 | - ⬆️ Bump tmpl from 1.0.4 to 1.0.5 ([#128](https://github.com/frinyvonnick/node-html-to-image/issues/128)) [[d94e9fc](https://github.com/frinyvonnick/node-html-to-image/commit/d94e9fc8a604fbe5f8a7a7a57183dc39452d86d1)] 98 | - ⬆️ Bump node-fetch from 2.6.1 to 2.6.7 ([#153](https://github.com/frinyvonnick/node-html-to-image/issues/153)) [[520d1e7](https://github.com/frinyvonnick/node-html-to-image/commit/520d1e73583ea905d29a97524449cf715a7c1c31)] 99 | - ♻️ Refactor code to make issues easier to fix ([#155](https://github.com/frinyvonnick/node-html-to-image/issues/155)) [[d28d88e](https://github.com/frinyvonnick/node-html-to-image/commit/d28d88ecd757f2f11f976ce110c469db6015388a)] 100 | - ⬆️ Upgrade puppeteer and puppeteer-cluster ([#154](https://github.com/frinyvonnick/node-html-to-image/issues/154)) [[c42b6f0](https://github.com/frinyvonnick/node-html-to-image/commit/c42b6f08561af9af18b1cc436506a065ca003b77)] 101 | 102 | ### Fixed 103 | 104 | - 🐛 Prevent handlebar to compile template if content is empty ([#156](https://github.com/frinyvonnick/node-html-to-image/issues/156)) [[2684645](https://github.com/frinyvonnick/node-html-to-image/commit/2684645f9bc883f9f7b43ae78240d1b6d000a986)] 105 | 106 | 107 | 108 | ## 3.2.0 (2021-06-26) 109 | 110 | ### Added 111 | 112 | - ✨ Add selector option ([#114](https://github.com/frinyvonnick/node-html-to-image/issues/114)) [[701b514](https://github.com/frinyvonnick/node-html-to-image/commit/701b5143220aa80eac945945356743d6cb8e70a7)] 113 | 114 | ### Changed 115 | 116 | - ⬆️ Bump y18n from 3.2.1 to 3.2.2 ([#103](https://github.com/frinyvonnick/node-html-to-image/issues/103)) [[3ba0e96](https://github.com/frinyvonnick/node-html-to-image/commit/3ba0e966cf450f0112c06ffd0a7c2bc36cf66a02)] 117 | - ⬆️ Bump ssri from 6.0.1 to 6.0.2 ([#105](https://github.com/frinyvonnick/node-html-to-image/issues/105)) [[b419b3b](https://github.com/frinyvonnick/node-html-to-image/commit/b419b3b61eb7506dd912f4f8f98d8adecfa9cf4a)] 118 | - ⬆️ Bump handlebars from 4.7.6 to 4.7.7 ([#106](https://github.com/frinyvonnick/node-html-to-image/issues/106)) [[0dda192](https://github.com/frinyvonnick/node-html-to-image/commit/0dda1927a424dec0388626b5fdf2d59a4d67ac8a)] 119 | - ⬆️ Bump hosted-git-info from 2.8.8 to 2.8.9 ([#107](https://github.com/frinyvonnick/node-html-to-image/issues/107)) [[27614ac](https://github.com/frinyvonnick/node-html-to-image/commit/27614ac1851defc061435110f9e6c50dedde7768)] 120 | - ⬆️ Upgrade dependencies [[bc747a8](https://github.com/frinyvonnick/node-html-to-image/commit/bc747a8982d592b9e3942e7474925a4e79d7ac74)] 121 | - ⬆️ Bump node-notifier from 8.0.0 to 8.0.1 ([#86](https://github.com/frinyvonnick/node-html-to-image/issues/86)) [[a9db417](https://github.com/frinyvonnick/node-html-to-image/commit/a9db417d3a34564fd8797b5fffa61d331a3051fe)] 122 | - ⬆️ Bump ini from 1.3.5 to 1.3.8 ([#84](https://github.com/frinyvonnick/node-html-to-image/issues/84)) [[8724c5d](https://github.com/frinyvonnick/node-html-to-image/commit/8724c5db1b2d6fdbcb2eb4dbcbf060333062408f)] 123 | - ⬆️ Bump node-fetch from 2.6.0 to 2.6.1 ([#59](https://github.com/frinyvonnick/node-html-to-image/issues/59)) [[44595a7](https://github.com/frinyvonnick/node-html-to-image/commit/44595a79835b113d380d095ac285527e273f618d)] 124 | - ⬆️ Update puppeteer to 3.0.4 ([#113](https://github.com/frinyvonnick/node-html-to-image/issues/113)) [[5239595](https://github.com/frinyvonnick/node-html-to-image/commit/5239595894be9b46bd351780d124d13ba0accf22)] 125 | 126 | ### Miscellaneous 127 | 128 | - 📝 Remove unfinished sentence from README [[e9d1ddb](https://github.com/frinyvonnick/node-html-to-image/commit/e9d1ddb0f17c6142836091c6b14281780e45110f)] 129 | - 📝 Dealing with Fonts ([#76](https://github.com/frinyvonnick/node-html-to-image/issues/76)) [[2b8da4e](https://github.com/frinyvonnick/node-html-to-image/commit/2b8da4ec59a070e0de8956a135bef9503c0d2040)] 130 | - 📝 Add related articles in the README ([#69](https://github.com/frinyvonnick/node-html-to-image/issues/69)) [[dd258dd](https://github.com/frinyvonnick/node-html-to-image/commit/dd258ddecf873c874c686e641050190b3b4f7cba)] 131 | - 📝 Add CODE_OF_CONDUCT.md file [[e8a6ff8](https://github.com/frinyvonnick/node-html-to-image/commit/e8a6ff84215895b78c249d1a2e643bab2102ec2c)] 132 | 133 | 134 | 135 | ## 3.1.0 (2020-09-21) 136 | 137 | ### Added 138 | 139 | - ✨ Add beforeScreenshot parameter ([#65](https://github.com/frinyvonnick/node-html-to-image/issues/65)) [[5fcb054](https://github.com/frinyvonnick/node-html-to-image/commit/5fcb054956efe102f0f37ee6e5d7d84947f30e6d)] 140 | - 👷‍♂️ Add a code analysis action ([#64](https://github.com/frinyvonnick/node-html-to-image/issues/64)) [[5946e1b](https://github.com/frinyvonnick/node-html-to-image/commit/5946e1b379e293bde1accdd50a2aa2b9689589cf)] 141 | - 👷‍♂️ Add a CI that launchs test script ([#63](https://github.com/frinyvonnick/node-html-to-image/issues/63)) [[04e0a4a](https://github.com/frinyvonnick/node-html-to-image/commit/04e0a4a2e6c35c9cd16ba7d64bd5cabf8f34a5b3)] 142 | 143 | ### Changed 144 | 145 | - 📌 Fix vulnerabilities in dependencies [[52ac3eb](https://github.com/frinyvonnick/node-html-to-image/commit/52ac3eb4b12c00a70a3002ae1abe61e85f549020)] 146 | - ⬆️ Upgrade dev dependencies [[a105ceb](https://github.com/frinyvonnick/node-html-to-image/commit/a105ceb2cfecc5568b31c1b60d3c8b1fc8aa06c0)] 147 | - ⬆️ Upgrade handlebars to 4.7.6 [[5bf8499](https://github.com/frinyvonnick/node-html-to-image/commit/5bf849928f1227d259105ba3c38bb26d5590a150)] 148 | - 🔧 Create FUNDING.yml [[e0fedcc](https://github.com/frinyvonnick/node-html-to-image/commit/e0fedccfcd0d875f1ac69013b6f312fe70498c59)] 149 | 150 | ### Fixed 151 | 152 | - ✏️ Fix typo in Typescript section [[879bccd](https://github.com/frinyvonnick/node-html-to-image/commit/879bccdf48de7069d761043f497f210f5d8fb393)] 153 | 154 | ### Miscellaneous 155 | 156 | - 📝 Update version number in README.md ([#66](https://github.com/frinyvonnick/node-html-to-image/issues/66)) [[be23aa7](https://github.com/frinyvonnick/node-html-to-image/commit/be23aa7f920efed9b02add714225b24c0de6903f)] 157 | 158 | 159 | 160 | ## 3.0.1 (2020-07-10) 161 | 162 | ### Added 163 | 164 | - ✅ Add jest retryTimes and timeout ([#44](https://github.com/frinyvonnick/node-html-to-image/issues/44)) [[85724cd](https://github.com/frinyvonnick/node-html-to-image/commit/85724cd5b4a64c85e64b8e1300406ca86513b6ce)] 165 | 166 | ### Miscellaneous 167 | 168 | - 🏷️ Add TypeScript types ([#45](https://github.com/frinyvonnick/node-html-to-image/issues/45)) [[ff5aa92](https://github.com/frinyvonnick/node-html-to-image/commit/ff5aa92d6aa350b9fe4c2f8360985d7f74478f6f)] 169 | - 📦 Clean published files ([#43](https://github.com/frinyvonnick/node-html-to-image/issues/43)) [[1163e55](https://github.com/frinyvonnick/node-html-to-image/commit/1163e5531e596d87e96b8e0a4ea133cd1a50445e)] 170 | 171 | 172 | 173 | ## 3.0.0 (2020-07-03) 174 | 175 | ### Added 176 | 177 | - ✨ Add the possibility to create multiple image in one call ([#38](https://github.com/frinyvonnick/node-html-to-image/issues/38)) [[fed3ee5](https://github.com/frinyvonnick/node-html-to-image/commit/fed3ee500edacf5c4af00624009978fdd41b5c2b)] 178 | 179 | ### Breaking changes 180 | 181 | - 💥 Set waitUntil default value to networkidle0 [[1436613](https://github.com/frinyvonnick/node-html-to-image/commit/1436613532f32ea01231112d802a9e041f5af7c4)] 182 | 183 | ### Fixed 184 | 185 | - 🐛 Pass waitUntil option to setContent method ([#40](https://github.com/frinyvonnick/node-html-to-image/issues/40)) [[ad69d33](https://github.com/frinyvonnick/node-html-to-image/commit/ad69d337f0fcd2726b3930972576eabcd328bcdb)] 186 | - ✏️ Fix typo in example ([#29](https://github.com/frinyvonnick/node-html-to-image/issues/29)) [[459f573](https://github.com/frinyvonnick/node-html-to-image/commit/459f573001c94ebfe85b87121197262f88689af0)] 187 | 188 | ### Miscellaneous 189 | 190 | - 📝 Add a synopsis in the usage section ([#41](https://github.com/frinyvonnick/node-html-to-image/issues/41)) [[c92d252](https://github.com/frinyvonnick/node-html-to-image/commit/c92d25265d0a623b7bba7a8b3e3a590d3c1dcfed)] 191 | 192 | 193 | 194 | ## 2.1.1 (2020-05-20) 195 | 196 | ### Removed 197 | 198 | - 🔥 Remove npm lockfile [[8a1b22f](https://github.com/frinyvonnick/node-html-to-image/commit/8a1b22fb85bc14bc53045f860dd5df57247353bb)] 199 | 200 | ### Fixed 201 | 202 | - 🐛 Fix issue related to default quality property with png type ([#28](https://github.com/frinyvonnick/node-html-to-image/issues/28)) [[cddf200](https://github.com/frinyvonnick/node-html-to-image/commit/cddf200dadf85eec6ff23a349ba5793187bc16f3)] 203 | - ✏️ Remove extra style tag in example ([#26](https://github.com/frinyvonnick/node-html-to-image/issues/26)) [[06f16e7](https://github.com/frinyvonnick/node-html-to-image/commit/06f16e791eb026460c11394387cab95aee3ba144)] 204 | 205 | 206 | 207 | ## 2.1.0 (2020-05-19) 208 | 209 | ### Added 210 | 211 | - ✨ Add the quality parameter for jpg images ([#22](https://github.com/frinyvonnick/node-html-to-image/issues/22)) [[a4069e5](https://github.com/frinyvonnick/node-html-to-image/commit/a4069e544310f7a2c4d80a103989e753230567f3)] 212 | 213 | ### Changed 214 | 215 | - 📌 Move gitmoji-changelog to dev dependencies ([#25](https://github.com/frinyvonnick/node-html-to-image/issues/25)) [[acfd889](https://github.com/frinyvonnick/node-html-to-image/commit/acfd889aa4761c7bedb9ee9b6e5fb9ffc0ef06d1)] 216 | 217 | 218 | 219 | ## 2.0.0 (2020-05-11) 220 | 221 | ### Added 222 | 223 | - ✨ Add encoding option to allow user to change default encoding ([#11](https://github.com/frinyvonnick/node-html-to-image/issues/11)) [[8dacb45](https://github.com/frinyvonnick/node-html-to-image/commit/8dacb452c563df2b97e09294d55b155cc0150734)] 224 | - ✨ Return the buffer from .screenshot() in case we don't want to save image ([#10](https://github.com/frinyvonnick/node-html-to-image/issues/10)) [[22d5085](https://github.com/frinyvonnick/node-html-to-image/commit/22d5085c59ca1be25e6ff712e06da430a7669066)] 225 | 226 | ### Changed 227 | 228 | - ⬆️ Bump acorn from 5.7.3 to 5.7.4 ([#7](https://github.com/frinyvonnick/node-html-to-image/issues/7)) [[22746df](https://github.com/frinyvonnick/node-html-to-image/commit/22746df0befaf6f00f0a96225f07160f97329831)] 229 | 230 | ### Breaking changes 231 | 232 | - 💥 Remove output requirement ([#16](https://github.com/frinyvonnick/node-html-to-image/issues/16)) [[3c11b84](https://github.com/frinyvonnick/node-html-to-image/commit/3c11b84a36d861251a798c98f8692757126d9f0e)] 233 | 234 | ### Removed 235 | 236 | - 🔥 Remove deprecated explanations in Run tests section [[bec08d6](https://github.com/frinyvonnick/node-html-to-image/commit/bec08d6ec467362e42f428c2db7eda960210e926)] 237 | 238 | ### Fixed 239 | 240 | - ✏️ Fix typo in properties table ([#15](https://github.com/frinyvonnick/node-html-to-image/issues/15)) [[df746df](https://github.com/frinyvonnick/node-html-to-image/commit/df746df38be782c348dd10dce83b55c0d2d85353)] 241 | 242 | ### Miscellaneous 243 | 244 | - 📝 Update documentation to make output optional [[d4dcf1e](https://github.com/frinyvonnick/node-html-to-image/commit/d4dcf1e720737445f5e10dc62346e591d4e3d636)] 245 | - 💡 Improve dealing with local images instructions ([#8](https://github.com/frinyvonnick/node-html-to-image/issues/8)) [[c73a79a](https://github.com/frinyvonnick/node-html-to-image/commit/c73a79a6cba7d9ef6ba815f93772b078fe8c3ae8)] 246 | 247 | 248 | 249 | ## 1.2.0 (2020-03-24) 250 | 251 | ### Added 252 | 253 | - ✨ Add transparent option to omit background ([#6](https://github.com/frinyvonnick/node-html-to-image/issues/6)) [[a63f0f2](https://github.com/frinyvonnick/node-html-to-image/commit/a63f0f2ce18f1a12e47f1dfa52765e905e175a9c)] 254 | 255 | ### Changed 256 | 257 | - ♻️ Use Tesseract.js to simplify installation [[afa5f46](https://github.com/frinyvonnick/node-html-to-image/commit/afa5f4645e75c8ca2d8fc50284de057381422022)] 258 | 259 | ### Miscellaneous 260 | 261 | - 📝 Add a section about dealing with images [[07cb135](https://github.com/frinyvonnick/node-html-to-image/commit/07cb135b2aab78d82370e5a417678fba4a2d3446)] 262 | - 📝 Add a section about output image resolution [[7ea6de7](https://github.com/frinyvonnick/node-html-to-image/commit/7ea6de72aa5df8d2ed26902fb8a8a60870d5af85)] 263 | 264 | 265 | 266 | ## 1.1.0 (2019-12-06) 267 | 268 | ### Added 269 | 270 | - ✨ Add waitUntil option [[a8f1b46](https://github.com/frinyvonnick/node-html-to-image/commit/a8f1b46c7ab702553f66c3d6a26adec6b7f05a8c)] 271 | 272 | ### Miscellaneous 273 | 274 | - 📝 Add a mention to the cli [[bebd0f6](https://github.com/frinyvonnick/node-html-to-image/commit/bebd0f6211fcacca307949670d0eb9f4954f7e46)] 275 | - 📝 Fix examples [[2b1879b](https://github.com/frinyvonnick/node-html-to-image/commit/2b1879b796d61873be6957c37e7aab084c045112)] 276 | 277 | 278 | 279 | ## 1.0.0 (2019-12-05) 280 | 281 | ### Added 282 | 283 | - ✨ Implement a function that generates an image from html ([#1](https://github.com/frinyvonnick/node-html-to-image/issues/1)) [[2de2304](https://github.com/frinyvonnick/node-html-to-image/commit/2de23044e18fda2e1bcb4681be9555c078cce421)] 284 | 285 | ### Miscellaneous 286 | 287 | - 📝 Improve examples and add information about handlebars [[b4d2274](https://github.com/frinyvonnick/node-html-to-image/commit/b4d22742ab07169a7ded87b084493479bbbc32c0)] 288 | - 📝 Change emoji in title [[2ea3e7c](https://github.com/frinyvonnick/node-html-to-image/commit/2ea3e7cf3c89e3c491b554fbf729279c4946c794)] 289 | - 📝 Add missing comma in handlebars example [[2dc3924](https://github.com/frinyvonnick/node-html-to-image/commit/2dc39247d3ce80b8df1b5b737506e42ca5bf05cf)] 290 | - Initial commit [[d75796d](https://github.com/frinyvonnick/node-html-to-image/commit/d75796d6e9908eedff32484eb416f56e92a0a6fe)] 291 | 292 | 293 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at frin.yvonnick@gmail.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2021 Yvonnick Frin 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

Welcome to node-html-to-image 🌄

2 |

3 | Version 4 | 5 | Documentation 6 | 7 | 8 | License: Apache--2.0 9 | 10 | 11 | Twitter: yvonnickfrin 12 | 13 |

14 | 15 | > A Node.js library that generates images from HTML 16 | 17 | ### 🏠 [Homepage](https://github.com/frinyvonnick/node-html-to-image) 18 | 19 | 20 | ## Description 21 | 22 | This module exposes a function that generates images (png, jpeg) from HTML. It uses [puppeteer](https://github.com/puppeteer) in headless mode to achieve it. Additionally, it embarks [Handlebars](https://handlebarsjs.com/) to provide a way to add logic in your HTML. 23 | 24 | ## Install 25 | 26 | ```sh 27 | npm install node-html-to-image 28 | # or 29 | yarn add node-html-to-image 30 | ``` 31 | 32 | Note: When you install Puppeteer, it downloads a recent version of Chromium (~170MB Mac, ~282MB Linux, ~280MB Win) that is guaranteed to work with the API. 33 | 34 | ## Usage 35 | 36 | - [Simple example](#simple-example) 37 | - [TypeScript Support](#typescript-support) 38 | - [Options](#options) 39 | - [Setting output image resolution](#setting-output-image-resolution) 40 | - [Example with Handlebars](#example-with-handlebars) 41 | - [Using Handlebars helpers](#using-handlebars-helpers) 42 | - [Dealing with images](#dealing-with-images) 43 | - [Using the buffer instead of saving to disk](#using-the-buffer-instead-of-saving-to-disk) 44 | - [Generating multiple images](#generating-multiple-images) 45 | - [Using different puppeteer libraries](#using-different-puppeteer-libraries) 46 | 47 | ### Simple example 48 | 49 | ```js 50 | const nodeHtmlToImage = require('node-html-to-image') 51 | 52 | nodeHtmlToImage({ 53 | output: './image.png', 54 | html: 'Hello world!' 55 | }) 56 | .then(() => console.log('The image was created successfully!')) 57 | ``` 58 | 59 | ### TypeScript support 60 | 61 | The library is written in Typescript so it is available out of the box: 62 | 63 | ```ts 64 | import nodeHtmlToImage from 'node-html-to-image' 65 | ``` 66 | 67 | ### Options 68 | 69 | List of all available options: 70 | 71 | | option | description | type | required | 72 | |-------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------|-------------| 73 | | output | The ouput path for generated image | string | optional | 74 | | html | The html used to generate image content | string | required | 75 | | type | The type of the generated image | jpeg or png (default: png) | optional | 76 | | quality | The quality of the generated image (only applicable to jpg) | number (default: 80) | optional | 77 | | content | If provided html property is considered an handlebars template and use content value to fill it | object or Array | optional | 78 | | waitUntil | Define when to consider markup succeded. [Learn more](https://github.com/puppeteer/puppeteer/blob/8370ec88ae94fa59d9e9dc0c154e48527d48c9fe/docs/api.md#pagesetcontenthtml-options). | string or Array (default: networkidle0) | optional | 79 | | puppeteer | The puppeteer property let you use a different puppeteer library (like puppeteer-core or puppeteer-extra). | object (default: puppeteer) | optional | 80 | | puppeteerArgs | The puppeteerArgs property let you pass down custom configuration to puppeteer. [Learn more](https://github.com/puppeteer/puppeteer/blob/8370ec88ae94fa59d9e9dc0c154e48527d48c9fe/docs/api.md#puppeteerlaunchoptions). | object | optional | 81 | | beforeScreenshot | An async function that will execute just before screenshot is taken. Gives access to puppeteer page element. | Function | optional | 82 | | transparent | The transparent property lets you generate images with transparent background (for png type). | boolean | optional | 83 | | encoding | The encoding property of the image. Options are `binary` (default) or `base64`. | string | optional | 84 | | selector | The selector property lets you target a specific element to perform the screenshot on. (default `body`) | string | optional | 85 | | handlebarsHelpers | The handlebarsHelpers property lets add custom logic to the templates using Handlebars sub-expressions. [Learn more](https://handlebarsjs.com/guide/builtin-helpers.html#sub-expressions). | object | optional | 86 | | timeout | Timeout for a [puppeteer-cluster](https://github.com/thomasdondorf/puppeteer-cluster#clusterlaunchoptions) (in `ms`). Defaults to `30000` (30 seconds). | number | optional | 87 | 88 | 89 | ### Setting output image resolution 90 | 91 | `node-html-to-image` takes a screenshot of the body tag's content. If you want to set output image's resolution you need to set its dimension using CSS like in the following example. 92 | 93 | ```js 94 | const nodeHtmlToImage = require('node-html-to-image') 95 | 96 | nodeHtmlToImage({ 97 | output: './image.png', 98 | html: ` 99 | 100 | 106 | 107 | Hello world! 108 | 109 | ` 110 | }) 111 | .then(() => console.log('The image was created successfully!')) 112 | ``` 113 | 114 | ### Example with Handlebars 115 | 116 | [Handlerbars](https://handlebarsjs.com/) is a templating language. It generates HTML from a template and an input object. In the following example we provide a template to `node-html-to-image` and a content object to fill the template. 117 | 118 | ```js 119 | const nodeHtmlToImage = require('node-html-to-image') 120 | 121 | nodeHtmlToImage({ 122 | output: './image.png', 123 | html: 'Hello {{name}}!', 124 | content: { name: 'you' } 125 | }) 126 | .then(() => console.log('The image was created successfully!')) 127 | ``` 128 | 129 | [Handlebars](https://handlebarsjs.com/) provides a lot of expressions to handle common use cases like conditions or loops. 130 | 131 | 132 | ### Using Handlebars helpers 133 | 134 | [Handlerbars sub-expressions](https://handlebarsjs.com/guide/builtin-helpers.html#sub-expressions) can be used to add custom logic to the templates. To do this, you must pass a `handlebarsHelpers` object with functions defined within. 135 | 136 | For example, if you had a variable and wanted to do some conditional rendering depending on its value, you could do this: 137 | 138 | ```js 139 | const nodeHtmlToImage = require('node-html-to-image') 140 | 141 | nodeHtmlToImage({ 142 | output: './image.png', 143 | content: { myVar: 'foo' }, 144 | handlebarsHelpers: { 145 | equals: (a, b) => a === b, 146 | }, 147 | html: ` 148 | 149 | 150 | {{#if (equals myVar 'foo')}}
Foo
{{/if}} 151 | {{#if (equals myVar 'bar')}}
Bar
{{/if}} 152 | 153 | ` 154 | 155 | }) 156 | ``` 157 | 158 | ### Dealing with images 159 | 160 | If you want to display an image which is stored remotely do it as usual. In case your image is stored locally I recommend having your image in `base64`. Then you need to pass it to the template with the content property. Here is an example: 161 | 162 | ```js 163 | const nodeHtmlToImage = require('node-html-to-image') 164 | const fs = require('fs'); 165 | 166 | const image = fs.readFileSync('./image.jpg'); 167 | const base64Image = new Buffer.from(image).toString('base64'); 168 | const dataURI = 'data:image/jpeg;base64,' + base64Image 169 | 170 | nodeHtmlToImage({ 171 | output: './image.png', 172 | html: '', 173 | content: { imageSource: dataURI } 174 | }) 175 | ``` 176 | ### Dealing with fonts 177 | If you want to apply fonts, you need to synchronize your parts loading of your website. One way doing it is to convert your font to base64 and add it to your style in your html. For example: 178 | ```js 179 | const font2base64 = require('node-font2base64') 180 | 181 | const _data = font2base64.encodeToDataUrlSync('../my/awesome/font.ttf') 182 | 183 | const html = ` 184 | 185 | 186 | 192 | 193 | ... 194 | ``` 195 | 196 | ### Using the buffer instead of saving to disk 197 | 198 | If you don't want to save the image to disk and would rather do something with it immediately, you can use the returned value instead! The example below shows how you can generate an image and send it back to a client via using [express](https://github.com/expressjs/express). 199 | 200 | ```js 201 | const express = require('express'); 202 | const router = express.Router(); 203 | const nodeHtmlToImage = require('node-html-to-image'); 204 | 205 | router.get(`/api/tweet/render`, async function(req, res) { 206 | const image = await nodeHtmlToImage({ 207 | html: '
Check out what I just did! #cool
' 208 | }); 209 | res.writeHead(200, { 'Content-Type': 'image/png' }); 210 | res.end(image, 'binary'); 211 | }); 212 | ``` 213 | 214 | ### Generating multiple images 215 | 216 | If you want to generate multiple images in one call you must provide an array to the content property. 217 | 218 | #### Saving to disk 219 | 220 | To save on the disk you must provide the output property on each object in the content property. 221 | 222 | ```js 223 | nodeHtmlToImage({ 224 | html: 'Hello {{name}}!', 225 | content: [{ name: 'Pierre', output: './image1.png' }, { name: 'Paul', output: './image2.png' }, { name: 'Jacques', output: './image3.png' }] 226 | }) 227 | .then(() => console.log('The images were created successfully!')) 228 | ``` 229 | 230 | #### Using buffers 231 | 232 | If you don't want to save the images to disk you can use the returned value instead. It returns an array of Buffer objects. 233 | 234 | ```js 235 | const images = await nodeHtmlToImage({ 236 | html: 'Hello {{name}}!', 237 | content: [{ name: 'Pierre' }, { name: 'Paul' }, { name: 'Jacques' }] 238 | }) 239 | ``` 240 | 241 | ### Using different puppeteer libraries 242 | 243 | If you want to use different puppeteer library you must provide the puppeteer property. 244 | 245 | ```js 246 | const chrome = require('chrome-aws-lambda'); 247 | const nodeHtmlToImage = require('node-html-to-image') 248 | const puppeteerCore = require('puppeteer-core'); 249 | 250 | const image = await nodeHtmlToImage({ 251 | html: '
Hello
', 252 | puppeteer: puppeteerCore, 253 | puppeteerArgs: { 254 | args: chromium.args, 255 | executablePath: await chrome.executablePath, 256 | } 257 | }) 258 | ``` 259 | 260 | ## Related 261 | 262 | ### Libraries 263 | 264 | - [node-html-to-image-cli](https://github.com/frinyvonnick/node-html-to-image-cli) - CLI for this module 265 | 266 | ### Articles 267 | 268 | - [Generate images from HTML in Node.js](https://yvonnickfrin.dev/node-html-to-image) 269 | - [node-html-to-image v1.2 is out 🎉](https://dev.to/yvonnickfrin/node-html-to-image-v1-2-is-out-42f4) 270 | 271 | ## Run tests 272 | 273 | ```sh 274 | yarn test 275 | ``` 276 | 277 | ## Author 278 | 279 | 👤 **FRIN Yvonnick ** 280 | 281 | * Website: [https://yvonnickfrin.dev](https://yvonnickfrin.dev) 282 | * Twitter: [@yvonnickfrin](https://twitter.com/yvonnickfrin) 283 | * Github: [@frinyvonnick](https://github.com/frinyvonnick) 284 | 285 | ## 🤝 Contributing 286 | 287 | Contributions, issues and feature requests are welcome!
Feel free to check [issues page](https://github.com/frinyvonnick/node-html-to-image/issues). 288 | 289 | ## Show your support 290 | 291 | Give a ⭐️ if this project helped you! 292 | 293 | ## 📝 License 294 | 295 | Copyright © 2019 [FRIN Yvonnick ](https://github.com/frinyvonnick).
296 | This project is [Apache--2.0](https://github.com/frinyvonnick/node-html-to-image/blob/master/LICENSE) licensed. 297 | 298 | *** 299 | _This README was generated with ❤️ by [readme-md-generator](https://github.com/kefranabg/readme-md-generator)_ 300 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: [ 3 | ["@babel/preset-env", { targets: { node: "current" } }], 4 | "@babel/preset-typescript", 5 | ], 6 | }; 7 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | // For a detailed explanation regarding each configuration property, visit: 2 | // https://jestjs.io/docs/en/configuration.html 3 | 4 | module.exports = { 5 | // All imported modules in your tests should be mocked automatically 6 | // automock: false, 7 | 8 | // Stop running tests after `n` failures 9 | // bail: 0, 10 | 11 | // Respect "browser" field in package.json when resolving modules 12 | // browser: false, 13 | 14 | // The directory where Jest should store its cached dependency information 15 | // cacheDirectory: "/private/var/folders/1q/0np81g6s3_96sm16tljnhcfh0000gn/T/jest_dx", 16 | 17 | // Automatically clear mock calls and instances between every test 18 | clearMocks: true, 19 | 20 | // Indicates whether the coverage information should be collected while executing the test 21 | // collectCoverage: false, 22 | 23 | // An array of glob patterns indicating a set of files for which coverage information should be collected 24 | // collectCoverageFrom: null, 25 | 26 | // The directory where Jest should output its coverage files 27 | coverageDirectory: "coverage", 28 | 29 | // An array of regexp pattern strings used to skip coverage collection 30 | // coveragePathIgnorePatterns: [ 31 | // "/node_modules/" 32 | // ], 33 | 34 | // A list of reporter names that Jest uses when writing coverage reports 35 | // coverageReporters: [ 36 | // "json", 37 | // "text", 38 | // "lcov", 39 | // "clover" 40 | // ], 41 | 42 | // An object that configures minimum threshold enforcement for coverage results 43 | // coverageThreshold: null, 44 | 45 | // A path to a custom dependency extractor 46 | // dependencyExtractor: null, 47 | 48 | // Make calling deprecated APIs throw helpful error messages 49 | // errorOnDeprecated: false, 50 | 51 | // Force coverage collection from ignored files using an array of glob patterns 52 | // forceCoverageMatch: [], 53 | 54 | // A path to a module which exports an async function that is triggered once before all test suites 55 | // globalSetup: null, 56 | 57 | // A path to a module which exports an async function that is triggered once after all test suites 58 | // globalTeardown: null, 59 | 60 | // A set of global variables that need to be available in all test environments 61 | // globals: {}, 62 | 63 | // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. 64 | // maxWorkers: "50%", 65 | 66 | // An array of directory names to be searched recursively up from the requiring module's location 67 | // moduleDirectories: [ 68 | // "node_modules" 69 | // ], 70 | 71 | // An array of file extensions your modules use 72 | // moduleFileExtensions: [ 73 | // "js", 74 | // "json", 75 | // "jsx", 76 | // "ts", 77 | // "tsx", 78 | // "node" 79 | // ], 80 | 81 | // A map from regular expressions to module names that allow to stub out resources with a single module 82 | // moduleNameMapper: {}, 83 | 84 | // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader 85 | // modulePathIgnorePatterns: [], 86 | 87 | // Activates notifications for test results 88 | // notify: false, 89 | 90 | // An enum that specifies notification mode. Requires { notify: true } 91 | // notifyMode: "failure-change", 92 | 93 | // A preset that is used as a base for Jest's configuration 94 | // preset: null, 95 | 96 | // Run tests from one or more projects 97 | // projects: null, 98 | 99 | // Use this configuration option to add custom reporters to Jest 100 | // reporters: undefined, 101 | 102 | // Automatically reset mock state between every test 103 | // resetMocks: false, 104 | 105 | // Reset the module registry before running each individual test 106 | // resetModules: false, 107 | 108 | // A path to a custom resolver 109 | // resolver: null, 110 | 111 | // Automatically restore mock state between every test 112 | // restoreMocks: false, 113 | 114 | // The root directory that Jest should scan for tests and modules within 115 | // rootDir: null, 116 | 117 | // A list of paths to directories that Jest should use to search for files in 118 | // roots: [ 119 | // "" 120 | // ], 121 | 122 | // Allows you to use a custom runner instead of Jest's default test runner 123 | // runner: "jest-runner", 124 | 125 | // The paths to modules that run some code to configure or set up the testing environment before each test 126 | // setupFiles: [], 127 | 128 | // A list of paths to modules that run some code to configure or set up the testing framework before each test 129 | setupFilesAfterEnv: ["/jest.setup.js"], 130 | 131 | // A list of paths to snapshot serializer modules Jest should use for snapshot testing 132 | // snapshotSerializers: [], 133 | 134 | // The test environment that will be used for testing 135 | testEnvironment: "node", 136 | 137 | // Options that will be passed to the testEnvironment 138 | // testEnvironmentOptions: {}, 139 | 140 | // Adds a location field to test results 141 | // testLocationInResults: false, 142 | 143 | // The glob patterns Jest uses to detect test files 144 | // testMatch: [ 145 | // "**/__tests__/**/*.[jt]s?(x)", 146 | // "**/?(*.)+(spec|test).[tj]s?(x)" 147 | // ], 148 | 149 | // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped 150 | // testPathIgnorePatterns: [ 151 | // "/node_modules/" 152 | // ], 153 | 154 | // The regexp pattern or array of patterns that Jest uses to detect test files 155 | // testRegex: [], 156 | 157 | // This option allows the use of a custom results processor 158 | // testResultsProcessor: null, 159 | 160 | // This option allows use of a custom test runner 161 | testRunner: "jest-circus/runner" 162 | 163 | // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href 164 | // testURL: "http://localhost", 165 | 166 | // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout" 167 | // timers: "real", 168 | 169 | // A map from regular expressions to paths to transformers 170 | // transform: null, 171 | 172 | // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation 173 | // transformIgnorePatterns: [ 174 | // "/node_modules/" 175 | // ], 176 | 177 | // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them 178 | // unmockedModulePathPatterns: undefined, 179 | 180 | // Indicates whether each individual test should be reported during the run 181 | // verbose: null, 182 | 183 | // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode 184 | // watchPathIgnorePatterns: [], 185 | 186 | // Whether to use watchman for file crawling 187 | // watchman: true, 188 | }; 189 | -------------------------------------------------------------------------------- /jest.setup.js: -------------------------------------------------------------------------------- 1 | // Set the timeout to 1 minute to allow Tessarect plenty of time to run 2 | jest.setTimeout(1000 * 60); 3 | 4 | // Retry failed twice just in case Tessarect still fails 5 | jest.retryTimes(2); -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-html-to-image", 3 | "version": "5.0.0", 4 | "description": "A Node.js library that generates images from HTML", 5 | "main": "dist/index.js", 6 | "types": "dist/index.d.ts", 7 | "repository": "git@github.com:frinyvonnick/node-html-to-image.git", 8 | "author": "FRIN Yvonnick ", 9 | "license": "Apache-2.0", 10 | "dependencies": { 11 | "handlebars": "4.7.8", 12 | "puppeteer": "23.2.2", 13 | "puppeteer-cluster": "0.24.0" 14 | }, 15 | "scripts": { 16 | "test": "jest", 17 | "lint": "eslint ./src", 18 | "build": "tsc" 19 | }, 20 | "files": [ 21 | "src", 22 | "types", 23 | "!src/*.spec.js" 24 | ], 25 | "devDependencies": { 26 | "@babel/core": "^7.18.6", 27 | "@babel/preset-env": "^7.18.6", 28 | "@babel/preset-typescript": "^7.18.6", 29 | "@types/jest": "^28.1.4", 30 | "@types/node": "^16.11.43", 31 | "@typescript-eslint/eslint-plugin": "^5.30.4", 32 | "@typescript-eslint/parser": "^5.30.4", 33 | "eslint": "^8.19.0", 34 | "gitmoji-changelog": "2.3.0", 35 | "jest": "^28.1.2", 36 | "jest-circus": "^28.1.2", 37 | "puppeteer-core": "23.2.2", 38 | "rimraf": "^3.0.2", 39 | "tesseract.js": "4.1.1", 40 | "typescript": "^4.7.4" 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { nodeHtmlToImage } from "./main"; 2 | 3 | /* 4 | * The following code is for interop between CommonJS and ESModule 5 | */ 6 | /* eslint-disable @typescript-eslint/ban-ts-comment */ 7 | // @ts-ignore 8 | nodeHtmlToImage.default = nodeHtmlToImage; 9 | // @ts-ignore 10 | nodeHtmlToImage.__esModule = true; 11 | /* eslint-enable @typescript-eslint/ban-ts-comment */ 12 | export = nodeHtmlToImage; 13 | -------------------------------------------------------------------------------- /src/main.integration.spec.ts: -------------------------------------------------------------------------------- 1 | import { existsSync, mkdirSync, readdirSync } from "fs"; 2 | import puppeteer from "puppeteer"; 3 | import puppeteerCore from "puppeteer-core"; 4 | import rimraf from "rimraf"; 5 | import { createWorker } from "tesseract.js"; 6 | 7 | import { nodeHtmlToImage } from "./main"; 8 | 9 | describe("node-html-to-image", () => { 10 | let mockExit; 11 | let mockConsoleErr; 12 | const originalConsoleError = console.error; 13 | beforeEach(() => { 14 | rimraf.sync("./generated"); 15 | mkdirSync("./generated"); 16 | mockExit = jest.spyOn(process, "exit").mockImplementation((number) => { 17 | throw new Error("process.exit: " + number); 18 | }); 19 | mockConsoleErr = jest 20 | .spyOn(console, "error") 21 | .mockImplementation((value) => originalConsoleError(value)); 22 | }); 23 | 24 | afterEach(() => { 25 | mockExit.mockRestore(); 26 | mockConsoleErr.mockRestore(); 27 | }); 28 | 29 | afterAll(() => { 30 | rimraf.sync("./generated"); 31 | }); 32 | describe("error", () => { 33 | it("should stop the program properly", async () => { 34 | /* eslint-disable @typescript-eslint/ban-ts-comment */ 35 | await expect(async () => { 36 | await nodeHtmlToImage({ 37 | html: "", 38 | type: "jpeg", 39 | // @ts-ignore 40 | quality: "wrong value", 41 | }); 42 | }).rejects.toThrow(); 43 | 44 | expect(mockExit).toHaveBeenCalledWith(1); 45 | /* eslint-enable @typescript-eslint/ban-ts-comment */ 46 | }); 47 | }); 48 | 49 | describe("single image", () => { 50 | it("should generate output file", async () => { 51 | await nodeHtmlToImage({ 52 | output: "./generated/image.png", 53 | html: "", 54 | }); 55 | 56 | expect(existsSync("./generated/image.png")).toBe(true); 57 | }); 58 | 59 | it("should return a buffer", async () => { 60 | const result = await nodeHtmlToImage({ 61 | html: "", 62 | }); 63 | 64 | expect(result).toBeInstanceOf(Buffer); 65 | }); 66 | 67 | it("should throw an error if html is not provided", async () => { 68 | await expect(async () => { 69 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment 70 | // @ts-ignore 71 | await nodeHtmlToImage({ 72 | output: "./generated/image.png", 73 | }); 74 | }).rejects.toThrow(); 75 | expect(mockConsoleErr).toHaveBeenCalledWith( 76 | new Error("You must provide an html property.") 77 | ); 78 | }); 79 | 80 | it("should throw timeout error", async () => { 81 | await expect(async () => { 82 | await nodeHtmlToImage({ 83 | timeout: 500, 84 | html: "" 85 | }); 86 | }).rejects.toThrow(); 87 | expect(mockConsoleErr).toHaveBeenCalledWith( 88 | new Error("Timeout hit: 500") 89 | ); 90 | }); 91 | 92 | it("should generate an jpeg image", async () => { 93 | await nodeHtmlToImage({ 94 | output: "./generated/image.jpg", 95 | html: "", 96 | type: "jpeg", 97 | }); 98 | 99 | expect(existsSync("./generated/image.jpg")).toBe(true); 100 | }); 101 | 102 | it("should put html in output file", async () => { 103 | await nodeHtmlToImage({ 104 | output: "./generated/image.png", 105 | html: "Hello world!", 106 | }); 107 | 108 | const text = await getTextFromImage("./generated/image.png"); 109 | expect(text.trim()).toBe("Hello world!"); 110 | }); 111 | 112 | it("should use handlebars to customize content", async () => { 113 | await nodeHtmlToImage({ 114 | output: "./generated/image.png", 115 | html: "Hello {{name}}!", 116 | content: { name: "Yvonnick" }, 117 | }); 118 | 119 | const text = await getTextFromImage("./generated/image.png"); 120 | expect(text.trim()).toBe("Hello Yvonnick!"); 121 | }); 122 | 123 | it("should create selected element image", async () => { 124 | await nodeHtmlToImage({ 125 | output: "./generated/image.png", 126 | html: 'Hello
{{name}}!
', 127 | content: { name: "Sangwoo" }, 128 | selector: "div#section", 129 | }); 130 | 131 | const text = await getTextFromImage("./generated/image.png"); 132 | expect(text.trim()).toBe("Sangwoo!"); 133 | }); 134 | }); 135 | 136 | describe("batch", () => { 137 | it("should create two images", async () => { 138 | await nodeHtmlToImage({ 139 | type: "png", 140 | quality: 300, 141 | html: "Hello {{name}}!", 142 | content: [ 143 | { name: "Yvonnick", output: "./generated/image1.png" }, 144 | { name: "World", output: "./generated/image2.png" }, 145 | ], 146 | }); 147 | 148 | const text1 = await getTextFromImage("./generated/image1.png"); 149 | expect(text1.trim()).toBe("Hello Yvonnick!"); 150 | 151 | const text2 = await getTextFromImage("./generated/image2.png"); 152 | expect(text2.trim()).toBe("Hello World!"); 153 | }); 154 | 155 | it("should return two buffers", async () => { 156 | const result = await nodeHtmlToImage({ 157 | type: "png", 158 | quality: 300, 159 | html: "Hello {{name}}!", 160 | content: [{ name: "Yvonnick" }, { name: "World" }], 161 | }); 162 | 163 | expect(result?.[0]).toBeInstanceOf(Buffer); 164 | expect(result?.[1]).toBeInstanceOf(Buffer); 165 | }); 166 | 167 | it("should create selected elements images", async () => { 168 | await nodeHtmlToImage({ 169 | html: 'Hello
{{name}}!
World!
', 170 | content: [ 171 | { 172 | name: "Sangwoo", 173 | output: "./generated/image1.png", 174 | selector: "div#section1", 175 | }, 176 | { output: "./generated/image2.png", selector: "div#section2" }, 177 | ], 178 | }); 179 | 180 | const text1 = await getTextFromImage("./generated/image1.png"); 181 | expect(text1.trim()).toBe("Sangwoo!"); 182 | const text2 = await getTextFromImage("./generated/image2.png"); 183 | expect(text2.trim()).toBe("World!"); 184 | }); 185 | 186 | it.skip("should handle mass volume well", async () => { 187 | jest.setTimeout(60000 * 60); 188 | expect.hasAssertions(); 189 | const NUMBER_OF_IMAGES = 2000; 190 | const content = Array.from(Array(NUMBER_OF_IMAGES), (_, i) => ({ 191 | name: i, 192 | output: `./generated/${i}.jpg`, 193 | })); 194 | 195 | await nodeHtmlToImage({ 196 | type: "png", 197 | quality: 300, 198 | html: "Hello {{name}}!", 199 | content, 200 | }); 201 | 202 | expect(readdirSync("./generated")).toHaveLength(NUMBER_OF_IMAGES); 203 | }); 204 | }); 205 | describe("different instance", () => { 206 | it("should pass puppeteer instance and generate image", async () => { 207 | const executablePath = puppeteer.executablePath(); 208 | 209 | await nodeHtmlToImage({ 210 | output: "./generated/image.png", 211 | html: "", 212 | puppeteerArgs: { executablePath }, 213 | puppeteer: puppeteerCore, 214 | }); 215 | 216 | expect(existsSync("./generated/image.png")).toBe(true); 217 | }); 218 | 219 | it("should throw an error if executablePath is not provided", async () => { 220 | await expect(async () => { 221 | await nodeHtmlToImage({ 222 | output: "./generated/image.png", 223 | html: "", 224 | puppeteer: puppeteerCore, 225 | }); 226 | }).rejects.toThrow(); 227 | }); 228 | }); 229 | }); 230 | 231 | async function getTextFromImage(path) { 232 | const worker = await createWorker(); 233 | await worker.loadLanguage("eng"); 234 | await worker.initialize("eng"); 235 | 236 | const { 237 | data: { text }, 238 | } = await worker.recognize(path); 239 | await worker.terminate(); 240 | 241 | return text; 242 | } 243 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { Cluster } from "puppeteer-cluster"; 2 | 3 | import { Screenshot } from "./models/Screenshot"; 4 | import { makeScreenshot } from "./screenshot"; 5 | import { Options, ScreenshotParams } from "./types"; 6 | 7 | export async function nodeHtmlToImage(options: Options) { 8 | const { 9 | html, 10 | encoding, 11 | transparent, 12 | content, 13 | output, 14 | selector, 15 | type, 16 | quality, 17 | puppeteerArgs = {}, 18 | timeout = 30000, 19 | puppeteer = undefined, 20 | } = options; 21 | 22 | const cluster: Cluster = await Cluster.launch({ 23 | concurrency: Cluster.CONCURRENCY_CONTEXT, 24 | maxConcurrency: 2, 25 | timeout, 26 | puppeteerOptions: { ...puppeteerArgs, headless: "shell" }, 27 | puppeteer: puppeteer, 28 | }); 29 | 30 | const shouldBatch = Array.isArray(content); 31 | const contents = shouldBatch ? content : [{ ...content, output, selector }]; 32 | 33 | try { 34 | const screenshots: Array = await Promise.all( 35 | contents.map((content) => { 36 | const { output, selector: contentSelector, ...pageContent } = content; 37 | return cluster.execute( 38 | { 39 | html, 40 | encoding, 41 | transparent, 42 | output, 43 | content: pageContent, 44 | selector: contentSelector ? contentSelector : selector, 45 | type, 46 | quality, 47 | }, 48 | async ({ page, data }) => { 49 | const screenshot = await makeScreenshot(page, { 50 | ...options, 51 | screenshot: new Screenshot(data), 52 | }); 53 | return screenshot; 54 | }, 55 | ); 56 | }), 57 | ); 58 | await cluster.idle(); 59 | await cluster.close(); 60 | 61 | return shouldBatch 62 | ? screenshots.map(({ buffer }) => buffer) 63 | : screenshots[0].buffer; 64 | } catch (err) { 65 | console.error(err); 66 | await cluster.close(); 67 | process.exit(1); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main.unit.spec.ts: -------------------------------------------------------------------------------- 1 | import { nodeHtmlToImage } from "./main"; 2 | import { Cluster } from "puppeteer-cluster"; 3 | 4 | import { Screenshot } from "./models/Screenshot"; 5 | 6 | const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); 7 | 8 | describe("node-html-to-image | Unit", () => { 9 | let mockExit; 10 | let launchMock; 11 | const buffer1 = Buffer.alloc(1); 12 | const buffer2 = Buffer.alloc(1); 13 | const html = "{{message}}"; 14 | 15 | beforeEach(() => { 16 | launchMock = jest.spyOn(Cluster, "launch").mockImplementation( 17 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment 18 | // @ts-ignore 19 | jest.fn(() => ({ 20 | execute: jest 21 | .fn() 22 | .mockImplementationOnce(async () => { 23 | const screenshot = new Screenshot({ html }); 24 | screenshot.setBuffer(buffer1); 25 | await sleep(10); 26 | return screenshot; 27 | }) 28 | .mockImplementationOnce(() => { 29 | const screenshot = new Screenshot({ html }); 30 | screenshot.setBuffer(buffer2); 31 | return screenshot; 32 | }), 33 | idle: jest.fn(), 34 | close: jest.fn(), 35 | })) 36 | ); 37 | mockExit = jest.spyOn(process, "exit").mockImplementation((number) => { 38 | throw new Error("process.exit: " + number); 39 | }); 40 | }); 41 | 42 | afterEach(() => { 43 | mockExit.mockRestore(); 44 | }); 45 | 46 | it("should sort buffer in the right order", async () => { 47 | const result = await nodeHtmlToImage({ 48 | html, 49 | content: [{ message: "Hello world!" }, { message: "Bonjour monde!" }], 50 | }); 51 | 52 | expect(result).toEqual([buffer1, buffer2]); 53 | }); 54 | 55 | it("should pass 'timeout' to 'puppeteer-cluster' via options", async () => { 56 | const CLUSTER_TIMEOUT = 60 * 1000; 57 | await nodeHtmlToImage({ 58 | html, 59 | timeout: CLUSTER_TIMEOUT, 60 | }); 61 | 62 | expect(launchMock).toHaveBeenCalledWith(expect.objectContaining({ timeout: CLUSTER_TIMEOUT })) 63 | }); 64 | }); 65 | 66 | jest.mock("puppeteer-cluster"); 67 | -------------------------------------------------------------------------------- /src/models/Screenshot.spec.ts: -------------------------------------------------------------------------------- 1 | import { describe } from "jest-circus"; 2 | import { Screenshot } from "./Screenshot"; 3 | 4 | describe("Screenshot", () => { 5 | const html = "Hello world!"; 6 | 7 | it("should create a minimal Screenshot", () => { 8 | const screenshot = new Screenshot({ 9 | html, 10 | }); 11 | 12 | expect(screenshot.html).toEqual(html); 13 | }); 14 | 15 | it("should store buffer", () => { 16 | const screenshot = new Screenshot({ 17 | html, 18 | }); 19 | 20 | const expectedBuffer = Buffer.alloc(1); 21 | 22 | screenshot.setBuffer(expectedBuffer); 23 | 24 | expect(screenshot.buffer).toEqual(expectedBuffer); 25 | }); 26 | 27 | it("should set html", () => { 28 | const screenshot = new Screenshot({ 29 | html, 30 | }); 31 | 32 | const expectedHtml = "
Hello
"; 33 | 34 | screenshot.setHTML(expectedHtml); 35 | 36 | expect(screenshot.html).toEqual(expectedHtml); 37 | }); 38 | 39 | it("should throw an error when setting html with nothing", () => { 40 | const screenshot = new Screenshot({ 41 | html, 42 | }); 43 | 44 | expect(() => { 45 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment 46 | // @ts-ignore 47 | screenshot.setHTML(); 48 | }).toThrow("You must provide an html property."); 49 | 50 | expect(screenshot.html).toEqual(html); 51 | }); 52 | 53 | it("should throw an error when setting html with null", () => { 54 | const screenshot = new Screenshot({ 55 | html, 56 | }); 57 | 58 | expect(() => { 59 | screenshot.setHTML(null); 60 | }).toThrow("You must provide an html property."); 61 | 62 | expect(screenshot.html).toEqual(html); 63 | }); 64 | 65 | it("should throw an error when setting html with empty string", () => { 66 | const screenshot = new Screenshot({ 67 | html, 68 | }); 69 | 70 | expect(() => { 71 | screenshot.setHTML(""); 72 | }).toThrow("You must provide an html property."); 73 | 74 | expect(screenshot.html).toEqual(html); 75 | }); 76 | 77 | it("should create a Screenshot with a few attributes", () => { 78 | const attributes = { 79 | html, 80 | output: "something", 81 | content: { hello: "Salut" }, 82 | encoding: "base64", 83 | } as const; 84 | const screenshot = new Screenshot(attributes); 85 | 86 | expect(screenshot).toEqual({ 87 | ...attributes, 88 | transparent: false, 89 | selector: "body", 90 | type: "png", 91 | }); 92 | }); 93 | 94 | it("should create a Screenshot with different value from defaults", () => { 95 | const attributes = { 96 | html, 97 | transparent: true, 98 | selector: "something", 99 | type: "jpeg", 100 | } as const; 101 | const screenshot = new Screenshot(attributes); 102 | 103 | expect(screenshot).toEqual(expect.objectContaining(attributes)); 104 | }); 105 | 106 | it("should not set quality if type is different from jpeg", () => { 107 | const screenshot = new Screenshot({ 108 | html, 109 | quality: 3, 110 | }); 111 | 112 | expect(screenshot.quality).toEqual(undefined); 113 | }); 114 | 115 | it("should handle empty content", () => { 116 | const screenshot = new Screenshot({ 117 | html, 118 | content: {}, 119 | }); 120 | 121 | expect(screenshot.content).toEqual(undefined); 122 | }); 123 | 124 | it("should set quality if type is jpeg", () => { 125 | const screenshot = new Screenshot({ 126 | html, 127 | type: "jpeg", 128 | quality: 3, 129 | }); 130 | 131 | expect(screenshot.quality).toEqual(3); 132 | }); 133 | 134 | it("should set quality by default if type is jpeg", () => { 135 | const screenshot = new Screenshot({ 136 | html, 137 | type: "jpeg", 138 | }); 139 | 140 | expect(screenshot.quality).toEqual(80); 141 | }); 142 | 143 | it("should throw an Error if no params are passed", () => { 144 | expect(() => { 145 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment 146 | // @ts-ignore 147 | new Screenshot(); 148 | }).toThrow("You must provide an html property."); 149 | }); 150 | 151 | it("should throw an Error if html is missing", () => { 152 | expect(() => { 153 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment 154 | // @ts-ignore 155 | new Screenshot({}); 156 | }).toThrow("You must provide an html property."); 157 | }); 158 | 159 | it("should throw an Error if html is null", () => { 160 | expect(() => { 161 | new Screenshot({ html: null }); 162 | }).toThrow("You must provide an html property."); 163 | }); 164 | 165 | it("should throw an Error if html is empty", () => { 166 | expect(() => { 167 | new Screenshot({ html: "" }); 168 | }).toThrow("You must provide an html property."); 169 | }); 170 | }); 171 | -------------------------------------------------------------------------------- /src/models/Screenshot.ts: -------------------------------------------------------------------------------- 1 | import { ImageType, Encoding, Content, ScreenshotParams } from "../types"; 2 | 3 | export class Screenshot { 4 | output: string; 5 | content: Content; 6 | selector: string; 7 | html: string; 8 | quality?: number; 9 | buffer?: Buffer | string; 10 | type?: ImageType; 11 | encoding?: Encoding; 12 | transparent?: boolean; 13 | 14 | constructor(params: ScreenshotParams) { 15 | if (!params || !params.html) { 16 | throw Error("You must provide an html property."); 17 | } 18 | 19 | const { 20 | html, 21 | encoding, 22 | transparent = false, 23 | output, 24 | content, 25 | selector = "body", 26 | quality = 80, 27 | type = "png", 28 | } = params; 29 | 30 | this.html = html; 31 | this.encoding = encoding; 32 | this.transparent = transparent; 33 | this.type = type; 34 | this.output = output; 35 | this.content = isEmpty(content) ? undefined : content; 36 | this.selector = selector; 37 | this.quality = type === "jpeg" ? quality : undefined; 38 | } 39 | 40 | setHTML(html: string) { 41 | if (!html) { 42 | throw Error("You must provide an html property."); 43 | } 44 | this.html = html; 45 | } 46 | 47 | setBuffer(buffer: Buffer | string) { 48 | this.buffer = buffer; 49 | } 50 | } 51 | 52 | function isEmpty(val: object) { 53 | return val == null || !Object.keys(val).length; 54 | } 55 | -------------------------------------------------------------------------------- /src/screenshot.spec.ts: -------------------------------------------------------------------------------- 1 | import { describe } from "jest-circus"; 2 | import handlebars from "handlebars"; 3 | import { makeScreenshot } from "./screenshot"; 4 | import { Screenshot } from "./models/Screenshot"; 5 | 6 | describe("beforeScreenshot", () => { 7 | let page; 8 | const buffer = new ArrayBuffer(); 9 | 10 | beforeEach(() => { 11 | page = { 12 | setContent: jest.fn(), 13 | setDefaultTimeout: jest.fn(), 14 | $: jest.fn(() => ({ screenshot: jest.fn(() => buffer) })), 15 | }; 16 | }); 17 | 18 | it("should call beforeScreenshot with page", async () => { 19 | const beforeScreenshot = jest.fn(); 20 | await makeScreenshot(page, { 21 | beforeScreenshot, 22 | screenshot: new Screenshot({ 23 | html: "Hello world!", 24 | }), 25 | }); 26 | 27 | expect(beforeScreenshot).toHaveBeenCalledWith(page); 28 | }); 29 | 30 | it("should return a screenshot with a buffer", async () => { 31 | const screenshot = await makeScreenshot(page, { 32 | screenshot: new Screenshot({ 33 | html: "Hello world!", 34 | }), 35 | }); 36 | 37 | expect(screenshot.buffer).toEqual(Buffer.from(buffer)); 38 | }); 39 | 40 | it("should compile a screenshot if there is content", async () => { 41 | await makeScreenshot(page, { 42 | screenshot: new Screenshot({ 43 | html: "{{message}}", 44 | content: { message: "Hello world!" }, 45 | }), 46 | }); 47 | 48 | expect(page.setContent).toHaveBeenCalledWith( 49 | "Hello world!", 50 | expect.anything(), 51 | ); 52 | }); 53 | 54 | it("should call 'setDefaultTimeout' with option's timeout", async () => { 55 | const TIMEOUT = 40 * 1000; 56 | 57 | await makeScreenshot(page, { 58 | timeout: TIMEOUT, 59 | screenshot: new Screenshot({ 60 | html: "{{message}}", 61 | content: { message: "Hello world!" }, 62 | }), 63 | }); 64 | 65 | expect(page.setDefaultTimeout).toHaveBeenCalledWith(TIMEOUT); 66 | }); 67 | 68 | it("should not compile a screenshot if content is empty", async () => { 69 | await makeScreenshot(page, { 70 | screenshot: new Screenshot({ 71 | html: "{{message}}", 72 | content: {}, 73 | }), 74 | }); 75 | 76 | expect(page.setContent).toHaveBeenCalledWith( 77 | "{{message}}", 78 | expect.anything(), 79 | ); 80 | }); 81 | 82 | it("should wait until load event", async () => { 83 | await makeScreenshot(page, { 84 | screenshot: new Screenshot({ 85 | html: "Hello world!", 86 | }), 87 | waitUntil: "load", 88 | }); 89 | 90 | expect(page.setContent).toHaveBeenCalledWith(expect.anything(), { 91 | waitUntil: "load", 92 | }); 93 | }); 94 | 95 | it("should throw an error if not element is found", async () => { 96 | page.$.mockImplementationOnce(jest.fn()); 97 | await expect(async () => { 98 | await makeScreenshot(page, { 99 | screenshot: new Screenshot({ 100 | selector: "toto", 101 | html: "Hello world!", 102 | }), 103 | }); 104 | }).rejects.toThrow("No element matches selector: toto"); 105 | }); 106 | }); 107 | 108 | describe("handlebarsHelpers", () => { 109 | let page; 110 | const buffer = new ArrayBuffer(); 111 | 112 | beforeEach(() => { 113 | page = { 114 | setContent: jest.fn(), 115 | setDefaultTimeout: jest.fn(), 116 | $: jest.fn(() => ({ screenshot: jest.fn(() => buffer) })), 117 | }; 118 | if ( 119 | Object.prototype.hasOwnProperty.call(handlebars.helpers, "equals") && 120 | !!handlebars.helpers.equals 121 | ) { 122 | handlebars.registerHelper({ equals: undefined }); 123 | } 124 | }); 125 | 126 | const compactHtml = (htmlString) => htmlString.replace(/((^|\n)\s+)/gm, ""); 127 | 128 | describe("if no logic is given in the template", () => { 129 | const html = "

Hello world!

"; 130 | 131 | const cleanTests = [ 132 | { 133 | label: "handlebarsHelpers is not passed", 134 | options: { content: { myVar: "foo" }, html: html }, 135 | }, 136 | { 137 | label: "handlebarsHelpers is undefined", 138 | options: { 139 | content: { myVar: "foo" }, 140 | handlebarsHelpers: undefined, 141 | html: html, 142 | }, 143 | }, 144 | { 145 | label: "handlebarsHelpers is not an object", 146 | options: { 147 | content: { myVar: "foo" }, 148 | handlebarsHelpers: "I'm not an object", 149 | html: html, 150 | }, 151 | }, 152 | { 153 | label: "all helpers are functions but no content is passed", 154 | options: { 155 | handlebarsHelpers: { 156 | equals: (a, b) => a === b, 157 | }, 158 | html: html, 159 | }, 160 | }, 161 | { 162 | label: 163 | "all helpers are functions but content has not the sought variable", 164 | options: { 165 | content: { myOtherVar: "bar" }, 166 | handlebarsHelpers: { 167 | equals: (a, b) => a === b, 168 | }, 169 | html: html, 170 | }, 171 | }, 172 | ]; 173 | 174 | for (const test of cleanTests) { 175 | it(`if no logic is given in the template, it should not throw error when ${test.label}`, async () => { 176 | await expect( 177 | makeScreenshot(page, { 178 | screenshot: new Screenshot(test.options), 179 | handlebarsHelpers: test.options.handlebarsHelpers, 180 | }), 181 | ).resolves.not.toThrow(); 182 | }); 183 | 184 | it(`if no logic is given in the template, it should render the original template when ${test.label}`, async () => { 185 | const p = jest.fn(() => page); 186 | await makeScreenshot(p(), { 187 | screenshot: new Screenshot(test.options), 188 | handlebarsHelpers: test.options.handlebarsHelpers, 189 | }); 190 | expect(p().setContent).toHaveBeenCalledWith(html, expect.anything()); 191 | }); 192 | } 193 | 194 | it("if no logic is given in the template, it should throw error when handlebarsHelpers is an object but some helper is not a function", async () => { 195 | await expect( 196 | makeScreenshot(page, { 197 | handlebarsHelpers: { 198 | foo: () => myVar === "foo", 199 | bar: "I'm not a valid function", 200 | }, 201 | screenshot: new Screenshot({ 202 | content: { myVar: "foo" }, 203 | html: html, 204 | }), 205 | }), 206 | ).rejects.toThrow(/Some helper is not a valid function/); 207 | }); 208 | }); 209 | 210 | describe("if logic is given in the template", () => { 211 | const html = compactHtml(` 212 | 213 | 214 |

Hello world!

215 | {{#if (equals myVar 'foo')}}
Foo
{{/if}} 216 | 217 | 218 | `); 219 | 220 | const errorTests = [ 221 | { 222 | label: "handlebarsHelpers is not passed", 223 | options: { content: { myVar: "foo" }, html: html }, 224 | error: /Missing helper: "equals"/, 225 | }, 226 | { 227 | label: "handlebarsHelpers is passed as undefined", 228 | options: { 229 | content: { myVar: "foo" }, 230 | handlebarsHelpers: undefined, 231 | html: html, 232 | }, 233 | error: /Missing helper: "equals"/, 234 | }, 235 | { 236 | label: "handlebarsHelpers is not an object", 237 | options: { 238 | content: { myVar: "foo" }, 239 | handlebarsHelpers: "I'm not an object", 240 | html: html, 241 | }, 242 | error: /Missing helper: "equals"/, 243 | }, 244 | { 245 | label: 246 | "handlebarsHelpers is an object, but some helper is not a function", 247 | options: { 248 | handlebarsHelpers: { 249 | equals: (a, b) => a === b, 250 | bar: "I'm not a function", 251 | }, 252 | html: html, 253 | }, 254 | error: /Some helper is not a valid function/, 255 | }, 256 | ]; 257 | 258 | for (const test of errorTests) { 259 | it(`if logic is given in the template, it should throw error when ${test.label}`, async () => { 260 | await expect( 261 | makeScreenshot(page, { 262 | screenshot: new Screenshot(test.options), 263 | handlebarsHelpers: test.options.handlebarsHelpers, 264 | }), 265 | ).rejects.toThrow(test.error); 266 | }); 267 | } 268 | 269 | // -- 270 | 271 | const emptyHtml = compactHtml(` 272 | 273 | 274 |

Hello world!

275 | 276 | 277 | `); 278 | 279 | const validTests = [ 280 | { 281 | label: "all helpers are functions but no content is passed", 282 | options: { 283 | handlebarsHelpers: { 284 | equals: (a, b) => a === b, 285 | }, 286 | html: html, 287 | }, 288 | expectedHtml: emptyHtml, 289 | }, 290 | { 291 | label: "all helpers are functions but content is passed as undefined", 292 | options: { 293 | content: undefined, 294 | handlebarsHelpers: { 295 | equals: (a, b) => a === b, 296 | }, 297 | html: html, 298 | }, 299 | expectedHtml: emptyHtml, 300 | }, 301 | { 302 | label: 303 | "all helpers are functions but content has not the sought variable", 304 | options: { 305 | content: { myOtherVar: "bar" }, 306 | handlebarsHelpers: { 307 | equals: (a, b) => a === b, 308 | }, 309 | html: html, 310 | }, 311 | expectedHtml: emptyHtml, 312 | }, 313 | { 314 | label: "helpers and content are valid, and the condition is met", 315 | options: { 316 | content: { myVar: "foo" }, 317 | handlebarsHelpers: { 318 | equals: (a, b) => a === b, 319 | }, 320 | html: html, 321 | }, 322 | expectedHtml: compactHtml(` 323 | 324 | 325 |

Hello world!

326 |
Foo
327 | 328 | 329 | `), 330 | }, 331 | { 332 | label: "helpers and content are valid, and the condition is not met", 333 | options: { 334 | content: { myVar: "bar" }, 335 | handlebarsHelpers: { 336 | equals: (a, b) => a === b, 337 | }, 338 | html: html, 339 | }, 340 | expectedHtml: emptyHtml, 341 | }, 342 | ]; 343 | 344 | for (const test of validTests) { 345 | it(`if logic is given in the template, it should not throw error when ${test.label}`, async () => { 346 | await expect( 347 | makeScreenshot(page, { 348 | screenshot: new Screenshot(test.options), 349 | handlebarsHelpers: test.options.handlebarsHelpers, 350 | }), 351 | ).resolves.not.toThrow(); 352 | }); 353 | 354 | it(`if logic is given in the template, it should render the expected template when ${test.label}`, async () => { 355 | const p = jest.fn(() => page); 356 | await makeScreenshot(p(), { 357 | screenshot: new Screenshot(test.options), 358 | handlebarsHelpers: test.options.handlebarsHelpers, 359 | }); 360 | expect(p().setContent).toHaveBeenCalledWith( 361 | test.expectedHtml, 362 | expect.anything(), 363 | ); 364 | }); 365 | } 366 | }); 367 | 368 | describe("functional tests", () => { 369 | it("should do conditional rendering correctly", async () => { 370 | await makeScreenshot(page, { 371 | screenshot: new Screenshot({ 372 | html: "{{#if (equals hello 'world')}}
Hello world!
{{/if}}", 373 | content: { hello: "world" }, 374 | }), 375 | handlebarsHelpers: { 376 | equals: (a, b) => a === b, 377 | }, 378 | }); 379 | 380 | expect(page.setContent).toHaveBeenCalledWith( 381 | "
Hello world!
", 382 | expect.anything(), 383 | ); 384 | }); 385 | 386 | it("should do conditional rendering on an array correctly", async () => { 387 | await makeScreenshot(page, { 388 | screenshot: new Screenshot({ 389 | html: "{{#each arr}}{{#if (shows this)}}
{{this.word}}
{{/if}}{{/each}}", 390 | content: { 391 | arr: [ 392 | { show: true, word: "Hi!" }, 393 | { show: false, word: "I'm hidden!" }, 394 | { show: true, word: "Hello!" }, 395 | ], 396 | }, 397 | }), 398 | handlebarsHelpers: { 399 | shows: (a) => a.show, 400 | }, 401 | }); 402 | 403 | expect(page.setContent).toHaveBeenCalledWith( 404 | "
Hi!
Hello!
", 405 | expect.anything(), 406 | ); 407 | }); 408 | 409 | it("should do conditional rendering with unless correctly", async () => { 410 | await makeScreenshot(page, { 411 | screenshot: new Screenshot({ 412 | html: "{{#unless (equals hello 'there')}}
Not hello world!
{{/unless}}", 413 | content: { hello: "world" }, 414 | }), 415 | handlebarsHelpers: { 416 | equals: (a, b) => a === b, 417 | }, 418 | }); 419 | 420 | expect(page.setContent).toHaveBeenCalledWith( 421 | "
Not hello world!
", 422 | expect.anything(), 423 | ); 424 | }); 425 | 426 | it("should do conditional rendering with unless on an array correctly", async () => { 427 | await makeScreenshot(page, { 428 | screenshot: new Screenshot({ 429 | html: "{{#each arr}}{{#unless (shows this)}}
{{{this.word}}}
{{/unless}}{{/each}}", 430 | content: { 431 | arr: [ 432 | { show: true, word: "Hi!" }, 433 | { show: false, word: "I'm not hidden!" }, 434 | { show: true, word: "Hello!" }, 435 | ], 436 | }, 437 | }), 438 | handlebarsHelpers: { 439 | shows: (a) => a.show, 440 | }, 441 | }); 442 | 443 | expect(page.setContent).toHaveBeenCalledWith( 444 | "
I'm not hidden!
", 445 | expect.anything(), 446 | ); 447 | }); 448 | 449 | it("should transform a string correctly", async () => { 450 | await makeScreenshot(page, { 451 | screenshot: new Screenshot({ 452 | html: "{{#with (upcase str) as |upstr|}}
{{upstr}}
{{/with}}", 453 | content: { 454 | str: "Hi there", 455 | }, 456 | }), 457 | handlebarsHelpers: { 458 | upcase: (a: string) => a.toUpperCase(), 459 | }, 460 | }); 461 | 462 | expect(page.setContent).toHaveBeenCalledWith( 463 | "
HI THERE
", 464 | expect.anything(), 465 | ); 466 | }); 467 | 468 | it("should transform a number correctly", async () => { 469 | await makeScreenshot(page, { 470 | screenshot: new Screenshot({ 471 | html: "{{#with (addTwo number) as |numPlusTwo|}}
{{numPlusTwo}}
{{/with}}", 472 | content: { 473 | number: 5, 474 | }, 475 | }), 476 | handlebarsHelpers: { 477 | addTwo: (a: number) => a + 2, 478 | }, 479 | }); 480 | 481 | expect(page.setContent).toHaveBeenCalledWith( 482 | "
7
", 483 | expect.anything(), 484 | ); 485 | }); 486 | 487 | it("should replace a character correctly", async () => { 488 | await makeScreenshot(page, { 489 | screenshot: new Screenshot({ 490 | html: "{{#with (fooToBar str) as |newstr|}}
{{newstr}}
{{/with}}", 491 | content: { 492 | str: "This is foo", 493 | }, 494 | }), 495 | handlebarsHelpers: { 496 | fooToBar: (a: string) => a.replace(/foo/, "bar"), 497 | }, 498 | }); 499 | 500 | expect(page.setContent).toHaveBeenCalledWith( 501 | "
This is bar
", 502 | expect.anything(), 503 | ); 504 | }); 505 | }); 506 | }); 507 | -------------------------------------------------------------------------------- /src/screenshot.ts: -------------------------------------------------------------------------------- 1 | import { Page } from "puppeteer"; 2 | import handlebars, { compile } from "handlebars"; 3 | 4 | import { MakeScreenshotParams } from "./types"; 5 | 6 | export async function makeScreenshot( 7 | page: Page, 8 | { 9 | screenshot, 10 | beforeScreenshot, 11 | waitUntil = "networkidle0", 12 | timeout, 13 | handlebarsHelpers, 14 | }: MakeScreenshotParams, 15 | ) { 16 | page.setDefaultTimeout(timeout); 17 | const hasHelpers = handlebarsHelpers && typeof handlebarsHelpers === "object"; 18 | if (hasHelpers) { 19 | if ( 20 | Object.values(handlebarsHelpers).every((h) => typeof h === "function") 21 | ) { 22 | handlebars.registerHelper(handlebarsHelpers); 23 | } else { 24 | throw Error("Some helper is not a valid function"); 25 | } 26 | } 27 | 28 | if (screenshot?.content || hasHelpers) { 29 | const template = compile(screenshot.html); 30 | screenshot.setHTML(template(screenshot.content)); 31 | } 32 | 33 | await page.setContent(screenshot.html, { waitUntil }); 34 | const element = await page.$(screenshot.selector); 35 | if (!element) { 36 | throw Error("No element matches selector: " + screenshot.selector); 37 | } 38 | 39 | if (isFunction(beforeScreenshot)) { 40 | await beforeScreenshot(page); 41 | } 42 | 43 | const result = await element.screenshot({ 44 | path: screenshot.output, 45 | type: screenshot.type, 46 | omitBackground: screenshot.transparent, 47 | encoding: screenshot.encoding, 48 | quality: screenshot.quality, 49 | }); 50 | 51 | screenshot.setBuffer(Buffer.from(result)); 52 | 53 | return screenshot; 54 | } 55 | 56 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 57 | function isFunction(f: any) { 58 | return f && typeof f === "function"; 59 | } 60 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | import type { Page, PuppeteerLifeCycleEvent, PuppeteerNodeLaunchOptions } from "puppeteer"; 2 | import type { Screenshot } from "./models/Screenshot"; 3 | 4 | export type Content = Array<{ output: string; selector?: string }> | object; 5 | export type Encoding = "base64" | "binary"; 6 | export type ImageType = "png" | "jpeg"; 7 | 8 | export interface ScreenshotParams { 9 | html: string; 10 | encoding?: Encoding; 11 | transparent?: boolean; 12 | type?: ImageType; 13 | quality?: number; 14 | selector?: string; 15 | content?: Content; 16 | output?: string; 17 | } 18 | 19 | export interface Options extends ScreenshotParams { 20 | puppeteerArgs?: PuppeteerNodeLaunchOptions; 21 | // https://github.com/thomasdondorf/puppeteer-cluster/blob/b5b098aed84b8d2c170b3f9d0ac050f53582df45/src/Cluster.ts#L30 22 | // eslint-disable-next-line @typescript-eslint/no-explicit-any 23 | puppeteer?: any, 24 | waitUntil?: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[]; 25 | beforeScreenshot?: (page: Page) => void; 26 | timeout?: number 27 | } 28 | 29 | export interface MakeScreenshotParams { 30 | screenshot: Screenshot; 31 | waitUntil?: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[]; 32 | beforeScreenshot?: (page: Page) => void; 33 | handlebarsHelpers?: { [helpers: string]: (...args: any[]) => any }; 34 | 35 | timeout?: number 36 | } 37 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es6", 4 | "esModuleInterop": true, 5 | "forceConsistentCasingInFileNames": true, 6 | "module": "commonjs", 7 | "noImplicitAny": true, 8 | "rootDir": "./src", 9 | "outDir": "dist", 10 | "declaration": true 11 | }, 12 | "include": ["src/**/*"], 13 | "exclude": ["node_modules", "**/*.spec.ts"] 14 | } 15 | --------------------------------------------------------------------------------