我在将图像转换为 pdf 文件时遇到一些问题。
我完成了单个图像到 pdf 的转换,现在我想将多个图像转换为单个 pdf 文件。
我正在使用 itext 库来创建 pdf。
这是我的代码,用于仅使用一张图像创建单个 pdf。
Document convertJpgToPdf=new Document();
//Create PdfWriter for Document to hold physical file
PdfWriter.getInstance(convertJpgToPdf, new FileOutputStream("D:\\PDF_Path\\ConvertImagetoPDF.pdf"));
convertJpgToPdf.open();
// Write Somethinf into that File
convertJpgToPdf.add(new Paragraph("Welcome, Your Input Image is Converted to PDF, Save the File"));
convertJpgToPdf.add(new Paragraph("PDF Produced by Converting Image to PDF as Servlet"));
//Get the input image to Convert to PDF
Image convertJpg=Image.getInstance(uploadPath);
//Add image to Document
convertJpgToPdf.add(convertJpg);
//Close Document
convertJpgToPdf.close();
我的问题是我有一个文件夹,该文件夹包含 10 张图像,我如何将所有图像转换为单个 pdf 文件,
喜欢
PDF File Header
image1
image2
..........
..........
imageN
有可能吗。请帮我。提前致谢。
最佳答案
Document document = new Document();
// step 2
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
// step 3
document.open();
// step 4
// Adding a series of images
Image img;
for (int i = 0; i < RESOURCES.length; i++) {
img = Image.getInstance(String.format("resources/img/%s", RESOURCES[i]));
if (img.getScaledWidth() > 300 || img.getScaledHeight() > 300) {
img.scaleToFit(300, 300);
}
document.add(new Paragraph(
String.format("%s is an image of type %s", RESOURCES[i], img.getClass().getName())));
document.add(img);
}
请阅读 itext 的教程,它工作正常 click here
关于java - 如何在 java servlet 中将图像转换为 pdf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21015397/