1、引入jar包
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.3.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
2、公共方法
/**
*
* @param datas 数据源
* @param headers 列头
* @param crosswise rotate设置横向打印
* @param fileName 文件名
* @param title 标题
* @param response
*/
public static void createPdf(String[][] datas, String[] headers, boolean crosswise, String fileName, String title, HttpServletResponse response) {
Rectangle rectPageSize;
if (crosswise) {
rectPageSize = new Rectangle(PageSize.A4.rotate());// 定义A4页面大小, rotate设置横向打印
} else {
rectPageSize = new Rectangle(PageSize.A4);
}
Document document = new Document(rectPageSize, 50, 50, 50, 50);// 其余4个参数,设置了页面的4个边距,左右上下
try {
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font fontChinese = new Font(bfChinese, 12, Font.NORMAL);
Font fontMoney = new Font(bfChinese, 13, Font.BOLD, BaseColor.RED);
Font BlodFont = new Font(bfChinese, 12, Font.BOLD, BaseColor.BLACK);
String downloadName = new String(fileName.getBytes(), "ISO8859-1");
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment;filename=" + downloadName);
OutputStream output = response.getOutputStream();
PdfWriter.getInstance(document, output);
document.open();
Paragraph pph1 = new Paragraph(title, new Font(bfChinese, 20, Font.BOLD, BaseColor.BLACK));
pph1.setAlignment(Element.ALIGN_CENTER);
pph1.setSpacingAfter(10);
pph1.setSpacingBefore(5);
document.add(pph1);
PdfPTable table = new PdfPTable(headers.length);
table.setTotalWidth(500);
table.setLockedWidth(true);
table.setHorizontalAlignment(Element.ALIGN_CENTER);
for (int i = 0; i < headers.length; i++) {
PdfPCell cell = new PdfPCell(new Phrase(headers[i], fontChinese));
table.addCell(cell);
}
if (datas != null && datas.length > 0) {
for (int i = 0; i < datas.length; i++) {
if (i % 500 == 0) {
System.out.println("第" + i + "行,释放内存.............................................");
document.add(table);
table.deleteBodyRows();
table.setSkipFirstHeader(true);
}
for (int x = 0; x < datas[i].length; x++) {
PdfPCell cell = new PdfPCell(new Phrase(datas[i][x], fontChinese));
table.addCell(cell);
}
}
}
document.add(table);
document.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}