3

好吧,我遇到了一个问题,

我需要创建一个带有 html 源的 PDF,我这样做了:

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

好吧,我正在使用 JSP,所以我需要将此文件下载给用户,而不是写入服务器...

如何将此 Outputstream 输出转换为 java 中的文件而不将此文件写入硬盘驱动器?

4

3 回答 3

2

如果您使用的是 VRaptor 3.3.0+,则可以使用ByteArrayDownload该类。从您的代码开始,您可以使用它:

@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");
}
于 2015-04-19T16:41:23.927 回答
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.

于 2013-07-05T11:46:26.690 回答
-1

使用临时文件。

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

prefix -- 前缀字符串定义文件名;长度必须至少为三个字符。

suffix -- 后缀字符串定义文件的扩展名;如果为 null,则将使用后缀“.tmp”。

于 2015-04-04T10:34:41.580 回答