I am trying to insert images as pdf pages within an already created pdf document at various page numbers but I am getting the following exception com.aspose.pdf.internal.ms.System.lh: Invalid image stream (stream) com.aspose.pdf.XImageCollection.lf(Unknown Source) com.aspose.pdf.XImageCollection.lI(Unknown Source) com.aspose.pdf.XImageCollection.lI(Unknown Source) com.aspose.pdf.XImageCollection.lI(Unknown Source) com.aspose.pdf.XImageCollection.lI(Unknown Source) com.aspose.pdf.XImageCollection.lI(Unknown Source) com.aspose.pdf.XImageCollection.lf(Unknown Source) com.aspose.pdf.XImageCollection.add(Unknown Source)
Below is the code I am using to append images as pages into the pdf:
InputStream is = new FileInputStream();
Document pdfDocument = new Document(is);
PageCollection pageList = pdfDocument.getPages();
ByteArrayInputStream imageStream = new ByteArrayInputStream(PdfUtils.generateImage());
for(int i = 0 ; i < cmds.getNumberOfPages() ; i++) {
Page newPage = pageList.add();
newPage.getResources().getImages().add(imageStream);
}
Where:
- PdfUtils.generateImage() produces a byte array
Code for generating image to insert as a page:
public static byte[] generateImage() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream(200000);
int width = 595;
int height = 842;
int[] data = new int[width * height];
int i = 0;
for (int y = 0; y < height; y++) {
int red = (y * 255) / (height - 1);
for (int x = 0; x < width; x++) {
int green = (x * 255) / (width - 1);
int blue = 128;
data[i++] = (red << 16) | (green << 8) | blue;
}
}
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
image.setRGB(0, 0, width, height, data, 0, width);
ImageIO.write(image, “JPEG”, out);
return out.toByteArray();
}
Attaching the sample PDF in the post: 2.pdf (35.9 KB)
Test cases:
- When cmds.getNumberOfPages() = 2, result = Exception
- When cmds.getNumberOfPages() = 1, result = Insertion is successful