使用iTextSharp實現PDF檔案套打功能

來源:互聯網
上載者:User

當前項目有個需求是給多個單位提供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 載入出錯,只好隨便搞了個方正的字型了。。囧

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.