Free Support Forum -

Problem adding image

I’ve a problem adding an image to an existing pdf file.
I followed instructions from Aspose Pdf Java documentation.
I use the same signature and code file with 2 different pdf
One pdf shows the new added image perfetcly the other doesn’t.
No errors are shown in both executions.
In the both cases the size of the new file is a little larger then the original one.
What’s wrong ?
Here my code

public byte[] addLayer(byte[] xpDocument, byte[] xpLayer, DocumentoFirmabile xpCoordinate) throws IOException {
	Document doc = new Document(new ByteArrayInputStream(xpDocument));
	PageCollection collection = doc.getPages();
	int size = collection.size();
	Page page = collection.get_Item(size);  //ATTENZIONE base 1
	if(xpLayer != null) {
		InputStream imageStream = new ByteArrayInputStream(xpLayer);
		String imageName = page.getResources().getImages().add(imageStream);
		page.getContents().add(new GSave());
		int lowerLeftX = xpCoordinate.getLowerLeftX();
		int lowerLeftY = xpCoordinate.getLowerLeftY();
		int upperRightX = xpCoordinate.getUpperRightX();
		int upperRightY = xpCoordinate.getUpperRightY();
		Rectangle rectangle = new Rectangle(lowerLeftX, lowerLeftY, upperRightX, upperRightY);
		Matrix matrix = new Matrix(new double[] { rectangle.getURX() - rectangle.getLLX(), 0, 0, rectangle.getURY() - rectangle.getLLY(), rectangle.getLLX(), rectangle.getLLY() });
		page.getContents().add(new ConcatenateMatrix(matrix));
		page.getContents().add(new Do(imageName));
		page.getContents().add(new GRestore());
	ByteArrayOutputStream output = new ByteArrayOutputStream();;
	return output.toByteArray();


Could you kindly share your sample PDF documents (working and non-working) with us so that we can also test the scenario in our environment and address it accordingly. (933.5 KB)
You’ll find the required documents.
GoodBefore and BadBefore are the good and the bad one before adding the image.
GoodAfter and BadAfter are prodced after adding the image.


We could not find any signature image at all in the document i.e. BadAfter.pdf. Also, the second document contains an image inside instead of textual content. Rendering another image over an existing one may cause some issues. Nevertheless, would you please share your sample image with us as well and a screenshot of how it is looking bad? Also, please try to use ImageStamp in order to add images inside PDF for better results:

Document pdfDocument = new Document(dataDir + "BadBefore.pdf");
// create image stamp
ImageStamp imageStamp = new ImageStamp(dataDir + "signature.png");
// add stamp to particular page
// save output document + "ImageStamp_output.pdf");