示例:使用iText 如何在 pdf 文档中添加表格
public static void main(String[] args) { Document document = new Document(); try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream('AddTableExample.pdf')); document.open(); PdfPTable table = new PdfPTable(3); // 设置表格的列数 table.setWidthPercentage(100); //设置宽度 100% table.setSpacingBefore(10f); // 表格前后的空隙 table.setSpacingAfter(10f); // 各列的宽度 float[] columnWidths = {1f, 1f, 1f}; table.setWidths(columnWidths); PdfPCell cell1 = new PdfPCell(new Paragraph('Cell 1')); cell1.setBorderColor(BaseColor.BLUE); cell1.setPaddingLeft(10); cell1.setHorizontalAlignment(Element.ALIGN_CENTER); cell1.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell2 = new PdfPCell(new Paragraph('Cell 2')); cell2.setBorderColor(BaseColor.GREEN); cell2.setPaddingLeft(10); cell2.setHorizontalAlignment(Element.ALIGN_CENTER); cell2.setVerticalAlignment(Element.ALIGN_MIDDLE); PdfPCell cell3 = new PdfPCell(new Paragraph('Cell 3')); cell3.setBorderColor(BaseColor.RED); cell3.setPaddingLeft(10); cell3.setHorizontalAlignment(Element.ALIGN_CENTER); cell3.setVerticalAlignment(Element.ALIGN_MIDDLE); // 设置下面值,可以避免单元格边框和内容重叠 //cell1.setUserBorderPadding(true); //cell2.setUserBorderPadding(true); //cell3.setUserBorderPadding(true); table.addCell(cell1); table.addCell(cell2); table.addCell(cell3); document.add(table); document.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); } }
日期:2020-09-17 00:09:30 来源:oir作者:oir