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

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

 /// <summary>
/// 产生PDf
/// </summary>
/// <param name="strFileName">文件名称</param>
/// <param name="dt">数据源</param>
public void PDF(string strFileName, DataTable dt, string PrintName)
{
if (!Directory.Exists(AppConfigString.FilePath))
{
Directory.CreateDirectory(AppConfigString.FilePath);
}
string strPathTemp = AppConfigString.FilePath + DateTime.Now.ToString("yyyyMMddhhmmss") + ".pdf";
//零時的pdf地址,用于水印读取文件
string strPath = AppConfigString.FilePath + strFileName;//真正文件的位置
Document document = new Document(PageSize.A4, , , , );
FileStream stream = new FileStream(strPathTemp, FileMode.Create);
PdfWriter writer = PdfWriter.GetInstance(document, stream);
document.Footer = Foot();//页尾的函数,在open前定义
document.Open();
HeaderFooter head = new HeaderFooter(HeadTable(, PrintName), true);
//true为在页眉的右边生成一个页数,会影响到页眉的高度,在open后定义
//headTable为页眉的函数
head.Border = Rectangle.NO_BORDER;
document.Header = head;
//页眉第一页不会出现,第2页才会出现,所以此地直接在第一列加了一个表头
//页尾在第一页就会出现
document.Add(HeadTable(, PrintName));//第一頁表頭不自動添加
//主要数据的添加
int IRowCount = dt.Rows.Count;
int IColumnCount = dt.Columns.Count;
PdfPTable pdfTb = new PdfPTable(IColumnCount);
pdfTb.HeaderRows = ;//自動加表頭
for (int i = ; i < IRowCount; i++)
{
for (int j = ; j < IColumnCount; j++)
{
string value = dt.Rows[i][j].ToString();
Phrase phs = new Phrase(value, PdfFont.Font());
//此时把数据转为Phrase只是为了使用字体,不然中文不能显示
pdfTb.AddCell(phs);
}
}
document.Add(pdfTb);
document.Close();
writer.Close();
PDFWatermark(strPathTemp, strPath, , , PrintName);//为生成好的文件添加水印 }

上面为一段完整的使用过程,注释是我刚加的,比较详细了,说下面几个问题  1:页眉和页首    》页眉与页首都使用相同的类HeaderFooter,只是页眉是给 document.Header,页尾是给document.Footer    》页尾是在document.open前,页眉是在document.open后    》页眉第一页不会出现,第2页才会出现,所以此地直接在第一列加了一个表头。页尾在第一页就会出现。  2:页眉的制作方法   由于页眉不好制作,所以我选择直接先拼成PdfPTable,再把PdfPTable放到Phrase,再把Phrase放到HeaderFooter给页眉,这样就好操作些   这个是在百度知道上找到的思路,我就这样做了,呵呵...  下面为我制作页眉的方法,一些信息安全问题已换为XXXXX

/// <summary>
/// 產生表頭的數據
/// </summary>
/// <param name="IType">1:ID 2:Name 3:detali</param>
/// <returns></returns>
public Phrase HeadTable(int IType, string PrintName)
{
string strhead = "";
switch (IType)
{
case : strhead = "XXXXXXXXXXXXXXXXXXXX"; break;
case : strhead = "XXXXXXXXXXXXXXXXXXXX"; break;
case : strhead = "XXXXXXXXXXXXXXXXXXXX"; break;
}
Phrase phshead = new Phrase(strhead, PdfFont.Font());
Phrase phsjimi = new Phrase("XXXXXXXXXXXXXXXXXXXX ", PdfFont.Font()); Phrase phsPeople = new Phrase("XXXXXXXXXXXXXXXXXXXX" + PrintName + "XXXXXXXXXXXXXXXXXXXX" + PrintName, PdfFont.Font());
Phrase phsPage = new Phrase(" ", PdfFont.Font());
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());
PdfPCell pchead = new PdfPCell(phshead);
pchead.VerticalAlignment = ;
pchead.HorizontalAlignment = ;
PdfPCell pcjimi = new PdfPCell(phsjimi);
PdfPCell pcPeople = new PdfPCell(phsPeople);
PdfPCell pcPage = new PdfPCell(phsPage);
PdfPCell pcPrintDate = new PdfPCell(phsPrintDate);
PdfPCell pcnull = new PdfPCell();
pchead.Border = ;
pcjimi.Border = ;
pcPeople.Border = ;
pcPage.Border = ;
pcPrintDate.Border = ;
pcnull.Border = ;
pcPeople.PaddingBottom = ;
pcPrintDate.PaddingBottom = ;
Phrase phead = new Phrase();
PdfPTable thead = new PdfPTable();
thead.AddCell(pchead);
thead.AddCell(pcjimi);
thead.AddCell(pcnull);
thead.AddCell(pcPage);
thead.AddCell(pcPeople);
thead.AddCell(pcPrintDate);
thead.SetWidths(new float[] { PageSize.A4.Width, });
phead.Add(thead);
return phead; }
 

页尾的方法

        /// <summary>
/// 页尾
/// </summary>
/// <returns></returns>
public HeaderFooter Foot()
{
string strFoot = @"XXXXXXXXXXXXXXXXXX";
Phrase pfoot = new Phrase(strFoot, PdfFont.Font());
HeaderFooter foot = new HeaderFooter(pfoot, false);
foot.Border = Rectangle.NO_BORDER;
return foot;
}

