原文 使用ItextSharp产PDF完整操作

记得上回有写到用C#操作Excel(.net 4.0)

很多朋友说推荐用NPOI,的确,用微软自带的操作execl会有很大的问题。客户的主机不愿意安装excel,
这时我才意识到用自带组件完全是不行的,我本来准备改用NPOI组件,但是这时客户提出为了安全(数据安全),改用后台产PDF。
这就有了本文中ITextSharp的用法
本文介绍了基本全套的用法,包括页眉,页首,表格的用法,但是还是有很多问题没有处理好,只是把我已经ok的地方拿出来给一些需要的朋友学习。
 
一:下载地址
下面这篇博文说明了ITextsharp的下载地址,本人就是按照这篇文章进行的下载
注意版本不同,一些函数的用法也不相同了
 
二:产出PDF

  1. /// <summary>
  2. /// 产生PDf
  3. /// </summary>
  4. /// <param name="strFileName">文件名称</param>
  5. /// <param name="dt">数据源</param>
  6. public void PDF(string strFileName, DataTable dt, string PrintName)
  7. {
  8. if (!Directory.Exists(AppConfigString.FilePath))
  9. {
  10. Directory.CreateDirectory(AppConfigString.FilePath);
  11. }
  12. string strPathTemp = AppConfigString.FilePath + DateTime.Now.ToString("yyyyMMddhhmmss") + ".pdf";
  13. //零時的pdf地址,用于水印读取文件
  14. string strPath = AppConfigString.FilePath + strFileName;//真正文件的位置
  15. Document document = new Document(PageSize.A4, 25, 25, 25, 25);
  16. FileStream stream = new FileStream(strPathTemp, FileMode.Create);
  17. PdfWriter writer = PdfWriter.GetInstance(document, stream);
  18. document.Footer = Foot();//页尾的函数,在open前定义
  19. document.Open();
  20. HeaderFooter head = new HeaderFooter(HeadTable(3, PrintName), true);
  21. //true为在页眉的右边生成一个页数,会影响到页眉的高度,在open后定义
  22. //headTable为页眉的函数
  23. head.Border = Rectangle.NO_BORDER;
  24. document.Header = head;
  25. //页眉第一页不会出现,第2页才会出现,所以此地直接在第一列加了一个表头
  26. //页尾在第一页就会出现
  27. document.Add(HeadTable(3, PrintName));//第一頁表頭不自動添加
  28. //主要数据的添加
  29. int IRowCount = dt.Rows.Count;
  30. int IColumnCount = dt.Columns.Count;
  31. PdfPTable pdfTb = new PdfPTable(IColumnCount);
  32. pdfTb.HeaderRows = 1;//自動加表頭
  33. for (int i = 0; i < IRowCount; i++)
  34. {
  35. for (int j = 0; j < IColumnCount; j++)
  36. {
  37. string value = dt.Rows[i][j].ToString();
  38. Phrase phs = new Phrase(value, PdfFont.Font(3));
  39. //此时把数据转为Phrase只是为了使用字体,不然中文不能显示
  40. pdfTb.AddCell(phs);
  41. }
  42. }
  43. document.Add(pdfTb);
  44. document.Close();
  45. writer.Close();
  46. PDFWatermark(strPathTemp, strPath, 10, 10, PrintName);//为生成好的文件添加水印
  47.  
  48. }

上面为一段完整的使用过程,注释是我刚加的,比较详细了,说下面几个问题

1:页眉和页首

》页眉与页首都使用相同的类HeaderFooter,只是页眉是给 document.Header,页尾是给document.Footer

》页尾是在document.open前,页眉是在document.open后

》页眉第一页不会出现,第2页才会出现,所以此地直接在第一列加了一个表头。页尾在第一页就会出现。

2:页眉的制作方法

由于页眉不好制作,所以我选择直接先拼成PdfPTable,再把PdfPTable放到Phrase,再把Phrase放到HeaderFooter给页眉,这样就好操作些

这个是在百度知道上找到的思路,我就这样做了,呵呵...

