一、我常用的几个对象
BaseFont
1、含义:创建各种类型字体的基类
2、创建字体
BaseFont baseFont = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font titleFont = new Font(baseFont, 22, Font.BOLD);
Font columnFont = new Font(baseFont, 6, Font.BOLD);
Font dataFont = new Font(baseFont, 5, Font.NORMAL);
Paragraph
1、含义:段落
2、创建及设置文本和样式
Paragraph paragraph = new Paragraph();
paragraph.setAlignment(Element.ALIGN_CENTER);
paragraph.add(new Phrase("段落文本", titleFont));
PdfPTable
1、含义:表格
2、创建及设置样式
PdfPTable table = new PdfPTable(15);
table.setSpacingBefore(20f);
table.setSpacingAfter(20f);
PdfPCell
1、含义:单元格
2、创建、设置文本和样式、合并单元格操作
PdfPCell cell = new PdfPCell(new Phrase(columnName, font));
cell.setUseAscender(true);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setMinimumHeight(20f);
cell.setBackgroundColor(new BaseColor(217, 217, 217));
cell.setRowspan(rowSpan);
cell.setColspan(colspan);
cell.disableBorderSide(15);
二、导出 PDF 代码
1、导出到指定文件里面
public void exportExcel() {
OutputStream out = null;
try {
out = new FileOutputStream("D:/test.pdf");
Document doc = new Document();
doc.setPageSize(PageSize.LETTER.rotate());
PdfWriter.getInstance(doc, out);
doc.open();
doc.add(paragraph);
doc.add(table);
doc.close();
} catch (Exception e) {
e.printStackTrace();
if (out != null) {
try {
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
2、浏览器导出
public void exportExcel(HttpServletResponse response) throws IOException, DocumentException {
String filename = "PDF文件名称.pdf";
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filename, "UTF-8"));
Document doc = new Document();
doc.setPageSize(PageSize.LETTER.rotate());
PdfWriter.getInstance(doc, response.getOutputStream());
doc.open();
doc.add(paragraph);
doc.add(table);
doc.close();
}
3、如果代码太多,可以根据自己需求把代码部分代码提取出来
private void addPdfPCell(PdfPTable table, String columnName, Integer rowSpan, Integer colspan, Font font, Boolean isUseColor) {
PdfPCell cell = new PdfPCell(new Phrase(columnName, font));
cell.setMinimumHeight(20f);
if (isUseColor) {
cell.setBackgroundColor(new BaseColor(217, 217, 217));
}
if (rowSpan != null) {
cell.setRowspan(rowSpan);
}
if (colspan != null) {
cell.setColspan(colspan);
}
cell.setUseAscender(true);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
}