【问题标题】:programmatically print a web page以编程方式打印网页
【发布时间】:2021-09-03 05:07:44
【问题描述】:

我正在制作一个程序来自动访问网站并打印页面,似乎无法使其工作,我尝试了 selenium chrome 驱动程序,问题是它不起作用。我尝试了 action.sendkeys 键 ctrl + shift + p 无济于事,最大的问题是打印预览弹出窗口。 我尝试发送 JavaScript 命令:window.print(),但 chrome 中的打印预览挡住了我的路,因为您需要按 Enter。 JavaScript 中有没有办法模拟按下ENTER 键?帮助将不胜感激。

【问题讨论】:

    标签: javascript c# selenium-webdriver


    【解决方案1】:

    好吧,经过一番研究,我发现了这个video,如果你可以在chrome驱动启动时添加这些开关:“--kiosk --kiosk-printing”,它会自动跳过打印预览提示,如视频所示。 另外,我在最新版本的 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();
        }
    

    Here 找到答案,它使用 WebBrowser 控件导航到特定的 Url,可以是本地 url 或来自互联网,并使用您的默认打印机打印。

    【讨论】:

    • 非常感谢,我真的很感激,我今天为这个问题苦苦挣扎了 3 个小时,没有意识到要深入研究 c# 的 webbrowswer 控件,就像拿着它在手上搜索眼镜 LOL。我按下“接受”,这是我需要做的吗?我是回答、编辑评论和接受答案的新手。
    【解决方案2】:

    也许你可以使用这种不需要 Windows 窗体的方法,对我来说就像一个魅力: With C# use Chrome to covert HTML to 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(); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多