Giter VIP home page Giter VIP logo

chrome-headless-render-pdf's Introduction

npmnpm type definitions

Usage:

chrome-headless-render-pdf [OPTIONS] --url=URL --pdf=OUTPUT-FILE [--url=URL2 --pdf=OUTPUT-FILE2] ...
  Options:
    --help                   this screen
    --url                    url to load, for local files use: file:///path/to/file
    --pdf                    output for generated file can be relative to current directory
    --chrome-binary          set chrome location (use this options when autodetection fail)
    --chrome-option          set chrome option, can be used multiple times, e.g. --chrome-option=--no-sandbox
    --remote-host            set chrome host (for remote process)
    --remote-port            set chrome port (for remote process)
    --no-margins             disable default 1cm margins
    --include-background     include elements background
    --landscape              generate pdf in landscape orientation
    --window-size            specify window size, width(,x*)height (e.g. --window-size 1600,1200 or --window-size 1600x1200)
    --paper-width            specify page width in inches (defaults to 8.5 inches)
    --paper-height           specify page height in inches (defaults to 11 inches)
    --page-ranges            specify pages to render default all pages,  e.g. 1-5, 8, 11-13
    --scale                  specify scale of the webpage rendering (defaults to 1)
    --display-header-footer  display text headers and footers
    --header-template        HTML template for the header. Inject variables using the classes "date", "title", "url", "pageNumber" or "totalPages"
    --footerTemplate         HTML template for the footer. Inject variables using the classes "date", "title", "url", "pageNumber" or "totalPages"
    --js-time-budget         Virtual time budget in ms to wait for js execution (default 5000)
    --animation-time-budget  Time budget in ms to wait for in progress animations to finish (default 5000)

  Example:
    Render single pdf file
      chrome-headless-render-pdf --url http://google.com --pdf test.pdf
    Render pdf from local file
      chrome-headless-render-pdf --url file:///tmp/example.html --pdf test.pdf
    Render multiple pdf files
      chrome-headless-render-pdf --url http://google.com --pdf test.pdf --url file:///tmp/example.html --pdf test2.pdf
    Render pdf with custom footer and no header (styles are mandatory)
      chrome-headless-render-pdf --url file:///tmp/example.html --pdf test.pdf --display-header-footer --header-template ' ' --footer-template '<style type="text/css">.footer{font-size:8px;width:100%;text-align:center;color:#000;padding-left:0.65cm;}</style><div class="footer"><span class="pageNumber"></span> / <span class="totalPages"></span></div>'

This tool can be also used programmatically:

const RenderPDF = require('chrome-headless-render-pdf');
RenderPDF.generateSinglePdf('http://google.com', 'outputPdf.pdf');
const RenderPDF = require('chrome-headless-render-pdf');
RenderPDF.generateMultiplePdf([
    {url: 'http://google.com', pdf: 'outputPdf.pdf'},
    {utl: 'http://example.com', pdf: 'outputPdf2.pdf'}
]);
const RenderPDF = require('chrome-headless-render-pdf');
RenderPDF.generatePdfBuffer('http://google.com')
    .then((pdfBuffer) => {
      console.log(pdfBuffer);
    });

you can also use it from typescript or es6

import RenderPDF from 'chrome-headless-render-pdf';
RenderPDF.generateSinglePdf('http://google.com', 'outputPdf.pdf');

Motivation

google-chrome currently have option to render pdf files when used with headless option. But this option contains hardcoded adding header and footer to page rendering it unusable for pdf generation. This module allows to generate it without those elements.

chrome-headless-render-pdf's People

Contributors

cesarizu avatar chuckhoupt avatar cognitom avatar dependabot[bot] avatar dimfeld avatar domoritz avatar dudeofawesome avatar fgoepel avatar gief avatar klieber avatar nigelzor avatar ovr avatar pvinis avatar szpadel avatar wioux avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

chrome-headless-render-pdf's Issues

AWS Lambda

This is just for people like me who are trying to get this to work on Lambda. Now there's a search result, yay.

I'm using the binary from https://github.com/adieuadieu/serverless-chrome/releases

