【发布时间】:2015-10-04 11:56:19
【问题描述】:
我需要您帮助我从 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中的PdfWriter.getInstance(doc, out)是什么? -
@JonSkeet 我错过了一行。请查看更新后的帖子
标签: java pdf itext inputstream outputstream