Node.JS: use html-pdf-chrome to convert HTML to PDF


html-pdf-chrome
Home page: https://github.com/westy92/html-pdf-chrome

[root@tutorialspots ~]# npm install --save html-pdf-chrome
npm WARN saveError ENOENT: no such file or directory, open '/root/package.json'
/root
└─┬ html-pdf-chrome@0.6.0
  ├─┬ chrome-launcher@0.11.2
  │ ├── @types/node@13.7.0
  │ ├── is-wsl@2.1.1
  │ └─┬ lighthouse-logger@1.2.0
  │   ├─┬ debug@2.6.9
  │   │ └── ms@2.0.0
  │   └── marky@1.2.1
  └─┬ chrome-remote-interface@0.27.2
    └── commander@2.11.0

npm WARN enoent ENOENT: no such file or directory, open '/root/package.json'
npm WARN root No description
npm WARN root No repository field.
npm WARN root No README data
npm WARN root No license field.

For Node.JS v6, you must install html-pdf-chrome@0.5.0

Install Google Chrome on CentOS
For CentOS 7

cat << EOF > /etc/yum.repos.d/google-chrome.repo
[google-chrome]
name=google-chrome
baseurl=http://dl.google.com/linux/chrome/rpm/stable/x86_64
enabled=1
gpgcheck=1
gpgkey=https://dl.google.com/linux/linux_signing_key.pub
EOF
yum install google-chrome-stable

Result:

[root@tutorialspots ~]# yum install google-chrome-stable
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirror.dal.nexril.net
 * epel: ord.mirror.rackspace.com
 * extras: repos-tx.psychz.net
 * nux-dextop: mirror.li.nux.ro
 * remi-safe: mirror.bebout.net
 * updates: mirror.cs.pitt.edu
Resolving Dependencies
--> Running transaction check
---> Package google-chrome-stable.x86_64 0:79.0.3945.130-1 will be installed
--> Processing Dependency: liberation-fonts for package: google-chrome-stable-79.0.3945.130-1.x86_64
--> Processing Dependency: libappindicator3.so.1()(64bit) for package: google-chrome-stable-79.0.3945.130-1.x86_64
--> Running transaction check
---> Package libappindicator-gtk3.x86_64 0:12.10.0-13.el7 will be installed
--> Processing Dependency: libindicator3.so.7()(64bit) for package: libappindicator-gtk3-12.10.0-13.el7.x86_64
--> Processing Dependency: libdbusmenu-gtk3.so.4()(64bit) for package: libappindicator-gtk3-12.10.0-13.el7.x86_64
--> Processing Dependency: libdbusmenu-glib.so.4()(64bit) for package: libappindicator-gtk3-12.10.0-13.el7.x86_64
---> Package liberation-fonts.noarch 1:1.07.2-16.el7 will be installed
--> Processing Dependency: liberation-narrow-fonts = 1:1.07.2-16.el7 for package: 1:liberation-fonts-1.07.2-16.el7.noarch
--> Running transaction check
---> Package libdbusmenu.x86_64 0:16.04.0-4.el7 will be installed
---> Package libdbusmenu-gtk3.x86_64 0:16.04.0-4.el7 will be installed
---> Package liberation-narrow-fonts.noarch 1:1.07.2-16.el7 will be installed
---> Package libindicator-gtk3.x86_64 0:12.10.1-6.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

=======================================================================
 Package                 Arch   Version            Repository     Size
=======================================================================
Installing:
 google-chrome-stable    x86_64 79.0.3945.130-1    google-chrome  60 M
Installing for dependencies:
 libappindicator-gtk3    x86_64 12.10.0-13.el7     base           37 k
 libdbusmenu             x86_64 16.04.0-4.el7      base          132 k
 libdbusmenu-gtk3        x86_64 16.04.0-4.el7      base           34 k
 liberation-fonts        noarch 1:1.07.2-16.el7    base           13 k
 liberation-narrow-fonts noarch 1:1.07.2-16.el7    base          202 k
 libindicator-gtk3       x86_64 12.10.1-6.el7      base           63 k

Transaction Summary
=======================================================================
Install  1 Package (+6 Dependent packages)

Total download size: 60 M
Installed size: 212 M
Is this ok [y/d/N]: y
Downloading packages:
(1/7): libappindicator-gtk3-12.10.0-13.el7.x86_64 |  37 kB   00:00
(2/7): libdbusmenu-16.04.0-4.el7.x86_64.rpm       | 132 kB   00:00
(3/7): libdbusmenu-gtk3-16.04.0-4.el7.x86_64.rpm  |  34 kB   00:00
(4/7): liberation-fonts-1.07.2-16.el7.noarch.rpm  |  13 kB   00:00
(5/7): libindicator-gtk3-12.10.1-6.el7.x86_64.rpm |  63 kB   00:00
(6/7): liberation-narrow-fonts-1.07.2-16.el7.noar | 202 kB   00:00
warning: /var/cache/yum/x86_64/7/google-chrome/packages/google-chrome-stable-79.0.3945.130-1.x86_64.rpm: Header V4 DSA/SHA1 Signature, key ID 7fac5991: NOKEY
Public key for google-chrome-stable-79.0.3945.130-1.x86_64.rpm is not installed
(7/7): google-chrome-stable-79.0.3945.130-1.x86_6 |  60 MB   00:01
-----------------------------------------------------------------------
Total                                      44 MB/s |  60 MB  00:01
Retrieving key from https://dl.google.com/linux/linux_signing_key.pub
Importing GPG key 0x7FAC5991:
 Userid     : "Google, Inc. Linux Package Signing Key <linux-packages-keymaster@google.com>"
 Fingerprint: 4cca 1eaf 950c ee4a b839 76dc a040 830f 7fac 5991
 From       : https://dl.google.com/linux/linux_signing_key.pub
