Pal因此大希望将FOP转换为iTextSharp来拍卖。

初稿地址:Create/Read Advance PDF Report using iTextSharp in C# .NET:
Part
I   
By Debopam
Pal,
27 Nov 2013

背景:

 由于工作的因由一旦处理及打印一些pdf文档,目前之贯彻方式是FOP,园子里生及时点的牵线:Pdf
解决方案——fop。但项目中打印的pdf文档较生,每次用户打印文档都如run很丰富一段时间,因此很希望将FOP转换为iTextSharp来拍卖。iText大凡java中处理pdf文档很出名的一个开源类库,其NET版本的是iTextSharp,大家可以打这里下载源代码和dll文件,具体采用的上引用dll即可。

iText是开源的类库,文档可以参见该首页推荐的修:iText In Action
2nd。这书是iText的开创者Bruno写的,但中间的实例都是java写的。不过国外或有人形容了iTextSharp相关的片文档,博客园的权威很多,Careyson同学就翻了即无异多样:运iTextSharp在Asp.Net中操作PDF系列文章
目录。

 

资源下载:

 当然了无与伦比好之资料或者点提到的修::iText In Action
2nd,书可以于此下载。这按照开我绝对续续的羁押了绝大多数,也以圈了的大部java代码转换为C#本,于是想写有博客记录转。书被从带的代码都是命令行模式,为了有利于自己勾勒成了一个winform应用程序,以下也代码的周转界面:

图片 1

图片 2

描绘的winform没什么技术含量,大家双击右侧ListView中有Item就会见打开对应的pdf文档。本机开发环境也win7
64bit,VS2010,NET
4.0,代码大家好点击这里下载:chapter01.rar)

代码的solution如下图:

图片 3

漫天工程虽惟有区区个类库和一个winform,但援了三单第三正值的类库,这些dll已经嵌入代码中的Resource文件夹下。如齐图所示:我啊各一样省还创造了一个文本夹,大家眼前下载的只有chapter01目录下有像样公事,后续我哉止待放出对应章节的好像公事即可,大家呢如放入到对应之文书夹然后用那入到工程被即可。

世家如果专注的凡System.Data.SQLite.dll在win 32bit和win
64bit闹两样的本,如果是32个之电话,大家去
官方网站
找到呼应的下载。由于下了SqLite来存储数据,Resource文件夹下面还有一个Movie.db3文件,我本机用之是SQLite
Expert
Professional来查看和编里面的多寡,下载 点击这里。

以下也那运行界面:

图片 4

 其中坐FILM和FESTIVAL开头的阐明是iText In
Action书中demo要因此到的部分数目,最后一个表iTextSharpExample我存储的凡winform中listview对应的item数据。 iText
in
Action书中起因此到一些resource文件(比如说图片和xml文件),所以代码中呢亟需引用resource文件,大家先下载
Source文件,解压之后可以以SourceCodeiText\itext-book\book\resources文件夹着找到资源文件,然后修改下winform的app.config文件要其引述正确的目。

   
最后在app.config文件被还欲配备下SQLiteConnStr节点,对应之value就是方提到的Movie.db3文件,要注意的是最最安排绝对路径。以下也我本机的app.config文件内容:

  <appSettings>
    <add key="SQLiteConnStr" value="data source=D:\Movie.db3"/>
    <add key="ResourceFont" value="D:\MyFolder\SourceCodeiText\itext-book\book\resources\fonts\"/>
    <add key="ResourcePosters" value="D:\MyFolder\SourceCodeiText\itext-book\book\resources\posters\{0}.jpg"/>
    <add key="ResourceCalendar" value="D:\MyFolder\SourceCodeiText\itext-book\book\resources\calendar\{0}.jpg"/>
    <add key="ResourceImage" value="D:\MyFolder\SourceCodeiText\itext-book\book\resources\img\"/>
    <add key="ResourcePdfs" value="D:\MyFolder\SourceCodeiText\itext-book\book\resources\pdfs\"/>
    <add key="ResourceTxt" value="D:\MyFolder\SourceCodeiText\itext-book\book\resources\txt\"/>
    <add key="ResourceJS" value="D:\MyFolder\SourceCodeiText\itext-book\book\resources\js\"/>
    <add key="ResourceXml" value="D:\MyFolder\SourceCodeiText\itext-book\book\resources\xml\"/>
  </appSettings>

顶PDF原文介绍了iTextSharp这个类库,并演示了有些骨干的操作,基本属于入门级别之,可惜作者并从未以编辑后续的文章。

Creating a PDF document in five steps with iText

吓了,说来很多,我们现就算直奔主题。这无异于省的标题就是五步创建pdf文档,典型的代码如下:

HelloWorld.cs

