iText介紹

iText介紹

? 轉(zhuǎn)自https://www.cnblogs.com/h--d/p/6150320.html 記錄筆記

iText是著名的開放源碼的站點(diǎn)sourceforge一個項(xiàng)目媒抠,是用于生成PDF文檔的一個java類庫逆趋。通過iText不僅可以生成PDF或rtf的文檔奕扣,而且可以將XML茄螃、Html文件轉(zhuǎn)化為PDF文件。

項(xiàng)目要使用iText,必須引入jar包吴超。才能使用奴烙,maven依賴如下:

1 <dependency>
2     <groupId>com.itextpdf</groupId>
3     <artifactId>itextpdf</artifactId>
4     <version>5.5.10</version>
5 </dependency>

輸出中文庄呈,還要引入下面itext-asian.jar包:

1 <dependency>
2     <groupId>com.itextpdf</groupId>
3     <artifactId>itext-asian</artifactId>
4     <version>5.2.0</version>
5 </dependency>

? 設(shè)置pdf文件密碼蜕煌,還要引入下面bcprov-jdk15on.jar包:

1 <dependency>
2     <groupId>org.bouncycastle</groupId>
3     <artifactId>bcprov-jdk15on</artifactId>
4     <version>1.54</version>
5 </dependency>

iText常用類

  • com.itextpdf.text.Document:這是iText庫中最常用的類,它代表了一個pdf實(shí)例诬留。如果你需要從零開始生成一個PDF文件斜纪,你需要使用這個Document類。首先創(chuàng)建(new)該實(shí)例文兑,然后打開(open)它盒刚,并添加(add)內(nèi)容,最后關(guān)閉(close)該實(shí)例彩届,即可生成一個pdf文件伪冰。
  • com.itextpdf.text.Paragraph:表示一個縮進(jìn)的文本段落誓酒,在段落中樟蠕,你可以設(shè)置對齊方式,縮進(jìn)靠柑,段落前后間隔等寨辩。
  • com.itextpdf.text.Chapter:表示PDF的一個章節(jié),他通過一個Paragraph類型的標(biāo)題和整形章數(shù)創(chuàng)建歼冰。
  • com.itextpdf.text.Font:這個類包含了所有規(guī)范好的字體靡狞,包括family of font,大小隔嫡,樣式和顏色甸怕,所有這些字體都被聲明為靜態(tài)常量。
  • com.itextpdf.text.List:表示一個列表腮恩;
  • cocom.itextpdf.text.List:表示一個列表梢杭;
  • com.itextpdf.text.Anchor:表示一個錨,類似于HTML頁面的鏈接秸滴。
  • com.itextpdf.text.pdf.PdfWriter:當(dāng)這個PdfWriter被添加到PdfDocument后武契,所有添加到Document的內(nèi)容將會寫入到與文件或網(wǎng)絡(luò)關(guān)聯(lián)的輸出流中。
  • com.itextpdf.text.pdf.PdfReader:用于讀取PDF文件荡含;

iText使用

  1. 創(chuàng)建一個簡單的pdf文件咒唆,如下:

     1 package com.hd.pdf;
     2 
     3 import java.io.FileNotFoundException;
     4 import java.io.FileOutputStream;
     5 
     6 import com.itextpdf.text.Document;
     7 import com.itextpdf.text.DocumentException;
     8 import com.itextpdf.text.Paragraph;
     9 import com.itextpdf.text.pdf.PdfWriter;
    10 
    11 public class TestPDFDemo1 {
    12 
    13     public static void main(String[] args) throws FileNotFoundException, DocumentException {
    14 
    15         // 1.新建document對象
    16         Document document = new Document();
    17 
    18         // 2.建立一個書寫器(Writer)與document對象關(guān)聯(lián),通過書寫器(Writer)可以將文檔寫入到磁盤中释液。
    19         // 創(chuàng)建 PdfWriter 對象 第一個參數(shù)是對文檔對象的引用全释,第二個參數(shù)是文件的實(shí)際名稱,在該名稱中還會給出其輸出路徑误债。
    20         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:/Users/H__D/Desktop/test.pdf"));
    21 
    22         // 3.打開文檔
    23         document.open();
    24         
    25         // 4.添加一個內(nèi)容段落
    26         document.add(new Paragraph("Hello World!"));
    27 
    28         // 5.關(guān)閉文檔
    29         document.close();
    30 
    31     }
    32 
    33 }
    

