0

I created a pdf file based on the thymeleaf template i'm actually using the template resolver, flying saucer, to write the file on the output stream but since i can't access the front in order to define the content of the recap which would be generated every now and then when the client needs to, i thought it would be better to generate the pdf file on the server side. So my question is:

Is there a way to get the output stream where my data is written and convert it in order to write on the fly so it won't be created in the local storage

Here's a part of my business logic:

os = new FileOutputStream(pdf);
ITextRenderer renderer = new ITextRenderer();
renderer.layout();
renderer.createPDF(os);

i use this in my controller and i use attachement content attribut in the response entity

other then that i'm open to any suggestions thanks in advance

LonelyDaoist
  • 665
  • 8
  • 22
  • I have a hard time understanding your question. Could you please remove all the irrelevant stuff, and explain what you want to do? Do you want to write the PDF to the HTTP response stream rather than to a file? Something else? – JB Nizet Nov 15 '19 at 21:39

1 Answers1

1

I had a similar task some time ago for a simple Java EE + JSF project and here's how I did it:

byte[] asPdf = .... (your pdf data)
String filename = "demo.pdf";
HttpServletResponse response = Faces.getResponse(); // Using Omnifaces in this example, but that is irrelevant

// Details: https://stackoverflow.com/a/9394237/7598851
response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
response.setContentLength(asPdf.length);
response.setCharacterEncoding("UTF-8");

try (OutputStream output = response.getOutputStream()) {
    output.write(asPdf);
} catch (IOException e) {
    // ...
}

The complete project is here, the relevant code is in this file

MartinBG
  • 1,500
  • 13
  • 22