不是单页图片,是多页PDF转成一张图片的逻辑。
我这里的场景是PDF转成图片之后返回给前端,前端再在图片上实现签字,并且可拖拽的逻辑,就是签订合同的场景。
但是这里只写后端多页PDF转图片的逻辑。
先说逻辑,后面直接上代码,大致分为以下几步:
好了,直接上代码:
先在pom.xml导入依赖:
<dependency>
<groupId>org.apache.pdfboxgroupId>
<artifactId>pdfboxartifactId>
<version>2.0.1version>
dependency>
<dependency>
<groupId>org.apache.pdfboxgroupId>
<artifactId>fontboxartifactId>
<version>2.0.1version>
dependency>
public String getSinglePicBase64Contracts(String fileUrl) throws IOException {
byte[] pdfBytes = HttpUtil.createGet(fileUrl).execute().bodyBytes();
InputStream inputStream = new ByteArrayInputStream(pdfBytes);
PDDocument doc = PDDocument.load(inputStream);
PDFRenderer pdfRenderer = new PDFRenderer(doc);
List<BufferedImage> imageList = new ArrayList<>(doc.getNumberOfPages());
int maxWidth = 0;
int totalHeight = 0;
for (int i = 0; i < doc.getNumberOfPages(); i++) {
BufferedImage image = pdfRenderer.renderImage(i, 1.25f);
imageList.add(image);
if (image.getWidth() > maxWidth) {
maxWidth = image.getWidth();
}
totalHeight += image.getHeight();
}
// 绘制结果
BufferedImage result = new BufferedImage(maxWidth, totalHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = result.createGraphics();
int nowHeight = 0;
for (BufferedImage bufferedImage : imageList) {
// padding 为页面的左边距
int padding = (maxWidth - bufferedImage.getWidth()) / 2;
g2d.drawImage(bufferedImage, padding, nowHeight, null);
nowHeight += bufferedImage.getHeight();
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(result, "png", outputStream);
String singlePicBase64 = "data:image/png;base64," + Base64.encodeBase64String(outputStream.toByteArray());
return singlePicBase64;
}