使用WPF在C#中静默打印HTML文件

马丁·克莱门斯·布洛赫(Martin Clemens Bloch)

编辑:完全重写了问题并添加了赏金。

基于许多教程和stackoverflow问题,我现在可以:

  • 将多个页面一起打印为一个文档。
  • 打印实际内容。
  • 在页面上正确对齐内容。
  • 打印正确尺寸的文档。

该解决方案要求HTML文档的底部具有一些空白,并且样式标签html {overflow:hidden; }-隐藏滚动条并允许使用滚动进行分页-但我可以接受。

唯一剩下的问题是WPF不会呈现Web浏览器不在屏幕上的部分。

这意味着,如果倾斜计算机屏幕,则可以正确打印,但是如果没有,则文档会切掉下部。

我尝试渲染到位图,但是当我以视觉效果打印结果图像时,页面为空。

如果您知道如何强制WPF完全渲染或如何正确渲染为位图,请帮助我。

打印窗口XAML :(打印WPF仅适用于UI线程,否则将不呈现任何内容...)

<Window x:Class="CardLoader2000.PrintWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="PrintWindow" Height="1139" Width="820">
    <Grid x:Name="grid">
        <!--The alignment and size of the webbrowser is reflected in the print. If larger than document
        it will be cut. The width here corresponds to A4 paper width with a little margin-->
        <WebBrowser x:Name="webBrowser" Height="1089" Width="770" VerticalAlignment="Top" Margin="0,10,0,0"/>
    </Grid>
</Window>

后台打印窗口代码:

public partial class PrintWindow : Window
    {
        public PrintWindow(string path)
        {
            InitializeComponent();

            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);

            webBrowser.NavigateToStream(fs);

            ContentRendered += OnContentRendered;
        }

        private void OnContentRendered(object sender, EventArgs eventArgs)
        {
            PrintDialog pd = new PrintDialog
            {
                PrintTicket = new PrintTicket
                {
                    Duplexing = Duplexing.TwoSidedLongEdge,
                    OutputColor = OutputColor.Monochrome,
                    PageOrientation = PageOrientation.Portrait,
                    PageMediaSize = new PageMediaSize(794, 1122),
                    InputBin = InputBin.AutoSelect
                }
            };

            //Ok, final TODO: Page only renders what is on the PC screen...
            WebPaginator paginator = new WebPaginator(webBrowser, 1089, 1122, 794);

            pd.PrintDocument(paginator, "CustomerLetter");

            Close();
        }
    }

自定义分页器:

public class WebPaginator : DocumentPaginator
    {
        private readonly WebBrowser webBrowser;
        private readonly int pageScroll;
        private Size pageSize;

        public WebPaginator(WebBrowser webBrowser, int pageScroll, double pageHeight, double pageWidth)
        {
            this.webBrowser = webBrowser;
            this.pageScroll = pageScroll;
            pageSize = new Size(pageWidth, pageHeight);
        }

        public override DocumentPage GetPage(int pageNumber)
        {
            HTMLDocument htmlDoc = webBrowser.Document as HTMLDocument;
            if (htmlDoc != null) htmlDoc.parentWindow.scrollTo(0, pageScroll * pageNumber);
            Rect area = new Rect(pageSize);

            return new DocumentPage(webBrowser, pageSize, area, area);
        }

        public override bool IsPageCountValid
        {
            get { return true; }
        }

        /// <summary>
        /// Returns one less than actual length.
        /// Last page should be whitespace, used for scrolling.
        /// </summary>
        public override int PageCount
        {
            get
            {
                var doc = (IHTMLDocument2)webBrowser.Document;
                var height = ((IHTMLElement2)doc.body).scrollHeight;
                int tempVal = height*10/pageScroll;
                tempVal = tempVal%10 == 0
                    ? Math.Max(height/pageScroll, 1)
                    : height/pageScroll + 1;
                return tempVal > 1 ? tempVal-1 : tempVal;
            }
        }

        public override Size PageSize
        {
            get
            {
                return pageSize;
            }
            set
            {
                pageSize = value;
            }
        }

        /// <summary>
        /// Can be null.
        /// </summary>
        public override IDocumentPaginatorSource Source
        {
            get
            {
                return null;
            }
        }
    }
西蒙·莫里尔

您可以使用标准IE的打印功能(通过ExecWB方法),如下所示:

public partial class PrintWindow : Window
{
    public PrintWindow()
    {
        InitializeComponent();
        webBrowser.Navigate("http://www.google.com");
    }

    // I have added a button to demonstrate
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        // NOTE: this works only when the document as been loaded
        IOleServiceProvider sp = webBrowser.Document as IOleServiceProvider;
        if (sp != null)
        {
            Guid IID_IWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046");
            Guid IID_IWebBrowser2 = new Guid("D30C1661-CDAF-11d0-8A3E-00C04FC9E26E");
            const int OLECMDID_PRINT = 6;
            const int OLECMDEXECOPT_DONTPROMPTUSER = 2;

            dynamic wb; // will be of IWebBrowser2 type, but dynamic is cool
            sp.QueryService(IID_IWebBrowserApp, IID_IWebBrowser2, out wb);
            if (wb != null)
            {
                // note: this will send to the default printer, if any
                wb.ExecWB(OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER, null, null);
            }
        }
    }

    [ComImport, Guid("6D5140C1-7436-11CE-8034-00AA006009FA"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    private interface IOleServiceProvider
    {
        [PreserveSig]
        int QueryService([MarshalAs(UnmanagedType.LPStruct)] Guid guidService, [MarshalAs(UnmanagedType.LPStruct)]  Guid riid, [MarshalAs(UnmanagedType.IDispatch)] out object ppvObject);
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何使用C#静默打印.docx

来自分类Dev

如何在WPF C#中静默安装外部NSIS exe

来自分类Dev

如何在WPF C#中静默安装外部NSIS exe

来自分类Dev

在WPF应用程序中以编程方式C#打印pdf文件

来自分类Dev

打印保存在 C# 中的文件

来自分类Dev

使用C#打印文件Excel

来自分类Dev

使用C#打印文件Excel

来自分类Dev

在 c# wpf 中读取 xml 文件

来自分类Dev

如何在横向(WPF,C#)中打印流文档?

来自分类Dev

使用 C# 在 HTML 文件中搜索值的最佳方法

来自分类Dev

使用JavaScript在MVC 4和C#中的部分视图中使用HTML打印div

来自分类Dev

使用C#在Windows Server 2012 R2中打印PCL文件

来自分类Dev

使用 C# 静默卸载 InstallShield Installscript MSI 程序

来自分类Dev

打印Excel文件C#

来自分类Dev

如何打印文件C#

来自分类Dev

如何使用C#打印文本文件

来自分类Dev

使用html [开始]在php文件中打印值

来自分类Dev

使用xtable在R markdown文件中打印html表

来自分类Dev

如何使用python在HTML文件中打印嵌套列表?

来自分类Dev

使用VBA打印HTML文件

来自分类Dev

在WPF C#中复制和重命名文件

来自分类Dev

从资源中添加.wav文件(WPF C#)

来自分类Dev

从资源中添加.wav文件(WPF C#)

来自分类Dev

在WPF中使用C#下载非定向文件

来自分类Dev

使用C / C ++在Windows中打印HTML文档?

来自分类Dev

在C#中打印Excel(使用Spreadsheetgear生成)

来自分类Dev

使用单个过程在C#中打印多个gridview

来自分类Dev

如何使用 C# 在 WPF 中的 Canvas 中拖放图像

来自分类Dev

C# WPF 超链接 Mailto:使用绑定时不会打印正文