java实现一个,生成表格pdf的工具类,传入主标题,副标题,表格数据
时间: 2023-05-31 11:04:35 浏览: 162
,输出pdf文件。
我们可以使用iText库来生成pdf文件。以下是一个简单的示例代码,可以根据需要进一步修改和完善。
```java
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import java.io.FileOutputStream;
import java.util.List;
public class PDFGenerator {
private static Font titleFont = new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD);
private static Font subTitleFont = new Font(Font.FontFamily.HELVETICA, 14, Font.BOLD);
private static Font tableHeaderFont = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
private static Font tableBodyFont = new Font(Font.FontFamily.HELVETICA, 10);
public static void generatePDF(String mainTitle, String subTitle, List<String[]> tableData, String outputPath) throws Exception {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(outputPath));
document.open();
Paragraph title = new Paragraph(mainTitle, titleFont);
title.setAlignment(Element.ALIGN_CENTER);
document.add(title);
Paragraph sub = new Paragraph(subTitle, subTitleFont);
sub.setAlignment(Element.ALIGN_CENTER);
document.add(sub);
PdfPTable table = new PdfPTable(tableData.get(0).length);
table.setWidthPercentage(100);
for (int i = 0; i < tableData.get(0).length; i++) {
PdfPCell cell = new PdfPCell(new Phrase(tableData.get(0)[i], tableHeaderFont));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
table.addCell(cell);
}
for (int i = 1; i < tableData.size(); i++) {
for (int j = 0; j < tableData.get(i).length; j++) {
PdfPCell cell = new PdfPCell(new Phrase(tableData.get(i)[j], tableBodyFont));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
table.addCell(cell);
}
}
document.add(table);
document.close();
}
}
```
使用方法:
```java
String mainTitle = "表格PDF生成工具";
String subTitle = "示例表格";
List<String[]> tableData = new ArrayList<String[]>();
tableData.add(new String[]{"姓名", "年龄", "性别"});
tableData.add(new String[]{"张三", "20", "男"});
tableData.add(new String[]{"李四", "30", "女"});
String outputPath = "output.pdf";
PDFGenerator.generatePDF(mainTitle, subTitle, tableData, outputPath);
```
注意:这里只是一个简单的示例,实际应用中可能需要更多的定制和细节处理。
阅读全文