当前项目有个需求是给多个单位提供PDF文件下载
而这些文件都是一批文档,只是数据和单位不一致而已
于是想用iTextSharp往空模板上增加单位数据等信息。
网上资料也不少,这里大致整理下
1. 开源C# PDF操作类库搜集
http://csharp-source.net/open-source/pdf-libraries
2.RubyPdf关于中文iTextSharp的说明
http://www.cnblogs.com/hardrock/archive/2006/09/23/512605.html
3.iText的官网,java的,代码里大致改改就能用,多数是大小写和 方法 属性 封装不同
http://itextdocs.lowagie.com/tutorial/
4.关于往PDF上添加文本
参考了 PDF上添加水印的文章
改成了添加文本:
struct PDFTextInfo
{
public string sText;
public int iPageNo;
public int iPosX;
public int iPosY;
public override string ToString()
{
return string.Format("Page:{0},x:{1},y:{2},text:{3}", new object[] { iPageNo,iPosX,iPosY,sText});
}
}
private void AddTextToPDF(string fromPDFFile, string toPDFFile, PDFTextInfo[] texts)
{
//打开原文件
PdfReader reader = new PdfReader(fromPDFFile);
int n = reader.NumberOfPages;
//新建文件句柄
PdfStamper stamp = new PdfStamper(reader, new FileStream(toPDFFile, FileMode.Create));
PdfContentByte waterMark;
//加载宋体字体
BaseFont bfComic = BaseFont.CreateFont("SURSONG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
iTextSharp.text.Font font = new iTextSharp.text.Font(bfComic, 10);
//process
for (int i = 0; i < texts.Length; i++)
{
waterMark = stamp.GetOverContent(texts[i].iPageNo);
iTextSharp.text.Phrase ph = new Phrase(texts[i].sText, font);
ColumnText.ShowTextAligned(waterMark, Element.ALIGN_LEFT, ph, texts[i].iPosX, texts[i].iPosY, 0);
}
stamp.Close();
reader.Close();
}
{
public string sText;
public int iPageNo;
public int iPosX;
public int iPosY;
public override string ToString()
{
return string.Format("Page:{0},x:{1},y:{2},text:{3}", new object[] { iPageNo,iPosX,iPosY,sText});
}
}
private void AddTextToPDF(string fromPDFFile, string toPDFFile, PDFTextInfo[] texts)
{
//打开原文件
PdfReader reader = new PdfReader(fromPDFFile);
int n = reader.NumberOfPages;
//新建文件句柄
PdfStamper stamp = new PdfStamper(reader, new FileStream(toPDFFile, FileMode.Create));
PdfContentByte waterMark;
//加载宋体字体
BaseFont bfComic = BaseFont.CreateFont("SURSONG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
iTextSharp.text.Font font = new iTextSharp.text.Font(bfComic, 10);
//process
for (int i = 0; i < texts.Length; i++)
{
waterMark = stamp.GetOverContent(texts[i].iPageNo);
iTextSharp.text.Phrase ph = new Phrase(texts[i].sText, font);
ColumnText.ShowTextAligned(waterMark, Element.ALIGN_LEFT, ph, texts[i].iPosX, texts[i].iPosY, 0);
}
stamp.Close();
reader.Close();
}
其中,加载宋体字体那段,由于我机器上宋体是SIMSUN.TTC 加载出错,只好随便搞了个方正的字体了。。囧