Is this ok [y/N]: y
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : libdbusmenu-16.04.0-4.el7.x86_64                    1/7
  Installing : libdbusmenu-gtk3-16.04.0-4.el7.x86_64               2/7
  Installing : 1:liberation-narrow-fonts-1.07.2-16.el7.noarch      3/7
  Installing : 1:liberation-fonts-1.07.2-16.el7.noarch             4/7
  Installing : libindicator-gtk3-12.10.1-6.el7.x86_64              5/7
  Installing : libappindicator-gtk3-12.10.0-13.el7.x86_64          6/7
  Installing : google-chrome-stable-79.0.3945.130-1.x86_64         7/7
Redirecting to /bin/systemctl start atd.service
Failed to start atd.service: Unit not found.
  Verifying  : 1:liberation-fonts-1.07.2-16.el7.noarch             1/7
  Verifying  : libappindicator-gtk3-12.10.0-13.el7.x86_64          2/7
  Verifying  : libindicator-gtk3-12.10.1-6.el7.x86_64              3/7
  Verifying  : google-chrome-stable-79.0.3945.130-1.x86_64         4/7
  Verifying  : libdbusmenu-gtk3-16.04.0-4.el7.x86_64               5/7
  Verifying  : 1:liberation-narrow-fonts-1.07.2-16.el7.noarch      6/7
  Verifying  : libdbusmenu-16.04.0-4.el7.x86_64                    7/7

Installed:
  google-chrome-stable.x86_64 0:79.0.3945.130-1

Dependency Installed:
  libappindicator-gtk3.x86_64 0:12.10.0-13.el7
  libdbusmenu.x86_64 0:16.04.0-4.el7
  libdbusmenu-gtk3.x86_64 0:16.04.0-4.el7
  liberation-fonts.noarch 1:1.07.2-16.el7
  liberation-narrow-fonts.noarch 1:1.07.2-16.el7
  libindicator-gtk3.x86_64 0:12.10.1-6.el7

Complete!

Start chrome with pm2
If you don’t have pm2, install it first.

pm2 start google-chrome \
  --interpreter none \
  -- \
  --headless \
  --disable-gpu \
  --disable-translate \
  --disable-extensions \
  --disable-background-networking \
  --safebrowsing-disable-auto-update \
  --disable-sync \
  --metrics-recording-only \
  --disable-default-apps \
  --no-first-run \
  --mute-audio \
  --hide-scrollbars \
  --remote-debugging-port=44443 \
  --no-sandbox

You can use your own port (change 44443 to your own port)

Now you can use module html-pdf-chrome:
All available printOptions:

landscape : Paper orientation. Defaults to false.
displayHeaderFooter : Display header and footer. Defaults to false.
printBackground : Print background graphics. Defaults to false.
scale : Scale of the webpage rendering. Defaults to 1.
paperWidth : Paper width in inches. Defaults to 8.5 inches.
paperHeight : Paper height in inches. Defaults to 11 inches. 
marginTop : Top margin in inches. Defaults to 1cm (~0.4 inches). 
marginBottom : Bottom margin in inches. Defaults to 1cm (~0.4 inches). 
marginLeft : Left margin in inches. Defaults to 1cm (~0.4 inches).
marginRight : Right margin in inches. Defaults to 1cm (~0.4 inches).
pageRanges : Paper ranges to print, e.g., '1-5, 8, 11-13'.
    Defaults to the empty string, which means print all pages.
ignoreInvalidPageRanges : Whether to silently ignore invalid but successfully parsed
    page ranges, such as '3-2'. Defaults to false. 
headerTemplate : HTML template for the print header.
    Should be valid HTML markup with following classes used to inject printing values into them:
    - `date` formatted print date
    - `title` document title
    - `url` document location
    - `pageNumber` current page number
    - `totalPages` total pages in the document   
    For example, `<span class="title"></span>` would generate a span containing the title.
footerTemplate : HTML template for the print footer. Should use the same format as the `headerTemplate`.    
preferCSSPageSize : Whether or not to prefer page size as defined by css.
    Defaults to false, in which case the content will be scaled to fit the paper size.   

See Example 2 to know how to use printOptions.

Example 1: convert HTML code to PDF

const htmlPdf = require('html-pdf-chrome');

const html = '<p>Hello, TUTORIALSPOTS!</p>';
const options = {
  port: 44443, // port Chrome is listening on
};

htmlPdf.create(html, options).then((pdf) => pdf.toFile('pdf1.pdf'));
//htmlPdf.create(html, options).then((pdf) => pdf.toBase64());
//htmlPdf.create(html, options).then((pdf) => pdf.toBuffer());
//htmlPdf.create(html, options).then((pdf) => pdf.toStream());

Result: http://demo.tutorialspots.com/nodejs/html-pdf-chrome/pdf1.pdf

Example 2: use an external site

const htmlPdf = require('html-pdf-chrome');
 
const options = {
  port: 44443, // port Chrome is listening on
  printOptions: {printBackground: true}
};

const url = 'http://tutorialspots.com/';
 
htmlPdf.create(url, options).then((pdf) => pdf.toFile('pdf2.pdf'));

Result: http://demo.tutorialspots.com/nodejs/html-pdf-chrome/pdf2.pdf

Leave a Reply