3

I have implemented by guide pdf generating. my class PdfView has a method:

@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);
}

How should I implement controller with GET method to download PDF?

andrew17
  • 851
  • 2
  • 10
  • 25
  • Does this help - [link](https://www.codejava.net/frameworks/spring/spring-web-mvc-with-pdf-view-example-using-itext-5x) – Amey Kulkarni Jan 10 '20 at 17:53
  • You can save temporarily the pdf generated if you want it to be sent through an API later, or else you can write the stream to the response returned in the same API call with proper MIME type. – Ashutosh Jan 10 '20 at 17:58
  • @AmeyKulkarni I press download and nothing happens. I use thymeleaf and Spring Boot 2, so I dont have this spring-mvc.xml config, true? – andrew17 Jan 10 '20 at 18:20
  • @AshutoshSharma too strange answer whithout concrete examples... – andrew17 Jan 10 '20 at 18:29
  • @andrew17 tried to put my answer in sudo code in the answer section hope that helps. – Ashutosh Jan 10 '20 at 18:46

2 Answers2

2

The sample code looks like below to download the image using an 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());
    }
}

Goto the url - http://localhost:8080/download/api/download/fileName.pdf Assuming your sevices are deployed at port 8080
You should be able to preview the file.
Note : If you want to download the file set the Content-Disposition as attachment

Ashutosh
  • 917
  • 10
  • 19
1

The AbstractPdfView is a View itself and instance of it can be simply returned from a handler method to render the document.

From Spring Reference. PDF Views:

A controller can return such a view either from an external view definition (referencing it by name) or as a View instance from the handler method.


Here is a minimal example:

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()
}

When the / endpoint is hit, the pdf is rendered in browser.


If you need to download already existing pdf, you may take a look at this answer

Denis Zavedeev
  • 7,627
  • 4
  • 32
  • 53