C#使用itextsharp生成PDF文件
项目需求需要生成一个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);
重写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/
C#使用itextsharp生成PDF文件的更多相关文章
- iTextSharp生成PDF文件
这是一篇简单的教程,所以只涉及一些iTextSharp生成pdf的简单应用,详细教程请搜索iTextSharp进入官网看官方文档(英文版). iTextSharp官方文档:https://itextp ...
- 根据PDF模板生成PDF文件(基于iTextSharp)
根据PDF模板生成PDF文件,这里主要借助iTextSharp工具来完成.场景是这样的,假如要做一个电子协议,用过通过在线填写表单数据,然后系统根据用户填写的数据,生成电子档的协议.原理很简单,但是每 ...
- asp.net生成PDF文件 (1)
asp.net生成PDF文件 (1) 这个是例子是网上淘来的,哈哈,很有用的! 首先要到网上下载itextsharp.dll,然后添加引用,主程序如下: 1 2 3 4 5 6 7 8 9 10 11 ...
- itextsharp生成pdf后的直接打印问题
原文 itextsharp生成pdf后的直接打印问题 小弟这两天用itextsharp生成pdf文档,生成的pdf可以直接保存在指定路径的文件夹下,可是user不想保存,想要点一下button,就可以 ...
- C#生成PDF文件流
1.设置字体 static BaseFont FontBase = BaseFont.CreateFont("C:\\WINDOWS\\FONTS\\STSONG.TTF", Ba ...
- 在C#.NET中,如何生成PDF文件?主要有以下几个途径
1.使用.NET文件流技术:若通过.NET的文件流技术生成PDF文件,必须对PDF文件的语法很清楚,例如BT表示实体内容开始:ET表示实体内容结束:TD表示换行等等.我们可以从Adobe的官方网站上下 ...
- linux下编译bib、tex生成pdf文件
实验: 在linux环境下,编译(英文)*.bib和*.tex文件,生成pdf文件. 环境: fedora 20(uname -a : Linux localhost.localdomain 3.19 ...
- ThinkPHP3.2.3扩展之生成PDF文件(MPDF)
目前是PHP生成PDF文件最好的插件了,今天介绍下在ThinkPHP3.2.3里如何使用. 先安照路径放好如图. 下面是使用方法 public function pdf(){ //引入类库 Vendo ...
- [轉載]史上最强php生成pdf文件,html转pdf文件方法
之前有个客户需要把一些html页面生成pdf文件,然后我就找一些用php把html页面围成pdf文件的类.方法是可谓是找了很多很多,什么html2pdf,pdflib,FPDF这些都试过了,但是都没有 ...
随机推荐
- 以前5年只专注于.net,现今开始学习java.
从2011年毕业至今一直在学习.net和c#,大概几年6月份底开始研究java了. 虽然不知道以后的路是否好走,但是我依然会努力.不放弃! 写这篇文字是为了鼓励自己,也为这段时光留下记忆.加油,红红!
- 转:SRIO错误侦测和管理机制
http://www.deyisupport.com/question_answer/dsp_arm/c6000_multicore/f/53/t/22879.aspx http://www.deyi ...
- WebBrowser执行脚本
ExecuteJavaScript(WebBrowser:TWebBrowser; Code: string):Variant;var //发送脚本Document:IHTMLDocument2;Wi ...
- http状态码有那些?分别代表是什么意思
http状态码有那些?分别代表是什么意思? 简单版 [ 100 Continue 继续,一般在发送post请求时,已发送了http header之后服务端将返回此信息,表示确认,之后发送具体参数信息 ...
- 手机低端市场,联发科 vs 高通
联发科(MTK) 是山寨机的源头,我过去曾经鄙视他,现在来了180度转弯. 其实联发科是台湾的上市公司,手机如此复杂的东西,当年 联发科能把基础的手机做出来,而后小山寨厂改改外形,配件就能出若干款手机 ...
- 解决rsyslog 断电或者被kill 重发问题
$InputFilePersistStateInterval 1 Specifies how often the state file shall be written when processing ...
- bzoj4096 [Usaco2013 dec]Milk Scheduling
Description Farmer John has N cows that need to be milked (1 <= N <= 10,000), each of which ta ...
- Hadoop2.4.1 MapReduce通过Map端shuffle(Combiner)完成数据去重
package com.bank.service; import java.io.IOException; import org.apache.hadoop.conf.Configuration;im ...
- spring注解理解
步骤一:编写web.xml文件,主要代码如下:<servlet> Java代码 <servlet-name>spmvc</servlet-name> <ser ...
- UITextView换行问题解决办法
在UITextView中输入数据时常会遇到换行显示问题,不要再xib中输入text内容,要通过代码输入,换行处加上\r\n,即可以实现换行