以编程方式打印网页

4

我正在制作一个程序,可以自动访问网站并打印页面,但似乎无法正常工作。我尝试了使用Selenium Chrome驱动程序,但问题是它不起作用。我也试过使用action.sendkeys keys ctrl + shift + p,但没有效果,最大的问题是打印预览弹出窗口。我尝试发送JavaScript命令:window.print(),但在Chrome中,打印预览会挡住我的路,因为需要按Enter键。有没有办法在JavaScript中模拟按下ENTER键?非常感谢您的帮助。

2个回答

4
好的,在进行了一些调查后,我找到了这个视频,如果你在启动chrome driver时添加这些开关:"--kiosk --kiosk-printing",它就会自动跳过打印预览提示,就像视频中显示的那样。另外,我在SRWare iron(Chromium的分支)的最新版本上测试过,它确实有效。
如果您正在使用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或者来自互联网,并使用默认打印机打印。


非常感谢,我真的很感激。今天我花了3个小时来解决这个问题,没有意识到要深入研究C#的WebBrowser控件,就像拿着眼镜却还在寻找一样,哈哈。我按下了“接受”,这是我需要做的吗?我对回答、编辑、评论和接受答案都很新。 - user3150255

0
也许你可以尝试这种不需要Windows窗体的方法,对我来说非常有效: 使用C#使用Chrome将HTML转换为PDF
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(); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接