The issue you’re facing is due to the default orientation of the image being inserted. When you insert an image into a PDF, its orientation (portrait or landscape) can affect how it appears on the page. You need to adjust the image’s position and possibly its rotation based on the page’s orientation.
Solution
To insert the image at a fixed position based on the page’s orientation, you can set the image’s position using the setPosition method. Additionally, you can rotate the image if necessary. Here’s how you can modify your code:
Code
public static void main(String[] args) {
try {
String inFilePath = "E:\\test\\pdf_signature\\a.pdf";
String outFilePath = "E:\\test\\pdf_signature\\z" + Instant.now().toEpochMilli() + ".pdf";
String base64Image = "iVBORw0KGgoAAAANSUhEUgAAAUAAAACgCAYA";
// Load the PDF document
Document pdfDocument = new Document(inFilePath);
Page page = pdfDocument.getPages().get_Item(1);
boolean isLandscape = page.getPageInfo().getWidth() > page.getPageInfo().getHeight();
log.info("isLandscape: {}", isLandscape);
// Create an image object
Image image = new Image();
image.setImageStream(new ByteArrayInputStream(Base64.getDecoder().decode(base64Image)));
image.setFixWidth(100);
image.setFixHeight(50);
// Set the position based on orientation
if (isLandscape) {
image.setPosition(400, 100); // Adjust X and Y for landscape
} else {
image.setPosition(100, 400); // Adjust X and Y for portrait
}
// Optionally rotate the image if needed
// image.setRotation(90); // Uncomment to rotate
// Add the image to the page
page.getParagraphs().add(image);
pdfDocument.save(outFilePath);
} catch (Exception e) {
e.printStackTrace();
}
}
Next Steps
Adjust the setPosition values based on where you want the image to appear on the page.
If you need to rotate the image, uncomment the setRotation line and set the desired angle.
Test the code to ensure the image appears correctly in both landscape and portrait orientations.
If you have any further questions or need additional assistance, please let me know!