以编程方式打印网页

programmatically print a web page

本文关键字:网页 式打印 编程      更新时间:2023-09-26

我正在制作一个程序,自动转到网站并打印页面,似乎无法使其工作,我尝试了硒铬驱动程序,问题是它不工作。我尝试了action.sendkeys键ctrl + shift + p,但没有成功,最大的问题是打印预览弹出窗口。我尝试发送JavaScript命令:window.print(),但chrome中的打印预览挡住了我的去路,因为你需要按回车键。JavaScript中有没有一种方法可以模拟按下ENTER键?我们将不胜感激。

好吧,经过一点研究,我发现这个视频,如果你可以添加这些开关:"--kiosk---kiosk printing",到chrome驱动程序启动时,它会自动跳过打印预览提示,就像视频中所示。此外,我在最新版本的SRWare铁(铬叉)上测试了这一点,它成功了。

如果你使用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的Url,并使用默认打印机打印它。

也许你可以使用这种不需要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();