導出數據表格PDF樣式:
導入依賴:
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.1.5</version>
</dependency>
源碼:
private String[][] content = new String[][]{
{"姓名", "英文名", "年齡", "聯繫電話"},
{"劉先生", "puyuma", "22","15911111111"}
};
/**
* 創建一份普通表格的PDF文件
*
* @param fullFilePath 導出pdf文件後的存放地址
* @return
*/
public boolean toPDF(String fullFilePath) {
Document document = new Document();
try {
//構建一個PDF文檔輸出流程
OutputStream outputStream = new FileOutputStream(new File(fullFilePath));
PdfWriter.getInstance(document, outputStream);
//設置字體樣式
BaseFont baseFont = BaseFont.createFont("D:\\msyhbd.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
Font f8 = new Font(baseFont, 8, Font.NORMAL);
//打開PDF文件流
document.open();
//創建一個N列的表格控件
PdfPTable table = new PdfPTable(content[0].length);
//設置表格佔PDF文檔100%寬度
table.setWidthPercentage(100);
//設置表格控件水平方向左對齊
table.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
//創建一個表格的表頭單元格
PdfPCell pdfTableHeaderCell = new PdfPCell();
//設置表格的表頭單元格顏色
pdfTableHeaderCell.setBackgroundColor(new Color(213, 141, 69));
pdfTableHeaderCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
for (String tableHeaderInfo : content[0]) {
pdfTableHeaderCell.setPhrase(new Paragraph(tableHeaderInfo, f8));
table.addCell(pdfTableHeaderCell);
}
//創建一個表格的正文內容單元格
PdfPCell pdfTableContentCell = new PdfPCell();
pdfTableContentCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
pdfTableContentCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
//表格內容行數的填充
for (int i = 0; i < content.length-1; i++) {
for (String tableContentInfo : content[1]) {
pdfTableContentCell.setPhrase(new Paragraph(tableContentInfo, f8));
table.addCell(pdfTableContentCell);
}
}
document.add(table);
return true;
} catch (FileNotFoundException de) {
de.printStackTrace();
System.err.println("pdf file: " + de.getMessage());
return false;
} catch (DocumentException de) {
de.printStackTrace();
System.err.println("document: " + de.getMessage());
return false;
} catch (IOException de) {
de.printStackTrace();
System.err.println("pdf font: " + de.getMessage());
return false;
} finally {
//關閉PDF文檔流,OutputStream文件輸出流也將在PDF文檔流關閉方法內部關閉
if (document != null && document.isOpen()) {
document.close();
}
}
}