最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#使用iTextSharp操作PDF

 更新時(shí)間:2022年06月09日 14:44:19   作者:springsnow  
這篇文章介紹了C#使用iTextSharp操作PDF的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

最終版iTextSharp 5.5: https://github.com/itext/itextsharp ,已經(jīng)被 iText 7代替。

一、介紹

iTextSharp:是一個(gè)從JAVA項(xiàng)目iText衍生的.Net版本的開源項(xiàng)目。iText是一個(gè)PDF庫,可讓您創(chuàng)建,移植,檢查和維護(hù)可移植文檔格式(PDF)的文檔,從而使您可以輕松地向軟件項(xiàng)目添加PDF功能。我們甚至提供文檔來幫助您進(jìn)行編碼。

二、使用

1.下載安裝組件

首先下載該組件并添加引用,這里是使用VS自帶的NuGet來進(jìn)行安裝的,鍵項(xiàng)目選擇管理NuGet程序包,搜索iTextSharp選擇合適版本安裝即可,安裝完成會自動添加引用。

iTextSharp最新版本為5.5.13.1

2、創(chuàng)建文檔

在使用的文件里面引入命名空間

using iTextSharp.text;
using iTextSharp.text.pdf;

Document對象:頁面對象,就像是HTML里面的頁面對象一樣,用于操作頁面內(nèi)容和格式。通過Document對象的實(shí)例來操作內(nèi)存中的pdf文件。

Document document = new Document();

(1)自定義文檔的大小和邊距

Document對象默認(rèn)的文檔大小是A4(也就是210毫米x297毫米,或是8.26英尺x11.69英尺),頁邊距默認(rèn)都是半英尺。

很多時(shí)候,你并不希望通過默認(rèn)設(shè)置創(chuàng)建默認(rèn)大小,默認(rèn)邊距的PDF文檔,所以iTextSharp允許你自定義這些設(shè)置,所以Document對象還提供了其他兩個(gè)構(gòu)造函數(shù):

public Document(iTextSharp.text.Rectangle pageSize);
public Document(iTextSharp.text.Rectangle pageSize, float, float, float, float);

第一個(gè)構(gòu)造函數(shù)可以這樣使用:

var doc = new Document(PageSize.A5);

PageSize類包含了一系列Rectangle對象代表了大多數(shù)紙張的大小,從A0到A10,B0到B10,legal,分類賬,信封,明信片,剪報(bào)等,如果PageSize類內(nèi)的紙張大小無法滿足你的需求,你可以自定義一個(gè)Rectangle對象,對其設(shè)置值后作為參數(shù)傳給Document構(gòu)造函數(shù):

var doc = new Document(new Rectangle(100f, 300f));

上面代碼中,創(chuàng)建的PDF文檔為100像素寬,300像素長,因?yàn)槭?2像素/英尺,所以這個(gè)文檔并不大,實(shí)際上為1.39 英尺 x 4.17 英尺.

第二個(gè)構(gòu)造函數(shù)以Rectangle和四個(gè)float類型的數(shù)字作為參數(shù)允許你通過float類型的變量自定義頁邊距,同樣,單位是像素,默認(rèn)半英尺的像素為36像素。

Document document = new Document(new Rectangle(1000, 500), 10, 10, 120, 80);

(2)設(shè)置文檔的背景色

如果你使用PageSize類的構(gòu)造函數(shù),或者是自定義Rectangle,你還可以為文檔設(shè)置背景色。這個(gè)設(shè)置可以通過RGB顏色值,或是CMYK值。設(shè)置文檔的背景色,通過Rectangle對象的BackgroundColorproperty進(jìn)行設(shè)置:

r.BackgroundColor = new CMYKColor(25, 90, 25, 0);
r.BackgroundColor = new Color(191, 64, 124);

3、保存文檔

PdfWriter對象:用于將Document對象寫入PDF文件。

將內(nèi)存中的Document對象保存到硬盤中,使用PdfWriter類來實(shí)現(xiàn)這個(gè)功能:

Document document = new Document(new Rectangle(1000, 500), 10, 10, 120, 80);

PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(@"D:\aa.pdf", FileMode.Create));
//先打開文檔,往里寫一段內(nèi)容,最后關(guān)閉文檔
document.Open();
document.Add(new iTextSharp.text.Paragraph("Hello World! Hello People! Hello Sky! Hello Sun! Hello Moon! Hello Stars!"));
document.Close();
writer.Close();

4、設(shè)置字體

iTextSharp默認(rèn)支持14種字體,分別為:Courier, Courier Bold, Courier Italic, Courier Bold and Italic, Helvetica, Helvetica Bold, Helvetica Italic, Helvetica Bold and Italic, Times New Roman, Times Roman Bold, Times Roman Italic, Times Roman Bold and Italic, Symbol, ZapfDingBats®。

iTextSharp的默認(rèn)字體為Helvetica, 12pt,黑色,也就是所謂的正常(Normal)字體。

iTextSharp提供了3種主要方式來設(shè)置字體:

  • 一種是使用BaseFont.CreateFont()方法,BaseFont.CreateFont()有很多局限性,表現(xiàn)在僅僅是生成一個(gè)新的字體定義。
    下面的代碼創(chuàng)建了一個(gè)BaseFont對象并且使用內(nèi)置的constant值來設(shè)置字體類型和編碼類型。在是否將字體嵌入PDF中選擇了False以減少PDF的大小使用BaseFont來創(chuàng)建一個(gè)新的Font對象。
    下一行代碼進(jìn)一步從字體大小,字體風(fēng)格,顏色來設(shè)置字體,當(dāng)然,我們依然使用內(nèi)置的constant類型值,然后,將上述風(fēng)格字體加入段落:
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
Font times = new Font(bfTimes, 12, iTextSharp.text.Font.ITALIC, iTextSharp.text.BaseColor.RED);
document.Add(new iTextSharp.text.Paragraph("Hello World!", times));
  • 第二種方法是使用FontFactory.GetFont()方法。返回一個(gè)你可以直接操作的Font對象。并且提供了14種不同的重載來給你提供更多選項(xiàng)。包括:字體,顏色, 風(fēng)格,是否嵌入,編碼以及緩存等。
    每次你調(diào)用FontFactory.GetFont()時(shí)都會返回一個(gè)新的對象。這個(gè)方法對于字體的設(shè)置可以對任何在iTextSharp中注冊的字體進(jìn)行生效。
    在iTextSharp中注冊的字體包括windows字體的默認(rèn)目錄,這個(gè)目錄一般為”C:/WINDOWS/Fonts”,如果你想知道哪些字體在iTextSharp中已注冊,F(xiàn)ontFactory.RegisteredFonts將會告訴你答案,查看這個(gè)列表對于我們想獲得確切的字體名稱尤為重要。
    下面的一些方法使用iTextSharp的Color對象的constant值來設(shè)置字體顏色,還有諸如使用SetColor()方法傳入RGB值或是New一個(gè)Color對象傳入。通常情況下,我們都可以傳入int值作為字體風(fēng)格參數(shù),或者使用SetStyle()方法傳入一個(gè)字符串。
int totalfonts = FontFactory.RegisterDirectory("C:\\WINDOWS\\Fonts");
StringBuilder sb = new StringBuilder();
foreach (string fontname in FontFactory.RegisteredFonts)
{
    sb.Append(fontname + "\n");
}

document.Add(new Paragraph("All Fonts:\n" + sb.ToString()));

