I want to convert some images to PDDocument
object, and not save to hardware. How to get input stream from this PDDocument
object?
I wrote as below, got "Create InputStream called without data being written before to stream." error.
The part of source is:
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);
}
}
new PDStream(doc)
does not create an object from which the doc
can be retrieved in serialized form as you assume. What it actually does is create a PDF stream object belonging to the document doc
.
What you want to do is simply
doc.save(baos);