├── .github └── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── .gitignore ├── .npmignore ├── LICENSE ├── README.md ├── babel.config.js ├── documentation ├── api.md ├── assets.md ├── chunks.md ├── content.md ├── creating-pages.md ├── headers-footers.md ├── lists.md ├── real-time.md └── remote-api.md ├── examples ├── README.md ├── as-a-service │ ├── client.html │ ├── readme.md │ └── server.js ├── assets │ ├── README.md │ ├── img │ │ ├── pdftron.png │ │ └── pdftron2.png │ └── index.js ├── chunks │ ├── README.md │ ├── index.js │ └── src │ │ ├── index.html │ │ ├── index.scss │ │ └── myChunk.html ├── dynamic-content │ ├── README.md │ ├── index.js │ └── src │ │ ├── index.html │ │ └── style.scss ├── files-as-source │ ├── README.md │ ├── index.js │ └── src │ │ ├── index.html │ │ └── index.scss ├── function-to-pdf │ ├── README.md │ └── index.js ├── headers-footers │ ├── README.md │ ├── index.js │ └── src │ │ ├── footer.html │ │ ├── header.html │ │ ├── index.html │ │ └── style.scss ├── html-to-pdf-basic │ ├── README.md │ └── index.js ├── javascript │ ├── README.md │ ├── index.js │ └── src │ │ ├── cool-rendering.js │ │ ├── index.html │ │ └── style.scss ├── page-numbers │ ├── index.html │ ├── index.js │ ├── index.scss │ └── readme.md ├── react-to-pdf │ ├── README.md │ └── index.js ├── real-time │ ├── README.md │ ├── index.js │ ├── options.js │ └── src │ │ ├── index.html │ │ └── index.scss └── remote-source │ ├── README.md │ └── index.js ├── package.json ├── src ├── index.js ├── server.js ├── styles │ └── index.css ├── util │ ├── clean-html.js │ ├── copy-dir.js │ ├── custom-require.js │ ├── delete-dir.js │ ├── does-file-exist.js │ ├── ensure-exists.js │ ├── ensure-page.js │ ├── get-asset-source.js │ ├── get-content.js │ ├── get-css-src.js │ ├── get-custom-css.js │ ├── get-custom-scripts.js │ ├── get-html-from-source.js │ ├── get-options.js │ ├── get-render-type.js │ ├── get-script-src.js │ ├── inject-custom-scripts.js │ ├── inject-header-footer.js │ ├── inject-styles.js │ ├── insert-content.js │ ├── listen-to-changes.js │ ├── print-pdf.js │ ├── react-to-html.js │ ├── read-file.js │ ├── replace-page-numbers.js │ ├── to-absolute.js │ ├── type-check.js │ ├── verify-page.js │ └── write-file.js └── writer.js ├── test ├── assets.js ├── assets │ ├── content.json │ ├── index.html │ ├── options.js │ ├── script.js │ ├── style.scss │ └── temp.txt ├── clean-html.js ├── content.js ├── html.js ├── main.js ├── other.js ├── pageClass.js ├── realtime.js ├── remote.js ├── scripts.js └── style.js └── webpack.config.js /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | 5 | --- 6 | 7 | **Describe the bug** 8 | A clear and concise description of what the bug is. 9 | 10 | **To Reproduce** 11 | Steps to reproduce the behavior, include code or a sample repo if possible: 12 | ... 13 | 14 | 15 | **Expected behavior** 16 | A clear and concise description of what you expected to happen. 17 | 18 | **Screenshots** 19 | If applicable, add screenshots to help explain your problem. 20 | 21 | **Desktop (please complete the following information):** 22 | - OS: [e.g. iOS] 23 | - Browser [e.g. chrome, safari] 24 | - Version [e.g. 22] 25 | 26 | **Additional context** 27 | Add any other context about the problem here. 28 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | 5 | --- 6 | 7 | **Is your feature request related to a problem? Please describe.** 8 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 9 | 10 | **Describe the solution you'd like** 11 | A clear and concise description of what you want to happen. 12 | 13 | **Describe alternatives you've considered** 14 | A clear and concise description of any alternative solutions or features you've considered. 15 | 16 | **Additional context** 17 | Add any other context or screenshots about the feature request here. 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | dist/ 9 | outputs/ 10 | pages/ 11 | test-examples/ 12 | examples/template/ 13 | package-lock.json 14 | test/assets/temp.txt 15 | # Runtime data 16 | pids 17 | *.pid 18 | *.seed 19 | *.pid.lock 20 | 21 | # Directory for instrumented libs generated by jscoverage/JSCover 22 | lib-cov 23 | 24 | # Coverage directory used by tools like istanbul 25 | coverage 26 | 27 | # nyc test coverage 28 | .nyc_output 29 | 30 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 31 | .grunt 32 | 33 | # Bower dependency directory (https://bower.io/) 34 | bower_components 35 | 36 | # node-waf configuration 37 | .lock-wscript 38 | 39 | # Compiled binary addons (https://nodejs.org/api/addons.html) 40 | build/Release 41 | 42 | # Dependency directories 43 | node_modules/ 44 | jspm_packages/ 45 | 46 | # TypeScript v1 declaration files 47 | typings/ 48 | 49 | # Optional npm cache directory 50 | .npm 51 | 52 | # Optional eslint cache 53 | .eslintcache 54 | 55 | # Optional REPL history 56 | .node_repl_history 57 | 58 | # Output of 'npm pack' 59 | *.tgz 60 | 61 | # Yarn Integrity file 62 | .yarn-integrity 63 | 64 | # dotenv environment variables file 65 | .env 66 | 67 | # next.js build output 68 | .next 69 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | src 2 | .babelrc 3 | webpack.config.js 4 | outputs 5 | example-pages 6 | tests 7 | example-projects -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Web to PDF Converter 2 | Easily create beautiful PDFs using your favorite Javascript and CSS framework! 3 | 4 | Created and maintained by [PDFTron](https://pdftron.com). 5 | 6 | **This project is still in development and should not be used in a production environment! It has not been tested in all use cases.** 7 | 8 | **We are very interested in seeing how people use this tool. If you have any questions, comments or would just like to tell us how you're using it, please feel free to open a ticket!** 9 | 10 | ## Features 11 | - 💥 JS is fully supported, meaning you can use your favorite frameworks to generate your PDF. 12 | - 🔄 Comes with a powerful [content replacement](https://github.com/PDFTron/web-to-pdf/tree/master/documentation/content.md) system that allows for dynamic content. 13 | - 🔢 Insert [page numbers](https://github.com/PDFTron/web-to-pdf/tree/master/documentation/creating-pages.md#page-numbers) in your pages dynamically. 14 | - 💃 [Full SCSS support](https://github.com/PDFTron/web-to-pdf/tree/master/documentation/api.md#styles) 15 | - 👸 Support for [headers and footers](https://github.com/PDFTron/web-to-pdf/tree/master/documentation/headers-footers.md) 16 | - 🔗 Support for reusuable [HTML chunks](https://github.com/PDFTron/web-to-pdf/tree/master/documentation/chunks.md) 17 | - 🎥 [Real time mode](https://github.com/PDFTron/web-to-pdf/tree/master/documentation/real-time.md) with hot reloading, meaning you can build your PDF in real time 18 | - 🌏 Support for [rendering remote pages](https://github.com/PDFTron/web-to-pdf/tree/master/documentation/remote-api.md) (You can even inject your own css and js!) 19 | - 🚦 Queueing system so you can render 1000's of PDFs with a single script. 20 | - 👍 Much more! 21 | 22 | ## Roadmap 23 | - Examples (external repos?) of usage with other frameworks 24 | - Splitting of non-list content on page break 25 | - Support for form inputs 26 | 27 | ## Installation 28 | ``` 29 | npm i @pdftron/web-to-pdf 30 | ``` 31 | 32 | ## Example 33 | ```js 34 | const Renderer = require('@pdftron/web-to-pdf'); 35 | 36 | const r = new Renderer({ dirname: __dirname }); 37 | 38 | const htmlString = ` 39 | 40 | 41 | 42 | 43 | 44 |
45 | Page1: {{myText}} 46 |
47 | 48 |
49 | Page2: Goodbye world! 50 |
51 | 52 | 53 | `; 54 | 55 | r.render({ 56 | templateSource: htmlString, 57 | contentSource: { 58 | myText: "Hello world!" 59 | }, 60 | outputName: 'example' 61 | }); 62 | 63 | // Pdf will be rendered at ./outputs/example.pdf ! 64 | ``` 65 | 66 | See more examples [here](examples/). 67 | 68 | ## Documentation 69 | - [Creating pages + Dynamic page numbers](https://github.com/PDFTron/web-to-pdf/blob/master/documentation/creating-pages.md) 70 | - [API](https://github.com/PDFTron/web-to-pdf/blob/master/documentation/api.md) 71 | - [Rendering remote pages](https://github.com/PDFTron/web-to-pdf/blob/master/documentation/remote-api.md) 72 | - [Headers and footers](https://github.com/PDFTron/web-to-pdf/blob/master/documentation/headers-footers.md) 73 | - [Reusable Chunks](https://github.com/PDFTron/web-to-pdf/blob/master/documentation/chunks.md) 74 | - [Lists](https://github.com/PDFTron/web-to-pdf/blob/master/documentation/lists.md) 75 | - [Real time PDF building](https://github.com/PDFTron/web-to-pdf/blob/master/documentation/real-time.md) 76 | - [Styling with CSS & SASS](https://github.com/PDFTron/web-to-pdf/blob/master/documentation/api.md#styles) 77 | - [Assets](https://github.com/PDFTron/web-to-pdf/blob/master/documentation/assets.md) 78 | - [Dynamic content](https://github.com/PDFTron/web-to-pdf/blob/master/documentation/content.md) 79 | 80 | ## Real time PDF Building 81 | With a few changes to your options you can enable real time PDF building! 82 | See [the docs](https://github.com/PDFTron/web-to-pdf/blob/master/documentation/real-time.md) for more info. 83 | 84 | ## Development 85 | ``` 86 | git clone https://github.com/PDFTron/web-to-pdf.git 87 | cd web-to-pdf 88 | npm i 89 | ``` 90 | 91 | There are examples you can test on in the `examples` folder. These examples are run via scripts in `package.json` 92 | 93 | ## Contributing 94 | Before created a PR, please make sure tests pass: 95 | 96 | `npm run test` 97 | 98 | If you would like to contribute but aren't sure how, please open a ticket saying you would like to contribute. 99 | 100 | Feel free to add tests you feel needed. 101 | 102 | ## Caveats 103 | - Creation of PDF input fields is not supported (not supported by chromium). 104 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | "presets": ["@babel/preset-react"], 3 | "plugins": [ 4 | "@babel/plugin-proposal-function-sent", 5 | "@babel/plugin-proposal-export-namespace-from", 6 | "@babel/plugin-proposal-numeric-separator", 7 | "@babel/plugin-proposal-throw-expressions", 8 | "@babel/plugin-proposal-class-properties", 9 | "@babel/plugin-transform-dotall-regex", 10 | "@babel/plugin-proposal-object-rest-spread" 11 | ] 12 | } -------------------------------------------------------------------------------- /documentation/api.md: -------------------------------------------------------------------------------- 1 | # API 2 | 3 | ## new Renderer(options) 4 | 5 | ```js 6 | const Renderer = require('@pdftron/web-to-pdf'); 7 | const renderer = new Renderer(options); 8 | ``` 9 | **options** 10 | 11 | - [dirname](#dirname-required) (required) 12 | - [width](#width) 13 | - [height](#height) 14 | - [margin](#margin) 15 | - [keepAlive](#keepAlive) 16 | - [debug](#debug) 17 | - [port](#port) 18 | - [host](#host) 19 | - [autoOpen](#autoopen) 20 | - [args](#args) 21 | 22 | ### dirname (required) 23 | Directory of the file you are working in. Please pass `__dirname` for this option. 24 | 25 | ```js 26 | const renderer = new Renderer({ dirname: __dirname }); 27 | ``` 28 | 29 | ### width 30 | Width of each page in pixels. Must be an interger 31 | 32 | **default**: 612 33 | 34 | ### height 35 | Height of each page in pixels. Must be an interger value **or** set to 'auto' to match the height of the page. 36 | 37 | **default**: 792 38 | 39 | ### margin 40 | Object specifying page margins. `top`, `bottom`, `left` and `right` are accepted object values. Uses normal CSS values. 41 | 42 | ```js 43 | const Renderer = require('@pdftron/web-to-pdf'); 44 | const r = new Renderer({ 45 | margin: { 46 | top: '20px', 47 | left: '1in', 48 | right: '20px', 49 | bottom: '20px', 50 | } 51 | }) 52 | ``` 53 | 54 | ### keepAlive 55 | Set to true to keep the instance in memory when it's done rendering. Useful for using the tool as a service. 56 | 57 | **default**: false 58 | 59 | ### debug 60 | Set to true to enable some debugging logs. Setting this to true will also leave all the source files in your output directory (these are normally deleted after the PDF is generated.) 61 | 62 | **default**: false 63 | 64 | ### port 65 | Port to run the local server on. 66 | 67 | **default**: 8080 68 | 69 | ### host 70 | Host to run the local server on. 71 | 72 | **default**: 127.0.0.1 73 | 74 | ### autoOpen 75 | Set to true to auto open the PDF once its done rendering. Ignored if you are in real time mode. 76 | 77 | **default**: false 78 | 79 | ### args 80 | An array of arguments to pass to the puppeteer `launch` function. Possible values can be found [here](https://peter.sh/experiments/chromium-command-line-switches/) 81 | 82 | ## .render(renderOptions) 83 | 84 | ```js 85 | const Renderer = require('@pdftron/web-to-pdf'); 86 | const renderer = new Renderer(options); 87 | 88 | const result = await renderer.render(renderOptions); // see below for renderOptions 89 | ``` 90 | 91 | **NOTE** For `realTime` mode, you must pass a path to an options file instead of an options object. See [this](./real-time.md) for more details. 92 | 93 | **NOTE** If you want to render a remote URL, also see [this guide](./remote-api.md) 94 | 95 | #### Returns: 96 | 97 | Returns a promise that resolves with the following object: 98 | 99 | ``` 100 | { 101 | sourceMap: { 102 | ...list of read/writes that were made. Used mostly for debugging. 103 | }, 104 | output: 'path to where the PDF was written, relative to CWD', 105 | metadata: { 106 | numberOfPages: 'how many pages the PDF is' 107 | } 108 | } 109 | ``` 110 | 111 | 112 | **Render options:** 113 | - [templateSource](#templatesource-required) (required) 114 | - [react component](#react-component) 115 | - [html string](#html-string) 116 | - [html file](#html-file) 117 | - [function](#function) 118 | - [url](#url) 119 | - [contentSource](#contentsource) 120 | - [pageClass](#pageClass) 121 | - [chunks](#chunks) 122 | - [outputFolder](#outputfolder) 123 | - [outputName](#outputname) 124 | - [styles](#styles) 125 | - [ignoreWatch](#ignorewatch) 126 | - [middleware](#middleware) 127 | 128 | 129 | ### templateSource (required) 130 | The source for your PDF structure. Can be one of the following: 131 | 132 | #### react component 133 | If you pass a React component, it will be rendered to HTML via React.renderToString(). **Keep in mind that this is a server render**, so you dont have access to browser APIs, and you won't get all the lifecycle functions. 134 | 135 | 136 | ```js 137 | class Component extends React.Component { 138 | render() { 139 | return ( 140 |
141 |

My content here!