Font arial = FontFactory.GetFont("Arial", 28, iTextSharp.text.BaseColor.GRAY);
Font verdana = FontFactory.GetFont("Verdana", 16, Font.BOLDITALIC, new iTextSharp.text.BaseColor(125, 88, 15));
Font palatino = FontFactory.GetFont("palatino linotype italique", BaseFont.CP1252, BaseFont.EMBEDDED, 10, Font.ITALIC, iTextSharp.text.BaseColor.GREEN);
Font smallfont = FontFactory.GetFont("Arial", 7);
Font x = FontFactory.GetFont("nina fett");
x.Size = 10;
x.SetStyle("Italic");
  • 第三種方法是直接生成一個(gè)新的Font對象。
    有時(shí)候你會遇到在WEB服務(wù)器上你沒有權(quán)限安裝字體,這時(shí)你必須顯式在iTextSharp中注冊字體了。
    下面代碼中你也許會注意到字體文件是嵌入PDF中的(BaseFont.EMBEDDED),因?yàn)楹芏嗲闆r下你創(chuàng)建的PDF中的字體在用戶的電腦上并不存在。
BaseFont customfont = BaseFont.CreateFont("./myspecial.ttf", BaseFont.CP1252, BaseFont.EMBEDDED);
Font font = new Font(customfont, 12);
 string s = "My expensive custom font.";
 doc.Add(new Paragraph(s, font));

5.設(shè)置PDF文檔信息,利用Document對象。

document.AddTitle("這里是標(biāo)題");
document.AddSubject("主題");
document.AddKeywords("關(guān)鍵字");
document.AddCreator("創(chuàng)建者");
document.AddAuthor("作者");

6、利用塊,短語,段落添加文本

  • 塊(Chunks)是容納文本的最小容器,就像ASP.Net中的<asp:Label>一樣,可以使用”\n”或者Environment.NewLine,或者Chunk.NEWLINE作為給Chunk對象賦值的一部分。Chunk有一系列方法允許你為文本設(shè)置樣式,比如setUnderLine(), setBackGround(), 和 setTextRise()以及一些構(gòu)造函數(shù)來設(shè)置字體類型以及風(fēng)格。
  • 短語(Phrase)是比Chunk大一級的容器,Phrase可以理解為一組Chunk,并且會在長度超過文檔寬度后自動換行,每一行之間的行距(測量方法其實(shí)是每行底部之間的距離)是字體大小的1.5倍,因?yàn)樵趇TextSharp行距之間的舉例是12pt,所以下面代碼之間的行距為16pt.你可以在Phrase初始化的時(shí)候設(shè)置字體和行距.當(dāng)然也可以通過其多種構(gòu)造函數(shù)重載來在初始化時(shí)為Phrase添加內(nèi)容.
  • 段落(Paragraphs)是用的最多的類是.Paragraph其實(shí)是一組有序Phrase和Chunk的集合。Paragraph派生于Phrase,所以和Phrase一樣,Paragraph也會在長度超過文檔長度時(shí)自動換行。不僅如此,Paragraph和Paragraph之間也會自動空一行(就像文字處理軟件那樣)。

下面代碼中,我會將格式化的文本通過Chunk和Phrase來添加到Paragraphs中:每一個(gè)設(shè)置了風(fēng)格樣式的字體都需要包含在一個(gè)Chunk中,然后再將Chunk添加到Phrase來確保文字會自動換行,最后,所有Phrase和Chunk都會被添加到Paragraph對象中。還可以通過Paragraph.setAlignment()設(shè)置Paragraph的對齊方式,這個(gè)方法接受一個(gè)String類型的參數(shù),可以是"Left", "Center", "Justify",和 "Right".下面是設(shè)置p.setAlignment("Justify");居中的顯示效果:

string text = @"The result can be seen below, which shows the text
                    having been written to the document but it looks a    mess. Chunks have no concept of how to force a new    . ";

text = text.Replace(Environment.NewLine, String.Empty).Replace("  ", String.Empty);

Font courier = FontFactory.GetFont(BaseFont.COURIER, 12f);
courier.Color = BaseColor.GRAY;

Chunk beginning = new Chunk(text, courier);
Phrase p1 = new Phrase(beginning);

Chunk ending = new Chunk("You can of course force a newline using \"", courier);
Phrase p2 = new Phrase();
p2.Add(ending);

Paragraph p = new Paragraph();
p.Add(p1);
p.Add(p2);
document.Add(p);

