當前項目有個需求是給多個單位提供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();
}
其中,載入宋體字型那段,由於我機器上宋體是SIMSUN.TTC 載入出錯,只好隨便搞了個方正的字型了。。囧