SpringBoot 生成 PDF文件
文章目录
- 前言
- 一、使用步骤
- 添加iText依赖
- 2.创建一个Controller
- 总结
前言
在Spring Boot应用程序中生成PDF需要使用第三方库,本例中我们将使用iText库,它是一个用于生成PDF文件的Java库。下面是一个示例代码,演示了如何使用iText在Spring Boot中生成PDF。
一、使用步骤
1. 添加iText依赖
在pom.xml文件中添加以下依赖:
代码如下(示例):
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
2.创建一个Controller
在Spring Boot应用程序中,我们需要创建一个Controller类,将其注解为@Controller,并添加一个用于生成PDF的请求处理程序。
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class PDFController {
@GetMapping("/generate-pdf")
public @ResponseBody void generatePDF(HttpServletResponse response) throws IOException {
// 创建一个新的Document对象
Document document = new Document();
try {
// 创建一个输出流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 将输出流与PdfWriter绑定
PdfWriter.getInstance(document, baos);
// 打开document
document.open();
// 设置字体样式
Font font = new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL);
// 向document中添加内容
Paragraph paragraph = new Paragraph("Hello World!", font);
document.add(paragraph);
// 关闭document
document.close();
// 将PDF输出到浏览器
response.setContentType("application/pdf");
response.setContentLength(baos.size());
response.setHeader("Content-Disposition", "attachment; filename=example.pdf");
response.getOutputStream().write(baos.toByteArray());
response.getOutputStream().flush();
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
启动应用程序
现在,您可以启动Spring Boot应用程序并访问http://localhost:8080/generate-pdf来生成一个名为“example.pdf”的PDF文件,并将其下载到浏览器中。
需要注意的是,上面的代码中将PDF输出到了浏览器中,您也可以将PDF保存到本地文件系统中,只需要将以下代码添加到try-catch块的结尾即可:
FileOutputStream fileOutputStream = new FileOutputStream("example.pdf");
baos.writeTo(fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
总结
以上代码将生成一个名为“example.pdf”的PDF文件并将其保存到本地文件系统中。
还没有评论,来说两句吧...