// step 1
Document document = new Document();
using (document)
{
 // step 2
PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
// step 3
document.Open();
// step 4
document.Add(new Paragraph("Hello World"));
//step 5
document.Close();
}
  • 第一步:创建Document类的实例
  • 亚步:获取一个PdfWriter的实例
  • 老三步:打开文档
  • 季步:添加内容
  • 第五步:关闭文档

如上五步还是比好看懂的,下面就对准现实的各国一样步进行介绍:

刚好自己为当读书之类库,想实现一个导出ASPX页面及PDF的法力,如作者所说,网上找到的以身作则好多还是针对旧本子iTextSharp编写的,还生头驴唇不对马嘴,而且,很多抄的连验证都看望了,一点价值都没有。这篇文章终于详实的入门文章,实例也都基本操作了扳平布满实现无问题。

Step1:创建Document的实例

Document类我们得清楚啊一个容器,因此得以通往里面上加有强层次(high-level)的近乎。高层次之意是可观抽象了,里面没关系到pdf语法等有关等操作,和咱们平常创建的类类似。高层次之好像一般有:Chunk、Pharse、Paragraph等,这同节省吃我们就利用Paragraph类。那咱们先行看下Document类的老三独构造器:

public Document();
public Document(Rectangle pageSize);
public Document(Rectangle pageSize, float marginLeft, float marginRight, float marginTop, float marginBottom);

自打形参最丰富的构造器中可以摸清Document要发页面大小(PageSize)和页边距,因此我们啊得以用以下代码:

HelloWorldNarrow.cs

Rectangle pagesize = new Rectangle(216f, 720f);
Document document = new Document(pagesize, 36f, 72f, 108f, 180f);

方的代码好理解,要留意的是量单位,在pdf中度量单位凡用户单位(user
unit)。换算的公式是 1英寸=25.4mm=72 user
units≈72pt(磅)。老外的计量单位一般都是英寸,大家仔细看上面的代码,里面的数字都是36之翻番,也就是是0.5英寸。但在iText中,默认的心地单位是pt不是user
uint。因为pt和user
unit基本上是等的,而且pt也是于常用的襟怀单位。不过我们呢得以改他们中间的相应关系,代码如下:

HelloWorldMaximum.cs

// step 1
// maximum page size
Document document = new Document(new Rectangle(14400, 14400));
using (document)
{
// step 2
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
// changes the user unit
writer.Userunit = 75000f;
// step 3
document.Open();
// step 4
document.Add(new Paragraph("Hello World"));
}

经上述代码生成的pdf文档其页面大小是15000000(200*75000)英寸*15000000英寸,因为1user
unit对应了75000pt。 

 一般来讲,我们生成pdf文档是还见面选用一些业内页面大小。为了方便生成规范页面大小,iText中提供一个PageSize类,其中富含了大气正经页面大小,有B0到B10,A0到A10还来美国的正式页面:LETTER,LEGAL等。因此我们为足以遵循以下代码设置页面大小:

Document document = new Document(PageSize.LETTER);

在面创建的页面大小受到,都是长小余高度的。但为得以创造长度逾高度的文档,以下为代码:

HelloWorldLandscape1.cs

// step 1
Document document = new Document(PageSize.LETTER.Rotate());

或者

HelloWorldLandscape2.cs

Document document = new Document(new Rectangle(792, 612));

 通过以上两张法变的pdf文档打开看之话语是绝非呀界别。只是当pdf文档内部,第一种植之页面大小是长小余高度,但来一个90度过的页面旋转,而第二栽之页面大小是长超过高度没有页面的转动。这些都是有细小之歧异,在操作和拍卖已经在的文档时我们就得考虑这些细节。

 在Document类中还有SetPageSize()方法与SetMargins()方法,我们得当创建文档过程被之轻易时刻调用这些点子,但这些主意不见面影响时页面的安装,只会影响到下同样页。

此地而留心的是如果调用的Document的无论参构造器创建的页面大小就A4,页边距全是36pt。但我们或建议显示的安页面大小与页边距。

 页边距在文档双面打印的下如果注意有细节:如果文档要装订成册,那么我们不怕会愿意在装订的一边装特别一些的页边距,比如说平常的修左边装订,那么首先页的左侧距要深一点,而第二页的右距要同第一页的左手距同。总而言之页边距要对如。这些在iText中得这么设置:

HelloWorldMirroredMargins.cs

PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
document.SetPageSize(PageSize.A5);
document.SetMargins(36, 72, 108, 180);
document.SetMarginMirroring(true);

这么设置页面的左侧距同右侧距就本着如了,但还有局部题是于页面的上部或者下装订,因此便待页面的上距同下部距对如,代码如下:

HelloWorldMirroredMarginsTop.cs

document.SetMarginMirroringTopBottom(true);

ps.:第一不好翻译老外的稿子,英语水平一般,有些地方词不平易,还向海涵,如果进出希望协助指出。

Step2:获取一个PdfWriter的实例

点介绍Document类时说过那得以解呢一个器皿,我们吧那丰富一些high-level的靶子。但具体负责写副pdf文档的凡PdfWriter类,一般还是由此转代码获取PdfWriter实例:

PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));

上述的代码来一定量个意

  • 用Document类的实例和PdfWriter实例涉及起来,这样PdfWriter就见面监听Docuemnt,并拿在到Document类中的high-level对象转换为相应的pdf语句。

  • 报告PdfWriter实例要拿移好之pdf语句写入到老输出流。

这边的代码设置的且是文本流FileStream,但也得设置为任何的Stream:

HelloWorldMemory.cs

 public override void CreateFile(string fileName)
{
// step 1
Document document = new Document();
MemoryStream ms = new MemoryStream();
using (document)
{
// step 2
// we'll create the file in memory
PdfWriter.GetInstance(document, ms);
// step 3
document.Open();
// step 4
document.Add(new Paragraph("Hello World"));
}
// let's write the file in memory to a file anyway
FileStream fs = new FileStream(fileName, FileMode.Create);
using (fs)
{
BinaryWriter w = new BinaryWriter(fs);
using (w)
{
w.Write(ms.ToArray());
}
}
}

文章内容

  • 简介
  • 要求
  • 设置步骤
  • 6步创建PDF文档 
  • 涉嫌PDF文档的页面大小 
  • 装PDF文档背景色
  • 装PDF文档边距
  • 安装PDF文档文字对齐方式
  • 设置PDF文档的首批信息还是性质
  • 创多页文档
  • 从今曾经发文档创建新的PDF文档
  • 用Layer为PDF文档添加水印
  • 以Removing
    Layer移除刚刚创建Layer水印的PDF文档
  • 在创立进程吧各个一样页上加水印
  • E在匪存盘的情事下,导出/打印/输出PDF文件及客户端
    下面内容是在更新版本后添加的:
  • 装PDF浏览参数
  • 加密PDF文档
  • 声明
  • 参考文献
  • 历史

Step3:打开文档

当文档被打开时,进行了汪洋的初始化的装,其中囊括用pdf文件头信息写副到输出流中。下图虽是公创造的首先单pdf文件:hello.pdf用记事本打开的则:

图片 5

 

率先行看起应当是如此:

%PDF-1.4
%âãÏÓ

以上就是pdf文档的header,Pdf文档是由header,body,cross-reference
table和footer组成,更加详实的音方可参考书的chapter13。大家从达成吗怀疑到pdf的本子是1.4,现在大部分底pdf文档基本上还是1.4本,其它的版可以这样设置:

HelloWorldVersion_1_7.cs

// Creating a PDF 1.7 document
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
writer.PdfVersion = PdfWriter.VERSION_1_7;

简介

日前我一直于寻觅一个高档的工具来创造复杂的PDF报告据此当C#.NET中,我找到了iTextSharp.主要的题材是iTextSharp.缺乏文档。好吧,有少量之C#代码例子,但是那些对初学者的话是不够的而这些示例代码都是建于iTextSharp的旧本子及,在新型版本及出过多弯。所以,对初学者的话转换旧本子及新本子比较艰苦。此外,我当一旦自己形容一篇有关iTextSharp的章,它能辅助自己以为会看做下的参阅,我将为各国一个效益点书示例。老实说,在就篇稿子,我修的富有示例,你还能以《iText
in Action, Second
Edition》这本开之首先节约找到,这本书是针对性Java开发者编写的。我将以本人之稿子中讲[从java到c#]当下仍开余生段的兼具的示例.所以,如果有人对之库房(iTextSharp)感兴趣,这里以凡一个好的开始。

想念明白有关(iTextSharp)的重新多细节,可以透过她们之官方网站了解

Step4:添加始末

上述啰啰嗦嗦的用了森,其实我们而体贴的基本点就是是加上内容。

添加始末也生零星单主意

  • 朝Document类中上加high-level的靶子

  • 直用PdfWriter实例补充加于low-level的数码。

以下代码就是一个押起有点复杂,但可以为大家一个有关iText内部PDF创建过程的大概印象。

HelloWorldDirect.cs

PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
// step 3
document.Open();
// step 4
PdfContentByte canvas = writer.DirectContent;
writer.CompressionLevel = 0;
canvas.SaveState(); //q
canvas.BeginText(); //BT
canvas.MoveText(36, 788); //36 788 Td
canvas.SetFontAndSize(BaseFont.CreateFont(), 12); //F1 12 Tf
canvas.ShowText("Hello world"); //(Hello world)Tj
canvas.EndText(); // ET
canvas.RestoreState();//Q

 和先代码不同之是:我们拿转移的PdfWriter实例保存及有变量writer中。因为累要通过之writer来获取canvas画线画图。代码中经设置CompressionLevel属性为0得以避免对输出流的压缩,我们为得以透过记事本来查看pdf的语法语句。以上canvas的每个方法后的诠释对许切实的pdf语法,大家于是记事本打开就可以看到。但代码看起便比较复杂,而且只是简单的一个hello
world,如果假定描写更多之情节,那代码可能就是进一步难掌握。

故iText提供了有方便的方来调用:

HelloWorldColumn.cs

PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(OnePdfFile, FileMode.Create));
// step 3
document.Open();
// step 4
// we set the compression to 0 so that we can read the PDF syntax
writer.CompressionLevel = 0;
// writes something to the direct content using a convenience method
Phrase hello = new Phrase("Hello World");
PdfContentByte canvas = writer.DirectContent;
ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT, hello, 36, 788, 0);