I had to add a few flags to make it run:

{
  chromeBinary: 'bin/headless-chromium-you-have-downloaded',
  chromeOptions: ['--disable-dev-shm-usage', '--no-zygote', '--single-process', '--no-sandbox']
}

Source: https://github.com/adieuadieu/serverless-chrome/blob/886c2c4f5c5b2e8f9b79670e0935ee8afb970aab/packages/lambda/src/flags.js

Add support for custom page header and footer and page margins

I have attached enhanced chrome-headless-render-pdf to support custom page header and footer and page margins. I am one of the developers on the free Windows Mbox Mail Viewer project. The current Viewer relies on -print-to-pdf Chrome's command line option to print HTML mails to PDF without user interaction. However, Chrome browser lack's ability to customize header and footer requested by users. I found the chrome-headless-render-pdf project that leverages CDP protocol to connect to Chrome Browser and render PDF but lacks an option to customize the page header and footer. I enhanced the chrome-headless-render-pdf application to support customization and attached the enhanced code for use by interested users. However, it would be best if the official project is enhanced. Attached are also two helper scripts that I was using during the development:

  1. render-html-pdf.js This script creates various header and footer templates in HTML for the enhanced chrome-headless-render-pdf.js. These templates were eventually integrated into the chrome-headless-render-pdf.js.
  2. render-pdf.js The small script to exec the chrome-headless-render-pdf.js to render pdf with one of the predefined custom header and footer templates.

Below shows new options implemented by the enhanced chrome-headless-render-pdf to support custom page header and footer and to configure page margins. The zip file doesn't contain valid npm package so it should not be installed by the npm manager. Just unzip the file and use as is. Run "node render-html-pdf.js" "node render-pdf.js" or run directly the chrome-headless-render-pdf.js with proper command line arguments. Development and testing was done on Windows 10. I am new to javascript so emhancements may not be optimal.

NOTE that Chrome Browser may not paint header and footer correctly for some web pages. This seems to be due to the fact that painting of header and footer is not independent from painting web page content.

function printHelp() {
console.log('chrome-headless-render-pdf [OPTIONS] --url=URL --pdf=OUTPUT-FILE [--url=URL2 --pdf=OUTPUT-FILE2] ...');
console.log(' Options:');
console.log(' --help this screen');
console.log(' --url url to load, for local files use: file:///path/to/file');
console.log(' --pdf output for generated file can be relative to current directory');
console.log(' --chrome-binary set chrome location (use this options when autodetection fail)');
console.log(' --chrome-option set chrome option, can be used multiple times, e.g. --chrome-option=--no-sandbox');
console.log(' --remote-host set chrome host (for remote process)');
console.log(' --remote-port set chrome port (for remote process)');
console.log(' --include-background include elements background');
console.log(' --landscape generate pdf in landscape orientation');
console.log(' --window-size specify window size, width(,x*)height (e.g. --window-size 1600,1200 or --window-size 1600x1200)');
console.log(' --paper-width specify page width in inches (defaults to 8.5 inches)');
console.log(' --paper-height specify page height in inches (defaults to 11.0 inches)');
console.log(' --margin-top page top margin (defaults to ~0.4inches i.e. 1 centimeter)');
console.log(' --margin-bottom page bottom margin (defaults to ~0.4inches i.e. 1 centimeter)');
console.log(' --margin-left page left margin (defaults to ~0.4inches i.e. 1 centimeter)');
console.log(' --margin-right page right margin (defaults to ~0.4inches i.e. 1 centimeter)');
console.log(' --page-ranges specify pages to render default all pages, e.g. 1-5, 8, 11-13');
console.log(' --scale specify scale of the webpage rendering (defaults to 1.0)');
console.log(' Header and Footer Options:');
console.log(' --url-alias replace url with url-alias in PDF page footer');
console.log(' --header-template custom HTML template for the page header. Takes precedence over --header-template-number');
console.log(' --footer-template custom HTML template for the page footer. Takes precedence over --footer-template-number');
console.log(' --header-template-number number assigned to preconfigured HTML template for the page header');
console.log(' 0=empty, 1=[date][title], 2==[title][date], 3=[title]');
console.log(' --footer-template-number number assigned to preconfigured HTML template for the page footer');
console.log(' 0=empty, 1=[url][page#], 2==[page#], 3=[date][url][page#], 4=[date][page#]');
console.log(' --header-footer-margin left and right margin size of page header and footer (defaults to 0.3inches)');
console.log(' --header-footer-font-size font size of page header and footer (defaults to 8px)');
console.log(' if you configure font size > 10, you will likely need to increase --margin-bottom and --margin-top');
console.log(' --page-numbering-style page numbering format in the page footer (defaults to 1)');
console.log(' 1=page# of total pages, 2=page#/total pages, 3=page#');
console.log(' --display-header-footer print page header and footer (defaults to false)');
console.log(' --display-header-footer-native let browser create and print page header and footer (defaults to false)');
console.log('');
console.log(' Example:');
console.log(' Render single pdf file');
console.log(' chrome-headless-render-pdf --url=http://google.com --pdf=test.pdf');
console.log(' Render pdf from local file');
console.log(' chrome-headless-render-pdf --url=file:///tmp/example.html --pdf=test.pdf');
console.log(' Render multiple pdf files');
console.log(' chrome-headless-render-pdf --url=http://google.com --pdf=test.pdf --url="file:///tmp/example.html" --pdf=test2.pdf');
console.log('');
console.log(' NOTE: To avoid surprises, place url, url-alias and pdf between double quotes, for example --url-alias="GOOGLE HOME PAGE"');
console.log('');
}
chrome-headless-render-pdf-master.zip

