2
我想将一些图像转换为PDDocument对象,而不是保存到硬件。 如何从此PDDocument对象获取输入流? 我写的是吹,得到“创建InputStream调用没有数据被写入流之前。”错误。pdfbox将图像转换为pdf文件
源的部分是:
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);
}
}
谢谢,它的工作原理。 – user1737352
@ user1737352太棒了!在这种情况下,请将答案标记为已接受(点击左上角的勾号)。 – mkl
抱歉,由于我的声望小于15,我无法点击左上方的三角形符号。 – user1737352