`package com.haier.hsi.uap.util;

    import com.aliyun.oss.OSS;
    import com.aliyun.oss.model.OSSObject;
    import com.aliyun.oss.model.ObjectMetadata;
    import com.aliyun.oss.model.PutObjectRequest;
    import com.haier.hsi.framework.commons.util.UuidUtil;
    import com.haier.interconn.monitor.StringUtil;

    import io.netty.util.concurrent.DefaultThreadFactory;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.pdfbox.pdmodel.PDDocument;
    import org.apache.pdfbox.rendering.PDFRenderer;
    import org.icepdf.core.exceptions.PDFException;
    import org.icepdf.core.exceptions.PDFSecurityException;
    import org.icepdf.core.pobjects.Document;
    import org.icepdf.core.util.GraphicsRenderingHints;

    import javax.imageio.ImageIO;
    import java.awt.image.BufferedImage;
    import java.io.;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.LinkedBlockingDeque;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.concurrent.TimeUnit;
    *import
    java.util.concurrent.atomic.AtomicInteger;

    /*
    @description:
    * @author:
    *
    @date;
    */
    @Slf4j
    public class PdfToImageUtil {

    1. _/**<br /> * 将pdf转换成图片的线程池<br /> */<br /> _**public static **ThreadPoolExecutor _executor _= **new **ThreadPoolExecutor(10,10,1L, TimeUnit.**_HOURS_**,**new **LinkedBlockingDeque<Runnable>(),**new **DefaultThreadFactory(**"pdf2img-pool"**));

    _// // pdf缓存设置
    // private static MemoryUsageSetting memoryUsageSetting = MemoryUsageSetting.setupMainMemoryOnly(-1);
    //// private static MemoryUsageSetting memoryUsageSetting = MemoryUsageSetting.setupTempFileOnly(1L);

    1. _**public **PdfToImageUtil(){
    2. }
    3. _/**<br /> * 转换后的图片格式<br /> */<br /> _**public static final **String **_IMG_Type _**= **"png"**;
    4. _/**<br /> * DPI越高清晰度越高,转换速度越慢<br /> */<br /> _**public static final **Integer **_DPI _**= 108;
    5. **public static **PDDocument load(**byte**[] fileByte) **throws **IOException {<br /> **return **PDDocument._load_(fileByte);<br /> }
    6. **public static **PDDocument load(InputStream fileByte) **throws **IOException {<br /> **return **PDDocument._load_(fileByte);<br /> }
    7. **public static **List<**byte**[]> pdfToImg(**byte**[] fileByte) **throws **IOException {<br /> PDDocument load = _load_(fileByte);<br /> **return **_pdfToImg_(**_IMG_Type_**,**_DPI_**,load);<br /> }
    8. **public static **List<**byte**[]> pdfToImg(InputStream fileByte) **throws **IOException {<br /> PDDocument load = _load_(fileByte);<br /> **return **_pdfToImg_(**_IMG_Type_**,**_DPI_**,load);<br /> }
    9. **public static **List<**byte**[]> pdfToImg(**int **dpi,**byte**[] fileByte) **throws **IOException {<br /> PDDocument load = _load_(fileByte);<br /> **return **_pdfToImg_(**_IMG_Type_**,dpi,load);<br /> }
    10. **public static **List<**byte**[]> pdfToImg(**int **dpi,InputStream fileByte) **throws **IOException {<br /> PDDocument load = PDDocument._load_(fileByte);<br /> **return **_pdfToImg_(**_IMG_Type_**,dpi,load);<br /> }
    11. **public static **List<**byte**[]> pdfToImg(String type,**int **dpi,**byte**[] fileByte) **throws **IOException {<br /> PDDocument load = _load_(fileByte);<br /> **return **_pdfToImg_(type,dpi,load);<br /> }
    12. **public static **List<**byte**[]> pdfToImg(String type,**int **dpi,InputStream fileByte) **throws **IOException {<br /> PDDocument load = _load_(fileByte);<br /> **return **_pdfToImg_(type,dpi,load);<br /> }
    13. **public static **List<**byte**[]> pdfToImg(String type, **int **dpi, PDDocument load){<br /> List<**byte**[]> res;<br /> AtomicInteger lock = **new **AtomicInteger();<br /> **try **{<br /> PDFRenderer renderer = **new **PDFRenderer(load);<br /> lock.set(load.getNumberOfPages());<br /> res = **new **ArrayList<>();<br /> List<**byte**[]> finalRes = res;<br /> **for **(**int **i = 0; i < load.getNumberOfPages(); i++) {<br /> _// 初始化容器 避免越界异常<br /> _res.add(**null**);<br /> **int **finalI = i;<br /> _executor_.execute(()->{<br /> ByteArrayOutputStream out = **null**;<br /> **try **{<br /> BufferedImage bufferedImage = renderer.renderImageWithDPI(finalI, dpi);<br /> out = **new **ByteArrayOutputStream();<br /> ImageIO._write_(bufferedImage,type,out);<br /> finalRes.set(finalI,out.toByteArray());<br /> } **catch **(Exception e) {<br /> **_log_**.error(**"pdf转图片失败 error is {}"**,e.getMessage());<br /> }**finally **{<br /> **if**(**null **!= out){<br /> **try **{<br /> out.close();<br /> } **catch **(IOException e) {<br /> **_log_**.error(**"字节流关闭异常,error is {}"**,e.getMessage());<br /> }<br /> }<br /> }<br /> lock.getAndAdd(-1);<br /> });<br /> }<br /> } **catch **(Exception e) {<br /> **_log_**.error(**"pdf转图片失败 error is {}"**,e.getMessage());<br /> _// 更改线程标识 返回结果<br /> _lock.set(-1);<br /> res = **null**;<br /> }<br /> _// 自旋锁等所有线程执行完毕<br /> _**for**(;lock.get()>0;){};<br /> _// 关闭pdf流<br /> _**if**(**null**!= load){<br /> **try **{<br /> load.close();<br /> } **catch **(IOException e) {<br /> **_log_**.error(**"关闭pdf流失败,error is {}"**,e.getMessage());<br /> }<br /> }<br /> **return **res;<br /> }
    14. _/**<br /> * 获取oss上pdf文件并转换成pdf后上传到同一目录<br /> * _**_@param __oSSClient _**_目标oss<br /> * _**_@param __bucket _**_桶<br /> * _**_@param __pdfPath _**_相对路径<br /> * _**_@return _**_转换图片的相对路径<br /> */<br /> _**public **List<String> dealAndPushOss(OSS oSSClient, String bucket, String pdfPath) **throws **Exception {<br /> _// 获取pdf流<br /> _**if**(StringUtil._isEmpty_(pdfPath)|| **null **== oSSClient || StringUtil._isEmpty_(bucket)){<br /> **_log_**.error(**"pdf转图片入参不合法,pdf路径 :{} 桶:{}"**,pdfPath,bucket);<br /> _// throw new ResultEnumException(ResultEnum.PARAM_INVALID_2);<br /> _**throw new **Exception();<br /> }<br /> OSSObject ossObject = **null**;<br /> **try **{<br /> ossObject = oSSClient.getObject(bucket, pdfPath);<br /> } **catch **(Exception e) {<br /> **_log_**.error(**"从oss下载文件失败,error is : {}"**,e.getMessage());<br /> }<br /> _// 文件不存在<br /> _**if**(**null **== ossObject){<br /> **_log_**.error(**"路径为:{} 的pdf在oss上不存在"**,pdfPath);<br /> **return null**;<br /> }<br /> InputStream objectContent = ossObject.getObjectContent();
    15. _//准备图片写入变量<br /> _String subStr = pdfPath.substring(0,pdfPath.lastIndexOf(**"."**));<br /> String newStr = subStr.concat(**"-"**);<br /> ObjectMetadata objectMetadata = **new **ObjectMetadata();<br /> objectMetadata.setContentType(**"image/jpg"**);<br /> **int **i = 1;<br /> List<String> paths = **new **ArrayList<>();
    16. **try **{<br /> _//res = pdfToImg(objectContent);<br /> _Document document = **new **Document();<br /> document.setInputStream(objectContent,pdfPath);<br /> _//缩放比例<br /> _**float **scale = 2.5f;<br /> _//旋转角度<br /> _**float **rotation = 0f;
    17. **for **(**int **m = 0; m < document.getNumberOfPages(); m++) {<br /> **int **a = m;<br /> _//开始写图片到oss<br /> _String key = newStr+i+**".png"**;<br /> paths.add(key);<br /> BufferedImage image = **null**;<br /> image = (BufferedImage)<br /> document.getPageImage(a, GraphicsRenderingHints.**_SCREEN_**, org.icepdf.core.pobjects.Page.**_BOUNDARY_CROPBOX_**, rotation, scale);
    18. _executor_.submit(**new **pdfToImgRunnable(m,bucket,key,objectMetadata,oSSClient,image));<br /> i++;
    19. }<br /> document.dispose();
    20. } **catch **(IOException e) {<br /> **_log_**.error(**"pdf 转图片失败 , error is {}"**,e.getMessage());<br /> } **catch **(PDFException e) {<br /> e.printStackTrace();<br /> } **catch **(PDFSecurityException e) {<br /> e.printStackTrace();<br /> } **catch **(InterruptedException e) {<br /> e.printStackTrace();<br /> } **finally **{<br /> **if**(**null **!= objectContent){<br /> **try **{<br /> objectContent.close();<br /> } **catch **(IOException e) {<br /> **_log_**.error(**"oss 文件输入流关闭失败"**);<br /> }<br /> }<br /> }<br /> **return **paths;<br /> }<br /> **class **pdfToImgRunnable **implements **Runnable{
    21. **int a**;<br /> String **bucket**;<br /> String **key**;<br /> ObjectMetadata **objectMetadata**;<br /> OSS **oSSClient**;<br /> BufferedImage **image**;
    22. @Override<br /> **public void **run() {<br /> InputStream in = **null**;
    23. **try **{<br /> _// String fileName = UUIDUtil.getUuid()+"-"+a + "." + "png";<br /> _String fileName = UuidUtil._getUuid_()+**"-"**+**a **+ **"." **+ **"png"**;<br /> File imageFile = **new **File(fileName);<br /> ImageIO._write_(**image**, **"png"**, imageFile);<br /> in = **new **FileInputStream(imageFile);<br /> PutObjectRequest putObjectRequest = **new **PutObjectRequest(**bucket**,**key**,in,**objectMetadata**);<br /> **oSSClient**.putObject(putObjectRequest);<br /> **if**(imageFile.exists()){<br /> imageFile.delete();<br /> }<br /> } **catch **(Exception e) {<br /> **_log_**.error(**"上传图片信息到 {} 失败,error is :{},"**,**key**,e.getMessage());<br /> }**finally **{<br /> **if**(**null **!= in){<br /> **try **{<br /> in.close();<br /> } **catch **(IOException e) {<br /> **_log_**.error(**"pdf转图片后的文件输入流关闭失败"**);<br /> }<br /> }<br /> **if**(**null **!= **image**){<br /> **image**.flush();<br /> }<br /> }<br /> }<br /> **public **pdfToImgRunnable(**int **a,String bucket,String key,ObjectMetadata objectMetadata,OSS oSSClient,BufferedImage image){<br /> **this**.**a **= a;<br /> **this**.**bucket **= bucket;<br /> **this**.**key **= key;<br /> **this**.**objectMetadata **= objectMetadata;<br /> **this**.**oSSClient **= oSSClient;<br /> **this**.**image **= image;<br /> }<br /> }<br />}<br />`

    依赖如果不全 可以参考导包


    <dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.24</version>
    </dependency>
    <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>
    <dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>jbig2-imageio</artifactId>
    <version>3.0.3</version>
    </dependency>

    <dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.13.1</version>
    </dependency>