(轉)C#使用itextsharp生成PDF文件


原文鏈接:https://blog.csdn.net/c79651760/article/details/56480109
               
           
                   
                                                   
                                       
                   
                   
                                            前言
前段時間公司需要實現一個PDF文件下載功能,涉及到頁眉頁腳,段落,圖片的生成。遂使用itextsharp來實現這一功能,但是itextsharp功能強大,類庫繁多,特別是5.0版本后關於頁眉頁腳生成的介紹並不多,研究了好久,才弄成功,寫下這篇博客做個記錄。
先來看下最后實現的效果:
 

下面來看代碼
添加引用:
幫助類的代碼,這個類可以直接使用,如果你需要增加或者完善某功能,可以對其進行修改。
此類使用方法下面做介紹:
 
public class HeaderAndFooterEvent : PdfPageEventHelper, IPdfPageEvent
    {
        #region 靜態字段
        public static PdfTemplate tpl = null;
        public static bool PAGE_NUMBER = false;//為True時就生成 頁眉和頁腳 
        public static iTextSharp.text.Rectangle rect = PageSize.A4;   //文檔大小
        /// <summary>
        /// 正文字體
        /// </summary>
        private static Font font;
        /// <summary>
        /// 頁眉頁腳字體
        /// </summary>
        public static string HeaderFooterFontName = "黑體";
        /// <summary>
        /// 頁頭頁腳字號
        /// </summary>
        public static int HeaderFooterFontSize = 10;
        /// <summary>
        /// 頁頭頁尾字體顏色
        /// </summary>
        public static BaseColor HeaderFooterFontColor = BaseColor.BLACK;
        /// <summary>
        /// 左邊頁眉
        /// </summary>
        public static string HeaderLeft { get; set; }
        /// <summary>
        /// 右邊頁眉
        /// </summary>
        public static string HeaderRight { get; set; }
        /// <summary>
        /// 左邊頁腳
        /// </summary>
        public static string FooterLeft { get; set; }
        /// <summary>
        /// 右邊頁腳
        /// </summary>
        public static string FooterRight { get; set; }
        #endregion
        #region 設置頁面大小
        /// <summary>
        /// 設置頁面大小
        /// </summary>
        /// <param name="type">頁面大小(如"A4")</param>
        public static void SetPageSize(string type)
        {
            switch (type.Trim())
            {
                case "A4":
                    rect = PageSize.A4;
                    break;
                case "A8":
                    rect = PageSize.A8;
                    break;
            }
        }
        #endregion
        #region 設置字體
        /// <summary>
        /// 設置字體
        /// </summary>
        /// <param name="size">字體大小</param>
        public static void SetFont(BaseColor color, string fontName = "華文中宋", float size = 12, int style = Font.NORMAL)
        {
            font = new Font(BaseFontAndSize(fontName), size, style, color);
        }
        #endregion
        #region 生成頁眉頁腳
        /// <summary>
        /// 關閉一個頁面時發生 
        /// </summary>
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            if (PAGE_NUMBER)
            {
                Font HeaderFooterFont = FontAndSize(HeaderFooterFontName, HeaderFooterFontSize, Font.NORMAL, HeaderFooterFontColor);
                Phrase header_left = new Phrase(HeaderLeft, HeaderFooterFont);
                Phrase header_right = new Phrase(HeaderRight, HeaderFooterFont);
                Phrase footer_left = new Phrase(FooterLeft, HeaderFooterFont);
                Phrase footer_center = new Phrase("第" + (writer.PageNumber) + "頁/共     頁", HeaderFooterFont);
                Phrase footer_right = new Phrase(FooterRight, HeaderFooterFont);
 
                PdfContentByte cb = writer.DirectContent;
                //模版 顯示總共頁數 
                cb.AddTemplate(tpl, document.Right - 290 + document.LeftMargin, document.Bottom - 15);//調節模版顯示的位置 
                //頁眉顯示的位置 
                ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, header_right,
                       document.Right - 50 + document.LeftMargin, document.Top + 15, 0);
                ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, header_left,
                       document.Right - 500 + document.LeftMargin, document.Top + 15, 0);
                //頁腳顯示的位置 
                ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, footer_left,
                       document.Right - 535 + document.LeftMargin, document.Bottom - 15, 0);
                ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, footer_center,
                       document.Right - 300 + document.LeftMargin, document.Bottom - 15, 0);
                ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, footer_right,
                       document.Right - 80 + document.LeftMargin, document.Bottom - 15, 0);
            }
        }
        /// <summary>
        /// 打開一個新頁面時發生
        /// </summary>
        public override void OnStartPage(PdfWriter writer, Document document)
        {
            if (PAGE_NUMBER)
            {
                writer.PageCount = writer.PageNumber - 1;
            }
        }
        /// <summary>
        /// 關閉PDF文檔時發生該事件
        /// </summary>
        public override void OnCloseDocument(PdfWriter writer, Document document)
        {
            BaseFont bf = BaseFontAndSize(HeaderFooterFontName);
            tpl.BeginText();
            tpl.SetFontAndSize(bf, HeaderFooterFontSize);
            tpl.ShowText((writer.PageNumber - 1).ToString());//總頁數
            tpl.EndText();
            tpl.ClosePath();
        }
        #endregion
        #region 私有方法
        private static Font FontAndSize(string font_name, int size, int style, BaseColor baseColor)
        {
            BaseFont baseFont;
            BaseFont.AddToResourceSearch("iTextAsian.dll");
            BaseFont.AddToResourceSearch("iTextAsianCmaps.dll");
            Font font = null;
            string file_name = "";
            int fontStyle;
            switch (font_name)
            {
                case "黑體":
                    file_name = "SIMHEI.TTF";
                    break;
                case "華文中宋":
                    file_name = "STZHONGS.TTF";
                    break;
                case "宋體":
                    file_name = "SIMYOU.TTF";
                    break;
                default:
                    file_name = "SIMYOU.TTF";
                    break;
            }
            baseFont = BaseFont.CreateFont(@"c:/windows/fonts/" + file_name, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            if (style < -1)
            {
                fontStyle = Font.NORMAL;
            }
            else
            {
                fontStyle = style;
            }
            font = new Font(baseFont, size, fontStyle, baseColor);
            return font;
        }
        private static BaseFont BaseFontAndSize(string font_name)
        {
            BaseFont baseFont;
            BaseFont.AddToResourceSearch("iTextAsian.dll");
            BaseFont.AddToResourceSearch("iTextAsianCmaps.dll");
            string file_name = "";
            switch (font_name)
            {
                case "黑體":
                    file_name = "SIMHEI.TTF";
                    break;
                case "華文中宋":
                    file_name = "STZHONGS.TTF";
                    break;
                case "宋體":
                    file_name = "SIMYOU.TTF";
                    break;
                default:
                    file_name = "SIMYOU.TTF";
                    break;
            }
            baseFont = BaseFont.CreateFont(@"c:/windows/fonts/" + file_name, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            return baseFont;
        }
        #endregion
        #region 添加段落
        /// <summary>
        /// 添加段落
        /// </summary>
        /// <param name="content">內容</param>
        /// <param name="Alignment">對齊方式(1為居中,0為居左,2為居右)</param>
        /// <param name="SpacingAfter">段后空行數(0為默認值)</param>
        /// <param name="SpacingBefore">段前空行數(0為默認值)</param>
        /// <param name="MultipliedLeading">行間距(0為默認值)</param>
        public static Paragraph AddParagraph(string content, int Alignment, float SpacingAfter, float SpacingBefore, float MultipliedLeading)
        {
            Paragraph pra = new Paragraph(content, font);
            pra.Alignment = Alignment;
            pra.SpacingAfter = SpacingAfter;
            pra.SpacingBefore = SpacingBefore;
            pra.MultipliedLeading = MultipliedLeading;
            return pra;
        }
        public static Paragraph AddParagraph(string content, int Alignment, float MultipliedLeading)
        {
            Paragraph pra = new Paragraph(content, font);
            pra.Alignment = Alignment;
            pra.MultipliedLeading = MultipliedLeading;
            return pra;
        }
        public static void AddPhrase(PdfWriter writer, Document document, string content, float marginLift, float marginBottom)
        {
            Phrase phrase = new Phrase(content, font);
            PdfContentByte cb = writer.DirectContent;
            ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, phrase,
                       marginLift + document.LeftMargin, marginBottom, 0);
        }
        #endregion
        #region 添加圖片
        /// <summary>
        /// 添加圖片
        /// <param name="Alignment">對齊方式 (0/1/2)</param>
        /// <param name="marginRight">頁邊距</param>
        /// <param name="marginBottom">頁邊距</param>
        /// </summary>
        public static iTextSharp.text.Image AddImage(string path, int Alignment, float marginRight, float marginBottom)
        {
            Image img = Image.GetInstance(new Uri(path));
            img.Alignment = Alignment;
            //等比縮放,寬與高的縮放系數哪個大就取哪一個(比如高的系數是0.8,寬的是0.7,則取0.7。這樣圖片就不會超出頁面范圍)
            if (img.Width > img.Height)
            {
                //這里計算圖片的縮放系數,因為圖片width>height,所以將圖片旋轉90度以適應頁面,計算縮放系數的時候寬與高對調
                float PageHeight = PageSize.A4.Height - marginBottom * 3;
                double percentHeight = Math.Round((PageHeight / img.Width), 2);
                float PageWidth = PageSize.A4.Width - marginRight * 2;
                double percentWidth = Math.Round((PageWidth / img.Height), 2);
                double percent = percentHeight > percentWidth ? percentWidth : percentHeight;
                img.ScalePercent((float)percent * 100);
                img.RotationDegrees = 90f;
            }
            else
            {
                float PageHeight = PageSize.A4.Height - marginBottom * 3;
                double percentHeight = Math.Round((PageHeight / img.Height), 2);
                float PageWidth = PageSize.A4.Width - marginRight * 2;
                double percentWidth = Math.Round((PageWidth / img.Width), 2);
                double percent = percentHeight > percentWidth ? percentWidth : percentHeight;
                img.ScalePercent((float)percent * 100);
            }
            return img;
        }
        #endregion
    }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
