She*_*don 4 java pdf-generation itext
我正在从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();
Run Code Online (Sandbox Code Playgroud)
现在,当用户搜索PDF并打印它们时,我不需要将它们存储在磁盘上.我需要(如果可能的话)在内存中生成它们并使用命令打开(使用acrobat reader)该文档.
那可能吗?任何的想法.
如果没有,有什么建议(根据您的经验).
提前谢谢你.
编辑:
适用于标准Java桌面应用程序.
小智 8
如果您不希望iText将文档生成到磁盘,那么只需执行以下操作:
Document documento = new Document(PageSize.A4, 25, 25, 25, 25);
ByteArrayOutputStream out = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(documento, out);
(...)
return out.getBytes();
Run Code Online (Sandbox Code Playgroud)
但这对你没有帮助,因为在你将它写入某处Acrobat可以访问它之前,Reader无法访问它.如果您不希望它在磁盘上,则在内存磁盘中安装虚拟文件并在那里写入文件.如何执行此操作取决于您的操作系统.
是的......这很容易.您只需将内容流回请求者(即通过Servlet中的Response对象).您还需要设置标题
'Content-type: application/pdf'
Run Code Online (Sandbox Code Playgroud)
您可能还想将其设置为不在浏览器中打开
'Content-Disposition: attachment; filename="downloaded.pdf"'
Run Code Online (Sandbox Code Playgroud)
为此,Acrobat需要能够访问另一个进程(Java)的内存.这是不可能的.
您可能只想将文件写入系统的临时目录.
如果您的应用停留在Acrobat打开PDF打开后,你可能要考虑使用的组合File.createTempFile()并File.deleteOnExit(),有在JVM的终止删除的文件.