Как отправить созданный PDF-документ в веб-интерфейс Restfull в Spring Boot? - PullRequest
1 голос
/ 10 января 2020

Я реализовал руководство по генерации 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?

1 Ответ

0 голосов
/ 10 января 2020

Пример кода выглядит ниже для загрузки изображения с помощью 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());
    }
}

Перейти к URL - http://localhost: 8080 / download / api / download / fileName.pdf Предполагая, что ваши службы развернуты в порту 8080 Вы должны быть в состоянии предварительно просмотреть файл. Примечание: Если вы хотите загрузить файл , установите Content-Disposition в качестве вложения

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...