Java PDF轉換成圖片並輸出給前臺展現

首先須要導入所需工具類html

<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>
 ajax

一、PDF轉圖片的方法    for那裏看看是幾張圖片。 幾頁。根據頁數進行轉apache

/***
* 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;
}
}
 json

二、調用這個方法  生成BASE64數據app

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);
 工具

三、使用ajax的方式將圖片數據取回。直接設置如IMG標籤中post

img就是取回的數據ui

<img id="ImagePic" src="data:image/png;base64,'+img+'" alt="Base64 encoded image" style="width:600px;" />
完整的ajax代碼url

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="width: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);
}
});
 code

相關文章
相關標籤/搜索