面试造航母,工作CURD,又是一天。
今天遇到了一个小需求,页面上上传一个pdf,要求上传成功之后,显示出该pdf的图片缩略图,至于需求,不想说什么,来,看代码:
Controller的方法:
public ApiResponse<String> displayBack(@RequestParam("src") String path) {
String src = path.trim();
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
PDDocument doc = null;
ByteArrayOutputStream out = null;
try {
URL url = new URL(src);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
inputStream = urlConnection.getInputStream();
doc = PDDocument.load(inputStream);
PDFRenderer renderer = new PDFRenderer(doc);
BufferedImage image = renderer.renderImage(0);
int height = image.getHeight();
int width = image.getWidth();
BufferedImage newBImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
newBImage.getGraphics().drawImage(image, 0, 0, width, height, null);
out = new ByteArrayOutputStream();
ImageIO.write(newBImage, "jpg", out);
byte[] smallContent = out.toByteArray();
//进行base64加密
String data = Base64Utils.encodeToString(smallContent);
return ApiResponse.success("data:image/jpg;base64,".concat(data));
} catch (IOException e) {
LOGGER.error("打开失败,文件路径为:" + src, e);
e.printStackTrace();
} finally {
try {
doc.close();
inputStream.close();
urlConnection.disconnect();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
重点是找对jar包,此处用的是
org.apache.pdfbox.pdmodel.PDDocument
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.11</version>
</dependency>
和它的一些方法,比如convertToImage(),之后就没什么了,获取BufferedImage,然后画图,输出为字节数组,然后转换为base64串,传给页面的img标签显示,当然在src前要加: data:image/jpg;base64,这样才能正确显示出为jpg格式的图片。
今天领导说,显示pdf、图片这种事情,由前端来做,后台是提供服务的,如果提供文件流,接口调得多了就死了。。又长见识了。
所以,就有了pdf.js,火狐的,用来做pdf阅读器的,功能很强大~