这般代码看起便比亲民一些,而且用Adobe
Reader打开以上之一定量客Pdf文档,看起是同样的。如果就此记事本打开,里面会起一些轻微的差别。这里仍作者的传道就是是PDF内置的性状,而且要你用同样之等同客代码生成两客pdf文档,也会见时有发生一对差别。

要求

  • 编译这个类库,你要一个C#2008(vs2008)编译器或者再次胜版本,Visual
    Studio 2008 or Visual C# 2008 Express Edition
  • 本条库房代码运行在:
    • .NET 2.0
    • .NET 3.0
    • .NET 3.5
    • .NET 4.0
    • .NET 4.0 Client Profile
    • .NET 4.5
    • .NET 4.5 Client Profile

Step5:关闭文档

关闭的时刻iText会在pdf文档中描绘副EOF(End of
File)标记,在iTextSharp中,Document实现了IDisposable接口,因此便就此了using语句。要留心的凡在关闭Document的时,设置的输出流也会于电动关闭,但奇迹我们想输出流不深受活动关闭。

HelloZip.cs

// creating a zip file with different PDF documents
ZipOutputStream zip = new ZipOutputStream(new FileStream(fileName, FileMode.Create));
for (int i = 0; i < 4; i++)
{
 ZipEntry entry = new ZipEntry("hello_" + i + ".pdf");
zip.PutNextEntry(entry);
// step 1
Document document= new Document();
// step 2
PdfWriter writer = PdfWriter.GetInstance(document, zip);
writer.CloseStream = false;
// step 3
document.Open();
// step 4
document.Add(new Paragraph("Hello " + i));
// step 5
document.Close();
zip.CloseEntry();
}
zip.Close();

以上代码会有一个压缩包,包中含有了4个pdf文件,因为安装的凡ZipOutpuStream,我们无盼于中等生成pdf文档时输出流被机关关闭,这里要设置PdfWriter的ClosedStream属性为true即可。

安装

  • 你用安装 NuGet
    package

或者
你得起底下是SourceForge的链接下载DLL,然后参照下步骤:

  • 丰富引用BlahBlah(步骤如下,翻译掠过). Just see the image below:
    图片 6
  • 卿得引入到C#文件被之命名空间:
    • iTextSharp.text
    • iTextSharp.text.pdf

总结

由此五步我们学会了创建pdf文档,每一样步也都有矣着力的了解。但我们无限要关怀之尽管是第四步:添加情。其它的步骤大家发只概念并知道有配置就足以了。在连续的区块中,我们会也pdf文档添加一些发实际意义的内容,大家呢会关切有常用high-level对象的操作。

高效入门

同步

此文章已联名到目录索引:iText in Action 2nd
读书笔记。

6步创建一个PDF文档:

  • Step 1: 创建一个 System.IO.FileStream 对象:

    FileStream fs = new FileStream(“Chapter1_Example1.pdf”, FileMode.Create, FileAccess.Write, FileShare.None);

  • Step 2: 创建一个 iTextSharp.text.Document 对象:

    Document doc = new Document();

  • Step 3: 创建一个 iTextSharp.text.pdf.PdfWriter 对象:
    它助长将Document书写及一定的FileStream:

    PdfWriter writer = PdfWriter.GetInstance(doc, fs);

  • Step 4: 打开 Document:

    doc.Open();

  • Step 5: 创建一个 iTextSharp.text.Paragraph 对象并加加到Document里:

    doc.Add(new Paragraph(“Hello World”));

  • Step 6: 关闭 Document:

    doc.Close();

涉及PDF文档的页面大小:

开创一个特定大小的页面,我们得创造一个iTextSharp.text.Rectangle
对象又传递一个页面大小的参数到她的构造函数里面,下面是概念页面大小的方:

  • 首先栽概念一个版面大小的道:
    通过定义像素或者英寸定义一个页面尺寸。注意:在iTextSharp里头页面大小的单位凡‘point。72point=1英寸。假设我们得一个宽=2英寸&高度=10英寸的PDF文件,那么我们要144pt&72pt,让我们看下该怎么开:

