欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-20 13:18:28
项目需求需要生成一个pdf文档,使用的是vs2010,asp.net。网络上多次搜索没有自己想要的,于是硬着头皮到itextpdf官网看英文文档,按时完成任务,以实用为主,...
项目需求需要生成一个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;
                }
            }
            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);
                    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;
        }
    }
}

上一篇:

下一篇: