java doc/pdf转图片跑通代码

代码

 @ApiOperation(value="doc/pdf转图片")
    @PostMapping("/docAndPdfToPhoto")
    public CommonResult docAndPdfToPhoto(@RequestBody Request<PdfAndType> request) throws IOException {
    
    
        return cerCertifficateService.docAndPdfToPhoto(request);
    }
 /**
     *   doc/pdf转图片方法
     * @author tujr
     * @createTime 2020/9/10 0010 16:17
     **/

    CommonResult docAndPdfToPhoto(Request<PdfAndType> request) throws IOException;
@Override
    public CommonResult docAndPdfToPhoto(Request<PdfAndType> request) throws IOException {
    
    
        if (request==null){
    
    
            return CommonResult.validateFailed();
        }
        PdfAndType pdfAndType = JSON.parseObject(JSON.toJSONString(request.getData()), PdfAndType.class);
        if (pdfAndType==null||StringUtil.isBlank(pdfAndType.getUrl())||pdfAndType.getType()==null){
    
    
            return CommonResult.validateFailed();
        }
        //默认文件夹
        String tempDir = System.getProperty("java.io.tmpdir");
        String pdfPath =tempDir + "contract" + File.separator + "tempFile.pdf";
        String photoPath =tempDir + "photo" + File.separator;
        File file3 =new File(photoPath);
        //如果文件夹不存在则创建
        if  (!file3 .exists()  && !file3 .isDirectory()) {
    
    
            file3 .mkdir();
        }
            if (pdfAndType.getType()==1) {
    
    
            //word文件
            //将文件转为pdf并存起来
            DocToPdfUtil.doc2pdf(pdfAndType.getUrl(), pdfPath);
            }
            if (pdfAndType.getType()==2){
    
    
                //将文件下载到本地
                DocToPdfUtil.downloadFile(pdfAndType.getUrl(),pdfPath);
            }
            //pdf转图片
            List<PhotoNamePath> photos = DocToPdfUtil.pdfToImage(pdfPath, photoPath);
            //上传
            for (PhotoNamePath photo:photos){
    
    
            //将文件转为MultipartFile
            File file = new File(photo.getFilePath());
            FileInputStream fileInputStream = new FileInputStream(file);
            MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(),
                ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
            CommonResult commonResult = storageObjService.storageObjV1(multipartFile, 1);
            UploadDto uploadDto = JSON.parseObject(JSON.toJSONString(commonResult.getData()), UploadDto.class);
            if (StringUtil.isBlank(uploadDto.getRealPath())){
    
    
            return CommonResult.failed("文件转换失败");
            }
            photo.setFilePath(uploadDto.getRealPath());
            //转换成功后删除临时文件夹里面的文件
            file.delete();
        }
            File file2 = new File(pdfPath);
            file2.delete();

        System.out.println(tempDir);
        return CommonResult.success(photos);
    }


/**
 * doc转pdf
 * @author 
 * @date 2018/8/31 17:29
 */
public class DocToPdfUtil {
    
    
    /**
     * 获取配置文件信息
     *
     * @return boolean
     */
    public static boolean getLicense() {
    
    
        try {
    
    
            InputStream is = FileUtils.class.getClassLoader().getResourceAsStream("License.xml"); //  license.xml应放在..\WebRoot\WEB-INF\classes路径下
            License license = new License();
            license.setLicense(is);
            return true;
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 转换文件流
     *
     *   本地文件地址
     */
    public static String doc2pdf(String inPath, String outPath) {
    
    

        if (getLicense()) {
    
    
            try {
    
    
                long old = System.currentTimeMillis();
                File file = new File(outPath);
                if (!file.getParentFile().exists()) {
    
    
                    file.getParentFile().mkdirs();
                }
                FileOutputStream os = new FileOutputStream(file);
                Document doc = new Document(inPath);                    //Address是将要被转化的word文档
                doc.save(os, SaveFormat.PDF);//支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
                long now = System.currentTimeMillis();
                System.out.println("pdf转换成功,共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
                return outPath;
            } catch (Exception e) {
    
    
                e.printStackTrace();
            }
        } else {
    
    
            System.out.println("转化失败");
            return null;
        }
        return null;
    }

    public static void main(String[] args) {
    
    
//        String outPath = File.separator+"contract"+File.separator+"tempFile.pdf";
//        doc2pdf("http://intern-java-test.oss-cn-shenzhen.aliyuncs.com/20200630/image_path/image/15934922857374813.doc", outPath);
//          pdf2Image("D:\\temp\\2.pdf","D:\\temp",2);
//        List<PhotoNamePath> photoNamePaths = pdfToImage("D:\\temp\\2.pdf", "D:\\temp\\");
//        System.out.println(photoNamePaths);
        String s = downloadFile("http://intern-java-test.oss-cn-shenzhen.aliyuncs.com/20200910/video_path/video/1599732853017616.pdf", "D:\\temp\\temp.pdf");
        System.out.println(s);
    }

    /**
     * @Description: PDF转图片
     * @param:
     * @return:
     * @auther: 
     * @date: 2019/8/20 14:23
     */
    public static List<PhotoNamePath> pdfToImage(String pdfPath, String outPath) {
    
    
        List<PhotoNamePath> list = new ArrayList<>();

        File file = null;
        PDDocument pdDocument = null;
        try {
    
    
            int dpi = 296;
            file = new File(pdfPath);
            pdDocument = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(pdDocument);
            int pageCount = pdDocument.getNumberOfPages();
            /* dpi越大转换后越清晰,相对转换速度越慢 */
            for (int i = 0; i < pageCount; i++) {
    
    
                PhotoNamePath photo = new PhotoNamePath();
                String fileName =i+".png";
                String filePath = outPath + fileName;
                File dstFile = new File(filePath);
                BufferedImage image = renderer.renderImageWithDPI(i, dpi);
                ImageIO.write(image, "png", dstFile);

               photo.setFileName(fileName);
               photo.setFilePath(filePath);
               list.add(photo);
            }
        }catch (Exception e){
    
    
            e.printStackTrace();
        }finally {
    
    
            try {
    
    
                // 这里需要关闭PDDocument,不然如果想要删除pdf文件时会提示文件正在使用,无法删除的情况
                pdDocument.close();
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
        return list;
    }
    /**
     *   下载文件到本地方法
     * @author tujr
     * @createTime 2020/9/11 0011 10:12
     **/

        public static String downloadFile(String remoteFilePath, String localFilePath) {
    
    
            URL urlfile = null;
            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);
                }
                System.out.println("上传成功");
                bos.flush();
                bis.close();
                httpUrl.disconnect();
            } catch (Exception e) {
    
    
                e.printStackTrace();
            } finally {
    
    
                try {
    
    
                    bis.close();
                    bos.close();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
            }
            return localFilePath;
        }
}

依赖

<!--pdf转图片-->
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>fontbox</artifactId>
            <version>2.0.12</version>
        </dependency>
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.1</version>
        </dependency>
        <!--        word转为pdf-->
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-words</artifactId>
            <version>15.8.0</version>
            <classifier>jdk16</classifier>
        </dependency>
<!--        将文件转为MultipartFile-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.7.RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>

我这边是加了一步生成的图片直接上传到阿里云上面的

猜你喜欢

转载自blog.csdn.net/weixin_43285931/article/details/108622280