Rectangle rec = new Rectangle(144, 720);
  • 次栽概念版面大小的法门:
    应用内建的 iTextSharp.text.PageSize 类定义:

    Rectangle rec2 = new Rectangle(PageSize.A4);
    

    下面是外建之版面大小。. 完整的页面大小说明链接 Documentation of
    Page
    Size:

    • _11X17
    • A0
    • A1
    • A10
    • A2
    • A3
    • A4
    • A4_LANDSCAPE
    • A5
    • A6
    • A7
    • A8
    • A9
    • ARCH_A
    • ARCH_B
    • ARCH_C
    • ARCH_D
    • ARCH_E
    • B0
    • B1
    • B10
    • B2
    • B3
    • B4
    • B5
    • B6
    • B7
    • B8
    • B9
    • CROWN_OCTAVO
    • CROWN_QUARTO
    • DEMY_OCTAVO
    • DEMY_QUARTO
    • EXECUTIVE
    • FLSA
    • FLSE
    • HALFLETTER
    • ID_1
    • ID_2
    • ID_3
    • LARGE_CROWN_OCTAVO
    • LARGE_CROWN_QUARTO
    • LEDGER
    • LEGAL
    • LEGAL_LANDSCAPE
    • LETTER
    • LETTER_LANDSCAPE
    • NOTE
    • PENGUIN_LARGE_PAPERBACK
    • PENGUIN_SMALL_PAPERBACK
    • POSTCARD
    • ROYAL_OCTAVO
    • ROYAL_QUARTO
    • SMALL_PAPERBACK
    • TABLOID
  • 其三种概念版面大小的措施:
    反转文档的可观成为宽度&反之亦然:

    Rectangle rec3 = new Rectangle(PageSize.A4.Rotate());
    

今昔,把刚的是 iTextSharp.text.Rectangle 对象
(任意一个)也不怕是点的 ‘rec’,或者 ‘rec2’还是
‘rec3’加入iTextSharp.text.Document‘s 的构造函数中:

Document doc = new Document(rec);

设置PDF文档背景色:

起几乎种艺术来装背景色:

  • 先是栽方法:
    需要动用对象 iTextSharp.text.BaseColor. 实例化BaseColor
    采用System.Drawing.Color
    (.NET)对象或您啊得就此传递RGB值的样式来定义:

    rec.BackgroundColor = new BaseColor(System.Drawing.Color.WhiteSmoke);
    
  • 其次栽办法:
    用利用对象 iTextSharp.text.pdf.CMYKColor. CMYKColor 通过传递
    CMYK 值的不二法门来布局:

    rec2.BackgroundColor = new CMYKColor(25, 90, 25, 0);
    

安装PDF文档边距:

页边距可以像设置版面大小一样来定义
加盟我们装如下的页边距:

  • Left : 0.5 inch
  • Right : 1 inch
  • Top : 1.5 inch
  • Bottom : 2.5 inch

用我们要各自安装页面的 Left, Right, Top, Bottom
页边距使用point单位,因为咱们懂得 iTextSharp
中是下point作为单位之,并且 72 points = 1 inch.

  • Left : 36pt => 0.5 inch
  • Right : 72pt => 1 inch
  • Top : 108pt => 1.5 inch
  • Bottom : 180pt => 2.5 inch

实现如下:

Document doc = new Document(PageSize.A4, 36, 72, 108, 180);

装PDF文档文字对齐方式:

AlignmentiTextSharp.text.Paragraph靶的属性. iTextSharp
提供了各种针对齐方式. 可以由此iTextSharp.text.Element
类设置对其.以下是iTextSharp提供的针对齐方式:

  • ALIGN_BASELINE[^]
  • ALIGN_BOTTOM[^]
  • ALIGN_CENTER[^]
  • ALIGN_JUSTIFIED[^]
  • ALIGN_JUSTIFIED_ALL[^]
  • ALIGN_LEFT[^]
  • ALIGN_MIDDLE[^]
  • ALIGN_RIGHT[^]
  • ALIGN_TOP[^]
  • ALIGN_UNDEFINED[^]

咱已知晓在 iTextSharp.text.Document
的构造函数中得iTextSharp.text.Paragraph
对象,所以当创立Paragraph对象下咱们可以安装它的对准齐方式,我们得以以Document创建进程将Prargraph传递进去.

落实如下:

Paragraph para = new Paragraph("Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World");
// Setting paragraph's text alignment using iTextSharp.text.Element class
para.Alignment = Element.ALIGN_JUSTIFIED;
// Adding this 'para' to the Document object
doc.Add(para);

设置PDF文档的第一信息或性质:

下面这些PDF文档的首信息
你可经过iTextSharp.text.Document创立的对象doc(上文的doc)里面的方式来安:

  • Author
    Name[^)]
  • Creation
    Date[^)]
  • Creator
    Name[^)]
  • Header Name &
    Content[^)]
  • Keywords[^)]
  • Langugae[^)]
  • Producer[^)]
  • Subject[^)]
  • Title[^)]

下是他们之一些实现:

// Setting Document properties e.g.
// 1. Title
// 2. Subject
// 3. Keywords
// 4. Creator
// 5. Author
// 6. Header
doc.AddTitle("Hello World example");
doc.AddSubject("This is an Example 4 of Chapter 1 of Book 'iText in Action'");
doc.AddKeywords("Metadata, iTextSharp 5.4.4, Chapter 1, Tutorial");
doc.AddCreator("iTextSharp 5.4.4");
doc.AddAuthor("Debopam Pal");
doc.AddHeader("Nothing", "No Header");

今天,打开一个PDF文档后,右键->属性,你见面盼刚才设置的音讯:
图片 7

创立多页文档:

我们可以经过iTextSharp.text.DocumentNewPage()术创建新页面,我们来创造5个PDF文档(页面)
:

for (int i = 1; i <= 5; i++)
{
    doc.NewPage();
    doc.Add(new Paragraph(string.Format("This is a page {0}", i)));
}

从都起文档创建新的PDF文档:

我们得以利用iTextSharp.text.pdf.PdfReader靶读取一个PDF文档,然后下
iTextSharp.text.pdf.PdfStamper目标来把她形容及任何一个PDF文档。实现如下:

string originalFile = "Original.pdf";
string copyOfOriginal = "Copy.pdf";
using (FileStream fs = new FileStream(originalFile, FileMode.Create, FileAccess.Write, FileShare.None))
using (Document doc = new Document(PageSize.LETTER))
using (PdfWriter writer = PdfWriter.GetInstance(doc, fs))
{
    doc.Open();
    doc.Add(new Paragraph("Hi! I'm Original"));
    doc.Close();
}
PdfReader reader = new PdfReader(originalFile);
using (FileStream fs = new FileStream(copyOfOriginal, FileMode.Create, FileAccess.Write, FileShare.None))
// Creating iTextSharp.text.pdf.PdfStamper object to write
// Data from iTextSharp.text.pdf.PdfReader object to FileStream object
using (PdfStamper stamper = new PdfStamper(reader, fs)) { }

使用Layer为PDF文档添加水印:

iTextSharp遭遇,PDF文档创建后好增长水印,在此间我用使用iTextSharp.text.pdf.PdfLayer也曾有些PDF文档(Original.pdf)添加水印。实现如下:

string watermarkedFile = "Watermarked.pdf";
// Creating watermark on a separate layer
// Creating iTextSharp.text.pdf.PdfReader object to read the Existing PDF Document
PdfReader reader1 = new PdfReader(originalFile);
using (FileStream fs = new FileStream(watermarkedFile, FileMode.Create, FileAccess.Write, FileShare.None))
// Creating iTextSharp.text.pdf.PdfStamper object to write Data from iTextSharp.text.pdf.PdfReader object to FileStream object
using (PdfStamper stamper = new PdfStamper(reader1, fs))
{
    // Getting total number of pages of the Existing Document
    int pageCount = reader1.NumberOfPages;

    // Create New Layer for Watermark
    PdfLayer layer = new PdfLayer("WatermarkLayer", stamper.Writer);
    // Loop through each Page
    for (int i = 1; i <= pageCount; i++)
    {
        // Getting the Page Size
        Rectangle rect = reader1.GetPageSize(i);

        // Get the ContentByte object
        PdfContentByte cb = stamper.GetUnderContent(i);

        // Tell the cb that the next commands should be "bound" to this new layer
        cb.BeginLayer(layer);
        cb.SetFontAndSize(BaseFont.CreateFont(
          BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 50);

        PdfGState gState = new PdfGState();
        gState.FillOpacity = 0.25f;
        cb.SetGState(gState);

        cb.SetColorFill(BaseColor.BLACK);
        cb.BeginText();
        cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, watermarkText, rect.Width / 2, rect.Height / 2, 45f);
        cb.EndText();

        // Close the layer
        cb.EndLayer();
    }
}

兑现结果如下:
图片 8

运Removing Layer移除刚刚创建Layer水印的PDF文档:

