WPF网页浏览器在更改设置后打印,无需用户交互

本文关键字:打印 交互 用户 设置 网页浏览 网页 浏览器 WPF | 更新日期: 2023-09-27 18:02:29

我有一个从WebBrowser控件打印到标签打印机的应用程序。这个想法是,当我们打印HTML文档时,会根据纸张大小和方向等不同的设置进行打印。当我这样做的时候,一切都很好:

public Boolean DrawHTML(String HTML)
{
  try
  {
    // Load HTML document as a string
    //using (StringReader reader = new StringReader(HTML))
    using (StreamReader reader = new StreamReader(HTML))
    {
      // Navigate to HTML document string
      Web_Document.Navigate(reader.ReadToEnd());
    }
    return true;
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message + ":'nFile:'n'n" + HTML);
    return false;
  }
}
public Boolean Print(String PrinterName, String PrintJobName, Boolean IsLandscape, int LabelCount,double LabelWidth, double LabelHeight)
{
  try
  {
    PrintQueueCollection _Printers = new PrintServer().GetPrintQueues(new[] {
    EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Connections});
    foreach (PrintQueue Q in _Printers)
    {
      if (Q.FullName == PrinterName)
      {
        Q.UserPrintTicket.CopyCount = LabelCount;
        if (IsLandscape)
        {
          Q.UserPrintTicket.PageOrientation = PageOrientation.Landscape;
        }
        else
        {
          Q.UserPrintTicket.PageOrientation = PageOrientation.Portrait;
        }
        Q.UserPrintTicket.PageBorderless = PageBorderless.Borderless;
        double W = ((LabelWidth / 25.4) * 96);
        double H = ((LabelHeight / 25.4) * 96);
        Q.UserPrintTicket.PageMediaSize = new PageMediaSize(PageMediaSizeName.Unknown, W, H);
        var writer = PrintQueue.CreateXpsDocumentWriter(Q);
        writer.Write(Web_Document, Q.UserPrintTicket);

        return true;
      }
    }
    //Printer Not Found
    return false;
  }
  catch (Exception)
  {
    //problem occured
    return false;
  }
}   
#endregion

}

一切正常,除了三个问题。

  1. 如果HTML正文不包含scroll ="no"则会出现滚动条,这是可以的,但也打印,这是不可以的。

  2. 印刷真的很糟糕。非常模糊。

  3. 如果主机框架小于html内容,将只打印可见内容。我想打印全部内容

有什么建议吗?

谢谢

WPF网页浏览器在更改设置后打印,无需用户交互

使用以下代码:

try
{ 
    var doc = Web_Document.Document as mshtml.IHTMLDocument2;
    const string keyName = @"Software'Microsoft'Internet Explorer'PageSetup";
    using (var key = Registry.CurrentUser.OpenSubKey(keyName, true))
    {
        if (key != null)
        {
            var oldFooter = key.GetValue("footer"); 
            var oldHeader = key.GetValue("header"); 
            key.SetValue("footer", ""); 
            key.SetValue("header", "");
            doc.execCommand("Print", true, null);
            key.SetValue("footer", oldFooter); 
            key.SetValue("header", oldHeader);
        }
    }
}
catch (Exception ex)
{
    Log.Error(ex.Message,ex);
}

如果没有页眉和页脚,打印效果会很好