1.引入依赖
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.24</version>
</dependency>
2.工具方法
package com.prescription.transfer.system.utils;
import org.apache.pdfbox.io.IOUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class ImgToPdf {
public static File getPdfFile(File imgFile, String filePath) throws IOException {
File outputFile = new File(filePath);
genPdf(readBytesFromFile(imgFile), outputFile);
return outputFile;
}
private static void genPdf(byte[] imageBytes, File outputFile) throws IOException {
PDDocument document = new PDDocument();
PDImageXObject image = PDImageXObject.createFromByteArray(document, imageBytes, "image");
PDRectangle pageSize = new PDRectangle(image.getWidth(), image.getHeight());
PDPage page = new PDPage(pageSize);
document.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
float pageWidth = pageSize.getWidth();
float pageHeight = pageSize.getHeight();
float imageWidth = image.getWidth();
float imageHeight = image.getHeight();
float scale = Math.min(pageWidth / imageWidth, pageHeight / imageHeight);
float scaledWidth = imageWidth * scale;
float scaledHeight = imageHeight * scale;
float x = (pageWidth - scaledWidth) / 2;
float y = (pageHeight - scaledHeight) / 2;
contentStream.drawImage(image, x, y, scaledWidth, scaledHeight);
contentStream.close();
document.save(outputFile);
document.close();
}
private static byte[] readBytesFromFile(File file) throws IOException {
FileInputStream inputStream = new FileInputStream(file);
byte[] bytes = IOUtils.toByteArray(inputStream);
inputStream.close();
return bytes;
}
}