开源免费且稳定实用的.NET PDF打印组件itextSharp(.NET组件介绍之八)

本文原创自news.mkq.online
版权声明:本文为原创文章,版权牛站新闻所有
转载请注明http://www.niuzhan.com/Bago/
在这个.NET组件的介绍系列中,受到了很多园友的支持,一些园友(如:数据之巅、 [秦时明月]等等这些大神 )也给我提出了对应的建议,我正在努力去改正,有不足之处还望大家多多包涵。在传播一些简单的知识的同时,我自己也得到了一些提升,这个是我感觉到的最大的益处。知识需要传播,在传播的过程中去让学习的人去提升,在交流中的过程中去让思考的人去展望,我希望我也能在这个传播的过程中出一份力。由于自身能力有限,在编写博文时出现的错误和一些不到位的讲解,还望大家多多见谅。

上面卖完情怀,下面就该切入正题了。

提到打印,恐怕对于很多人都不会陌生,无论是开发者,还是非计算机专业的人员都会接触到打印。对于项目开发中使用到打印的地方会非常多,在.NET项目中,选择打印的方式比较多,例如原始的IE网页打印、水晶报表、JS插件实现打印、导出文档打印,以及今天提到的使用itextSharp组件实现PDF打印等等。

在.NET中实现PDF打印的组件比较多,例如PDFsharp、Report.NET、sharpPDF、itextSharp等等,今天主要简单的介绍itextSharp组件。

一.itextSharp组件概述:

1.iText的是PDF库,它允许你创建,调整,检查和维护的可移植文档格式文件(PDF):

    (1).基于从XML文件或数据库中的数据生成文件和报告。

    (2).创建地图和书籍,利用众多的互动在PDF可用的功能。

    (3).添加书签,页码,水印等功能,以现有的PDF文件。

    (4).从现有PDF文件拆分或连接页面;填写交互式表单。

    (5).即成动态生成或操纵PDF文档到Web浏览器。  

iText所使用的的Java,.NET,Android和GAE开发人员加强与PDF功能的应用程序。iTextSharp的是.NET端口。

2.itextSharp的一些特征:

   (1).PDF生成。

   (2).PDF操作(冲压水印,合并/拆分PDF文件,...)。

   (3).PDF表单填写。

   (4).XML功能。

   (5).数字签名。

以上是对itextSharp组件的一些特性的简单介绍,如果需要更加深入的了解itextSharp组件的相关信息,可以细致的查看API文档和itextSharp产品介绍。https://sourceforge.net/projects/itextsharp/#overview

二.itextSharp组件核心类和方法:

谈到打印,在我们的项目中需要首先考虑的是我们需要打印的东西是什么。在大脑里面应该首先有一个文档的概念,在我们编程的过程中,“文档”这个词无处不在,这个可以是一个宽泛的概念,也可以是一个狭窄的概念,宽泛的“文档”是指容器,用以存放一些元素;狭窄的“文档”是指实际的文件类型。

对于打印的“文档”,具体看一下宽泛的概念,文档包含元素和节点等等。在组织打印的时候,我们需要创建文档,写入元素和节点等信息,最后组合成为我们需要打印的内容。itextSharp组件可以插入段落、表格、图片等等信息,可以很方便的完成我们需要完成的功能。

Paragraph:报表中的文本;Image:报表中的图片;PdfPTable:表格;PdfPCell:单元格。

1.Document类Open()方法:打开文档对象。

01
public virtual void Open()
02
{
03
if (!this.close)
04
{
05
this.open = true;
06
}
07
foreach (IDocListener listener in this.listeners)
08
{
09
listener.SetPageSize(this.pageSize);
10
listener.SetMargins(this.marginLeft, this.marginRight, this.marginTop, this.marginBottom);
11
listener.Open();
12
}
13
}
以上的代码可以看到,我们在打开文档的时候,会设置文档大小,文档页边距等信息。

2.Paragraph类Add()方法:向段落添加元素。

01
public override bool Add(IElement o)
02
{
03
if (o is List)
04
{
05
List element = (List) o;
06
element.IndentationLeft += this.indentationLeft;
07
element.IndentationRight = this.indentationRight;
08
base.Add(element);
09
return true;
10
}
11
if (o is Image)
12
{
13
base.AddSpecial((Image) o);
14
return true;
15
}
16
if (o is Paragraph)
17
{
18
base.Add(o);
19
IList<Chunk> chunks = this.Chunks;
20
if (chunks.Count > 0)
21
{
22
Chunk chunk = chunks[chunks.Count - 1];
23
base.Add(new Chunk("\n", chunk.Font));
24
}
25
else
26
{
27
base.Add(Chunk.NEWLINE);
28
}
29
return true;
30
}
31
base.Add(o);
32
return true;
33
}
01
public interface IElement
02
{
03
// Methods
04
bool IsContent();
05
bool IsNestable();
06
bool Process(IElementListener listener);
07
string ToString();
08

09
// Properties
10
IList<Chunk> Chunks { get; }
11
int Type { get; }
12
}
以上的add()方法是向段落添加元素,我们可以看到参数是个接口“IElement”,我们接下来看一下这个接口,接口主要元素是块。我们看到在向段落添加元素时,可以添加List,Image,Paragraph,Chunk。

3.Image.GetInstance()获取图片实例。

01
public static Image GetInstance(Image image)
02
{
03
if (image == null)
04
{
05
return null;
06
}
07
return (Image) image.GetType().GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(Image) }, null).Invoke(new object[] { image });
08
}
09

10

11
public static Image GetInstance(byte[] imgb)
12
{
13
int num = imgb[0];
14
int num2 = imgb[1];
15
int num3 = imgb[2];
16
int num4 = imgb[3];
17
if (((num == 0x47) && (num2 == 0x49)) && (num3 == 70))
18
{
19
GifImage image = new GifImage(imgb);
20
return image.GetImage(1);
21
}
22
if ((num == 0xff) && (num2 == 0xd8))
23
{
24
return new Jpeg(imgb);
25
}
26
if (((num == 0) && (num2 == 0)) && ((num3 == 0) && (num4 == 12)))
27
{
28
return new Jpeg2000(imgb);
29
}
30
if (((num == 0xff) && (num2 == 0x4f)) && ((num3 == 0xff) && (num4 == 0x51)))
31
{
32
return new Jpeg2000(imgb);
33
}
34
if (((num == PngImage.PNGID[0]) && (num2 == PngImage.PNGID[1])) && ((num3 == PngImage.PNGID[2]) && (num4 == PngImage.PNGID[3])))
35
{
36
return PngImage.GetImage(imgb);
37
}
38
if ((num == 0xd7) && (num2 == 0xcd))
39
{
40
return new ImgWMF(imgb);
41
}
42
if ((num == 0x42) && (num2 == 0x4d))
43
{
44
return BmpImage.GetImage(imgb);
45
}
46
if ((((num == 0x4d) && (num2 == 0x4d)) && ((num3 == 0) && (num4 == 0x2a))) || (((num == 0x49) && (num2 == 0x49)) && ((num3 == 0x2a) && (num4 == 0))))
47
{
48
RandomAccessFileOrArray s = null;
49
try
50
{
51
s = new RandomAccessFileOrArray(imgb);
52
Image tiffImage = TiffImage.GetTiffImage(s, 1);
53
if (tiffImage.OriginalData == null)
54
{
55
tiffImage.OriginalData = imgb;
56
}
57
return tiffImage;
58
}
59
finally
60
{
61
if (s != null)
62
{
63
s.Close();
64
}
65
}
66
}
67
throw new IOException(MessageLocalization.GetComposedMessage("the.byte.array.is.not.a.recognized.imageformat"));
68
}
该方法根据参数获取图片实例的方式比较多,例如:Image,PdfTemplate,PRIndirectReference,byte[],Stream,string ,Uri等等,以上给出了根据Image和byte[]获取ItextSharp的image实例。

4.Image的ScaleAbsolute():设置图片信息。

1
public void ScaleAbsolute(float newWidth, float newHeight)
2
{
3
this.plainWidth = newWidth;
4
this.plainHeight = newHeight;
5
float[] matrix = this.Matrix;
6
this.scaledWidth = matrix[6] - matrix[4];
7
this.scaledHeight = matrix[7] - matrix[5];
8
this.WidthPercentage = 0f;
9
}
以上代码可以看出,设置图片的信息主要包括高度、宽度、排列等信息。