Whenever we add Layer in PDF Document, then the content of the Layer
resides under OCG Group. So if I remove this Layer we can remove the
content of the Layer also e.g. here it is Watermark Text. To remove all
the Layers from PDF Document, you have to remove OCG Group completely
from the Document usingreader.Catalog.Remove(PdfName.OCPROPERTIES).
Now follow the Steps below to remove the Watermark Text from Layer:

  • Read the existing watermarked document using
    iTextSharp.text.pdf.PdfReader‘s object
  • Taking each Page in the iTextSharp.text.pdf.PdfDictionary‘s object
    using GetPageN(int pageNumber) method of
    iTextSharp.text.pdf.PdfReader‘s object.
  • Taking the Content of the Page in the
    iTextSharp.text.pdf.PdfArray‘s object
    usingGetAsArray(PdfName.CONTENTS) method of
    iTextSharp.text.pdf.PdfDictionary‘s object
  • Loop through this array and Get each element as
    iTextSharp.text.pdf.PRStream‘s object
    usingGetAsStream(int arrayIndex) method of
    iTextSharp.text.pdf.PdfArray‘s object
  • Convert each stream into Bytes using Static method
    GetStreamBytes(PRStream stream) ofiTextSharp.text.pdf.PdfReader
    class
  • Convert these Bytes into String using
    System.Text.Encoding.ASCII.GetString(byte[] bytes)method
  • Search for the String “/OC” and also the Watermarked Text. If
    found then remove it by giving it zero length and zero data using
    two methods: Put() & SetData() of iTextSharp.text.pdf.PRStream
    class
  • Write this modified document exists in the reader to a new
    document usingiTextSharp.text.pdf.PdfStamper‘s object

Lets Implement it:

// Removing the layer created above
// 1. First we bind a reader to the watermarked file
// 2. Then strip out a branch of things
// 3. Finally use a simple stamper to write out the edited reader
PdfReader reader2 = new PdfReader(watermarkedFile);

// NOTE: This will destroy all layers in the Document, only use if you don't have any addtional layers
// Remove the OCG group completely from the Document: reader2.Catalog.Remove(PdfName.OCPROPERTIES);

// Clean up the reader, optional
reader2.RemoveUnusedObjects();

// Placeholder variables
PRStream stream;
string content;
PdfDictionary page;
PdfArray contentArray;

// Get the number of pages
int pageCount2 = reader2.NumberOfPages;

// Loop through each page
for (int i = 1; i <= pageCount2; i++)
{
    // Get the page
    page = reader2.GetPageN(i);

    // Get the raw content
    contentArray = page.GetAsArray(PdfName.CONTENTS);

    if (contentArray != null)
    {
        // Loop through content
        for (int j = 0; j < contentArray.Size; j++)
        {
            stream = (PRStream)contentArray.GetAsStream(j);

            // Convert to a String, NOTE: you might need a different encoding here
            content = System.Text.Encoding.ASCII.GetString(PdfReader.GetStreamBytes(stream));

            //Look for the OCG token in the stream as well as our watermarked text
            if (content.IndexOf("/OC") >= 0 && content.IndexOf(watermarkText) >= 0)
            {
                //Remove it by giving it zero length and zero data
                stream.Put(PdfName.LENGTH, new PdfNumber(0));
                stream.SetData(new byte[0]);
            }
        }
    }
}

// Write the content out
using (FileStream fs = new FileStream(unwatermarkedFile, 
          FileMode.Create, FileAccess.Write, FileShare.None))
using (PdfStamper stamper = new PdfStamper(reader2, fs)) { }

每当开立进程吧各级一样页上加水印:

Now, we already know that, watermark cannot be add during Page creation,
it have to add after document creation. So, I’ve created a class
PDFWriterEvents which implements the interface
iTextSharp.text.pdf.IPdfPageEventand modify the event OnStartPage.
This interface contains a set of events from the Openning & to Closing
the PDF Document. The events are following:

  • public void OnOpenDocument(PdfWriter writer, Document document)
  • public void OnCloseDocument(PdfWriter writer, Document document)
  • public void OnStartPage(PdfWriter writer, Document document)
  • public void OnEndPage(PdfWriter writer, Document document)
  • public void OnParagraph(PdfWriter writer, Document document, float paragraphPosition)
  • public void OnParagraphEnd(PdfWriter writer, Document document, float paragraphPosition)
  • public void OnChapter(PdfWriter writer, Document document, float paragraphPosition, Paragraph title)
  • public void OnChapterEnd(PdfWriter writer, Document document, float paragraphPosition)
  • public void OnSection(PdfWriter writer, Document document, float paragraphPosition, int depth, Paragraph title)
  • public void OnSectionEnd(PdfWriter writer, Document document, float paragraphPosition)
  • public void OnGenericTag(PdfWriter writer, Document document, Rectangle rect, String text)

You may modify other events accroding to your needs which occured
against a particular action. Let see the which I’ve created:

// Creating Watermark inside OnStartPage Event by implementing IPdfPageEvent interface
// So that, dusring Page Creation, Watermark will be create
class PDFWriterEvents : IPdfPageEvent
{
    string watermarkText;
    float fontSize = 80f;
    float xPosition = 300f;
    float yPosition = 800f;
    float angle = 45f;

    public PDFWriterEvents(string watermarkText, float fontSize = 80f, 
       float xPosition = 300f, float yPosition = 400f, float angle = 45f)
    {
        this.watermarkText = watermarkText;
        this.xPosition = xPosition;
        this.yPosition = yPosition;
        this.angle = angle;
    }

    public void OnOpenDocument(PdfWriter writer, Document document) { }
    public void OnCloseDocument(PdfWriter writer, Document document) { }
    public void OnStartPage(PdfWriter writer, Document document)
    {
        try
        {
            PdfContentByte cb = writer.DirectContentUnder;
            BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
            cb.BeginText();
            cb.SetColorFill(BaseColor.LIGHT_GRAY);
            cb.SetFontAndSize(baseFont, fontSize);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, watermarkText, xPosition, yPosition, angle);
            cb.EndText();
        }
        catch (DocumentException docEx)
        {
            throw docEx;
        }
    }
    public void OnEndPage(PdfWriter writer, Document document) { }
    public void OnParagraph(PdfWriter writer, Document document, float paragraphPosition) { }
    public void OnParagraphEnd(PdfWriter writer, Document document, float paragraphPosition) { }
    public void OnChapter(PdfWriter writer, Document document, float paragraphPosition, Paragraph title) { }
    public void OnChapterEnd(PdfWriter writer, Document document, float paragraphPosition) { }
    public void OnSection(PdfWriter writer, Document document, float paragraphPosition, int depth, Paragraph title) { }
    public void OnSectionEnd(PdfWriter writer, Document document, float paragraphPosition) { }
    public void OnGenericTag(PdfWriter writer, Document document, Rectangle rect, String text) { }
}

Lets see how & when you use the object of this class:

using (FileStream fs = new FileStream(
      "Watermark_During_Page_Creation.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
using (Document doc = new Document(PageSize.LETTER))
using (PdfWriter writer = PdfWriter.GetInstance(doc, fs))
{
    writer.PageEvent = new PDFWriterEvents("This is a Test");
    doc.Open();
    doc.Add(new Paragraph("This is a page 1"));
    doc.Close();
}

See, OnStartPage event called during adding a new paragraph. So I
don’t need to add watermark
later图片 9

于非存盘的场面下,导出/打印/输出PDF文件及客户端:

We can create PDF File in memory by creatig System.IO.MemorySystem‘s
object. Lets see:

using (MemoryStream ms = new MemoryStream())
using(Document document = new Document(PageSize.A4, 25, 25, 30, 30))
using(PdfWriter writer = PdfWriter.GetInstance(document, ms))
{
    document.Open();
    document.Add(new Paragraph("Hello World"));
    document.Close();
    writer.Close();
    ms.Close();
    Response.ContentType = "pdf/application";
    Response.AddHeader("content-disposition", "attachment;filename=First_PDF_document.pdf");
    Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
}

装PDF浏览参数:

The values of the different ViewerPreferences were originally stored
in iTextSharp.text.pdf.PdfWriter class as an integer constant. You can
set the ViewerPreferences by following two ways:

  • By setting property ViewerPreferences of
    iTextSharp.text.pdf.PdfWriter class. To know all
    theViewerPreferences and its purpose, please read
    this)
    first. E.g.-

    writer.ViewerPreferences = PdfWriter.HideMenubar;
    
  • By calling method
    AddViewerPreference(PdfName key, PdfObject value)
    ofiTextSharp.text.pdf.PdfWriter‘s object. To know which value is
    appropiate for which key, read
    this)first.
    E.g.-

    writer.AddViewerPreference(PdfName.HIDEMENUBAR, new PdfBoolean(true));
    

加密PDF文档:

By SetEncryption() method of iTextSharp.text.pdf.PdfWriter‘s object,
we can encrypt a PDF document. Read full documentation of this method
here.
To know all the encryption types, click
here.
E.g.-

writer.SetEncryption(PdfWriter.STRENGTH40BITS, null, null, PdfWriter.ALLOW_COPY);

声明

Please download the source code for detail. I hope you'll understand as the source code is documented. If any doubt, just post your comment below. Thank you.

参考文献

  • iText Official Website
  • iText in Action, Second
    Edition
  • Core iText API Documentation
  • RubyPdf Blog – iText# in
    Action
  • Create PDFs in ASP.NET – getting started with
    iTextSharp
  • Basic PDF Creation Using iTextSharp – Part
    I

历史

25th Nov, 2013: PART-I Release. PART-II will release soon
图片 10

许可

This article, along with any associated source code and files, is
licensed under The Code Project Open License
(CPOL)

 

相关文章

网站地图xml地图