【前言】 由于公司项目需求,今天接触了c#开发pdf的知识,参考来源于博客:http://www.cnblogs.com/zhuor/archive/2005/12/31/308908.html
使用的类库为:itextsharp.dll
【iTextSharp简介】iTextSharp由国外开发人员出品,官方网站:http://sourceforge.net/projects/itextsharp/?source=typ_redirect
你也可以直接在这里下载相关类库或src文件
压缩文件包含:
【个人开发Demo】下面均为B/S架构下的演示:直接上运行截图+核心代码
Demo v0.0.01 目的:生成一个写有”Hello World!” 的pdf文件
效果图:
实际生成不包含红色边框哦
记得引用:itextsharp.dll
核心实现方法:
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
/// <summary>
/// 创建一个Document
/// </summary>
public void CreateDocument()
{
//创建一个document操作实例
Document document = new Document();
//为该Document类创建一个Writer实例
PdfWriter.GetInstance(document, new FileStream(Server.MapPath("~")+"Chap0101.pdf", FileMode.OpenOrCreate));
//打开document
document.Open();
//向document写入内容
document.Add(new Paragraph("Hello World!"));
//关闭Document
document.Close();
}
Demo v0.0.02 目的: 封装好了PDFHelper类,使用PDF更加方便|可直接创建,写入,自动下载到本地等|可加入显示中文,加入字体库的使用等
源码:请联系我,这里没法直接上传
效果截图:
项目目录:
PDFHelper.cs
using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
/// <summary>
/// PDFHelper
/// 描述:快速操作 PDF文档的帮助类
/// 作者:刘壮
/// 时间:2016-01-13 11:41
/// </summary>
public class PDFHelper
{
//创建一个document
Document document = null;
#region 关于文档属性的基础设置
/// <summary>
/// 文档显示的方向
/// 竖向或横向
/// </summary>
public enum direction { Virtical, Horizontal };
#endregion
#region 构造函数
/// <summary>
/// 创建一个无任何修饰的文档
/// </summary>
/// <param name="_filename">包含后缀的文件名</param>
public PDFHelper(string _filename)
{
document = new Document();
InitPathToOpen(_filename);
}
/// <summary>
/// 实例化一个A4大小的文档
/// </summary>
/// <param name="_filename">包含后缀的文件名</param>
/// <param name="_rectangle">内容区域</param>
public PDFHelper(string _filename, Rectangle _rectangle)
{
//指定内容区域
document = new Document(_rectangle);
//写入权限控制
InitPathToOpen(_filename);
//写入数据
}
#endregion
#region 公共方法
#region document的基础参数配置方法
/// <summary>
/// 初始化路径并打开document的写入权限
/// </summary>
/// <param name="_filename">包含后缀的文件名</param>
private void InitPathToOpen(string _filename)
{
//为该Document类创建一个Writer实例
PdfWriter.GetInstance(document, new FileStream(HttpContext.Current.Server.MapPath("~/PDFS/")+ _filename, FileMode.OpenOrCreate));
//打开document
document.Open();
}
/// <summary>
/// 关闭document
/// </summary>
public void Close()
{
document.Close();
}
/// <summary>
/// 得到一个设置好的字体颜色格式
/// </summary>
/// <param name="_size">字号大小</param>
/// <param name="_alpha">透明度</param>
/// <param name="_red">红色</param>
/// <param name="_green">绿色</param>
/// <param name="_blue">蓝色</param>
/// <param name="_sytle">样式:下划线,加粗,标准?Font.UNDERLINE</param>
/// <returns></returns>
public static Font GetFont(float _size, int _alpha, int _red, int _green, int _blue,int _sytle)
{
//设置字体
BaseFont _bfont = BaseFont.CreateFont(HttpContext.Current.Server.MapPath("~/Fonts") + "\\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//设置字体颜色
System.Drawing.Color _color = System.Drawing.Color.FromArgb(_alpha, _red, _green, _blue);
BaseColor _bColor = new BaseColor(_color.ToArgb());
Font _font = new Font(_bfont, _size, _sytle, _bColor);
return _font;
}
/// <summary>
/// 设置并获取一个标准的Rectangle类
/// 若想设置背景色,边框等样式,请直接新建Rectangle实例详细设置
/// </summary>
/// <param name="_rectangle">区域,可以直接用 PageSize类选择A4等标准大小默认宽高度</param>
/// <param name="_direction">文档方向,横向还是竖向</param>
/// <returns></returns>
public static Rectangle GetRectangle(Rectangle _rectangle, direction _direction)
{
return (_direction == PDFHelper.direction.Horizontal) ? _rectangle.Rotate() : _rectangle;
}
#endregion
#region 添加内容的方法
/// <summary>
/// 添加节点
/// </summary>
/// <param name="_IElement"></param>
public void Add(IElement _IElement)
{
try
{
document.Add(_IElement);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
#endregion
#region 下载文件
/// <summary>
/// 下载PDF文件
/// </summary>
/// <param name="filename">含有后缀的文件名</param>
public void DownloadPDF(string _filename)
{
//服务端存储路径
string filepath = HttpContext.Current.Server.MapPath("~/PDFS/")+_filename;
//以字符流的形式下载文件
byte[] bytes;
using (FileStream fs = new FileStream(filepath,FileMode.Open))
{
bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
}
HttpContext.Current.Response.Charset = "utf-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.ContentType = "application/octet-stream";
//通知浏览器下载|不打开
HttpContext.Current.Response.AddHeader("Content-Disposition","attachment; filename="+HttpUtility.UrlEncode(_filename,System.Text.Encoding.UTF8));
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
/// <summary>
/// 创建文件夹
/// </summary>
/// <returns></returns>
private string CreateDirectory(string _dirName) //要查找的文件夹名
{
string path = "";
string physicsPath = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath); //将当前虚拟根路径转为实际物理路径
string toFindDirectoryName = _dirName; //要查找的文件夹名
FindDirectory(physicsPath + "\\", toFindDirectoryName, out path);//用递归的方式去查找文件夹
if (!string.IsNullOrEmpty(path)) //如果存在,返回该文件夹所在的物理路径
{
//将该物理路径转为虚拟路径
GetVirtualPath(path, HttpContext.Current.Request.ApplicationPath);
}
else
{
//没有找到路径,创建新文件夹
path = physicsPath + "\\" + toFindDirectoryName;
Directory.CreateDirectory(path);
}
return path;
}
/// <summary>
/// 在指定目录下递归查找子文件夹
/// </summary>
/// <param name="bootPath">根文件夹路径</param>
/// <param name="directoryName">要查找的文件夹名</param>
private void FindDirectory(string bootPath, string directoryName, out string filePath)
{
//在指定目录下递归查找子文件夹
DirectoryInfo dir = new DirectoryInfo(bootPath);
filePath = "";
try
{
foreach (DirectoryInfo d in dir.GetDirectories()) //查找子文件夹
{
if (d.Name == directoryName) //找到,返回文件夹路径
{
filePath = d.FullName;
break;
}
FindDirectory(bootPath + d.Name + "\\", directoryName, out filePath); //否则继续查找
}
}
catch (Exception e)
{
HttpContext.Current.Response.Write(e.Message);
}
}
/// <summary>
/// 将物理路径转为虚拟路径
/// </summary>
/// <param name="physicsPath">物理路径</param>
/// <param name="virtualRootPath">虚拟根路径</param>
/// <returns></returns>
private string GetVirtualPath(string physicsPath, string virtualRootPath)
{
int index = physicsPath.IndexOf(virtualRootPath.Substring(1));
return "/" + physicsPath.Substring(index).Replace("\\", "/");
}
#endregion
#endregion
#region 扩展方法
#endregion
}
生成效果图的主要方法:
Default.cs文件中:
/// <summary>
/// 创建一个Document
/// </summary>
public void CreateDocument()
{
//使用PDFHelper类获取标准格式区域
//PDFHelper pdfHelper = new PDFHelper("newpdf.pdf", PDFHelper.GetRectangle(PageSize.A4, PDFHelper.direction.Virtical));
//文件名
string filename = "newpdf.pdf";
//自定义区域
Rectangle r = new Rectangle(PageSize.A4);
r.BorderWidthTop = 10;
r.BorderColorTop = new BaseColor(System.Drawing.Color.Red);
r.BackgroundColor = new BaseColor(System.Drawing.Color.White);
PDFHelper pdfHelper = new PDFHelper(filename,r);
Chunk chunk = new Chunk("PDF生成演示", PDFHelper.GetFont(18,100,100,101,80,Font.NORMAL));
pdfHelper.Add(chunk);
#region 添加一个段落
Chunk chunk1 = new Chunk("刘壮真好123adffadsfa\n真的吗?当然啦", PDFHelper.GetFont(18, 100, 1, 1, 80,Font.NORMAL));
//chunk1.SetBackground(BaseColor.BLUE);
//设置字符间距
chunk1.SetWordSpacing(1f);
//chunk1.SetUnderline(BaseColor.RED, 2f, 1f, 1f, 3f, 2);
//设置下划线的宽度以及针对原始位置的偏移量|有重载方法,可以设置下划线颜色等
chunk1.SetUnderline(1f, -2f);
Paragraph p1 = new Paragraph(chunk1);
pdfHelper.Add(p1);
#endregion
#region 添加一个锚点|外部链接
Anchor anchor = new Anchor("点击打开网址",PDFHelper.GetFont(18,200,0,0,255,Font.UNDERLINE));
anchor.Reference = "http://myggou.com";
anchor.Name = "website";
pdfHelper.Add(anchor);
#endregion
#region 添加一个锚点|内部链接
Anchor anchor1 = new Anchor("Click here to jump to the internal link", PDFHelper.GetFont(18, 200, 0, 0, 133,Font.NORMAL));
anchor1.Reference = "#website";
pdfHelper.Add(anchor1);
#endregion
pdfHelper.Close();
pdfHelper.DownloadPDF(filename);
}
更新待续…