iTextSharp 使用详解(转) 感谢原著作者 .
2013-09-10 17:20
274 查看
TextSharp是一个生成Pdf文件的开源项目,最近在项目中有使用到这个项目,对使用中的经验作一个小结.
ITextSharp中相关的概念:
一、Document
这个对象有三个构造函数:
隐藏行号复制代码?这是一段程序代码。
publicDocument();
publicDocument(RectanglepageSize,
intmarginLeft,
intmarginRight,
第一个构造函数以A4页面作为参数调用第二个构造函数,第二个构造函数以每边36磅页边距为参数调用调用第三个构造函数。
页面尺寸:
你可以通过指定的颜色和大小创建你自己的页面,示例代码0102创建一个细长的浅黄色背景的页面:
RectanglepageSize=newRectangle(144,720);
pageSize.BackgroundColor=newColor(0xFF,0xFF,0xDE);
Documentdocument=newDocument(pageSize);
通常,你不必创建这样的页面,而可以从下面页面尺寸中选择:
A0-A10,LEGAL,LETTER,HALFLETTER,_11x17,LEDGER,NOTE,B0-B5,ARCH_A-ARCH_E,FLSA和FLSE
大多数情况下使用纵向页面,如果希望使用横向页面,你只须使用rotate()函数:
Documentdocument=newDocument(PageSize.A4.rotate());
详细代码见示例代码0103。
页边距:
当创建一个文件时,你还可以定义上、下、左、右页边距:
Documentdocument=newDocument(PageSize.A5,36,72,108,180);
说明:
当创建一个矩形或设置边距时,你可能希望知道该用什么度量单位:厘米、英寸或象素,事实上,默认的度量系统以排版单位磅为基础得出其他单位的近似值,如1英寸=72磅,如果你想在A4页面的PDF中创建一个矩形,你需要计算以下数据:
21厘米/2.54=8.2677英寸
8.2677英寸*72=595磅
29.7厘米/2.54=11.6929英寸
11.6929英寸*72=842磅
默认边距为36磅即半英寸。
如果你修改了页面尺寸,仅仅影响到下一页,如果你修改了页边距,则影响到全部,故慎用。
二、Writer
一旦创建了document,我们可以创建该文档的多个Writer的实例,所有这些Writer实例均继承自抽象类“iTextSharp.text.DocWriter”。
同时还有另外一种情况,你可以用iTextSharp.text.pdf.PdfWriter产生文档PDF文件,如果你想创建一个TeX文档,你可以使用iTextSharp.text.TeX.TeXWriter包。
Writer类的构造函数是私有的,你只能通过下面的方法创建一个实例:
publicstaticxxxWritergetInstance(Documentdocument,Streamos);(xxx是Pdf或Xml)
你可以通过下面的方法创建一个实例:
PdfWriterwriter=PdfWriter.getInstance(document,newFileStream("Chap01xx.pdf"));
但是你几乎永远不会用到Writer实例(除非你想创建高级PDF或者希望用一些非常特殊的函数,如ViewerPreferences或Encryption)。所以通过下面的办法得到实例已经足够了:PdfWriter.getInstance(document,newFileStream("Chap01xx.pdf"));
在第一步中创建一个文档时,第一个参数意义不大,第二个参数可以是任何一种流,到目前为止我们一直使用System.IO.FileStream将Document写入文件中,示例代码0105用到了System.IO.MemoryStream(这不是一个独立的例子,你必须在ServletEngine中测试这些代码。
文档加密:
publicvoidsetEncryption(booleanstrength,StringuserPassword,StringownerPassword,intpermissions);
·strength是下面两个常量之一:
oPdfWriter.STRENGTH40BITS:40位
oPdfWriter.STRENGTH128BITS:128位(AcrobatReader5.0及以上版本支持)
·UserPassword和ownerPassword可以为空或零长度,这种情况下,ownerPassword将被随机的字符串代替
·Permissions为下列常量之一:
oPdfWriter.AllowPrinting
oPdfWriter.AllowModifyContents
oPdfWriter.AllowCopy
oPdfWriter.AllowModifyAnnotations
oPdfWriter.AllowFillIn
oPdfWriter.AllowScreenReaders
oPdfWriter.AllowAssembly
PdfWriter.AllowDegradedPrinting
三、块(Chunk)
块(Chunk)是能被添加到文档的文本的最小单位,块可以用于构建其他基础元素如短句、段落、锚点等,块是一个有确定字体的字符串,要添加块到文档中时,其他所有布局变量均要被定义。
四、短句(Phrases)
短句(Phrases)是一系列以特定间距(两行之间的距离)作为参数的块,一个短句有一个主字体,但短句中的一些块具有不同于主字体的字体,你有更多的选择去创建短句。
五、段落
段落是一系列块和(或)短句。同短句一样,段落有确定的间距。用户还可以指定缩排;在边和(或)右边保留一定空白,段落可以左对齐、右对齐和居中对齐。添加到文档中的每一个段落将自动另起一行。
说明:一个段落有一个且仅有一个间距,如果你添加了一个不同字体的短句或块,原来的间距仍然有效,你可以通过SetLeading来改变间距,但是段落中所有内容将使用新的中的间距。
更改分割符
通常,当文本不能放在一行时,文本将被分割成不同的部分,iText首先会查找分割符,如果没有找到,文本将在行尾被截断。有一些预定的分割符如“”空格和“-”连字符,但是你可以使用setSplitCharacter方法来覆盖这些默认值。
以使用IndentationLeft和IndentationRight,FirstLineIndent属性设置缩排;
六、锚点(Anchor)
如果你想在文档中添加一个外部链接(例如使用URL链接到WEB上的其他文档),你可以简单地使用Anchor对象,它派生于Phrase对象,使用方法相同。只有两种额外方法定义两种额外变量:setName和setReference。
外部链接示例:
隐藏行号复制代码?这是一段程序代码。
Anchoranchor=newAnchor("website",FontFactory.getFont(FontFactory.HELVETICA,12,Font.UNDERLINE,newColor(0,0,255)));
anchor.Reference=http://itextsharp.sourceforge.net;
anchor.Name="website";
如果你想添加内部链接,你需要选择该链接不同的名称,就象你相位在HTML中利用名称作为锚点一样。为达到该目的,你需要添加一个“#”。
内部链接示例:
隐藏行号复制代码?这是一段程序代码。
Anchoranchor1=newAnchor("Thisisaninternallink");
anchor1.Name="link1";
Anchoranchor2=newAnchor("Clickheretojumptotheinternallink");
anchor.Reference="#link1";
七、列表(List,ListItem)
通过类List和ListItem,你可以添加列表到PDF文件中,对于列表你还可以选择是否排序。
排序列表示例:
隐藏行号复制代码?这是一段程序代码。
Listlist=newList(true,20);
list.Add(newListItem("Firstline"));
list.Add(newListItem("Thesecondlineislongertoseewhathappensoncetheendofthelineisreached.Willitstartonanewline?"));
list.Add(newListItem("Thirdline"));
结果如下:
1.Firstline
2.Thesecondlineislongertoseewhathappensoncetheendofthelineisreached.Willitstartonanewline?
3.Thirdline
不排序示例如下:
隐藏行号复制代码?这是一段程序代码。
Listoverview=newList(false,10);
overview.Add(newListItem("Thisisanitem"));
overview.Add("Thisisanotheritem");
结果如下:
·Thisisanitem
·Thisisanotheritem
可以通过SetListSymbol方法来更改列表符号,可以使用图片或其它对象作为列表符号。
隐藏行号复制代码?这是一段程序代码。
//用字符串作为列表符号
list1.ListSymbol="*";
//用Chunk作为列表符号(包含“•”字符)
list2.ListSymbol=newChunk("\u2022",FontFactory.getFont(FontFactory.HELVETICA,20));
//用图片作为列表符号
list3.ListSymbol=newChunk(Image.getInstance("myBullet.gif"),0,0);
还可以使用IndentationLeft和IndentationRight属性设置缩排,列表符号的缩排使用SymbolIndent属性,也可以在构造函数中设置。
八、注释
你可以添加一小段文本到你的文档中,但它并非文档内容的一部分,注释有标题和内容:
Annotationa=newAnnotation(
"authors",
"Maybeit'sbecauseIwantedtobeanauthormyselfthatIwroteiText.");
外部链接注释:
你需要指定一个可点击的矩形和一个字符串(URL描述)或URL对象:
Annotationannot=newAnnotation(100f,700f,200f,800f,newURL("http://www.lowagie.com"));
Annotationannot=newAnnotation(100f,700f,200f,800f,"http://www.lowagie.com");
外部PDF文件链接注释:
你需要指定一个可点击的矩形和一个字符串(文件名称)和目的文件或页码。
Annotationannot=newAnnotation(100f,700f,200f,800f,"other.pdf","mark");
Annotationannot=newAnnotation(100f,700f,200f,800f,"other.pdf",2);
指定行为链接注释
你需要指定一个可点击的矩形和一个指定的行为:
Annotationannot=newAnnotation(100f,700f,200f,800f,PdfAction.FIRSTPAGE);
u应用程序链接注释:
你需要指定一个可点击的矩形和一个应用程序:
Annotationannot=newAnnotation(300f,700f,400f,800f,"C://winnt/notepad.exe",null,null,null);
我们无须在页面上指定一个位置,iText会内部处理。你能够看到iText添加文本注释在页面上当前位置下面,第一个在段后第一行下面,第二个在短句结束处的下面。
所有其他注释需要指定想匹配的矩形区域,在示例代码0304中,我们画了一些正方形(使用的函数将在第十章中介绍),为每个正方形添加了一些链接注释。
九、页眉页脚
在旧版本中,有HeaderFooter对象就可以设置页眉页脚,但是新版本中,已经不存在这个对象。
新版本中,使用新的对象PdfWriter中有一个对象:PdfEvent对象,它实现了如下接口:
隐藏行号复制代码?这是一段程序代码。
publicinterfaceIPdfPageEvent
{
voidOnChapter(PdfWriterwriter,Documentdocument,floatparagraphPosition,Paragraphtitle);
voidOnChapterEnd(PdfWriterwriter,Documentdocument,floatparagraphPosition);
voidOnCloseDocument(PdfWriterwriter,Documentdocument);
voidOnEndPage(PdfWriterwriter,Documentdocument);
voidOnGenericTag(PdfWriterwriter,Documentdocument,Rectanglerect,stringtext);
voidOnOpenDocument(PdfWriterwriter,Documentdocument);
voidOnParagraph(PdfWriterwriter,Documentdocument,floatparagraphPosition);
voidOnSection(PdfWriterwriter,Documentdocument,floatparagraphPosition,intdepth,Paragraphtitle);
voidOnStartPage(PdfWriterwriter,Documentdocument);
可以在这里面实现。
十、章节(Chapter)和区域(Section)
章节的使用就比较少了,并且不太好控制,这就不作说明
十一、书签
简单创建书签,使用如下代码:
隐藏行号复制代码?这是一段程序代码。
protectedPdfOutlineSetDestination(PdfOutlineroot,Chunkchk,stringname,stringdestination)
{chk.SetLocalDestination(destination);
returnnewPdfOutline(root,PdfAction.GotoLocalPage(destination,false),name);
}
复杂的书签就要使用Pdfaction,PdfOutline,PdfDestination三个对象来创建了。
十二、中文语言支持
中文语言支持,要加入一些扩展dll,加入方法如下所示:
publicstaticvoidRegisterFont()
{if(!_isRegisterFont)
{lock(typeof(TextSharpHelper))
{if(!_isRegisterFont)
{BaseFont.AddToResourceSearch("iTextAsian.dll");
BaseFont.AddToResourceSearch("iTextAsianCmaps.dll");
FontFactory.Register(Environment.GetFolderPath(Environment.SpecialFolder.System)+
@"\..\Fonts\STSONG.ttf");
FontFactory.Register(Environment.GetFolderPath(Environment.SpecialFolder.System)+
@"\..\Fonts\simhei.ttf");
FontFactory.Register(Environment.GetFolderPath(Environment.SpecialFolder.System)+
@"\..\Fonts\simsun.ttc");
_isRegisterFont=true;
}
}
}
}
上面的两个dll是注册中文语言支持,后面是注册系统下的一些中文字体文件。
十三、文字、表格、图像混排
在进行文字、表格、图像混排中,有时比较难控制位置,最好是把文字、表格、图像分别放到不同的段落中,这样才能很好控制位置。
十四、表单写入
读取表单中的域:
隐藏行号复制代码?这是一段程序代码。
publicstaticDictionary<string,string>ReadForm(stringpdfTemplate)
Dictionary<string,string>dic=newDictionary<string,string>();
try
pdfReader=newPdfReader(pdfTemplate);
foreach(KeyValuePair<string,AcroFields.Item>deinpdfFormFields.Fields)
dic.Add(de.Key,"");
finally
if(pdfReader!=null)
pdfReader.Close();
}
returndic;
对表单中的域进行填充:
隐藏行号复制代码?这是一段程序代码。
publicstaticvoidFillForm(stringpdfTemplate,stringnewFile,Dictionary<string,string>dic)
PdfReaderpdfReader=null;
try
pdfReader=newPdfReader(pdfTemplate);
newFile,FileMode.Create));
foreach(KeyValuePair<string,string>deindic)
pdfFormFields.SetField(de.Key,de.Value);
}
{
{
}
if(pdfStamper!=null)
pdfStamper.Close();
}
ITextSharp中相关的概念:
一、Document
这个对象有三个构造函数:
隐藏行号复制代码?这是一段程序代码。
publicDocument(RectanglepageSize);
intmarginTop,
intmarginBottom);
第一个构造函数以A4页面作为参数调用第二个构造函数,第二个构造函数以每边36磅页边距为参数调用调用第三个构造函数。
页面尺寸:
你可以通过指定的颜色和大小创建你自己的页面,示例代码0102创建一个细长的浅黄色背景的页面:
RectanglepageSize=newRectangle(144,720);
pageSize.BackgroundColor=newColor(0xFF,0xFF,0xDE);
Documentdocument=newDocument(pageSize);
通常,你不必创建这样的页面,而可以从下面页面尺寸中选择:
A0-A10,LEGAL,LETTER,HALFLETTER,_11x17,LEDGER,NOTE,B0-B5,ARCH_A-ARCH_E,FLSA和FLSE
大多数情况下使用纵向页面,如果希望使用横向页面,你只须使用rotate()函数:
Documentdocument=newDocument(PageSize.A4.rotate());
详细代码见示例代码0103。
页边距:
当创建一个文件时,你还可以定义上、下、左、右页边距:
Documentdocument=newDocument(PageSize.A5,36,72,108,180);
说明:
当创建一个矩形或设置边距时,你可能希望知道该用什么度量单位:厘米、英寸或象素,事实上,默认的度量系统以排版单位磅为基础得出其他单位的近似值,如1英寸=72磅,如果你想在A4页面的PDF中创建一个矩形,你需要计算以下数据:
21厘米/2.54=8.2677英寸
8.2677英寸*72=595磅
29.7厘米/2.54=11.6929英寸
11.6929英寸*72=842磅
默认边距为36磅即半英寸。
如果你修改了页面尺寸,仅仅影响到下一页,如果你修改了页边距,则影响到全部,故慎用。
二、Writer
一旦创建了document,我们可以创建该文档的多个Writer的实例,所有这些Writer实例均继承自抽象类“iTextSharp.text.DocWriter”。
同时还有另外一种情况,你可以用iTextSharp.text.pdf.PdfWriter产生文档PDF文件,如果你想创建一个TeX文档,你可以使用iTextSharp.text.TeX.TeXWriter包。
Writer类的构造函数是私有的,你只能通过下面的方法创建一个实例:
publicstaticxxxWritergetInstance(Documentdocument,Streamos);(xxx是Pdf或Xml)
你可以通过下面的方法创建一个实例:
PdfWriterwriter=PdfWriter.getInstance(document,newFileStream("Chap01xx.pdf"));
但是你几乎永远不会用到Writer实例(除非你想创建高级PDF或者希望用一些非常特殊的函数,如
在第一步中创建一个文档时,第一个参数意义不大,第二个参数可以是任何一种流,到目前为止我们一直使用System.IO.FileStream将Document写入文件中,示例代码0105用到了System.IO.MemoryStream(这不是一个独立的例子,你必须在ServletEngine中测试这些代码。
文档加密:
publicvoidsetEncryption(booleanstrength,StringuserPassword,StringownerPassword,intpermissions);
·strength是下面两个常量之一:
oPdfWriter.STRENGTH40BITS:40位
oPdfWriter.STRENGTH128BITS:128位(AcrobatReader5.0及以上版本支持)
·UserPassword和ownerPassword可以为空或零长度,这种情况下,ownerPassword将被随机的字符串代替
·Permissions为下列常量之一:
oPdfWriter.AllowPrinting
oPdfWriter.AllowModifyContents
oPdfWriter.AllowCopy
oPdfWriter.AllowModifyAnnotations
oPdfWriter.AllowFillIn
oPdfWriter.AllowScreenReaders
oPdfWriter.AllowAssembly
PdfWriter.AllowDegradedPrinting
三、块(Chunk)
块(Chunk)是能被添加到文档的文本的最小单位,块可以用于构建其他基础元素如短句、段落、锚点等,块是一个有确定字体的字符串,要添加块到文档中时,其他所有布局变量均要被定义。
四、短句(Phrases)
短句(Phrases)是一系列以特定间距(两行之间的距离)作为参数的块,一个短句有一个主字体,但短句中的一些块具有不同于主字体的字体,你有更多的选择去创建短句。
五、段落
段落是一系列块和(或)短句。同短句一样,段落有确定的间距。用户还可以指定缩排;在边和(或)右边保留一定空白,段落可以左对齐、右对齐和居中对齐。添加到文档中的每一个段落将自动另起一行。
说明:一个段落有一个且仅有一个间距,如果你添加了一个不同字体的短句或块,原来的间距仍然有效,你可以通过SetLeading来改变间距,但是段落中所有内容将使用新的中的间距。
更改分割符
通常,当文本不能放在一行时,文本将被分割成不同的部分,iText首先会查找分割符,如果没有找到,文本将在行尾被截断。有一些预定的分割符如“”空格和“-”连字符,但是你可以使用setSplitCharacter方法来覆盖这些默认值。
以使用IndentationLeft和IndentationRight,FirstLineIndent属性设置缩排;
六、锚点(Anchor)
如果你想在文档中添加一个外部链接(例如使用URL链接到WEB上的其他文档),你可以简单地使用Anchor对象,它派生于Phrase对象,使用方法相同。只有两种额外方法定义两种额外变量:setName和setReference。
外部链接示例:
隐藏行号复制代码?这是一段程序代码。
如果你想添加内部链接,你需要选择该链接不同的名称,就象你相位在HTML中利用名称作为锚点一样。为达到该目的,你需要添加一个“#”。
内部链接示例:
隐藏行号复制代码?这是一段程序代码。
七、列表(List,ListItem)
通过类List和ListItem,你可以添加列表到PDF文件中,对于列表你还可以选择是否排序。
排序列表示例:
隐藏行号复制代码?这是一段程序代码。
结果如下:
1.Firstline
2.Thesecondlineislongertoseewhathappensoncetheendofthelineisreached.Willitstartonanewline?
3.Thirdline
不排序示例如下:
隐藏行号复制代码?这是一段程序代码。
结果如下:
·Thisisanitem
·Thisisanotheritem
可以通过SetListSymbol方法来更改列表符号,可以使用图片或其它对象作为列表符号。
隐藏行号复制代码?这是一段程序代码。
还可以使用IndentationLeft和IndentationRight属性设置缩排,列表符号的缩排使用SymbolIndent属性,也可以在构造函数中设置。
八、注释
你可以添加一小段文本到你的文档中,但它并非文档内容的一部分,注释有标题和内容:
Annotationa=newAnnotation(
"authors",
"Maybeit'sbecauseIwantedtobeanauthormyselfthatIwroteiText.");
外部链接注释:
你需要指定一个可点击的矩形和一个字符串(URL描述)或URL对象:
Annotationannot=newAnnotation(100f,700f,200f,800f,newURL("http://www.lowagie.com"));
Annotationannot=newAnnotation(100f,700f,200f,800f,"http://www.lowagie.com");
外部PDF文件链接注释:
你需要指定一个可点击的矩形和一个字符串(文件名称)和目的文件或页码。
Annotationannot=newAnnotation(100f,700f,200f,800f,"other.pdf","mark");
Annotationannot=newAnnotation(100f,700f,200f,800f,"other.pdf",2);
指定行为链接注释
你需要指定一个可点击的矩形和一个指定的行为:
Annotationannot=newAnnotation(100f,700f,200f,800f,PdfAction.FIRSTPAGE);
u应用程序链接注释:
你需要指定一个可点击的矩形和一个应用程序:
Annotationannot=newAnnotation(300f,700f,400f,800f,"C://winnt/notepad.exe",null,null,null);
我们无须在页面上指定一个位置,iText会内部处理。你能够看到iText添加文本注释在页面上当前位置下面,第一个在段后第一行下面,第二个在短句结束处的下面。
所有其他注释需要指定想匹配的矩形区域,在示例代码0304中,我们画了一些正方形(使用的函数将在第十章中介绍),为每个正方形添加了一些链接注释。
九、页眉页脚
在旧版本中,有HeaderFooter对象就可以设置页眉页脚,但是新版本中,已经不存在这个对象。
新版本中,使用新的对象PdfWriter中有一个对象:PdfEvent对象,它实现了如下接口:
隐藏行号复制代码?这是一段程序代码。
voidOnParagraphEnd(PdfWriterwriter,Documentdocument,floatparagraphPosition);
voidOnSectionEnd(PdfWriterwriter,Documentdocument,floatparagraphPosition);
}
可以在这里面实现。
十、章节(Chapter)和区域(Section)
章节的使用就比较少了,并且不太好控制,这就不作说明
十一、书签
简单创建书签,使用如下代码:
隐藏行号复制代码?这是一段程序代码。
returnnewPdfOutline(root,PdfAction.GotoLocalPage(destination,false),name);
}
复杂的书签就要使用Pdfaction,PdfOutline,PdfDestination三个对象来创建了。
十二、中文语言支持
中文语言支持,要加入一些扩展dll,加入方法如下所示:
{if(!_isRegisterFont)
{lock(typeof(TextSharpHelper))
{if(!_isRegisterFont)
{BaseFont.AddToResourceSearch("iTextAsian.dll");
BaseFont.AddToResourceSearch("iTextAsianCmaps.dll");
FontFactory.Register(Environment.GetFolderPath(Environment.SpecialFolder.System)+
@"\..\Fonts\STSONG.ttf");
FontFactory.Register(Environment.GetFolderPath(Environment.SpecialFolder.System)+
@"\..\Fonts\simhei.ttf");
FontFactory.Register(Environment.GetFolderPath(Environment.SpecialFolder.System)+
@"\..\Fonts\simsun.ttc");
_isRegisterFont=true;
}
}
}
}
上面的两个dll是注册中文语言支持,后面是注册系统下的一些中文字体文件。
十三、文字、表格、图像混排
在进行文字、表格、图像混排中,有时比较难控制位置,最好是把文字、表格、图像分别放到不同的段落中,这样才能很好控制位置。
十四、表单写入
读取表单中的域:
隐藏行号复制代码?这是一段程序代码。
{
PdfReaderpdfReader=null;
{
AcroFieldspdfFormFields=pdfReader.AcroFields;
{
}
}
{
{
}
}
对表单中的域进行填充:
隐藏行号复制代码?这是一段程序代码。
{
PdfStamperpdfStamper=null;
{
pdfStamper=newPdfStamper(pdfReader,newFileStream(
AcroFieldspdfFormFields=pdfStamper.AcroFields;
{
}
pdfStamper.FormFlattening=true;
finally
if(pdfReader!=null)
pdfReader.Close();
{
}
}
相关文章推荐
- iTextSharp 使用详解(转) 感谢原著作者
- 诺基亚E71使用技巧大全 转帖 感谢作者
- iTextSharp 使用详解(转)
- iTextSharp 使用详解(转)
- iTextSharp 使用详解
- iTextSharp 使用详解
- iTextSharp 使用详解(转)
- iTextSharp 使用详解&用C#制作PDF文件全攻略
- iTextSharp 使用详解(转)
- iTextSharp 使用详解
- iTextSharp 使用详解(转)
- iTextSharp 使用详解
- pdf详解 iTextSharp 使用详解
- iTextSharp 使用详解(转)
- iTextSharp 使用详解
- iTextSharp 使用详解
- iTextSharp 使用详解(转)
- const使用详解 作者:康建东
- iTextSharp 使用详解
- 转帖文章(感谢作者)-pyenv安 3ff0 装与使用-多版本python共存解决方法