项目需求需要生成一个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. arm linux上的第一个应用程序 BOA移植

    1. 首先, linux在开发板上能跑起来了. 包括网络驱动也有了, ifconfig之后, 能看到在rcS里面设置的IP, 也能ping通windows主机了, 当然, 也要window关掉防火墙才 ...

  2. C#中struct与class的区别详解

    转自:http://blog.csdn.net/justlovepro/archive/2007/11/02/1863734.aspx 有这么几点不同: 1.struct 是值类型,class是对象类 ...

  3. 三分钟PJ隐藏SSID无线网络

    一般来说用户可以通过路由或主机设置来隐藏无线信号的SSID网络信息,在这种情况下我们使用XP系统自带的无线信号扫描工具将看不到该无线网络的踪影,在这种情况下XP系统无线信号管理工具只能够看到将SSID ...

  4. poj 3130 How I Mathematician Wonder What You Are!

    http://poj.org/problem?id=3130 #include <cstdio> #include <cstring> #include <algorit ...

  5. 介绍PS大局观很不错的转文

    http://blog.chinaunix.net/uid-20535506-id-1931615.html PowerShell初探 PowerShell的一些特点: ü         内含上百种 ...

  6. poj2063 Investment(多次完全背包)

    http://poj.org/problem?id=2063 多次完全背包~ #include <stdio.h> #include <string.h> #define MA ...

  7. 【HDOJ】2526 浪漫手机

    字符串大水题. #include <cstdio> #include <cstring> #include <cstdlib> #define MAXN 105 t ...

  8. Delphi 调试Dll报错 通过GetLastError显示错误信息。

    LibHandle := LoadLibrary('c:\windows\system32\SpcClass.dll');  ShowMessage(SysErrorMessage(GetLastEr ...

  9. linux image writes boot log to console

  10. C - Critical Links - uva 796(求桥)

    题意:有一些网络通过一些线路连接,求关键的连接,也就是桥,如果删除这个链接那么会产生两个子树 分析:注意一下图不是连通图即可 ************************************* ...