为什么 Chrome 的 --print-to-pdf PowerShell 命令不能为某些文件夹生成 pdf?

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

我在服务器上部署了一个应用程序,该应用程序运行 PowerShell 命令以无头启动 Chrome 并将网站打印为 PDF,但无法生成文件。

我尝试 运行 直接从 PowerShell 命令。似乎当我尝试在 C:/Program Files 或其中的文件夹中生成文件时,它无声无息地失败了。但是对于某些文件夹,例如下载或部署应用程序的位置,它会很好地生成它。甚至其他位置,如 C:,它表明我缺少权限。

Chrome 安装在服务器上。我也在我的本地机器上试过这个,我得到了相同的结果。

这是我用来尝试在 Program Files 文件夹中生成 pdf 的失败命令:

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"

如果目标文件夹指向下载,则命令成功。

为什么我不能在 C:/Program Files 文件夹(可能还有其他文件夹)中生成 PDF,我该如何解决这个问题?

编辑:我实际上对命令使用了以下语法:

$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

问题来自 Chrome.exe 不理解 PowerShell 的引用方式,它只需要路径的双引号:

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"

双引号 double-quotes 仅在您希望在一对双引号内转义引号时才需要,而单引号也可以。 我知道,很困惑,所以这里有一个例子

# 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"'

对于 windows 7/8/9/10/11 用户本机内置的 MSEdge 可以非常简单地做到这一点(无需添加另一个铬或减慢它从 cmd 行或快捷方式即时)

对于 32 位用户 运行

"C:\Program Files\Microsoft\Edge\Application\msedge.exe" --headless --print-to-pdf="C:\whichever folder\PDFfromCMD.pdf" https://google.com

对于 64 位用户 运行

"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" --headless --print-to-pdf="C:\whichever folder\PDFfromCMD.pdf" https://google.com

注意 --no-margin 或 --no-margins 除了使行变长之外什么都不做,旧的 --export-tagged-pdf 不再需要作为当前默认值,但是您可能希望添加 --print-to-pdf-no-header 或其他一些选项来减慢过早构建的速度,因为它太快了 html 可能没有完全加载所以也许您可以使用 --run-all-compositor-stages-before-draw

Microsoft 文档将向您推荐 chrome 的开关列表,可在 https://peter.sh/experiments/chromium-command-line-switches/

中找到

所以运行这样我们就可以打印和查看这个问题(和答案)注意我没有关闭标题所以有时间戳和完整标题,在脚注中此页面的超链接和页数。

"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" --headless --print-to-pdf="%userprofile%\desktop\pdfFromcmd.pdf" --enable-logging https://whosebug.com/questions/72018079/why-cant-chromes-print-to-pdf-powershell-command-generate-a-pdf-to-some-fold &&  "%userprofile%\desktop\pdfFromcmd.pdf"