iText5官方系列教程-iText in Action(一)
1 iText 的介紹和說明
?如果你想通過java操作PDF文件,那么 iText 絕對是你的首選。我接觸iText 是因為公司有一個需求想要針對已經學完課程的學員提供PDF格式的結業證書下載。由于對iText一無所知,所以自己在網上各種搜索iText先關資料,并完成了當時的需求功能的開發。但是并沒有對iText有很深入了解。于是想寫一個iText 教程系列專題,一方面加深一下之前的操作,另一方面更深入了解一下iText的其他操作。
在開講之前我先說明一下 我不生產代碼,我只是大自然的搬運工。我將會把itext 官網提供的教程來介紹。您也可以自行訪問官網進行查看相關示例教程。網站是:https://developers.itextpdf.com/examples
我們這里講解的是iText5
我這里會帶大家去看官網示例來更快入手iText,另外建議大家學習新的技術盡可能的去看官網的文檔和示例教程。
我們先來介紹 由Bruno Lowagie?編寫?iText in Action - Second Edition 一書中的HelloWord示例 。因為自己沒有讀過iText in Action 2nd這本書,只是看官網提供的一些代碼示例。代碼中一些語法有很多不理解的地方。在此感謝JulyLuo作者的<<iText in Action 2nd>>1.3節(Creating a PDF document in five steps with iText)讀書筆記?一文,幫助我理解了。
在介紹之前先來搭建我們的基礎環境,開發工具 jdk, maven?,iText 版本本如下:
開發工具:Spring Tool Suite (STS)
jdk版本:1.8.0_144
maven版本: :3.2.5
itextpdf:5.5.11
itext-asian:5.2.0
需要引入pom AGV:
<dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.11</version> </dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version> </dependency>2 iText in Action hello word 示例代碼介紹
第1章:PDF和iText簡介
文章網站:https://developers.itextpdf.com/examples/itext-action-second-edition/chapter-1
1.1?第一個iText示例:Hello World
快速入手iText攏共需要5步:
具體代碼如下:
package cn.zhuoqianmingyue.chapter_1;import java.io.FileOutputStream; import java.io.IOException; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter;/*** 第1章:PDF和iText簡介* 1.1第一個iText示例:Hello World*/ public class HelloWorld {/** 生成的PDF文件的路徑。 */public static final String RESULT = "D:/results/part1/chapter01/hello.pdf";/*** 創建一個PDF文件:hello.pdf * @param args no arguments needed*/public static void main(String[] args) throws DocumentException, IOException {new HelloWorld().createPdf(RESULT);}/*** 創建PDF文檔.* @param filename 新PDF文檔的路徑* @throws DocumentException * @throws IOException */public void createPdf(String filename) throws DocumentException, IOException {// 第一步 創建文檔實例Document document = new Document();// 第二步 獲取PdfWriter實例PdfWriter.getInstance(document, new FileOutputStream(filename));// 第三步 打開文檔document.open();// 第四步 添加段落內容document.add(new Paragraph("Hello World!"));// 第五部 操作完成后必須執行文檔關閉操作。document.close();} }具體代碼如下:
生成文件效果如下:
1.2 文檔構造函數示例
該示例通過?Document構造函數來設置頁面的大小尺寸和 頁面邊距。
Document(Rectangle pageSize, float marginLeft, float marginRight, float marginTop, float marginBottom)
其中通過?Rectangle(寬,高)來指定pdf頁面的尺寸大小,通過marginLeft??marginRight?marginTop?marginBottom來設置頁面邊距
具體代碼如下:
package cn.zhuoqianmingyue.chapter_1;import java.io.FileOutputStream; import java.io.IOException;import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.PdfWriter; /*** 1.2 Document 構造函數*/ public class HelloWorldNarrow {/** 生成的PDF文件的路徑。 */public static final String RESULT= "D:/results/part1/chapter01/hello_narrow.pdf";/*** 創建一個PDF文件: hello_narrow.pdf* @param args no arguments needed*/public static void main(String[] args)throws DocumentException, IOException {// step 1// 自定義頁面大小使用Rectangle pagesize = new Rectangle(216f, 720f);Document document = new Document(pagesize, 36f, 72f, 108f, 180f);// step 2PdfWriter.getInstance(document, new FileOutputStream(RESULT));// step 3document.open();// step 4document.add(new Paragraph("Hello World! Hello People! " +"Hello Sky! Hello Sun! Hello Moon! Hello Stars!"));// step 5document.close();} }生成文件效果如下:
?
1.3 設置最大尺寸頁面的pdf
在pdf中度量單位是用戶單位(user unit)。換算的公式是 1英寸=25.4mm=72 user units≈72pt(磅)。老外的計量單位一般都是英寸,大家仔細看上面的代碼,里面的數字都是36的倍數,也就是0.5英寸。但在iText中,默認的度量單位是pt不是user uint。因為pt和user unit基本上是相等的,而且pt也是比較常用的度量單位。不過我們也可以修改他們之間的對應關系,代碼如下:
通過下面代碼代碼生成的pdf文檔其頁面大小是15000000(14400/72*75000)英寸*15000000英寸,因為1user unit對應了75000pt。(user unit最大的值為75000pt)一(上內容摘抄自<<iText in Action 2nd>>1.3節(Creating a PDF document in five steps with iText)讀書筆記)
1.2 中我們介紹如何設置頁面尺寸的大小 這里我們設置最大的頁面尺寸。pdf最大可設置的尺寸為 寬:14400pt, 高:14400pt
具體代碼如下:
package cn.zhuoqianmingyue.chapter_1;import java.io.FileOutputStream; import java.io.IOException;import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.PdfWriter; /*** 創建最大頁面的pdf*/ public class HelloWorldMaximum {/** Path to the resulting PDF file. */public static final String RESULT = "D:/results/part1/chapter01/hello_maximum.pdf";/*** Creates a PDF file: hello_maximum.pdf* Important notice: the PDF is valid (in conformance with* ISO-32000), but some PDF viewers won't be able to render* the PDF correctly due to their own limitations.* @param args no arguments needed*/public static void main(String[] args)throws DocumentException, IOException {// 第一步//最大頁面尺寸Document document = new Document(new Rectangle(14400, 14400));// 第二步PdfWriter writer =PdfWriter.getInstance(document, new FileOutputStream(RESULT));// 改變用戶單位 使用此方法設置用戶單位。UserUnit是定義默認用戶空間單位的值。最小UserUnit為1(1個單位= 1/72英寸)。最大UserUnit為75,000。請注意,此用戶單元僅適用于從PDF1.6開始!writer.setUserunit(75000f);// step 3document.open();// step 4document.add(new Paragraph("Hello World"));// step 5document.close();} }生成文件效果如下:?
?我嘗試將尺寸改為大于14400 程序報如下錯誤:
?1.4 生成紙張尺寸大小的pdf文件
除了指定pdf尺寸大小的方式外,我們也可以通過在Documnet 構造中通過PageSize.LETTER來指定頁面的大小。在實際開發中PageSize.A4使用的比較多。如果構造不指定的話默認就是PageSize.A4 頁邊距全是36pt。
具體代碼如下:
package cn.zhuoqianmingyue.chapter_1;import java.io.FileOutputStream; import java.io.IOException;import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter;/*** 使用紙張尺寸Letter的Hello World示例。*/ public class HelloWorldLetter {/** 生成的PDF文件的路徑。 */public static final String RESULT = "D:/results/part1/chapter01/hello_letter.pdf";/*** 創建一個PDF文件: hello_letter.pdf.* @param args no arguments needed*/public static void main(String[] args) throws DocumentException, IOException {// 第一步// 指定頁大小Document document = new Document(PageSize.LETTER);// 第二步PdfWriter.getInstance(document, new FileOutputStream(RESULT));// 第三步document.open();// 第四步document.add(new Paragraph("Hello World"));// 第五步document.close();} }生成文件效果如下:??
1.5 橫向顯示pdf通過?rotate()
我們可以通過PageSize.LETTER.rotate() 來設置pdf 橫向顯示 也就是旋轉90度。
具體代碼如下:
package cn.zhuoqianmingyue.chapter_1;import java.io.FileOutputStream; import java.io.IOException;import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter;public class HelloWorldLandscape1 {/** 生成的PDF文件的路徑 */public static final String RESULT = "D:/results/part1/chapter01/hello_landscape1.pdf";/*** 創建一個PDF文件: hello_landscape1.pdf* @param args no arguments needed*/public static void main(String[] args)throws DocumentException, IOException {// 第一步//橫向的格式通過 rotate() 方法Document document = new Document(PageSize.LETTER.rotate());// 第二步PdfWriter.getInstance(document, new FileOutputStream(RESULT));// 第三步document.open();// 第四步document.add(new Paragraph("Hello World"));// 第五步document.close();} }生成文件效果如下:
下圖是豎向的pdf.有對比是不是就比較明顯了。
1.6?橫向顯示pdf通過設置寬高
除了通過rotate() 方法我們也可以指定 pdf文件的寬度大于高度來設置成橫向顯示。
具體代碼如下:
package cn.zhuoqianmingyue.chapter_1;import java.io.FileOutputStream; import java.io.IOException;import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.PdfWriter;public class HelloWorldLandscape2 {/** 生成的PDF文件的路徑 */public static final String RESULT = "D:/results/part1/chapter01/hello_landscape2.pdf";/*** 創建一個PDF文件: hello_landscape2.pdf* @param args no arguments needed*/public static void main(String[] args)throws DocumentException, IOException {// 第一步//橫向格式 通過 寬度 大于 高度Document document = new Document(new Rectangle(792, 612));// 第二步PdfWriter.getInstance(document, new FileOutputStream(RESULT));// 第三步document.open();// 第四步document.add(new Paragraph("Hello World"));// 第五步document.close();} }生成文件效果如下:
1.7 設置頁邊距和裝訂格式
對于需要裝訂成冊的多個pdf,如果是左右裝訂(正反面打印)的話我們第一頁的左邊距要大一點,而第二頁的右邊距要和第一頁的左邊距一樣,也就是保證頁邊距要對稱。具體效果如下圖:
第一頁
第二頁
我們可以通過 setMargins設置頁邊距,通過setMarginMirroring(true) 來設置2頁的邊距對稱。?如果我們的書是上下裝訂的方式那我們就需要通過 setMarginMirroringTopBotton(true) 來實現。具體效果如下圖:
第一頁
?
第二頁
?
具體代碼如下:
package cn.zhuoqianmingyue.chapter_1;import java.io.FileOutputStream; import java.io.IOException;import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter;public class HelloWorldMirroredMargins {/** 生成的PDF文件的路徑。 */public static final String RESULT = "D:/results/part1/chapter01/hello_mirrored_margins.pdf";/*** 創建一個PDF文: hello_mirrored_margins.pdf* @param args no arguments needed*/public static void main(String[] args)throws DocumentException, IOException {// step 1Document document = new Document();// step 2PdfWriter.getInstance(document, new FileOutputStream(RESULT));document.setPageSize(PageSize.A5);document.setMargins(36, 72, 108, 180);document.setMarginMirroring(true);// step 3document.open();// step 4document.add(new Paragraph("The left margin of this odd page is 36pt (0.5 inch); " +"the right margin 72pt (1 inch); " +"the top margin 108pt (1.5 inch); " +"the bottom margin 180pt (2.5 inch)."));Paragraph paragraph = new Paragraph();paragraph.setAlignment(Element.ALIGN_JUSTIFIED);for (int i = 0; i < 20; i++) {paragraph.add("Hello World! Hello People! " +"Hello Sky! Hello Sun! Hello Moon! Hello Stars!");}document.add(paragraph);document.add(new Paragraph("The right margin of this even page is 36pt (0.5 inch); " +"the left margin 72pt (1 inch)."));// step 5document.close();} } package cn.zhuoqianmingyue.chapter_1;import java.io.FileOutputStream; import java.io.IOException;import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter;public class HelloWorldMirroredMarginsTop {/** 生成的PDF文件的路徑。 */public static final String RESULT = "D:/results/part1/chapter01/hello_mirrored_top.pdf";/*** 創建一個PDF文件: hello_mirrored_margins.pdf* @param args no arguments needed*/public static void main(String[] args)throws DocumentException, IOException {// step 1Document document = new Document();// step 2PdfWriter.getInstance(document, new FileOutputStream(RESULT));// setting page size, margins and mirrered marginsdocument.setPageSize(PageSize.A5);document.setMargins(36, 72, 108, 180);document.setMarginMirroringTopBottom(true);// step 3document.open();// step 4document.add(new Paragraph("The left margin of this odd page is 36pt (0.5 inch); " +"the right margin 72pt (1 inch); " +"the top margin 108pt (1.5 inch); " +"the bottom margin 180pt (2.5 inch)."));Paragraph paragraph = new Paragraph();paragraph.setAlignment(Element.ALIGN_JUSTIFIED);for (int i = 0; i < 20; i++) {paragraph.add("Hello World! Hello People! " +"Hello Sky! Hello Sun! Hello Moon! Hello Stars!");}document.add(paragraph);document.add(new Paragraph("The top margin 180pt (2.5 inch)."));// step 5document.close();} }1.8 內存中操作PDF文件
具體代碼如下:
package cn.zhuoqianmingyue.chapter_1;import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.IOException;import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter;public class HelloWorldMemory {/** Path to the resulting PDF file. */public static final String RESULT = "D:/results/part1/chapter01/hello_memory.pdf";/*** 創建一個PDF文件: hello_memory.pdf* @param args no arguments needed*/public static void main(String[] args)throws DocumentException, IOException {// step 1Document document = new Document();// step 2// we'll create the file in memoryByteArrayOutputStream baos = new ByteArrayOutputStream();PdfWriter.getInstance(document, baos);// step 3document.open();// step 4document.add(new Paragraph("Hello World!"));// step 5document.close();// let's write the file in memory to a file anywayFileOutputStream fos = new FileOutputStream(RESULT);fos.write(baos.toByteArray());fos.close();} }1.9 設置pdf 的版本
我們可以通過PdfWriter 的?setPdfVersion 方法來設置我們pdf的版本號。
package cn.zhuoqianmingyue.chapter_1;import java.io.FileOutputStream; import java.io.IOException;import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter;public class HelloWorldVersion_1_7 {/** Path to the resulting PDF file. */public static final String RESULT = "D:/results/part1/chapter01/hello_1_7.pdf";/*** Creates a PDF file: hello.pdf* @param args no arguments needed*/public static void main(String[] args)throws DocumentException, IOException {// step 1Document document = new Document();// step 2// Creating a PDF 1.7 documentPdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));writer.setPdfVersion(PdfWriter.VERSION_1_7);// step 3document.open();// step 4document.add(new Paragraph("Hello World!"));// step 5document.close();} }1.10 HelloWorldDirect :設置指定位置添加pdf的內容 更為直接的方式
該示例程序生成的文件通過記事本打開內容如下:代碼注釋對應的是生成具體內容。更為直接展示如何生成pdf的過程。
package cn.zhuoqianmingyue.chapter_1;import java.io.FileOutputStream; import java.io.IOException;import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfWriter;public class HelloWorldDirect {/** Path to the resulting PDF file. */public static final String RESULT = "D:/results/part1/chapter01/hello_direct.pdf";/*** Creates a PDF file: hello_direct.pdf* @param args no arguments needed*/public static void main(String[] args)throws DocumentException, IOException {// step 1Document document = new Document();// step 2PdfWriter writer =PdfWriter.getInstance(document, new FileOutputStream(RESULT));// step 3document.open();// step 4PdfContentByte canvas = writer.getDirectContentUnder();writer.setCompressionLevel(0);canvas.saveState(); // qcanvas.beginText(); // BTcanvas.moveText(36, 788); // 36 788 Tdcanvas.setFontAndSize(BaseFont.createFont(), 12); // /F1 12 Tfcanvas.showText("Hello World"); // (Hello World)Tjcanvas.endText(); // ETcanvas.restoreState(); // Q// step 5document.close();} }?
1.11 設置指定位置添加pdf的內容 容易理解的方式
和上面的示例生成效果基本一致, 該示例的代碼比上圖的代碼更容易理解。
package cn.zhuoqianmingyue.chapter_1;import java.io.FileOutputStream; import java.io.IOException;import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Phrase; import com.itextpdf.text.pdf.ColumnText; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfWriter;public class HelloWorldColumn {/** Path to the resulting PDF file. */public static final String RESULT = "D:/results/part1/chapter01/hello_column.pdf";/*** Creates a PDF file: hello_column.pdf* @param args no arguments needed*/public static void main(String[] args)throws DocumentException, IOException {// step 1Document document = new Document();// step 2PdfWriter writer= PdfWriter.getInstance(document, new FileOutputStream(RESULT));// step 3document.open();// step 4// we set the compression to 0 so that we can read the PDF syntaxwriter.setCompressionLevel(0);// writes something to the direct content using a convenience methodPhrase hello = new Phrase("Hello World");PdfContentByte canvas = writer.getDirectContentUnder();ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT,hello, 36, 788, 0);// step 5document.close();} }1.12 壓縮多個pdf文件
我們可以通過ZipEntry 將多個pdf壓縮成一個壓縮文件。
package cn.zhuoqianmingyue.chapter_1;import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream;import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter;public class HelloZip {/** Path to the resulting PDF file. */public static final String RESULT = "D:/results/part1/chapter01/hello.zip";/*** Creates a zip file with five PDF documents:* hello1.pdf to hello5.pdf* @param args no arguments needed*/public static void main(String[] args)throws DocumentException, IOException {// creating a zip file with different PDF documentsZipOutputStream zip =new ZipOutputStream(new FileOutputStream(RESULT));for (int i = 1; i <= 3; i++) {ZipEntry entry = new ZipEntry("hello_" + i + ".pdf");zip.putNextEntry(entry);// step 1Document document = new Document();// step 2PdfWriter writer = PdfWriter.getInstance(document, zip);writer.setCloseStream(false);// step 3document.open();// step 4document.add(new Paragraph("Hello " + i));// step 5document.close();zip.closeEntry();}zip.close();} }參考文獻:https://www.cnblogs.com/julyluo/archive/2012/06/08/2542512.html?
總結
以上是生活随笔為你收集整理的iText5官方系列教程-iText in Action(一)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab图像显示 imagesc 和
- 下一篇: 脚本自动化互相阅读文章教程