我们可以使用setWidthPercentage()com.itextpdf.text.pdf.PdfPTable类的方法设置表格的宽度。此方法接受浮点值作为参数。此方法以表格在页面中占据的宽度的百分比设置宽度。默认表的宽度为80%。
让我们看下面的代码示例:
package org.nhooo.example.itextpdf; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Phrase; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import java.io.FileNotFoundException; import java.io.FileOutputStream; public class TableWidthDemo { public static void main(String[] args) { Document doc = new Document(); try { PdfWriter.getInstance(doc, new FileOutputStream("TableWidthDemo.pdf")); doc.open(); // 创建一个具有5列的表格 PdfPTable table = new PdfPTable(5); table.addCell(new PdfPCell(new Phrase("Cell 1"))); table.addCell(new PdfPCell(new Phrase("Cell 2"))); table.addCell(new PdfPCell(new Phrase("Cell 3"))); table.addCell(new PdfPCell(new Phrase("Cell 4"))); table.addCell(new PdfPCell(new Phrase("Cell 5"))); // 设置表格将占用的宽度百分比 // 在页面中。 table.setWidthPercentage(50); doc.add(table); } catch (DocumentException | FileNotFoundException e) { e.printStackTrace(); } finally { doc.close(); } } }
Maven依赖
<!-- http://repo1.maven.org/maven2/com/itextpdf/itextpdf/5.5.10/itextpdf-5.5.10.jar --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.10</version> </dependency>