C#利用word(模板)标签功能打印和form自带的打印功能
利用word标签功能打印实现
public void DocumentPrint(Request request) { Microsoft.Office.Interop.Word.Application app = null; Microsoft.Office.Interop.Word.Document doc = null; object missing = System.Reflection.Missing.Value; object templateFile = @"D:\Downloads\试卷命题印刷流程单.doc"; try { app = new Microsoft.Office.Interop.Word.ApplicationClass(); doc = app.Documents.Add(ref templateFile, ref missing, ref missing, ref missing); try { #region 替换书签 object markName = "书签名"; Microsoft.Office.Interop.Word.Bookmark bm = doc.Bookmarks.get_Item(ref markName); . . . #endregion } catch { } //打印 app.Visible = false; //doc.PrintPreview();//要预览必须先把app.Visible设置成true doc.PrintOut(ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); } catch (Exception exp) { throw new Exception(exp.Message); } //销毁word进程 finally { object saveChange = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges; if (doc != null) doc.Close(ref saveChange, ref missing, ref missing); if (app != null) app.Quit(ref missing, ref missing, ref missing); } }
利用form自带的打印功能
public void DocumentPrint(PrintDocument docToPrint) { //打印开始前 docToPrint.BeginPrint += new PrintEventHandler(docToPrint_BeginPrint); //打印输出(过程) docToPrint.PrintPage += new PrintPageEventHandler(docToPrint_PrintPage); //打印结束 docToPrint.EndPrint += new PrintEventHandler(docToPrint_EndPrint);
PrintDocument docToPrint = new PrintDocument(); PrintDialog pd = new PrintDialog(); //string filepath = @"D:\Downloads\试卷命题印刷流程单.doc"; //fs = new FileStream(filepath, FileMode.Open, FileAccess.Read); pd.Document = docToPrint; if (DialogResult.OK == pd.ShowDialog()) //如果确认,将会覆盖所有的打印参数设置 { //页面设置对话框(可以不使用,其实PrintDialog对话框已提供页面设置) PageSetupDialog psd = new PageSetupDialog(); psd.Document = docToPrint; if (DialogResult.OK == psd.ShowDialog()) { //打印预览 PrintPreviewDialog ppd = new PrintPreviewDialog(); ppd.Document = docToPrint; if (DialogResult.OK == ppd.ShowDialog()) docToPrint.Print(); //打印 } } } private void docToPrint_BeginPrint(object sender, PrintEventArgs e) { //也可以把一些打印的参数放在此处设置 } private void docToPrint_PrintPage(object sender, PrintPageEventArgs e) { //打印啥东东就在这写了 Graphics g = e.Graphics; Brush b = new SolidBrush(Color.Black); Font titleFont = new Font("宋体", 16); string title ="";//这里是打印内容 g.DrawString(title, titleFont, b, new PointF((e.PageBounds.Width - g.MeasureString(title, titleFont).Width) / 2, 20)); //e.Cancel//获取或设置是否取消打印 //e.HasMorePages //为true时,该函数执行完毕后还会重新执行一遍(可用于动态分页) } private void docToPrint_EndPrint(object sender, PrintEventArgs e) { //打印结束后相关操作 }
两种方法都不是特别完美。第一种可以打印图片,打印文件,功能比较强大,但是如果想要模板的话很麻烦
第二种利用了word标签功能,这种方法用模板很方便,仅仅是简单打印。稍微复杂点就略显疲惫了