【发布时间】:2020-04-28 09:32:54
【问题描述】:
我已经通过指南 pdf 生成实现了。
我的班级PdfView 有一个方法:
@Override
protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer, HttpServletRequest request, HttpServletResponse response) {
response.setHeader("Content-Disposition", "attachment; filename=\"animal-profile.pdf\"");
List<Animal> animals = (List<Animal>) model.get("animals");
try {
document.add(new Paragraph("Generated animals: " + LocalDate.now()));
} catch (DocumentException e) {
e.printStackTrace();
}
PdfPTable table = new PdfPTable(animals.stream().findAny().get().getColumnCount());
table.setWidthPercentage(100.0f);
table.setSpacingBefore(10);
Font font = FontFactory.getFont(FontFactory.TIMES);
font.setColor(BaseColor.WHITE);
PdfPCell cell = new PdfPCell();
cell.setBackgroundColor(BaseColor.DARK_GRAY);
cell.setPadding(5);
cell.setPhrase(new Phrase("Animal Id", font));
table.addCell(cell);
cell.setPhrase(new Phrase("Animal name", font));
for (Animal animal : animals) {
table.addCell(animal.getId().toString());
table.addCell(animal.getName());
}
document.add(table);
}
我应该如何用GET方法实现控制器来下载PDF?
【问题讨论】:
-
这有帮助吗 - link
-
如果您希望稍后通过 API 发送生成的 pdf,您可以暂时保存它,或者您可以将流写入到具有正确 MIME 类型的同一 API 调用中返回的响应中。跨度>
-
@AmeyKulkarni 我按下下载按钮,没有任何反应。我使用的是 thymeleaf 和 Spring Boot 2,所以我没有这个 spring-mvc.xml 配置,对吗?
-
@AshutoshSharma 太奇怪的答案没有具体的例子......
-
@andrew17 试图将我的答案放在答案部分的 sudo 代码中,希望对您有所帮助。
标签: java spring spring-boot pdf