public String changePdfToImage(String filePath1,String appId) throws Exception{
String imgUrl=null;
String tempDirPath = System.getProperty("java.io.tmpdir") + "/tclLoanPz/"+appId;
File tempDir = new File(tempDirPath);
if (!tempDir.exists()) {
tempDir.mkdirs();
}
String filePath = tempDirPath + "/"+appId+".pdf";
//下载文件到本地
downloadFile(filePath1, filePath);
try(InputStream stream = new FileInputStream(filePath);
PDDocument doc = PDDocument.load(stream);
ByteArrayOutputStream os = new ByteArrayOutputStream();) {
String imgFileName="/"+appId+".jpg";
// 加载解析PDF文件
PDFRenderer pdfRenderer = new PDFRenderer(doc);
PDPageTree pages = doc.getPages();
File file = new File(tempDirPath+imgFileName);
int pageCount = pages.getCount();
for (int i = 0; i < pageCount; i++) {
BufferedImage bim = pdfRenderer.renderImageWithDPI(i, 200);
ImageIO.write(bim, "jpg", os);
byte[] dataList = os.toByteArray();
// jpg文件转出路径
if (!file.getParentFile().exists()) {
// 不存在则创建父目录及子文件
file.getParentFile().mkdirs();
file.createNewFile();
}
try(OutputStream out=new FileOutputStream(file);) {
out.write(dataList);
}catch (Exception ex){
throw new FundException("转换文件异常");
}
}
if(file.exists()){
String imgPath=file.getPath();
imgUrl = fileUpload.uploadFile(imgPath);
}
return imgUrl;
} catch (Exception e) {
throw new FundException(appId+"pdf转换成图片异常:"+e.getMessage());
} finally {
File tempFile = new File(tempDirPath);
if (tempFile.exists()) {
tempFile.deleteOnExit();
}
}
}
public static boolean downloadFile(String remoteFilePath, String localFilePath) {
logger.info("资源downloadFile: " + remoteFilePath + "下载to:" + localFilePath);
URL urlfile = null;
disableSslVerification();
HttpURLConnection httpUrl = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
File f = new File(localFilePath);
try {
urlfile = new URL(remoteFilePath);
httpUrl = (HttpURLConnection) urlfile.openConnection();
httpUrl.connect();
bis = new BufferedInputStream(httpUrl.getInputStream());
bos = new BufferedOutputStream(new FileOutputStream(f));
int len = 2048;
byte[] b = new byte[len];
while ((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
}
bos.flush();
bis.close();
httpUrl.disconnect();
System.out.println("成功");
return true;
} catch (Exception e) {
httpUrl.disconnect();
logger.info("资源路径:(" + remoteFilePath + ")下载至:(" + localFilePath + " )发生异常错误:" + e.getMessage(), e);
System.out.println("错误");
return false;
} finally {
try {
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
System.out.println("错误");
}
}
}