C#使用itextsharp產生PDF檔案的實現代碼

來源:互聯網
上載者:User

以下是對在C#中使用itextsharp產生PDF檔案的實現代碼進行了詳細分析介紹,需要的朋友可以過來參考下 

項目需求需要產生一個PDF文檔,使用的是VS2010,ASP.NET。
網路上多次搜尋沒有自己想要的,於是硬著頭皮到itextpdf官網看英文文檔,按時完成任務,以實用為主,共用一下:
使用HTML檔案建立PDF模板:
使用自訂字型的一種方法:

複製代碼 代碼如下:
                FontFactory.Register(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "FontsRAGE.TTF", "myFont");
                Font myFont = FontFactory.GetFont("myFont");
                BaseFont bf = myFont.BaseFont;


其中RAGE.TTF是微軟作業系統內建的字型,目錄在C:WindowsFonts,建議將需要的字型拷貝到項目中使用,否則會出現引用不到的情況。
使用自訂樣式:

複製代碼 代碼如下:
                StyleSheet css = new StyleSheet();
                Dictionary<String, String> dict= new Dictionary<string, string>();
                dict.Add(HtmlTags.BGCOLOR, "#01366C");
                dict.Add(HtmlTags.COLOR, "#000000");
                dict.Add(HtmlTags.SIZE,"25");
                css.LoadStyle("css1", dict);


這裡既可以使用了StyleSheet的LoadStyle方法。
注意itextsharp對HTML元素的支援很弱,像label、div等元素的對齊、背景顏色等屬性支援不好,建議使用table標籤。
重寫Font的GetFont方法:

複製代碼 代碼如下:
public  class MyFontFactory : IFontProvider
        {
            public  Font GetFont(String fontname,String encoding, Boolean embedded, float size,int style, BaseColor color)
            {
                if (fontname == "微軟雅黑")
                {
                    string fontpath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "FontsMSYH.ttf";
                    BaseFont bf3 = BaseFont.CreateFont(fontpath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                    Font fontContent = new Font(bf3,size,style,color);
                    return fontContent;
                }
                else {
                    Font fontContent = FontFactory.GetFont(fontname, size, style, color);
                    return fontContent;
                }
            }
            public  Boolean IsRegistered(String fontname)
            {
                return false;
            }
        }


這裡要想使用自訂字型需要繼承IFontProvider介面,並重寫Font的GetFont方法。
將自訂字型和樣式表加入到文檔:

複製代碼 代碼如下:
                Dictionary<String, Object> font = new Dictionary<string, object>();
                font.Add(HTMLWorker.FONT_PROVIDER,new MyFontFactory());

                List<IElement> p = HTMLWorker.ParseToList(new StreamReader(html), css,font);


使用PdfContentByte為元素加背景顏色:

複製代碼 代碼如下:
                PdfContentByte pcb = writer.DirectContentUnder;
                pcb.SetRGBColorFill(0, 255, 0);
                pcb.SetRGBColorFill(1, 54, 108);
                pcb.Rectangle(20, 413, 800, 42);
                pcb.Fill();


缺點顯而易見,就是需要絕對座標,小弟學疏才淺,再加時間緊迫,只能如此。如果大牛知道更好的方法,還望不吝賜教。
完整代碼:

複製代碼 代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.IO;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.html;
/// <summary>
///CreatePDF 的摘要說明
/// </summary>
namespace WSE.LCPI
{
    public class CreatePDF
    {
        public CreatePDF()
        {
            //
            //TODO: 在此處添加建構函式邏輯
            //
        }
       public  class MyFontFactory : IFontProvider
        {
            public  Font GetFont(String fontname,String encoding, Boolean embedded, float size,int style, BaseColor color)
            {
                if (fontname == "微軟雅黑")
                {
                    string fontpath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "LCPIFontsMSYH.ttf";
                    BaseFont bf3 = BaseFont.CreateFont(fontpath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                    Font fontContent = new Font(bf3,size,style,color);
                    return fontContent;
                }
                else {
                    Font fontContent = FontFactory.GetFont(fontname, size, style, color);
                    return fontContent;
                }
            }
            public  Boolean IsRegistered(String fontname)
            {
                return false;
            }
        }
        /// <summary>
        /// 產生PDF
        /// </summary>
        /// <param name="html"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static Boolean HTMLToPDF(string html, String fileName)
        {
            Boolean isOK = false;
            try
            {
                TextReader reader = new StringReader(html);
                // step 1: creation of a document-object
                Document document = new Document(PageSize.A4.Rotate(), 30, 30, 30, 30);
                // step 2:
                // we create a writer that listens to the document
                // and directs a XML-stream to a file
                fileName = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "PDF" + fileName+".pdf";
              FileStream fs=new FileStream(fileName, FileMode.Create,FileAccess.Write,FileShare.ReadWrite);
                PdfWriter writer = PdfWriter.GetInstance(document,fs );
                HTMLWorker worker = new HTMLWorker(document);
                document.Open();
                worker.StartDocument();
                StyleSheet css = new StyleSheet();
                Dictionary<String, Object> font = new Dictionary<string, object>();
                font.Add(HTMLWorker.FONT_PROVIDER,new MyFontFactory());
                Dictionary<String, String> dict= new Dictionary<string, string>();
                dict.Add(HtmlTags.BGCOLOR, "#01366C");
                dict.Add(HtmlTags.COLOR, "#000000");
                dict.Add(HtmlTags.SIZE,"25");
                css.LoadStyle("css", dict);

                List<IElement> p = HTMLWorker.ParseToList(new StreamReader(html), css,font);
                for (int k = 0; k < p.Count; k++)
                {
                    document.Add((IElement)p[k]);
                }
                PdfContentByte pcb = writer.DirectContentUnder;
                pcb.SetRGBColorFill(0, 255, 0);
                pcb.SetRGBColorFill(1, 54, 108);
                pcb.Rectangle(20, 413, 800, 42);
                pcb.Fill();
                worker.EndDocument();
                worker.Close();              
                document.Close();
                reader.Close();
                isOK = true;
            }
            catch (Exception ex)
            {
                isOK = false;
            }
            finally {

            }
            return isOK;
        }
    }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.