Javascript 以编程方式打印网页
我正在做一个程序,自动去一个网站,打印一个页面,似乎无法使它工作,我尝试硒铬驱动程序,问题是它不工作。我尝试了action.sendkeysJavascript 以编程方式打印网页,javascript,c#,selenium-webdriver,Javascript,C#,Selenium Webdriver,我正在做一个程序,自动去一个网站,打印一个页面,似乎无法使它工作,我尝试硒铬驱动程序,问题是它不工作。我尝试了action.sendkeysctrl+shift+p但没有效果,最大的问题是打印预览弹出窗口。 我尝试发送JavaScript命令:window.print(),但chrome中的打印预览妨碍了我,因为您需要按enter键。JavaScript中是否有方法模拟按下ENTER键?非常感谢您的帮助。经过一点研究,我发现,如果您可以在chrome驱动程序启动中添加这些开关:“--kiosk-
ctrl+shift+p
但没有效果,最大的问题是打印预览弹出窗口。
我尝试发送JavaScript命令:
window.print()
,但chrome中的打印预览妨碍了我,因为您需要按enter键。JavaScript中是否有方法模拟按下ENTER
键?非常感谢您的帮助。经过一点研究,我发现,如果您可以在chrome驱动程序启动中添加这些开关:“--kiosk--kiosk printing”,它将自动跳过打印预览提示,如视频所示。
此外,我在最新版本的SRWare iron(铬叉)上测试了这一点,它起了作用
如果您使用C#制作程序,那么有一个更简单的解决方案:
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或来自internet,并使用默认打印机进行打印。也许您可以使用这种不需要windows窗体的方法,对我来说很有吸引力:
非常感谢,我真的很感激,我今天为这个问题挣扎了3个小时,没有意识到去钻研Webbrowser控制c#,就像在你手里拿着眼镜的时候搜索眼镜LOL。我按下“接受”,这就是我需要做的吗?我在回答、编辑评论和接受答案方面是新手。
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();