【问题标题】:How to send generated PDF document to frontend in Restfull way in Spring Boot?如何在 Spring Boot 中以 Restfull 方式将生成的 PDF 文档发送到前端?
【发布时间】: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


【解决方案1】:

使用 API 下载图像的示例代码如下所示 -

@RequestMapping("/api/download/{fileName:.+}")
public void downloadPDFResource(HttpServletRequest request, HttpServletResponse response,@PathVariable("fileName") String fileName) throws IOException {
    String path = somePath + fileName;
    File file = new File(path);
    if (file.exists()) {
        String mimeType = URLConnection.guessContentTypeFromName(file.getName()); // for you it would be application/pdf
        if (mimeType == null) mimeType = "application/octet-stream";
        response.setContentType(mimeType);
        response.setHeader("Content-Disposition", String.format("inline; filename=\"" + file.getName() + "\""));
        response.setContentLength((int) file.length());
        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
        FileCopyUtils.copy(inputStream, response.getOutputStream());
    }
}

转到网址 - http://localhost:8080/download/api/download/fileName.pdf 假设您的服务部署在 8080 端口
您应该可以预览文件。
注意:如果您想下载文件将 Content-Disposition 设置为附件

【讨论】:

  • somePath 是什么?它是我的pdf文件的路径吗?因为我没有,所以我生成 pdf 到前端而不是本地目录
  • 你只需要文件可以在任何地方,我写的一般。
【解决方案2】:

AbstractPdfView 本身就是一个View,它的实例可以简单地从处理程序方法返回以呈现文档。

来自Spring Reference. PDF Views

控制器可以从外部视图定义(按名称引用它)或作为处理程序方法的View 实例返回这样的视图。


这是一个最小的例子:

SimplePdfView.kt:

class SimplePdfView : AbstractPdfView() {
    override fun buildPdfDocument(
            model: MutableMap<String, Any>,
            document: Document, writer: PdfWriter,
            request: HttpServletRequest, response: HttpServletResponse
    ) {
        document.add(Paragraph("My paragraph"))
    }
}

SimpleController.kt:

@Controller
class SimpleController {
    @GetMapping
    fun getPdf() = SimplePdfView()
}

/ 端点被命中时,pdf 在浏览器中呈现。


如果你需要下载已有的pdf,你可以看看this answer

【讨论】:

    猜你喜欢
    • 2017-04-09
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 2010-09-21
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    相关资源
    最近更新 更多