spring.net框架开发合并PDF文件程序,请大家多提宝贵意见
2009-09-02 17:59
495 查看
合并PDF文件的接口:
实现类二:支持多量的PDF文件(不限)
执行合并代理类:
using System;using System.Collections.Generic;using System.IO;using iTextSharp.text;using iTextSharp.text.pdf;using Spring.Objects.Factory.Attributes;using System.ComponentModel;using System.Windows.Forms;using System.Collections;namespace BLL{ /// <summary> /// 支持多文件(PDF)合并 /// </summary> public class PdfMerger : IPdfMerger { public string pdfCreatDir { get; set; } public PictureBox pb { get; set; } public Label Lb { get; set; } private IPdfPageEvent _pdfPageEvent; private string currentfileName=string.Empty; [Required] public IPdfPageEvent PdfPageEvent { get { return _pdfPageEvent; } set { _pdfPageEvent = value; } } /// <summary> /// Merge pdf files. /// </summary> /// <param name="sourceFiles">PDF files being merged.</param> /// <returns></returns> public byte[] GetByteFiles(List<byte[]> sourceFiles) { Document document = new Document(); MemoryStream output = new MemoryStream(); try { try { // Initialize pdf writer PdfWriter writer = PdfWriter.GetInstance(document, output); writer.PageEvent = this.PdfPageEvent; // Open document to write document.Open(); PdfContentByte content = writer.DirectContent; // Iterate through all pdf documents for (int fileCounter = 0; fileCounter < sourceFiles.Count; fileCounter++) { // Create pdf reader PdfReader reader = new PdfReader(sourceFiles[fileCounter]); int numberOfPages = reader.NumberOfPages; // Iterate through all pages for (int currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++) { // Determine page size for the current page document.SetPageSize(reader.GetPageSizeWithRotation(currentPageIndex)); // Create page document.NewPage(); PdfImportedPage importedPage = writer.GetImportedPage(reader, currentPageIndex); // Determine page orientation int pageOrientation = reader.GetPageRotation(currentPageIndex); if ((pageOrientation == 90) || (pageOrientation == 270)) { content.AddTemplate(importedPage, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(currentPageIndex).Height); } else { content.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0); } } } } catch (Exception exception) { throw new Exception("There has an unexpected exception occured during the pdf merging process.", exception); } } finally { document.Close(); } return output.GetBuffer(); } /// <summary> /// 递归执行文件 /// </summary> /// <param name="path"></param> public void MergeFiles(object sender) { string path = sender.ToString(); DirectoryInfo[] ChildDirectory; DirectoryInfo FatherDirectory = new DirectoryInfo(path); ChildDirectory = FatherDirectory.GetDirectories("*.*"); //FileInfo[] NewFileInfo= FatherDirectory.GetFiles("*.pdf"); //FileInfo[] NewFileInfo2 = FatherDirectory.GetFiles("*.*"); string[] NewFileInfo3 = Directory.GetFiles(FatherDirectory.FullName,"*.pdf"); string[] NewFileInfo4 = Directory.GetFiles(FatherDirectory.FullName, "*.*",SearchOption.TopDirectoryOnly); // 排序 Array.Sort(NewFileInfo3, new MyDateSorter()); List<byte[]> filesByte = new List<byte[]>(); // 刪除除pdf以外的文件 foreach (string FI in NewFileInfo4) { if (FI.IndexOf(".pdf")==-1) { File.Delete(FI); } } foreach (string FI in NewFileInfo3) { filesByte.Add(File.ReadAllBytes(FI)); File.WriteAllBytes(FatherDirectory.FullName + "//" + FatherDirectory.Name + ".pdf", GetByteFiles(filesByte)); currentfileName = FI; setLableText(); File.Delete(FI); } foreach (DirectoryInfo dirInfo in ChildDirectory) { MergeFiles(dirInfo.FullName); } } # region 合并PDF public void MergeFilesExe(object sender) { System.ComponentModel.BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += new DoWorkEventHandler(bw_DoWork); bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted); bw.RunWorkerAsync(sender); } # endregion # region 执行后台线程 void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { pb.Visible = false; this.Lb.Text = "PDF文件合并完成!"; } void bw_DoWork(object sender, DoWorkEventArgs e) { setVisible(); MergeFiles(e.Argument.ToString()); } # endregion # region 线程访问控件 delegate void setProgressBarPositionCallBack(System.Windows.Forms.PictureBox refpb); public void setVisiblebyDelegate(System.Windows.Forms.PictureBox refpb) { refpb.Visible = true; } public void setVisible() { setProgressBarPositionCallBack scc = new setProgressBarPositionCallBack(setVisiblebyDelegate); this.pb.Invoke(scc,new object[]{this.pb}); } delegate void setProgressBarPositionCallBackLable(string refLb); public void setVisiblebyDelegateLable(string refLb) { this.Lb.Text = "正在合并" + refLb + "......"; } public void setLableText() { setProgressBarPositionCallBackLable scc = new setProgressBarPositionCallBackLable(setVisiblebyDelegateLable); this.Lb.Invoke(scc, new object[] { currentfileName }); } # endregion } /// <summary> /// 文件排序 /// </summary> public class MyDateSorter : IComparer { #region IComparer Members public int Compare(object x, object y) { if (x == null && y == null) { return 0; } if (x == null) { return -1; } if (y == null) { return 1; } string xInfo = (string)x; string yInfo = (string)y; //依名稱排序 //return xInfo.Name.CompareTo(yInfo.Name);//遞增 int index = xInfo.IndexOf("-"); string strXInfo = ""; string strYInfo = ""; // 期刊数据 if (index == -1) { strXInfo = xInfo.Replace(".pdf",""); strYInfo = yInfo.Replace(".pdf", ""); } // 中文会议 else { strXInfo = xInfo.Substring(index + 1).Replace(".pdf", ""); strYInfo = yInfo.Substring(index + 1).Replace(".pdf", ""); } strXInfo = strXInfo.Replace("//","|"); string[] temp = strXInfo.Split('|'); strXInfo = temp[temp.Length - 1].ToString(); temp = null; strYInfo = strYInfo.Replace("//", "|"); temp = strYInfo.Split('|'); strYInfo = temp[temp.Length - 1].ToString(); if (int.Parse(strXInfo) > int.Parse(strYInfo)) { return 1; } else if (int.Parse(strXInfo) < int.Parse(strYInfo)) { return -1; } else { return 0; } //return yInfo.FullName.CompareTo(xInfo.FullName);//遞減 //依修改日期排序 //return xInfo.LastWriteTime.CompareTo(yInfo.LastWriteTime);//遞增 //return yInfo.LastWriteTime.CompareTo(xInfo.LastWriteTime);//遞減 } #endregion }}
实现类二:支持多量的PDF文件(不限)
using System;using System.Collections.Generic;using System.Linq;using System.Text;using iTextSharp.text;using iTextSharp.text.pdf;namespace BLL{ /// <summary> /// Implements custom page events. /// </summary> internal class PdfPageEvents : IPdfPageEvent { #region members private BaseFont _baseFont = null; private PdfContentByte _content; #endregion #region IPdfPageEvent Members public void OnOpenDocument(PdfWriter writer, Document document) { _baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); _content = writer.DirectContent; } public void OnStartPage(PdfWriter writer, Document document) { } public void OnEndPage(PdfWriter writer, Document document) { //// Write header text //string headerText = "PDF Merger by Smart-Soft"; //_content.BeginText(); //_content.SetFontAndSize(_baseFont, 8); //_content.SetTextMatrix(GetCenterTextPosition(headerText, writer), writer.PageSize.Height - 10); //_content.ShowText(headerText); //_content.EndText(); //// Write footer text (page numbers) //string text = "Page " + writer.PageNumber; //_content.BeginText(); //_content.SetFontAndSize(_baseFont, 8); //_content.SetTextMatrix(GetCenterTextPosition(text, writer), 10); //_content.ShowText(text); //_content.EndText(); } public void OnCloseDocument(PdfWriter writer, Document document) { } public void OnParagraph(PdfWriter writer, Document document, float paragraphPosition) { } public void OnParagraphEnd(PdfWriter writer, Document document, float paragraphPosition) { } public void OnChapter(PdfWriter writer, Document document, float paragraphPosition, Paragraph title) { } public void OnChapterEnd(PdfWriter writer, Document document, float paragraphPosition) { } public void OnSection(PdfWriter writer, Document document, float paragraphPosition, int depth, Paragraph title) { } public void OnSectionEnd(PdfWriter writer, Document document, float paragraphPosition) { } public void OnGenericTag(PdfWriter writer, Document document, Rectangle rect, string text) { } #endregion private float GetCenterTextPosition(string text, PdfWriter writer) { return writer.PageSize.Width / 2 - _baseFont.GetWidthPoint(text, 8) / 2; } }}
执行合并代理类:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using BLL;using Spring.Context;using Spring.Context.Support;using Spring.Objects.Factory.Config;using Spring.Objects.Factory.Support;using Spring.Objects.Factory.Xml;namespace PDF_Merger{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } /// <summary> /// 合併PDF文件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnMerge_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBox1.Text)) { MessageBox.Show("請指定文件目錄!"); return; } IApplicationContext ctx = ContextRegistry.GetContext(); ProxyPdfMerger Merger = (ProxyPdfMerger)ctx.GetObject("ProxyPdfMer"); Merger.MergeFiles(this.textBox1.Text,"",ref this.pbLoading,ref this.label3); } /// <summary> /// 選擇文件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnChooseFolder_Click(object sender, EventArgs e) { folderBrowserDialog1 = new FolderBrowserDialog(); if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) { textBox1.Text = folderBrowserDialog1.SelectedPath; } } }}
<?xml version="1.0" encoding="utf-8" ?><configuration> <configSections> <sectionGroup name="spring"> <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/> <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" /> </sectionGroup> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" /> <sectionGroup name="common"> <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" /> </sectionGroup> </configSections> <common> <logging> <factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4Net"> <!-- choices are INLINE, FILE, FILE-WATCH, EXTERNAL--> <!-- otherwise BasicConfigurer.Configure is used --> <!-- log4net configuration file is specified with key configFile--> <arg key="configType" value="INLINE" /> </factoryAdapter> </logging> </common> <spring> <context> <resource uri="config://spring/objects"/> </context> <!--`合并PDF文件代理--> <objects xmlns="http://www.springframework.net" > <object id="ProxyPdfMer" type="BLL.ProxyPdfMerger,BLL"> <property name="PdfMerger" ref="PdfMergerB"/> </object> <!-- 不支持多PDF文件合并--> <object name="PdfMergerA" type="BLL.PdfMerger2,BLL"> <property name="PdfPageEvent" ref="PdfPageEventA"/> </object> <!-- 支持多PDF文件合并--> <object name="PdfMergerB" type="BLL.PdfMerger,BLL"> <property name="PdfPageEvent" ref="PdfPageEventA"/> </object> <object name="PdfPageEventA" type="BLL.PdfPageEvents,BLL"> </object> </objects> </spring> <log4net> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> <file value="log-file.txt" /> <appendToFile value="true" /> <encoding value="unicode" /> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" /> </layout> </appender> <!-- Set default logging level to DEBUG --> <root> <level value="DEBUG" /> <appender-ref ref="ConsoleAppender" /> </root> <logger name="MySpringNet1.EatForDinner"> <level value="DEBUG" /> </logger> <!-- Set logging for Spring to INFO. Logger names in Spring correspond to the namespace --> <logger name="Spring"> <level value="INFO" /> </logger> </log4net> </configuration>
相关文章推荐
- 《iOS开发指南》图灵出版开始预售了-源码-样章-目录,欢迎大家提出宝贵意见
- Js和css文件动态合并------用Node.js开发的一个前端优化小程序
- 欢迎大家试用我开发的RSS浏览器并多提宝贵意见!
- DISCUZ!X1程序目录、文件列表及模板文件结构说明,帮助大家二级开发
- 工作所需,开发了一款 “二进制文件合并工具 V1.0” 共享给大家
- 合并小文件——一个算法在实际程序开发中应用的例子
- 使用web程序导出Excel,PDF和CSV三种文件
- 在项目中用程序中嵌入mdf文件的方式来进行SQLServer数据库开发
- Discuz!X论坛开发(八)二次开发 教你识别程序目录和文件列表for discuzx!1--NO.7
- iOS开发:第一个iOS程序分析——AppDelegate.h文件和视图View、视图控制器ViewController
- C#将制定文件夹下的PDF文件合并成一个并输出至指定路径
- C#将制定文件夹下的PDF文件合并成一个并输出至指定路径
- 编写一个程序,将a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt文件中,a.txt文件中的单词用回车符分隔,b.txt文件中用回车或空格进行分隔
- ubuntu下整合eclipse和javah生成jni头文件开发android的native程序
- PE可执行文件的镶入式程序后门开发
- 在64位环境下开发程序时常遇到的一个错误:无法加载文件或程序集
- 拆除vs发展c++程序开发过程中产生的.ipch和.sdf文件的方法
- 最新CC++函数与算法速查大辞典 中国铁道出版社 上线了请大家关注,多提宝贵意见
- Qt开发:生成pdf文件
- java程序开发,随机人员分组功能,感觉还不错,分享给大家