且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-06-24 08:28:37

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

Take a look at the MultipleImages example and you'll discover that there are two errors in your code:


  1. 您创建一个大小为595 x 842用户单位的页面,无论图像的尺寸如何,您都将每个图像添加到该页面。

  2. 您声称只添加了一个图像,但事实并非如此。您正在同一页上将所有图像添加到彼此之上。最后一张图片涵盖了上述所有图片。

  1. You create a page with size 595 x 842 user units, and you add every image to that page regardless of the dimensions of the image.
  2. You claim that only one image is added, but that's not true. You are adding all the images on top of each other on the same page. The last image covers all the preceding images.

查看我的代码:

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

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

I create a Document instance using the size of the first image. I then loop over an array of images, setting the page size of the next page to the size of each image before I trigger a newPage() [*]. Then I add the image at coordinate 0, 0 because now the size of the image will match the size of each page.

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

[*] The newPage() method only has effect if something was added to the current page. The first time you go through the loop, nothing has been added yet, so nothing happens. This is why you need set the page size to the size of the first image when you create the Document instance.