我想将一些图像转换为PDDocument对象,而不是保存到硬件。 如何从此PDDocument对象获取输入流? 我写了一个打击,得到“创建InputStream调用没有数据被写入之前流。”错误。
源的部分是:
public ByteArrayOutputStream imagesToPdf(final List<ImageEntity> images) throws IOException {
final PDDocument doc = new PDDocument();
final int count = images.size();
InputStream in = null;
PDPageContentStream contentStream = null;
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
for(int i = 0; i < count; i ++) {
final ImageEntity image = images.get(i);
byte[] byteCode = image.getByteCode();
in = new ByteArrayInputStream(byteCode);
BufferedImage bi = ImageIO.read(in);
float width = bi.getWidth();
float height = bi.getHeight();
PDPage page = new PDPage(new PDRectangle(width, height));
doc.addPage(page);
PDImageXObject pdImage = PDImageXObject.createFromByteArray(doc, byteCode, null);
contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true);
float scale = 1f;
contentStream.drawImage(pdImage, 0, 0, pdImage.getWidth()*scale, pdImage.getHeight()*scale);
IOUtils.closeQuietly(contentStream);
IOUtils.closeQuietly(in);
}
PDStream ps = new PDStream(doc);
is = ps.createInputStream();
IOUtils.copy(is, baos);
return baos;
} finally {
IOUtils.closeQuietly(contentStream);
IOUtils.closeQuietly(in);
}
}
答案 0 :(得分:1)
new PDStream(doc)
不创建一个对象,从中可以按照您的序列化形式检索doc
。它实际上做的是创建属于文档doc
的PDF流对象。
您想要做的只是
doc.save(baos);