打開文件

img
  1. 給PDF文件設(shè)置文件屬性浸船,例如:

     1 public static void main(String[] args) throws FileNotFoundException, DocumentException {
     2         
     3         //創(chuàng)建文件
     4         Document document = new Document();
     5         //建立一個書寫器
     6         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:/Users/H__D/Desktop/test2.pdf"));
     7         //打開文件
     8         document.open();
     9         //添加內(nèi)容
    10         document.add(new Paragraph("Some content here"));
    11      
    12         //設(shè)置屬性
    13         //標(biāo)題
    14         document.addTitle("this is a title");
    15         //作者
    16         document.addAuthor("H__D");
    17         //主題
    18         document.addSubject("this is subject");
    19         //關(guān)鍵字
    20         document.addKeywords("Keywords");
    21         //創(chuàng)建時間
    22         document.addCreationDate();
    23         //應(yīng)用程序
    24         document.addCreator("hd.com");
    25         
    26         //關(guān)閉文檔
    27         document.close();
    28         //關(guān)閉書寫器
    29         writer.close();
    30     }
    

    打開文件
    [圖片上傳失敗...(image-8ed6aa-1582768057652)]

  2. PDF中添加圖片

     1 public static void main(String[] args) throws DocumentException, IOException {
     2         
     3         //創(chuàng)建文件
     4         Document document = new Document();
     5         //建立一個書寫器
     6         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:/Users/H__D/Desktop/test3.pdf"));
     7         //打開文件
     8         document.open();
     9         //添加內(nèi)容
    10         document.add(new Paragraph("HD content here"));
    11      
    12         //圖片1
    13         Image image1 = Image.getInstance("C:/Users/H__D/Desktop/IMG_0109.JPG");
    14         //設(shè)置圖片位置的x軸和y周
    15         image1.setAbsolutePosition(100f, 550f);
    16         //設(shè)置圖片的寬度和高度
    17         image1.scaleAbsolute(200, 200);
    18         //將圖片1添加到pdf文件中
    19         document.add(image1);
    20      
    21         //圖片2
    22         Image image2 = Image.getInstance(new URL("http://static.cnblogs.com/images/adminlogo.gif"));
    23         //將圖片2添加到pdf文件中
    24         document.add(image2);
    25         
    26         //關(guān)閉文檔
    27         document.close();
    28         //關(guān)閉書寫器
    29         writer.close();
    30     }
    

打開文件


img
  1. PDF中創(chuàng)建表格
 1 public static void main(String[] args) throws DocumentException, FileNotFoundException {
 2         //創(chuàng)建文件
 3         Document document = new Document();
 4         //建立一個書寫器
 5         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:/Users/H__D/Desktop/test4.pdf"));
 6         //打開文件
 7         document.open();
 8         //添加內(nèi)容
 9         document.add(new Paragraph("HD content here"));
10      
11         // 3列的表.
12         PdfPTable table = new PdfPTable(3); 
13         table.setWidthPercentage(100); // 寬度100%填充
14         table.setSpacingBefore(10f); // 前間距
15         table.setSpacingAfter(10f); // 后間距
16 
17         List<PdfPRow> listRow = table.getRows();
18         //設(shè)置列寬
19         float[] columnWidths = { 1f, 2f, 3f };
20         table.setWidths(columnWidths);
21         
22         //行1
23         PdfPCell cells1[]= new PdfPCell[3];
24         PdfPRow row1 = new PdfPRow(cells1);
25        
26         //單元格
27         cells1[0] = new PdfPCell(new Paragraph("111"));//單元格內(nèi)容
28         cells1[0].setBorderColor(BaseColor.BLUE);//邊框驗(yàn)證
29         cells1[0].setPaddingLeft(20);//左填充20
30         cells1[0].setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
31         cells1[0].setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
32 
33         cells1[1] = new PdfPCell(new Paragraph("222"));
34         cells1[2] = new PdfPCell(new Paragraph("333"));
35         
36         //行2
37         PdfPCell cells2[]= new PdfPCell[3];
38         PdfPRow row2 = new PdfPRow(cells2);
39         cells2[0] = new PdfPCell(new Paragraph("444"));
40 
41         //把第一行添加到集合
42         listRow.add(row1);
43         listRow.add(row2);
44         //把表格添加到文件中
45         document.add(table);
46         
47         //關(guān)閉文檔
48         document.close();
49         //關(guān)閉書寫器
50         writer.close();
51     }

