关于PDF打印的问题,前面有篇文章(Winform 打印PDF顺序混乱,获取打印队列)也叙述过,今天来谈谈另外一种方法。
其实方法很简单,因为需要把多个PDF文档按顺序连续打印,为此我们把要打印的pdf文档按顺序合并成一个PDF打印,如此就简单多了。
这里文章写出来并不是为了炫耀什么,只是觉得发现些好东西就分享出来而已,同时也做个记录,方便以后查找。
开始正文
1、为了方便,打印方法就不另寻他路了,和前面一致,具体如下:
Process proc = new Process();
proc.StartInfo.CreateNoWindow = false;
proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.FileName = itemPath;//打印文件路径(本地完整路径包括文件名和后缀名)
proc.StartInfo.Verb = "print";
proc.Start();
proc.Close();
2、就是重点了,合并PDF文档,方法很简单,网上一搜一大把,因为我的需求需要把jpg图片和pdf一起打印,因此合并方法中包含图片。
使用此方法需要第三方控件iTextSharp.dll(点击这里下载)。
/// <summary>/// 把多个PDF文件和JPG/PNG图合并成一个PDF文档/// </summary>/// <param name="fileList">需要合并文件的完整路径列表</param>/// <param name="outMergeFile">输出文件完整路径</param>public static void MergePDFFile(List<string> fileList, string outMergeFile){PdfReader reader;Document document = new Document();PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create));document.Open();PdfContentByte cb = writer.DirectContent;PdfImportedPage newPage;foreach (var itemFile in fileList){if (!File.Exists(itemFile)){string fileName = Path.GetFileName(itemFile);LogMessageWrite.WriteMessage(string.Format("文件打印合并__{0} 文件不存在", fileName));continue;}FileInfo fInfo = new FileInfo(itemFile);if (fInfo.Length < 1){string fileName = Path.GetFileName(itemFile);LogMessageWrite.WriteMessage(string.Format("文件打印合并__文件内容为空,无法打印,{0}", fileName));return;}var ext = Path.GetExtension(itemFile).ToLower();if (".pdf".Equals(ext)){reader = new PdfReader(itemFile);int iPageNum = reader.NumberOfPages;for (int j = 1; j <= iPageNum; j++){document.NewPage();newPage = writer.GetImportedPage(reader, j);cb.AddTemplate(newPage, 0, 0);}}else if (".jpg".Equals(ext) || ".jpge".Equals(ext) || ".png".Equals(ext)){FileStream rf = new FileStream(itemFile, FileMode.Open, FileAccess.Read);int size = (int)rf.Length;byte[] imext = new byte[size];rf.Read(imext, 0, size);rf.Close();Image img = Image.GetInstance(imext);//调整图片大小,使之适合A4var imgHeight = img.Height;var imgWidth = img.Width;if (img.Height > iTextSharp.text.PageSize.A4.Height){imgHeight = iTextSharp.text.PageSize.A4.Height;}if (img.Width > iTextSharp.text.PageSize.A4.Width){imgWidth = iTextSharp.text.PageSize.A4.Width;}img.ScaleToFit(imgWidth, imgHeight);//调整图片位置,使之居中img.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE;document.NewPage();document.Add(img);}}document.Close();}
3、打印合并后的文件:
try{var mergeFilePath = string.Format("{0}mergepdf.pdf", tempDownDir);PDFPrintHelper.MergePDFFile(pdfList, mergeFilePath);Process proc = new Process();proc.StartInfo.CreateNoWindow = false;proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;proc.StartInfo.UseShellExecute = true;proc.StartInfo.FileName = mergeFilePath;//打印文件路径(本地完整路径包括文件名和后缀名)proc.StartInfo.Verb = "print";proc.Start();proc.Close();}catch (Exception ex){LogMessageWrite.WriteMessage(ex.Message);}
至此,大功告成。