在前段时间做了一下打印,因为需要支持的格式比较多,所以wpf能打印的有限分享一下几种格式的打印(.xls .xlsx .doc .docx .png .jpg .bmp .pdf)

首先为了保证excel和word的格式问题,excel和word是调用的office进行打印的。

获取所有打印机的方法:

LocalPrintServer print = new LocalPrintServer();var printers = print.GetPrintQueues();foreach (var item in printers){//打印机名称  item.Name;}

Excel打印。三个参数 :1.打印机名称  2要打印的文件路径+名称   3要打印的sheet页名称(可以不写就打印全部sheet)

static Excel.Application Application { get; set; }public static void PrintExcel(string printName, string fileName, List<string> sheetNames = null){if (Application == null)Application = new Excel.Application();Application.Visible = false;//Application.Calculation = Excel.XlCalculation.xlCalculationManual;var book = Application.Workbooks.Open(fileName);if (sheetNames == null){sheetNames = new List<string>();Excel.Sheets sheets = book.Sheets;for (int i = 1; i <= sheets.Count; i++){Excel.Worksheet workSheet = sheets.Item[i];if (workSheet.Visible != Excel.XlSheetVisibility.xlSheetHidden)sheetNames.Add(workSheet.Name);}}foreach (var item in sheetNames){Excel.Worksheet workSheet = (Excel.Worksheet)book.Worksheets[item];//------------------------打印页面相关设置--------------------------------workSheet.PageSetup.PaperSize = Excel.XlPaperSize.xlPaperA4;//纸张大小//workSheet.PageSetup.Orientation = Excel.XlPageOrientation.xlLandscape;//页面横向workSheet.PageSetup.Zoom = 75; //打印时页面设置,缩放比例百分之几workSheet.PageSetup.Zoom = false; //打印时页面设置,必须设置为false,页高,页宽才有效workSheet.PageSetup.FitToPagesWide = 1; //设置页面缩放的页宽为1页宽workSheet.PageSetup.FitToPagesTall = false; //设置页面缩放的页高自动//workSheet.PageSetup.LeftHeader = "Nigel";//页面左上边的标志//workSheet.PageSetup.CenterFooter = "第 &P 页,共 &N 页";//页面下标workSheet.PageSetup.FirstPageNumber = (int)Excel.Constants.xlAutomatic;workSheet.PageSetup.Order = Excel.XlOrder.xlDownThenOver;workSheet.PageSetup.PrintGridlines = true; //打印单元格网线workSheet.PageSetup.TopMargin = 1.5 / 0.035; //上边距为2cm(转换为in)workSheet.PageSetup.BottomMargin = 1.5 / 0.035; //下边距为1.5cmworkSheet.PageSetup.LeftMargin = 2 / 0.035; //左边距为2cmworkSheet.PageSetup.RightMargin = 2 / 0.035; //右边距为2cmworkSheet.PageSetup.CenterHorizontally = true; //文字水平居中//------------------------打印页面设置结束--------------------------------
                workSheet.PrintOutEx(Missing.Value, Missing.Value, Missing.Value, Missing.Value, printName);}//book.PrintOutEx(Missing.Value, Missing.Value, Missing.Value, Missing.Value, printName); //直接打印book.Close(false); //关闭工作空间
            }

excel有时候关不干净,贡献一个强制关闭的方法,可以在excel操作完成后调用:

[DllImport("User32.dll")]public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int Processid);public static void ExcelClose(){if (Application != null){Application.Quit();int iId = 0;IntPtr intptr = new IntPtr(Application.Hwnd);System.Diagnostics.Process p = null;try{GetWindowThreadProcessId(intptr, out iId);p = System.Diagnostics.Process.GetProcessById(iId);if (p != null){p.Kill();p.Dispose();}Application = null;}catch (Exception e){throw e;}}System.GC.Collect();}

Word打印(打印机名称,要打印的文件路径+名称)