Ability to define port number generator function

It would be cool to add to the options object the ability to either manually set the *port number or to inject a function to dynamically generate it.

The default implementation can cause issues on environments where some ports have already been taken.

It gave me a bit of headache as chrome endlessly tried to send instructions to an app already running on the port generated by the following statement:

  • this.port = Math.floor(Math.random() * 10000 + 1000);

To overtake that issue I created my own function that is a copy of the static method "generateSinglePdf"

let generatePDF = async (url, filename, options) => {
    const renderer = new RenderPDF(options)
    renderer.port = generatePortNumber()
    await renderer.connectToChrome()
    try {
        const buff = await renderer.renderPdf(url, renderer.generatePdfOptions())
        fs.writeFileSync(filename, buff);
        renderer.log(`Saved ${filename}`)
    } catch (e) {
        renderer.error('error:', e)
    }
    renderer.killChrome()
}

This function will generate port numbers within a determined range (6000-7000)

let generatePortNumber = () => {
    const min = 6000
    const max = 7000
    return Math.floor(Math.random() * (max - min + 1)) + min
}

When chromeBinary path has spaces in it

When the chrome binary path has spaces in it the file location does not appear to be found by default or when the file location is explicitly passed in. For example:

const RenderPDF = require('chrome-headless-render-pdf');
RenderPDF.generateMultiplePdf([
{url:'http://google.com',pdf:'C:\Users\Your Name\Desktop\outputPdf.pdf', chromeBinary:'C:\Program Files (x86)\Google\Chrome\Application\'}
]).then(function(args){
console.log(args);
}, function(err){
console.log(err);
});

Results in:

Error: Couldn't detect chrome version installed! use --chrome-binary to pass custom location
at RenderPDF.detectChrome (C:\dev\paylockReportRunner\node_modules\chrome-headless-render-pdf\index.js:282:15)
at process._tickCallback (internal/process/next_tick.js:109:7)

Obviously I'm on Windows. Specifically W10 and Chrome 68, both 64-bit. I tried replacing the \ with / but the result is the same. I also tried explicitly adding in the chrome.exe but still the same result. This led me to the conclusion that it was the spaces in the path. Suggestions?

TypeError: Browser.getVersion is not a function

I'm on Arch Linux, installed via npm install chrome-headless-render-pdf. Command doesn't work programmically or via cli, I suspect this was introduced recently, because older versions work fine.

RenderPDF generateSinglePdf does not work in docker at times

RenderPDF generateSinglePdf stops working in docker occasionally , it crashes maybe 1 out of 75. It requires pod to restart in order to make it work again . It works fine with same payloads till it reaches that breaking point where it stops to generate Pdf.

There is no error log as well in generateSinglePdf which suggest what may be going wrong. There is no issue with windows though.

Stuck at "Chrome port open!"

I've been using chrome-headless-render-pdf every month without an issue for the past 5 years... until today.

$ chrome-headless-render-pdf --url http://google.com --pdf test.pdf --chrome-binary 'C:\Program Files\Google\Chrome\Application\chrome.exe'
Using C:\Program Files\Google\Chrome\Application\chrome.exe
Waiting for chrome to became available
Chrome port open!
Chrome port open!
Chrome port open!
Chrome port open!
Chrome port open!
[...]

My current environment:

  • Windows: Version 19044.2486
  • Chrome: Version 110.0.5481.77 (Official Build) (64-bit)

I've updated to from [email protected] to latest v1.10.0, but same issue exists.

I suspect the issue might be within Chrome itself which updated recently.

Extra page on generation

I've noticed that if I pass the --no-margins parameter I get a second, blank page on the generated PDF.

CSS is ignored

Hi, I cannot get any css to work - I'm trying to render this file

<html>
  <head>
    <meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
    <title></title>
    <style type='text/css' media='all'>
      .redbackground {
        background-color: #FF0000;
      }
    </style>
  </head>
  <body>
    <div class="redbackground">Red</div>
    <div style="background-color: #00FF00;">Green</div>
  </body>
</html>

with this command

chrome-headless-render-pdf --url "file:///tmp/test.html" --pdf /tmp/test.pdf

No color is ever rendered. Am I missing something obvious?

--chromeBinary vs. --chrome-binary

In

throw Error('Couldn\'t detect chrome version installed! use --chrome-binary to pass custom location');
the user is asked to provide the option --chrome-binary. However, that still fails for me. Only by checking the source code I was able to correctly use the CLI, namely by passing the option --chromeBinary.

I'd expect either the message to be correct or the function detectChrome to be able to handle both --chromeBinary and --chrome-binary.

Waiting for chrome to became available

I got following error:
`Using /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome
Waiting for chrome to became available
events.js:160
throw er; // Unhandled 'error' event
^

Error: spawn /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome ENOENT
at exports._errnoException (util.js:1022:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:193:32)
at onErrorNT (internal/child_process.js:359:16)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)`

chrome version 60.0.3112.113

Can't find Chrome on Ubuntu

Works great on Mac but when I run in prod I get the following error when trying to run cli.

Error: Couldn't detect chrome version installed! use --chrome-binary to pass custom location
    at RenderPDF._callee10$ (/home/justin/.nvm/versions/node/v12.16.2/lib/node_modules/chrome-headless-render-pdf/dist/index.js:665:39)
    at tryCatch (/home/justin/.nvm/versions/node/v12.16.2/lib/node_modules/chrome-headless-render-pdf/node_modules/babel-runtime/node_modules/regenerator-runtime/runtime.js:62:40)
    at Generator.invoke [as _invoke] (/home/justin/.nvm/versions/node/v12.16.2/lib/node_modules/chrome-headless-render-pdf/node_modules/babel-runtime/node_modules/regenerator-runtime/runtime.js:296:22)
    at Generator.prototype.<computed> [as next] (/home/justin/.nvm/versions/node/v12.16.2/lib/node_modules/chrome-headless-render-pdf/node_modules/babel-runtime/node_modules/regenerator-runtime/runtime.js:114:21)
    at step (/home/justin/.nvm/versions/node/v12.16.2/lib/node_modules/chrome-headless-render-pdf/node_modules/babel-runtime/helpers/asyncToGenerator.js:17:30)
    at /home/justin/.nvm/versions/node/v12.16.2/lib/node_modules/chrome-headless-render-pdf/node_modules/babel-runtime/helpers/asyncToGenerator.js:28:13

I tried to add dependencies with this install command but still get the same error

sudo apt-get install gconf-service libasound2 libatk1.0-0 libatk-bridge2.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 ca-certificates fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget

How can I update the node version dependency?

I'm using this library along with angular 8 and AWS, but the pdf download fails since aws doesn't support node v8.xx
Someone has an idea on how can I solve this compatibility issue? without changing the library.

Screen resolution at 800x600

The 800x600 screen resolution is a restriction on how the page prints to pdf for a number of sites.
Can we either hard-code a larger screen resolution or pass on a variable to fix this?

Example:
chrome-headless-render-pdf --url https://www.whatismyscreenresolution.com/ --no-margins --pdf screen.pdf
Result: 800x600

Request:
(a) hardcoded screen resolution at a larger standard size.

Line 332: of index.js would simply add '--window-size=1600,1280' to the array of parameters for chromeExec. The danger, of course, is that this would change the rendering for scripts that depend on the 800x600 resolution.

(b) flag for screen resolution
I believe this would require:

  1. Adding arguments to argv (cli/chrome-headless-render-pdf.js:27)
    string: ['url','pdf','chrome-binary','window-size'],
  2. Parsing out width and height
    var [x,y] = "window-size".split(',');
  3. Applying x and y to the call to chromeExec (assuming this is uniform across execs)
    "--window-size="+x+","+y

Media emulation option

It would be nice, if it were possible to set the media emulation setting.
Example command (without configurability):
await Emulation.setEmulatedMedia({media: "screen"});

Force Chrome to wait before PDF print

Thank you for this very useful software.

I have a use case where I need to force Chrome to wait before it prints a PDF. The page itself needs to run some Javascript and complete this work prior to printing. I've tried passing virtual-time-budget, but it seems to have no effect. The log output returned from chrome-headless-render-pdf includes the following:

Wait for js execution took 1ms

Is there a flag or other setting I can use with chrome-headless-render-pdf to force Chrome to wait for perhaps 2000ms before printing to PDF?

Hangs when running on Ubuntu with Chrome 64

I don't seem to be able to get chrome-headless-render-pdf to do anything other than hang. This is what I get for a variety of normal and localhost (my actual use case) web sites:

$ npx chrome-headless-render-pdf --url 'https://news.bbc.co.uk' --pdf ./output.pdf --chrome-binary=/usr/bin/chromium-browser
Using /usr/bin/chromium-browser
Waiting for chrome to became available
Connected!
Opening https://news.bbc.co.uk
^C

I let it set there for a couple of minutes before killing it. Is there anything I can do to get more diagnostics, to see what's going on?

System info:

  • Ubuntu 17.10
  • Chromium 64.0.3282.140 (Official Build) Built on Ubuntu , running on Ubuntu 17.10 (64-bit)
  • node -v # => v8.9.4
  • grep pdf package.json # => "chrome-headless-render-pdf": "^1.5.0",

Starting chrome via `chrome-headless-render-pdf` fails (2023)

When running chrome via chrome-headless-render-pdf
( Node.js script https://github.com/Szpadel/chrome-headless-render-pdf ),
I get error, that I cannot yet understand what to do with it.

Versions:

  • Google Chrome 112.0.5615.49
  • chrome-headless-render-pdf 1.11.0

Error Log:

Using /usr/bin/google-chrome
Waiting for chrome to became available
Detected ipv4 connection
Chrome port open!
Chrome stopped (null)
(chrome) (out) 
(chrome) (err) qemu: uncaught target signal 5 (Trace/breakpoint trap) - core dumped
(chrome) (err) qemu: uncaught target signal 5 (Trace/breakpoint trap) - core dumped
(chrome) (err) [0417/090555.189718:ERROR:bus.cc(399)] Failed to connect to the bus: Failed to connect to socket /run/dbus/system_bus_socket: No such file or directory
(chrome) (err) [0417/090555.285522:ERROR:bus.cc(399)] Failed to connect to the bus: Failed to connect to socket /run/dbus/system_bus_socket: No such file or directory
(chrome) (err) [0417/090555.286453:ERROR:bus.cc(399)] Failed to connect to the bus: Failed to connect to socket /run/dbus/system_bus_socket: No such file or directory
(chrome) (err) [0417/090555.300120:ERROR:file_path_watcher_inotify.cc(315)] inotify_init() failed: Function not implemented (38)
(chrome) (err) 
(chrome) (err) DevTools listening on ws://127.0.0.1:49238/devtools/browser/ec0a1593-97aa-4a19-8360-7ceb4b950e68
(chrome) (err) qemu: unknown option 'type=utility'
(chrome) (err) [0417/090555.613256:WARNING:bluez_dbus_manager.cc(247)] Floss manager not present, cannot set Floss enable/disable.
(chrome) (err) [0417/090555.617069:ERROR:gpu_process_host.cc(936)] GPU process launch failed: error_code=1002
(chrome) (err) [0417/090555.617211:WARNING:gpu_process_host.cc(1292)] The GPU process has crashed 1 time(s)
(chrome) (err) [0417/090555.635196:ERROR:network_service_instance_impl.cc(541)] Network service crashed, restarting service.
(chrome) (err) qemu: unknown option 'type=utility'
(chrome) (err) [0417/090555.688126:ERROR:gpu_process_host.cc(936)] GPU process launch failed: error_code=1002
(chrome) (err) [0417/090555.688202:WARNING:gpu_process_host.cc(1292)] The GPU process has crashed 2 time(s)
(chrome) (err) [0417/090555.697249:ERROR:network_service_instance_impl.cc(541)] Network service crashed, restarting service.
(chrome) (err) qemu: unknown option 'type=utility'
(chrome) (err) [0417/090555.722214:ERROR:gpu_process_host.cc(936)] GPU process launch failed: error_code=1002
(chrome) (err) [0417/090555.722285:WARNING:gpu_process_host.cc(1292)] The GPU process has crashed 3 time(s)
(chrome) (err) [0417/090555.722377:FATAL:gpu_data_manager_impl_private.cc(440)] GPU process isn't usable. Goodbye.
(chrome) (err) [0417/090555.724842:ERROR:scoped_ptrace_attach.cc(27)] ptrace: Function not implemented (38)
(chrome) (err) qemu: uncaught target signal 5 (Trace/breakpoint trap) - core dumped
(chrome) (err) 
Chrome port open!
Chrome port open!

chrome and chrome-headless-render-pdf are running in docker.

Chrome is installed as

FROM ubuntu:22.04 AS linux_with_chrome

# Installing latest Chrome directly from Google repository
# check actual version at https://www.ubuntuupdates.org/ppa/google_chrome?dist=stable
# TODO install Chrome of specific version, check links in https://askubuntu.com/questions/1334876/how-to-install-google-chrome-version-88-for-ubuntu
RUN apt-get update
# Install wget.
RUN apt-get install -y wget
# dependency of Chrome
RUN apt-get install -y gnupg
# Set the Chrome key and repository.
RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
    && echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list
# Install Chrome.
RUN apt-get update && apt-get -y install google-chrome-stable

Also on https://stackoverflow.com/questions/76035608/starting-chrome-via-chrome-headless-render-pdf-fails-2023

Which version of node ? Windows support ?

Hi

This seems like a great tool.
Trying it out on windows a.t.m. Unfortunately it explodes right into my face when running a small example.
const RenderPDF = require('chrome-headless-render-pdf'); RenderPDF.generateSinglePdf('http://google.com', 'outputPdf.pdf');

image

Running node v7.2.1.

Any help ?

How to set cookies using chrome-headless-render-pdf?

Hi,

I want to generate a PDF from a page where a user is authenticated. Therefore, I'd like to pass the session cookie when using chrome-headless-render-pdf.

However, using the library, I haven't see anything regarding setting cookies. Maybe through the --chrome-options flag?

Which chrome options though? I've found this list: https://peter.sh/experiments/chromium-command-line-switches/ but there does not seem to have anything related to setting cookies.

generatePdfBuffer doesn't work

Because the finally block executes immediately and kills Chrome before it has had the change to return the data to the requester.

The return line is missing the await.

What format do I use for parameters to pass to generateMultiplePdf?

Hi, I expect this is me just not getting some ES6 thing, but I'm trying to generate multiple pdfs from several local files and getting an error: Error: Invalid parameters (url: string value expected)

I'm confused because in the instructions it shows a format that I don't recognize. It looks like an array of objects, but inside the curly brackets doesn't appear to be a valid object ({url, output} instead of {url: output}). I've tried several different ways to pass parameters but having no luck. Can you clarify what the function is looking for?

Thanks!

From the readme:

RenderPDF.generateMultiplePdf([
    {'http://google.com', 'outputPdf.pdf'},
    {'http://example.com', 'outputPdf2.pdf'}
]);

My Error logs:

multiplePdfObject after loop [ { 'file:\C:\modernsubmissions-redux\tmp\1504789339753_acord126.html': 'file:\\C:\\modernsubmissions-redux\\tmp\\1504789339753_acord126.pdf' },
  { 'file:\C:\modernsubmissions-redux\tmp\1504789339753_acord140.html': 'file:\\C:\\modernsubmissions-redux\\tmp\\1504789339753_acord140.pdf' },
  { 'file:\C:\modernsubmissions-redux\tmp\1504789339753_acord130.html': 'file:\\C:\\modernsubmissions-redux\\tmp\\1504789339753_acord130.pdf' },
  { 'file:\C:\modernsubmissions-redux\tmp\1504789339753_acord131.html': 'file:\\C:\\modernsubmissions-redux\\tmp\\1504789339753_acord131.pdf' },
  { 'file:\C:\modernsubmissions-redux\tmp\1504789339753_acord125.html': 'file:\\C:\\modernsubmissions-redux\\tmp\\1504789339753_acord125.pdf' },
  { 'file:\C:\modernsubmissions-redux\tmp\1504789339753_MSSuppLiquor.html': 'file:\\C:\\modernsubmissions-redux\\tmp\\1504789339753_MSSuppLiquor.pdf' },
  { 'file:\C:\modernsubmissions-redux\tmp\1504789339753_MSEandO.html': 'file:\\C:\\modernsubmissions-redux\\tmp\\1504789339753_MSEandO.pdf' },
  { 'file:\C:\modernsubmissions-redux\tmp\1504789339753_MSSuppDandO.html': 'file:\\C:\\modernsubmissions-redux\\tmp\\1504789339753_MSSuppDandO.pdf' },
  { 'file:\C:\modernsubmissions-redux\tmp\1504789339753_MSAuto.html': 'file:\\C:\\modernsubmissions-redux\\tmp\\1504789339753_MSAuto.pdf' },
  { 'file:\C:\modernsubmissions-redux\tmp\1504789339753_MSCyber.html': 'file:\\C:\\modernsubmissions-redux\\tmp\\1504789339753_MSCyber.pdf' },
  { 'file:\C:\modernsubmissions-redux\tmp\1504789339753_MSEandOIndustrySuppTech.html': 'file:\\C:\\modernsubmissions-redux\\tmp\\1504789339753_MSEandOIndustrySuppTech.pdf' },
  { 'file:\C:\modernsubmissions-redux\tmp\1504789339753_MSLossRunRequestLetter.html': 'file:\\C:\\modernsubmissions-redux\\tmp\\1504789339753_MSLossRunRequestLetter.pdf' } ]
(node:5108) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Invalid parameters (url: string value expected)

Chrome headless instances remain running.

When calling generateSinglePdf from express.js I am seeing chrome instances get spawned but never destroyed, they remain running in the background. It appears the the kill command is being called but the chrome instances are still using memory. I am on windows 10 chrome build Version 60.0.3112.78 (Official Build) beta (64-bit), any ideas?

/* global */
'use strict';

const RenderPDF = require('chrome-headless-render-pdf');

module.exports = function (cb) {
    const htmlFileName = 'file://page.html';

    const pdfName = Date.now() + '_page.pdf';
    
    RenderPDF.generateSinglePdf(htmlFileName, pdfName, { chromeBinary: 'chrome' }).then(resp => {
            cb(null, pdfName);
        })
        .catch(err => {
            cb(err);
        });
};
const express = require('express')
const app = express()
const render = require('./render4');

app.get('/', function (req, res) {
    render((err, resp) => {
        res.send(resp);
    });
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

Stuck on "Opening https:// ..."

When I run this command:

chrome-headless-render-pdf --chrome-binary="C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --url=https://www.chromestatus.com/features --pdf=output.pdf

I get up to "Opening https://www.chromestatus.com/features" and nothing else happens?

Full cmd log

C:\bin\urls to pdf> chrome-headless-render-pdf --chrome-binary="C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --url=https://www.chromestatus.com/features --pdf=output.pdf
Using C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
Waiting for chrome to became available
Connected!
Connected to HeadlessChrome/65.0.3325.181, protocol 1.2
Opening https://www.chromestatus.com/features

Chrome Headless opens up and does not close. All of these chrome processes are spawned when printing, and I started with no other chrome.exe open.

image

Margins Settings

I can not find anywhere to set margins for top, bottom, right, and left.
If it is possible?
If not, will it be added?

Use an existing instance of Chromium

Hi!

I'm using your CLI tool on Docker, running on my Mac M2 machine. I use Debian in the container.

I try to create a shell script that launch Chromium once at the startup of the container, and then connect your tool to this existing instance, but I get this error :

Capture d’écran 2023-02-15 à 22 01 26

Can you please help?

Thanks!

Adding include-background options

I am not sure how to add the options to include background when using this code:

ex:
const RenderPDF = require('chrome-headless-render-pdf');

RenderPDF.generatePdfBuffer('http://google.com')
.then((pdfBuffer) => {
console.log(pdfBuffer);
});

Obscure chrome error logging

Errors from the statement below do not display any meaningful message as the .toString() basically prints "[Object object]".

this.browserLog('err', this.chrome.stderr.toString());

Intermittent hangs due to virtual time budget never expiring

Running 65.0.3325.181 on Ubuntu, the cli sometimes hangs when rendering even trivial documents like this:

<html>
  <body>
    <h1>hello world</h1>
  </body>
</html>

It appears to be due to the virtual time budget / jsDone callback steps -- I can fix my issue by removing the related lines:

await Emulation.setVirtualTimePolicy({policy: 'pauseIfNetworkFetchesPending', budget: 5000});
...
const jsDone = this.cbToPromise(Emulation.virtualTimeBudgetExpired);
...
await jsDone;

Perhaps there could be an option like --wait-for-networking=false to disable this behavior? It seems this feature of the debugging protocol is still experimental.[1] I'd be happy to submit a PR if that seems like a good option.

edit: The issue also goes away completely if I move the setVirtualTimePolicy call to after the Page.loadEventFired event, as in this diff. I'm going to open a PR for this rather than add another CLI option.

[1] https://chromedevtools.github.io/devtools-protocol/tot/Emulation/#method-setVirtualTimePolicy

Can I use it with Apache/PHP?

I would like to run this module ot of PHP (maybe with exec()) - how would its installation llok like for me then?

unable to pass options when using programatically

Hi,

how can we pass the options arguments when using the tool programmatically? i'm thinking something like this:

const RenderPDF = require('chrome-headless-render-pdf');
const options = {include-background: true, no-margins: true, page-ranges: '1'};
RenderPDF.generateSinglePdf( 'http://www.google.com', 'output.pdf', options);

Multi pdf example not working

const RenderPDF = require('chrome-headless-render-pdf');
RenderPDF.generateMultiplePdf([
{'http://google.com', 'outputPdf.pdf'},
{'http://example.com', 'outputPdf2.pdf'}
]);

Running this example gives the following output

{'http://google.com', 'outputPdf.pdf'},
^
SyntaxError: Unexpected token ','
at wrapSafe (internal/modules/cjs/loader.js:979:16)
at Module._compile (internal/modules/cjs/loader.js:1027:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47

Single pdf example is working fine

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.