7、列表

在iTextSharp中列表的創(chuàng)建是通過iTextSharp.text.List對象實(shí)現(xiàn)的。列表實(shí)質(zhì)上是iTextSharp.text.ListItem的集合.也就是由ListItem組成的數(shù)組.ListItem繼承了Paragraph對象(而Paragraph對象繼承于Phrase,Phrase又繼承于Arraylist),所以生成的每一個(gè)List都會自動換行.就如同List在HTML分為<ul>和<ol>一樣,iTextSharp中列表同樣分為有序列表和無序列表.下面我們來直接看如何生成列表的代碼:

第一件事是創(chuàng)建一個(gè)List對象,并傳入一個(gè)布爾類型的參數(shù)告訴List生成的是有序或無序列表.默認(rèn)是False(也就是無序列表),  第二個(gè)參數(shù)(float類型)傳入List的構(gòu)造函數(shù),用于將每一個(gè)列表項(xiàng)的縮進(jìn)設(shè)置成10(也就是列表符號和列表項(xiàng)第一個(gè)字符的距離。).然后我通過SetListSymbol方法將列表項(xiàng)符號改成更傳統(tǒng)的”.”,最后我將整個(gè)列表向右縮進(jìn)30然后為List加入了5個(gè)項(xiàng)。第一個(gè)項(xiàng)是通過匿名函數(shù)傳入String參數(shù)類型來創(chuàng)建ListItem并傳入,從第二個(gè)開始,則是直接傳入String類型的參數(shù).最后是創(chuàng)建一個(gè)Paragraph對象和list對象共同傳入document。

如果你使用有序列表并將羅馬數(shù)字作為標(biāo)識,你可以使用RomanList類。

List list = new List(List.UNORDERED, 10f);
list.SetListSymbol("\u2022");
list.IndentationLeft = 30f;

list.Add(new ListItem("One"));
list.Add("Two");
list.Add("Three");
list.Add("Four");
list.Add("Five");

Paragraph para = new Paragraph();
para.Add("Lists");
document.Add(para);
document.Add(list);

8.向PDF里面添加圖片。

Fimg為圖片路徑,創(chuàng)建一個(gè)iTextSharp.text.Image對象,將該對象添加到文檔里面。SetAbsolutePosition方法是設(shè)置圖片出現(xiàn)的位置。

在iTextSharp中使用Image.GetInstance()方法創(chuàng)建圖片有很多種方式許最常用的方式是傳文件的路徑名:

string imgurl = @System.Web.HttpContext.Current.Server.MapPath(Fimg);
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imgurl);
img.SetAbsolutePosition(0, 0);
writer.DirectContent.AddImage(img);

設(shè)置圖片的屬性和方法

Image jpg = Image.GetInstance("Sunset.jpg");
Paragraph paragraph = new Paragraph(@"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Suspendisse blandit blandit turpis. Nam in lectus ut dolor consectetuer bibendum. Morbi neque ipsum, laoreet id; dignissim et, viverra id, mauris. Nulla mauris elit, consectetuer sit amet, accumsan eget, congue ac, libero. Vivamus suscipit. Nunc dignissim consectetuer lectus. Fusce elit nisi; commodo non, facilisis quis, hendrerit eu, dolor? Suspendisse eleifend nisi ut magna. Phasellus id lectus! Vivamus laoreet enim et dolor. Integer arcu mauris, ultricies vel, porta quis, venenatis at, libero. Donec nibh est, adipiscing et, ullamcorper vitae, placerat at, diam. Integer ac turpis vel ligula rutrum auctor! Morbi egestas erat sit amet diam. Ut ut ipsum? Aliquam non sem. Nulla risus eros, mollis quis, blandit ut; luctus eget, urna. Vestibulum vestibulum dapibus erat. Proin egestas leo a metus?");
paragraph.Alignment = Element.ALIGN_JUSTIFIED;
jpg.ScaleToFit(250f, 250f);
jpg.Alignment = Image.TEXTWRAP | Image.ALIGN_RIGHT;
jpg.IndentationLeft = 9f;
jpg.SpacingAfter = 9f;
jpg.BorderWidthTop = 36f;
jpg.BorderColorTop = BaseColor.WHITE;
jpg.Border = Rectangle.BOX;
jpg.BorderColor = BaseColor.YELLOW;
jpg.BorderWidth = 5f;

