首先,确保项目中导入了itextpdf5.5.8的jar包,如果是maven的话,确保引入了itextpdf的依赖
由于itextpdf5.5.8的版本中对中文是不支持的,如果pdf中存在中文的话需要引入字体,可以百度一些免费的商用字体,可以在这里面下载ttf文件到项目中
首先创建document对象
Document document = new Document();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ServletContext servletContext = getRequest().getServletContext();
Font chineseFont = fontUtils(servletContext, "/fonts/HanZiZhiMeiFangSongGBK-MianFei(God-FangSongGBK-free)-2.ttf");
然后通过ByteArrayOutPutStream写入字节数组中,ByteArrayOutPutStream是输出流写入一个内部字节数组的一个类。当你想将数据先存储在内存中,而不是直接写入文件或网络时,它非常有用。获取servletContext上下文,通过fontUtils将中文字体设置出来
private Font fontUtils(ServletContext servletContext, String fontFilePath) throws IOException, DocumentException {
InputStream is = servletContext.getResourceAsStream(fontFilePath);
if (is == null) {
throw new IOException("Font file not found at path: " + fontFilePath);
}
// 创建一个临时文件来存储字体文件
File tempFile = File.createTempFile("font", ".ttf");
try (FileOutputStream fos = new FileOutputStream(tempFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
// 如果创建临时文件或写入时发生错误,删除可能已创建的临时文件
if (tempFile != null && tempFile.exists()) {
tempFile.delete();
}
throw e; // 重新抛出异常
} finally {
if (is != null) {
is.close();
}
}
// 关闭输入流
is.close();
// 使用临时文件的路径创建BaseFont对象
String fontPath = tempFile.getAbsolutePath();
BaseFont baseFont = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
boolean deleted = tempFile.delete();
if (!deleted) {
// 如果删除失败,您可以选择记录一个警告或抛出异常
log.warn("Unable to delete temporary font file: " + tempFile.getAbsolutePath());
}
// 创建并返回Font对象
return new Font(baseFont, 12, Font.NORMAL);
}
}
try {
PdfWriter instance = PdfWriter.getInstance(document, baos);
document.open();
Paragraph numberParagraph = new Paragraph("编号: " + formRecords.getStr("number"),chineseFont);
document.add(numberParagraph);
document.add(new Chunk(Chunk.NEWLINE)); // 添加新行
//这是pdf中一个form表单的部分
document.add(currencyParagraph);
document.add(new Chunk(Chunk.NEWLINE)); // 添加新行
PdfPTable table = new PdfPTable(customHeaders.length);
for (String headerText : customHeaders) {
PdfPCell headerCell = new PdfPCell(new Phrase(headerText, chineseFont)); // 使用中文字体
headerCell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(headerCell);
}
BigDecimal totalPrice = BigDecimal.ZERO;
for (Record record : tableRecords) {
// 使用中文字体创建单元格内容
table.addCell(new Phrase(record.getStr("artno"), chineseFont));
}
// 将表格添加到PDF文档中
document.add(table);
document.close();
byte[] pdfBytes = baos.toByteArray();
HttpServletResponse response = getResponse();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=report.pdf");
response.setContentLength(pdfBytes.length);
try (ServletOutputStream os = response.getOutputStream()) {
os.write(pdfBytes);
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
通过以上代码可以实现生成pdf前端进行下载