SpringBoot 生成 PDF文件

蔚落 2024-03-22 14:47 152阅读 0赞

文章目录

  • 前言
  • 一、使用步骤
      1. 添加iText依赖
    • 2.创建一个Controller
  • 总结

前言

在Spring Boot应用程序中生成PDF需要使用第三方库,本例中我们将使用iText库,它是一个用于生成PDF文件的Java库。下面是一个示例代码,演示了如何使用iText在Spring Boot中生成PDF。

一、使用步骤

1. 添加iText依赖

在pom.xml文件中添加以下依赖:

代码如下(示例):

  1. <dependency>
  2. <groupId>com.itextpdf</groupId>
  3. <artifactId>itextpdf</artifactId>
  4. <version>5.5.13</version>
  5. </dependency>

2.创建一个Controller

在Spring Boot应用程序中,我们需要创建一个Controller类,将其注解为@Controller,并添加一个用于生成PDF的请求处理程序。

  1. import java.io.ByteArrayOutputStream;
  2. import java.io.IOException;
  3. import javax.servlet.http.HttpServletResponse;
  4. import com.itextpdf.text.Document;
  5. import com.itextpdf.text.DocumentException;
  6. import com.itextpdf.text.Font;
  7. import com.itextpdf.text.Paragraph;
  8. import com.itextpdf.text.pdf.PdfWriter;
  9. import org.springframework.stereotype.Controller;
  10. import org.springframework.web.bind.annotation.GetMapping;
  11. import org.springframework.web.bind.annotation.ResponseBody;
  12. @Controller
  13. public class PDFController {
  14. @GetMapping("/generate-pdf")
  15. public @ResponseBody void generatePDF(HttpServletResponse response) throws IOException {
  16. // 创建一个新的Document对象
  17. Document document = new Document();
  18. try {
  19. // 创建一个输出流
  20. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  21. // 将输出流与PdfWriter绑定
  22. PdfWriter.getInstance(document, baos);
  23. // 打开document
  24. document.open();
  25. // 设置字体样式
  26. Font font = new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL);
  27. // 向document中添加内容
  28. Paragraph paragraph = new Paragraph("Hello World!", font);
  29. document.add(paragraph);
  30. // 关闭document
  31. document.close();
  32. // 将PDF输出到浏览器
  33. response.setContentType("application/pdf");
  34. response.setContentLength(baos.size());
  35. response.setHeader("Content-Disposition", "attachment; filename=example.pdf");
  36. response.getOutputStream().write(baos.toByteArray());
  37. response.getOutputStream().flush();
  38. } catch (DocumentException e) {
  39. e.printStackTrace();
  40. }
  41. }
  42. }

启动应用程序
现在,您可以启动Spring Boot应用程序并访问http://localhost:8080/generate-pdf来生成一个名为“example.pdf”的PDF文件,并将其下载到浏览器中。

需要注意的是,上面的代码中将PDF输出到了浏览器中,您也可以将PDF保存到本地文件系统中,只需要将以下代码添加到try-catch块的结尾即可:

  1. FileOutputStream fileOutputStream = new FileOutputStream("example.pdf");
  2. baos.writeTo(fileOutputStream);
  3. fileOutputStream.flush();
  4. fileOutputStream.close();

总结

以上代码将生成一个名为“example.pdf”的PDF文件并将其保存到本地文件系统中。

发表评论

表情:
评论列表 (有 0 条评论,152人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Itext生成PDF文件

    最近做一个项目的报表,设计导出问题,要求pdf、excel、word。说实话一个字,烦。写个备忘录吧。。。虽然还是很烦 所需依赖:itext-asian-5.2.0.jar