Reputation: 2485
I'm trying to merge multiple images in a directory in a single PDF file. I've built an example code from the itext site, however the problem is that images are not added correctly to the PDF, just the border of each image is visible on the right:
private void generateMultiPageTiff(String path) throws Exception {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(
"C:\\Users\\Desktop\\out.pdf"));
document.open();
Paragraph p = new Paragraph();
File files[] = new File(path).listFiles();
for (int ii = 0; ii < files.length; ii++) {
Image img = Image.getInstance(files[ii].getAbsolutePath());
img.setAlignment(Image.LEFT);
img.setAbsolutePosition(
(PageSize.POSTCARD.getWidth() - img.getScaledWidth()) / 2,
(PageSize.POSTCARD.getHeight() - img.getScaledHeight()) / 2);
p.add(new Chunk(img, 0, 0, true));
document.add(p);
}
document.close();
}
Any help?
Upvotes: 1
Views: 2802
Reputation: 4328
Try add your images as Cell tables. See the following example:
private void generateMultiPageTiff(String path) throws Exception {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(
"C:\\Users\\Desktop\\out.pdf"));
document.open();
Paragraph p = new Paragraph();
File files[] = new File(path).listFiles();
PdfPTable table = new PdfPTable(1);
for (int ii = 0; ii < files.length; ii++) {
table.setWidthPercentage(100);
table.addCell(createImageCell(files[ii].getAbsolutePath()));
}
document.add(table);
document.close();
}
public static PdfPCell createImageCell(String path)
throws DocumentException, IOException {
Image img = Image.getInstance(path);
PdfPCell cell = new PdfPCell(img, true);
return cell;
}
Upvotes: 2