我正在制作一个程序,可以自动访问网站并打印页面,但似乎无法正常工作。我尝试了使用Selenium Chrome驱动程序,但问题是它不起作用。我也试过使用action.sendkeys keys ctrl + shift + p
,但没有效果,最大的问题是打印预览弹出窗口。我尝试发送JavaScript命令:window.print()
,但在Chrome中,打印预览会挡住我的路,因为需要按Enter键。有没有办法在JavaScript中模拟按下ENTER
键?非常感谢您的帮助。
我正在制作一个程序,可以自动访问网站并打印页面,但似乎无法正常工作。我尝试了使用Selenium Chrome驱动程序,但问题是它不起作用。我也试过使用action.sendkeys keys ctrl + shift + p
,但没有效果,最大的问题是打印预览弹出窗口。我尝试发送JavaScript命令:window.print()
,但在Chrome中,打印预览会挡住我的路,因为需要按Enter键。有没有办法在JavaScript中模拟按下ENTER
键?非常感谢您的帮助。
private void Button1_Click(object sender, EventArgs e)
{
PrintHelpPage();
}
private void PrintHelpPage()
{
// Create a WebBrowser instance.
WebBrowser webBrowserForPrinting = new WebBrowser();
// Add an event handler that prints the document after it loads.
webBrowserForPrinting.DocumentCompleted +=
new WebBrowserDocumentCompletedEventHandler(PrintDocument);
// Set the Url property to load the document.
webBrowserForPrinting.Url = new Uri(@"http://www.google.com"); //This is what you want to change
}
private void PrintDocument(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
// Print the document now that it is fully loaded.
((WebBrowser)sender).Print();
// Dispose the WebBrowser now that the task is complete.
((WebBrowser)sender).Dispose();
}
在这里找到了答案,使用WebBrowser控件导航到特定的Url,可以是本地url或者来自互联网,并使用默认打印机打印。
var process = new System.Diagnostics.Process();
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
var chrome = Path.Combine(Environment.GetEnvironmentVariable("ProgramFiles(x86)"), @"Google\Chrome\Application\chrome.exe");
// use powershell
process.StartInfo.FileName = "powershell";
// set the Chrome path as local variable in powershell and run
process.StartInfo.Arguments = "$chrome='" + chrome + @"'; & $chrome --headless --print-to-pdf='c:\Users\" + Environment.UserName + @"\desktop\myReport.pdf' https://google.com";
process.Start();