5.Anchor类的Process()方法:重写链接的处理方法。

01
public override bool Process(IElementListener listener)
02
{
03
try
04
{
05
bool flag = (this.reference != null) && this.reference.StartsWith("#");
06
bool flag2 = true;
07
foreach (Chunk chunk in this.Chunks)
08
{
09
if (((this.name != null) && flag2) && !chunk.IsEmpty())
10
{
11
chunk.SetLocalDestination(this.name);
12
flag2 = false;
13
}
14
if (flag)
15
{
16
chunk.SetLocalGoto(this.reference.Substring(1));
17
}
18
else if (this.reference != null)
19
{
20
chunk.SetAnchor(this.reference);
21
}
22
listener.Add(chunk);
23
}
24
return true;
25
}
26
catch (DocumentException)
27
{
28
return false;
29
}
30
}
以上方法可以看到,该方法是在本类中被重写,用以处理链接的相关信息。

6.PageSize:设置纸张的类型。

01
public class PageSize
02
{
03
// Fields
04
public static readonly Rectangle _11X17;
05
public static readonly Rectangle A0;
06
public static readonly Rectangle A1;
07
public static readonly Rectangle A10;
08
public static readonly Rectangle A2;
09
public static readonly Rectangle A3;
10
public static readonly Rectangle A4;
11
public static readonly Rectangle A4_LANDSCAPE;
12
public static readonly Rectangle A5;
13
public static readonly Rectangle A6;
14
public static readonly Rectangle A7;
15
public static readonly Rectangle A8;
16
public static readonly Rectangle A9;
17
public static readonly Rectangle ARCH_A;
18
public static readonly Rectangle ARCH_B;
19
public static readonly Rectangle ARCH_C;
20
public static readonly Rectangle ARCH_D;
21
public static readonly Rectangle ARCH_E;
22
public static readonly Rectangle B0;
23
public static readonly Rectangle B1;
24
public static readonly Rectangle B10;
25
public static readonly Rectangle B2;
26
public static readonly Rectangle B3;
27
public static readonly Rectangle B4;
28
public static readonly Rectangle B5;
29
public static readonly Rectangle B6;
30
public static readonly Rectangle B7;
31
public static readonly Rectangle B8;
32
public static readonly Rectangle B9;
33
public static readonly Rectangle CROWN_OCTAVO;
34
public static readonly Rectangle CROWN_QUARTO;
35
public static readonly Rectangle DEMY_OCTAVO;
36
public static readonly Rectangle DEMY_QUARTO;
37
public static readonly Rectangle EXECUTIVE;
38
public static readonly Rectangle FLSA;
39
public static readonly Rectangle FLSE;
40
public static readonly Rectangle HALFLETTER;
41
public static readonly Rectangle ID_1;
42
public static readonly Rectangle ID_2;
43
public static readonly Rectangle ID_3;
44
public static readonly Rectangle LARGE_CROWN_OCTAVO;
45
public static readonly Rectangle LARGE_CROWN_QUARTO;
46
public static readonly Rectangle LEDGER;
47
public static readonly Rectangle LEGAL;
48
public static readonly Rectangle LEGAL_LANDSCAPE;
49
public static readonly Rectangle LETTER;
50
public static readonly Rectangle LETTER_LANDSCAPE;
51
public static readonly Rectangle NOTE;
52
public static readonly Rectangle PENGUIN_LARGE_PAPERBACK;
53
public static readonly Rectangle PENGUIN_SMALL_PAPERBACK;
54
public static readonly Rectangle POSTCARD;
55
public static readonly Rectangle ROYAL_OCTAVO;
56
public static readonly Rectangle ROYAL_QUARTO;
57
public static readonly Rectangle SMALL_PAPERBACK;
58
public static readonly Rectangle TABLOID;
59

60
// Methods
61
static PageSize();
62
public PageSize();
63
public static Rectangle GetRectangle(string name);
64
}
以上的类中,我们可以看到我们可以设置需要打印的纸张类型,根据实际情况可以选择。在最下面我们看到了两种方法,一个是PageSize()设置纸张大小,一个是GetRectangle()绘制矩形。

以上是对itextSharp组件的一些类和方法的简单介绍,对于表格,单元格等等类的介绍就不再继续,有兴趣的可以自己查看源代码信息。

