C#使用itextsharp生成PDF文件的实现代码

Hedva ·
更新时间:2024-11-15
· 818 次阅读

项目需求需要生成一个PDF文档,使用的是VS2010,ASP.NET。
网络上多次搜索没有自己想要的,于是硬着头皮到itextpdf官网看英文文档,按时完成任务,以实用为主,共享一下:
使用HTML文件创建PDF模板:
使用自定义字体的一种方法:
代码如下:
                FontFactory.Register(System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "\\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 + "\\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;
            & nbsp;   }
            }
            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 + "\\LCPI\\Fonts\\MSYH.ttf";
                    BaseFont bf3 = BaseFont.CreateFont(fontpath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
           &nb sp;        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();
        & nbsp;       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;
        }
    }
}

您可能感兴趣的文章:C# 利用Aspose.Words.dll将 Word 转成PDFC#使用iTextSharp封装的PDF文件操作类实例C# 生转换网页为pdfC# 中使用iTextSharp组件创建PDF的简单方法C#将jpg转换为pdf的方法C#使用iTextSharp从PDF文档获取内容的方法C#实现pdf导出 .Net导出pdf文件C#实现HTML转WORD及WORD转PDF的方法用C#来解析PDF文件C#使用private font改变PDF文件的字体详解



itextsharp C# pdf

需要 登录 后方可回复, 如果你还没有账号请 注册新账号