C#引用第三方库iTextSharp.dll 合并PDF

///
/// 类说明:Assistant
/// 编 码 人:苏飞
/// 联系方式:361983679
/// 更新网站:http://www.cckan.net/thread-655-1-1.html
///
using System;
using System.Collections.Generic;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace Common
{
///
/// PDF文档操作类
///
//------------------------------------调用--------------------------------------------
//PDFOperation pdf = new PDFOperation();
//pdf.Open(new FileStream(path, FileMode.Create));
//pdf.SetBaseFont(@“C:\Windows\Fonts\SIMHEI.TTF”);
//pdf.AddParagraph(“测试文档(生成时间:” + DateTime.Now + “)”, 15, 1, 20, 0, 0);
//pdf.Close();
//-------------------------------------------------------------------------------------
public class PDFOperation
{
#region 构造函数
///
/// 构造函数
///
public PDFOperation()
{
rect = PageSize.A4;
document = new Document(rect);
}

    /// /// 构造函数/// /// 页面大小(如"A4")public PDFOperation(string type){SetPageSize(type);document = new Document(rect);}/// /// 构造函数/// /// 页面大小(如"A4")/// 内容距左边框距离/// 内容距右边框距离/// 内容距上边框距离/// 内容距下边框距离public PDFOperation(string type, float marginLeft, float marginRight, float marginTop, float marginBottom){SetPageSize(type);document = new Document(rect, marginLeft, marginRight, marginTop, marginBottom);}#endregion#region 私有字段private Font font;private Rectangle rect;   //文档大小private Document document;//文档对象private BaseFont basefont;//字体#endregion#region 设置字体/// /// 设置字体/// public void SetBaseFont(string path){basefont = BaseFont.CreateFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);}/// /// 设置字体/// /// 字体大小public void SetFont(float size){font = new Font(basefont, size);}#endregion#region 设置页面大小/// /// 设置页面大小/// /// 页面大小(如"A4")public void SetPageSize(string type){switch (type.Trim()){case "A4":rect = PageSize.A4;break;case "A8":rect = PageSize.A8;break;}}#endregion#region 实例化文档/// /// 实例化文档/// /// 文档相关信息(如路径,打开方式等)public void GetInstance(Stream os){PdfWriter.GetInstance(document, os);}#endregion#region 打开文档对象/// /// 打开文档对象/// /// 文档相关信息(如路径,打开方式等)public void Open(Stream os){GetInstance(os);document.Open();}#endregion#region 关闭打开的文档/// /// 关闭打开的文档/// public void Close(){document.Close();}#endregion#region 添加段落/// /// 添加段落/// /// 内容/// 字体大小public void AddParagraph(string content, float fontsize){SetFont(fontsize);Paragraph pra = new Paragraph(content, font);document.Add(pra);}/// /// 添加段落/// /// 内容/// 字体大小/// 对齐方式(1为居中,0为居左,2为居右)/// 段后空行数(0为默认值)/// 段前空行数(0为默认值)/// 行间距(0为默认值)public void AddParagraph(string content, float fontsize, int Alignment, float SpacingAfter, float SpacingBefore, float MultipliedLeading){SetFont(fontsize);Paragraph pra = new Paragraph(content, font);pra.Alignment = Alignment;if (SpacingAfter != 0){pra.SpacingAfter = SpacingAfter;}if (SpacingBefore != 0){pra.SpacingBefore = SpacingBefore;}if (MultipliedLeading != 0){pra.MultipliedLeading = MultipliedLeading;}document.Add(pra);}#endregion#region 添加图片/// /// 添加图片/// /// 图片路径/// 对齐方式(1为居中,0为居左,2为居右)/// 图片宽(0为默认值,如果宽度大于页宽将按比率缩放)/// 图片高public void AddImage(string path, int Alignment, float newWidth, float newHeight){Image img = Image.GetInstance(path);img.Alignment = Alignment;if (newWidth != 0){img.ScaleAbsolute(newWidth, newHeight);}else{if (img.Width > PageSize.A4.Width){img.ScaleAbsolute(rect.Width, img.Width * img.Height / rect.Height);}}document.Add(img);}#endregion#region 添加链接、点/// /// 添加链接/// /// 链接文字/// 字体大小/// 链接地址public void AddAnchorReference(string Content, float FontSize, string Reference){SetFont(FontSize);Anchor auc = new Anchor(Content, font);auc.Reference = Reference;document.Add(auc);}/// /// 添加链接点/// /// 链接文字/// 字体大小/// 链接点名public void AddAnchorName(string Content, float FontSize, string Name){SetFont(FontSize);Anchor auc = new Anchor(Content, font);auc.Name = Name;document.Add(auc);}/// /// 读取合并的pdf文件名称/// /// 目录/// 导出的路径public static void MergePDF(string Directorypath, string outpath){List filelist2 = new List();DirectoryInfo di2 = new DirectoryInfo(Directorypath);FileInfo[] ff2 = di2.GetFiles("*.pdf");BubbleSort(ff2);foreach (FileInfo temp in ff2){filelist2.Add(Directorypath + "\\" + temp.Name);}mergePDFFiles(filelist2, outpath);//mergePDFFiles2(filelist2, outpath);DeleteAllPdf(Directorypath);}/// /// 冒泡排序/// /// 文件名数组public static void BubbleSort(FileInfo[] arr){for (int i = 0; i < arr.Length; i++){for (int j = i; j < arr.Length; j++){if (arr[i].LastWriteTime > arr[j].LastWriteTime)//按创建时间(升序){FileInfo temp = arr[i];arr[i] = arr[j];arr[j] = temp;}}}}/// /// 合成pdf文件,多个PDF文件合并成一个PDF多页 /// /// pdf文件名集合/// 合并后的输出路径public static void mergePDFFiles(List pdfFileLst, string outMergeFile){PdfReader reader;List readerList = new List();Rectangle rec = new Rectangle(1660, 1000);//尺寸单位磅,一磅等于0.3527毫米Document document = new Document(rec);PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create));document.Open();PdfContentByte cb = writer.DirectContent;PdfImportedPage newPage;for (int i = 0; i < pdfFileLst.Count; i++){reader = new PdfReader(pdfFileLst[i]);int iPageNum = reader.NumberOfPages;for (int j = 1; j <= iPageNum; j++){document.SetPageSize(reader.GetPageSizeWithRotation(j));document.NewPage();newPage = writer.GetImportedPage(reader, j);float pageHeight = reader.GetPageSizeWithRotation(j).Height;float pageWidth = reader.GetPageSizeWithRotation(j).Width;int rotation = reader.GetPageRotation(j);switch (rotation){case 0:cb.AddTemplate(newPage, 1f, 0, 0, 1f, 0, 0);break;case 90:cb.AddTemplate(newPage, 0, -1f, 1f, 0, 0, pageHeight);break;case 180:cb.AddTemplate(newPage, -1f, 0, 0, -1f, pageWidth, pageHeight);break;case 270://cb.AddTemplate(newPage, 0, 1f, -1f, 0, pageHeight, 0);cb.AddTemplate(newPage, 0, 1f, -1f, 0, pageWidth, 0);break;default:throw new InvalidOperationException(string.Format("Unexpected page rotation: [{0}].", rotation));}//页码的样式BaseFont bfHei = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);Font font = new Font(bfHei, 8);//增加页码Phrase header = new Phrase("第" + (writer.PageNumber) + "页", font);//页脚显示的位置ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_CENTER, header,document.PageSize.Width / 2, document.Bottom, 0);readerList.Add(reader);}}document.Close();foreach (var rd in readerList)//清理占用{rd.Dispose();}}/// /// 删除一个文件里所有的文件/// /// 文件夹路径public static void DeleteAllPdf(string Directorypath){System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Directorypath);if (di.Exists){FileInfo[] ff = di.GetFiles("*.pdf");foreach (FileInfo temp in ff){File.Delete(Directorypath + "\\" + temp.Name);}}}#endregion
}

}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部