项目需求需要生成一个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;
}
}
}

itextpdf官网: http://itextpdf.com/

THE END


C#使用itextsharp生成PDF文件的更多相关文章

  1. iTextSharp生成PDF文件

    这是一篇简单的教程,所以只涉及一些iTextSharp生成pdf的简单应用,详细教程请搜索iTextSharp进入官网看官方文档(英文版). iTextSharp官方文档:https://itextp ...

  2. 根据PDF模板生成PDF文件(基于iTextSharp)

    根据PDF模板生成PDF文件,这里主要借助iTextSharp工具来完成.场景是这样的,假如要做一个电子协议,用过通过在线填写表单数据,然后系统根据用户填写的数据,生成电子档的协议.原理很简单,但是每 ...

  3. asp.net生成PDF文件 (1)

    asp.net生成PDF文件 (1) 这个是例子是网上淘来的,哈哈,很有用的! 首先要到网上下载itextsharp.dll,然后添加引用,主程序如下: 1 2 3 4 5 6 7 8 9 10 11 ...

  4. itextsharp生成pdf后的直接打印问题

    原文 itextsharp生成pdf后的直接打印问题 小弟这两天用itextsharp生成pdf文档,生成的pdf可以直接保存在指定路径的文件夹下,可是user不想保存,想要点一下button,就可以 ...

  5. C#生成PDF文件流

    1.设置字体 static BaseFont FontBase = BaseFont.CreateFont("C:\\WINDOWS\\FONTS\\STSONG.TTF", Ba ...

  6. 在C#.NET中,如何生成PDF文件?主要有以下几个途径

    1.使用.NET文件流技术:若通过.NET的文件流技术生成PDF文件,必须对PDF文件的语法很清楚,例如BT表示实体内容开始:ET表示实体内容结束:TD表示换行等等.我们可以从Adobe的官方网站上下 ...

  7. linux下编译bib、tex生成pdf文件

    实验: 在linux环境下,编译(英文)*.bib和*.tex文件,生成pdf文件. 环境: fedora 20(uname -a : Linux localhost.localdomain 3.19 ...

  8. ThinkPHP3.2.3扩展之生成PDF文件(MPDF)

    目前是PHP生成PDF文件最好的插件了,今天介绍下在ThinkPHP3.2.3里如何使用. 先安照路径放好如图. 下面是使用方法 public function pdf(){ //引入类库 Vendo ...

  9. [轉載]史上最强php生成pdf文件,html转pdf文件方法

    之前有个客户需要把一些html页面生成pdf文件,然后我就找一些用php把html页面围成pdf文件的类.方法是可谓是找了很多很多,什么html2pdf,pdflib,FPDF这些都试过了,但是都没有 ...

随机推荐

  1. 【结构型】Facade模式

    外观模式主要意图是为子系统提供一个统一的接口,从而使用用户对子系统的直接依赖中,解耦合出来.Facade主要是通过为子系统统一封装个入口一样,原先用户对子系统的接口.类等都是直接访问,现在要通过Fac ...

  2. Jackknife,Bootstraping, bagging, boosting, AdaBoosting, Rand forest 和 gradient boosting的区别

    引自http://blog.csdn.net/xianlingmao/article/details/7712217 Jackknife,Bootstraping, bagging, boosting ...

  3. nodejs 记入

    1. vs2015 使用最新的 nodejs refer : http://josharepoint.com/2016/05/04/how-to-configure-visual-studio-201 ...

  4. python常用数据结构的常用操作

    作为基础练习吧.列表LIST,元组TUPLE,集合SET,字符串STRING等等,显示,增删,合并... #===========List===================== shoplist ...

  5. Delphi判断进程是否存在(使用CreateToolhelp32Snapshot)

      program Project2; uses windows,TLHelp32; function FindProcess(AFileName:string):boolean; var hSnap ...

  6. rsyslog 日志服务器接收日志权限问题

    rsyslog 权限: 默认 [root@dr-mysql01 zjzc_log]# ls -ltr zj-frontend0*-access*27 -rw------- 1 root root 32 ...

  7. iOS项目更新之升级Xcode7 & iOS9

    金田 前言      Apple 的WWDC所发布内容在给大家带来惊喜之际,给各位iOS开发的同仁却也带来了不同程度的麻烦.首先不讲新功能,就单指原来老版本的项目升级.代码升级,就是一堆问题,而且是不 ...

  8. [LeetCode] 179. Largest Number 解题思路

    Given a list of non negative integers, arrange them such that they form the largest number. For exam ...

  9. zabbix discovery

    preface(见面礼): 仅扫tcp端口: netstat -tnlp|egrep -i "$1"

  10. java——Arrays.asList()方法

    Arrays.asList() 是将数组作为列表 问题来源于: public class Test { public static void main(String[] args) { int[] a ...