使用iText,在内存上生成一个在磁盘上生成的PDF

我正在从Java应用程序生成PDF。 (效果很好)问题是PDF在磁盘上生成为:

Document documento = new Document(PageSize.A4, 25, 25, 25, 25); PdfWriter writer = PdfWriter.getInstance(documento, new FileOutputStream("/Users/sheldon/Desktop/Registry.pdf")); documento.open(); // Put some images on the PDF for( byte[] imagen : imagenes ) { Image hoja = Image.getInstance(imagen); hoja.scaleToFit(documento.getPageSize().getHeight(), documento.getPageSize().getWidth()); documento.add(hoja); } documento.addTitle("Generated Registry!"); documento.close(); 

现在,当用户搜索PDF并打印它们时,我不需要将它们存储在磁盘上。 我需要(如果可能的话)在内存中生成它们并使用命令打开(使用acrobat reader)该文档。

那可能吗? 任何的想法。

如果没有,有什么建议(根据您的经验)。

提前谢谢你。

编辑:

适用于标准Java桌面应用程序。

为此,Acrobat需要能够访问另一个进程(Java)的内存。 这不可能。

您可能只想将文件写入系统的临时目录。

如果在Acrobat中打开PDF后您的应用程序保持打开状态,您可能希望使用File.createTempFile()File.deleteOnExit()的组合来在JVM终止时删除该文件。

如果您不希望iText将文档生成到磁盘,那么只需执行以下操作:

 Document documento = new Document(PageSize.A4, 25, 25, 25, 25); ByteArrayOutputStream out = new ByteArrayOutputStream(); PdfWriter writer = PdfWriter.getInstance(documento, out); (...) return out.getBytes(); 

这对你没有帮助,因为在你把它写在某处Acrobat可以访问它之前,Reader无法访问它。 如果您不希望它在磁盘上,则在内存磁盘中安装虚拟磁盘并在那里写入文件。 如何执行此操作取决于您的操作系统。

是的……这很容易。 您只需将内容流回请求者(即通过Servlet中的Response对象)。 您还需要设置标题

 'Content-type: application/pdf' 

您可能还想将其设置为不在浏览器中打开

 'Content-Disposition: attachment; filename="downloaded.pdf"' 

我不是JAVA程序员,但此刻我正在和iText合作,我有同样的问题。 我想如果pdfWriter只需要一个outputStream,那么也可以使用java.io.ByteArrayOutputStream。 那将是新的ByteArrayOutputStream()我想,在JAVA中,因为我正在使用ColdFusion。

对我来说,它有效。

该要求可以是用户可以下载在运行时生成的PDF的Web应用程序。 File.createTempFile()可能会为临时文件创建一个大数字,而File.deleteOnExit()只会在JVM出口上调用 – 这不是理想的情况。

在这种情况下,最好实现@behe建议的内容,最后将ByteArrayOutputStream对象写入ServletOutputStream

 ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream(); //get ByteArrayOutputStream from behe's code snippet ByteArrayOutputStream bout = (...) bout.writeTo(servletOutputStream); httpServletResponse.setContentType("application/octet-stream"); httpServletResponse.setHeader("Content-Disposition", "attachment;filename=\"" +  + "\"");