public static void PrintWord(string printName, string fileName){Word.Application appword = new Word.Application();appword.Visible = false;appword.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;Word.Document doc = appword.Documents.Open(fileName);appword.ActivePrinter = printName;doc.PrintOut(true);doc.Close(false);appword.Quit();}

图片打印WPF(支持格式 png jpg bmp)

public static string PrintImage(string printName, string fileName){System.Windows.Controls.PrintDialog dialog = new System.Windows.Controls.PrintDialog();//开始打印var printers = new LocalPrintServer().GetPrintQueues();var selectedPrinter = printers.FirstOrDefault(d => d.Name == printName);if (selectedPrinter == null){return "没有找到打印机";}dialog.PrintQueue = selectedPrinter;dialog.PrintDocument(new TestDocumentPaginator(new BitmapImage(new Uri(fileName))), "Image");return "";}

public class TestDocumentPaginator : DocumentPaginator{#region 字段private Size _pageSize;private ImageSource image;#endregion#region 构造public TestDocumentPaginator(BitmapImage img){image = img;//我们使用A3纸张大小var pageMediaSize = LocalPrintServer.GetDefaultPrintQueue().GetPrintCapabilities().PageMediaSizeCapability.FirstOrDefault(x => x.PageMediaSizeName == PageMediaSizeName.ISOA4);if (pageMediaSize != null){_pageSize = new Size((double)pageMediaSize.Width, (double)pageMediaSize.Height);}}#endregion#region 重写/// <summary>/// /// </summary>/// <param name="pageNumber">打印页是从0开始的</param>/// <returns></returns>public override DocumentPage GetPage(int pageNumber){var visual = new DrawingVisual();using (DrawingContext dc = visual.RenderOpen()){double imgWidth = 0;double imgHeight = 0;if (image.Height > _pageSize.Height){double h = _pageSize.Height / image.Height;imgWidth = image.Width * h;imgHeight = image.Height * h;}if (image.Width > _pageSize.Width){double w = _pageSize.Width / image.Width;imgWidth = image.Width * w;imgHeight = image.Height * w;}if (image.Width < _pageSize.Width && image.Height < _pageSize.Height){double h = _pageSize.Height / image.Height;double w = _pageSize.Width / image.Width;if (h > w){imgWidth = image.Width * w;imgHeight = image.Height * w;}else{imgWidth = image.Width * h;imgHeight = image.Height * h;}}double left = Math.Abs((_pageSize.Width - imgWidth) <= 0 ? 2 : (_pageSize.Width - imgWidth)) / 2;double top = Math.Abs((_pageSize.Height - imgHeight) <= 0 ? 2 : (_pageSize.Height - imgHeight)) / 2;dc.DrawImage(image, new Rect(left, top, imgWidth, imgHeight));}return new DocumentPage(visual, _pageSize, new Rect(_pageSize), new Rect(_pageSize));}public override bool IsPageCountValid{get{return true;}}public override Size PageSize{get{return _pageSize;}set{_pageSize = value;}}public override IDocumentPaginatorSource Source{get{return null;}}public override int PageCount{get{return 1;}}#endregion}

TestDocumentPaginator内部的重写方法是计算将图片全部居中显示。关于图片打印多说一句:在之前我是使用image加载图片,然后通过PrintVisual打印控件的方式打印的,但是这种方式我发现在win7机器上打印出来的是空白纸张,还没明白是为什么,所以就用这种方式了。

PDF打印(这是调用windows api去打印,不需要乱起八糟的第三方):
// Structure and API declarions:[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]public class DOCINFOA{[MarshalAs(UnmanagedType.LPStr)]public string pDocName;[MarshalAs(UnmanagedType.LPStr)]public string pOutputFile;[MarshalAs(UnmanagedType.LPStr)]public string pDataType;}[DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);[DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]public static extern bool ClosePrinter(IntPtr hPrinter);[DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);[DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]public static extern bool EndDocPrinter(IntPtr hPrinter);[DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]public static extern bool StartPagePrinter(IntPtr hPrinter);[DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]public static extern bool EndPagePrinter(IntPtr hPrinter);[DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);// SendBytesToPrinter()// When the function is given a printer name and an unmanaged array// of bytes, the function sends those bytes to the print queue.// Returns true on success, false on failure.public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount){Int32 dwError = 0, dwWritten = 0;IntPtr hPrinter = new IntPtr(0);DOCINFOA di = new DOCINFOA();bool bSuccess = false; // Assume failure unless you specifically succeed.
di.pDocName = "My C#.NET RAW Document";di.pDataType = "RAW";// Open the printer.if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero)){// Start a document.if (StartDocPrinter(hPrinter, 1, di)){// Start a page.if (StartPagePrinter(hPrinter)){// Write your bytes.bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);EndPagePrinter(hPrinter);}EndDocPrinter(hPrinter);}ClosePrinter(hPrinter);}// If you did not succeed, GetLastError may give more information// about why not.if (bSuccess == false){dwError = Marshal.GetLastWin32Error();}return bSuccess;}public static bool SendFileToPrinter(string szPrinterName, string szFileName){// Open the file.FileStream fs = new FileStream(szFileName, FileMode.Open);// Create a BinaryReader on the file.BinaryReader br = new BinaryReader(fs);// Dim an array of bytes big enough to hold the file's contents.Byte[] bytes = new Byte[fs.Length];bool bSuccess = false;// Your unmanaged pointer.IntPtr pUnmanagedBytes = new IntPtr(0);int nLength;nLength = Convert.ToInt32(fs.Length);// Read the contents of the file into the array.bytes = br.ReadBytes(nLength);// Allocate some unmanaged memory for those bytes.pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);// Copy the managed byte array into the unmanaged array.Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);// Send the unmanaged bytes to the printer.bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);// Free the unmanaged memory that you allocated earlier.
            Marshal.FreeCoTaskMem(pUnmanagedBytes);return bSuccess;}public static bool SendStringToPrinter(string szPrinterName, string szString){IntPtr pBytes;Int32 dwCount;// How many characters are in the string?dwCount = szString.Length;// Assume that the printer is expecting ANSI text, and then convert// the string to ANSI text.pBytes = Marshal.StringToCoTaskMemAnsi(szString);// Send the converted ANSI string to the printer.
            SendBytesToPrinter(szPrinterName, pBytes, dwCount);Marshal.FreeCoTaskMem(pBytes);return true;}
public static void PrintPDF(string printName, string fileName){SendFileToPrinter(printName, fileName);}

以上就是wpf常用的打印,目前看起来格式还是可以达到要求的,更多技术讨论请关注页面下方的qq群。

转载于:https://www.cnblogs.com/BeiJing-Net-DaiDai/p/10243072.html

WPF实战案例-打印相关推荐

  1. linux运维脚本编写,最强Linux自动化运维 Shell高级脚本编程实战 带习题+项目实战案例+全套配置脚本...

    最强Linux自动化运维 Shell高级脚本编程实战 带习题+项目实战案例+全套配置脚本 大家可以通过参考下面的课程学习目录,就会发现单单只从目录上来分析就知道这是一部非常系统的Shell自动化脚本运 ...

  2. 基于微博评论的文本情感分析与关键词提取的实战案例~

    点击上方"Python爬虫与数据挖掘",进行关注 回复"书籍"即可获赠Python从入门到进阶共10本电子书 今 日 鸡 汤 宣室求贤访逐臣,贾生才调更无伦. ...

  3. Salesforce学习之路-developer篇(五)一文读懂Aura原理及实战案例分析

    很喜欢曾经看到的一句话:以输出倒逼输入.以输出的形式强制自己学习,确实是高效的学习方式,真的很棒.以下仅为个人学习理解,如有错误,欢迎指出,共同学习. 1. 什么是Lightning Componen ...

  4. Python爬虫---爬虫介绍,实战案例

    目录标题 1.爬虫介绍 1.1 爬虫的合法性 1.2 网络爬虫的尺寸 1.3 robots.txt协议 1.4 http&https协议 1.5 requests模块 1.5.1 reques ...

  5. 基础爬虫实战案例之获取游戏商品数据

    文章目录 前言 一.爬虫是什么? 二.爬虫实战案例 1.引入库 2.请求网页处理 3.生成访问链接 4.读入数据到mongodb 5.获得数据 6.加入多线程 总结 前言 在想获取网站的一些数据时,能 ...

  6. SpringBoot 整合WebSocket 简单实战案例

    前言 这个简单实战案例主要目的是让大家了解websocket的一些简单使用. 另外使用stomp方式的: <Springboot 整合 WebSocket ,使用STOMP协议 ,前后端整合实战 ...

  7. 字节青训营Go语言学习第一天--基础语言+实战案例

    文章目录 走进Go语言基础语言 2.2基础语言-变量 2.3基础语法- if else 2.4基础语法-循环 基础语法-switch 基础语法-数组 基础语法-切片 基础语法-map 基础语法-ran ...

  8. TCP实战案例之即时通信、BS架构模拟

    即时通信是什么含义,要实现怎么样的设计? 1.即时通信,是指一个客户端的消息发出去,其他客户端可以接收到 2.之前我们的消息都是发给服务端的 3.即时通信需要进行端口转发的设计思想 4.服务端需要把在 ...

  9. 前端~html~HTML零基础(二) ~HTML常见标签补充/实战案例:个人简历网页展示/填写

    文章目录 回顾复习 超链接标签a(补充) 表格标签 列表标签 表单标签 label标签 select标签 textarea标签 无语义标签 div&& span 实战案例 个人简历网页 ...

最新文章

  1. 2019年的人工智能,那些吹过的牛能实现吗?
  2. 网页右边固定php,左侧固定,右侧自适应的布局方式
  3. IOC注解注入View
  4. hosts文件配置不生效的解决办法
  5. TCP/IP协议详解---概述
  6. asp.net操作Excel总结
  7. linux某个线程信号唤醒,linux多线程编程--信号量和条件变量 唤醒丢失事件
  8. yield表达式形式的应用
  9. 最全免费C语言之苏小红版《高级语言程序设计》第七章188页小学计算机辅助教学系统程序设计
  10. Git使用手册:HTTPS和SSH方式的区别和使用
  11. 普通程序员,如何转型大数据相关方向?
  12. k8s pod里访问不到外部ip_安全公告:影响所有K8s版本的设计缺陷
  13. Java实验4 面向对象基础
  14. [转]HTML DIV+CSS 命名规范大全
  15. Selenium---环境配置
  16. KMP + 求最小循环节 --- HDU 1358 Period
  17. BZOJ1827[USACO 2010 Mar Gold 1.Great Cow Gathering]——树形DP
  18. MAC电脑新手入门指南
  19. 很迷茫,30岁,大专学历,没有一技之长,负债累累,怎么翻身?
  20. JavaScript高级(二)

热门文章

  1. delphi valuelisteditor控件的使用
  2. 曾经我也迷茫,你还在迷茫吗?写给像我一样的在校计算机专业学生作者:Cat_Lee 来源:博客园 发布时间:2009-05-30 20:25 阅读:1104 次 原文链接 [收藏]
  3. BugkuCTF-Misc:这是一张单纯的图片
  4. idea部署web项目,能访问jsp,访问Servlet却出现404错误的解决方法汇总
  5. Java基本数据类型及String类
  6. springboot学习笔记(十)
  7. 从并发视角来看智能合约(上)【渡鸦论文系列】
  8. Go 从入门到精通(三)字符串,时间,流程控制,函数
  9. Android Camera 系统架构源码分析
  10. 一起学设计模式-观察者模式