【问题标题】:Convert Outputstream to file将输出流转换为文件
【发布时间】:2013-07-03 11:42:04
【问题描述】:

我遇到了一个问题,

我需要创建一个带有 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 中的文件?

【问题讨论】:

  • 您想写入一个文件,但硬盘上没有这个文件?我不明白你的问题
  • 我需要下载pdf而不是写入硬盘。
  • 下载文件意味着将其存储到硬盘中...

标签: java html jsp pdf vraptor


【解决方案1】:

File 对象实际上并不保存数据,而是将所有操作委托给文件系统(请参阅this discussion)。 但是,您可以使用File.createTempFile 创建一个临时文件。另请查看here 寻找可能的替代方案,而不使用File 对象。

【讨论】:

    【解决方案2】:

    使用临时文件。

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

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

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

    【讨论】:

      【解决方案3】:

      如果您使用的是 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");
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-09-06
        • 2011-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-25
        相关资源
        最近更新 更多