即时创建PDF而不将其存储在驱动器/服务器上,然后将其转换为FileBody类型

时间:2017-04-11 16:22:51

标签: java file pdf-generation

我有以下代码:

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    //Want this to be on-the-fly pdf creation instead of using an existing one
    File thePDF = new File("/path-to-pdf");

    FileBody fb = new FileBody(thePDF);
    builder.addPart("Body", fb);
    ....Code to use this builder with pdf in a rest callout

在上面的代码中我使用的是现有的pdf文件。我想使用动态创建的pdf代替。我知道如何使用iText创建pdf,但我不想在服务器中创建新文件。有没有办法存储文件的内容并输入类型为FileBody或File以与MultipartEntityBuilder一起使用,而不是在磁盘上实际创建文件?

有什么建议吗?

提前致谢!

1 个答案:

答案 0 :(得分:3)

创建PDF使用:

ByteArrayOutputStream baOut = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, baOut);

并且用于构建HttpEntity:

builder.addBinaryBody(name, baOut.toByteArray(), contentType, filename);