142 |
143 | ) 144 | } 145 | } 146 | 147 | const renderer = new Renderer({ dirname: __dirname }); 148 | renderer.render({ 149 | templateSource: Component 150 | }); 151 | ``` 152 | 153 | #### html (string) 154 | If you pass a valid html string, it will be used directly to render the PDF. 155 | 156 | ```js 157 | const renderer = new Renderer({ dirname: __dirname }); 158 | renderer.render({ 159 | templateSource: ` 160 | 161 | 162 |
163 | My content goes here! 164 |
165 | 166 | 167 | ` 168 | }); 169 | ``` 170 | 171 | #### html (file) 172 | If you pass a path to a html file, it will be used directly to render the PDF. 173 | 174 | ```js 175 | const renderer = new Renderer({ dirname: __dirname }); 176 | renderer.render({ 177 | templateSource: 'index.html' 178 | }); 179 | ``` 180 | 181 | #### function 182 | If you pass a function, it will be called and the result will be used to render the PDF. This means the function should return valid HTML, **or a promise that resolves with valid HTML**. 183 | 184 | The function is passed the content that is passed via the [contentSource](#contentSource) option. This makes dynamic HTML structures possible. 185 | 186 | ```js 187 | const renderer = new Renderer({ dirname: __dirname }); 188 | renderer.render({ 189 | templateSource: (content) => { 190 | return ` 191 | 192 | 193 |
194 | ${ 195 | content.list.map((item) => { 196 | return `

${item}

` 197 | }) 198 | } 199 |
200 | 201 | 202 | ` 203 | } 204 | }); 205 | ``` 206 | 207 | #### url 208 | If you pass a URL, the remote page will be rendered. 209 | 210 | Url must start with `http` or `https`. 211 | 212 | Also see [this guide](./remote-api.md) 213 | 214 | ```js 215 | const renderer = new Renderer({ dirname: __dirname }); 216 | renderer.render({ 217 | templateSource: 'https://google.com' 218 | }); 219 | ``` 220 | 221 | ### contentSource 222 | Either a JS object or a path to a JSON file containing your content. This content will be used to replace your [mustaches](content.md), and is also passed into the [templateSource function method.](#function). The content is also available at `window.content` if you are using some client side rendering. If not supplied, no content will be replaced. 223 | 224 | **NOTE:** content replacement will only work if you pass in raw HTML, or pass a [react component](#react-component) to templateSource. If you are using Javascript to generate the DOM on the client, content replacement will not work. In this case you can access your data at `window.content`. 225 | 226 | default: `null` 227 | 228 | #### json (file) 229 | 230 | ```js 231 | 232 | const html = ` 233 | 234 | 235 |
236 | {{myString}} 237 |
238 | 239 | 240 | ` 241 | 242 | const renderer = new Renderer({ dirname: __dirname }); 243 | renderer.render({ 244 | templateSource: html, 245 | contentSource: 'content.html' 246 | }); 247 | ``` 248 | 249 | #### json (object) 250 | 251 | ```js 252 | const renderer = new Renderer({ dirname: __dirname }); 253 | 254 | const html = ` 255 | 256 | 257 |
258 | {{myString}} 259 |
260 | 261 | 262 | ` 263 | 264 | renderer.render({ 265 | templateSource: html, 266 | contentSource: { 267 | "myString": "Hello world!" 268 | } 269 | }); 270 | ``` 271 | 272 | 273 | ### pageClass 274 | Use your own custom class to seperate pages. 275 | 276 | By default, each div with a `Page` class will be its own page. You can change this by setting this property. 277 | 278 | ```js 279 | const html = ` 280 | 281 | 282 |
283 | {{header}} 284 | Hi! 285 | 286 | {{copy}} 287 |
288 | 289 | 290 | ` 291 | 292 | renderer.render({ 293 | templateSource: html, 294 | pageClass: 'CustomPage' 295 | }); 296 | ``` 297 | 298 | 299 | ### chunks 300 | A map of HTML snippets to reuse throughout your template. 301 | 302 | Accepts any of the types that [templateSource](#templatesource) accepts (except a remote url). Whatever is passed will replace any {{chunkName}} mustaches. 303 | 304 | See [here](./content.md) for more info on mustache syntax. 305 | See [here](./chunks.md) for more info and examples on chunks. 306 | 307 | ```js 308 | const renderer = new Renderer({ dirname: __dirname }); 309 | 310 | const html = ` 311 | 312 | 313 |
314 | {{header}} 315 | Hi! 316 | 317 | {{copy}} 318 |
319 | 320 | 321 | ` 322 | 323 | const header = ` 324 |
325 | My Header here 326 |
327 | ` 328 | 329 | const mainCopy = ` 330 |
331 | My main copy 332 |
333 | ` 334 | 335 | renderer.render({ 336 | templateSource: html, 337 | contentSource: { 338 | "myString": "Hello world!" 339 | }, 340 | chunks: { 341 | header: header, 342 | copy: mainCopy 343 | } 344 | }); 345 | ``` 346 | 347 | ### outputFolder 348 | A string containing the name of the desired output folder. Will be created relative to the CWD. 349 | 350 | default: `outputs` 351 | 352 | ```js 353 | const renderer = new Renderer({ dirname: __dirname }); 354 | renderer.render({ 355 | templateSource: 'template.html', 356 | outputFolder: 'pdf-outputs' 357 | }); 358 | ``` 359 | 360 | Will create `./pdf-outputs/index.pdf` 361 | 362 | ### outputName 363 | Name of the PDF file that is generated. 364 | 365 | default `index` 366 | 367 | ```js 368 | const renderer = new Renderer({ dirname: __dirname }); 369 | renderer.render({ 370 | templateSource: 'template.html', 371 | outputFolder: 'pdf-outputs', 372 | outputName: 'report-card' 373 | }); 374 | ``` 375 | 376 | Will create `./pdf-outputs/report-card.pdf` 377 | 378 | ### styles 379 | 380 | **IMPORTANT: If your css/scss is referenced (via link tags) in your html, then you don't need to do this. [See the examples to learn more](../examples)** 381 | 382 | An array of string representing paths to css files or actual css or scss you want to use to style your PDF. If you provide a `.scss` file, it (and any linked files) will be automatically compiled to css. These styles will be automatically injected into the HTML generated by your [templateSource](#templateSource). **This is only useful if you cant link the css in your HTML for some reason.** 383 | 384 | 385 | default: `[]` 386 | 387 | ```js 388 | const renderer = new Renderer({ dirname: __dirname }); 389 | renderer.render({ 390 | templateSource: 'template.html', 391 | styles: [ 392 | 'style.css', // paths to css 393 | 'customStyle.scss', // paths to scss 394 | ` 395 | #test { 396 | color: red / 397 | } 398 | ` // or actual css or scss 399 | ], 400 | }); 401 | ``` 402 | 403 | ### ignoreWatch 404 | Sometimes you will have your own file watcher and you won't have to reply on our on change function for certain files. 405 | 406 | Accepts an [anymatch](https://www.npmjs.com/package/anymatch) array or glob of files to ignore. 407 | 408 | default: null 409 | 410 | ```js 411 | const renderer = new Renderer({ dirname: __dirname }); 412 | renderer.render({ 413 | templateSource: 'template.html', 414 | ignoreWatch: "**/bundle.js" // ignore bundle.js 415 | }); 416 | ``` 417 | 418 | ### middleware 419 | An array of functions used to transform HTML. Each function will be called one after the other. Each function recieves HTML as a parameter and should return the transformed HTML string. 420 | 421 | Middleware functions can be asyncronous. The next middleware in the chain won't get called until the previous one is finished 422 | 423 | ```js 424 | const renderer = new Renderer({ dirname: __dirname }); 425 | renderer.render({ 426 | templateSource: 'template.html', 427 | middleware: [ 428 | (html) => { 429 | html = html.replace(/p/g, "h5"); 430 | return html; 431 | } 432 | ] 433 | }); 434 | ``` 435 | 436 | ## .on(key, callback) 437 | Subscribe to event throughout the render process. Possible keys are 438 | 439 | `change` - called when a file used to render changes, useful for [real time pdf building](./real-time.md). 440 | 441 | 442 | `html` - called when the final HTML is determined (useful for debugging). Callback is passed an html string. Not called when using a remote URL. 443 | 444 | ## .stop() 445 | Closes down all services. 446 | 447 | 448 | 449 | -------------------------------------------------------------------------------- /documentation/assets.md: -------------------------------------------------------------------------------- 1 | # Assets 2 | 3 | Assets referenced in your html will be automatically served and watched (if in real time mode). Please reference them relatively to your html file: 4 | 5 | File system 6 | ``` 7 | myProject/ 8 | - index.html 9 | assets/ 10 | - image.png 11 | ``` 12 | 13 | HTML 14 | ```html 15 |
16 | 17 |
18 | ``` 19 | -------------------------------------------------------------------------------- /documentation/chunks.md: -------------------------------------------------------------------------------- 1 | # Chunks 2 | 3 | Chunks are reusable snippets of HTML. They are referenced with mustache syntax, the same as [dynamic content](./content.md); 4 | 5 | These are useful for any reusuable chunks of code. 6 | 7 | Chunks can be any format that [templateSource](./api.md#templatesource-required) can be (html string, html file, react component, function, etc) 8 | 9 | To set the chunk content, use the [chunks](./api.md#chunks) render options. 10 | 11 | Chunks can be used to automatially append html to the top and bottom of every page - aka **headers and footers**. See [this guide](./headers-footers.md) for details 12 | 13 | ## Example 14 | 15 | ```js 16 | const renderer = new Renderer({ dirname: __dirname }); 17 | 18 | // main template 19 | const templateSource = ` 20 |
21 | {{chunkOne}} 22 | My page 1 content here 23 |
24 | 25 |
26 | {{chunkTwo}} 27 | My page 2 content here 28 |
29 | 30 |
31 | {{chunkOne}} 32 | My page 3 content here 33 | {{chunkTwo}} 34 |
35 | ` 36 | 37 | // Headers 38 | const chunkOne = ` 39 |
40 | PDFTron.com 41 |
42 | ` 43 | 44 | // Footers 45 | const chunkTwo = ` 46 |
47 | Page {{pageNumber}} 48 |
49 | ` 50 | 51 | renderer.render({ 52 | templateSource: html, 53 | chunks: { 54 | chunkOne, 55 | chunkTwo 56 | } 57 | }); 58 | ``` 59 | 60 | HTML output: 61 | ```html 62 |
63 |
64 | PDFTron.com 65 |
66 | My page 1 content here 67 |
68 | 69 |
70 |
71 | Page 2 72 |
73 | My page 2 content here 74 |
75 | 76 |
77 |
78 | PDFTron.com 79 |
80 | My page 3 content here 81 |
82 | Page 3 83 |
84 |
85 | ``` 86 | 87 | -------------------------------------------------------------------------------- /documentation/content.md: -------------------------------------------------------------------------------- 1 | # Dynamic Content 2 | 3 | We use mustache syntax to do content replacements. You may use mustache syntax in any html [templateSource](api.md#templateSource). The replacement happens AFTER the html is generated on the server. 4 | 5 | Your content can be loaded by the [contentSource](api.md#contentSource) option. 6 | 7 | If you are using client side JS (like React) to generate your DOM, mustaches will not be replaced. In this case, the content will be available at `window.content` for you to use dynamically. 8 | 9 | Content can be nested (see examples below) 10 | 11 | ## Examples: 12 | 13 | - [In HTML](#in-html-file) 14 | - [In templateSource function](#in-templatesource-function) 15 | - [In react component](#in-react-component) 16 | 17 | ## In HTML file 18 | 19 | index.js 20 | ```js 21 | const renderer = new Renderer({ dirname: __dirname }); 22 | renderer.render({ 23 | contentSource: 'content.json', 24 | templateSource: 'index.html', 25 | }); 26 | ``` 27 | 28 | index.html 29 | ```html 30 | 31 | 32 |

{{ myData }}

33 |

{{ my.nested.data }}

34 | 35 | 36 | ``` 37 | 38 | content.json 39 | ```json 40 | { 41 | "myData": "Hello world!", 42 | "my": { 43 | "nested": { 44 | "data": "Goodbye world!" 45 | } 46 | } 47 | } 48 | ``` 49 | 50 | output: 51 | ```html 52 | 53 | 54 |

Hello world!

55 |

Goodbye world!

56 | 57 | 58 | ``` 59 | 60 | ## In templateSource function 61 | 62 | index.js 63 | ```js 64 | const renderer = new Renderer({ dirname: __dirname }); 65 | renderer.render({ 66 | contentSource: 'content.json', 67 | templateSource: (content) => { 68 | return ` 69 | 70 | 71 |

${content.myData}

72 | 73 | ${ 74 | content.my.nested.data.map(item => { 75 | return `

${item}

` 76 | }) 77 | } 78 | 79 | 80 | ` 81 | } 82 | }); 83 | ``` 84 | 85 | content.json 86 | ```json 87 | { 88 | "myData": "Hello world!", 89 | "my": { 90 | "nested": { 91 | "data": ["hey", "how", "are", "you"] 92 | } 93 | } 94 | } 95 | ``` 96 | 97 | output: 98 | ```html 99 | 100 | 101 |

Hello world!

102 |

hey

103 |

how

104 |

are

105 |

you

106 | 107 | 108 | ``` 109 | 110 | ## In react component (server side) 111 | Content is passed as a prop to the React component, but you can even use the mustache in your react component if you want. 112 | 113 | index.js 114 | ```js 115 | class Comp extends React.Component { 116 | render() { 117 | const { content } = this.props; 118 | return ( 119 |
120 |

{`{{ myData }}`}

121 |

{content.myData}

122 |
123 | ) 124 | } 125 | } 126 | 127 | const renderer = new Renderer({ dirname: __dirname }); 128 | renderer.render({ 129 | contentSource: 'content.json', 130 | templateSource: Comp, // passing this directly does a server render 131 | }); 132 | ``` 133 | 134 | content.json 135 | ```json 136 | { 137 | "myData": "Hello world!" 138 | } 139 | ``` 140 | 141 | output 142 | ```html 143 | 144 | 145 |
146 |

Hello world!

147 |

Hello world!

148 |
149 | 150 | 151 | ``` 152 | 153 | -------------------------------------------------------------------------------- /documentation/creating-pages.md: -------------------------------------------------------------------------------- 1 | # Creating Pages 2 | Creating pages is easy! All you need to do is apply the class `.Page` to a wrapper div. From this point, anything in that container will be part of the page. 3 | 4 | You can also use your own identifier to split pages. Pass in your custom value to the [pageClass](./api.md#pageClass) and it will be used to split pages. 5 | 6 | To create multiple pages, simply include mulitple page divs. 7 | 8 | **If you do not include a page div, all your content will be wrapped in a page.** 9 | 10 | [Click here](./api.md) for the full Renderer API 11 | 12 | ## Page numbers 13 | Page numbers can be inserted by using `{{pageNumber}}` The mustache will be automatially replaced with the proper page number. 14 | 15 | ## Examples 16 | 17 | ### HTML 18 | 19 | ```js 20 | 21 | const html = ` 22 | 23 | 24 |
25 | page {{pageNumber}} 26 |
27 | 28 |
29 | page {{pageNumber}} 30 |
31 | 32 |
33 | page {{pageNumber}} 34 |
35 | 36 | 37 | ` 38 | 39 | const renderer = new Renderer({ dirname: __dirname }); 40 | renderer.render({ 41 | templateSource: html, 42 | }); 43 | 44 | // NOTE: You do not have to include the or tags if you have no header items. So this would be okay as well: 45 | /* 46 | const html = ` 47 |
48 | page {{pageNumber}} 49 |
50 | 51 |
52 | page {{pageNumber}} 53 |
54 | 55 |
56 | page {{pageNumber}} 57 |
58 | ` 59 | */ 60 | 61 | ``` 62 | 63 | ### React 64 | 65 | ```js 66 | const React = require('react'); 67 | const Renderer = require('@pdftron/web-to-pdf'); 68 | 69 | class Component extends React.Component { 70 | render() { 71 | return ( 72 | 73 |
74 | Page {`{{pageNumber}}`} 75 |
76 | 77 |
78 | Page {`{{pageNumber}}`} 79 |
80 | 81 |
82 | Page {`{{pageNumber}}`} 83 |
84 |
85 | ) 86 | } 87 | } 88 | 89 | const renderer = new Renderer({ dirname: __dirname }); 90 | renderer.render({ 91 | templateSource: Component, 92 | }); 93 | ``` -------------------------------------------------------------------------------- /documentation/headers-footers.md: -------------------------------------------------------------------------------- 1 | # Headers and Footers 2 | 3 | Adding headers and footer to each page is easy! Simple add a `header` and/or `footer` [chunk](./chunks.md) to your render options, and it will be automatically added. 4 | 5 | The header and footer content can be in any format that [templateSource](./api.md#templatesource-required) accepts (except a remote URL). 6 | 7 | ### Example 8 | 9 | ```js 10 | const renderer = new Renderer({ dirname: __dirname }); 11 | 12 | // main template 13 | const templateSource = ` 14 |
15 | My page 1 content here 16 |
17 | 18 |
19 | My page 2 content here 20 |
21 | ` 22 | 23 | // Headers 24 | const header = ` 25 |
26 | PDFTron.com 27 |
28 | ` 29 | 30 | // Footers 31 | const footer = ` 32 | 35 | ` 36 | 37 | renderer.render({ 38 | templateSource: html, 39 | chunks: { 40 | header, 41 | footer 42 | } 43 | }); 44 | ``` 45 | 46 | Output 47 | 48 | ```html 49 |
50 |
51 | PDFTron.com 52 |
53 | My page 1 content here 54 | 57 |
58 | 59 |
60 |
61 | PDFTron.com 62 |
63 | My page 2 content here 64 | 67 |
68 | ``` -------------------------------------------------------------------------------- /documentation/lists.md: -------------------------------------------------------------------------------- 1 | # Lists 2 | 3 | When rendering lists of data, its possible that the contents of the list will overflow off the page. We solve this problem by dynamically altering your lists to fit to individual pages. 4 | 5 | To use this feature, simply wrap your list contents in a `.List` class. We will take any overflow content and insert it into a new page! 6 | 7 | ```js 8 |
9 |
10 | { 11 | myItems.map(item => { 12 | return

{item}

13 | }) 14 | } 15 |
16 |
17 | 18 | ``` -------------------------------------------------------------------------------- /documentation/real-time.md: -------------------------------------------------------------------------------- 1 | # Real time PDF Building 2 | 3 | Real time mode allows you to view your PDF in the browser as you build it! Any change to a file will rebuild the PDF and hot reload it in the browser. 4 | 5 | **To enable real time mode, please follow these two (three if you're using react) steps:** 6 | 7 | ## 1) Export renderOptions from a different file. 8 | In order for us to get your new render params when they change, we need to be able to dynamically require them. In order to do this, your render params must be exported from another file, and you must pass us a path to this file. This file must export (default) a function that returns your params. This function may be asyncronous if you need to do some network fetching here. 9 | 10 | See [here](./api.md#renderrenderoptions) for possible renderOptions 11 | 12 | Example of real time building [here](./../examples/real-time) 13 | 14 | **index.js** 15 | ```js 16 | const renderer = new Renderer({ dirname: __dirname }); 17 | 18 | const render = () => { 19 | renderer.render('options.js'); 20 | } 21 | 22 | renderer.on('change', render); 23 | render(); 24 | ``` 25 | 26 | **options.js** 27 | ```js 28 | 29 | module.exports = () => { 30 | return { 31 | templateSource: "
Hey!!!
", 32 | // ...other renderOptions 33 | } 34 | } 35 | 36 | ``` 37 | 38 | ## 2) Add a change listener 39 | 40 | To trigger re-renders, you need to hook into the `onchange` event. Follow this pattern to do so: 41 | 42 | ```js 43 | const renderer = new Renderer({ dirname: __dirname }); 44 | 45 | const render = () => { 46 | renderer.render('options.js'); 47 | } 48 | 49 | renderer.on('change', render); 50 | render(); 51 | ``` 52 | 53 | Web-to-pdf will trigger your render function any time a file changes. 54 | 55 | ## 3) React components (server rendered) 56 | 57 | If you are using a React component as a source and you want hot reloading, you need to use our special `pathTo` function to require it. 58 | 59 | In the function exported from your [options file](#1-export-renderoptions-from-a-different-file), use the first parameter to reference your react component. 60 | 61 | Example: 62 | 63 | **options.js** 64 | ```js 65 | module.exports = async (pathTo) => { 66 | 67 | return { 68 | templateSource: pathTo('./root'), // ./root exports the root react component 69 | } 70 | 71 | } 72 | ``` 73 | 74 | [Here is an example](../examples/complex-2) of this method in use. 75 | 76 | -------------------------------------------------------------------------------- /documentation/remote-api.md: -------------------------------------------------------------------------------- 1 | # Remote API 2 | 3 | Passing a URL to templateSource allows you to render a remote page. The API is the same as rendering a local PDF, but here are some ways you can edit the remote PDF. 4 | 5 | ## new Renderer(options) 6 | See [renderer api](./api.md#new-rendereroptions) for constructor options 7 | 8 | ```js 9 | const Renderer = require('@pdftron/web-to-pdf'); 10 | const renderer = new Renderer(options); 11 | ``` 12 | 13 | ## .render(renderOptions) 14 | - [templateSource](#templateSource) (required) 15 | - [styles](#styles), 16 | - [scripts](#scripts), 17 | - [outputFolder](#outputfolder) 18 | - [outputName](#outputname) 19 | - [ignoreWatch](#ignorewatch) 20 | 21 | **NOTE** For `realTime` mode, you must pass a path to an options file instead of an options object. See [this](./real-time.md) for more details. 22 | 23 | **NOTE** If you want to render a local html file, please see [this guide](./api.md) 24 | 25 | ### templateSource 26 | The URL of the page to render. 27 | 28 | ```js 29 | const renderer = new Renderer(options); 30 | 31 | renderer.renderRemote({ 32 | templateSource: 'http://google.com' 33 | }); 34 | ``` 35 | 36 | ### styles 37 | An array of paths to `css` or `scss` files to inject into the page. Useful for removing unwanted elements from the page. 38 | 39 | Paths are relative to the current file. 40 | 41 | ```js 42 | const renderer = new Renderer(options); 43 | 44 | renderer.renderRemote({ 45 | templateSource: 'http://google.com', 46 | styles: [ 47 | 'style.css', 48 | 'style.scss', 49 | ] 50 | }); 51 | ``` 52 | 53 | ### scripts 54 | An array of paths to javscript files to inject into the page. Useful for running custom scripts before the PDF is generated. 55 | 56 | Scripts are injected into the top of the page. 57 | 58 | Paths are relative to the current file. 59 | 60 | ```js 61 | const renderer = new Renderer(options); 62 | 63 | renderer.renderRemote({ 64 | templateSource: 'http://google.com', 65 | scripts: [ 66 | 'myScript.js', 67 | ] 68 | }); 69 | ``` 70 | 71 | ### outputFolder 72 | A string containing the name of the desired output folder. Will be created relative to the CWD. 73 | 74 | default: `outputs` 75 | 76 | ```js 77 | const renderer = new Renderer({ dirname: __dirname }); 78 | renderer.renderRemote({ 79 | templateSource: 'http://google.com', 80 | outputFolder: 'pdf-outputs' 81 | }); 82 | ``` 83 | 84 | Will create `./pdf-outputs/index.pdf` 85 | 86 | ### outputName 87 | Name of the PDF file that is generated. 88 | 89 | default `index` 90 | 91 | ```js 92 | const renderer = new Renderer({ dirname: __dirname }); 93 | renderer.renderRemote({ 94 | templateSource: 'http://google.com', 95 | outputFolder: 'pdf-outputs', 96 | outputName: 'report-card' 97 | }); 98 | ``` 99 | 100 | Will create `./pdf-outputs/report-card.pdf` 101 | 102 | ### ignoreWatch 103 | Sometimes you will have your own file watcher and you won't have to reply on our on change function for certain files. 104 | 105 | Accepts an [anymatch](https://www.npmjs.com/package/anymatch) array or glob of files to ignore. 106 | 107 | default: null 108 | 109 | ```js 110 | const renderer = new Renderer({ dirname: __dirname }); 111 | renderer.renderRemote({ 112 | templateSource: 'http://google.com', 113 | ignoreWatch: "**/style.scss" // ignore style.scss 114 | }); 115 | ``` 116 | 117 | 118 | 119 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # Examples 2 | This directory contains a bunch of examples. 3 | 4 | Here is a categorized list of examples: 5 | 6 | ### The basics 7 | - [HTML to PDF](./html-to-pdf-basic) 8 | - [React to PDF](./react-to-pdf) 9 | - [Function to PDF](./function-to-pdf) 10 | - [Local files to PDF](./files-as-source) 11 | 12 | ### Content 13 | - [Dynamic content/copy](./dynamic-content) 14 | - [Reusuable HTML chunks](./chunks) 15 | - [Page numbers](./page-numbers) 16 | 17 | ### Structure 18 | - [Headers and footers](./headers-footers) 19 | 20 | ### Real Time 21 | - [Real time PDF building](./real-time) 22 | 23 | ### Cool stuff 24 | - 💥[**Using third party JS libraries to render stuff**](./javascript)💥 25 | - 💥[**Running as a service**](./as-a-service)💥 -------------------------------------------------------------------------------- /examples/as-a-service/client.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 23 | 24 | -------------------------------------------------------------------------------- /examples/as-a-service/readme.md: -------------------------------------------------------------------------------- 1 | # As a service. 2 | 3 | You can use web-to-pdf as an online service to render PDFs! 4 | 5 | This example uses a node + express server to provide a PDF rendering API. 6 | 7 | When the client presses the submit button, it sends a request to the API that tells it to render whatever remote page the user enters. When its done rendering, it returns the remote location of the generated PDF, and the client navigates there. 8 | 9 | **This is a very basic example - more precautions should be taken in a real life scenerio**. 10 | 11 | ### Running 12 | 13 | If you dont have the repo installed, do so by running: 14 | ``` 15 | git clone https://github.com/PDFTron/web-to-pdf.git 16 | cd web-to-pdf 17 | npm i 18 | ``` 19 | 20 | Run the example: 21 | ``` 22 | npx babel-node examples/as-a-service/server.js 23 | ``` 24 | 25 | ### Try the sample: 26 | Navigate to http://localhost:8080 and enter a website to render as a PDF. A new tab will open displaying the PDF. -------------------------------------------------------------------------------- /examples/as-a-service/server.js: -------------------------------------------------------------------------------- 1 | const Renderer = require('../../src'); 2 | const express = require('express'); 3 | const app = express(); 4 | const Path = require('path'); 5 | const port = 8080; 6 | 7 | const r = new Renderer({ dirname: __dirname, keepAlive: true, height: 'auto' }); 8 | 9 | // use express to serve static assets at /outputs 10 | app.use('/outputs', express.static(Path.resolve(__dirname, './outputs'))); 11 | 12 | // serve the client app 13 | app.get('/', (req, res) => { 14 | res.sendFile(Path.join(__dirname + '/client.html')); 15 | }) 16 | 17 | // convert api 18 | app.get('/convert', async (req, res) => { 19 | const path = req.query.url; 20 | const u = new URL(path); 21 | 22 | await r.render({ 23 | templateSource: path, 24 | outputFolder: Path.resolve(__dirname, './outputs'), // render stuff (relative to this file) 25 | outputName: u.hostname 26 | }); 27 | 28 | // returns the remote location of the file 29 | res.send(`http://localhost:${port}/outputs/${u.hostname}.pdf`); 30 | }); 31 | 32 | app.listen(port, () => { console.log(`Listening on port ${port}. Navigate to http://localhost:8080 to test the app!`) }); 33 | -------------------------------------------------------------------------------- /examples/assets/README.md: -------------------------------------------------------------------------------- 1 | # NAME 2 | DESCRIPTION 3 | 4 | ### Running 5 | 6 | If you dont have the repo installed, do so by running: 7 | ``` 8 | git clone https://github.com/XodoDocs/web-to-pdf.git 9 | cd web-to-pdf 10 | npm i 11 | ``` 12 | 13 | Run the example: 14 | ``` 15 | npx babel-node examples/assets/index.js 16 | ``` 17 | 18 | ### APIs and Techniques Used 19 | - [HTML String as template source](../../documentation/api.md#html-string) 20 | - [Output name](../../documentation/api.md#outputname) -------------------------------------------------------------------------------- /examples/assets/img/pdftron.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ApryseSDK/web-to-pdf/651ebc4ee85e53b7bb161f6b0443d9b08c9be283/examples/assets/img/pdftron.png -------------------------------------------------------------------------------- /examples/assets/img/pdftron2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ApryseSDK/web-to-pdf/651ebc4ee85e53b7bb161f6b0443d9b08c9be283/examples/assets/img/pdftron2.png -------------------------------------------------------------------------------- /examples/assets/index.js: -------------------------------------------------------------------------------- 1 | const WebToPDF = require('../../src/index'); 2 | // const WebToPDF = require('@pdftron/web-to-pdf'); // or this 3 | 4 | (async () => { 5 | const renderer = new WebToPDF({ dirname: __dirname, debug: true }); 6 | 7 | const html = ` 8 |
9 |
10 |

Web to PDF

11 |

Basic assets example

12 | 13 | 14 |
15 | This should have a background image 16 |
17 |
18 |
19 | `; 20 | 21 | const style = ` 22 | .bg { 23 | background-image: url('./img/pdftron2.png'); 24 | } 25 | ` 26 | 27 | renderer.render({ 28 | templateSource: html, 29 | styles: [style], 30 | outputName: 'assetsBasic' 31 | }) 32 | 33 | })() 34 | -------------------------------------------------------------------------------- /examples/chunks/README.md: -------------------------------------------------------------------------------- 1 | # Chunks example 2 | This example shows how to use the chunks api to insert chunks of html throughout your template. 3 | 4 | ### Running 5 | 6 | If you dont have the repo installed, do so by running: 7 | ``` 8 | git clone https://github.com/PDFTron/web-to-pdf.git 9 | cd web-to-pdf 10 | npm i 11 | ``` 12 | 13 | Run the example: 14 | ``` 15 | npx babel-node examples/chunks 16 | ``` 17 | 18 | ### APIs and Techniques Used 19 | - [Chunks](../../documentation/chunks.md) 20 | - [HTML String as template source](../../documentation/api.md#html-string) 21 | - [HTML File as chunk source](../../documentation/api.md#html-file) 22 | - [React component as chunk source](../../documentation/api.md#react-component) 23 | - [Output name](../../documentation/api.md#outputname) -------------------------------------------------------------------------------- /examples/chunks/index.js: -------------------------------------------------------------------------------- 1 | const WebToPDF = require('../../src/index'); 2 | // const WebToPDF = require('@pdftron/web-to-pdf'); // or this 3 | 4 | const React = require('react'); 5 | 6 | class ReactChunk extends React.Component { 7 | render() { 8 | return ( 9 |
10 | Cool! Rendered via React. 11 |
12 | ) 13 | } 14 | } 15 | 16 | (async () => { 17 | const renderer = new WebToPDF({ dirname: __dirname }); 18 | 19 | await renderer.render({ 20 | templateSource: './src/index.html', 21 | chunks: { 22 | fileChunk: './src/myChunk.html', 23 | reactChunk: ReactChunk, 24 | htmlChunk: ` 25 |
26 |

I will be dynamically inserted!

27 |
28 | ` 29 | }, 30 | outputName: "chunks" 31 | }) 32 | 33 | })() 34 | -------------------------------------------------------------------------------- /examples/chunks/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 |

Insert chunks of content using mustache syntax and the chunks api

9 | {{fileChunk}} 10 | 11 |

Chunks can be any input that templateSource accepts
(html string, React component, html file, function)

12 | {{reactChunk}} 13 | 14 |

No need to duplicate your html!

15 | {{htmlChunk}} 16 |
17 | 18 | -------------------------------------------------------------------------------- /examples/chunks/src/index.scss: -------------------------------------------------------------------------------- 1 | .Page { 2 | display: flex; 3 | justify-content: center; 4 | align-items: center; 5 | flex-direction: column; 6 | } -------------------------------------------------------------------------------- /examples/chunks/src/myChunk.html: -------------------------------------------------------------------------------- 1 |
2 | This is a chunk of content! 3 |
-------------------------------------------------------------------------------- /examples/dynamic-content/README.md: -------------------------------------------------------------------------------- 1 | # Dynamic Content Example 2 | This is an example of using dynamic content in your PDFs. 3 | 4 | This is useful for writing a script to generate a PDF invoice, report, report card, etc. You can use your own service to fetch the content and dynamically insert it into your template. 5 | 6 | ### Running 7 | 8 | If you dont have the repo installed, do so by running: 9 | ``` 10 | git clone https://github.com/PDFTron/web-to-pdf.git 11 | cd web-to-pdf 12 | npm i 13 | ``` 14 | 15 | Run the example: 16 | ``` 17 | npx babel-node examples/dynamic-content 18 | ``` 19 | 20 | ### APIs and Techniques Used 21 | - [HTML File as template source](../../documentation/api.md#html-file) 22 | - [Dynamic content](../../documentation/content.md) 23 | - [Output name](../../documentation/api.md#outputname) -------------------------------------------------------------------------------- /examples/dynamic-content/index.js: -------------------------------------------------------------------------------- 1 | const WebToPDF = require('../../src/index'); 2 | // const WebToPDF = require('@pdftron/web-to-pdf'); // or this 3 | 4 | (async () => { 5 | const renderer = new WebToPDF({ dirname: __dirname }); 6 | 7 | // You could load this JSON object from your own service 8 | // This is useful for generating reports, invoices, etc 9 | const myContent = { 10 | pageTitle: "Using dynamic content in your PDFs", 11 | subtitle: "This example shows how you can use JSON data to render dynamic content in your PDF", 12 | content: { 13 | body: "You can even use nested data!" 14 | } 15 | } 16 | 17 | await renderer.render({ 18 | templateSource: './src/index.html', 19 | contentSource: myContent, 20 | outputName: "dynamic-content" 21 | }) 22 | 23 | })() 24 | -------------------------------------------------------------------------------- /examples/dynamic-content/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |

{{pageTitle}}

7 |

{{subtitle}}

8 |

{{content.body}}

9 | 10 | -------------------------------------------------------------------------------- /examples/dynamic-content/src/style.scss: -------------------------------------------------------------------------------- 1 | .Page { 2 | display: flex; 3 | flex-direction: column; 4 | height: 100%; 5 | justify-content: center; 6 | align-items: center; 7 | } -------------------------------------------------------------------------------- /examples/files-as-source/README.md: -------------------------------------------------------------------------------- 1 | # Local files as a source 2 | This example shows how you can use `html`, `scss` and `css` files as sources. 3 | 4 | This example also shows how you can use Google Fonts to style your text. 5 | 6 | ### Running 7 | 8 | If you dont have the repo installed, do so by running: 9 | ``` 10 | git clone https://github.com/PDFTron/web-to-pdf.git 11 | cd web-to-pdf 12 | npm i 13 | ``` 14 | 15 | Run the example: 16 | ``` 17 | npx babel-node examples/files-as-source/index.js 18 | ``` 19 | 20 | ### APIs and Techniques Used 21 | - [HTML File as template source](../../documentation/api.md#html-file) 22 | - [Output name](../../documentation/api.md#outputname) -------------------------------------------------------------------------------- /examples/files-as-source/index.js: -------------------------------------------------------------------------------- 1 | const WebToPDF = require('../../src/index'); 2 | // const WebToPDF = require('@pdftron/web-to-pdf'); // or this 3 | 4 | (async () => { 5 | const renderer = new WebToPDF({ dirname: __dirname }); 6 | 7 | await renderer.render({ 8 | templateSource: './src/index.html', 9 | outputName: 'files-as-source' 10 | }) 11 | })() 12 | -------------------------------------------------------------------------------- /examples/files-as-source/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 |

Using an HTML file as a source.

9 |

You can use an HTML file to generate a PDF. You can even reference external CSS/SCSS as seen above!

10 |

This example uses Google fonts (imported in index.scss, check it out!)

11 |
12 | 13 | -------------------------------------------------------------------------------- /examples/files-as-source/src/index.scss: -------------------------------------------------------------------------------- 1 | // You can use external web fonts! 2 | @import url('https://fonts.googleapis.com/css?family=Roboto'); 3 | 4 | .Page { 5 | h1, p { 6 | font-family: Roboto; 7 | } 8 | 9 | display: flex; 10 | flex-direction: column; 11 | justify-content: center; 12 | align-items: center; 13 | } 14 | -------------------------------------------------------------------------------- /examples/function-to-pdf/README.md: -------------------------------------------------------------------------------- 1 | # Function to PDF example 2 | Web-to-pdf can accept a function as a source. This function can be async, meaning you can fetch data to use when rendering your PDF. 3 | 4 | ### Running 5 | 6 | If you dont have the repo installed, do so by running: 7 | ``` 8 | git clone https://github.com/PDFTron/web-to-pdf.git 9 | cd web-to-pdf 10 | npm i 11 | ``` 12 | 13 | Run the example: 14 | ``` 15 | npx babel-node examples/function-to-pdf/index.js 16 | ``` 17 | 18 | ### APIs and Techniques Used 19 | - [Function as template source](../../documentation/api.md#function) 20 | - [SCSS Strings as styles](../../documentation/api.md#styles) 21 | - [Output name](../../documentation/api.md#outputname) -------------------------------------------------------------------------------- /examples/function-to-pdf/index.js: -------------------------------------------------------------------------------- 1 | const WebToPDF = require('../../src/index'); 2 | // const WebToPDF = require('@pdftron/web-to-pdf'); // or this 3 | 4 | const fetch = require('node-fetch'); 5 | 6 | (async () => { 7 | const renderer = new WebToPDF({ dirname: __dirname }); 8 | 9 | const getHTML = async () => { 10 | const response = await fetch('https://jsonplaceholder.typicode.com/todos'); 11 | let json = await response.json(); 12 | 13 | json = json.slice(0, 10); 14 | 15 | const content = json.reduce((acc, data) => { 16 | return acc + ` 17 |
18 |

${data.title} ${data.completed ? "" : ""}

19 |
20 | ` 21 | }, '') 22 | 23 | const html = ` 24 |
25 |
26 | ${content} 27 |
28 |
29 | `; 30 | 31 | return html; 32 | 33 | }; 34 | 35 | await renderer.render({ 36 | templateSource: getHTML, 37 | outputName: 'function-to-pdf', 38 | styles: [ 39 | ` 40 | .list { 41 | margin: 20px; 42 | } 43 | 44 | .item { 45 | p { 46 | font-size: 24px; 47 | 48 | .green { 49 | color: green; 50 | } 51 | 52 | .red { 53 | color: red; 54 | } 55 | } 56 | 57 | } 58 | ` 59 | ] 60 | }) 61 | })() 62 | -------------------------------------------------------------------------------- /examples/headers-footers/README.md: -------------------------------------------------------------------------------- 1 | # Header and footer example 2 | This example shows how `header` and `footer` chunks are automatically appended to each page. 3 | 4 | ### Running 5 | 6 | If you dont have the repo installed, do so by running: 7 | ``` 8 | git clone https://github.com/PDFTron/web-to-pdf.git 9 | cd web-to-pdf 10 | npm i 11 | ``` 12 | 13 | Run the example: 14 | ``` 15 | npx babel-node examples/headers-footers 16 | ``` 17 | 18 | ### APIs and Techniques Used 19 | - [Headers and footers](../../documentation/headers-footers.md) 20 | - [HTML File as template source](../../documentation/api.md#html-file) 21 | - [Output name](../../documentation/api.md#outputname) -------------------------------------------------------------------------------- /examples/headers-footers/index.js: -------------------------------------------------------------------------------- 1 | const WebToPDF = require('../../src/index'); 2 | // const WebToPDF = require('@pdftron/web-to-pdf'); // or this 3 | 4 | (async () => { 5 | const renderer = new WebToPDF({ dirname: __dirname }); 6 | 7 | await renderer.render({ 8 | templateSource: "./src/index.html", 9 | chunks: { 10 | header: "./src/header.html", 11 | footer: "./src/footer.html" 12 | }, 13 | outputName: "headers-footers" 14 | }) 15 | 16 | })() 17 | -------------------------------------------------------------------------------- /examples/headers-footers/src/footer.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/headers-footers/src/header.html: -------------------------------------------------------------------------------- 1 |
2 |

Header content is automatically appended to each page.

3 |
-------------------------------------------------------------------------------- /examples/headers-footers/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 |
9 | Page 1 content 10 |
11 |
12 | 13 |
14 |
15 | Page 2 content 16 |
17 |
18 | 19 |
20 |
21 | Page 3 content 22 |
23 |
24 | 25 | -------------------------------------------------------------------------------- /examples/headers-footers/src/style.scss: -------------------------------------------------------------------------------- 1 | .content { 2 | height: 100%; 3 | display: flex; 4 | flex-direction: column; 5 | justify-content: center; 6 | align-items: center; 7 | } 8 | 9 | .header, .footer { 10 | background-color: #222222; 11 | color: white; 12 | height: 50px; 13 | display: flex; 14 | justify-content: center; 15 | align-items: center; 16 | 17 | p { 18 | margin: 0; 19 | } 20 | } -------------------------------------------------------------------------------- /examples/html-to-pdf-basic/README.md: -------------------------------------------------------------------------------- 1 | # HTML to PDF Basic Example 2 | This example shows how to convert an HTML string and SCSS string to a PDF. 3 | 4 | ### Running 5 | 6 | If you dont have the repo installed, do so by running: 7 | ``` 8 | git clone https://github.com/PDFTron/web-to-pdf.git 9 | cd web-to-pdf 10 | npm i 11 | ``` 12 | 13 | Run the example: 14 | ``` 15 | npx babel-node examples/html-to-pdf-basic/index.js 16 | ``` 17 | 18 | ### APIs and Techniques Used 19 | - [HTML String as template source](../../documentation/api.md#html-string) 20 | - [SCSS Strings as styles](../../documentation/api.md#styles) 21 | - [Output name](../../documentation/api.md#outputname) -------------------------------------------------------------------------------- /examples/html-to-pdf-basic/index.js: -------------------------------------------------------------------------------- 1 | const WebToPDF = require('../../dist/web-to-pdf'); 2 | // const WebToPDF = require('@pdftron/web-to-pdf'); // or this 3 | 4 | (async () => { 5 | const renderer = new WebToPDF({ dirname: __dirname, debug: true }); 6 | 7 | const html = ` 8 |
9 |
10 |

Web to PDF

11 |

Basic HTML Example

12 |
13 |
14 | `; 15 | 16 | const scss = ` 17 | .container { 18 | display: flex; 19 | flex-direction: column; 20 | justify-content: center; 21 | align-items: center; 22 | height: 100%; 23 | 24 | @media screen and (min-width: 300px) { 25 | background-color: red; 26 | } 27 | 28 | @media screen and (min-width: 400px) { 29 | background-color: green; 30 | } 31 | 32 | @media screen and (min-width: 500px) { 33 | background-color: blue; 34 | } 35 | 36 | @media screen and (min-width: 600px) { 37 | background-color: yellow; 38 | } 39 | 40 | @media screen and (min-width: 700px) { 41 | background-color: pink; 42 | } 43 | 44 | @media screen and (min-width: 800px) { 45 | background-color: black; 46 | } 47 | 48 | @media screen and (min-width: 900px) { 49 | background-color: grey; 50 | } 51 | } 52 | 53 | 54 | `; 55 | 56 | await renderer.render({ 57 | templateSource: html, 58 | styles: [scss], 59 | outputName: 'htmlBasic' 60 | }); 61 | })() 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /examples/javascript/README.md: -------------------------------------------------------------------------------- 1 | # Javascript example 2 | This example shows how we can use a third party JS library to render elements in our PDF, such as charts and graphs. 3 | 4 | ### Running 5 | 6 | If you dont have the repo installed, do so by running: 7 | ``` 8 | git clone https://github.com/PDFTron/web-to-pdf.git 9 | cd web-to-pdf 10 | npm i 11 | ``` 12 | 13 | Run the example: 14 | ``` 15 | npx babel-node examples/javascript 16 | ``` 17 | 18 | ### APIs and Techniques Used 19 | - [HTML File as template source](../../documentation/api.md#html-file) 20 | - [Output name](../../documentation/api.md#outputname) -------------------------------------------------------------------------------- /examples/javascript/index.js: -------------------------------------------------------------------------------- 1 | const WebToPDF = require('../../src/index'); 2 | // const WebToPDF = require('@pdftron/web-to-pdf'); // or this 3 | 4 | (async () => { 5 | const renderer = new WebToPDF({ dirname: __dirname, debug: true }); 6 | 7 | await renderer.render({ 8 | templateSource: './src/index.html', 9 | outputName: 'javascript' 10 | }) 11 | })() 12 | -------------------------------------------------------------------------------- /examples/javascript/src/cool-rendering.js: -------------------------------------------------------------------------------- 1 | const ctx = document.getElementById("draw-here"); 2 | 3 | const myChart = new Chart(ctx, { 4 | type: 'doughnut', 5 | data: { 6 | labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], 7 | datasets: [{ 8 | label: '# of Votes', 9 | data: [12, 19, 3, 5, 2, 3], 10 | backgroundColor: [ 11 | 'rgba(255, 99, 132, 1)', 12 | 'rgba(54, 162, 235, 1)', 13 | 'rgba(255, 206, 86, 1)', 14 | 'rgba(75, 192, 192, 1)', 15 | 'rgba(153, 102, 255, 1)', 16 | 'rgba(255, 159, 64, 1)' 17 | ], 18 | borderColor: [ 19 | 'rgba(255,99,132,1)', 20 | 'rgba(54, 162, 235, 1)', 21 | 'rgba(255, 206, 86, 1)', 22 | 'rgba(75, 192, 192, 1)', 23 | 'rgba(153, 102, 255, 1)', 24 | 'rgba(255, 159, 64, 1)' 25 | ], 26 | borderWidth: 1 27 | }] 28 | }, 29 | }); 30 | -------------------------------------------------------------------------------- /examples/javascript/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 |
11 | 12 |
13 | 14 |
15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /examples/javascript/src/style.scss: -------------------------------------------------------------------------------- 1 | .Page { 2 | display: flex; 3 | justify-content: center; 4 | align-items: center; 5 | flex-direction: column; 6 | } -------------------------------------------------------------------------------- /examples/page-numbers/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | Page {{pageNumber}} 10 |
11 | 12 |
13 | Page {{pageNumber}} 14 |
15 | 16 |
17 | Page {{pageNumber}} 18 |
19 | 20 | -------------------------------------------------------------------------------- /examples/page-numbers/index.js: -------------------------------------------------------------------------------- 1 | import Renderer from '../../src'; 2 | 3 | const r = new Renderer({ dirname: __dirname }); 4 | 5 | r.render({ 6 | templateSource: 'index.html', 7 | outputName: 'pageNumbers' 8 | }) 9 | -------------------------------------------------------------------------------- /examples/page-numbers/index.scss: -------------------------------------------------------------------------------- 1 | .Page { 2 | display: flex; 3 | justify-content: center; 4 | align-items: center; 5 | font-size: 40px; 6 | } -------------------------------------------------------------------------------- /examples/page-numbers/readme.md: -------------------------------------------------------------------------------- 1 | # Javascript example 2 | This example shows you how to add page numbers dynamically into your PDFs 3 | 4 | ### Running 5 | 6 | If you dont have the repo installed, do so by running: 7 | ``` 8 | git clone https://github.com/PDFTron/web-to-pdf.git 9 | cd web-to-pdf 10 | npm i 11 | ``` 12 | 13 | Run the example: 14 | ``` 15 | npx babel-node examples/page-numbers 16 | ``` 17 | 18 | ### APIs and Techniques Used 19 | - [HTML File as template source](../../documentation/api.md#html-file) 20 | - [Page numbers](../../documentation/creating-pages.md#page-numbers) -------------------------------------------------------------------------------- /examples/react-to-pdf/README.md: -------------------------------------------------------------------------------- 1 | # React to PDF Example 2 | This example shows how you can use a server side react component to render a PDF. 3 | 4 | ### Running 5 | 6 | If you dont have the repo installed, do so by running: 7 | ``` 8 | git clone https://github.com/PDFTron/web-to-pdf.git 9 | cd web-to-pdf 10 | npm i 11 | ``` 12 | 13 | Run the example: 14 | ``` 15 | npx babel-node examples/react-to-pdf/index.js 16 | ``` 17 | 18 | ### APIs and Techniques Used 19 | - [React Component as template source](../../documentation/api.md#react-component) 20 | - [SCSS Strings as styles](../../documentation/api.md#styles) 21 | - [Output name](../../documentation/api.md#outputname) -------------------------------------------------------------------------------- /examples/react-to-pdf/index.js: -------------------------------------------------------------------------------- 1 | const React = require('react'); 2 | const WebToPDF = require('../../src/index'); 3 | // const WebToPDF = require('@pdftron/web-to-pdf'); // or this 4 | 5 | class RootComponent extends React.Component { 6 | render() { 7 | const data = [ 8 | { firstName: "Homer", lastname: "Simpson" }, 9 | { firstName: "Marge", lastname: "Simpson" }, 10 | { firstName: "Lisa", lastname: "Simpson" }, 11 | { firstName: "Bart", lastname: "Simpson" }, 12 | ] 13 | 14 | return ( 15 |
16 |

Simpsons Characters

17 | { 18 | data.map(({ firstName, lastname }) => ) 19 | } 20 |
21 | ) 22 | } 23 | } 24 | 25 | class ListItem extends React.Component { 26 | render() { 27 | return ( 28 |
29 |

{this.props.firstName} {this.props.lastname}

30 |
31 | ) 32 | } 33 | } 34 | 35 | (async () => { 36 | const renderer = new WebToPDF({ dirname: __dirname }); 37 | 38 | await renderer.render({ 39 | templateSource: RootComponent, 40 | outputName: 'react-to-pdf', 41 | styles: [ 42 | ` 43 | .Root { 44 | height: 100%; 45 | display: flex; 46 | flex-direction: column; 47 | justify-content: center; 48 | align-items: center; 49 | } 50 | 51 | .ListItem { 52 | p { 53 | font-size: 24px; 54 | } 55 | } 56 | ` 57 | ] 58 | }) 59 | 60 | })() 61 | -------------------------------------------------------------------------------- /examples/real-time/README.md: -------------------------------------------------------------------------------- 1 | # Real time PDF building 2 | This example shows how to build your PDF templates in real time. 3 | 4 | ### Running 5 | 6 | If you dont have the repo installed, do so by running: 7 | ``` 8 | git clone https://github.com/PDFTron/web-to-pdf.git 9 | cd web-to-pdf 10 | npm i 11 | ``` 12 | 13 | Run the example: 14 | ``` 15 | npx babel-node examples/real-time 16 | ``` 17 | 18 | ### APIs and Techniques Used 19 | - [HTML files as template source](../../documentation/api.md#html-file) 20 | - [Real time PDF building](../../documentation/real-time.md) 21 | - [Multiple page PDFs](../../documentation/creating-pages.md) 22 | - [Dynamic content](../../documentation/content.md) 23 | - [Output name](../../documentation/api.md#outputname) -------------------------------------------------------------------------------- /examples/real-time/index.js: -------------------------------------------------------------------------------- 1 | const WebToPDF = require('../../src/index'); 2 | // const WebToPDF = require('@pdftron/web-to-pdf'); // or this 3 | 4 | (async () => { 5 | const renderer = new WebToPDF({ dirname: __dirname }); 6 | 7 | const renderFunc = () => { 8 | renderer.render('options.js'); 9 | } 10 | 11 | renderer.on('change', renderFunc); 12 | renderFunc(); 13 | 14 | })() 15 | -------------------------------------------------------------------------------- /examples/real-time/options.js: -------------------------------------------------------------------------------- 1 | module.exports = () => { 2 | 3 | const contentSource = { 4 | title: "Real time PDF building ya ya ya!!!!", 5 | subtitle: "Try changing me and see what happens wow", 6 | description: "You can change anything in this file, in src/index.html, or any other referenced files (like index.scss).

