合并PDF文件中的多个图像 [英] Merge multiple images in a PDF file

查看:204
本文介绍了合并PDF文件中的多个图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试合并单个PDF文件中目录中的多个图像。我已经从itext网站构建了一个示例代码,但问题是图像没有正确添加到PDF中,只是每个图像的边框在右边可见:

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();

}

任何帮助?

推荐答案

尝试将图像添加为单元格表格。请参阅以下示例:

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

这篇关于合并PDF文件中的多个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