3:字体的问题  如果没有定义字体,汉字是不会出现的,下面是我定义的字体,使用的ITextSharp控件字体,当然也可以使用字体文件详情可查看http://winsystem.ctocio.com.cn/334/12194834.shtml

        /// <summary>
/// 文字类型定义
/// </summary>
/// <param name="IType">返回文字类别</param>
/// <returns></returns>
public static Font Font(int IType)
{
BaseFont.AddToResourceSearch("iTextAsian.dll");
BaseFont.AddToResourceSearch("iTextAsianCmaps.dll");
BaseFont bf = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
//简体?繁体不能使用
//
Font font = new Font(bf);//普通文章
font.Size = ;
Font fontFoot = new Font(bf);//頁脚文字
fontFoot.Size = ;
fontFoot.Color = Color.RED;
Font fontNormal = new Font(bf);//正常文字
fontNormal.Size = ;
switch (IType)
{
case : return font;
case : return fontFoot;
case : return fontNormal;
default: return fontNormal;
}
}

4:主要内容的制作 根据数据源,利用PdfPTable和Phase等制作,块等我还没用会,主要是样式和定位没搞会下面的博客有在Asp.Net中操作PDF – iTextSharp -利用块,短语,段落添加文本的方法http://www.cnblogs.com/CareySon/archive/2011/11/03/2234625.html5:水印的添加

        /// <summary>
/// 為生成的pdf添加水印
/// </summary>
/// <param name="inputfilepath"></param>
/// <param name="outputfilepath"></param>
/// <param name="top"></param>
/// <param name="left"></param>
/// <returns></returns>
public bool PDFWatermark(string inputfilepath, string outputfilepath, float top, float left, string strName)
{
PdfReader pdfReader = null;
PdfStamper pdfStamper = null;
try
{
pdfReader = new PdfReader(inputfilepath); int numberOfPages = pdfReader.NumberOfPages; iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(); float width = psize.Width; float height = psize.Height; pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create)); PdfContentByte waterMarkContent; WatermarkCreater wmc = new WatermarkCreater();
Draw.Image image = wmc.GetImageByte(strName, AppConfigString.WaterMarkPath);
var img = Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Png);
if (left < )
{
left = width - image.Width + left;
}
img.SetAbsolutePosition(left, (height - image.Height) - top);
//每一页加水印,也可以设置某一页加水印
for (int i = ; i <= numberOfPages; i++)
{
waterMarkContent = pdfStamper.GetUnderContent(i); waterMarkContent.AddImage(img);
}
return true;
}
catch (Exception ex)
{
ex.Message.Trim();
return false;
}
finally
{ if (pdfStamper != null)
pdfStamper.Close(); if (pdfReader != null)
pdfReader.Close();
//把添加水印前的pdf文件刪除,保存最新的文件
if (File.Exists(inputfilepath))
{
File.Delete(inputfilepath);
}
} }

这就是我们为什么要用一个零时路径了,先把产出的pdf放到零时路径,用来产生水印的时候读取,生成水印文件后,再把零时文件删除即可其中的WatermarkCreater方法可以看我以前的博客,报表水印的产生http://www.cnblogs.com/xiaoshuai1992/p/waterMark.html,方法相同 至此可以达到客户的要求,但是一些样式的问题就需要大家仔细研究了,这就是我的实践过程,希望可以和大家一起学习了

最新文章

  1. Android Tips: 打电话和发短信
  2. 关于GC垃圾回收的原理
  3. 字节流与字符流的区别&amp;&amp;用字节流好还是用字符流好?
  4. [转载]initwithcoder和 initwithframe
  5. WCF中的由于目标计算机积极拒绝,无法连接
  6. HDU 1540 Tunnel Warfare (线段树)
  7. mysql安装常见问题(系统找不到指定的文件、发生系统错误 1067 进程意外终止)
  8. iOS关于友盟分享弹不出面板问题
  9. git push 报错 &quot;Peer certificate cannot be authenticated with known CA certificates&quot;
  10. react-router(v4)
  11. gdb 调试 python
  12. 用SAX解析xml文件,java
  13. 【SFA官方翻译】使用 Kubernetes、Spring Boot 2.0 和 Docker 的微服务快速指南
  14. MySQL 处理海量数据时一些优化查询速度方法
  15. 自动化测试-20.selenium常用JS代码执行
  16. mysql explain中的type列含义和extra列的含义
  17. 项目报错:Caused by: java.lang.ClassNotFoundException: Didn&#39;t find class &quot;...&quot;on path: DexPathList
  18. Eclipse中如何在指定工程中搜索指定的字符串
  19. python中sys.stdout、sys.stdin
  20. Python3.5 学习三

热门文章

  1. Mybatis常用xml
  2. CFileDialog OFN_NOCHANGEDIR
  3. CentOS 7.X 搭建时间服务器 --- chrony
  4. virtualenv简介以及一个比较折腾的scrapy安装方法
  5. Git从入门到熟练
  6. android的5个进程等级
  7. php jsonp单引号转义
  8. jeakins忘记密码时的处理(简单粗暴)
  9. Windows7中如何让python2和python3共存并使用pip
  10. 简述Shiro验证过程