Its magic!" 7 | } 8 | 9 | return { 10 | templateSource: './src/index.html', 11 | contentSource, 12 | outputName: "real-time", 13 | pageClass: "Split", 14 | } 15 | } -------------------------------------------------------------------------------- /examples/real-time/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 |

{{title}}

9 |

{{subtitle}}

10 |

{{description}}

11 |
12 | 13 |
14 |

This is my page two content!! Wow it changes in real time!

15 |
16 | 17 | -------------------------------------------------------------------------------- /examples/real-time/src/index.scss: -------------------------------------------------------------------------------- 1 | .Split { 2 | display: flex; 3 | flex-direction: column; 4 | align-items: center; 5 | justify-content: center; 6 | background-color: #222222; 7 | color: white; 8 | font-family: arial; 9 | 10 | p { 11 | text-align: center; 12 | color: blue; 13 | } 14 | } -------------------------------------------------------------------------------- /examples/remote-source/README.md: -------------------------------------------------------------------------------- 1 | # Remote source example 2 | Renders a PDF of https://www.pdftron.com. 3 | 4 | This example shows how we can inject CSS into a remote page to format it before render. 5 | 6 | ### Running 7 | 8 | If you dont have the repo installed, do so by running: 9 | ``` 10 | git clone https://github.com/PDFTron/web-to-pdf.git 11 | cd web-to-pdf 12 | npm i 13 | ``` 14 | 15 | Run the example: 16 | ``` 17 | npx babel-node examples/remote-source 18 | ``` 19 | 20 | ### APIs and Techniques Used 21 | - [Remote URL as source](../../documentation/remote-api.md) 22 | - [Inject SCSS into page](../../documentation/remote-api.md#styles) 23 | - [Width and height](../../documentation/api.md#width) 24 | - [Output name](../../documentation/api.md#outputname) -------------------------------------------------------------------------------- /examples/remote-source/index.js: -------------------------------------------------------------------------------- 1 | const WebToPDF = require('../../src/index'); 2 | // const WebToPDF = require('@pdftron/web-to-pdf'); // or this 3 | 4 | (async () => { 5 | const renderer = new WebToPDF({ 6 | dirname: __dirname, 7 | height: 'auto', 8 | width: 1200, 9 | }); 10 | 11 | await renderer.render({ 12 | templateSource: "https://www.pdftron.com", 13 | styles: [ 14 | ` 15 | .Header, .Footer, .main-cta { 16 | display: none !important; 17 | } 18 | 19 | ` 20 | ], 21 | outputName: "remote-source" 22 | }) 23 | 24 | })() 25 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@pdftron/web-to-pdf", 3 | "version": "0.7.0", 4 | "description": "Headless HTML to PDF conversion", 5 | "main": "dist/web-to-pdf.js", 6 | "bin": { 7 | "web-to-pdf": "dist/web-to-pdf.js" 8 | }, 9 | "scripts": { 10 | "test": "nyc mocha --compilers js:@babel/register", 11 | "build": "npm run test && npx webpack", 12 | "publish-npm": "npm run build && npm publish", 13 | "preinstall": "npm i node-sass live-server --save" 14 | }, 15 | "repository": { 16 | "type": "git", 17 | "url": "git+https://github.com/PDFTron/web-to-pdf.git" 18 | }, 19 | "author": "Logan Bittner", 20 | "license": "AGPL", 21 | "bugs": { 22 | "url": "https://github.com/PDFTron/web-to-pdf/issues" 23 | }, 24 | "homepage": "https://github.com/PDFTron/web-to-pdf#readme", 25 | "dependencies": { 26 | "@babel/runtime": "^7.1.2", 27 | "anymatch": "^2.0.0", 28 | "cheerio": "^1.0.0-rc.2", 29 | "chokidar": "^2.0.4", 30 | "emitter": "0.0.5", 31 | "fs-extra": "^6.0.1", 32 | "http-proxy": "^1.17.0", 33 | "live-server": "^1.2.0", 34 | "passport": "^0.4.0", 35 | "pretty": "^2.0.0", 36 | "puppeteer": "^1.9.0", 37 | "react": "^16.4.1", 38 | "react-dom": "^16.4.1", 39 | "rimraf": "^2.6.2" 40 | }, 41 | "devDependencies": { 42 | "@babel/core": "^7.1.2", 43 | "@babel/node": "^7.0.0", 44 | "@babel/plugin-proposal-class-properties": "^7.1.0", 45 | "@babel/plugin-proposal-decorators": "^7.1.2", 46 | "@babel/plugin-proposal-export-namespace-from": "^7.0.0", 47 | "@babel/plugin-proposal-function-sent": "^7.1.0", 48 | "@babel/plugin-proposal-numeric-separator": "^7.0.0", 49 | "@babel/plugin-proposal-throw-expressions": "^7.0.0", 50 | "@babel/plugin-transform-dotall-regex": "^7.0.0", 51 | "@babel/plugin-transform-runtime": "^7.1.0", 52 | "@babel/polyfill": "^7.0.0", 53 | "@babel/preset-env": "^7.1.0", 54 | "@babel/preset-react": "^7.0.0", 55 | "@babel/preset-stage-2": "^7.0.0", 56 | "@babel/register": "^7.0.0", 57 | "babel-loader": "^8.0.4", 58 | "chalk": "^2.4.1", 59 | "copy-webpack-plugin": "^4.6.0", 60 | "css-loader": "^1.0.0", 61 | "express": "^4.16.4", 62 | "extract-text-webpack-plugin": "^3.0.2", 63 | "faker": "^4.1.0", 64 | "json-server": "^0.14.0", 65 | "mini-css-extract-plugin": "^0.4.1", 66 | "mocha": "^5.2.0", 67 | "node-fetch": "^2.2.0", 68 | "node-loader": "^0.6.0", 69 | "node-nightly": "^1.7.3", 70 | "node-sass": "^4.9.4", 71 | "nyc": "^12.0.2", 72 | "sass": "^1.9.2", 73 | "sass-loader": "^7.0.3", 74 | "shebang-loader": "0.0.1", 75 | "style-loader": "^0.21.0", 76 | "webpack": "^4.16.0", 77 | "webpack-cli": "^3.0.8", 78 | "wtfnode": "^0.7.0" 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | // require('@babel/polyfill'); 2 | 3 | const isProd = process.env.NODE_ENV === 'production'; 4 | 5 | const readFile = require('./util/read-file'); 6 | const server = require('./server'); 7 | const printPDF = require('./util/print-pdf'); 8 | const ensureExists = require('./util/ensure-exists'); 9 | const injectStyles = require('./util/inject-styles'); 10 | const cleanHTML = require('./util/clean-html'); 11 | const getScriptSrc = require('./util/get-script-src');; 12 | const listenToChanges = require('./util/listen-to-changes'); 13 | const getCssSrc = require('./util/get-css-src'); 14 | const getHTMLFromSource = require('./util/get-html-from-source'); 15 | const insertContent = require('./util/insert-content'); 16 | const replacePageNumbers = require('./util/replace-page-numbers'); 17 | const getAssetSources = require('./util/get-asset-source'); 18 | const getContent = require('./util/get-content'); 19 | const injectCustomScripts = require('./util/inject-custom-scripts'); 20 | const ensurePage = require('./util/ensure-page'); 21 | const injectHeaderAndFooter = require('./util/inject-header-footer'); 22 | const deleteDir = require('./util/delete-dir'); 23 | const getCustomCSS = require('./util/get-custom-css'); 24 | const getCustomScripts = require('./util/get-custom-scripts'); 25 | const getOptions = require('./util/get-options'); 26 | 27 | const puppeteer = require('puppeteer'); 28 | const pretty = require('pretty'); 29 | const Writer = require('./writer'); 30 | const exec = require('child_process').exec; 31 | 32 | const Path = require('path'); 33 | const chalk = require('chalk'); 34 | 35 | class Renderer { 36 | constructor(options = {}) { 37 | this.debug = options.debug || false; 38 | this.port = options.port || 8080; 39 | this.host = options.host || '127.0.0.1'; 40 | this.width = options.width || 612; 41 | this.height = options.height || 792; 42 | this.autoOpen = options.autoOpen || false; 43 | this.dirname = options.dirname; 44 | this.keepAlive = options.keepAlive || false; 45 | this.args = options.args || []; 46 | this.margin = options.margin || { 47 | top: '0px', 48 | right: '0px', 49 | bottom: '0px', 50 | left: '0px' 51 | } 52 | 53 | this.__openBrowser = options.__openBrowser || false; 54 | 55 | if (!options.dirname) { 56 | throw new Error(`Missing required parameter 'dirname'. Please add { dirname: __dirname } to your constructor options`); 57 | } 58 | 59 | // internal stuff 60 | this._listening = false; 61 | 62 | this._changeFunc = null; 63 | this._renderedHTML = null; 64 | 65 | this._queue = [] 66 | this._activeWorkers = 0; 67 | this._maxWorkers = 20; 68 | this._lastPageSplitClass = 'Page'; 69 | 70 | this.__browserPromise = new Promise(async (resolve) => { 71 | this.browser = await puppeteer.launch({ 72 | headless: !this.__openBrowser, 73 | args: this.args, 74 | defaultViewport: { 75 | width: this.width, 76 | height: this.height === 'auto' ? 792 : this.height, 77 | deviceScaleFactor: 2 78 | } 79 | }); 80 | resolve(); 81 | }) 82 | } 83 | 84 | on = (key, func) => { 85 | switch (key) { 86 | case 'change': 87 | this._changeFunc = func; 88 | break; 89 | case 'html': 90 | this._renderedHTML = func; 91 | break; 92 | } 93 | } 94 | 95 | _stop = async (err) => { 96 | if (!this.keepAlive) { 97 | return this.stop(err); 98 | } 99 | } 100 | 101 | stop = async (err) => { 102 | 103 | await this.__browserPromise; 104 | 105 | if (this.listener) { 106 | this.listener.close(); 107 | } 108 | 109 | if (this.server) { 110 | server.close(this.server); 111 | } 112 | 113 | if (this.browser) { 114 | await this.browser.close(); 115 | } 116 | 117 | if (err) throw err; 118 | } 119 | 120 | _autoOpen = (outputFolder, outputName) => { 121 | if (this.autoOpen && !this._changeFunc) { 122 | const getCommandLine = () => { 123 | switch (process.platform) { 124 | case 'darwin' : return 'open'; 125 | case 'win32' : return 'start'; 126 | case 'win64' : return 'start'; 127 | default : return 'xdg-open'; 128 | } 129 | } 130 | 131 | exec(getCommandLine() + ' ' + `${outputFolder}/${outputName}/${outputName}.pdf`); 132 | } 133 | } 134 | 135 | _pushQueue = (f) => { 136 | this._queue.push(f); 137 | this._flush(); 138 | } 139 | 140 | _flush = async () => { 141 | if (this._activeWorkers < this._maxWorkers && this._queue.length > 0) { 142 | const next = this._queue.pop(); 143 | this._activeWorkers++; 144 | 145 | await this.__browserPromise; 146 | 147 | await next(); 148 | this._activeWorkers--; 149 | 150 | if (this._queue.length === 0 && this._activeWorkers === 0) { 151 | if (!this._changeFunc) { 152 | this._stop(); 153 | } 154 | 155 | return; 156 | } 157 | 158 | this._flush(); 159 | } 160 | 161 | } 162 | 163 | render(options) { 164 | return new Promise(async (r) => { 165 | const optionsResult = await getOptions(options, this.dirname); 166 | ({ options } = optionsResult); 167 | this._pushQueue(async () => { 168 | let result; 169 | if (typeof options.templateSource === 'string') { 170 | const src = options.templateSource.trim(); 171 | if ((src.startsWith('http') || src.startsWith('https'))) { 172 | result = await this._renderRemote(optionsResult).catch(this._stop); 173 | } 174 | } 175 | 176 | if (!result) { 177 | result = await this._render(optionsResult).catch(this._stop); 178 | } 179 | 180 | r(result); 181 | }); 182 | }).catch(this._stop) 183 | } 184 | 185 | 186 | async _renderRemote(optionsResult) { 187 | let options; 188 | let optionsPath = ''; 189 | ({ options, optionsPath } = optionsResult); 190 | 191 | let { 192 | styles = [], 193 | scripts = [], 194 | templateSource: url, 195 | outputFolder = 'outputs', 196 | outputName = 'index', 197 | ignoreWatch 198 | } = options; 199 | 200 | let style = await getCustomCSS(styles, this.dirname, this.debug); 201 | let { linkedStyles } = style; 202 | 203 | style = style.css; 204 | const renderedScripts = await getCustomScripts(scripts, this.dirname, this.debug); 205 | 206 | await ensureExists(`${outputFolder}`); 207 | 208 | const result = await printPDF({ 209 | url, 210 | scripts: renderedScripts, 211 | style, 212 | browser: this.browser, 213 | outputFolder, 214 | outputName, 215 | width: this.width, 216 | height: this.height, 217 | realtime: !!this._changeFunc, 218 | openBrowser: this.__openBrowser 219 | }); 220 | 221 | console.log(chalk.green.bold(`Succesfully finished rendering ${chalk.bold(`${outputFolder}/${outputName}.pdf\n\n`)}`)); 222 | 223 | if (this._changeFunc && !this._listening) { 224 | this.listener = listenToChanges([ 225 | ...scripts, 226 | ...styles, 227 | ...linkedStyles, 228 | optionsPath 229 | ], 230 | this._changeFunc, 231 | this.debug, 232 | ignoreWatch, 233 | this.dirname 234 | ); 235 | 236 | this._listening = true; 237 | } 238 | 239 | this._autoOpen(outputFolder, outputName); 240 | 241 | return { 242 | sourceMap: { 243 | html: result.html 244 | }, 245 | output: `${outputFolder}/${outputName}.pdf`, 246 | metadata: { 247 | numberOfPages: null 248 | } 249 | }; 250 | } 251 | 252 | async _render(optionsResult) { 253 | let options; 254 | let optionsPath = ''; 255 | ({ options, optionsPath } = optionsResult); 256 | 257 | let { 258 | templateSource, 259 | contentSource = '', 260 | outputFolder = 'outputs', 261 | outputName = 'index', 262 | styles = [], 263 | chunks = {}, 264 | assets = [], // not part of API 265 | ignoreWatch, 266 | middleware = [], 267 | pageClass = 'Page' 268 | } = options; 269 | 270 | // map of writes / sourceMap 271 | const writer = new Writer(this.debug); 272 | 273 | if (!templateSource) { 274 | await this._stop(new Error('templateSource is required')); 275 | } 276 | 277 | // If content source is set, parse it an apply it 278 | let content = await getContent({ 279 | contentSource, debug: this.debug, dirname: this.dirname 280 | }) 281 | 282 | // pass options into closure to avoid duplicating parameters everywhere 283 | const htmlGetter = getHTMLFromSource({ 284 | debug: this.debug, 285 | dirname: this.dirname, 286 | listening: this._listening, 287 | content 288 | }) 289 | 290 | let html = await htmlGetter(templateSource, 'templateSource'); 291 | 292 | // Chunks! 293 | const chunkP = Object.keys(chunks).map((chunkName) => { 294 | return new Promise(async (r) => { 295 | const chunkData = await htmlGetter(chunks[chunkName], chunkName); 296 | html = insertContent(html, { [chunkName]: cleanHTML(chunkData) }); 297 | r(); 298 | }) 299 | }) 300 | if(chunkP.length) await Promise.all(chunkP); 301 | 302 | if (!html) { 303 | await this._stop(new Error('Could not parse templateSource to html, please make sure your input is a supported format.')); 304 | } 305 | 306 | //copy scripts 307 | const scripts = getScriptSrc(html, templateSource, this.dirname); 308 | scripts.forEach(({ fullPath, relativePath }) => { 309 | const to = Path.join(`${outputFolder}/${outputName}/`, relativePath); 310 | writer.addWrite(Writer.TYPES.SCRIPT, Writer.METHODS.COPY, to, fullPath); 311 | }); 312 | 313 | 314 | styles = [...styles, ...(getCssSrc(html, templateSource, this.dirname) || [])]; 315 | const cssResult = await getCustomCSS(styles, this.dirname, this.debug); 316 | 317 | let { linkedStyles, css } = cssResult; 318 | let customCss = css; 319 | 320 | let headerChunk = ''; 321 | let footerChunk = ''; 322 | 323 | if (chunks.header) { 324 | headerChunk = await htmlGetter(chunks.header, 'header'); 325 | } 326 | 327 | if (chunks.footer) { 328 | footerChunk = await htmlGetter(chunks.footer, 'footer'); 329 | } 330 | 331 | //HTML transforms 332 | html = cleanHTML(html, true); 333 | html = ensurePage(html, pageClass); 334 | html = injectHeaderAndFooter(html, pageClass, headerChunk, footerChunk); 335 | html = injectStyles(html, !!customCss); 336 | html = replacePageNumbers(html, pageClass); 337 | html = injectCustomScripts(html, content, pageClass); 338 | html = pretty(html, { ocd: true }); 339 | 340 | // copy assets 341 | assets = [...assets, ...getAssetSources(html, customCss, this.dirname)]; 342 | assets.forEach((asset) => { 343 | 344 | const relativeLocation = Path.relative(this.dirname, asset) 345 | writer.addWrite( 346 | Writer.TYPES.ASSET, 347 | Writer.METHODS.COPY, 348 | Path.join(`${outputFolder}/${outputName}`, relativeLocation), 349 | asset 350 | ) 351 | }) 352 | 353 | const nextMiddleWare = async () => { 354 | const next = middleware.pop(); 355 | if (!next) return; 356 | html = await next(html); 357 | return nextMiddleWare(); 358 | } 359 | 360 | middleware.reverse(); 361 | await nextMiddleWare(); 362 | 363 | if (this._renderedHTML) { 364 | this._renderedHTML(html); 365 | } 366 | 367 | if (!this._listening) { 368 | await ensureExists(`${outputFolder}`); 369 | await ensureExists(`${outputFolder}/${outputName}`); 370 | } 371 | 372 | 373 | if (!!customCss) { 374 | writer.addWrite(Writer.TYPES.CSS, Writer.METHODS.DATA, `${outputFolder}/${outputName}/custom.css`, customCss); 375 | } 376 | 377 | writer.addWrite(Writer.TYPES.HTML, Writer.METHODS.DATA, `${outputFolder}/${outputName}/index.html`, html); 378 | 379 | // only write this once, so if we are already listening then we dont need to write it again (unless the pageClass changes) 380 | if (!this._listening || pageClass !== this._lastPageSplitClass) { 381 | const path = Path.resolve(__dirname, isProd ? './index.css' : `./styles/index.css`); 382 | let css = await readFile(path); 383 | 384 | css = css.replace(/__WIDTH/g, this.width + 'px'); 385 | css = css.replace(/__HEIGHT/g, this.height + 'px'); 386 | css = css.replace(/__PAGE_NAME/g, pageClass); 387 | css = css.replace(/__MARGIN/g, `${this.margin.top} ${this.margin.right} ${this.margin.bottom} ${this.margin.left} !important`) 388 | 389 | writer.addWrite(Writer.TYPES.CSS, Writer.METHODS.DATA, `${outputFolder}/${outputName}/index.css`, css); 390 | } 391 | 392 | this._lastPageSplitClass = pageClass; 393 | 394 | const sourceMap = await writer.write(); 395 | 396 | if (!this.server) { 397 | this.server = await server(this.port, this.host, outputFolder, this.debug); 398 | if (this._changeFunc) { 399 | console.log(chalk.green(`You can view your live PDF at ${chalk.bgGreen.whiteBright(`http://${this.host}:${this.port}/${outputName}`)}\n`)); 400 | } 401 | } 402 | 403 | const reg = new RegExp(`class=['"].*?${pageClass}.*?['"].*?>`, 'gm'); 404 | const numberOfPages = (html.match(reg) || []).length 405 | 406 | await printPDF({ 407 | outputFolder, 408 | outputName, 409 | numberOfPages, 410 | browser: this.browser, 411 | width: this.width, 412 | height: this.height, 413 | margin: this.margin, 414 | realtime: !!this._changeFunc, 415 | source: `http://${this.host}:${this.port}` 416 | }); 417 | 418 | console.log(chalk.green.bold(`Succesfully finished rendering ${chalk.bold(`${outputFolder}/${outputName}.pdf\n\n`)}`)) 419 | 420 | if (this._changeFunc && !this._listening) { 421 | this.listener = listenToChanges( 422 | [ 423 | contentSource, 424 | templateSource, 425 | ...Object.values(chunks), 426 | ...scripts, 427 | ...styles, 428 | ...assets, 429 | ...linkedStyles, 430 | optionsPath, 431 | ], 432 | this._changeFunc, 433 | this.debug, 434 | ignoreWatch, 435 | this.dirname 436 | ); 437 | 438 | this._listening = true; 439 | } 440 | 441 | if (!this.debug && !this._changeFunc) { 442 | await deleteDir(`${outputFolder}/${outputName}`); 443 | } 444 | 445 | this._autoOpen(outputFolder, outputName); 446 | 447 | 448 | return { 449 | sourceMap, 450 | output: `${outputFolder}/${outputName}.pdf`, 451 | metadata: { 452 | numberOfPages 453 | } 454 | }; 455 | } 456 | } 457 | 458 | module.exports = Renderer; 459 | -------------------------------------------------------------------------------- /src/server.js: -------------------------------------------------------------------------------- 1 | const liveServer = require('live-server'); 2 | 3 | module.exports = (port, host, outputFolder, debug) => { 4 | return new Promise(async r => { 5 | const params = { 6 | port, 7 | host, 8 | root: `${outputFolder}`, 9 | open: false, 10 | quiet: true, 11 | logLevel: 0, 12 | ignore: '**/*.html,**/*.js,**/*.css,**/*.scss', 13 | wait: 500 14 | }; 15 | 16 | const s = liveServer.start(params); 17 | await new Promise(resolve => setTimeout(resolve, 1000)); 18 | r(s); 19 | }) 20 | 21 | } 22 | 23 | module.exports.close = (instance) => { 24 | liveServer.shutdown(instance); 25 | } -------------------------------------------------------------------------------- /src/styles/index.css: -------------------------------------------------------------------------------- 1 | * { 2 | box-sizing: border-box; 3 | -webkit-print-color-adjust: exact; 4 | } 5 | 6 | html, body { 7 | padding: 0; 8 | margin: 0; 9 | font-family: Roboto; 10 | background-color: rgb(247, 239, 239); 11 | color: black; 12 | display: flex; 13 | flex-direction: column; 14 | align-items: center; 15 | } 16 | 17 | .__PAGE_NAME { 18 | width: __WIDTH !important; 19 | height: __HEIGHT !important; 20 | background-color: white; 21 | position: relative; 22 | padding: __MARGIN; 23 | } 24 | 25 | body * { 26 | max-width: __WIDTH; 27 | max-height: __HEIGHT; 28 | } 29 | 30 | .page-spacer { 31 | height: 2px; 32 | width: 100vw; 33 | background: #00a5e4; 34 | opacity: 0.5; 35 | left: 0; 36 | min-width: 100vw; 37 | z-index: 999; 38 | } 39 | 40 | .List { 41 | max-height: 100% !important; 42 | } 43 | 44 | .List > * { 45 | max-height: 100% !important; 46 | } 47 | 48 | .webpdf-element { 49 | position: absolute; 50 | left: 0; 51 | right: 0; 52 | width: 100%; 53 | z-index: 99; 54 | } 55 | 56 | .webpdf-header { 57 | top: 0; 58 | } 59 | 60 | .webpdf-footer { 61 | bottom: 0; 62 | } 63 | 64 | .webpdf-error { 65 | color: white; 66 | background-color: red; 67 | position: fixed; 68 | z-index: 9999; 69 | top: 0; 70 | left: 0; 71 | width: 100vw; 72 | height: 100vh; 73 | display: flex; 74 | justify-content: center; 75 | align-items: center; 76 | } 77 | 78 | .webpdf-error p { 79 | font-size: 40px; 80 | } 81 | 82 | -------------------------------------------------------------------------------- /src/util/clean-html.js: -------------------------------------------------------------------------------- 1 | 2 | module.exports = (input, includeOuter) => { 3 | input = input.replace(/&/g, '&'); 4 | input = input.replace(/</g, '<'); 5 | input = input.replace(/>/g, '>'); 6 | input = input.replace(/'/g, '"') 7 | input = input.replace(/\\n/g, ` 8 | `) 9 | 10 | if (includeOuter) { 11 | const html = //gms; 12 | const body = //gms; 13 | const hasBody = input.match(body); 14 | 15 | if (!input.match(html)) { 16 | if (hasBody) { 17 | input = `${input}` 18 | } else { 19 | input = `${input}` 20 | } 21 | } else if (!hasBody) { 22 | input = input.replace(html, (m ,g1) => { 23 | return `${g1}` 24 | }) 25 | } 26 | } 27 | 28 | return input; 29 | } -------------------------------------------------------------------------------- /src/util/copy-dir.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs-extra') 2 | const path = require('path'); 3 | 4 | module.exports = (from, to) => { 5 | return new Promise(async (resolve) => { 6 | 7 | var cbCalled = false; 8 | 9 | fs.ensureDirSync( 10 | path.dirname(to) 11 | ) 12 | 13 | var rd = fs.createReadStream(from); 14 | rd.on("error", function(err) { 15 | done(err); 16 | }); 17 | var wr = fs.createWriteStream(to); 18 | wr.on("error", function(err) { 19 | done(err); 20 | }); 21 | wr.on("close", function(ex) { 22 | done(); 23 | }); 24 | rd.pipe(wr); 25 | 26 | function done(err) { 27 | if (!cbCalled) { 28 | return resolve(); 29 | cbCalled = true; 30 | } 31 | } 32 | 33 | }) 34 | } -------------------------------------------------------------------------------- /src/util/custom-require.js: -------------------------------------------------------------------------------- 1 | const isProd = process.env.NODE_ENV === 'production'; 2 | 3 | module.exports = () => { 4 | if (isProd) { 5 | return __non_webpack_require__; 6 | } else { 7 | return require; 8 | } 9 | } -------------------------------------------------------------------------------- /src/util/delete-dir.js: -------------------------------------------------------------------------------- 1 | const rimraf = require('rimraf'); 2 | 3 | module.exports = (dir) => { 4 | return new Promise((r) => { 5 | rimraf(dir, r); 6 | }) 7 | } -------------------------------------------------------------------------------- /src/util/does-file-exist.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | 3 | module.exports = (path) => { 4 | return fs.existsSync(path); 5 | } -------------------------------------------------------------------------------- /src/util/ensure-exists.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | 3 | module.exports = (path, mask) => { 4 | return new Promise(resolve => { 5 | if (typeof mask == 'function') { // allow the `mask` parameter to be optional 6 | cb = mask; 7 | mask = 484; 8 | } 9 | fs.mkdir(path, mask, function(err) { 10 | if (err) { 11 | if (err.code == 'EEXIST') return resolve(); // ignore the error if the folder already exists 12 | throw err; 13 | } else resolve(); // successfully created folder 14 | }); 15 | }) 16 | 17 | } -------------------------------------------------------------------------------- /src/util/ensure-page.js: -------------------------------------------------------------------------------- 1 | const cheerio = require('cheerio') 2 | 3 | module.exports = (html, pageClass) => { 4 | const $ = cheerio.load(html); 5 | 6 | const pages = $(`.${pageClass}`); 7 | 8 | if (pages.length > 0) return html; 9 | 10 | const bodyRegex = /(.*?)<\/body>/gms; 11 | 12 | return html.replace(bodyRegex, (m ,g1) => { 13 | return `
${g1}
` 14 | }) 15 | 16 | } -------------------------------------------------------------------------------- /src/util/get-asset-source.js: -------------------------------------------------------------------------------- 1 | const Path = require('path'); 2 | 3 | module.exports = (html, css, dirname) => { 4 | const results = {}; 5 | 6 | const getter = (m, g1) => { 7 | g1 = g1.trim(); 8 | 9 | if (g1.startsWith('http')) return m; 10 | 11 | const fullPath = Path.resolve(dirname, g1); 12 | results[fullPath] = true; 13 | return m; 14 | } 15 | 16 | html.replace(/<(?!script).*?src=['"](.*?)['"].*?>/gm, getter); 17 | 18 | if (css) { 19 | css.replace(/url\(['"](.*?)['"]\)/gm, getter); 20 | } 21 | 22 | return Object.keys(results); 23 | } -------------------------------------------------------------------------------- /src/util/get-content.js: -------------------------------------------------------------------------------- 1 | const getType = require('./type-check'); 2 | const readFile = require('./read-file'); 3 | const Path = require('path'); 4 | const chalk = require('chalk'); 5 | 6 | module.exports = async ({ contentSource, debug, dirname }) => { 7 | let obj = {}; 8 | // If content source is set, parse it an apply it 9 | if (contentSource) { 10 | const contentSourceType = getType(contentSource); 11 | 12 | if (contentSourceType === 'string') { 13 | contentSource = contentSource.trim(); 14 | if (contentSource.endsWith('.json')) { 15 | const j = await readFile(Path.resolve(dirname, contentSource)); 16 | try { 17 | obj = JSON.parse(j); 18 | } catch (e) { 19 | obj = null; 20 | if (debug) { 21 | console.log(chalk.red(`${Path.resolve(dirname, contentSource)} contains invalid JSON, Skipping`)); 22 | } 23 | } 24 | 25 | if (debug) { 26 | console.log(chalk.keyword('orange')(`Got content from ${chalk.bold(Path.resolve(dirname, contentSource))}`)) 27 | } 28 | 29 | } else { 30 | 31 | if (debug) { 32 | console.log(chalk.keyword('orange')(`Got content from object passed in from contentSource`)) 33 | } 34 | obj = JSON.parse(contentSource); 35 | } 36 | } else if(contentSourceType === 'object' || contentSourceType === 'array'){ 37 | obj = contentSource; 38 | } 39 | 40 | if(debug && !obj) { 41 | console.log(chalk.red('contentSource could not be parsed, skipping')); 42 | } 43 | } 44 | 45 | 46 | return obj; 47 | } -------------------------------------------------------------------------------- /src/util/get-css-src.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | 3 | module.exports = (html, templateSource, dirname = __dirname) => { 4 | const regex = / { 13 | if (g1.startsWith('http')) return html; 14 | 15 | list.push(path.resolve(pathToHTML, g1)); 16 | return html; 17 | }) 18 | 19 | return list; 20 | 21 | } -------------------------------------------------------------------------------- /src/util/get-custom-css.js: -------------------------------------------------------------------------------- 1 | const NodeSass = require('node-sass'); 2 | const doesFileExist = require('./does-file-exist'); 3 | const Path = require('path'); 4 | 5 | module.exports = async (styles, dirname, debug) => { 6 | let linkedStyles = []; 7 | const p = styles.map((src) => { 8 | if (src.endsWith('css') || src.endsWith('scss')) { 9 | src = Path.resolve(dirname, src); 10 | return new Promise(async r => { 11 | const exists = doesFileExist(src); 12 | if (!exists) { 13 | if (debug) console.log(chalk.red(`File ${src} was not found, skipping`)); 14 | return r(''); 15 | } 16 | 17 | let data = ''; 18 | if (src.endsWith('.css')) { 19 | data = await readFile(src); 20 | } else if (src.endsWith('.scss')) { 21 | const nodeResults = NodeSass.renderSync({ file: src }) 22 | data = nodeResults.css; 23 | linkedStyles = nodeResults.stats.includedFiles; 24 | } 25 | r(data); 26 | }) 27 | } else { 28 | const nodeResults = NodeSass.renderSync({ data: src }) 29 | return Promise.resolve(nodeResults.css); 30 | } 31 | 32 | }); 33 | 34 | const result = await Promise.all(p); 35 | return { 36 | css: result.reduce((acc, s) => { return acc + `\n${s}` }, '') || null, 37 | linkedStyles 38 | } 39 | } -------------------------------------------------------------------------------- /src/util/get-custom-scripts.js: -------------------------------------------------------------------------------- 1 | const Path = require('path'); 2 | const doesFileExist = require('./does-file-exist'); 3 | const readFile = require('./read-file'); 4 | 5 | 6 | module.exports = async (scripts, dirname, debug) => { 7 | const p = scripts.map((src) => { 8 | src = Path.resolve(dirname, src); 9 | return new Promise(async r => { 10 | const exists = doesFileExist(src); 11 | if (!exists) { 12 | if (debug) console.log(chalk.red(`File ${src} was not found, skipping`)); 13 | return r(''); 14 | } 15 | 16 | let data = ''; 17 | data = await readFile(src); 18 | r(data); 19 | }) 20 | }); 21 | 22 | const result = await Promise.all(p); 23 | return result.reduce((acc, s) => { return acc + `\n${s}` }, '') || null; 24 | } -------------------------------------------------------------------------------- /src/util/get-html-from-source.js: -------------------------------------------------------------------------------- 1 | const chalk = require('chalk'); 2 | const getRenderType = require('./get-render-type'); 3 | const insertContent = require('./insert-content'); 4 | const reactToHTML = require('./react-to-html'); 5 | const Path = require('path'); 6 | const readFile = require('./read-file'); 7 | 8 | const TYPES = getRenderType.TYPES; 9 | 10 | module.exports = ({debug, listening, dirname, content}) => async (templateSource, chunkName) => { 11 | 12 | const renderType = getRenderType(templateSource, content); 13 | let html = null; 14 | 15 | if (debug && !listening) { 16 | console.log(chalk.black(`Using type ${chalk.whiteBright.bold.bgBlack(' ' + renderType + ' ')} for ${chalk.bold(chunkName)}`)); 17 | } 18 | 19 | switch (renderType) { 20 | case TYPES.REACT_COMPONENT: 21 | { 22 | html = reactToHTML({ Component: templateSource, content }) 23 | break; 24 | } 25 | case TYPES.CUSTOM_FUNCTION: 26 | { 27 | html = await templateSource(content); 28 | break; 29 | } 30 | case TYPES.HTML_STRING: 31 | { 32 | html = templateSource; 33 | break; 34 | } 35 | case TYPES.HTML_FILE: 36 | { 37 | html = await readFile(Path.resolve(dirname, templateSource)); 38 | if (html === null) { 39 | throw new Error(`File ${templateSource} was not found.`); 40 | } 41 | break; 42 | } 43 | } 44 | 45 | // replace content 46 | if (content) { 47 | html = insertContent(html, content); 48 | } 49 | 50 | return html; 51 | } -------------------------------------------------------------------------------- /src/util/get-options.js: -------------------------------------------------------------------------------- 1 | const getType = require('./type-check'); 2 | const Path = require('path'); 3 | const customRequire = require('./custom-require'); 4 | 5 | const getComp = (dirname) => { 6 | p = Path.resolve(dirname, p); 7 | delete require.cache[require.resolve(p)] 8 | const c = require(p); 9 | return c; 10 | } 11 | 12 | module.exports = async (options, dirname) => { 13 | let optionsPath = ''; 14 | const optionsType = getType(options) 15 | if (optionsType === 'string') { 16 | optionsPath = Path.resolve(dirname, options); 17 | delete customRequire().cache[customRequire().resolve(optionsPath)]; 18 | options = customRequire()(optionsPath); 19 | 20 | if (getType(options) !== 'function') { 21 | await this.stop(new Error(chalk.bgRed.whiteBright(`Please export a function from ${optionsPath}. Got type: '${optionsType}'`))); 22 | } 23 | 24 | options = await options(getComp); 25 | } 26 | 27 | return { options, optionsPath }; 28 | } -------------------------------------------------------------------------------- /src/util/get-render-type.js: -------------------------------------------------------------------------------- 1 | const React = require('react'); 2 | const getType = require('./type-check'); 3 | 4 | const TYPES = { 5 | REACT_COMPONENT: "REACT_COMPONENT", 6 | CUSTOM_FUNCTION: "CUSTOM_FUNCTION", 7 | HTML_STRING: "HTML_STRING", 8 | HTML_FILE: "HTML_FILE" 9 | } 10 | 11 | module.exports = (Input, obj) => { 12 | const type = getType(Input); 13 | 14 | if (type === 'function') { 15 | 16 | try { 17 | let funcOutput = Input(obj); 18 | let funcOutputType = getType(funcOutput); 19 | if (funcOutputType === 'string' || funcOutput.then) { 20 | return TYPES.CUSTOM_FUNCTION; 21 | } 22 | } catch (e) { 23 | // Not a custom function 24 | } 25 | 26 | const isReact = React.isValidElement(); 27 | if (isReact) { 28 | return TYPES.REACT_COMPONENT; 29 | } 30 | 31 | } 32 | 33 | if (type === 'string') { 34 | Input = Input.trim(); 35 | 36 | if (Input.startsWith('<')) { 37 | return TYPES.HTML_STRING; 38 | } 39 | 40 | if (Input.endsWith('.html')) { 41 | return TYPES.HTML_FILE; 42 | } 43 | 44 | } 45 | } 46 | 47 | module.exports.TYPES = TYPES; -------------------------------------------------------------------------------- /src/util/get-script-src.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | 3 | module.exports = (html, templateSource, dirname = __dirname) => { 4 | const regex = / { 13 | if (g1.startsWith('http')) return html; 14 | 15 | list.push({ 16 | fullPath: path.resolve(htmlPath, g1), 17 | relativePath: g1 18 | }); 19 | return html; 20 | }) 21 | 22 | return list; 23 | 24 | } -------------------------------------------------------------------------------- /src/util/inject-custom-scripts.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | const getScript = (pageClass) => { 4 | return ` 5 | (function() { 6 | function checkOverflow(el) 7 | { 8 | var curOverflow = el.style.overflow; 9 | 10 | if ( !curOverflow || curOverflow === "visible" ) 11 | el.style.overflow = "auto"; 12 | 13 | var isOverflowing = el.clientHeight < el.scrollHeight; 14 | 15 | el.style.overflow = curOverflow; 16 | 17 | return isOverflowing; 18 | } 19 | 20 | var lists = document.getElementsByClassName('List'); 21 | 22 | for(var i = 0; i < lists.length; i++) { 23 | 24 | var list = lists[i]; 25 | var listChildren = list.children; 26 | 27 | var page = list.closest(".${pageClass}"); 28 | 29 | var cloned = []; 30 | 31 | for(var ii = 0; ii < listChildren.length; ii++) { 32 | var child = listChildren[ii]; 33 | var style = getComputedStyle(child); 34 | cloned.push({ 35 | node: child.cloneNode(true), 36 | 37 | }); 38 | } 39 | 40 | list.innerHTML = ''; 41 | 42 | var ii = 0, howManyTimes = cloned.length; 43 | function f(done) { 44 | var child = cloned[ii]; 45 | var node = child.node; 46 | list.appendChild(node); 47 | 48 | setTimeout(function() { 49 | if(checkOverflow(list)) { 50 | 51 | var clone = node.cloneNode(true); 52 | node.remove(); 53 | // list.parentNode.removeChild(node); 54 | 55 | var newPage = document.createElement('div'); 56 | var newList = document.createElement('div'); 57 | 58 | newList.appendChild(clone); 59 | 60 | newList.className = list.className; 61 | newPage.className = '${pageClass}'; 62 | 63 | newPage.appendChild(newList); 64 | list = newList; 65 | 66 | page.parentNode.insertBefore(newPage, page.nextSibling); 67 | page = newPage; 68 | } 69 | 70 | ii++; 71 | if( ii < howManyTimes ){ 72 | f(done); 73 | } else { 74 | done() 75 | } 76 | 77 | }, 0); 78 | } 79 | f(); 80 | } 81 | 82 | 83 | if(window.location.hash !== '#node') { 84 | var eles = document.getElementsByClassName('${pageClass}'); 85 | for(var iii = 0; iii < eles.length; iii++) { 86 | var ele = eles[iii]; 87 | 88 | var node = document.createElement('div'); 89 | node.className = 'page-spacer'; 90 | 91 | ele.parentNode.insertBefore(node, ele.nextSibling); 92 | } 93 | } 94 | 95 | })() 96 | `; 97 | } 98 | 99 | const inject = (html, content, pageClass) => { 100 | const r = /(.*)<\/body>/gms; 101 | 102 | html = html.replace(r, (m, g1) => { 103 | return ` 104 | 105 | 106 | 109 | 110 | ${g1} 111 | 112 | 113 | 116 | 117 | ` 118 | }); 119 | 120 | return html; 121 | } 122 | 123 | module.exports = inject; 124 | 125 | -------------------------------------------------------------------------------- /src/util/inject-header-footer.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | module.exports = (html, pageClass, header = '', footer = '') => { 4 | 5 | const pageRegex = new RegExp(`(.*?)<\/div>`, 'gms') 6 | 7 | return html.replace(pageRegex, (m, g1) => { 8 | const r = m.replace(g1, (match) => { 9 | return `
${header}
10 | ${match} 11 | `; 12 | }); 13 | 14 | return r; 15 | }) 16 | } -------------------------------------------------------------------------------- /src/util/inject-styles.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | module.exports = (html, hasCustom) => { 4 | 5 | let match = false; 6 | 7 | const css = ` 8 | 9 | ${hasCustom ? ` ` : ''} 10 | `; 11 | 12 | html = html.replace(//gm, ''); 13 | 14 | // if there is a head tag present 15 | html = html.replace(/(.*)<\/head>/ms, (fm, g1) => { 16 | match = true; 17 | return ` 18 | 19 | ${g1.trim()} 20 | ${css.trim()} 21 | 22 | `; 23 | }); 24 | 25 | // if there is no head tag present 26 | if (!match) { 27 | html = html.replace(/(.*)<\/html>/ms, (fm, g1) => { 28 | match = true; 29 | return ` 30 | 31 | 32 | ${css.trim()} 33 | 34 | 35 | ${g1.trim()} 36 | 37 | `; 38 | }); 39 | } 40 | 41 | if (!match) { 42 | console.warn("Please make sure your html is formatted properly. CSS styles could not be injected."); 43 | } 44 | 45 | 46 | return html; 47 | 48 | } -------------------------------------------------------------------------------- /src/util/insert-content.js: -------------------------------------------------------------------------------- 1 | const getType = require('./type-check'); 2 | 3 | const getValue = (keys, objToSearch) => { 4 | const key = keys.pop(); 5 | 6 | const value = objToSearch[key]; 7 | if (!value) return null; 8 | 9 | const type = getType(value); 10 | 11 | if (type === 'string') return value; 12 | if (type === 'number') return value; 13 | 14 | if (type === 'array') { 15 | return "~|" + JSON.stringify(value) + "|~"; 16 | } 17 | 18 | return getValue(keys, value); 19 | } 20 | 21 | module.exports = (string, contentObj) => { 22 | const regex = /{{(.*?)}}/gm; 23 | 24 | let r = string; 25 | 26 | if (contentObj) { 27 | r = string.replace(regex, (m, g1) => { 28 | const splitKeys = g1.trim().split('.').reverse(); 29 | 30 | const v = getValue(splitKeys, contentObj); 31 | 32 | if (!v) { 33 | return m 34 | } 35 | 36 | const result = v.replace(/\n/g, "\\n"); 37 | return result; 38 | }); 39 | } 40 | 41 | return r.replace(/~\|/g, '').replace(/\|~/g, ''); 42 | 43 | } -------------------------------------------------------------------------------- /src/util/listen-to-changes.js: -------------------------------------------------------------------------------- 1 | const chokidar = require('chokidar'); 2 | const chalk = require('chalk'); 3 | const anymatch = require('anymatch'); 4 | const fs = require('fs-extra'); 5 | const path = require('path'); 6 | module.exports = (sources, callback, debug, ignoreWatch, dirname) => { 7 | let throttle = null; 8 | 9 | sources = sources.reduce((acc, src) => { 10 | if (typeof src !== 'string') { 11 | return acc; 12 | } 13 | 14 | if (ignoreWatch && anymatch(ignoreWatch, src)) { 15 | return acc; 16 | } 17 | 18 | if (!src || src === '') { 19 | return acc; 20 | } 21 | 22 | if (!fs.existsSync(src)) { 23 | 24 | // try to resolve it 25 | src = path.resolve(dirname, src); 26 | 27 | if (!fs.existsSync(src)) { 28 | return acc; 29 | } 30 | 31 | } 32 | 33 | acc.push(src); 34 | 35 | return acc; 36 | }, []); 37 | 38 | if (debug) { 39 | console.log(chalk.bgMagenta.whiteBright('Listening to these files:')) 40 | sources.forEach(src => console.log(chalk.magenta(src))); 41 | console.log("\n"); 42 | } 43 | 44 | return chokidar.watch(sources).on('change', (...params) => { 45 | clearTimeout(throttle); 46 | throttle = setTimeout(() => { 47 | if (debug) { 48 | params.forEach(p => { 49 | if (typeof p === 'string') { 50 | console.log(chalk.magenta(`Detected change at ${chalk.bold(p)}`)) 51 | } 52 | }) 53 | } 54 | if (callback) { 55 | callback(params); 56 | } 57 | }, 1000) 58 | }); 59 | } -------------------------------------------------------------------------------- /src/util/print-pdf.js: -------------------------------------------------------------------------------- 1 | module.exports = ({ url, scripts, style, browser, outputFolder, outputName, width, height, source, numberOfPages = 1 }) => { 2 | return new Promise(async (resolve) => { 3 | 4 | const page = await browser.newPage(); 5 | 6 | const p = page.waitForNavigation(); 7 | 8 | if (source) { 9 | await page.goto(source + '/' + outputName + "#node", {waitUntil: 'networkidle0'}); 10 | } else { 11 | await page.goto(url, { waitUntil: 'networkidle0' }); 12 | } 13 | 14 | await p; 15 | 16 | if (style && url) { 17 | await page.addStyleTag({ 18 | content: style 19 | }) 20 | } 21 | 22 | if (scripts && url) { 23 | await page.addScriptTag({ 24 | content: scripts, 25 | }) 26 | } 27 | 28 | await page.emulateMedia('screen'); 29 | if (height === 'auto') { 30 | let override = Object.assign(page.viewport(), { width }); 31 | await page.setViewport(override); 32 | 33 | height = await page.evaluate(() => { 34 | return document.documentElement.offsetHeight; 35 | }); 36 | } 37 | 38 | await page.setViewport({ width, height }); 39 | 40 | await page.pdf({ 41 | path: `${outputFolder}/${outputName}.pdf`, 42 | printBackground: true, 43 | width: width + 'px', 44 | height: height + 'px', 45 | pageRanges: `1-${Math.max(1, numberOfPages)}` 46 | }) 47 | 48 | const html = await page.content(); 49 | 50 | await page.close(); 51 | 52 | return resolve({ 53 | browser, 54 | html 55 | }); 56 | }) 57 | } -------------------------------------------------------------------------------- /src/util/react-to-html.js: -------------------------------------------------------------------------------- 1 | const React = require('react'); 2 | const ReactDOMServer = require('react-dom/server'); 3 | 4 | {/* 5 | */} 6 | 7 | module.exports = ({ Component, content }) => { 8 | const inner = ReactDOMServer.renderToString(); 9 | 10 | return ` 11 | 12 | 13 | 14 | 15 | 16 | 17 | ${inner} 18 | 19 | ` 20 | } -------------------------------------------------------------------------------- /src/util/read-file.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | 3 | module.exports = (path) => { 4 | return new Promise((resolve) => { 5 | fs.readFile(path, (err, data) => { 6 | if (err) { 7 | return resolve(null); 8 | } 9 | resolve('' + data); 10 | }) 11 | }) 12 | } -------------------------------------------------------------------------------- /src/util/replace-page-numbers.js: -------------------------------------------------------------------------------- 1 | const cheerio = require('cheerio') 2 | 3 | 4 | module.exports = (html, pageClass) => { 5 | 6 | const regex = /\{\{pageNumber\}\}/gms; 7 | 8 | if (!html.match(regex)) { 9 | return html; 10 | } 11 | 12 | const $ = cheerio.load(html); 13 | 14 | $(`.${pageClass}`).map(function (index) { 15 | let o = $(this); 16 | let innerText = o.html(); 17 | innerText = innerText.replace(regex, index + 1); 18 | return o.html(innerText); 19 | }); 20 | 21 | return $.html(); 22 | } -------------------------------------------------------------------------------- /src/util/to-absolute.js: -------------------------------------------------------------------------------- 1 | const Path = require('path'); 2 | 3 | module.exports = (arr, dirname) => { 4 | return arr.map(src => Path.resolve(dirname, src)); 5 | } -------------------------------------------------------------------------------- /src/util/type-check.js: -------------------------------------------------------------------------------- 1 | module.exports = (o) => { 2 | if (!o) return null; 3 | if (Array.isArray(o)) return 'array'; 4 | if (typeof o === 'string') return 'string'; 5 | if (typeof o === 'number') return 'number'; 6 | if (typeof o === 'function') return 'function'; 7 | 8 | if (typeof o === 'object') return 'object'; 9 | } -------------------------------------------------------------------------------- /src/util/verify-page.js: -------------------------------------------------------------------------------- 1 | // this script checks that at least one .Page exists 2 | 3 | module.exports = (html) => { 4 | return html.match(/class=['"]\s?Page\s?['"]/gms); 5 | } -------------------------------------------------------------------------------- /src/util/write-file.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const EnsureExists = require('./ensure-exists'); 3 | const path = require('path'); 4 | 5 | module.exports = (filePath, data) => { 6 | return new Promise(async (resolve) => { 7 | 8 | const dir = path.dirname(filePath); 9 | 10 | await EnsureExists(dir); 11 | fs.writeFile(filePath, data, resolve); 12 | }) 13 | } -------------------------------------------------------------------------------- /src/writer.js: -------------------------------------------------------------------------------- 1 | const writeFile = require('./util/write-file'); 2 | const copyFile = require('./util/copy-dir'); 3 | const chalk = require('chalk'); 4 | 5 | class Writer { 6 | constructor(debug) { 7 | this.writes = {}; 8 | this.debug = debug; 9 | } 10 | 11 | addWrite = (type, method, to, from) => { 12 | if (!this.writes[type]) { 13 | this.writes[type] = []; 14 | } 15 | this.writes[type].push({ 16 | method, 17 | to, 18 | from 19 | }); 20 | } 21 | 22 | write = async () => { 23 | 24 | if (this.debug) { 25 | console.log(chalk.bgCyan.whiteBright("\nMaking the following writes:")); 26 | } 27 | 28 | const p = Object.keys(this.writes).map((type) => new Promise(async (r) => { 29 | const writesForType = this.writes[type]; 30 | 31 | const pp = writesForType.map((writeData) => new Promise(async rr => { 32 | const { method, to, from } = writeData; 33 | 34 | if (method === METHODS.COPY) { 35 | 36 | if (this.debug) { 37 | console.log(chalk.cyan(`Copying ${chalk.bold(from)} to ${chalk.bold(to)}`)) 38 | } 39 | 40 | await copyFile(from, to); 41 | } else { 42 | 43 | if (this.debug) { 44 | console.log(chalk.cyan(`Writing ${chalk.bold(to)}`)) 45 | } 46 | 47 | await writeFile(to, from); 48 | } 49 | 50 | rr(); 51 | })) 52 | 53 | await Promise.all(pp); 54 | r(); 55 | })); 56 | 57 | await Promise.all(p); 58 | 59 | const copy = { ...this.writes }; 60 | 61 | this.writes = {}; 62 | 63 | console.log('\n'); 64 | 65 | return copy; 66 | } 67 | } 68 | 69 | const TYPES = { 70 | HTML: 'html', 71 | CSS: 'css', 72 | SCRIPT: 'script', 73 | ASSET: 'assets' 74 | } 75 | 76 | const METHODS = { 77 | DATA: "data", 78 | COPY: "copy" 79 | } 80 | 81 | module.exports = Writer; 82 | module.exports.TYPES = TYPES; 83 | module.exports.METHODS = METHODS; -------------------------------------------------------------------------------- /test/assets.js: -------------------------------------------------------------------------------- 1 | require('@babel/polyfill'); 2 | const getAssetSources = require('../src/util/get-asset-source'); 3 | const assert = require('assert'); 4 | const path = require('path'); 5 | 6 | describe('assets', () => { 7 | it('can get a list of assets from HTML', async () => { 8 | 9 | const html = ` 10 |
11 | 12 | 13 |
14 | ` 15 | 16 | const r = getAssetSources(html, null, __dirname); 17 | 18 | assert(r.length === 2); 19 | assert(r.indexOf(path.resolve(__dirname, 'img.png')) > -1); 20 | assert(r.indexOf(path.resolve(__dirname, 'asset.jpg')) > -1); 21 | 22 | return; 23 | }); 24 | 25 | it('can get a list of assets from css', async () => { 26 | 27 | const html = ` 28 |
29 |
30 | ` 31 | 32 | const css = ` 33 | .bg { 34 | background-image: url('img.png'); 35 | } 36 | ` 37 | 38 | const r = getAssetSources(html, css, __dirname); 39 | 40 | assert(r.length === 1); 41 | assert(r.indexOf(path.resolve(__dirname, 'img.png')) > -1); 42 | 43 | return; 44 | 45 | 46 | }) 47 | 48 | }) -------------------------------------------------------------------------------- /test/assets/content.json: -------------------------------------------------------------------------------- 1 | { 2 | "test": "test", 3 | "react": "pdf", 4 | "nested": { 5 | "data": "is cool" 6 | } 7 | } -------------------------------------------------------------------------------- /test/assets/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |
4 | {{react}} 5 | 6 | {{nested.data}} 7 | 8 | 9 | {{customFooter}} 10 |
11 | 12 | -------------------------------------------------------------------------------- /test/assets/options.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | module.exports = () => { 4 | return { 5 | templateSource: "
" 6 | } 7 | } -------------------------------------------------------------------------------- /test/assets/script.js: -------------------------------------------------------------------------------- 1 | console.log('waddup'); -------------------------------------------------------------------------------- /test/assets/style.scss: -------------------------------------------------------------------------------- 1 | .MY-STYLE { 2 | background-color: red; 3 | } -------------------------------------------------------------------------------- /test/assets/temp.txt: -------------------------------------------------------------------------------- 1 | My data 0.7759274003893943 -------------------------------------------------------------------------------- /test/clean-html.js: -------------------------------------------------------------------------------- 1 | require('@babel/polyfill'); 2 | const assert = require('assert'); 3 | const cleanHTML = require('../src/util/clean-html'); 4 | const ensurePage = require('../src/util/ensure-page'); 5 | const insertChunks = require('../src/util/inject-header-footer'); 6 | 7 | 8 | describe('Inject headers and footers', () => { 9 | it('injects headers and footers', () => { 10 | 11 | const html = ` 12 |
13 | Content 14 |
15 |
16 | Content 17 |
18 | ` 19 | 20 | const header = `
Header
` 21 | const footer = `` 22 | 23 | const result = insertChunks(html, 'Page', header, footer); 24 | 25 | assert.equal((result.match(/Header/g) || []).length, 2) 26 | assert.equal((result.match(/Footer/g) || []).length, 2) 27 | assert.equal((result.match(/Content/g) || []).length, 2) 28 | assert.equal((result.match(/webpdf-header/g) || []).length, 2) 29 | assert.equal((result.match(/webpdf-footer/g) || []).length, 2) 30 | 31 | }) 32 | }) 33 | 34 | describe('Ensure page', () => { 35 | it ('Doesnt add a page if one already exists', () => { 36 | const html = ` 37 | 38 | 39 |
40 | Test 41 |
42 | 43 | 44 | `; 45 | 46 | const result = ensurePage(html, 'Page'); 47 | 48 | assert(result === html); 49 | }) 50 | 51 | it ('Adds a page if one doesnt exists', () => { 52 | const html = ` 53 | 54 | 55 | Test 56 | 57 | 58 | `; 59 | 60 | const result = ensurePage(html, 'Page'); 61 | 62 | assert(result.indexOf("class='Page'") > -1); 63 | assert(result.indexOf("Test") > -1); 64 | }) 65 | }) 66 | 67 | 68 | describe('HTML cleaner', () => { 69 | it('adds html and body tags if none are present and true is passed', async () => { 70 | 71 | const html = ` 72 |
73 | 74 |
75 | `; 76 | const result = cleanHTML(html, true); 77 | assert(result.indexOf('') > -1); 78 | assert(result.indexOf('') > -1); 79 | 80 | assert(result.indexOf('') > -1); 81 | assert(result.indexOf('') > -1); 82 | return; 83 | }); 84 | 85 | it('does not add html and body tags if none are present and true is not passed', async () => { 86 | 87 | const html = ` 88 |
89 | 90 |
91 | `; 92 | const result = cleanHTML(html); 93 | assert(result.indexOf('') === -1); 94 | assert(result.indexOf('') === -1); 95 | 96 | assert(result.indexOf('') === -1); 97 | assert(result.indexOf('') === -1); 98 | return; 99 | }); 100 | 101 | it('Adds body tag if none present', () => { 102 | const html = ` 103 | 104 |
105 | 106 |
107 | 108 | `; 109 | 110 | const result = cleanHTML(html, true); 111 | 112 | assert(result.indexOf('') > -1); 113 | assert(result.indexOf('') > -1); 114 | }) 115 | 116 | it('Replaces encoded strings', async () => { 117 | 118 | const html = ` 119 | <div> 120 | hello&test 121 | </div> 122 | `; 123 | const result = cleanHTML(html); 124 | assert(result.indexOf('
') > -1); 125 | assert(result.indexOf('
') > -1); 126 | 127 | assert(result.indexOf('hello&test') > -1); 128 | return; 129 | }); 130 | }) -------------------------------------------------------------------------------- /test/content.js: -------------------------------------------------------------------------------- 1 | require('@babel/polyfill'); 2 | const assert = require('assert'); 3 | const GetContent = require('../src/util/get-content'); 4 | const Renderer = require('../src'); 5 | 6 | describe('get content', () => { 7 | it('can read a json file', async () => { 8 | const obj = await GetContent({ 9 | contentSource: 'assets/content.json', 10 | dirname: __dirname 11 | }); 12 | assert(obj.test, 'test'); 13 | return; 14 | }); 15 | 16 | it('can read a js object', async () => { 17 | const obj = await GetContent({ 18 | contentSource: { 19 | test: 'test' 20 | }, 21 | dirname: __dirname 22 | }); 23 | 24 | assert(obj.test, 'test'); 25 | return; 26 | }); 27 | 28 | it('can write nested content', async () => { 29 | 30 | const r = new Renderer({ dirname: __dirname }); 31 | 32 | const html = ` 33 | 34 | 35 |
36 | {{my.nested.content}} 37 |
38 | 39 | 40 | `; 41 | 42 | const contentSource = { 43 | my: { 44 | nested: { 45 | content: "Wow!" 46 | } 47 | } 48 | }; 49 | 50 | const result = await r.render({ 51 | templateSource: html, 52 | contentSource 53 | }); 54 | 55 | assert(result.sourceMap.html[0].from.indexOf('Wow!') > -1); 56 | 57 | }).timeout(7000) 58 | }) -------------------------------------------------------------------------------- /test/html.js: -------------------------------------------------------------------------------- 1 | require('@babel/polyfill'); 2 | const assert = require('assert'); 3 | const getHTML = require('../src/util/get-html-from-source'); 4 | const React = require('react'); 5 | 6 | describe('HTML Parser', () => { 7 | 8 | const htmlGetter = getHTML({ 9 | dirname: __dirname, 10 | obj: {} 11 | }) 12 | 13 | it('can get html from a file', async () => { 14 | const html = await htmlGetter('assets/index.html'); 15 | assert(html.indexOf('Page')); 16 | return; 17 | }); 18 | 19 | it ('can get html from a string', async () => { 20 | const html = await htmlGetter(`
`); 21 | assert(html.indexOf('Page')); 22 | return; 23 | }) 24 | 25 | it('can get html from a function', async () => { 26 | const fun = () => { 27 | return `
`; 28 | } 29 | const html = await htmlGetter(fun); 30 | assert(html.indexOf('Page')); 31 | return; 32 | }) 33 | 34 | it('can get html from a promise', async () => { 35 | const fun = () => { 36 | return new Promise(r => { 37 | setTimeout(() => { 38 | r(`
`) 39 | }, 1000) 40 | }); 41 | } 42 | const html = await htmlGetter(fun); 43 | assert(html.indexOf('Page')); 44 | return; 45 | }) 46 | 47 | it('can get html from a react component', async () => { 48 | class Comp extends React.Component { 49 | render() { 50 | return ( 51 |
52 | ) 53 | } 54 | } 55 | 56 | const html = await htmlGetter(Comp); 57 | assert(html.indexOf('Page')); 58 | return; 59 | }); 60 | 61 | it('can get html from a react function', async () => { 62 | 63 | const Comp = ({ }) => { 64 | return
65 | } 66 | 67 | const html = await htmlGetter(Comp); 68 | assert(html.indexOf('Page')); 69 | return; 70 | }) 71 | 72 | }) -------------------------------------------------------------------------------- /test/main.js: -------------------------------------------------------------------------------- 1 | require('@babel/polyfill'); 2 | const assert = require('assert'); 3 | const Renderer = require('../src'); 4 | const Path = require('path'); 5 | const React = require('react'); 6 | async function assertThrowsAsync(fn, regExp) { 7 | let f = () => {}; 8 | try { 9 | await fn(); 10 | } catch(e) { 11 | f = () => {throw e}; 12 | } finally { 13 | assert.throws(f, regExp); 14 | } 15 | } 16 | 17 | describe('WebToPDF', () => { 18 | 19 | it('throws if dirname is not provided', () => { 20 | assert.throws(() => { 21 | const ren = new Renderer({ }); 22 | }, Error) 23 | }) 24 | 25 | 26 | it('throws if no templateSource is provided', async () => { 27 | const ren = new Renderer({ dirname: __dirname }); 28 | 29 | assertThrowsAsync(async () => { 30 | await ren.render({ 31 | 32 | }); 33 | }, /Error/) 34 | }).timeout(7000); 35 | 36 | it('throws if templateSource cannot be parsed', async () => { 37 | const ren = new Renderer({ dirname: __dirname }); 38 | 39 | assertThrowsAsync(async () => { 40 | await ren.render({ 41 | templateSource: 'dsgkhsdlfgj' 42 | }); 43 | }, /Error/) 44 | }).timeout(7000); 45 | 46 | 47 | it('should return a sourcemap of assets written', async () => { 48 | const ren = new Renderer({ dirname: __dirname }); 49 | 50 | const html = ` 51 | 52 | 53 |
54 |
55 | 56 | 57 | ` 58 | 59 | const sm = await ren.render({ 60 | templateSource: html, 61 | }); 62 | 63 | assert.equal(sm.sourceMap.html[0].to, 'outputs/index/index.html'); 64 | assert(!!sm.sourceMap.html[0].from); 65 | assert(!!sm.sourceMap.html[0].method); 66 | 67 | assert.equal(sm.sourceMap.css[0].to, 'outputs/index/index.css'); 68 | return; 69 | }).timeout(7000); 70 | 71 | it('automatically appends header and footer chunks to every page', async () => { 72 | const ren = new Renderer({ dirname: __dirname }); 73 | 74 | const source = ` 75 | 76 | 77 |
78 | Content 79 |
80 | 81 |
82 | Content 83 |
84 | 85 | 86 | `; 87 | 88 | const header = `
My header
` 89 | const footer = `` 90 | 91 | const sm = await ren.render({ 92 | templateSource: source, 93 | chunks: { header, footer } 94 | }); 95 | 96 | const html = sm.sourceMap.html[0].from; 97 | 98 | assert.equal((html.match(/My header/g) || []).length, 2); 99 | assert.equal((html.match(/My footer/g) || []).length, 2); 100 | assert.equal((html.match(/Content/g) || []).length, 2); 101 | 102 | }).timeout(7000); 103 | 104 | 105 | it('should replace content in HTML', async () => { 106 | const ren = new Renderer({ dirname: __dirname }); 107 | 108 | const sm = await ren.render({ 109 | templateSource: 'assets/index.html', 110 | contentSource: 'assets/content.json' 111 | }); 112 | 113 | const html = sm.sourceMap.html[0].from; 114 | 115 | 116 | assert(html.indexOf('pdf') > -1); 117 | assert(html.indexOf('is cool') > -1); 118 | 119 | return; 120 | }).timeout(7000); 121 | 122 | 123 | it('should replace chunks in HTML', async () => { 124 | const ren = new Renderer({ dirname: __dirname }); 125 | 126 | const customFooter = ` 127 | 130 | ` 131 | 132 | const sm = await ren.render({ 133 | templateSource: 'assets/index.html', 134 | contentSource: 'assets/content.json', 135 | chunks: { 136 | customFooter 137 | } 138 | }); 139 | 140 | const html = sm.sourceMap.html[0].from; 141 | 142 | assert(html.indexOf('MY FOOTER!') > -1); 143 | 144 | return; 145 | }).timeout(7000); 146 | 147 | it('should replace page numbers in HTML', async () => { 148 | const ren = new Renderer({ dirname: __dirname }); 149 | 150 | const htmlS = ` 151 |
152 | ONE {{pageNumber}} 153 |
154 |
155 | TWO {{pageNumber}} 156 |
157 |
158 | THREE {{pageNumber}} 159 | 160 | {{otherContent}} 161 |
162 | ` 163 | const otherContent = ` 164 | 167 | ` 168 | 169 | const sm = await ren.render({ 170 | templateSource: htmlS, 171 | contentSource: 'assets/content.json', 172 | chunks: { 173 | otherContent 174 | } 175 | }); 176 | 177 | const html = sm.sourceMap.html[0].from; 178 | 179 | assert(html.indexOf('ONE 1') > -1); 180 | assert(html.indexOf('TWO 2') > -1); 181 | assert(html.indexOf('THREE 3') > -1); 182 | assert(html.indexOf('footer 3') > -1); 183 | 184 | return; 185 | }).timeout(7000); 186 | 187 | it('can set page width and height', async () => { 188 | const ren = new Renderer({ dirname: __dirname, width: 500, height: 700 }); 189 | 190 | const sm = await ren.render({ 191 | templateSource: 'assets/index.html', 192 | 193 | }); 194 | 195 | const css = sm.sourceMap.css[0].from; 196 | 197 | assert(css.indexOf('width: __WIDTH') === -1); 198 | assert(css.indexOf('height: __HEIGHT') === -1); 199 | 200 | return; 201 | }).timeout(7000); 202 | 203 | it('passes content to a function', async () => { 204 | 205 | const ren = new Renderer({ dirname: __dirname }); 206 | let called = false; 207 | const func = (content) => { 208 | 209 | assert(content.test === 'hello'); 210 | called = true; 211 | return ` 212 | 213 |
214 | 215 | ` 216 | } 217 | 218 | await ren.render({ 219 | templateSource: func, 220 | contentSource: { 221 | "test": "hello" 222 | } 223 | }); 224 | 225 | assert(called); 226 | 227 | return; 228 | }).timeout(7000); 229 | 230 | it('passes content to a react component', async () => { 231 | 232 | const ren = new Renderer({ dirname: __dirname }); 233 | 234 | let called = false; 235 | class Comp extends React.Component { 236 | render() { 237 | const { content } = this.props; 238 | assert(content.test === 'hello'); 239 | called = true; 240 | return
241 | } 242 | } 243 | 244 | await ren.render({ 245 | templateSource: Comp, 246 | contentSource: { 247 | "test": "hello" 248 | } 249 | }); 250 | 251 | assert(called); 252 | 253 | return; 254 | }).timeout(7000); 255 | 256 | it('copies scripts to server folder', async () => { 257 | const ren = new Renderer({ dirname: __dirname }); 258 | 259 | const html = ` 260 | 261 | 262 | 263 | 264 | 265 |
266 | 267 | 268 | `; 269 | 270 | const sm = await ren.render({ 271 | templateSource: html, 272 | }); 273 | 274 | const write = sm.sourceMap.script[0]; 275 | 276 | assert.equal(write.from, Path.resolve(__dirname, 'assets/script.js')); 277 | assert.equal(write.to, 'outputs/index/assets/script.js'); 278 | 279 | return; 280 | }).timeout(7000); 281 | 282 | it('calls on html event', async () => { 283 | const ren = new Renderer({ dirname: __dirname }); 284 | 285 | const html = ` 286 | 287 | 288 | 289 | 290 | 291 |
292 | 293 | 294 | `; 295 | 296 | let called = false; 297 | 298 | ren.on('html', (h) => { 299 | called = h; 300 | }) 301 | 302 | const sm = await ren.render({ 303 | templateSource: html, 304 | }); 305 | 306 | assert(called); 307 | assert(called.indexOf('') > -1); 308 | 309 | return; 310 | }).timeout(7000); 311 | 312 | it('can accept html transforming middleware', async () => { 313 | const ren = new Renderer({ dirname: __dirname }); 314 | 315 | const html = ` 316 | 317 | 318 | 319 | 320 | 321 |
322 | 323 | 324 | `; 325 | 326 | 327 | const sm = await ren.render({ 328 | templateSource: html, 329 | middleware: [ 330 | (h) => { 331 | h = html.replace('assets/script.js', "TEST!"); 332 | return h; 333 | } 334 | ] 335 | }); 336 | 337 | const returnedHTML = sm.sourceMap.html[0].from; 338 | 339 | assert(returnedHTML.indexOf('TEST!') > -1); 340 | 341 | return; 342 | }).timeout(7000); 343 | 344 | 345 | it('can accept async middleware', async () => { 346 | const ren = new Renderer({ dirname: __dirname }); 347 | 348 | const html = ` 349 | 350 | 351 | 352 | 353 | 354 |
355 | 356 | 357 | `; 358 | 359 | 360 | const sm = await ren.render({ 361 | templateSource: html, 362 | middleware: [ 363 | async (h) => { 364 | await new Promise(r => setTimeout(r, 500)); 365 | h = h.replace('assets/script.js', "TEST!"); 366 | return h; 367 | }, 368 | async (h) => { 369 | await new Promise(r => setTimeout(r, 700)); 370 | h = h.replace('TEST!', "TEST2!"); 371 | return h; 372 | } 373 | ] 374 | }); 375 | 376 | const returnedHTML = sm.sourceMap.html[0].from; 377 | 378 | assert(returnedHTML.indexOf('TEST!') === -1); 379 | assert(returnedHTML.indexOf('TEST2!') > -1); 380 | 381 | return; 382 | }).timeout(1233333) 383 | 384 | 385 | it('gets image sources in chunks', async () => { 386 | const ren = new Renderer({ dirname: __dirname }); 387 | 388 | const html = ` 389 |
390 | {{htmlChunk}} 391 |
392 | `; 393 | 394 | const sm = await ren.render({ 395 | templateSource: html, 396 | chunks: { 397 | htmlChunk: ` 398 |
399 |

I will be dynamically inserted!

400 | 401 |
402 | ` 403 | }, 404 | }) 405 | 406 | const assets = sm.sourceMap.assets; 407 | assert.ok(assets); 408 | assert.ok(assets.length === 1); 409 | assert.ok(assets[0].from.indexOf('test.png') > -1) 410 | 411 | // const returnedHTML = sm.sourceMap.html[0].from; 412 | }).timeout(6000) 413 | 414 | it('can accept inline styles as a styles param', async () => { 415 | const ren = new Renderer({ dirname: __dirname }); 416 | 417 | const html = ` 418 |
419 | `; 420 | 421 | const css = ` 422 | #testCSS { 423 | color: red; 424 | } 425 | ` 426 | 427 | const scss = ` 428 | #testSCSS { 429 | p.testP { 430 | color: white; 431 | } 432 | } 433 | `; 434 | 435 | const sm = await ren.render({ 436 | templateSource: html, 437 | styles: [ css, scss ] 438 | }) 439 | 440 | const returnedCSS = sm.sourceMap.css[0].from; 441 | 442 | assert(returnedCSS.indexOf('#testCSS') > -1); 443 | assert(returnedCSS.indexOf('#testSCSS') > -1); 444 | assert(returnedCSS.indexOf('.testP') > -1); 445 | return; 446 | 447 | }).timeout(7000); 448 | }) -------------------------------------------------------------------------------- /test/other.js: -------------------------------------------------------------------------------- 1 | require('@babel/polyfill'); 2 | const assert = require('assert'); 3 | const verifyPage = require('../src/util/verify-page'); 4 | 5 | describe('verification', () => { 6 | it('returns false if no .Page is present', async () => { 7 | 8 | const html = `
`; 9 | 10 | const html2 = "
" 11 | 12 | assert(!verifyPage(html)); 13 | assert(verifyPage(html2)); 14 | 15 | }); 16 | 17 | }) -------------------------------------------------------------------------------- /test/pageClass.js: -------------------------------------------------------------------------------- 1 | require('@babel/polyfill'); 2 | const assert = require('assert'); 3 | const React = require('react'); 4 | const Renderer = require('../src'); 5 | 6 | describe('HTML Parser', () => { 7 | 8 | 9 | it('can use custom className as page divider', async () => { 10 | 11 | const r = new Renderer({ dirname: __dirname }) 12 | 13 | const html = ` 14 | 15 | 16 |
17 | Test 1 18 |
19 | 20 |
21 | Test 2 22 |
23 | 24 | 25 | ` 26 | 27 | const sm = await r.render({ 28 | templateSource: html, 29 | pageClass: 'Split' 30 | }); 31 | 32 | assert.equal(sm.metadata.numberOfPages, 2); 33 | 34 | return; 35 | }).timeout(7000); 36 | 37 | it('replaces css page with custom class', async () => { 38 | const r = new Renderer({ dirname: __dirname }) 39 | 40 | const html = ` 41 | 42 | 43 |
44 | Test 1 45 |
46 | 47 |
48 | Test 2 49 |
50 | 51 | 52 | ` 53 | 54 | const sm = await r.render({ 55 | templateSource: html, 56 | pageClass: 'Split' 57 | }); 58 | 59 | 60 | assert(sm.sourceMap.css[0].from.indexOf('.Split') > -1); 61 | assert(sm.sourceMap.css[0].from.indexOf('.Page') === -1); 62 | }).timeout(7000) 63 | 64 | 65 | 66 | }) -------------------------------------------------------------------------------- /test/realtime.js: -------------------------------------------------------------------------------- 1 | require('@babel/polyfill'); 2 | const assert = require('assert'); 3 | const listenToChanges = require('../src/util/listen-to-changes'); 4 | const writeFile = require('../src/util/write-file'); 5 | const path = require('path'); 6 | const Renderer = require('../src'); 7 | 8 | describe('real time listener', () => { 9 | // it('can listen to files and return changed files', (done) => { 10 | 11 | // const w = listenToChanges([path.resolve(__dirname, 'assets/temp.txt')], (changes) => { 12 | // assert(changes.length === 1); 13 | // assert(changes[0] === path.resolve(__dirname, 'assets/temp.txt')); 14 | // w.close(); 15 | // done(); 16 | // }) 17 | 18 | // writeFile(path.resolve(__dirname, 'assets/temp.txt'), `My data ${Math.random()}`); 19 | // }).timeout(60000); 20 | 21 | it('ignored empty entries', (done) => { 22 | 23 | const w = listenToChanges([path.resolve(__dirname, 'assets/temp.txt'), '', '', ''], (changes) => { 24 | assert(changes.length === 1); 25 | assert(changes[0] === path.resolve(__dirname, 'assets/temp.txt')); 26 | w.close(); 27 | done(); 28 | }) 29 | 30 | writeFile(path.resolve(__dirname, 'assets/temp.txt'), `My data ${Math.random()}`); 31 | }).timeout(6000); 32 | 33 | it('can ignore files', (done) => { 34 | 35 | let called = false; 36 | 37 | const w = listenToChanges([path.resolve(__dirname, 'assets/temp.txt'), '', '', ''], (changes) => { 38 | called = true; 39 | }, false, "**/*.txt") 40 | 41 | writeFile(path.resolve(__dirname, 'assets/temp.txt'), `My data ${Math.random()}`); 42 | 43 | setTimeout(() => { 44 | assert(!called); 45 | done(); 46 | }, 4000) 47 | }).timeout(6000); 48 | 49 | it('goes into real time mode when on change handler is set', (done) => { 50 | const r = new Renderer({ dirname: __dirname }); 51 | const ren = () => { 52 | assert(!!r._changeFunc); 53 | 54 | r.stop(); 55 | done(); 56 | } 57 | r.on('change', ren); 58 | ren(); 59 | }).timeout(7000); 60 | 61 | it('can accept an options file instead of options object', async () => { 62 | const r = new Renderer({ dirname: __dirname }); 63 | const ren = async () => { 64 | assert(!!r._changeFunc); 65 | const sm = await r.render('assets/options.js'); 66 | r.stop(); 67 | return sm; 68 | } 69 | r.on('change', ren); 70 | const sm = await ren(); 71 | 72 | assert(sm); 73 | 74 | r.stop(); 75 | return; 76 | 77 | }).timeout(7000); 78 | }) -------------------------------------------------------------------------------- /test/remote.js: -------------------------------------------------------------------------------- 1 | require('@babel/polyfill'); 2 | const assert = require('assert'); 3 | const Renderer = require('../src'); 4 | 5 | describe('verification', () => { 6 | it('can render a remote source', async () => { 7 | const renderer = new Renderer({ dirname: __dirname }); 8 | 9 | const sm = await renderer.render({ 10 | templateSource: 'http://pdftron.com' 11 | }); 12 | 13 | assert(sm.sourceMap.html.indexOf('___gatsby') > -1); 14 | return; 15 | 16 | }).timeout(14000); 17 | 18 | 19 | it('can inject a stylesheet', async () => { 20 | const renderer = new Renderer({ dirname: __dirname }); 21 | 22 | const sm = await renderer.render({ 23 | templateSource: 'http://pdftron.com', 24 | styles: [ 25 | './assets/style.scss' 26 | ] 27 | }); 28 | 29 | assert(sm.sourceMap.html.indexOf('.MY-STYLE') > -1); 30 | return; 31 | 32 | }).timeout(14000); 33 | 34 | it('can inject a script', async () => { 35 | const renderer = new Renderer({ dirname: __dirname }); 36 | 37 | const sm = await renderer.render({ 38 | templateSource: 'http://pdftron.com', 39 | scripts: [ 40 | './assets/script.js' 41 | ] 42 | }); 43 | 44 | assert(sm.sourceMap.html.indexOf("console.log('waddup');") > -1); 45 | return; 46 | 47 | }).timeout(14000); 48 | 49 | }) -------------------------------------------------------------------------------- /test/scripts.js: -------------------------------------------------------------------------------- 1 | require('@babel/polyfill'); 2 | const assert = require('assert'); 3 | const getSciptSrc = require('../src/util/get-script-src'); 4 | 5 | describe('scripts', () => { 6 | it('can extract script tags', async () => { 7 | 8 | const html = ` 9 | 10 |