2017-02-22 279 views
0

我有一個C#WPF .NET 4.6程序可以創建HTML文件,我想用已知的非默認打印機自動打印它們(沒有對話框)。當然這包括首先渲染HTML。由於程序創建這些文件,HTML數據可能來自MemoryStreamFileStream或直接來自字符串。渲染並打印HTML到非默認打印機

該方案具有設置,允許用戶指定要打印的打印機事先使用System.Drawing.Printing.PrinterSettings.InstalledPrinters,因爲每個文件可能需要不同的打印機。在打印時,打印機的名稱是已知的,但可能與Windows默認打印機不同。

我已經研究了很多其他項目,但他們似乎沒有考慮到打印機是不同於默認。更改默認打印機將是反社會的,並會導致與穿線相關的痛苦世界。這似乎是#1接受的解決方案,但不能是最好的解決方案?


研究和解決方案的看着:

Printing the contents of a WPF WebBrowserSilently print HTML from WPF WebBrowsercorresponding MSDNforum discussions 不足以作爲COM ExecWB函數只打印到默認打印機

MSDN example只使用(?)在WebBrowser上再次使用默認打印機的Print()命令。

所以我沿着嘗試更改打印機選項的路線走下去。 Programmatically changing the destination printer for a WinForms WebBrowser control被問到了,但有一個相當不滿意的答案,因爲它有一個斷開的鏈接,我不知道運行的計算機有什麼外部程序,所以我不能保證Adobe,OpenOffice等OP提到他們解析了ActiveX COM沒有詳細說明。聽起來很棘手。

也許我可以從像this project寫入到一個RichTextBox不閃光的東西,並隱藏盒子?

我認爲Silent print HTML file in C# using WPF是一個很好的路徑,但原始文章有硬編碼的屏幕尺寸‽和OP提到打印機切斷文檔。接受的(和獎勵)答案再次使用ExecWB默認打印機設置方法。

