基於iTextSharp的PDF操作(PDF打印,PDF下載)
准備
1. iTextSharp的簡介
iTextSharp是一個移植於java平台的iText項目,被封裝成c#的組件來用於C#生成PDF文檔,目前,也有不少操作PDF的類庫,(國產的有福盺的,免費試用,用於商業用途收費)但是功能普遍沒有iText強大,而且使用沒有iText廣泛。還有他就是開源的。目前比較新的是5.5版本的。
2. 使用工具
硬件:
PC機:一台
軟件:
Windows操作系統
Isual studio 2013 (可以是任意版本)
.Net frameWork 4.5 (可以是任意版本)
iTextSharp 5.5 可以到官網下載(iTextSharp)http://sourceforge.net/projects/itextsharp/

下載后,解壓得到iTextSharp.dll文件
基本知識
1. 主要對象
1).Document 對象:
Document 對象主要用於操作頁面的大小,就是頁面的尺寸。頁面的尺寸一般有以下幾種:
A0-A10, LEGAL, LETTER, HALFLETTER, _11x17, LEDGER, NOTE, B0-B5, ARCH_A-ARCH_E, FLSA 和 FLSE,例如,需要創建一個A4紙張大小的PDF文檔:
Document document = new Document(PageSize.A4);
這個文檔漠然是縱向的,如果滿足不了你橫向文檔的需要,可以加上rotate屬性。
有的時候,我們需要生成特定顏色的,特定大小的PDF文檔,可以使用下面的方法
Rectangle pageSize = new Rectangle(120, 520); //120*520規格
pageSize.BackgroundColor = new Color(0xFF, 0xFF, 0xDE); //背景色
Document document = new Document(pageSize); //新建Documen對象
頁邊距:
Document document = new Document(PageSize.A5, 36, 72, 108, 180);//默認單位為磅。
2).PdfWriter對象:
創建了Documen對象后,我們就要對PDF文檔進行操作(合並,刪除,更改,添加內容等)。這個時候必須創建PdfWriter對象實例。PdfWriter類對對象繼承自iTextSharp.text.DocWriter抽象類。如果需要創建Ext文件,則需要iTextSharp.text.TeX.TeXWriter這個類。
//注意FileMode-Create表示如果目標文件不存在,則創建,如果已存在,則覆蓋。
PdfWriter writer = PdfWriter.GetInstance(document,
new FileStream(strFileName, FileMode.Create));
如代碼所示,創建成功了一個PDF的PdfWriter實例。 FileMode.Create:表示如果目標文件不存在,則創建,如果已存在,則覆蓋。FileMode.New 表示新建,FileMode.Append表示追加,如果你是操作PDF模版,你可以使用Append。
PdfPTable對象,
我們需要用到的屬性:
/// <param name="sdr_Context">List</param>
/// <param name="title">標題名稱</param>
/// <param name="fontpath_Title">標題字體路徑</param>
/// <param name="fontsize_Title">標題字體大小</param>
/// <param name="fontStyle_Title">標題樣式</param>
/// <param name="fontColor_Title">標題顏色</param>
/// <param name="fontpath_Col">列頭字體路徑</param>
/// <param name="fontsize_Col">列頭字體大小</param>
/// <param name="fontStyle_Col">列頭字體樣式</param>
/// <param name="fontColor_Col">列頭字體顏色</param>
/// <param name="col_Width">表格總寬度</param>
/// <param name="arr_Width">每列的寬度</param>
/// <param name="pdf_Filename">在服務器端保存PDF時的文件名</param>
/// <param name="FontPath">正文字體路徑</param>
/// <param name="FontSize">正文字體大小</param>
/// <param name="fontStyle_Context">正文字體樣式</param>
/// <param name="fontColor_Context">正文字體顏色</param>
方法(長長的,可以封裝成對象):
public void exp_Pdf( List<Customer> sdr_Context, string title, string fontpath_Title, float fontsize_Title, int fontStyle_Title,
BaseColor fontColor_Title, string fontpath_Col, float fontsize_Col, int fontStyle_Col, BaseColor fontColor_Col, float col_Width,
int[] arr_Width, string pdf_Filename, string FontPath, float FontSize, int fontStyle_Context, BaseColor fontColor_Context)
2.基本屬性設置
字體顏色等
//在服務器端保存PDF時的文件名
string strFileName = pdf_Filename + ".pdf";
//初始化一個目標文檔類
Document document = new Document(PageSize.A4.Rotate(), 0, 0, 10, 10);
//調用PDF的寫入方法流
//注意FileMode-Create表示如果目標文件不存在,則創建,如果已存在,則覆蓋。
PdfWriter writer = PdfWriter.GetInstance(document,
new FileStream(strFileName, FileMode.Create));
//標題字體
BaseFont basefont_Title = BaseFont.CreateFont(
fontpath_Title,
BaseFont.IDENTITY_H,
BaseFont.NOT_EMBEDDED);
Font font_Title = new Font(basefont_Title, fontsize_Title, fontStyle_Title, fontColor_Title);
//表格列字體
BaseFont basefont_Col = BaseFont.CreateFont(
fontpath_Col,
BaseFont.IDENTITY_H,
BaseFont.NOT_EMBEDDED);
Font font_Col = new Font(basefont_Col, fontsize_Col, fontStyle_Col, fontColor_Col);
//正文字體
BaseFont basefont_Context = BaseFont.CreateFont(
FontPath,
BaseFont.IDENTITY_H,
BaseFont.NOT_EMBEDDED);
Font font_Context = new Font(basefont_Context, FontSize, fontStyle_Context, fontColor_Context);
3.打開文檔
//打開目標文檔對象document.PageNumber
document.Open();
//添加標題
Paragraph p_Title = new Paragraph(title, font_Title);
p_Title.Alignment = Element.ALIGN_CENTER;
p_Title.IndentationLeft = 200;
p_Title.PaddingTop = 300;
p_Title.ExtraParagraphSpace = 300;
p_Title.SpacingAfter = 100;
document.Add(p_Title);
4.生成表格
//根據數據表內容創建一個PDF格式的表
PdfPTable table = new PdfPTable(5); //1
table.TotalWidth = col_Width;//表格總寬度
table.LockedWidth = true;//鎖定寬度
table.SetWidths(arr_Width);//設置每列寬度
//構建列頭
//設置列頭背景色
table.DefaultCell.BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY;
//設置列頭文字水平、垂直居中
table.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
table.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
// 告訴程序這行是表頭,這樣頁數大於1時程序會自動為你加上表頭。
table.HeaderRows = 1;
table.AddCell(new Phrase("222222", font_Col));
table.AddCell(new Phrase("222222", font_Col));
table.AddCell(new Phrase("222222", font_Col));
table.AddCell(new Phrase("222222", font_Col));
table.AddCell(new Phrase("222222", font_Col));
// 添加數據
//設置標題靠左居中
table.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
// 設置表體背景色
table.DefaultCell.BackgroundColor = BaseColor.WHITE;
for (int i = 0; i < sdr_Context.Count(); i++)
{
table.AddCell(new Phrase(sdr_Context[i].Id.ToString(), font_Context));
table.AddCell(new Phrase(sdr_Context[i].Name, font_Context));
table.AddCell(new Phrase(sdr_Context[i].Place, font_Context));
table.AddCell(new Phrase(sdr_Context[i].Address, font_Context));
table.AddCell(new Phrase(sdr_Context[i].Address, font_Context));
}
5.把表格加進文檔
document.Add(table);
6.關閉文檔
//關閉目標文件
document.Close();
//關閉寫入流
writer.Close();
7.直接打印預覽
MemoryStream PDFData = new MemoryStream(data);
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.ClearContent();
System.Web.HttpContext.Current.Response.ClearHeaders();
System.Web.HttpContext.Current.Response.ContentType = "application/pdf";
System.Web.HttpContext.Current.Response.Charset = string.Empty;
System.Web.HttpContext.Current.Response.Cache.SetCacheability(System.Web.HttpCacheability.Public);
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition",
"inline; filename=" + strFileName.Replace(" ", "").Replace(":", "-") + ".pdf");
System.Web.HttpContext.Current.Response.OutputStream.Write(PDFData.ToArray(), 0, PDFData.ToArray().Length);
System.Web.HttpContext.Current.Response.OutputStream.Flush();
System.Web.HttpContext.Current.Response.OutputStream.Close();
8.如果需要下載
try
{
//這里是你文件在項目中的位置,根目錄下就這么寫
String FullFileName = strFileName;
FileInfo DownloadFile = new FileInfo(FullFileName);
//System.Web.HttpContext.Current.Response.Clear();
//System.Web.HttpContext.Current.Response.ClearHeaders();
//System.Web.HttpContext.Current.Response.Buffer = true;
//System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
//System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename="
// + System.Web.HttpUtility.UrlEncode(DownloadFile.FullName, System.Text.Encoding.UTF8));
//System.Web.HttpContext.Current.Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
//System.Web.HttpContext.Current.Response.WriteFile(DownloadFile.FullName);
}
catch (Exception)
{
throw;
}
finally
{
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.End();
}
9.實現第X頁 共X頁
舊的的iTextSharp版本和新的版本不一樣,主要是通過頁眉和頁腳實現。
public class HeaderAndFooterEvent : PdfPageEventHelper, IPdfPageEvent
{
public static PdfTemplate tpl;
public static bool PAGE_NUMBER = false;
iTextSharp.text.Font font = BaseFontAndSize("黑體", 10, Font.NORMAL, BaseColor.BLACK);
//關閉PDF文檔時
public override void OnCloseDocument(PdfWriter writer, Document document)
{
BaseFont bf = BaseFont.CreateFont(@"c:\\windows\\FONTS\\simsun.ttc,1", BaseFont.IDENTITY_H, false); //調用的字體
tpl.BeginText();
tpl.SetFontAndSize(bf, 10);//生成的模版的字體、顏色
tpl.ShowText((writer.PageNumber - 1).ToString());//模版顯示的內容
tpl.EndText();
tpl.ClosePath();
}
//重寫 關閉一個頁面時
public override void OnEndPage(PdfWriter writer, Document document)
{
if (PAGE_NUMBER)
{
// Phrase header = new Phrase("PDF測試生成頁眉分析報告", font);
Phrase header = new Phrase("第" + (writer.PageNumber) + "頁/共 頁", font);
PdfContentByte cb = writer.DirectContent; //模版 顯示總共頁數
cb.AddTemplate(tpl, document.Right - 140 + document.LeftMargin - 70, document.Top + 40);//調節模版顯示的位置
//頁眉顯示的位置
ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, header,
document.Right - 140 + document.LeftMargin-80, document.Top +40, 0);
}
}
//重寫 打開一個新頁面時
public override void OnStartPage(PdfWriter writer, Document document)
{
if (PAGE_NUMBER)
{
writer.PageCount = writer.PageNumber;
}
}
//定義字體 顏色
public static Font BaseFontAndSize(string font_name, int size, int style, BaseColor baseColor)
{
BaseFont baseFont;
Font font = null;
string file_name = "";
int fontStyle;
switch (font_name)
{
case "黑體":
file_name = "SIMHEI.TTF";
break;
case "華文中宋":
file_name = "STZHONGS.TTF";
break;
case "宋體":
file_name = "SIMYOU.TTF";
break;
default:
file_name = "SIMYOU.TTF";
break;
}
baseFont = BaseFont.CreateFont(@"c:/windows/fonts/" + file_name, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//字體:黑體
if (style < -1)
{
fontStyle = Font.NORMAL;
}
else
{
fontStyle = style;
}
font = new Font(baseFont, size, fontStyle, baseColor);
return font;
}
//定義輸出文本
public static Paragraph InsertTitleContent(string text)
{
iTextSharp.text.Font font = BaseFontAndSize("華文中宋", 16, Font.BOLD,BaseColor.BLACK);
//BaseFont bfSun = BaseFont.CreateFont(@"c:\windows\fonts\STZHONGS.TTF", BaseFont.IDENTITY_H, false); //調用的字體
//Font font = new Font(bfSun, 15);
Paragraph paragraph = new Paragraph(text, font);//新建一行
paragraph.Alignment = Element.ALIGN_CENTER;//居中
paragraph.SpacingBefore = 5;
paragraph.SpacingAfter = 5;
paragraph.SetLeading(1, 2);//每行間的間隔
return paragraph;
}
}
運行結果:



注:如需要源代碼,請關注百度貼吧,然后發帖支持作者(軟件頻道)http://tieba.baidu.com/f?kw=%C8%ED%BC%FE%C6%B5%B5%C0&fr=index,最后找作者要代碼:QQ:763630473
