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