1.加入依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.0.6</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
2.示例
@RequestMapping(value = "/downloadDiploma")
public void downloadDiploma(HttpServletRequest request, HttpServletResponse response) throws IOException {
//创建文档对象,A4纸大小
Document document = new Document(PageSize.A4);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
PdfWriter.getInstance(document, stream);
document.open();
//解决中文乱码问题,仅适用windows系统
BaseFont baseFont = BaseFont.createFont("c:/windows/fonts/simkai.ttf",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
Font font = new Font(baseFont);
PdfPTable table = new PdfPTable(2); //创建2列的表格
PdfPCell cell1=new PdfPCell(new Paragraph("党课主题",font));//创建单元格
cell1.setFixedHeight(25);//设置行高
cell1.setHorizontalAlignment(Element.ALIGN_LEFT);//水平居左
cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
cell1.setBackgroundColor(new BaseColor(250, 250, 250));//背景色
cell1.setColspan(2);//合并单元格
table.addCell(cell1);
document.add(table,font);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
//设置响应文档类型为pdf
response.setContentType("application/pdf");
//设置响应数据大小
response.setContentLength(stream.size());
String fname="会议记录.pdf";
response.addHeader("Content-Disposition", "attachment;filename=" + new String(fname.getBytes("gb2312"), "ISO8859-1"));//设置导出pdf文件的名称
//获取响应数据流
ServletOutputStream out = response.getOutputStream();
//将pdf数据流写入响应数据流中
stream.writeTo(out);
out.flush();
out.close();
}
}
3.Linux系统下解决中文乱码问题:
使用资源字体(ClassPath) 注意资源文件在打包的时候需要忽略,不可以编译
String path =this.getClass().getResource("/").getPath() + "SIMKAI.TTF";
BaseFont baseFont = BaseFont.createFont(path,BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
4.样式结果
5.参考地址:https://www.cnblogs.com/chenpi/p/5534595.html#_label1