下面为我制作页眉的方法,一些信息安全问题已换为XXXXX

  1. /// <summary>
  2. /// 產生表頭的數據
  3. /// </summary>
  4. /// <param name="IType">1:ID 2:Name 3:detali</param>
  5. /// <returns></returns>
  6. public Phrase HeadTable(int IType, string PrintName)
  7. {
  8. string strhead = "";
  9. switch (IType)
  10. {
  11. case 1: strhead = "XXXXXXXXXXXXXXXXXXXX"; break;
  12. case 2: strhead = "XXXXXXXXXXXXXXXXXXXX"; break;
  13. case 3: strhead = "XXXXXXXXXXXXXXXXXXXX"; break;
  14. }
  15. Phrase phshead = new Phrase(strhead, PdfFont.Font(1));
  16. Phrase phsjimi = new Phrase("XXXXXXXXXXXXXXXXXXXX ", PdfFont.Font(3));
  17.  
  18. Phrase phsPeople = new Phrase("XXXXXXXXXXXXXXXXXXXX" + PrintName + "XXXXXXXXXXXXXXXXXXXX" + PrintName, PdfFont.Font(3));
  19. Phrase phsPage = new Phrase(" ", PdfFont.Font(3));
  20. Phrase phsPrintDate = new Phrase("列印時間:" + DateTime.Now.ToString("yyyy/MM/dd hh:mm") + "\r\n Print Date:" + DateTime.Now.ToString("yyyy/MM/dd hh:mm"), PdfFont.Font(3));
  21. PdfPCell pchead = new PdfPCell(phshead);
  22. pchead.VerticalAlignment = 1;
  23. pchead.HorizontalAlignment = 1;
  24. PdfPCell pcjimi = new PdfPCell(phsjimi);
  25. PdfPCell pcPeople = new PdfPCell(phsPeople);
  26. PdfPCell pcPage = new PdfPCell(phsPage);
  27. PdfPCell pcPrintDate = new PdfPCell(phsPrintDate);
  28. PdfPCell pcnull = new PdfPCell();
  29. pchead.Border = 0;
  30. pcjimi.Border = 0;
  31. pcPeople.Border = 0;
  32. pcPage.Border = 0;
  33. pcPrintDate.Border = 0;
  34. pcnull.Border = 0;
  35. pcPeople.PaddingBottom = 10;
  36. pcPrintDate.PaddingBottom = 10;
  37. Phrase phead = new Phrase();
  38. PdfPTable thead = new PdfPTable(2);
  39. thead.AddCell(pchead);
  40. thead.AddCell(pcjimi);
  41. thead.AddCell(pcnull);
  42. thead.AddCell(pcPage);
  43. thead.AddCell(pcPeople);
  44. thead.AddCell(pcPrintDate);
  45. thead.SetWidths(new float[] { PageSize.A4.Width, 200 });
  46. phead.Add(thead);
  47. return phead;
  48.  
  49. }
 

页尾的方法

  1. /// <summary>
  2. /// 页尾
  3. /// </summary>
  4. /// <returns></returns>
  5. public HeaderFooter Foot()
  6. {
  7. string strFoot = @"XXXXXXXXXXXXXXXXXX";
  8. Phrase pfoot = new Phrase(strFoot, PdfFont.Font(2));
  9. HeaderFooter foot = new HeaderFooter(pfoot, false);
  10. foot.Border = Rectangle.NO_BORDER;
  11. return foot;
  12. }

3:字体的问题

如果没有定义字体,汉字是不会出现的,下面是我定义的字体,使用的ITextSharp控件字体,当然也可以使用字体文件

