添加依赖
<!-- PDF导出 --><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.11</version></dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version></dependency>
准备字体
因为转成pdf文件可能出现乱码或者不展示中文,所以需要自定义字体
打开目录 C:\Windows\Fonts
挑一个自己喜欢的字体,然后CV大法
代码
controller新增方法
// 导出pdf@GetMapping("/exportPdf")public void exportPdf(HttpServletResponse response) throws DocumentException, IOException {byte[] pdfBytes = userPdfExportService.exportUsersToPdf();String filename = "用户信息.pdf";String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString()).replace("+", "%20");response.setContentType("application/pdf");response.setHeader("Content-Disposition", "attachment; filename=" + encodedFilename);response.setContentLength(pdfBytes.length);response.getOutputStream().write(pdfBytes);response.getOutputStream().flush();response.getOutputStream().close();}
新增UserPdfExportService类
@Service
public class UserPdfExportService {@Autowiredprivate ISysUserService sysUserService;public byte[] exportUsersToPdf() throws DocumentException, IOException {//查询要导出的数据List<SysUser> users = sysUserService.selectUserList(new SysUser());ByteArrayOutputStream baos = new ByteArrayOutputStream();Document document = new Document();PdfWriter.getInstance(document, baos);document.open();// 添加标题document.add(new Paragraph("用户列表"));// 加载自定义字体InputStream is = getClass().getResourceAsStream("/static/fonts/simfang.ttf");if (is == null) {throw new IOException("字体文件未找到");}byte[] fontBytes = toByteArray(is);BaseFont baseFont = BaseFont.createFont("simfang.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED, true, fontBytes, null);Font font = new Font(baseFont, 12);// 创建表格PdfPTable table = new PdfPTable(4);table.setWidthPercentage(100);// 在表格单元格中也应使用相同的字体table.addCell(new PdfPCell(new Phrase("用户名", font)));table.addCell(new PdfPCell(new Phrase("姓名", font)));table.addCell(new PdfPCell(new Phrase("邮箱", font)));table.addCell(new PdfPCell(new Phrase("手机号", font)));for (SysUser user : users) {table.addCell(new PdfPCell(new Phrase(user.getUserName(), font)));table.addCell(new PdfPCell(new Phrase(user.getNickName(), font)));table.addCell(new PdfPCell(new Phrase(user.getEmail(), font)));table.addCell(new PdfPCell(new Phrase(user.getPhonenumber(), font)));}document.add(table);document.close();return baos.toByteArray();}/*** 流转byte字节* @param is* @return* @throws IOException*/private byte[] toByteArray(InputStream is) throws IOException {ByteArrayOutputStream buffer = new ByteArrayOutputStream();int nRead;byte[] data = new byte[16384];while ((nRead = is.read(data, 0, data.length)) != -1) {buffer.write(data, 0, nRead);}buffer.flush();return buffer.toByteArray();}}
测试
记得添加请求头