打開文件


img
  1. PDF中創(chuàng)建列表
 1 public static void main(String[] args) throws DocumentException, FileNotFoundException {
 2         //創(chuàng)建文件
 3         Document document = new Document();
 4         //建立一個書寫器
 5         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:/Users/H__D/Desktop/test5.pdf"));
 6         //打開文件
 7         document.open();
 8         //添加內(nèi)容
 9         document.add(new Paragraph("HD content here"));
10      
11         //添加有序列表
12         List orderedList = new List(List.ORDERED);
13         orderedList.add(new ListItem("Item one"));
14         orderedList.add(new ListItem("Item two"));
15         orderedList.add(new ListItem("Item three"));
16         document.add(orderedList);
17 
18         //關(guān)閉文檔
19         document.close();
20         //關(guān)閉書寫器
21         writer.close();
22     }

打開文件

![img](https://upload-images.jianshu.io/upload_images/21608567-84f3897a36e37bc5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
  1. PDF中設(shè)置樣式/格式化輸出符衔,輸出中文內(nèi)容,必須引入itext-asian.jar
 1 public static void main(String[] args) throws DocumentException, IOException {
 2         //創(chuàng)建文件
 3         Document document = new Document();
 4         //建立一個書寫器
 5         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:/Users/H__D/Desktop/test6.pdf"));
 6         //打開文件
 7         document.open();
 8         
 9         //中文字體,解決中文不能顯示問題
10         BaseFont bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
11         
12         //藍(lán)色字體
13         Font blueFont = new Font(bfChinese);
14         blueFont.setColor(BaseColor.BLUE);
15         //段落文本
16         Paragraph paragraphBlue = new Paragraph("paragraphOne blue front", blueFont);
17         document.add(paragraphBlue);
18      
19         //綠色字體
20         Font greenFont = new Font(bfChinese);
21         greenFont.setColor(BaseColor.GREEN);
22         //創(chuàng)建章節(jié)
23         Paragraph chapterTitle = new Paragraph("段落標(biāo)題xxxx", greenFont);
24         Chapter chapter1 = new Chapter(chapterTitle, 1);
25         chapter1.setNumberDepth(0);
26        
27         Paragraph sectionTitle = new Paragraph("部分標(biāo)題", greenFont);
28         Section section1 = chapter1.addSection(sectionTitle);
29      
30         Paragraph sectionContent = new Paragraph("部分內(nèi)容", blueFont);
31         section1.add(sectionContent);
32         
33         //將章節(jié)添加到文章中
34         document.add(chapter1);
35         
36         //關(guān)閉文檔
37         document.close();
38         //關(guān)閉書寫器
39         writer.close();
40     }

打開文件


img

img
  1. 給PDF文件設(shè)置密碼糟袁,需要引入bcprov-jdk15on.jar包:
 1 public static void main(String[] args) throws DocumentException, IOException {
 2         // 創(chuàng)建文件
 3         Document document = new Document();
 4         // 建立一個書寫器
 5         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:/Users/H__D/Desktop/test8.pdf"));
 6 
 7         //用戶密碼
 8         String userPassword = "123456";
 9         //擁有者密碼
10         String ownerPassword = "hd";
11         writer.setEncryption(userPassword.getBytes(), ownerPassword.getBytes(), PdfWriter.ALLOW_PRINTING,
12                 PdfWriter.ENCRYPTION_AES_128);
13 
14         // 打開文件
15         document.open();
16         
17         //添加內(nèi)容
18         document.add(new Paragraph("password !!!!"));
19 
20         // 關(guān)閉文檔
21         document.close();
22         // 關(guān)閉書寫器
23         writer.close();
24     }

打開文件


img
  1. 給PDF文件設(shè)置權(quán)限
 1 public static void main(String[] args) throws DocumentException, IOException {
 2         // 創(chuàng)建文件
 3         Document document = new Document();
 4         // 建立一個書寫器
 5         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:/Users/H__D/Desktop/test9.pdf"));
 6 
 7         // 只讀權(quán)限
 8         writer.setEncryption("".getBytes(), "".getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);
 9 
10         // 打開文件
11         document.open();
12 
13         // 添加內(nèi)容
14         document.add(new Paragraph("password !!!!"));
15 
16         // 關(guān)閉文檔
17         document.close();
18         // 關(guān)閉書寫器
19         writer.close();
20     }
  1. 讀取/修改已有的PDF文件
 1 public static void main(String[] args) throws DocumentException, IOException {
 2         
 3         //讀取pdf文件
 4         PdfReader pdfReader = new PdfReader("C:/Users/H__D/Desktop/test1.pdf");
 5      
 6         //修改器
 7         PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream("C:/Users/H__D/Desktop/test10.pdf"));
 8      
 9         Image image = Image.getInstance("C:/Users/H__D/Desktop/IMG_0109.JPG");
10         image.scaleAbsolute(50, 50);
11         image.setAbsolutePosition(0, 700);
12      
13         for(int i=1; i<= pdfReader.getNumberOfPages(); i++)
14         {
15             PdfContentByte content = pdfStamper.getUnderContent(i);
16             content.addImage(image);
17         }
18      
19         pdfStamper.close();
20     }