document.Add(jpg);
document.Add(paragraph);

9.向PDF里面添加表格,表格對象為PdfTable對象。

iTextSharp中表格元素的命名方式和HTML與CSS中非常類似。iTextSharp提供了多個(gè)類用于創(chuàng)建表格,為了不讓讀者產(chǎn)生混淆,這里我使用PdfPTable這個(gè)專門為在PDF中創(chuàng)建表格的類,下面代碼展示了如何創(chuàng)建一個(gè)表格并將其加入PDF中:

PdfPTable table = new PdfPTable(3);//為pdfpTable的構(gòu)造函數(shù)傳入整數(shù)3,pdfpTable被初始化為一個(gè)三列的表格
PdfPCell cell = new PdfPCell(new Phrase("Header spanning 3 columns"));
cell.Colspan = 3;
cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
table.AddCell(cell);
table.AddCell("Col 1 Row 1");
table.AddCell("Col 2 Row 1");
table.AddCell("Col 3 Row 1");
table.AddCell("Col 1 Row 2");
table.AddCell("Col 2 Row 2");
table.AddCell("Col 3 Row 2");
document.Add(table);

為pdfpTabled添加單元格有多種方式,第一個(gè)單元格是通過PdfPCell對象添加進(jìn)去的,PdfPCell的構(gòu)造函數(shù)接受一個(gè)Phrase對象作為參數(shù),然后將Cell的colspan設(shè)置為3,這樣這個(gè)單元格占了整個(gè)一行.就像HTML中表格那樣,單元格的水平對齊方式使用了三個(gè)值中的一個(gè)(譯者:左對齊,居中,右對齊),這三個(gè)值我加在了注釋中。后面的單元格我都通過AddCell方法加入,最后文檔的效果如下:

下面的示例一開始被初始化為兩列的表格,然后設(shè)置了表格的固定寬度,然后對每一列設(shè)置相對寬度為別為整個(gè)表格的三分之一和三分之二。如果你想將寬度設(shè)置為5分之一和是5分之四,只需要將參數(shù)分別改為1f和4f.如果你想設(shè)置每列的絕對寬度,只需要將列寬度和表格的總寬度傳入

PdfPTable table = new PdfPTable(2);
//actual width of table in points
table.TotalWidth = 216f;

//fix the absolute width of the table
table.LockedWidth = true;

//relative col widths in proportions - 1/3 and 2/3
float[] widths = new float[] { 1f, 2f };
table.SetWidths(widths);
table.HorizontalAlignment = 0;

該類的構(gòu)造函數(shù)可以設(shè)置表格的列數(shù),new float[] { 180, 140, 140, 160, 180, 140, 194 }里面是每列的寬度,也可在構(gòu)造函數(shù)里面直接寫列數(shù)如:new PdfPTable(3);

接下來需要將單元格扔到表格里面,單元格為PdfPCell對象,構(gòu)造函數(shù)里面可以寫入單元格要顯示的文本信息,其中fontb為字體,如果是顯示中文必須創(chuàng)建中文字體:

