如何从 iText 获取书面 PDF 的 OutputStream

How to get the OutputStream of a written PDF from iText

我需要你的帮助,从 iText 获取书面 PDF 并将其存储在 OutputStream 中,然后将其转换为 InputStream

编写PDF的代码如下:

public void  CreatePDF() throws IOException {
      try{
        Document doc = new Document(PageSize.A4, 50, 50, 50, 50);
        OutputStream out = new ByteArrayOutputStream();            
        PdfWriter writer = PdfWriter.getInstance(doc, out);

        doc.open();
        PdfPTable table = new PdfPTable(1);
        PdfPCell cell = new PdfPCell(new Phrase("First PDF"));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setRunDirection(PdfWriter.RUN_DIRECTION_LTR);
        table.addCell(cell);
        doc.add(table);
        doc.close();

      }
        catch (Exception e) {
          e.printStackTrace();
                }
    } 

所以我正在寻求您的帮助,以 OutputStream 格式编写该 PDF,然后将其转换为 InputStream

我需要获取 InputStream 值,以便将其传递给文件下载行:

StreamedContent file = new DefaultStreamedContent(InputStream, "application/pdf", "xxx.pdf");

更新乔恩答案:

public InputStream createPdf1() throws IOException {
    Document doc = new Document(PageSize.A4, 50, 50, 50, 50);
    try {        

    ByteArrayOutputStream out = new ByteArrayOutputStream();            
        PdfWriter writer;
            try {
                writer = PdfWriter.getInstance(doc, out);
            } catch (DocumentException e) {
            }
            doc.open();
        PdfPTable table = new PdfPTable(1);
        PdfPCell cell = new PdfPCell(new Phrase("First PDF"));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setRunDirection(PdfWriter.RUN_DIRECTION_LTR);
        table.addCell(cell);
        doc.add(table);

        }
        catch ( Exception e)
        {
        e.printStackTrace();
        }
    return new ByteArrayInputStream(out.toByteArray());
}

您应该将 out 的声明更改为 ByteArrayOutputStream 类型,而不仅仅是 OutputStream。然后你可以调用 ByteArrayOutputStream.toByteArray() 来获取字节,并构造一个 ByteArrayInputStream 包装它。

顺便说一句,我不会那样捕获 Exception,并且我会使用 try-with-resources 语句来关闭文档,假设它实现了 AutoCloseable。遵循 Java 命名约定也是一个好主意。例如,您可能有:

public InputStream createPdf() throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();            
    try (Document doc = new Document(PageSize.A4, 50, 50, 50, 50)) {
        PdfWriter writer = PdfWriter.getInstance(doc, out);
        doc.open();
        PdfPTable table = new PdfPTable(1);
        PdfPCell cell = new PdfPCell(new Phrase("First PDF"));
        cell.setBorder(Rectangle.NO_BORDER);
        cell.setRunDirection(PdfWriter.RUN_DIRECTION_LTR);
        table.addCell(cell);
        doc.add(table);
    }
    return new ByteArrayInputStream(out.toByteArray());
}