C# 打印文档(word文档)

我测试了几种打印文档的方案,第一个方案测试过程中发现打印的都是乱码,后来我发现,word文档好像不能以流的方式读取,这个还有待研究。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Office.Interop.Word;
using Spire.Doc;

namespace PrintTestPro
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private System.Drawing.Font printFont;
        private StreamReader streamToPrint;
        private void button1_Click(object sender, EventArgs e)
        {
            //这种方式打印,打印不了word文件,我不确定word能不能以流的方式读取
            try
            {
                //streamToPrint = new StreamReader("D:\\Git\\wordTemplateTest\\wordTemplateTest\\Template\\myfile.doc", Encoding.Default);
                streamToPrint = new StreamReader("E:\\MyFile.txt", Encoding.Default);
                try
                {
                    printFont = new System.Drawing.Font("Arial", 10);
                    PrintDocument pd = new PrintDocument();
                    pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
                    跳出打印对话框,提供打印参数可视化设置,如选择哪个打印机打印此文档等
                    //PrintDialog pdg = new PrintDialog();
                    //pdg.Document = pd;
                    //if (DialogResult.OK == pdg.ShowDialog()) //如果确认,将会覆盖所有的打印参数设置
                    //{
                    //    //打印预览
                    //    PrintPreviewDialog ppd = new PrintPreviewDialog();
                    //    ppd.Document = pd;
                    //    if (DialogResult.OK == ppd.ShowDialog())
                    //    {
                    //        pd.Print(); //打印
                    //    }
                    //}
                    pd.Print(); //打印
                }
                finally
                {
                    streamToPrint.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        // The PrintPage event is raised for each page to be printed.
        private void pd_PrintPage(object sender, PrintPageEventArgs ev)
        {
            float linesPerPage = 0;
            float yPos = 0;
            int count = 0;
            float leftMargin = ev.MarginBounds.Left;
            float topMargin = ev.MarginBounds.Top;
            string line = null;

            // Calculate the number of lines per page.
            linesPerPage = ev.MarginBounds.Height /
               printFont.GetHeight(ev.Graphics);

            // Print each line of the file.
            while (count < linesPerPage &&((line = streamToPrint.ReadLine()) != null))
            {
                //Console.WriteLine(line);
                yPos = topMargin + (count *
                   printFont.GetHeight(ev.Graphics));
                ev.Graphics.DrawString(line, printFont, Brushes.Black,
                   leftMargin, yPos, new StringFormat());
                count++;
            }

            // If more lines exist, print another page.
            if (line != null)
                ev.HasMorePages = true;
            else
                ev.HasMorePages = false;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            wordOperate();
            
        }
        public static void wordOperate()
        {
            Object oMissing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document wordDoc = new Microsoft.Office.Interop.Word.Document();
            try
            {
                //Set no alerts as printing in background.
                wordApp.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;
                //Set the printer.默认打印机
                //wordApp.ActivePrinter = printerName;

                wordDoc = wordApp.Documents.Open("D:\\Git\\wordTemplateTest\\wordTemplateTest\\Template\\myfile.doc");
                wordDoc.Activate();

                //设置打印纸张
                wordDoc.PageSetup.PaperSize = WdPaperSize.wdPaperA5;
                //wordDoc.PageSetup.PaperSize = WdPaperSize.wdPaperA4;
                wordDoc.PrintOut(); //打印
            }
            catch (Exception ex)
            {

            }
            finally
            {
                wordDoc.Close(SaveChanges: false);
                wordApp.Application.Quit();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //第三方库封装的word操作库
            // 创建一个Documnet类对象
            Spire.Doc.Document doc = new Spire.Doc.Document();
            // 加载需要打印的Word文档
            doc.LoadFromFile(@"D:\\Git\\wordTemplateTest\\wordTemplateTest\\Template\\myfile.doc");
            // 实例化System.Windows.Forms.PrintDialog对象
            PrintDialog dialog = new PrintDialog();
            dialog.AllowPrintToFile = true;
            dialog.AllowCurrentPage = true;
            dialog.AllowSomePages = true;
            dialog.UseEXDialog = true;
            // 关联doc.PrintDialog属性和PrintDialog对象 
            doc.PrintDialog = dialog;
            // 后台打印
             PrintDocument printDoc = doc.PrintDocument;        
            // printDoc.Print();
            // 显示打印对话框并打印
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                printDoc.Print();
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //这种方式也可以实现打印word文档
            using (PrintDialog pd = new PrintDialog())
            {
                pd.ShowDialog();

                ProcessStartInfo info = new ProcessStartInfo("D:\\闸机人证核查系统客户端使用说明 - V1.0.doc");

                info.Verb = "PrintTo";
                info.Arguments = pd.PrinterSettings.PrinterName;
                info.UseShellExecute = true;

                info.CreateNoWindow = false;

                info.WindowStyle = ProcessWindowStyle.Hidden;

                Process.Start(info);
            }
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值