三.itextSharp组件实例:

上面介绍了itextSharp组件的背景、特性,以及组件的核心类和方法,在这里给出一个简单的itextSharp组件操作的实例,这个实例只是一个简单的介绍。

001
/// <summary>
002
/// 字体
003
/// </summary>
004
private Font _font;
005

006
/// <summary>
007
/// 文档大小
008
/// </summary>
009
private Rectangle _rect;
010

011
/// <summary>
012
/// 文档对象
013
/// </summary>
014
private readonly Document _document;
015

016
/// <summary>
017
/// 基础字体
018
/// </summary>
019
private BaseFont _basefont;
020

021
/// <summary>
022
/// 构造函数
023
/// </summary>
024
public PDFOperation()
025
{
026
_rect = PageSize.A4;
027
_document = new Document(_rect);
028
}
029

030
/// <summary>
031
/// 构造函数
032
/// </summary>
033
/// <param name="type">页面大小(如"A4")</param>
034
public PDFOperation(string type)
035
{
036
if (string.IsNullOrEmpty(type))
037
{
038
throw new ArgumentNullException(type);
039
}
040
SetPageSize(type);
041
_document = new Document(_rect);
042
}
043

044
/// <summary>
045
/// 构造函数
046
/// </summary>
047
/// <param name="type">页面大小(如"A4")</param>
048
/// <param name="marginLeft">内容距左边框距离</param>
049
/// <param name="marginRight">内容距右边框距离</param>
050
/// <param name="marginTop">内容距上边框距离</param>
051
/// <param name="marginBottom">内容距下边框距离</param>
052
public PDFOperation(string type, float marginLeft, float marginRight, float marginTop, float marginBottom)
053
{
054
if (string.IsNullOrEmpty(type))
055
{
056
throw new ArgumentNullException(type);
057
}
058
SetPageSize(type);
059
_document = new Document(_rect, marginLeft, marginRight, marginTop, marginBottom);
060
}
061

062

063
/// <summary>
064
/// 设置字体
065
/// </summary>
066
public void SetBaseFont(string path)
067
{
068
if (string.IsNullOrEmpty(path))
069
{
070
throw new ArgumentNullException(path);
071
}
072
_basefont = BaseFont.CreateFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
073
}
074

075
/// <summary>
076
/// 设置字体
077
/// </summary>
078
/// <param name="size">字体大小</param>
079
public void SetFont(float size)
080
{
081
_font = new Font(_basefont, size);
082
}
083

084
/// <summary>
085
/// 设置页面大小
086
/// </summary>
087
/// <param name="type">页面大小(如"A4")</param>
088
public void SetPageSize(string type)
089
{
090
if (string.IsNullOrEmpty(type))
091
{
092
throw new ArgumentNullException(type);
093
}
094
switch (type.Trim())
095
{
096
//枚举需要的文档纸张大小
097
case "A3":
098
_rect = PageSize.A3;
099
break;
100
case "A4":
101
_rect = PageSize.A4;
102
break;
103
case "A8":
104
_rect = PageSize.A8;
105
break;
106
}
107
}
108

109
/// <summary>
110
/// 实例化文档
111
/// </summary>
112
/// <param name="os">文档相关信息(如路径,打开方式等)</param>
113
public void GetInstance(Stream os)
114
{
115
if (os == null)
116
{
117
throw new ArgumentNullException("os");
118
}
119
PdfWriter.GetInstance(_document, os);
120
}
121

122
/// <summary>
123
/// 打开文档对象
124
/// </summary>
125
/// <param name="os">文档相关信息(如路径,打开方式等)</param>
126
public void Open(Stream os)
127
{
128
if (os == null)
129
{
130
throw new ArgumentNullException("os");
131
}
132
GetInstance(os);
133
_document.Open();
134
}
135

136
/// <summary>
137
/// 关闭打开的文档
138
/// </summary>
139
public void Close()
140
{
141
_document.Close();
142
}
143

144
/// <summary>
145
/// 添加段落
146
/// </summary>
147
/// <param name="content">内容</param>
148
/// <param name="fontsize">字体大小</param>
149
public void AddParagraph(string content, float fontsize)
150
{
151
SetFont(fontsize);
152
var pra = new Paragraph(content, _font);
153
_document.Add(pra);
154
}
155

