Reputation: 3984
I am trying to add image to pdf using iText with A4
page properties:
com.itextpdf.text.Document document = new com.itextpdf.text.Document(
com.itextpdf.text.PageSize.A4);
PdfWriter.getInstance(document, new FileOutputStream(m_pathToCreateFileIn + "my_web.pdf"));
System.out.println("New pdf -> " + m_pathToCreateFileIn + "my_web.pdf");
document.open();
Image image = Image.getInstance(pngPath);
image.scaleToFit(com.itextpdf.text.PageSize.A4.getWidth(), com.itextpdf.text.PageSize.A4.getHeight());
document.add(image);
I set both document
and Image
to A4 page size and still the image does not fit my document page size.
Thank you for any help.
Upvotes: 2
Views: 4928
Reputation: 51
I know this is super late to the party, but I wanted to extend on the answer from @DonKanallie a bit (which was super helpful btw) to be a bit more flexibly in dealing with images of different sizes/dimensions. As the original poster mentioned, my Image was not fitting properly in an A4 output, hence the size of the image taken into consideration and the custom rectangle below
Document document = new Document();
FileOutputStream fos = new FileOutputStream(outputPath);
Image image = Image.getInstance(inputFile);
//Get Size of Original Image for conversion
float origWidth = image.getWidth();
float origHeight = image.getHeight();
image.scaleToFit(origWidth,origHeight);
//Set position of image in top left corner
image.setAbsolutePosition(0,0);
//Create Rectangle in support of new page size
Rectangle rectangle = new Rectangle(origWidth,origHeight);
PdfWriter writer = PdfWriter.getInstance(document, fos);
writer.open();
document.open();
//Set page size before adding new page
document.setPageSize(rectangle);
document.newPage();
document.add(image);
document.close();
writer.close();
Upvotes: 2
Reputation: 449
You have to add document.newPage() before your changes will take effect, because you can't change the current page. Try:
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(m_pathToCreateFileIn + "my_web.pdf"));
document.open();
Image image = Image.getInstance(pngPath);
image.scaleToFit(PageSize.A4);
document.setPageSize(PageSize.A4);
document.newPage();
document.add(image);
document.close();
Upvotes: 2
Reputation: 44
Try to adjust parameters by x and y axis using this methods.
String imageUrl1 = "";
Image image1 = Image.getInstance(new URL(imageUrl1));
image1.scaleAbsolute(140, 190);
image1.setAbsolutePosition(450, 580);
document.add(image1);
Upvotes: -2