下面是使用方法:
在你需要生成文件的地方實例化Document和PdfWriter 對象:
Document document = new Document(HeaderAndFooterEvent.rect);
//此處使用的是http請求的流,你也可以使用文件流Stream
PdfWriter writer = PdfWriter.GetInstance(document, HttpContext.Current.Response.OutputStream);
document.Open();
writer.PageEvent = new HeaderAndFooterEvent();12345
實現頁眉和頁腳:
 
HeaderAndFooterEvent.PAGE_NUMBER = true;//實現頁眉跟頁腳 
HeaderAndFooterEvent.tpl = writer.DirectContent.CreateTemplate(500, 500); //定義模板
HeaderAndFooterEvent.HeaderLeft = "Aviation Meteorological Center";
HeaderAndFooterEvent.HeaderRight = "民航氣象中心";
HeaderAndFooterEvent.FooterLeft = "TEL:010-87922095";
HeaderAndFooterEvent.FooterRight = _dtm.ToString("yyyy-MM-dd HH:mm:ss") + "(UTC)";1234567
首頁
 
//每次在添加文本內容之前可以先設置字體,有效期持續到重新設置之前
HeaderAndFooterEvent.SetFont(BaseColor.BLACK, "宋體", 25, Font.BOLD);
//添加一個空段落來占位,五個參數分別為:內容,對齊方式(1為居中,0為居左,2為居右),段后空行數,段前空行數,行間距
document.Add(HeaderAndFooterEvent.AddParagraph(" ", 1, 200, 0, 1.5f));
//這個方法為上一個方法的重載,三個參數分別為:內容,對齊方式,行間距
document.Add(HeaderAndFooterEvent.AddParagraph("飛行氣象文件", 1, 1.5f));
HeaderAndFooterEvent.SetFont(BaseColor.BLACK, "宋體", 18, Font.BOLD);
document.Add(HeaderAndFooterEvent.AddParagraph("Meteorological Aviation Report", 1, 1.5f));123456789
然后就是新建頁了,每需要一頁的時候就 document.NewPage();  就可以了,當然,如果你在其中一頁添加的內容超過了此頁的篇幅,則會自動追加一頁。下面演示怎么新建一頁並添加內容:
 
document.NewPage();
HeaderAndFooterEvent.SetFont(BaseColor.DARK_GRAY, "宋體", 15, Font.BOLD);
document.Add(HeaderAndFooterEvent.AddParagraph("飛行氣象文件", 1, 1.5f));
HeaderAndFooterEvent.SetFont(BaseColor.DARK_GRAY, "宋體", 12);
document.Add(HeaderAndFooterEvent.AddParagraph("航班號:      " ));
1234567
下面演示添加圖片:
添加圖片比較簡單,當圖片的寬度超過高度時,會進行旋轉並按照比例縮放,從而盡量鋪滿整個頁面。如果你不需要旋轉,可以對幫助類進行修改。
 
document.NewPage();
//四個參數分別為:圖片路徑,對齊方式,文檔的右邊距,下邊距;邊距這兩個參數用於計算圖片的縮放尺寸。
document.Add("圖片路徑", 0, document.RightMargin, document.Bottom));1234
到現在,大功告成
只需要關閉文檔和流就行了。
 
writer.Flush();
writer.CloseStream = true;
document.Close();
————————————————
版權聲明:本文為CSDN博主「飛翔的牛魔王」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/c79651760/article/details/56480109


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM