Home > Mobile >  Why can't Chrome's --print-to-pdf PowerShell command generate a pdf to some folders?
Why can't Chrome's --print-to-pdf PowerShell command generate a pdf to some folders?

Time:04-27

I have an app deployed on a server that runs a PowerShell command to launch headless Chrome and print a website as a PDF but it fails to generate the file.

I tried running the command directly from PowerShell. It seems that when I try to generate the file in C:/Program Files or a folder within it, it silently fails. But then to some folders, like Download or where the app is deployed, it generates it fine. And to even other locations, like C:, it shows that I am missing permissions.

Chrome is installed on the server. I also tried this on my local machine and I'm getting the same results.

This is the failing command I'm using to try and generate a pdf within Program Files folder:

Start-Process -FilePath "C:\Program Files\Google\Chrome\Application\chrome.exe" -ArgumentList "--headless","--print-to-pdf=C:\Program Files\pdfFromPowershell.pdf","--no-margins","--enable-logging","https://google.com"

Command succeeds if the target folder is pointed to Downloads.

Why can't I generate a PDF within C:/Program Files folder (and possibly others) and what can I do to fix this?

Edit: I am actually using the following syntax for the command:

$chrome='C:\Program Files\Google\Chrome\Application\chrome.exe'; & $chrome --headless --print-to-pdf-no-header --print-to-pdf='C:\Program Files\temp\pdfFromPowershell.pdf' --no-margins https://google.com

CodePudding user response:

The issue comes from Chrome.exe not understanding PowerShell's way of quoting, where it just wants double quotes for the path:

Start-Process -FilePath "C:\Program Files\Google\Chrome\Application\chrome.exe" `
              -ArgumentList "--headless",
                            "--print-to-pdf=""C:\Program Files\pdfFromPowershell.pdf""",
                            "--no-margins","--enable-logging","https://google.com"

The need for double double-quotes only comes when you're looking to escape the quotes within a pair of double quotes, whereas single quotes would work too. I know, confusing, so here's an example:

# escape the double quotes inside double quotes by doubling quotes inside.
"--print-to-pdf=""C:\Program Files\pdfFromPowershell.pdf""" 

# using single quotes this should work as well, where only one pair is needed.
'--print-to-pdf="C:\Program Files\pdfFromPowershell.pdf"'
  • Related