详情可查看http://winsystem.ctocio.com.cn/334/12194834.shtml

  1. /// <summary>
  2. /// 文字类型定义
  3. /// </summary>
  4. /// <param name="IType">返回文字类别</param>
  5. /// <returns></returns>
  6. public static Font Font(int IType)
  7. {
  8. BaseFont.AddToResourceSearch("iTextAsian.dll");
  9. BaseFont.AddToResourceSearch("iTextAsianCmaps.dll");
  10. BaseFont bf = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
  11. //简体?繁体不能使用
  12. //
  13. Font font = new Font(bf);//普通文章
  14. font.Size = 10;
  15. Font fontFoot = new Font(bf);//頁脚文字
  16. fontFoot.Size = 7;
  17. fontFoot.Color = Color.RED;
  18. Font fontNormal = new Font(bf);//正常文字
  19. fontNormal.Size = 7;
  20. switch (IType)
  21. {
  22. case 1: return font;
  23. case 2: return fontFoot;
  24. case 3: return fontNormal;
  25. default: return fontNormal;
  26. }
  27. }

4:主要内容的制作

根据数据源,利用PdfPTable和Phase等制作,块等我还没用会,主要是样式和定位没搞会

下面的博客有在Asp.Net中操作PDF – iTextSharp -利用块,短语,段落添加文本的方法

http://www.cnblogs.com/CareySon/archive/2011/11/03/2234625.html

5:水印的添加

  1. /// <summary>
  2. /// 為生成的pdf添加水印
  3. /// </summary>
  4. /// <param name="inputfilepath"></param>
  5. /// <param name="outputfilepath"></param>
  6. /// <param name="top"></param>
  7. /// <param name="left"></param>
  8. /// <returns></returns>
  9. public bool PDFWatermark(string inputfilepath, string outputfilepath, float top, float left, string strName)
  10. {
  11. PdfReader pdfReader = null;
  12. PdfStamper pdfStamper = null;
  13. try
  14. {
  15. pdfReader = new PdfReader(inputfilepath);
  16.  
  17. int numberOfPages = pdfReader.NumberOfPages;
  18.  
  19. iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);
  20.  
  21. float width = psize.Width;
  22.  
  23. float height = psize.Height;
  24.  
  25. pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create));
  26.  
  27. PdfContentByte waterMarkContent;
  28.  
  29. WatermarkCreater wmc = new WatermarkCreater();
  30. Draw.Image image = wmc.GetImageByte(strName, AppConfigString.WaterMarkPath);
  31. var img = Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Png);
  32. if (left < 0)
  33. {
  34. left = width - image.Width + left;
  35. }
  36. img.SetAbsolutePosition(left, (height - image.Height) - top);
  37. //每一页加水印,也可以设置某一页加水印
  38. for (int i = 1; i <= numberOfPages; i++)
  39. {
  40. waterMarkContent = pdfStamper.GetUnderContent(i);
  41.  
  42. waterMarkContent.AddImage(img);
  43. }
  44. return true;
  45. }
  46. catch (Exception ex)
  47. {
  48. ex.Message.Trim();
  49. return false;
  50. }
  51. finally
  52. {
  53.  
  54. if (pdfStamper != null)
  55. pdfStamper.Close();
  56.  
  57. if (pdfReader != null)
  58. pdfReader.Close();
  59. //把添加水印前的pdf文件刪除,保存最新的文件
  60. if (File.Exists(inputfilepath))
  61. {
  62. File.Delete(inputfilepath);
  63. }
  64. }
  65.  
  66. }

这就是我们为什么要用一个零时路径了,先把产出的pdf放到零时路径,用来产生水印的时候读取,生成水印文件后,再把零时文件删除即可

其中的WatermarkCreater方法可以看我以前的博客,报表水印的产生http://www.cnblogs.com/xiaoshuai1992/p/waterMark.html,方法相同

至此可以达到客户的要求,但是一些样式的问题就需要大家仔细研究了,这就是我的实践过程,希望可以和大家一起学习了

 
 
 

