什么是Itext
Apache iText 是一個開源 Java 庫,支持 PDF 文檔的開發和轉換。
在本教程中,我們將學習如何使用 iText 開發可以創建、轉換和操作 PDF 文檔的 Java 程序。
Itext目前遵從AGPL開源協議,AGPL 可以說是最嚴格的 GPL 了,強傳染性,即使是 RPC 調用也會被感染,不發行軟件而是作為 web 服務對外提供也必須開放源代碼
目前Itext有很多product開始收費,但你所需的功能基本上open source都能滿足
Itext是可以商用,但是必須公開的你項目源碼!!!
iText 的特點
以下是 iText 庫的顯着特點 −
- Interactive − iText 為你提供類(API)來生成交互式 PDF 文檔。使用這些,你可以創建地圖和書籍。
- Adding bookmarks, page numbers, etc − 使用 iText,你可以添加書簽、頁碼和水印。
- Split & Merge − 使用 iText,你可以將現有的 PDF 拆分為多個 PDF,還可以向其中添加/連接其他頁面。
- Fill Forms − 使用 iText,你可以在 PDF 文檔中填寫交互式表單。
- Save as Image − 使用 iText,你可以將 PDF 保存為圖像文件,例如 PNG 或 JPEG。
- Canvas − iText 庫為您提供了一個 Canvas 類,你可以使用它在 PDF 文檔上繪制各種幾何形狀,如圓形、線條等。
- Create PDFs − 使用 iText,你可以從 Java 程序創建新的 PDF 文件。你也可以包含圖像和字體。
IText使用
創建一個空白的PDF
可以通過實例化Document類來創建一個空的 PDF 文檔。在實例化此類時,你需要將PdfDocument對象作為參數傳遞給其構造函數。
第 1 步:創建一個 PdfWriter 對象
該PdfWriter類表示PDF文檔的作家。此類屬於包com.itextpdf.kernel.pdf。此類的構造函數接受一個字符串,表示要在其中創建 PDF 的文件的路徑。
通過向其構造函數傳遞一個字符串值(表示您需要創建 PDF 的路徑)來實例化 PdfWriter 類,如下所示。
第 2 步:創建一個 PdfDocument 對象
該PdfDocument類為表示在iText的PDF文檔類。此類屬於包com.itextpdf.kernel.pdf。要實例化此類(在寫入模式下),您需要將PdfWriter類的對象傳遞給其構造函數。
通過將上面創建的 PdfWriter 對象傳遞給其構造函數來實例化 PdfDocument 類,如下所示。
第 3 步:添加一個空頁面
PdfDocument類的addNewPage()方法用於在 PDF 文檔中創建一個空白頁面。
為上一步創建的 PDF 文檔添加一個空白頁面,如下所示。
第 4 步:創建一個 Document 對象
包com.itextpdf.layout的Document類是創建自給自足的 PDF 時的根元素。此類的構造函數之一接受類 PdfDocument 的對象。
通過傳遞在前面的步驟中創建的類PdfDocument的對象來實例化Document類,如下所示。
步驟 5:關閉文檔
使用Document類的close()方法關閉文檔,如下所示。
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
public class create_PDF {
public static void main(String args[]) throws Exception {
// 1、Creating a PdfWriter
String dest = "C:/itextExamples/sample.pdf";
PdfWriter writer = new PdfWriter(dest);
// 2、Creating a PdfDocument
PdfDocument pdfDoc = new PdfDocument(writer);
// 3、Adding an empty page
pdfDoc.addNewPage();
// 4、Creating a Document
Document document = new Document(pdfDoc);
// 5、Closing the document
document.close();
System.out.println("PDF Created");
}
}
創建一個 AreaBreak
你可以通過實例化Document類來創建一個空的 PDF 文檔。在實例化此類時,你需要將PdfDocument對象作為參數傳遞給其構造函數。
然后,要將 areabreak 添加到文檔,你需要實例化AreaBreak類並使用add()方法將此對象添加到文檔。
創建區域中斷對象
所述AreaBreak類屬於包com.itextpdf.layout.element。在實例化這個類時,當前的上下文區域將被終止並創建一個具有相同大小的新區域(如果我們使用默認構造函數)。
實例化AreaBreak類,如下所示。
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.AreaBreak;
public class AddingAreaBreak {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter
String dest = "C:/itextExamples/addingAreaBreak.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfDocument
PdfDocument pdf = new PdfDocument(writer);
// Creating a Document by passing PdfDocument object to its constructor
Document document = new Document(pdf);
// Creating an Area Break
AreaBreak aB = new AreaBreak();
// Adding area break to the PDF
document.add(aB);
// Closing the document
document.close();
System.out.println("Pdf created");
}
}
創建段落
你可以通過實例化Document類來創建一個空的 PDF 文檔。
在實例化此類時,你需要將PdfDocument對象作為參數傳遞給其構造函數。
然后,要將段落添加到文檔中,你需要實例化Paragraph類並使用add()方法將此對象添加到文檔中。
創建一個段落對象
的段落類表示的文本和圖形信息的自包含塊。它屬於com.itextpdf.layout.element包。
通過將文本內容作為字符串傳遞給其構造函數來實例化Paragraph類,如下所示。
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
public class AddingParagraph {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter
String dest = "C:/itextExamples/addingParagraph.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfDocument
PdfDocument pdf = new PdfDocument(writer);
// Creating a Document
Document document = new Document(pdf);
String para1 = "Tutorials Point originated from the idea that there exists
a class of readers who respond better to online content and prefer to learn
new skills at their own pace from the comforts of their drawing rooms.";
String para2 = "The journey commenced with a single tutorial on HTML in 2006
and elated by the response it generated, we worked our way to adding fresh
tutorials to our repository which now proudly flaunts a wealth of tutorials
and allied articles on topics ranging from programming languages to web designing
to academics and much more.";
// Creating Paragraphs
Paragraph paragraph1 = new Paragraph(para1);
Paragraph paragraph2 = new Paragraph(para2);
// Adding paragraphs to document
document.add(paragraph1);
document.add(paragraph2);
// Closing the document
document.close();
System.out.println("Paragraph added");
}
}
創建列表
你可以通過實例化Document類來創建一個空的 PDF 文檔。
在實例化此類時,你需要將PdfDocument對象作為參數傳遞給其構造函數。
然后,要將列表添加到文檔中,你需要實例化List類並使用add()方法將此對象添加到文檔中。
創建一個 List 對象
該目錄類表示一系列垂直列出的對象。它屬於com.itextpdf.layout.element包。
實例化List類,如下所示。
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.List;
import com.itextpdf.layout.element.Paragraph;
public class AddingList {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter
String dest = "C:/itextExamples/addngList.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfDocument
PdfDocument pdf = new PdfDocument(writer);
// Creating a Document
Document document = new Document(pdf);
// Creating a Paragraph
Paragraph paragraph = new Paragraph("Tutorials Point provides the following tutorials");
// Creating a list
List list = new List();
// Add elements to the list
list.add("Java");
list.add("JavaFX");
list.add("Apache Tika");
list.add("OpenCV");
list.add("WebGL");
list.add("Coffee Script");
list.add("Java RMI");
list.add("Apache Pig");
// Adding paragraph to the document
document.add(paragraph);
// Adding list to the document
document.add(list);
// Closing the document
document.close();
System.out.println("List added");
}
}
將表格添加到 Pdf
你可以通過實例化Document類來創建一個空的 PDF 文檔。
在實例化此類時,你需要將PdfDocument對象作為參數傳遞給其構造函數。
然后,要將表格添加到文檔中,你需要實例化Table類並使用add()方法將此對象添加到文檔中。
創建一個 Table 對象
該表類表示填充有以行和列排列的細胞的二維網格。它屬於com.itextpdf.layout.element包。
實例化Table類,如下所示。
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Table;
public class AddingTable {
public static void main(String args[]) throws Exception {
// Creating a PdfDocument object
String dest = "C:/itextExamples/addingTable.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfDocument object
PdfDocument pdf = new PdfDocument(writer);
// Creating a Document object
Document doc = new Document(pdf);
// Creating a table
float [] pointColumnWidths = {150F, 150F, 150F};
Table table = new Table(pointColumnWidths);
// Adding cells to the table
table.addCell(new Cell().add("Name"));
table.addCell(new Cell().add("Raju"));
table.addCell(new Cell().add("Id"));
table.addCell(new Cell().add("1001"));
table.addCell(new Cell().add("Designation"));
table.addCell(new Cell().add("Programmer"));
// Adding Table to document
doc.add(table);
// Closing the document
doc.close();
System.out.println("Table created successfully..");
}
}
格式化表格中的單元格
你可以通過實例化 Document 類來創建一個空的 PDF文檔。
在實例化此類時,你需要將PdfDocument對象作為參數傳遞給其構造函數。
然后,要將表格添加到文檔中,你需要實例化Table類並使用add()方法將此對象添加到文檔中。
你可以使用Cell類的方法格式化表格中單元格的內容。
為單元格添加背景
創建單元格並向其中添加內容后,可以設置單元格的格式。
例如,可以設置其背景,對齊單元格內的文本,更改文本顏色等,使用單元格類的不同方法,
例如setBackgroundColor()、setBorder()、setTextAlignment()。
import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.border.Border;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.TextAlignment;
public class BackgroundToTable {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter object
String dest = "C:/itextExamples/addingBackground.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfDocument object
PdfDocument pdfDoc = new PdfDocument(writer);
// Creating a Document object
Document doc = new Document(pdfDoc);
// Creating a table
float [] pointColumnWidths = {200F, 200F};
Table table = new Table(pointColumnWidths);
// Populating row 1 and adding it to the table
Cell c1 = new Cell(); // Creating cell 1
c1.add("Name"); // Adding name to cell 1
c1.setBackgroundColor(Color.DARK_GRAY); // Setting background color
c1.setBorder(Border.NO_BORDER); // Setting border
c1.setTextAlignment(TextAlignment.CENTER); // Setting text alignment
table.addCell(c1); // Adding cell 1 to the table
Cell c2 = new
Cell();
c2.add("Raju");
c2.setBackgroundColor(Color.GRAY);
c2.setBorder(Border.NO_BORDER);
c2.setTextAlignment(TextAlignment.CENTER);
table.addCell(c2);
// Populating row 2 and adding it to the table
Cell c3 = new Cell();
c3.add("Id");
c3.setBackgroundColor(Color.WHITE);
c3.setBorder(Border.NO_BORDER);
c3.setTextAlignment(TextAlignment.CENTER);
table.addCell(c3);
Cell c4 = new Cell();
c4.add("001");
c4.setBackgroundColor(Color.WHITE);
c4.setBorder(Border.NO_BORDER);
c4.setTextAlignment(TextAlignment.CENTER);
table.addCell(c4);
// Populating row 3 and adding it to the table
Cell c5 = new Cell();
c5.add("Designation");
c5.setBackgroundColor(Color.DARK_GRAY);
c5.setBorder(Border.NO_BORDER);
c5.setTextAlignment(TextAlignment.CENTER);
table.addCell(c5);
Cell c6 = new Cell();
c6.add("Programmer");
c6.setBackgroundColor(Color.GRAY);
c6.setBorder(Border.NO_BORDER);
c6.setTextAlignment(TextAlignment.CENTER);
table.addCell(c6);
// Adding Table to document
doc.add(table);
// Closing the document
doc.close();
System.out.println("Background added successfully..");
}
}
格式化單元格的邊框
可以通過實例化Document類來創建一個空的 PDF 文檔。
在實例化此類時,需要將PdfDocument對象作為參數傳遞給其構造函數。
格式化單元格的邊框
iText 庫提供了各種表示邊框的類,例如DashedBorder、SolidBorder、DottedBorder、DoubleBorder、RoundDotsBorder等。
這些類的構造函數接受兩個參數:一個表示邊框顏色的顏色對象和一個表示邊框寬度的整數。
選擇其中一種邊框類型並通過傳遞顏色對象和一個表示寬度的整數來實例化相應的邊框,如下所示。
import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.border.Border;
import com.itextpdf.layout.border.DashedBorder;
import com.itextpdf.layout.border.DottedBorder;
import com.itextpdf.layout.border.DoubleBorder;
import com.itextpdf.layout.border.RoundDotsBorder;
import com.itextpdf.layout.border.SolidBorder;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.TextAlignment;
public class FormatedBorders {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter object
String dest = "C:/itextExamples/coloredBorders.pdf";
PdfWriter writer = new
PdfWriter(dest);
// Creating a PdfDocument object
PdfDocument pdfDoc = new PdfDocument(writer);
// Creating a Document object
Document doc = new Document(pdfDoc);
// Creating a table
float [] pointColumnWidths = {200F, 200F};
Table table = new Table(pointColumnWidths);
// Adding row 1 to the table
Cell c1 = new Cell();
// Adding the contents of the cell
c1.add("Name");
// Setting the back ground color of the cell
c1.setBackgroundColor(Color.DARK_GRAY);
// Instantiating the Border class
Border b1 = new DashedBorder(Color.RED, 3);
// Setting the border of the cell
c1.setBorder(b1);
// Setting the text alignment
c1.setTextAlignment(TextAlignment.CENTER);
// Adding the cell to the table
table.addCell(c1);
Cell c2 = new Cell();
c2.add("Raju");
c1.setBorder(new SolidBorder(Color.RED, 3));
c2.setTextAlignment(TextAlignment.CENTER);
table.addCell(c2);
// Adding row 2 to the table
Cell c3 = new Cell();
c3.add("Id");
c3.setBorder(new DottedBorder(Color.DARK_GRAY, 3));
c3.setTextAlignment(TextAlignment.CENTER);
table.addCell(c3);
Cell c4 = new Cell();
c4.add("001");
c4.setBorder(new DoubleBorder(Color.DARK_GRAY, 3));
c4.setTextAlignment(TextAlignment.CENTER);
table.addCell(c4);
// Adding row 3 to the table
Cell c5 = new Cell();
c5.add("Designation");
c5.setBorder(new RoundDotsBorder(Color.RED, 3));
c5.setTextAlignment(TextAlignment.CENTER);
table.addCell(c5);
Cell c6 = new Cell();
c6.add("Programmer");
c6.setBorder(new RoundDotsBorder(Color.RED, 3));
c6.setTextAlignment(TextAlignment.CENTER);
table.addCell(c6);
// Adding Table to document
doc.add(table);
// Closing the document
doc.close();
System.out.println("Borders added successfully..");
}
}
將圖像添加到表格
可以通過實例化Document類來創建一個空的 PDF 文檔。
在實例化此類時,需要將PdfDocument對象作為參數傳遞給其構造函數。
然后,要將表格添加到文檔中,需要實例化Table類並使用add()方法將此對象添加到文檔中。
創建圖像
要創建圖像對象,首先要使用ImageDataFactory類的create()方法創建一個ImageData對象。
作為該方法的參數,傳入一個代表圖片路徑的字符串參數,如下。
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Image;
import com.itextpdf.layout.element.Table;
public class a3AddingImageToTable {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter object
String dest = "C:/itextExamples/addingImage.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfDocument object
PdfDocument pdfDoc = new PdfDocument(writer);
// Creating a Document object
Document doc = new Document(pdfDoc);
// Creating a table
float [] pointColumnWidths = {150f, 150f};
Table table = new Table(pointColumnWidths);
// Populating row 1 and adding it to the table
Cell cell1 = new Cell();
cell1.add("Tutorial ID");
table.addCell(cell1);
Cell cell2 = new Cell();
cell2.add("1");
table.addCell(cell2);
// Populating row 2 and adding it to the table
Cell cell3 = new Cell();
cell3.add("Tutorial Title");
table.addCell(cell3);
Cell cell4 = new Cell();
cell4.add("JavaFX");
table.addCell(cell4);
// Populating row 3 and adding it to the table
Cell cell5 = new Cell();
cell5.add("Tutorial Author");
table.addCell(cell5);
Cell cell6 = new Cell();
cell6.add("Krishna Kasyap");
table.addCell(cell6);
// Populating row 4 and adding it to the table
Cell cell7 = new Cell();
cell7.add("Submission date");
table.addCell(cell7);
Cell cell8 = new Cell();
cell8.add("2016-07-06");
table.addCell(cell8);
// Populating row 5 and adding it to the table
Cell cell9 = new Cell();
cell9.add("Tutorial Icon");
table.addCell(cell9);
// Creating the cell10
Cell cell10 = new Cell();
// Creating an ImageData object
String imageFile = "C:/itextExamples/javafxLogo.jpg";
ImageData data = ImageDataFactory.create(imageFile);
// Creating the image
Image img = new Image(data);
// Adding image to the cell10
cell10.add(img.setAutoScale(true));
// Adding cell110 to the table
table.addCell(cell10);
// Adding Table to document
doc.add(table);
// Closing the document
doc.close();
System.out.println("Image added to table successfully..");
}
}
在PDF中添加嵌套表
可以通過實例化Document類來創建一個空的 PDF 文檔。
在實例化此類時,需要將PdfDocument對象作為參數傳遞給其構造函數。
然后,要將表格添加到文檔中,需要實例化Table類並使用add()方法將此對象添加到文檔中。
要將表添加到該表中,需要創建另一個表(嵌套表),並使用Cell類的add()方法將其傳遞給單元對象。
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Table;
public class a4AddNestedTablesPdf {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter object
String dest = "C:/itextExamples/addingNestedTable.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfDocument object
PdfDocument pdfDoc = new PdfDocument(writer);
// Creating a Document object
Document doc = new Document(pdfDoc);
// Creating a table
float [] pointColumnWidths1 = {150f, 150f};
Table table = new Table(pointColumnWidths1);
// Populating row 1 and adding it to the table
Cell cell1 = new Cell();
cell1.add("Name");
table.addCell(cell1);
Cell cell2 = new Cell();
cell2.add("Raju");
table.addCell(cell2);
// Populating row 2 and adding it to the table
Cell cell3 = new Cell();
cell3.add("Id");
table.addCell(cell3);
Cell cell4 = new Cell();
cell4.add("1001");
table.addCell(cell4);
// Populating row 3 and adding it to the table
Cell cell5 = new Cell();
cell5.add("Designation");
table.addCell(cell5);
Cell cell6 = new Cell();
cell6.add("Programmer");
table.addCell(cell6);
// Creating nested table for contact
float [] pointColumnWidths2 = {150f, 150f};
Table nestedTable = new Table(pointColumnWidths2);
// Populating row 1 and adding it to the nested table
Cell nested1 = new Cell();
nested1.add("Phone");
nestedTable.addCell(nested1);
Cell nested2 = new Cell();
nested2.add("9848022338");
nestedTable.addCell(nested2);
// Populating row 2 and adding it to the nested table
Cell nested3 = new Cell();
nested3.add("email");
nestedTable.addCell(nested3);
Cell nested4 = new Cell();
nested4.add("Raju123@gmail.com");
nestedTable.addCell(nested4);
// Populating row 3 and adding it to the nested table
Cell nested5 = new Cell();
nested5.add("Address");
nestedTable.addCell(nested5);
Cell nested6 = new Cell();
nested6.add("Hyderabad");
nestedTable.addCell(nested6);
// Adding table to the cell
Cell cell7 = new Cell();
cell7.add("Contact");
table.addCell(cell7);
Cell cell8 = new Cell();
cell8.add(nestedTable);
table.addCell(cell8);
// Adding table to the document
doc.add(table);
// Closing the document
doc.close();
System.out.println("Nested Table Added successfully..");
}
}
將列表添加到 PDF 中的表格
可以通過實例化Document類來創建一個空的 PDF 文檔。
在實例化此類時,需要將PdfDocument對象作為參數傳遞給其構造函數。
然后,要將表格添加到文檔中,需要實例化Table類並使用add()方法將此對象添加到文檔中。
將列表添加到表格的單元格
現在,使用Cell 類的add()方法將上面創建的列表添加到表格的單元格中。
然后,使用Table類的addCell()方法將此單元格添加到表格中,如下所示
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.List;
import com.itextpdf.layout.element.ListItem;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.TextAlignment;
public class AddingListsToTable {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter object
String file = "C:/itextExamples/addingObjects.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(file));
// Creating a Document object
Document doc = new Document(pdfDoc);
// Creating a table
float [] pointColumnWidths = {300F, 300F};
Table table = new Table(pointColumnWidths);
// Adding row 1 to the table
Cell c1 = new Cell();
c1.add("Java Related Tutorials");
c1.setTextAlignment(TextAlignment.LEFT);
table.addCell(c1);
List list1 = new List();
ListItem item1 = new ListItem("JavaFX");
ListItem item2 = new ListItem("Java");
ListItem item3 = new ListItem("Java Servlets");
list1.add(item1);
list1.add(item2);
list1.add(item3);
Cell c2 = new Cell();
c2.add(list1);
c2.setTextAlignment(TextAlignment.LEFT);
table.addCell(c2);
// Adding row 2 to the table
Cell c3 = new Cell();
c3.add("No SQL Databases");
c3.setTextAlignment(TextAlignment.LEFT);
table.addCell(c3);
List list2 = new List();
list2.add(new ListItem("HBase"));
list2.add(new ListItem("Neo4j"));
list2.add(new ListItem("MongoDB"));
Cell c4 = new Cell();
c4.add(list2);
c4.setTextAlignment(TextAlignment.LEFT);
table.addCell(c4);
// Adding Table to document
doc.add(table);
// Closing the document
doc.close();
System.out.println("Lists added to table successfully..");
}
}
將圖像添加到 Pdf
可以通過實例化Document類來創建一個空的 PDF 文檔。
在實例化此類時,需要將PdfDocument對象作為參數傳遞給其構造函數。
要將圖像添加到 PDF,請創建需要添加的圖像對象,並使用Document類的add()方法添加它。
創建一個 Image 對象
要創建圖像對象,首先要使用ImageDataFactory類的create()方法創建一個ImageData對象。
作為該方法的參數,傳入一個代表圖片路徑的字符串參數,如下
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
public class AddingImage {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter
String dest = "C:/itextExamples/addingImage.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfDocument
PdfDocument pdf = new PdfDocument(writer);
// Creating a Document
Document document = new Document(pdf);
// Creating an ImageData object
String imFile = "C:/itextExamples/logo.jpg";
ImageData data = ImageDataFactory.create(imFile);
// Creating an Image object
Image image = new Image(data);
// Adding image to the document
document.add(image);
// Closing the document
document.close();
System.out.println("Image added");
}
}
設置圖像的位置
可以通過實例化Document類來創建一個空的 PDF 文檔。
在實例化此類時,需要將PdfDocument對象作為參數傳遞給其構造函數。
設置圖片的位置
可以使用Image的setFixedPosition()方法設置圖像在 PDF 文檔中的位置。
使用此方法將圖像的位置設置為文檔上的坐標(100, 250),如下所示
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
public class SettingPosition {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter
String dest = "C:/EXAMPLES/itextExamples/3images/positionOfImage.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfDocument
PdfDocument pdfDoc = new PdfDocument(writer);
// Creating a Document
Document document = new Document(pdfDoc);
// Creating an ImageData object
String imFile = "C:/EXAMPLES/itextExamples/3images/logo.jpg";
ImageData data = ImageDataFactory.create(imFile);
// Creating an Image object
Image image = new Image(data);
// Setting the position of the image to the center of the page
image.setFixedPosition(100, 250);
// Adding image to the document
document.add(image);
// Closing the document
document.close();
System.out.println("Image added");
}
}
縮放PDF中的圖像
可以通過實例化Document類來創建一個空的 PDF 文檔。
在實例化此類時,需要將PdfDocument對象作為參數傳遞給其構造函數。
縮放圖像
您可以使用setAutoScale()方法縮放圖像。
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
public class SettingAutoScale {
public static void main(String args[]) throws Exception{
// Creating a PdfWriter
String dest = "C:/itextExamples/positionOfImage.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfDocument
PdfDocument pdfDoc = new PdfDocument(writer);
// Creating a Document
Document document = new Document(pdfDoc);
// Creating an ImageData object
String imFile = "C:/itextExamples/logo.jpg";
ImageData data = ImageDataFactory.create(imFile);
// Creating an Image object
Image image = new Image(data);
// Setting the position of the image to the center of the page
image.setFixedPosition(100,250);
// Adding image to the document
document.add(image);
// Closing the document
document.close();
System.out.println("Image Scaled");
}
}
旋轉PDF中的圖像
可以通過實例化Document類來創建一個空的 PDF 文檔。
在實例化此類時,需要將PdfDocument對象作為參數傳遞給其構造函數。
旋轉圖像
可以使用setRotationAngle()方法旋轉圖像。
對於此方法,需要傳遞一個整數,該整數表示要旋轉圖像的旋轉角度。
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
public class RotatingImage {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter
String dest = "C:/itextExamples/rotatingImage.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfDocument
PdfDocument pdfDoc = new PdfDocument(writer);
// Creating a Document
Document document = new Document(pdfDoc);
// Creating an ImageData object
String imFile = "C:/itextExamples/logo.jpg";
ImageData data = ImageDataFactory.create(imFile);
// Creating an Image object
Image image = new Image(data);
// Rotating the image
image.setRotationAngle(45);
// Adding image to the document
document.add(image);
// Closing the document
document.close();
System.out.println("Image rotated");
}
}
在PDF中創建文本注釋
可以通過實例化Document類來創建一個空的 PDF 文檔。
在實例化此類時,需要將PdfDocument對象作為參數傳遞給其構造函數。
創建 PdfAnnotation 對象
該PdfAnnotation類的包com.itextpdf.kernel.pdf.annot代表所有注釋的超類。
在其派生類中,PdfTextAnnotation類表示文本注釋。創建此類的對象,如下所示。
設置注釋的顏色
使用PdfAnnotation類的setColor()方法為注釋設置顏色。
import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfString;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.annot.PdfAnnotation;
import com.itextpdf.kernel.pdf.annot.PdfTextAnnotation;
import com.itextpdf.layout.Document;
public class TextAnnotation {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter
String dest = "C:/itextExamples/textAnnotation.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfDocument
PdfDocument pdf = new PdfDocument(writer);
// Creating a Document
Document document = new Document(pdf);
// Creating PdfTextAnnotation object
Rectangle rect = new Rectangle(20, 800, 0, 0);
PdfAnnotation ann = new PdfTextAnnotation(rect);
// Setting color to the annotation
ann.setColor(Color.GREEN);
// Setting title to the annotation
ann.setTitle(new PdfString("Hello"));
// Setting contents of the annotation
ann.setContents("Hi welcome to Tutorialspoint.");
// Creating a new page
PdfPage page = pdf.addNewPage();
// Adding annotation to a page in a PDF
page.addAnnotation(ann);
// Closing the document
document.close();
System.out.println("Annotation added successfully");
}
}
在PDF中創建鏈接注釋
可以通過實例化Document類來創建一個空的 PDF 文檔。
在實例化此類時,需要將PdfDocument對象作為參數傳遞給其構造函數。
PdfAnnotation 對象
該PdfAnnotation類的包com.itextpdf.kernel.pdf.annot代表所有注釋的超類。
在其派生類中,PdfLinkAnnotation類表示鏈接注釋。創建這個類的一個對象,如下。
設置注解的動作
使用PdfLinkAnnotation類的setAction()方法將操作設置為注釋,如下所示。
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.action.PdfAction;
import com.itextpdf.kernel.pdf.annot.PdfLinkAnnotation;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Link;
import com.itextpdf.layout.element.Paragraph;
public class LinkAnnotation {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter
String dest = "C:/itextExamples/linkAnnotation.pdf";
PdfWriter writer = new
PdfWriter(dest);
// Creating a PdfDocument
PdfDocument pdf = new PdfDocument(writer);
// Creating a Document
Document document = new Document(pdf);
// Creating a PdfLinkAnnotation object
Rectangle rect = new Rectangle(0, 0);
PdfLinkAnnotation annotation = new PdfLinkAnnotation(rect);
// Setting action of the annotation
PdfAction action = PdfAction.createURI("http:// www.tutorialspoint.com/");
annotation.setAction(action);
// Creating a link
Link link = new Link("Click here", annotation);
// Creating a paragraph
Paragraph paragraph = new Paragraph("Hi welcome to Tutorialspoint ");
// Adding link to paragraph
paragraph.add(link.setUnderline());
// Adding paragraph to document
document.add(paragraph);
// Closing the document
document.close();
System.out.println("Annotation added successfully");
}
}
在PDF中創建線注釋
可以通過實例化Document類來創建一個空的 PDF 文檔。
在實例化此類時,需要將PdfDocument對象作為參數傳遞給其構造函數。
創建 PdfAnnotation 對象
該PdfAnnotation類的包com.itextpdf.kernel.pdf.annot代表的是所有注釋的超類。
在其派生類中,PdfLineAnnotation類表示線注釋。創建此類的對象,如下所示
設置注釋的標題和內容
分別使用PdfAnnotation類的setTitle()和setContents()方法設置注釋的標題和內容,如下所示。
import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfString;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.annot.PdfAnnotation;
import com.itextpdf.kernel.pdf.annot.PdfLineAnnotation;
import com.itextpdf.layout.Document;
public class LineAnnotation {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter
String dest = "C:/itextExamples/lineAnnotations.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfDocument
PdfDocument pdf = new PdfDocument(writer);
// Creating a Document
Document document = new Document(pdf);
// Creating a PdfPage
PdfPage page = pdf.addNewPage();
// creating PdfLineAnnotation object
Rectangle rect = new Rectangle(0, 0);
float[] floatArray = new float[]{
20, 790, page.getPageSize().getWidth() - 20, 790
};
PdfAnnotation annotation = new PdfLineAnnotation(rect, floatArray);
// Setting color of the PdfLineAnnotation
annotation.setColor(Color.BLUE);
// Setting title to the PdfLineAnnotation
annotation.setTitle(new PdfString("iText"));
// Setting contents of the PdfLineAnnotation
annotation.setContents("Hi welcome to Tutorialspoint");
// Adding annotation to the page
page.addAnnotation(annotation);
// Closing the document
document.close();
System.out.println("Annotation added successfully");
}
}
在PDF中創建標記注釋
可以通過實例化Document類來創建一個空的 PDF 文檔。
在實例化此類時,需要將PdfDocument對象作為參數傳遞給其構造函數。
要在 PDF 文檔中使用文本注釋,需要創建PdfTextAnnotation類的對象並將其添加到PdfPage。
創建 PdfAnnotation 對象
該PdfAnnotation類的包com.itextpdf.kernel.pdf.annot代表所有注釋的超類。
在其派生類中,PdfTextMarkupAnnotation類表示文本標記注釋。創建此類的對象,如下所示。
設置注釋的標題和內容
分別使用PdfAnnotation類的setTitle()和setContents()方法設置注釋的標題和內容。
import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfString;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.annot.PdfAnnotation;
import com.itextpdf.kernel.pdf.annot.PdfTextMarkupAnnotation;
import com.itextpdf.layout.Document;
public class MarkupAnnotation {
public static void main(String args[]) throws Exception {
// Creating a PdfDocument object
String file = "C:/itextExamples/markupAnnotation.pdf";
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(file));
// Creating a Document object
Document doc = new Document(pdfDoc);
// Creating a PdfTextMarkupAnnotation object
Rectangle rect = new Rectangle(105, 790, 64, 10);
float[] floatArray = new float[]{169, 790, 105, 790, 169, 800, 105, 800};
PdfAnnotation annotation =
PdfTextMarkupAnnotation.createHighLight(rect,floatArray);
// Setting color to the annotation
annotation.setColor(Color.YELLOW);
// Setting title to the annotation
annotation.setTitle(new PdfString("Hello!"));
// Setting contents to the annotation
annotation.setContents(new PdfString("Hi welcome to Tutorialspoint"));
// Creating a new Pdfpage
PdfPage pdfPage = pdfDoc.addNewPage();
// Adding annotation to a page in a PDF
pdfPage.addAnnotation(annotation);
// Closing the document
doc.close();
System.out.println("Annotation added successfully");
}
}
在PDF中創建圓形注釋
可以通過實例化Document類來創建一個空的 PDF 文檔。
在實例化此類時,需要將PdfDocument對象作為參數傳遞給其構造函數。
要在 PDF 文檔中使用文本注釋,您需要創建 PdfTextAnnotation 類的對象並將其添加到Pdfpage。
import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfString;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.annot.PdfAnnotation;
import com.itextpdf.kernel.pdf.annot.PdfCircleAnnotation;
import com.itextpdf.layout.Document;
public class CircleAnnotation {
public static void main(String args[]) throws Exception {
// Creating a PdfDocument object
String file = "C:/itextExamples// circleAnnotation.pdf";
PdfDocument pdf = new PdfDocument(new PdfWriter(file));
// Creating a Document object
Document doc = new Document(pdf);
// Creating a PdfCircleAnnotation object
Rectangle rect = new Rectangle(150, 770, 50, 50);
PdfAnnotation annotation = new PdfCircleAnnotation(rect);
// Setting color to the annotation
annotation.setColor(Color.YELLOW);
// Setting title to the annotation
annotation.setTitle(new PdfString("circle annotation"));
// Setting contents of the annotation
annotation.setContents(new PdfString("Hi welcome to Tutorialspoint"));
// Creating a new page
PdfPage page = pdf.addNewPage();
// Adding annotation to a page in a PDF
page.addAnnotation(annotation);
// Closing the document
doc.close();
System.out.println("Annotation added successfully");
}
}
在PDF上繪制圓弧
可以通過實例化Document類來創建一個空的 PDF 文檔。
在實例化此類時,需要將PdfDocument對象作為參數傳遞給其構造函數。
上繪制一個PdfDocument電弧,實例化PdfCanvas類的包的com.itextpdf.kernel.pdf .canvas和創建使用電弧弧()此類的方法。
創建一個 PdfCanvas 對象
使用PdfDocument類的addNewPage()方法創建一個新的PdfPage類。
實例化PdfCanvas封裝的對象com.itextpdf.kernel.pdf.canvas通過將上面創建PdfPage目的是這個類的構造函數,如下所示。
繪制圓弧
使用Canvas類的arc()方法繪制圓弧,使用fill()方法填充
import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Document;
public class DrawingArc {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter
String dest = "C:/itextExamples/drawingArc.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfDocument object
PdfDocument pdfDoc = new PdfDocument(writer);
// Creating a Document object
Document doc = new Document(pdfDoc);
// Creating a new page
PdfPage pdfPage = pdfDoc.addNewPage();
// Creating a PdfCanvas object
PdfCanvas canvas = new PdfCanvas(pdfPage);
// Drawing an arc
canvas.arc(50, 50, 300, 545, 0, 360);
// Filling the arc
canvas.fill();
// Closing the document
doc.close();
System.out.println("Object drawn on pdf successfully");
}
}
在PDF上畫線
可以通過實例化Document類來創建一個空的 PDF 文檔。
在實例化此類時,需要將PdfDocument對象作為參數傳遞給其構造函數。
在 PdfDocument 上畫一條線 實例化包com.itextpdf.kernel.pdf.canvas的PdfCanvas類,並使用該類的moveTo()和lineTO()方法創建一條線。
創建一個 PdfCanvas 對象
使用PdfDocument類的addNewPage()方法創建一個新的PdfPage類。
實例化PdfCanvas封裝的對象com.itextpdf.kernel.pdf.canvas通過將上面創建PdfPage目的是這個類的構造函數,如下所示。
畫線
使用Canvas類的moveTO()方法設置線的初始點,如下所示。
// Initial point of the line
canvas.moveTo(100, 300);
現在,使用lineTo()方法繪制一條從該點到另一點的線,如下所示。
// Drawing the line
canvas.lineTo(500, 300);
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Document;
public class DrawingLine {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter
String dest = "C:/itextExamples/drawingLine.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfDocument object
PdfDocument pdfDoc = new PdfDocument(writer);
// Creating a Document object
Document doc = new Document(pdfDoc);
// Creating a new page
PdfPage pdfPage = pdfDoc.addNewPage();
// Creating a PdfCanvas object
PdfCanvas canvas = new PdfCanvas(pdfPage);
// Initial point of the line
canvas.moveTo(100, 300);
// Drawing the line
canvas.lineTo(500, 300);
// Closing the path stroke
canvas.closePathStroke();
// Closing the document
doc.close();
System.out.println("Object drawn on pdf successfully");
}
}
在PDF上畫圓
可以通過實例化Document類來創建一個空的 PDF 文檔。
在實例化此類時,需要將PdfDocument對象作為參數傳遞給其構造函數。
要在 PdfDocument 上繪制圓,請實例化包com.itextpdf.kernel.pdf .canvas的PdfCanvas類並調用該類的circle()方法
創建一個 PdfCanvas 對象
使用PdfDocument類的addNewPage()方法創建一個新的PdfPage類。實例化PdfCanvas封裝的對象com.itextpdf.kernel.pdf.canvas通過將PdfPage對象這一類的構造函數,如下所示。
設置顏色使用Canvas類的setColor()方法設置圓圈的顏色,如下所示。
// Setting color to the circle
Color color = Color.GREEN;
canvas.setColor(color, true);
繪制圓圈 通過調用Canvas的circle()方法繪制一個圓,如下所示
// creating a circle
canvas.circle(300, 400, 200);
import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Document;
public class DrawingCircle {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter
String dest = "C:/itextExamples/drawingCircle.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfDocument object
PdfDocument pdfDoc = new PdfDocument(writer);
// Creating a Document object
Document doc = new Document(pdfDoc);
// Creating a new page
PdfPage pdfPage = pdfDoc.addNewPage();
// Creating a PdfCanvas object
PdfCanvas canvas = new PdfCanvas(pdfPage);
// Setting color to the circle
Color color = Color.GREEN;
canvas.setColor(color, true);
// creating a circle
canvas.circle(300, 400, 200);
// Filling the circle
canvas.fill();
// Closing the document
doc.close();
System.out.println("Object drawn on pdf successfully");
}
}
設置PDF中文本的字體
可以通過實例化Document類來創建一個空的 PDF 文檔。
在實例化此類時,需要將PdfDocument對象作為參數傳遞給其構造函數。
要將段落添加到文檔中,需要實例化Paragraph類並使用add()方法將此對象添加到文檔中。可以分別使用setFontColor()和setFont()方法為文本設置顏色和字體。
創建文本,通過實例化包com.itextpdf.layout.element的Text類來創建文本,如下所示
設置文字的字體和顏色:
創建PdfFont使用對象的createFont()之類的方法PdfFontFactory封裝com.itextpdf.kernel.font如下所示
// Setting font of the text PdfFont
font = PdfFontFactory.createFont(FontConstants.HELVETICA_BOLD);
現在,使用Text類的setFont()方法將字體設置為該方法。將PdfFont對象作為參數傳遞,如下所示。
text1.setFont(font);
要為文本設置顏色,請調用Text 類的setFontColor()方法,如下所示。
// Setting font color
text.setFontColor(Color.GREEN)
import com.itextpdf.io.font.FontConstants;
import com.itextpdf.kernel.color.Color;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Text;
public class FormatingTheText {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter object
String dest = "C:/itextExamples/fonts.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfDocument object
PdfDocument pdf = new PdfDocument(writer);
// Creating a Document object
Document doc = new Document(pdf);
// Creating text object
Text text1 = new Text("Tutorialspoint");
// Setting font of the text
PdfFont font = PdfFontFactory.createFont(FontConstants.HELVETICA_BOLD);
text1.setFont(font);
// Setting font color
text1.setFontColor(Color.GREEN);
// Creating text object
Text text2 = new Text("Simply Easy Learning");
text2.setFont(PdfFontFactory.createFont(FontConstants.HELVETICA));
// Setting font color
text2.setFontColor(Color.BLUE);
// Creating Paragraph
Paragraph paragraph1 = new Paragraph();
// Adding text1 to the paragraph
paragraph1.add(text1);
paragraph1.add(text2);
// Adding paragraphs to the document
doc.add(paragraph1);
doc.close();
System.out.println("Text added to pdf ..");
}
}
縮小PDF中的內容
使用AffineTransform類的getScaleInstance()方法,縮小源文檔頁面的內容,如下所示。
// Shrink original page content using transformation matrix
AffineTransform transformationMatrix = AffineTransform.getScaleInstance(
page.getPageSize().getWidth()/ orig.getWidth()/2,
page.getPageSize().getHeight()/ orig.getHeight()/2);
復制頁面
將上一步中創建的仿射變換矩陣連接到目標 PDF 文檔的畫布對象的矩陣,如下所示。
// Concatenating the affine transform matrix to the current matrix
PdfCanvas canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
現在,將頁面副本添加到源文檔的目標 PDF的畫布對象中,如下所示。
// Add the object to the canvas
PdfFormXObject pageCopy = origPage.copyAsFormXObject(destpdf);
canvas.addXObject(pageCopy, 0, 0);
import com.itextpdf.kernel.geom.AffineTransform;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import com.itextpdf.layout.Document;
public class ShrinkPDF {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter object
String dest = "C:/itextExamples/shrinking.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfReader
String src = "C:/itextExamples/pdfWithImage.pdf";
PdfReader reader = new PdfReader(src);
// Creating a PdfDocument objects
PdfDocument destpdf = new PdfDocument(writer);
PdfDocument srcPdf = new PdfDocument(reader);
// Opening a page from the existing PDF
PdfPage origPage = srcPdf.getPage(1);
// Getting the page size
Rectangle orig = origPage.getPageSizeWithRotation();
// Adding a page to destination Pdf
PdfPage page = destpdf.addNewPage();
// Scaling the image in a Pdf page
AffineTransform transformationMatrix = AffineTransform.getScaleInstance(
page.getPageSize().getWidth()/orig.getWidth()/2,
page.getPageSize().getHeight()/ orig.getHeight()/2);
// Shrink original page content using transformation matrix
PdfCanvas canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
// Add the object to the canvas
PdfFormXObject pageCopy = origPage.copyAsFormXObject(destpdf);
canvas.addXObject(pageCopy, 0, 0);
// Creating a Document object
Document doc = new Document(destpdf);
// Closing the document
doc.close();
System.out.println("Table created successfully..");
}
}
平鋪PDF頁面
以下 Java 程序演示了如何使用 iText 庫將 PDF 頁面的內容平鋪到不同的頁面。
它創建一個名為tilingPdfPages.pdf的 PDF 文檔並將其保存在路徑C:/itextExamples/ 中。
import com.itextpdf.kernel.geom.AffineTransform;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
public class TilingPDFPages {
public static void main(String args[]) throws Exception {
// Creating a PdfWriter object
String dest = "C:/itextExamples/tilingPdfPages.pdf";
PdfWriter writer = new PdfWriter(dest);
// Creating a PdfReader
String src = "C:/itextExamples/pdfWithImage.pdf";
PdfReader reader = new PdfReader(src);
// Creating a PdfDocument objects
PdfDocument destpdf = new PdfDocument(writer);
PdfDocument srcPdf = new PdfDocument(reader);
// Opening a page from the existing PDF
PdfPage origPage = srcPdf.getPage(1);
// Getting the page size
Rectangle orig = origPage.getPageSizeWithRotation();
// Getting the size of the page
PdfFormXObject pageCopy = origPage.copyAsFormXObject(destpdf);
// Tile size
Rectangle tileSize = PageSize.A4.rotate();
AffineTransform transformationMatrix =
AffineTransform.getScaleInstance(tileSize.getWidth() / orig.getWidth() *
2f, tileSize.getHeight() / orig.getHeight() * 2f);
// The first tile
PdfPage page =
destpdf.addNewPage(PageSize.A4.rotate());
PdfCanvas canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, 0, -orig.getHeight() / 2f);
// The second tile
page = destpdf.addNewPage(PageSize.A4.rotate());
canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, -orig.getWidth() / 2f, -orig.getHeight() / 2f);
// The third tile
page = destpdf.addNewPage(PageSize.A4.rotate());
canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, 0, 0);
// The fourth tile
page = destpdf.addNewPage(PageSize.A4.rotate());
canvas = new PdfCanvas(page);
canvas.concatMatrix(transformationMatrix);
canvas.addXObject(pageCopy, -orig.getWidth() / 2f, 0);
// closing the documents
destpdf.close();
srcPdf.close();
System.out.println("PDF created successfully..");
}
}
動態添加表格且自動換頁
package com.example.itext;
import com.example.utile.ItextPdfUtil;
import com.itextpdf.text.*;
import com.itextpdf.text.Font;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
public class Testone {
public static void main(String[] args)throws Exception {
File file = new File("C:/itextExamples/tilingPdfPages.pdf");
byte[] fileContent = Files.readAllBytes(file.toPath());
byte[] bytes = fill_patient_info(fileContent).toByteArray();
Path path = Paths.get("C:/itextExamples/tilingPdfPages.pdf");
Files.write(path, bytes);
}
public static ByteArrayOutputStream fill_patient_info(byte[] file_data) throws IOException, DocumentException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
PdfReader reader = new PdfReader(file_data);
Rectangle pagesize = reader.getPageSize(1);
int elementType = Element.ALIGN_LEFT;
Font tableContent = new Font(com.itextpdf.text.Font.FontFamily.COURIER, 9, Font.BOLD);
PdfStamper stamper = new PdfStamper(reader, byteArrayOutputStream);
// CREATE TABLE
PdfPTable table = new PdfPTable(3);
for (String s : Arrays.asList("TableColumn1", "TableColumn2", "TableColumn3")) {
table.addCell(ItextPdfUtil.getTableHeaderCell(s));
}
table.setHeaderRows(1);
// SET TABLE COLUMN WIDTH
table.setWidths(new int[]{100,100,100});
// ADD TABLE DATA
for (int i = 1; i <= 150; i++) {
table.addCell(new PdfPCell(new Phrase(elementType,"Test" + i,tableContent)));
table.addCell(new PdfPCell(new Phrase(elementType,"Test" + i,tableContent)));
table.addCell(new PdfPCell(new Phrase(elementType,"Test" + i,tableContent)));
}
ColumnText column = new ColumnText(stamper.getOverContent(1));
column.setSimpleColumn(ItextPdfUtil.tableHeaderRectPage);
column.addElement(table);
int pagecount = 1;
int status = column.go();
while (ColumnText.hasMoreText(status)) {
status = triggerNewPage(stamper, pagesize, column, ItextPdfUtil.tableContentRectPage, ++pagecount);
}
stamper.setFormFlattening(true);
stamper.close();
reader.close();
return byteArrayOutputStream;
}
public static int triggerNewPage(PdfStamper stamper, Rectangle pageSize,
ColumnText column, Rectangle rect,
int pageCount) throws DocumentException {
stamper.insertPage(pageCount, pageSize);
PdfContentByte canvas = stamper.getOverContent(pageCount);
column.setCanvas(canvas);
column.setSimpleColumn(rect);
return column.go();
}
}
Merger兩個PDF
/**
* merger all pdf
* @param readers all pdf reader
* @param outputStream out stream
* @return
*/
public static ByteArrayOutputStream mergerPdf(List<PdfReader> readers, ByteArrayOutputStream outputStream){
Document document = new Document();
try{
PdfCopy copy = new PdfCopy(document, outputStream);
document.open();
int n;
for(int i = 0 ; i < readers.size(); i++){
PdfReader reader = readers.get(i);
n = reader.getNumberOfPages();
for(int page = 0; page < n;){
copy.addPage(copy.getImportedPage(reader, ++page));
}
copy.freeReader(reader);
reader.close();
}
document.close();
}catch (Exception e){
e.printStackTrace();
}
return outputStream;
}