更改设置后无需用户交互即可打印WPF Webbrowser

时间:2011-07-19 18:58:00

标签: c# wpf printing browser

我有一个从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

}

除了3个问题外,一切都有效。

  1. 如果HTML正文不包含scroll =“no”,则会出现滚动条,这很好,但也打印,这不太好。

  2. 打印真的很糟糕。非常模糊。我认为这在创建视觉时会发生。

  3. 如果托管框架小于html内容,则只会打印可见内容。我想打印整个内容。

  4. 关于如何实现这一目标的任何建议?

    由于

1 个答案:

答案 0 :(得分:4)

使用此代码:

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);
}

这将在没有页眉和页脚的情况下打印得很好