使用ItextSharp产PDF完整操作的更多相关文章

  1. 利用ItextSharp产PDF完整操作

    记得上回有写到用C#操作Excel(.net 4.0) 很多朋友说推荐用NPOI,的确,用微软自带的操作execl会有很大的问题.客户的主机不愿意安装excel, 这时我才意识到用自带组件完全是不行的 ...

  2. 利用NPOI组件产Excel完整操作

    最终还是要使用NPOi了.刚开始做的是用com组件,发现如果本机不按照excel就不能使用,后来把其中一支改为了用Itextsharp产生pdf,但是还有几支批次要产生Excel,只能改用NPOI了. ...

  3. 利用Com组件产Excel完整操作

    最近公司要批次产出报表,是利用控制台应用程序操作Excel,并设置各种样式. 在网上搜索此类的例子,但是感觉一些用法都已经发生了变化,我用的.net 4.0 ,Microsoft.Office.Int ...

  4. 基于iTextSharp的PDF文档操作

    公司是跨境电商,需要和各种物流打交道,需要把东西交给物流,让他们发到世界各地.其中需要物流公司提供一个运单号,来追踪货物到达哪里?! 最近在和DHL物流公司(应该是个大公司)对接,取运单号的方式是调用 ...

  5. 基于iTextSharp的PDF操作(PDF打印,PDF下载)

    基于iTextSharp的PDF操作(PDF打印,PDF下载) 准备 1. iTextSharp的简介 iTextSharp是一个移植于java平台的iText项目,被封装成c#的组件来用于C#生成P ...

  6. 根据路径获得文件名以及Aspose.Cells.dll操作excel 以及使用iTextSharp.text.pdf.PdfReader.dll对PDF的操作

    string result = Regex.Match(str,@"[^\\]+$").Value;//正则表达式 this.listBox1.Items.Add(Path.Get ...

  7. .NET的那些事儿(9)——C# 2.0 中用iTextSharp制作PDF(基础篇) .

    该文主要介绍如何借助iTextSharp在C# 2.0中制作PDF文件,本文的架构大致按照iTextSharp的操作文档进行翻译,如果需要查看原文,请点击一下链接:http://itextsharp. ...

  8. itextsharp去掉PDF加密

    在操作PDF文件时会遇到PDF文件加密了,不能操作的问题,从网络中查找资料一上午,鼓捣出如下的代码,可实现将已加密的PDF转化成未加密的PDF文件,纯代码,无需借助PDF解密软件,使用前需要导入如下引 ...

  9. [PDF] PDFOperation--C#PDF文件操作帮助类 (转载)

    点击下载 PDFOperation.rar 这个类是关于PDFOperation的帮助类,主要是实现C#PDF的文件操作,具体实现功能如下1.构造函数2.私有字段3.设置字体4.设置页面大小5.实例化 ...

随机推荐

  1. Java疯狂讲义(二)

  2. Hadoop_Lucene

    http://codelife.me/blog/2012/11/03/jackson-polymorphic-deserialization/ http://itindex.net/blog/2012 ...

  3. viminfo: 无效的启动字符

    当自己进入一个用户,使用vi打开一个文件时,出现以下情况: [gexd@localhost ~]$ vi test.c E575: viminfo: 无效的启动字符 位于行: int main() . ...

  4. 【充电器】小米手机2S电池座充——小米手机官网

    ligh@local-host$ ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.0.3 [充电器]小米手机2S电池座充--小米手机官网 小米手机2S电池座 ...

  5. HDU 4569Special equations2012长沙邀请赛E题(数学知识)

    Special equations Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others ...

  6. Strategic Game(匈牙利算法,最小点覆盖数)

    Strategic Game Time Limit: 20000/10000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) ...

  7. __autoload函数

    ./index.php----------------------------------------------------------------------------------<?ph ...

  8. ognl--数据运转的催化剂

    原文链接:http://struts2.group.iteye.com/group/wiki/1353-ognl-catalyst-for-data-operation-in-struts2 首先让我 ...

  9. Apache ab 使用说明

    第一章 简介 ab是Apache超文本传输协议(HTTP)的性能测试工具.其设计意图是描绘当前所安装的Apache的执行性能,主要是显示你安装的Apache每秒可以处理多少个请求. 第二章 说明 ab ...

  10. VC++在对话框中加入属性页

    当一个基于对话框的程序中有相当多的控件时,你一定会想到使用属性页来将这些控件分类放置.本文针对这种方法来讨论几种可能实现的方案. 方案一本方案的例子请见源代码打包文件中的Property1部分 在对话 ...