打開文件


img

[圖片上傳失敗...(image-dc840e-1582768057652)]

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末判族,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子项戴,更是在濱河造成了極大的恐慌形帮,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,110評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件周叮,死亡現(xiàn)場離奇詭異辩撑,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)仿耽,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,443評論 3 395
  • 文/潘曉璐 我一進(jìn)店門合冀,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人项贺,你說我怎么就攤上這事君躺。” “怎么了开缎?”我有些...
    開封第一講書人閱讀 165,474評論 0 356
  • 文/不壞的土叔 我叫張陵棕叫,是天一觀的道長。 經(jīng)常有香客問我奕删,道長俺泣,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,881評論 1 295
  • 正文 為了忘掉前任完残,我火速辦了婚禮伏钠,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘谨设。我一直安慰自己熟掂,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,902評論 6 392
  • 文/花漫 我一把揭開白布铝宵。 她就那樣靜靜地躺著打掘,像睡著了一般。 火紅的嫁衣襯著肌膚如雪鹏秋。 梳的紋絲不亂的頭發(fā)上尊蚁,一...
    開封第一講書人閱讀 51,698評論 1 305
  • 那天,我揣著相機(jī)與錄音侣夷,去河邊找鬼横朋。 笑死,一個胖子當(dāng)著我的面吹牛百拓,可吹牛的內(nèi)容都是我干的琴锭。 我是一名探鬼主播晰甚,決...
    沈念sama閱讀 40,418評論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼决帖!你這毒婦竟也來了厕九?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,332評論 0 276
  • 序言:老撾萬榮一對情侶失蹤地回,失蹤者是張志新(化名)和其女友劉穎扁远,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體刻像,經(jīng)...
    沈念sama閱讀 45,796評論 1 316
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡畅买,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,968評論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了细睡。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片谷羞。...
    茶點(diǎn)故事閱讀 40,110評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖溜徙,靈堂內(nèi)的尸體忽然破棺而出湃缎,到底是詐尸還是另有隱情,我是刑警寧澤萌京,帶...
    沈念sama閱讀 35,792評論 5 346
  • 正文 年R本政府宣布雁歌,位于F島的核電站宏浩,受9級特大地震影響知残,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜比庄,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,455評論 3 331
  • 文/蒙蒙 一求妹、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧佳窑,春花似錦制恍、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,003評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至坡慌,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間渣玲,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,130評論 1 272
  • 我被黑心中介騙來泰國打工藻雪, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留指煎,地道東北人。 一個月前我還...
    沈念sama閱讀 48,348評論 3 373
  • 正文 我出身青樓晋渺,卻偏偏與公主長得像,于是被迫代替她去往敵國和親吗讶。 傳聞我的和親對象是個殘疾皇子鸠信,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,047評論 2 355

推薦閱讀更多精彩內(nèi)容