方案一 icepdf转png
入坑指南
由于icepdf转png时,如果pdf中存在中文有可能会出现乱码问题,引文pdf转png时,使用pdf中的字体,所以需要使用pdf阅读器查看当前使用的pdf使用的所有字体,尤其是中文字体,务必保证pdf中使用的字体全部安装到服务器,有条件的话尽量提前在正式服务器上验证是否会出现乱码,具体查看pdf中使用的全部字体,方法参考:点击查看
本人不建议使用icepdf这个三方工具类,因为我遇到了服务器上由于字体问题导致乱码问题,解决起来,很麻烦。推荐使用方案二
使用指南
项目添加依赖:
<!-- https://mvnrepository.com/artifact/org.icepdf.os/icepdf-core -->
<dependency>
<groupId>org.icepdf.os</groupId>
<artifactId>icepdf-core</artifactId>
<version>6.2.2</version>
<exclusions>
<exclusion>
<groupId>javax.media</groupId>
<artifactId>jai_core</artifactId>
</exclusion>
</exclusions>
</dependency>
具体使用的代码:
/**
* 根据pdfurl转png图片
* @param url pdfurl
* @return 转成本地png文件地址集合,使用后需要删除
* @throws InterruptedException
*/
public static List<String> pdf2Image(String url) throws InterruptedException {
// pdf转成本地png结果集合
List<String> localPathPngList = Lists.newArrayList();
Document document = new Document();
try{
// 此处会进行url地址的链接解析、流转换
document.setUrl(new URL(url));
// 缩放比例
float scale = 2.0f;
// 旋转角度
float rotation = 0f;
String uuid = UUID.randomUUID().toString().replaceAll("-","");
String toLocalDir = "/Users/wucj/Desktop/pdfToPng/";
toLocalDir = toLocalDir + uuid+"/";
Stopwatch stopwatch = Stopwatch.createStarted();
String toLocalPngPathName = "";
for (int i = 0; i < document.getNumberOfPages(); i++) {
BufferedImage image = (BufferedImage)
document.getPageImage(i, GraphicsRenderingHints.SCREEN, org.icepdf.core.pobjects.Page.BOUNDARY_CROPBOX, rotation, scale);
RenderedImage rendImage = image;
try {
toLocalPngPathName = toLocalDir+i+".png";
File file = new File(toLocalPngPathName);
File dirParentFile = new File(file.getParent());
if(!dirParentFile.exists()){
dirParentFile.mkdirs();
}
ImageIO.write(rendImage, "png", file);
log.info("给定pdf的url转png,url:{},操作成功",url);
localPathPngList.add(toLocalPngPathName);
} catch (IOException e) {
log.error("url转png,url:{},异常:{}",url,e);
}finally {
if(null!=image){
image.flush();
}
}
}
log.info("pdf转png响应耗时:{}毫秒",stopwatch.elapsed(TimeUnit.MICROSECONDS));
return localPathPngList;
}catch (Exception e){
log.error("给定pdf的url:{}链接建立异常:{}",url,e);
return Lists.newArrayList();
}finally {
if(null!=document){
document.dispose();
}
}
}
方案二 pdfbox转png
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>fontbox</artifactId>
<version>2.0.15</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.15</version>
</dependency>
@Slf4j
public class PdfBoxToPngUtils {
private static final String toLocalDir = "/data/logs";
/**
* pdf url地址转图片
* @param pdfUrl pdf url
* @return List<String>
*/
public static List<String> pdfToPngAndUpload(String pdfUrl){
List<String> localFilePathList = pdfUrlToLocalPdf(pdfUrl);
if(CollectionUtils.isEmpty(localFilePathList)){
return Lists.newArrayList();
}
// 文件名称
String localFileName = "";
// png文件的后缀
String pngSuffix = ".png";
// 转换成功之后的png url
String pngUrl = "";
List<String> pngUrlList = Lists.newArrayList();
for (String localFilePath : localFilePathList) {
String[] localFilePathArr = localFilePath.split("\\/");
if(localFilePathArr.length>1){
localFileName = localFilePathArr[localFilePathArr.length-1];
}
try{
if(!StringUtils.isBlank(localFileName)&&localFileName.contains(pngSuffix)){
pngUrl = CloudUtil.uploadFile(UcloudConfig.BUCKET_DEVELOP, localFilePath, localFileName);
if(!StringUtils.isBlank(pngUrl)){
pngUrlList.add(pngUrl);
}
}else{
log.info("本地临时文件:{},上传至ucloud地址:{}",localFilePath,pngUrl);
}
}catch (Exception e){
log.error("本地临时文件:{}上传至ucloud异常:{}",localFilePath,e);
}finally {
// 本地文件上传至服务器之后,删除本地缓存
log.info("删除本地文件,{}", localFilePath);
com.mryx.fms.invoice.common.util.FileUtils.deleteFile(localFilePath);
}
}
return pngUrlList;
}
/**
* 网络pdf url文件转图片
* @param url pdf网络文件
* @return 集合
*/
public static List<String> pdfUrlToLocalPdf(String url){
String filePath = toLocalDir+"/"+ UUIDUtil.create() +".pdf";
try{
org.apache.commons.io.FileUtils.copyURLToFile(new URL(url),new File(filePath),1000*60,1000*60);
}catch (Exception e){
log.error("pdfbox转png异常:{}",e);
return Lists.newArrayList();
}
try{
return pdfToImagePath(filePath);
}catch (Exception e){
log.error("pdfbox转png异常:{}",e);
return Lists.newArrayList();
}finally {
// 删除本地保存的临时文件
FileUtils.deleteQuietly(new File(filePath));
}
}
/**
* 将PDF按页数每页转换成一个jpg图片
* @param pdfFilePath 本地pdf文件路径
* @return 转换后的图片本地地址集合
*/
public static List<String> pdfToImagePath(String pdfFilePath){
List<String> list = new ArrayList<>(16);
String imagePath;
File file = new File(pdfFilePath);
PDDocument doc = null;
try {
File f = new File(toLocalDir);
if(!f.exists()){
f.mkdir();
}
doc = PDDocument.load(file);
PDFRenderer renderer = new PDFRenderer(doc);
int pageCount = doc.getNumberOfPages();
for(int i=0; i<pageCount; i++){
/**
* 方式1,第二个参数是设置缩放比(即像素) renderImageWithDPI(i, 296);
* 方式2,第二个参数是设置缩放比(即像素) 第二个参数越大生成图片分辨率越高,转换时间也就越长
*/
BufferedImage image = renderer.renderImage(i, 1.25f);
imagePath = toLocalDir + "/"+UUIDUtil.create() + ".png";
ImageIO.write(image, "PNG", new File(imagePath));
list.add(imagePath);
}
} catch (IOException e) {
log.error("pdfbox转图片异常:{}",e);
}finally {
if(null!=doc){
try {
// 关闭文件,不然该pdf文件会一直被占用。
doc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return list;
}
}