Merge multiple images in a PDF file

扶醉桌前 提交于 2019-12-24 11:26:46

问题


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?


回答1:


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;
}


来源:https://stackoverflow.com/questions/27425738/merge-multiple-images-in-a-pdf-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!