我正在尝试使用打印对话框另存为pdf,这是一个我已经使用Selenium和Headless Chrome(v81(登录的网页。所有文章都指出我应该能够使用kiosk模式将文档打印/保存为pdf,其中打印到pdf会自动发生,因此预览对话框被按下,例如
我无法让 Chrome 在使用硒时默认另存为 PDF 硒铬另存为 pdf 更改下载文件夹
到目前为止,我有以下代码:
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.AddArguments("--headless", "--disable-infobars", "--disable-extensions", "--test-type", "--allow-insecure-localhost", "--ignore-certificate-errors", "--ignore-ssl-errors=yes", "--disable-gpu", "--kiosk-printing", "--allow-running-insecure-content");
chromeOptions.AcceptInsecureCertificates = acceptInsecureCertificates;
chromeOptions.UnhandledPromptBehavior = UnhandledPromptBehavior.Ignore;
chromeOptions.AddUserProfilePreference("print.always_print_silent", true);
chromeOptions.AddUserProfilePreference("download.default_directory", @"C:Temp");
chromeOptions.AddUserProfilePreference("savefile.default_directory", @"C:Temp");
chromeOptions.AddUserProfilePreference("download.prompt_for_download", false);
chromeOptions.AddUserProfilePreference("printing.default_destination_selection_rules", "{"kind": "local", "namePattern": "Save as PDF"}");
chromeOptions.AddUserProfilePreference("printing.print_preview_sticky_settings.appState", "{"recentDestinations": [{"id": "Save as PDF", "origin": "local", "account": "" }],"version":2,"isGcpPromoDismissed":false,"selectedDestinationId":"Save as PDF"}");
webDriver = new ChromeDriver(ChromeDriverService.CreateDefaultService(), chromeOptions, TimeSpan.FromMinutes(timeoutMinutes));
然后我用这个打印页面:
var driver = FeatureContext.Current.GetWebDriver();
driver.ExecuteJavaScript("window.print();");
但是我总是收到打印预览对话框,并且设置了默认打印机而不是另存为PDF。
但是,我会使用chrome命令行,因为我需要登录到该站点。上面的代码有什么问题?
更新 20/05/2022:使用 Selenium 4,现在可以更轻松地"保存到 PDF"。有一个条件:您的应用程序需要在无头模式下运行,否则,Selenium 将抛出异常PrintToPDF is only supported in headless mode
。但是如果某种原因,您无法在无头模式下运行,我之前的回复仍然有效。
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using System.IO;
private static ChromeOptions _chromeOptions;
private static WebDriver _driver;
private static string fileName = "MyPrint";
private static string printFinalPath = Path.Combine($@"C:Users{Environment.UserName}Downloads", string.Concat(fileName, ".pdf"));
static void Main(string[] args)
{
_chromeOptions = new ChromeOptions();
_chromeOptions.AddArguments("headless"); //your chrome driver needs run in headless!
//creating webdriver
_driver = new ChromeDriver(_chromeOptions);
//go to the website
_driver.Navigate().GoToUrl("https://www.google.com/");
//defining configurations for de printing
PrintOptions printOptions = new PrintOptions
{
Orientation = PrintOrientation.Portrait
};
//printing...
PrintDocument printDocument = _driver.Print(printOptions);
//saving the file
printDocument.SaveAsFile(printFinalPath);
}
原始回复Selenium 4具有一些新功能,例如通过ChromeDevTools"执行命令"。有了这个功能,我们可以直接从chrome调用"PdfAsync"之类的东西(像Puppersharp,但使用硒(。但不幸的是,我们还没有在 c# 中启用此选项。"打印-pdf"将来会更容易。
但是,使用 selenium 3.141.0,在 Web 的主题中进行一些搜索,我在您的代码的帮助下解决了这个问题。我在将字符串 C# 转换为 json 对象时遇到了一些问题。
使用 chrome 中的日志记录来提供帮助。
更新 27/07/2021: 不幸的是,使用参数"无头"窗口.print(("将不起作用。
我的最终代码是:
public class Program
...
static void Main(string[] args)
{
private static IWebDriver _driver;
private static ChromeOptions _chromeOptions;
private static ChromeDriverService _chromeService;
private static string pathLogChromeDriver = "chrome_driver_logs";
private static string nameFileLog = "chromedriver.log";
//creating chrome service, to logging
_chromeService = ChromeDriverService.CreateDefaultService(".");
//using to see the modifications in google chrome arguments
_chromeService.LogPath = Path.Combine(Directory.GetCurrentDirectory(), pathLogChromeDriver, nameFileLog);
_chromeService.EnableVerboseLogging = true;
//creating chromeOptions, to set the profile preferences
_chromeOptions = new ChromeOptions();
//using Dictionary to pass parameter name (string) and json object to AddUserProfilePreference.
Dictionary<string, object> prefs = new Dictionary<string, object>();
prefs.Add("downloadFile", "{"recentDestinations": [{"id": "Save as PDF", "origin": "local", "account": "" }],"version":2,"isGcpPromoDismissed":false,"selectedDestinationId":"Save as PDF"}");
prefs.Add("pathFinalFile", "C:\Users\" + Environment.UserName + "\Downloads\");
//using the dictionary values to set the parameters
_chromeOptions.AddUserProfilePreference("printing.print_preview_sticky_settings.appState", prefs["downloadFile"])
_chromeOptions.AddUserProfilePreference("savefile.default_directory", prefs["pathFinalFile"]);
//disable 'chrome is being controlled by automated test software' bar
_chromeOptions.AddUserProfilePreference("useAutomationExtension", false);
_chromeOptions.AddExcludedArgument("enable-automation");
//using --kiosk-printing to enable "silent printing"
_chromeOptions.AddArgument("--kiosk-printing");
//creating webdriver
_driver = new ChromeDriver(_chromeService, _chromeOptions);
_driver.Navigate().GoToUrl("https://applitools.com/blog/selenium-4-chrome-devtools/");
_driver.Manage().Window.Maximize();
//run javascript to print
_driver.ExecuteJavaScript("window.print();");
//is done!
}
如果窗口"另存为"仍然打开,则某些参数不正确。