a亚洲精品_精品国产91乱码一区二区三区_亚洲精品在线免费观看视频_欧美日韩亚洲国产综合_久久久久久久久久久成人_在线区

首頁 > 編程 > C# > 正文

C#使用itextsharp生成PDF文件的實現代碼

2020-01-24 03:11:24
字體:
來源:轉載
供稿:網友
項目需求需要生成一個PDF文檔,使用的是VS2010,ASP.NET。
網絡上多次搜索沒有自己想要的,于是硬著頭皮到itextpdf官網看英文文檔,按時完成任務,以實用為主,共享一下:
使用HTML文件創建PDF模板:
使用自定義字體的一種方法:
復制代碼 代碼如下:

                FontFactory.Register(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "http://Fonts//RAGE.TTF", "myFont");
                Font myFont = FontFactory.GetFont("myFont");
                BaseFont bf = myFont.BaseFont;

其中RAGE.TTF是微軟操作系統自帶的字體,目錄在C:/Windows/Fonts,建議將需要的字體拷貝到項目中使用,否則會出現引用不到的情況。
使用自定義樣式:
復制代碼 代碼如下:

                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 + "http://Fonts//MSYH.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 + "http://LCPI//Fonts//MSYH.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 + "http://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;
        }
    }
}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 一区二区日韩精品 | 成人一区二区三区视频 | 亚洲综人网 | www.com久久| 日韩一区欧美 | 成人在线视频免费观看 | 久久综合九色综合欧美狠狠 | 欧美日一区二区 | 一区二区三区免费网站 | 日本一区中文字幕 | 色免费视频| 国产精品免费一区二区 | 色爱区综合 | 91久久久久久 | 国产午夜视频 | 97超碰人人在线 | www.久久 | 人人骚 | 日韩成人影院 | 久久久久久久久久久久久久久 | 亚洲免费综合 | 日本激情网 | 亚洲视频 欧美视频 | 91色在线观看| 亚洲欧美在线人成swag | 久久久精品欧美一区二区免费 | 午夜一级 | 一本一本久久a久久精品牛牛影视 | 成人1区2区 | 国产精品久久久久久久午夜 | 午夜精品久久久久久久久久久久久 | 成人欧美一区二区三区在线播放 | av网站观看 | 狠狠做深爱婷婷综合一区 | 综合一区二区三区 | 国产精品久久久久久久久久久免费看 | 天堂成人国产精品一区 | 国产传媒一区 | 理论片一区 | 欧美一区永久视频免费观看 | 久久草视频 |