BaseFont bsFont = BaseFont.CreateFont(@System.Web.HttpContext.Current.Server.MapPath("./upload/fonts/MSYH.TTC") + ",0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font fontb = new Font(bsFont, Tab_Content_FontSize, Font.BOLD, new BaseColor(0xFF, 0xFF, 0xFF));

單元格創(chuàng)建出來扔到表格中排列方式類似與HTML里面的流式布局,沒有行一說,所以造的單元格數(shù)量和列數(shù)相掛鉤才能顯示正確。

PdfPTable tablerow1 = new PdfPTable(new float[] { 180, 140, 140, 160, 180, 140, 194 });
tablerow1.TotalWidth = 1000; //表格寬度
tablerow1.LockedWidth = true;
 
//造單元格
PdfPCell cell11 = new PdfPCell(new Paragraph("單元格內(nèi)容", fontb));
cell11.HorizontalAlignment = 1;
cell11.PaddingBottom = 10;
cell11.PaddingTop = 10;
cell11.BorderColor = borderColor;
cell11.SetLeading(1.2f, 1.2f);
tablerow1.AddCell(cell11);//將單元格添加到表格中
            
document.Add(tablerow1);//將表格添加到pdf文檔中

單元格格式可以進(jìn)行設(shè)置:

  • HorizontalAlignment:代表單元格內(nèi)文本的對齊方式
  • PaddingBottom和PaddingTop:為單元格內(nèi)間距(下,上)
  • BorderColor:邊框顏色
  • SetLeading():該方法設(shè)置單元格內(nèi)多行文本的行間距
PdfPTable table = new PdfPTable(3);
table.AddCell("Cell 1");
PdfPCell cell = new PdfPCell(new Phrase("Cell 2", FontFactory.GetFont(BaseFont.COURIER, 12f, Font.NORMAL, BaseColor.YELLOW)));
cell.BackgroundColor = new BaseColor(0, 150, 0);
cell.BorderColor = new BaseColor(255, 242, 0);
cell.Border = Rectangle.BOTTOM_BORDER | Rectangle.TOP_BORDER;
cell.BorderWidthBottom = 3f;
cell.BorderWidthTop = 3f;
cell.PaddingBottom = 10f;
cell.PaddingLeft = 20f;
cell.PaddingTop = 4f;
table.AddCell(cell);
table.AddCell("Cell 3");
document.Add(table);

10.圖像和文本的絕對位置

將文本放到頁面指定位置PdfContentByte。

PdfContent對象可以通過在使用Writer對象中使用getDirectContent()方法來得到該對象。

PdfContentByte cb = writer.DirectContent;
Phrase txt = new Phrase("測試文本", fontb);
ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, txt,  425, 460, 0);

我們可以使用諸如moveTo和lineTo方法移動到頁面上當(dāng)前位置然后畫一條直線到其他位置。例如

cb.LineWidth=10f;
cb.moveTo(100,700);
cb.lineTo(200,800);
cb.stroke();

11.創(chuàng)建新的頁面

如果想要?jiǎng)?chuàng)建出新一頁的話需要使用代碼:

document.NewPage();

如果創(chuàng)建的新頁面需要重新開始計(jì)算頁數(shù)的話,在創(chuàng)建新頁面之前:

document.ResetPageCount();

12.添加頁眉頁腳及水印

添加頁眉頁腳及水印,頁腳需要顯示頁數(shù),如果正常添加很簡單,但需求里面要求有背景色,有水印,而且背景色在最底層,水印在上層,文字表格等在最上層,處理這個(gè)需求是整個(gè)iTextSharp最難的地方。

先分析一下,如果在創(chuàng)建Rectangle對象的時(shí)候添加背景色,那么接下來加水印有兩種可選情況:

1.水印加在內(nèi)容下面,可選,但水印會加到背景色的下面導(dǎo)致水印不顯示。

2.水印加在內(nèi)容上面,不可選,水印會覆蓋最上層的文字,實(shí)現(xiàn)的效果不好。

為了解決這個(gè)問題,找到了iTextSharp提供的一個(gè)接口IPdfPageEvent及PdfPageEventHelper,該接口里面有一個(gè)方法可以實(shí)現(xiàn),該方法為:OnEndPage當(dāng)頁面創(chuàng)建完成時(shí)觸發(fā)執(zhí)行。

那么就利用這個(gè)方法來實(shí)現(xiàn):先添加背景色,再添加水印,添加在內(nèi)容下方即可。

實(shí)現(xiàn)該方法需要一個(gè)類來實(shí)現(xiàn)接口:

