更新时间: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:
看看我的代码:
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.