首先需要导入所需工具类
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>fontbox</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.1.19</version>
</dependency>
1、PDF转图片的方法 for那里看看是几张图片。 几页。根据页数进行转
/***
* PDF文件转PNG图片,全部页数
*
* @param PdfFilePath pdf完整路径
* @param dpi dpi越大转换后越清晰,相对转换速度越慢
* @return
*/
public static String pdf2Image(String PdfFilePath, String dstImgFolder, int dpi) {
File file = new File(PdfFilePath);
PDDocument pdDocument;
try {
String imgPDFPath = file.getParent();
int dot = file.getName().lastIndexOf('.');
String imagePDFName = file.getName().substring(0, dot); // 获取图片文件名
String imgFolderPath = dstImgFolder;
pdDocument = PDDocument.load(file);
PDFRenderer renderer = new PDFRenderer(pdDocument);
/* dpi越大转换后越清晰,相对转换速度越慢 */
StringBuffer imgFilePath = null;
for (int i = 1; i < 2; i++) {
String imgFilePathPrefix = imgFolderPath + File.separator + imagePDFName;
imgFilePath = new StringBuffer();
imgFilePath.append(imgFilePathPrefix);
imgFilePath.append(".png");
File dstFile = new File(imgFilePath.toString());
BufferedImage image = renderer.renderImageWithDPI(i, dpi);
ImageIO.write(image, "png", dstFile);
}
System.out.println("PDF文档转PNG图片成功!");
return imgFilePath.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
2、调用这个方法 生成BASE64数据
String s = wpath + BRCA + "-" + CTNND1_15951 + "-KMplot.pdf";
//转换返回图片地址
String s1 = pdf2Image(s, wpath, 300);
File file = new File(s1);
//把图片转换为BASE64数据
FileInputStream inputFile = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
inputFile.read(buffer);
inputFile.close();
String ss = new BASE64Encoder().encode(buffer);
3、使用ajax的方式将图片数据取回。直接设置如IMG标签中
img就是取回的数据
<img id="ImagePic" src="data:image/png;base64,'+img+'" alt="Base64 encoded image" style="600px;" />
完整的ajax代码
var index = layer.load();
$.ajax({
type:"post",
dataType:"json",
contentType:'application/json;charset=UTF-8',
url:"getTnImg",
data:JSON.stringify(data),
success:function(resp){
layer.close(index);
var img = resp.img;
var html = '<img id="ImagePic" src="data:image/png;base64,'+img+'" alt="Base64 encoded image" style="600px;" />';
layer.open({
type: 1,
skin: 'layui-layer-rim', //加上边框
area: ['50%', '90%'], //宽高
content: html
});
},
error:function(XMLHttpRequest,textStatus,errorThrown) {
console.log(XMLHttpRequest.status);
console.log(XMLHttpRequest.statusText);
}
});