本地图片转换为PDF
1.需要使用到pdfbox
需要添加如下依赖
<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.25</version>
</dependency>
2.图片转PDF
直接上代码
/**
* 合成PDF方法
*
* @param folderPath 图片所在路径(最好都是英文)
* @param outputPath pdf 输出路径
* @throws IOException 抛出IO异常
*/
public static void createPDFFromFolder(String folderPath, String outputPath) throws IOException {
File folder = new File(folderPath);
// 可以添加其他的图片格式
File[] files = folder.listFiles((dir, name) -> name.toLowerCase().endsWith(".jpg") || name.toLowerCase().endsWith(".png"));
if (files == null) {
throw new IOException("No files found in the specified folder.");
}
//根据文件名排序(此处可按需将比较规则重新设定)
Arrays.sort(files, Comparator.comparing(File::getName));
try (PDDocument document = new PDDocument()) {
for (File file : files) {
FileInputStream fileInputStream = new FileInputStream(file);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
byte[] result = null;
int len;
while ((len = fileInputStream.read(bytes)) != -1) {
byteArrayOutputStream.write(bytes, 0, len);
}
result = byteArrayOutputStream.toByteArray();
BufferedImage image = ImageIO.read(file);
imageToPdf(document, result, image);
}
document.save(outputPath);
}
}
public static PDDocument imageToPdf(PDDocument document, byte[] result, BufferedImage image) throws IOException {
if (image == null) {
System.out.println("无法读取当前图片" );
return document;
}
//设置为A4大小(可设置其他的大小)
PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);
try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
float imageWidth = page.getMediaBox().getWidth();
float imageHeight = page.getMediaBox().getHeight();
// 确保图片按比例缩放以适合页面大小
float scale = Math.min(imageWidth / image.getWidth(), imageHeight / image.getHeight());
// 将图片画到PDF页面上,按比例缩放
// contentStream.drawImage(PDImageXObject.createFromFile(file.toString(), document),
contentStream.drawImage(PDImageXObject.createFromByteArray(document, result,null),
0, 0,
image.getWidth() * scale, image.getHeight() * scale);
}
return document;
}