public class IsHandF : PdfPageEventHelper, IPdfPageEvent
{
        /// <summary>
        /// 創(chuàng)建頁面完成時(shí)發(fā)生 
        /// </summary>
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            base.OnEndPage(writer, document);
 
            //頁眉頁腳使用字體
            BaseFont bsFont = BaseFont.CreateFont(@System.Web.HttpContext.Current.Server.MapPath("./upload/fonts/MSYH.TTC") + ",0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            iTextSharp.text.Font fontheader = new iTextSharp.text.Font(bsFont, 30, iTextSharp.text.Font.BOLD);
            iTextSharp.text.Font fontfooter = new iTextSharp.text.Font(bsFont, 20, iTextSharp.text.Font.BOLD);
            //水印文件地址
            string syurl = "./upload/images/sys/black.png";
               
            //獲取文件流
            PdfContentByte cbs = writer.DirectContent;          
            cbs.SetCharacterSpacing(1.3f); //設(shè)置文字顯示時(shí)的字間距
            Phrase header = new Phrase("頁眉", fontheader);
            Phrase footer = new Phrase(writer.PageNumber.ToString(), fontfooter); //writer.PageNumber.ToString()為頁碼。
            //頁眉顯示的位置 
            ColumnText.ShowTextAligned(cbs, Element.ALIGN_CENTER, header,
                       document.Right / 2, document.Top + 40, 0);
            //頁腳顯示的位置 
            ColumnText.ShowTextAligned(cbs, Element.ALIGN_CENTER, footer,
                       document.Right / 2, document.Bottom - 40, 0);
 
            //添加背景色及水印,在內(nèi)容下方添加
            PdfContentByte cba = writer.DirectContentUnder;
            //背景色
            Bitmap bmp = new Bitmap(1263, 893);
            Graphics g = Graphics.FromImage(bmp);
            Color c = Color.FromArgb(0x33ff33);
            SolidBrush b = new SolidBrush(c);//這里修改顏色
            g.FillRectangle(b, 0, 0, 1263, 893);
            System.Drawing.Image ig = bmp;
            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(ig, new BaseColor(0xFF, 0xFF, 0xFF));
            img.SetAbsolutePosition(0, 0);
            cba.AddImage(img);
 
            //水印
            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(@System.Web.HttpContext.Current.Server.MapPath(syurl));
            image.RotationDegrees = 30;//旋轉(zhuǎn)角度
 
            PdfGState gs = new PdfGState();
            gs.FillOpacity = 0.1f;//透明度
            cba.SetGState(gs);
 
            int x = -1000;
            for (int j = 0; j < 15; j++)
            {
                x = x + 180;
                int a = x;
                int y = -170;
                for (int i = 0; i < 10; i++)
                {
                    a = a + 180;
                    y = y + 180;
                    image.SetAbsolutePosition(a, y);
                    cba.AddImage(image);
                }
            }
        }
    }

該類創(chuàng)建完成后,在需要添加頁眉頁腳水印的頁面代碼位置添加如下代碼,整個(gè)文檔生成過程中添加一次即可,確保該事件可以觸發(fā),添加該代碼后在剩余的頁面都會觸發(fā)生成頁眉頁腳:

writer.PageEvent = new IsHandF();

到此這篇關(guān)于C#使用iTextSharp操作PDF的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論

嘉定区| 康乐县| 东光县| 延津县| 托克逊县| 渝北区| 县级市| 阜康市| 武平县| 乳山市| 滨海县| 邯郸县| 竹北市| 历史| 兴海县| 遂溪县| 盖州市| 盈江县| 黄冈市| 嘉兴市| 邮箱| 龙陵县| 金堂县| 杭锦后旗| 阳城县| 南川市| 顺平县| 资中县| 邳州市| 嘉禾县| 大理市| 高尔夫| 木兰县| 荆州市| 合川市| 乌鲁木齐市| 伊吾县| 本溪市| 霞浦县| 莱州市| 黄石市|