第一个谷歌结果带我到 Add multiple images into a single pdf file with iText using java这是5年前发布的。我不确定他们使用的是哪个版本,因为 Image 对象甚至没有适合我的 getInstance 方法。不用说,我没有从该链接中得到太多帮助。
无论如何,我正在尝试创建一个 javaFX 应用程序,该应用程序循环多个 JPG 图像以创建单个 PDF 文档。下面是我的代码,它成功地从 2 个图像创建了一个 PDF,但我在使第二个图像显示在第二页上时遇到问题。
在我上面发布的链接中,我看到的简单解决方案是执行 document.newPage() 然后执行 document.add(img),但我的文档对象没有该方法?我不知道该怎么办。
PdfWriter writer = new PdfWriter("D:/sample1.pdf");
// Creating a PdfDocument
PdfDocument pdfDoc = new PdfDocument(writer);
// Adding a new page
// I can add multiple pages here, but when I add multiple images they do not
// automatically flow over to the next page.
pdfDoc.addNewPage();
pdfDoc.addNewPage();
// Creating a Document
Document document = new Document(pdfDoc);
String imageFile = "C:/Users/***/Downloads/MAT204/1.3-1.4 HW/test.jpg";
ImageData data = ImageDataFactory.create(imageFile);
Image img = new Image(data);
img.setAutoScale(true);
img.setRotationAngle(-Math.toRadians(90));
// I can add multiple images, but they overlaps each other and only
// appears on the first page.
// Is there a way for me to change the current page to write on?
document.add(img);
document.add(img);
// Closing the document
document.close();
System.out.println("PDF Created");
无论如何,我只想弄清楚如何在编写循环来自动化该过程之前手动添加另一个图像。
最佳答案
经过更多研究后,我在这里找到了答案。
https://kb.itextpdf.com/home/it7kb/examples/multiple-images
protected void manipulatePdf(String dest) throws Exception {
Image image = new Image(ImageDataFactory.create(IMAGES[0]));
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc, new PageSize(image.getImageWidth(), image.getImageHeight()));
for (int i = 0; i < IMAGES.length; i++) {
image = new Image(ImageDataFactory.create(IMAGES[i]));
pdfDoc.addNewPage(new PageSize(image.getImageWidth(), image.getImageHeight()));
image.setFixedPosition(i + 1, 0, 0);
doc.add(image);
}
doc.close();
}
关于java - 如何使用 itext7 Java 将多个图像添加到 PDF 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62475845/