我需要您的帮助,从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());
}