156
/// <summary>
157
/// 添加段落
158
/// </summary>
159
/// <param name="content">内容</param>
160
/// <param name="fontsize">字体大小</param>
161
/// <param name="alignment">对齐方式(1为居中,0为居左,2为居右)</param>
162
/// <param name="spacingAfter">段后空行数(0为默认值)</param>
163
/// <param name="spacingBefore">段前空行数(0为默认值)</param>
164
/// <param name="multipliedLeading">行间距(0为默认值)</param>
165
public void AddParagraph(string content, float fontsize, int alignment, float spacingAfter, float spacingBefore, float multipliedLeading)
166
{
167
SetFont(fontsize);
168
var pra = new Paragraph(content, _font)
169
{
170
Alignment = alignment
171
};
172
if (spacingAfter != 0)
173
{
174
pra.SpacingAfter = spacingAfter;
175
}
176
if (spacingBefore != 0)
177
{
178
pra.SpacingBefore = spacingBefore;
179
}
180
if (multipliedLeading != 0)
181
{
182
pra.MultipliedLeading = multipliedLeading;
183
}
184
_document.Add(pra);
185
}
186

187
/// <summary>
188
/// 添加图片
189
/// </summary>
190
/// <param name="path">图片路径</param>
191
/// <param name="alignment">对齐方式(1为居中,0为居左,2为居右)</param>
192
/// <param name="newWidth">图片宽(0为默认值,如果宽度大于页宽将按比率缩放)</param>
193
/// <param name="newHeight">图片高</param>
194
public void AddImage(string path, int alignment, float newWidth, float newHeight)
195
{
196
if (string.IsNullOrEmpty(path))
197
{
198
throw new ArgumentNullException(path);
199
}
200
var img = Image.GetInstance(path);
201
img.Alignment = alignment;
202
// ReSharper disable once CompareOfFloatsByEqualityOperator
203
if (newWidth != 0)
204
{
205
img.ScaleAbsolute(newWidth, newHeight);
206
}
207
else
208
{
209
if (img.Width > PageSize.A4.Width)
210
{
211
img.ScaleAbsolute(_rect.Width, img.Width * img.Height / _rect.Height);
212
}
213
}
214
_document.Add(img);
215
}
216

217
/// <summary>
218
/// 添加链接
219
/// </summary>
220
/// <param name="content">链接文字</param>
221
/// <param name="fontSize">字体大小</param>
222
/// <param name="reference">链接地址</param>
223
public void AddAnchorReference(string content, float fontSize, string reference)
224
{
225
if (string.IsNullOrEmpty(content))
226
{
227
throw new ArgumentNullException(content);
228
}
229
SetFont(fontSize);
230
var auc = new Anchor(content, _font)
231
{
232
Reference = reference
233
};
234
_document.Add(auc);
235
}
236

237
/// <summary>
238
/// 添加链接点
239
/// </summary>
240
/// <param name="content">链接文字</param>
241
/// <param name="fontSize">字体大小</param>
242
/// <param name="name">链接点名</param>
243
public void AddAnchorName(string content, float fontSize, string name)
244
{
245
if (string.IsNullOrEmpty(content))
246
{
247
throw new ArgumentNullException(content);
248
}
249
SetFont(fontSize);
250
var auc = new Anchor(content, _font)
251
{
252
Name = name
253
};
254
_document.Add(auc);
255
}
以上的实例比较的简单,主要是用作简单介绍组件的用法。如果需要将组件设计的更加通用,我们可以将组件的相关类和方法重写,并且可以开发一套cs或者bs程序,实现组件的图形化操作,图形化操作生成文件模板。文件模板可以将相关信息序列化(json或者二进制),在项目中直接加载模型,并将数据绑定在模板中,实现pdf打印的动态配置。

这个程序的开发难度一般,如果有兴趣的可以自行开发一套工具,可以更好的实现我们的项目pdf打印功能。

四.总结:

上面介绍了itextSharp组件的相关信息,在这个系列的组件介绍中,对于组件的介绍都是比较的简单,旨在向大家介绍这个组件,在实际的开发中,我们可以根据实际情况自行选择相应的组件,组件没有绝对的好坏,只有合适的场景

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章