使用java将多个图像添加到带有iText的单个pdf文件中

aur*_*anr 3 java pdf image itext

我有以下代码,但此代码仅将最后一个图像添加到 pdf 中。

    try {
        filePath = (filePath != null && filePath.endsWith(".pdf")) ? filePath
                : filePath + ".pdf";
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream(filePath));
        document.open();    
        // document.add(new Paragraph("Image Example"));
        for (String imageIpath : imagePathsList) {

            // Add Image
            Image image1 = Image.getInstance(imageIpath);
            // Fixed Positioning
            image1.setAbsolutePosition(10f, 10f);
            // Scale to new height and new width of image
            image1.scaleAbsolute(600, 800);
            // image1.scalePercent(0.5f);
            // Add to document
            document.add(image1);
            //document.bottom();


        }
        writer.close();

    } catch (Exception e) {
        LOGGER.error(e.getMessage());
    }
Run Code Online (Sandbox Code Playgroud)

你能给我一个关于如何更新代码以便将所有图像添加到导出的 pdf 的提示吗?imagePathsList 包含我想添加到单个 pdf 中的所有图像路径。

最好的问候,奥勒良

Bru*_*gie 7

看一下MultipleImages示例,您会发现您的代码中有两个错误:

  1. 您创建一个大小为 595 x 842 用户单位的页面,然后将每个图像添加到该页面,而不管图像的尺寸如何。
  2. 您声称只添加了一张图片,但事实并非如此。您正在同一页面上将所有图像叠加在一起。最后一张图片涵盖了所有前面的图片。

看看我的代码:

public void createPdf(String dest) throws IOException, DocumentException {
    Image img = Image.getInstance(IMAGES[0]);
    Document document = new Document(img);
    PdfWriter.getInstance(document, new FileOutputStream(dest));
    document.open();
    for (String image : IMAGES) {
        img = Image.getInstance(image);
        document.setPageSize(img);
        document.newPage();
        img.setAbsolutePosition(0, 0);
        document.add(img);
    }
    document.close();
}
Run Code Online (Sandbox Code Playgroud)

Document使用第一个图像的大小创建了一个实例。然后我遍历一组图像,触发newPage() [*]之前将下一页的页面大小设置为每个图像的大小。然后我在坐标 0, 0 添加图像,因为现在图像的大小将匹配每个页面的大小。

[*]newPage()方法仅在当前页面添加了某些内容时才有效。第一次执行循环时,还没有添加任何内容,因此什么也没有发生。这就是为什么在创建Document实例时需要将页面大小设置为第一个图像的大小。