springboot导出带有图片的pdf文件
时间: 2025-06-28 18:02:51 浏览: 15
### 如何在Spring Boot项目中实现导出包含图片的PDF文件
#### 添加依赖项
为了使Spring Boot应用程序能够处理PDF文档中的图像,需确保`pom.xml`文件内包含了必要的库。对于OpenPDF而言,其Maven坐标应被加入到项目的构建配置里[^1]。
```xml
<dependency>
<groupId>com.github.librepdf</groupId>
<artifactId>openpdf</artifactId>
<version>1.3.28</version>
</dependency>
```
#### 创建服务类方法用于生成带图PDF
定义一个具体的服务层组件,在其中编写业务逻辑以创建带有嵌入式图形元素的PDF文档。此过程涉及加载源图像资源,并将其作为对象插入至页面布局之中[^2]。
```java
import org.springframework.stereotype.Service;
import java.io.FileOutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.PdfWriter;
@Service
public class PdfExportService {
public void exportPdfWithImage(String outputPath, String imagePath) throws Exception {
Document document = new Document(PageSize.A4);
try (FileOutputStream fos = new FileOutputStream(outputPath)) {
PdfWriter.getInstance(document, fos);
document.open();
Image img = Image.getInstance(imagePath); // 加载本地路径下的图片
img.scaleToFit(500f, 500f); // 设置最大宽度高度适应A4纸张大小
document.add(img); // 将图片添加进文档主体部分
} finally {
if (!document.isOpen()) // 关闭流之前确认已打开状态
document.close();
}
}
}
```
#### 控制器接口设计
最后一步是在控制器层面暴露RESTful API端点给前端调用者访问。当接收到请求时触发上述提到的方法完成实际操作并返回下载链接或直接响应二进制数据流形式的结果集给客户端浏览器展示下载对话框。
```java
@RestController
@RequestMapping("/api/pdf")
public class PdfController {
@Autowired
private PdfExportService pdfExportService;
@GetMapping(value="/export", produces="application/pdf")
public ResponseEntity<byte[]> generatePdf() {
File tempFile = null;
try {
tempFile = Files.createTempFile("temp-", ".pdf").toFile();
pdfExportService.exportPdfWithImage(tempFile.getAbsolutePath(), "path/to/your/image.png");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
headers.setContentDispositionFormData("filename", "example_with_image.pdf");
return ResponseEntity.ok()
.headers(headers)
.body(FileUtils.readFileToByteArray(tempFile));
} catch(Exception e){
throw new RuntimeException(e.getMessage());
}finally{
if(null != tempFile && tempFile.exists()){
tempFile.deleteOnExit(); // 清理临时文件防止占用过多磁盘空间
}
}
}
}
```
通过这种方式可以轻松地扩展现有的Spring Boot应用来支持更加丰富的PDF报告生成功能,不仅限于纯文本内容还可以包括图表、照片等多种类型的视觉素材。
阅读全文
相关推荐


















