溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C#如何使用iTextSharp操作PDF

發(fā)布時間:2022-06-10 10:04:57 來源:億速云 閱讀:1404 作者:iii 欄目:開發(fā)技術(shù)

這篇“C#如何使用iTextSharp操作PDF”文章的知識點(diǎn)大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“C#如何使用iTextSharp操作PDF”文章吧。

一、介紹

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

二、使用

1.下載安裝組件

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

iTextSharp最新版本為5.5.13.1

C#如何使用iTextSharp操作PDF

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)都是半英尺。

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

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

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

var doc = new Document(PageSize.A5);

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

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

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

第二個構(gòu)造函數(shù)以Rectangle和四個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è)置背景色。這個設(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)這個功能:

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)在僅僅是生成一個新的字體定義。
    下面的代碼創(chuàng)建了一個BaseFont對象并且使用內(nèi)置的constant值來設(shè)置字體類型和編碼類型。在是否將字體嵌入PDF中選擇了False以減少PDF的大小使用BaseFont來創(chuàng)建一個新的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()方法。返回一個你可以直接操作的Font對象。并且提供了14種不同的重載來給你提供更多選項(xiàng)。包括:字體,顏色, 風(fēng)格,是否嵌入,編碼以及緩存等。
    每次你調(diào)用FontFactory.GetFont()時都會返回一個新的對象。這個方法對于字體的設(shè)置可以對任何在iTextSharp中注冊的字體進(jìn)行生效。
    在iTextSharp中注冊的字體包括windows字體的默認(rèn)目錄,這個目錄一般為”C:/WINDOWS/Fonts”,如果你想知道哪些字體在iTextSharp中已注冊,F(xiàn)ontFactory.RegisteredFonts將會告訴你答案,查看這個列表對于我們想獲得確切的字體名稱尤為重要。
    下面的一些方法使用iTextSharp的Color對象的constant值來設(shè)置字體顏色,還有諸如使用SetColor()方法傳入RGB值或是New一個Color對象傳入。通常情況下,我們都可以傳入int值作為字體風(fēng)格參數(shù),或者使用SetStyle()方法傳入一個字符串。

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");
  • 第三種方法是直接生成一個新的Font對象。
    有時候你會遇到在WEB服務(wù)器上你沒有權(quán)限安裝字體,這時你必須顯式在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è)置字體和行距.當(dāng)然也可以通過其多種構(gòu)造函數(shù)重載來在初始化時為Phrase添加內(nèi)容.

  • 段落(Paragraphs)是用的最多的類是.Paragraph其實(shí)是一組有序Phrase和Chunk的集合。Paragraph派生于Phrase,所以和Phrase一樣,Paragraph也會在長度超過文檔長度時自動換行。不僅如此,Paragraph和Paragraph之間也會自動空一行(就像文字處理軟件那樣)。

下面代碼中,我會將格式化的文本通過Chunk和Phrase來添加到Paragraphs中:每一個設(shè)置了風(fēng)格樣式的字體都需要包含在一個Chunk中,然后再將Chunk添加到Phrase來確保文字會自動換行,最后,所有Phrase和Chunk都會被添加到Paragraph對象中。還可以通過Paragraph.setAlignment()設(shè)置Paragraph的對齊方式,這個方法接受一個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),所以生成的每一個List都會自動換行.就如同List在HTML分為<ul>和<ol>一樣,iTextSharp中列表同樣分為有序列表和無序列表.下面我們來直接看如何生成列表的代碼:

第一件事是創(chuàng)建一個List對象,并傳入一個布爾類型的參數(shù)告訴List生成的是有序或無序列表.默認(rèn)是False(也就是無序列表),  第二個參數(shù)(float類型)傳入List的構(gòu)造函數(shù),用于將每一個列表項(xiàng)的縮進(jìn)設(shè)置成10(也就是列表符號和列表項(xiàng)第一個字符的距離。).然后我通過SetListSymbol方法將列表項(xiàng)符號改成更傳統(tǒng)的”.”,最后我將整個列表向右縮進(jìn)30然后為List加入了5個項(xiàng)。第一個項(xiàng)是通過匿名函數(shù)傳入String參數(shù)類型來創(chuàng)建ListItem并傳入,從第二個開始,則是直接傳入String類型的參數(shù).最后是創(chuàng)建一個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)建一個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提供了多個類用于創(chuàng)建表格,為了不讓讀者產(chǎn)生混淆,這里我使用PdfPTable這個專門為在PDF中創(chuàng)建表格的類,下面代碼展示了如何創(chuàng)建一個表格并將其加入PDF中:

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

C#如何使用iTextSharp操作PDF

下面的示例一開始被初始化為兩列的表格,然后設(shè)置了表格的固定寬度,然后對每一列設(shè)置相對寬度為別為整個表格的三分之一和三分之二。如果你想將寬度設(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)建新的頁面

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

document.NewPage();

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

document.ResetPageCount();

12.添加頁眉頁腳及水印

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

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

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

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

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

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

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

public class IsHandF : PdfPageEventHelper, IPdfPageEvent
{
        /// <summary>
        /// 創(chuàng)建頁面完成時發(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è)置文字顯示時的字間距
            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)建完成后,在需要添加頁眉頁腳水印的頁面代碼位置添加如下代碼,整個文檔生成過程中添加一次即可,確保該事件可以觸發(fā),添加該代碼后在剩余的頁面都會觸發(fā)生成頁眉頁腳:

writer.PageEvent = new IsHandF();

以上就是關(guān)于“C#如何使用iTextSharp操作PDF”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對大家有幫助,若想了解更多相關(guān)的知識內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI