好吧,我遇到了一个问题,
我需要用 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 中的文件?
最佳答案
如果您使用的是 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");
}
关于java - 将输出流转换为文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17487709/