3

Well i'm stucked with a problem,

I need to create a PDF with a html source and i did this way:

File pdf = new File("/home/wrk/relatorio.pdf");
OutputStream out = new FileOutputStream(pdf);
InputStream input = new ByteArrayInputStream(build.toString().getBytes());//Build is a StringBuilder obj
Tidy tidy = new Tidy();
Document doc = tidy.parseDOM(input, null);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(doc, null);
renderer.layout();
renderer.createPDF(out);
out.flush();
out.close();

well i'm using JSP so i need to download this file to the user not write in the server...

How do I transform this Outputstream output to a file in the java without write this file in hard drive ?

gmlyranetwork
  • 91
  • 1
  • 2
  • 10

3 Answers3

2

If you're using VRaptor 3.3.0+ you can use the ByteArrayDownload class. Starting with your code, you can use this:

@Path("/download-relatorio")
public Download download() {
    // Everything will be stored into this OutputStream
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    InputStream input = new ByteArrayInputStream(build.toString().getBytes());
    Tidy tidy = new Tidy();
    Document doc = tidy.parseDOM(input, null);
    ITextRenderer renderer = new ITextRenderer();
    renderer.setDocument(doc, null);
    renderer.layout();
    renderer.createPDF(out);
    out.flush();
    out.close();

    // Now that you have finished, return a new ByteArrayDownload()
    // The 2nd and 3rd parameters are the Content-Type and File Name
    // (which will be shown to the end-user)
    return new ByteArrayDownload(out.toByteArray(), "application/pdf", "Relatorio.pdf");
}
Rafael Lins
  • 458
  • 7
  • 12
0

A File object does not actually hold the data but delegates all operations to the file system (see this discussion). You could, however, create a temporary file using File.createTempFile. Also look here for a possible alternative without using a File object.

Community
  • 1
  • 1
Michael Lang
  • 3,902
  • 1
  • 23
  • 37
-1

use temporary files.

File temp = File.createTempFile(prefix ,suffix);

prefix -- The prefix string defines the files name; must be at least three characters long.

suffix -- The suffix string defines the file's extension; if null the suffix ".tmp" will be used.

Rotom92
  • 696
  • 1
  • 7
  • 20