且构网

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

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

更新时间:2022-05-28 07:39:39

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

我使用第一个图像的大小创建了一个 Document 实例.然后我遍历一组图像,将下一页的页面大小设置为每个图像的大小 before 我触发 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.