在本教程中,我们将讨论如何使用 iText API
在 PDF
文档中创建表。 iText
是一个开源软件,广泛用于在 Java 应用程序/程序中创建 PDF
文档。
如果您是 Maven
用户,则可以直接在您的 pom.xml
中添加依赖项。
pom.xml
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>
注意: 这可能会在创建文档时出现任何问题时抛出 DocumentException
。 您需要通过使用 try and catch
块或在方法中声明 throws
来处理它。
iText API
示例向您展示如何在 PDF 文件中创建表格,并将数据写入其中。
CreateTableInPDF.java
package org.websparrow.itext;
import java.io.FileOutputStream;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class CreateTableInPDF {
public static void main(String[] args) {
try {
// creation of the document with a certain size and certain margins
Document document = new Document(PageSize.A4, 20, 20, 20, 20);
// creating table and set the column width
PdfPTable table = new PdfPTable(3);
float widths[] = { 3, 6, 3 };
table.setWidths(widths);
table.setHeaderRows(1);
// add cell of table - header cell
PdfPCell cell = new PdfPCell(new Phrase("Emp Id"));
cell.setBackgroundColor(new BaseColor(0, 173, 239));
table.addCell(cell);
cell = new PdfPCell(new Phrase("Emp Name"));
cell.setBackgroundColor(new BaseColor(0, 173, 239));
table.addCell(cell);
cell = new PdfPCell(new Phrase("Salary"));
cell.setBackgroundColor(new BaseColor(0, 173, 239));
table.addCell(cell);
Phrase ph;
// looping the table cell for adding definition
for (int ctr = 1; ctr <= 4; ctr++) {
cell = new PdfPCell();
ph = new Phrase("WS-" + ctr);
cell.addElement(ph);
table.addCell(cell);
cell = new PdfPCell();
ph = new Phrase("Sandeep Sharma " + ctr);
cell.addElement(ph);
table.addCell(cell);
cell = new PdfPCell();
ph = new Phrase("2000" + ctr);
cell.addElement(ph);
table.addCell(cell);
}
// write the all into a file and save it.
PdfWriter.getInstance(document, new FileOutputStream("EmployeeData.pdf"));
document.open();
document.add(table);
document.close();
System.out.println("Successfull.");
} catch (DocumentException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
输出:
如果您在控制台中看到成功消息,则表示您已成功创建 PDF 文档。 要检查它,请转到文件位置,这是结果。
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.websparrow.org/java/itext-api-creating-table-in-pdf-using-java
内容来源于网络,如有侵权,请联系作者删除!