execCommand("Print", false, IDon'tUnderstandThisArgument)也顯示出的承諾,因爲它的答案是更新MSDN answer,但發送到打印機的FILESTREAM不允許HTML,也不會從WebBrowserDocumentStream出現工作(打印機打印一個空白頁)。

How do I programatically change printer settings with the WebBrowser control?具有非常相似的要求對我來說,除了修改註冊表作爲解決方案。

除了研究如何人都做到了,我也嘗試打印WPF WebBrowser直接,因爲它是一個Visual控制:(?因爲WebBrowser是不可見的)

public static bool Print(string printer, Visual objToPrint) 
    { 
     if (string.IsNullOrEmpty(printer)) 
     { 
     return false; 
     } 

     var dlg = new PrintDialog 
     { 
     PrintQueue = new PrintServer().GetPrintQueue(printer) 
     }; 

     dlg.PrintTicket.CopyCount = 1; 
     dlg.PrintTicket.PageOrientation = PageOrientation.Portrait; 
     dlg.PrintTicket.PagesPerSheet = 1; 

     dlg.PrintVisual(objToPrint, "Print description"); 
     return true; 
    } 

但是這不打印任何東西。 並嘗試了PrintDocument作爲更新MSDN article建議:

public static async Task<bool> PrintHTMLAsync(string printer, string html) 
    { 
     bool result; 
     using (var webBrowser = new System.Windows.Forms.WebBrowser()) 
     { 
     webBrowser.DocumentCompleted += ((sender, e) => browserReadySemaphore.Release()); 
     byte[] buffer = Encoding.UTF8.GetBytes(html); 
     webBrowser.DocumentStream = new MemoryStream(buffer); 

     // Wait until the page loads. 
     await browserReadySemaphore.WaitAsync(); 

     try 
     { 
      using (PrintDocument pd = new PrintDocument()) 
      { 
      pd.PrinterSettings.PrinterName = printer; 
      pd.PrinterSettings.Collate = false; 
      pd.PrinterSettings.Copies = 1; 
      pd.PrinterSettings.FromPage = 1; 
      pd.PrinterSettings.ToPage = 1; 
      pd.Print(); 
      result = true; 
      } 
     } 
     catch (Exception ex) 
     { 
      result = false; 
      Debug.WriteLine(ex); 
     } 

     return result; 
     } 
    } 

沒有快樂。

我還使用了PRINT DOS命令:

public static string PerformSilentPrinting(string fileName, string printerName) 
{ 
    try 
    { 
    ProcessStartInfo startInfo = new ProcessStartInfo(fileName) 
    { 
     Arguments = string.Format("/C PRINT /D:\"{0}\" \"{1}\"", printerName, fileName), 
     FileName = "cmd.exe", 
     RedirectStandardOutput = true, 
     UseShellExecute = false, 
     WindowStyle = ProcessWindowStyle.Hidden, 
    }; 

    // Will execute the batch file with the provided arguments 
    Process process = Process.Start(startInfo); 

    // Reads the output   
    return process.StandardOutput.ReadToEnd(); 
    } 
    catch (Exception ex) 
    { 
    return ex.ToString(); 
    } 
} 

但打印命令似乎只接受文本文件。

回答

0

編輯:如果您只需要打印A4的一頁,此解決方案效果很好。但是它只會打印一個頁面,並截斷任何超過它的內容。


在我與一個WinForms web瀏覽器去結束時,複製控制成位圖,並使用PrintDialog,這也是在System.Windows.Forms命名空間打印。

using Microsoft.Win32; 
using System; 
using System.ComponentModel; 
using System.Drawing; 
using System.Drawing.Printing; 
using System.IO; 
using System.Threading; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

public static class PrintUtility 
{ 
    private static readonly SemaphoreSlim browserReadySemaphore = new SemaphoreSlim(0); 

    // A4 dimensions. 
    private const int DPI = 600; 
    private const int WIDTH = (int)(8.3 * DPI); 
    private const int HEIGHT = (int)(11.7 * DPI); 

    public static void Print(this Image image, string printer, bool showDialog = false) 
    { 
    if (printer == null) 
    { 
     throw new ArgumentNullException("Printer cannot be null.", nameof(printer)); 
    } 

    using (PrintDialog printDialog = new PrintDialog()) 
    { 
     using (PrintDocument printDoc = new PrintDocument()) 
     { 
     printDialog.Document = printDoc; 
     printDialog.Document.DocumentName = "My Document"; 
     printDialog.Document.OriginAtMargins = false; 
     printDialog.PrinterSettings.PrinterName = printer; 

     printDoc.PrintPage += (sender, e) => 
     { 
      // Draw to fill page 
      e.Graphics.DrawImage(image, 0, 0, e.PageSettings.PrintableArea.Width, e.PageSettings.PrintableArea.Height); 

      // Draw to default margins 
      // e.Graphics.DrawImage(image, e.MarginBounds); 
     }; 

     bool doPrint = !showDialog; 
     if (showDialog) 
     { 
      var result = printDialog.ShowDialog(); 
      doPrint = (result == DialogResult.OK); 
     } 

     if (doPrint) 
     { 
      printDoc.Print(); 
     } 
     } 
    } 
    } 

    public static async Task<bool> RenderAndPrintHTMLAsync(string html, string printer) 
    { 
    bool result = false; 

    // Enable HTML5 etc. (assuming we're running IE9+) 
    SetFeatureBrowserFeature("FEATURE_BROWSER_EMULATION", 9000); 

    // Force software rendering 
    SetFeatureBrowserFeature("FEATURE_IVIEWOBJECTDRAW_DMLT9_WITH_GDI", 1); 
    SetFeatureBrowserFeature("FEATURE_GPU_RENDERING", 0); 

    using (var webBrowser = new WebBrowser()) 
    { 
     webBrowser.ScrollBarsEnabled = false; 
     webBrowser.Width = WIDTH; 
     webBrowser.Height = HEIGHT; 
     webBrowser.DocumentCompleted += ((s, e) => browserReadySemaphore.Release()); 
     webBrowser.LoadHTML(html); 

     // Wait until the page loads. 
     await browserReadySemaphore.WaitAsync(); 

     // Save the picture 
     using (var bitmap = webBrowser.ToBitmap()) 
     { 
     bitmap.Save("WebBrowser_Bitmap.bmp"); 
     Print(bitmap, printer); 
     result = true; 
     } 
    } 

    return result; 
    } 

    /// <summary> 
    /// Make a Bitmap from the Control. 
    /// Remember to dispose after. 
    /// </summary> 
    /// <param name="control"></param> 
    /// <returns></returns> 
    public static Bitmap ToBitmap(this Control control) 
    { 
    Bitmap bitmap = new Bitmap(control.Width, control.Height); 
    Rectangle rect = new Rectangle(0, 0, control.Width, control.Height); 
    control.DrawToBitmap(bitmap, new Rectangle(0, 0, control.Width, control.Height)); 
    return bitmap; 
    } 

    /// <summary> 
    /// Required because of a bug where the WebBrowser only loads text once or not at all. 
    /// </summary> 
    /// <param name="webBrowser"></param> 
    /// <param name="htmlToLoad"></param> 
    /// <remarks> 
    /// http://stackoverflow.com/questions/5362591/how-to-display-the-string-html-contents-into-webbrowser-control/23736063#23736063 
    /// </remarks> 
    public static void LoadHTML(this WebBrowser webBrowser, string htmlToLoad) 
    { 
    webBrowser.Document.OpenNew(true); 
    webBrowser.Document.Write(htmlToLoad); 
    webBrowser.Refresh(); 
    } 

    /// <summary> 
    /// WebBrowser Feature Control 
    /// </summary> 
    /// <param name="feature"></param> 
    /// <param name="value"></param> 
    /// <remarks> 
    /// http://stackoverflow.com/questions/21697048/how-to-fix-a-opacity-bug-with-drawtobitmap-on-webbrowser-control/21828265#21828265 
    /// http://msdn.microsoft.com/en-us/library/ie/ee330733(v=vs.85).aspx 
    /// </remarks> 
    private static void SetFeatureBrowserFeature(string feature, uint value) 
    { 
    if (LicenseManager.UsageMode != LicenseUsageMode.Runtime) 
    { 
     return; 
    } 

    var appName = Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName); 
    Registry.SetValue(
     @"HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\" + feature, 
     appName, 
     value, 
     RegistryValueKind.DWord); 
    } 
} 
相關問題