Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何将pdf生成为变量而不是文件?_Java_Itext_Pdf Generation - Fatal编程技术网

Java 如何将pdf生成为变量而不是文件?

Java 如何将pdf生成为变量而不是文件?,java,itext,pdf-generation,Java,Itext,Pdf Generation,我正在创建一个pdf文件并将其存储在一个目录中。我现在想传回pdf数据,以便用户可以将其下载到他们首选的目录,即不再在该目录中创建文件。我如何创建要传回的pdfData 我知道这将涉及用变量名替换新的FileOutputStreamFILE来存储数据;然而,我无法计算出来,也无法在网上找到一个例子 我有: String filePath = System.getProperty("user.home") + "\\Documents\\"+fileName; //Test use Documen

我正在创建一个pdf文件并将其存储在一个目录中。我现在想传回pdf数据,以便用户可以将其下载到他们首选的目录,即不再在该目录中创建文件。我如何创建要传回的pdfData

我知道这将涉及用变量名替换新的FileOutputStreamFILE来存储数据;然而,我无法计算出来,也无法在网上找到一个例子

我有:

String filePath = System.getProperty("user.home") + "\\Documents\\"+fileName; //Test use
Document document = new Document(PageSize.A4, 72f, 72f, 72f, 72f);
try {
    PdfWriter.getInstance(document, new FileOutputStream(FILE));
    document.open();
    addMetaData(document);
    addImages(document);
    addTitlePage(document, recipeDetails, recipeName, servings, servingSize);
    document.close();
} catch (Exception e) {
  e.printStackTrace();
}
//return pdfData;

要显示mkl建议与代码合并的内容,请执行以下操作:

String filePath = System.getProperty("user.home") + "\\Documents\\"+fileName; //Test use
Document document = new Document(PageSize.A4, 72f, 72f, 72f, 72f);
try {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfWriter.getInstance(document, baos);
    document.open();
    addMetaData(document);
    addImages(document);
    addTitlePage(document, recipeDetails, recipeName, servings, servingSize);
    document.close();

    byte[] pdfData = baos.toByteArray();
    return pdfData;

} catch (Exception e) {
  e.printStackTrace();
}
pdfData是字节[]字节数组。这可以作为实际pdf直接流式传输/存储在任何地方。请记住,这是将PDF写入内存,因此如果同时执行大量大型PDF,则会出现可伸缩性问题


我希望这会有所帮助。

考虑使用ByteArrayOutputStream而不是FileOutputStream,在关闭文档后,从ByteArrayOutputStream检索字节数组。您好,Mark,这就是我开始的地方。有什么我应该看的吗?有什么我遗漏的吗?请只在finally子句中调用document.close。。或者最好使用新的try with resources语法:tryDocument document=new DocumentPageSize.A4、72f、72f、72f、72f{…}您的代码中有一个严重的资源泄漏错误。仅返回[B@5b0fc5b7作为检索到的字节数组,您显示的是字节数组的典型toString输出,而不是它的内容。