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 中的所有图像路径。
最好的问候,奥勒良
看一下MultipleImages示例,您会发现您的代码中有两个错误:
看看我的代码:
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实例时需要将页面大小设置为第一个图像的大小。