项目需求需要生成一个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. Linq延迟执行

    LINQ中大部分查询运算符都有一个非常重要的特性:延迟执行.这意味着,他们不是在查询创建的时候执行,而是在遍历的时候执行(换句话说,当enumerator的MoveNext方法被调用时).让我们考虑下 ...

  2. uva 10020 Minimal coverage

    http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&p ...

  3. 51单片机 Keil C 延时程序的简单研究

    应用单片机的时候,经常会遇到需要短时间延时的情况.需要的延时时间很短,一般都是几十到几百微妙(us).有时候还需要很高的精度,比如用单片机驱动DS18B20的时候,误差容许的范围在十几us以内,不然很 ...

  4. DACL, NULL or not NULL

    上周 hBifTs在折腾他的文件映射封装类的时候,碰到了不能在 ASP.NET 中直接打开由桌面程序创建的内核对象的问题. 内存映射文件与用户权限 他当时是的方法是修改 ASP.NET 配置文件,让 ...

  5. Collections.shuffle源码阅读

    java.util.Collections /** * Randomly permutes the specified list using a default source of * randomn ...

  6. 2014-07-30 MVC框架中对SQL Server数据库的访问

    今天是在吾索实习的第16天.我自己主要学习了基于MVC框架的系统的开发时,对SQL Server数据库的相关访问.其步骤如下: 第一步,在Models文件夹中创建一个类,并命名为Movies.cs,如 ...

  7. USACO6.4-Electric Fences:计算几何

    Electric Fences Kolstad & Schrijvers Farmer John has decided to construct electric fences. He ha ...

  8. C plus plus primer plus

    1,运算符,操作数; 使用相同的符号(基本运算符,+ - * /  %),进行多种操作(指使用一个运算符符号,对不用类型的变量进行操作,int ,float,double),此概念将运算符的重载(op ...

  9. freeCMS学习网站

    https://code.google.com/p/freecms/downloads/list

  10. Android中theme.xml与style.xml的区别

    一.相同点 两者的定义相同.继承方式也相同 <?xml version="1.0" encoding="utf-8"?> <resources ...