chendayu 1 rok temu
rodzic
commit
7d49f4ce10

+ 36 - 1
pom.xml

@@ -38,7 +38,42 @@
         <dependency>
             <groupId>org.apache.pdfbox</groupId>
             <artifactId>pdfbox</artifactId>
-            <version>2.0.16</version>
+            <version>2.0.1</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.pdfbox</groupId>
+            <artifactId>fontbox</artifactId>
+            <version>2.0.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.pdfbox</groupId>
+            <artifactId>jempbox</artifactId>
+            <version>1.8.11</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.pdfbox</groupId>
+            <artifactId>xmpbox</artifactId>
+            <version>2.0.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.pdfbox</groupId>
+            <artifactId>preflight</artifactId>
+            <version>2.0.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.pdfbox</groupId>
+            <artifactId>pdfbox-tools</artifactId>
+            <version>2.0.0</version>
+        </dependency>
+        <dependency>
+            <groupId>com.aliyun</groupId>
+            <artifactId>alibaba-dingtalk-service-sdk</artifactId>
+            <version>2.0.0</version>
+        </dependency>
+        <dependency>
+            <groupId>com.aliyun</groupId>
+            <artifactId>dingtalk</artifactId>
+            <version>1.4.78</version>
         </dependency>
     </dependencies>
 

+ 164 - 0
src/main/java/com/test/xiaoshi/test/controller/DingTalk.java

@@ -0,0 +1,164 @@
+package com.test.xiaoshi.test.controller;
+
+import com.aliyun.dingtalkoauth2_1_0.Client;
+import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest;
+import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
+import com.aliyun.teaopenapi.models.Config;
+import com.dingtalk.api.DefaultDingTalkClient;
+import com.dingtalk.api.DingTalkClient;
+import com.dingtalk.api.request.OapiInactiveUserV2GetRequest;
+import com.dingtalk.api.request.OapiUserCountRequest;
+import com.dingtalk.api.request.OapiV2DepartmentListsubRequest;
+import com.dingtalk.api.request.OapiV2UserGetRequest;
+import com.dingtalk.api.response.OapiInactiveUserV2GetResponse;
+import com.dingtalk.api.response.OapiUserCountResponse;
+import com.dingtalk.api.response.OapiV2DepartmentListsubResponse;
+import com.dingtalk.api.response.OapiV2UserGetResponse;
+
+/**
+ * @author chenyu
+ * @date 2023/11/1
+ */
+public class DingTalk {
+    public static void main(String[] args) throws Exception {
+        getDepartmentList();
+    }
+
+    /**
+     * 使用 Token 初始化账号Client,并获取 accessToken
+     *
+     * @throws Exception
+     */
+    public static String getAccessToken() throws Exception {
+        Config config = new Config();
+        config.protocol = "https";
+        config.regionId = "central";
+        Client client = new Client(config);
+        GetAccessTokenRequest getAccessTokenRequest = new GetAccessTokenRequest()
+                .setAppKey("dingil8pgnjfmrpokvrd")
+                .setAppSecret("N74TiI4r0xK1a0GgSh5Qk1H5Kx9jEpxqZdxbe2r0smSWVVM3rkIkBQdPM66KKTGO");
+        GetAccessTokenResponse getAccessTokenResponse = client.getAccessToken(getAccessTokenRequest);
+        String accessToken = getAccessTokenResponse.getBody().getAccessToken();
+        return accessToken;
+    }
+
+    /**
+     * 获取钉钉用户详情(姓名、手机号等)
+     * <p>
+     * 接口返回参数具体含义:https://open.dingtalk.com/document/orgapp/query-user-details
+     */
+    public static void getUserInfo() throws Exception {
+        String accessToken = getAccessToken();
+        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
+        OapiV2UserGetRequest req = new OapiV2UserGetRequest();
+        req.setUserid("065803563336241571");
+        req.setLanguage("zh_CN");
+        OapiV2UserGetResponse rsp = client.execute(req, accessToken);
+        System.out.println(rsp.getBody());
+        /*
+        {
+         "errcode":0,
+         "errmsg":"ok",
+         "result":
+             {
+                "active":true,
+                "admin":false,
+                "avatar":"https:\/\/static-legacy.dingtalk.com\/media\/lADPM4c6GX7cDIfNA2jNA2g_872_872.jpg",
+                "boss":false,
+                "dept_id_list":[1,901655056],
+                "dept_order_list":[{"dept_id":901655056,"order":176220183590297512},{"dept_id":1,"order":176220196009647512}],
+                "email":"",
+                "exclusive_account":false,
+                "hide_mobile":false,
+                "job_number":"",
+                "leader_in_dept":[{"dept_id":1,"leader":false},{"dept_id":901655056,"leader":false}],
+                "mobile":"15862539952",
+                "name":"邢丽霞",
+                "real_authed":true,
+                "remark":"",
+                "senior":false,
+                "state_code":"86",
+                "telephone":"",
+                "title":"",
+                "unionid":"h76iizKPr3AfhWiPLCVNPFgwiEiE",
+                "userid":"065803563336241571",
+                "work_place":""
+             },
+         "request_id":"15so18pd92mee"
+        }
+         */
+    }
+
+    /**
+     * 获取员工人数
+     * <p>
+     * 接口返回参数具体含义:https://open.dingtalk.com/document/orgapp/obtain-the-number-of-employees-v2
+     *
+     * @throws Exception
+     */
+    public static void getUserNum() throws Exception {
+        String accessToken = getAccessToken();
+        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/count");
+        OapiUserCountRequest req = new OapiUserCountRequest();
+        req.setOnlyActive(false);
+        OapiUserCountResponse rsp = client.execute(req, accessToken);
+        System.out.println(rsp.getBody());
+        /*
+        {
+            "errcode":0,
+            "errmsg":"ok",
+            "result":{"count":3},
+            "request_id":"16mqb7cz7c25v"
+        }
+         */
+    }
+
+    /**
+     * 获取部门列表
+     * <p>
+     * 接口返回参数具体含义:https://open.dingtalk.com/document/orgapp/query-the-list-of-department-userids
+     *
+     * @throws Exception
+     */
+    public static void getDepartmentList() throws Exception {
+        String accessToken = getAccessToken();
+        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
+        OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest();
+        req.setDeptId(1L);
+        req.setLanguage("zh_CN");
+        OapiV2DepartmentListsubResponse rsp = client.execute(req, accessToken);
+        System.out.println(rsp.getBody());
+        /*
+        {
+           "errcode":0,
+           "errmsg":"ok",
+           "result":
+               [
+               {"auto_add_user":true,"create_dept_group":true,"dept_id":901330703,"name":"产品研发部门","parent_id":1},
+               {"auto_add_user":true,"create_dept_group":true,"dept_id":901629148,"name":"威世博部门","parent_id":1},
+               {"auto_add_user":true,"create_dept_group":true,"dept_id":901655056,"name":"人事部门","parent_id":1}
+               ],
+           "request_id":"16kg1582mllrk"
+        }
+         */
+    }
+
+    /**
+     * 获取指定日期未登录钉钉的员工
+     *
+     * @throws Exception
+     */
+    public static void getUnloginUserList() throws Exception {
+        String accessToken = getAccessToken();
+        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/inactive/user/v2/get");
+        OapiInactiveUserV2GetRequest req = new OapiInactiveUserV2GetRequest();
+        req.setIsActive(false);
+        req.setDeptIds("1,2,3");
+        req.setOffset(0L);
+        req.setSize(100L);
+        req.setQueryDate("20231025");
+        OapiInactiveUserV2GetResponse rsp = client.execute(req, accessToken);
+        System.out.println(rsp.getBody());
+    }
+
+}

+ 0 - 128
src/main/java/com/test/xiaoshi/test/controller/GetUsersFromDingDing.java

@@ -1,128 +0,0 @@
-package com.test.xiaoshi.test.controller;
-
-import com.alibaba.fastjson2.JSONArray;
-import com.alibaba.fastjson2.JSONObject;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.net.HttpURLConnection;
-import java.net.URL;
-
-/**
- * @author chenyu
- * @date 2023/10/11
- */
-public class GetUsersFromDingDing {
-
-    /**
-     * 获取钉钉的 Access Token
-     * 首先,我们需要获取钉钉的 Access Token,用于后续的 API 调用。(通过发送 HTTP 请求获取 Access Token)
-     * 这段代码中,你需要替换 your_corp_id 和 your_corp_secret 分别为你的企业 ID 和企业密钥
-     */
-    public String getAccessToken() throws IOException {
-        String corpId = "ding54828c9e7edff1a924f2f5cc6abecb85";  //企业id
-        String corpSecret = "cb6c8a2b6a85336c809c81acb2e95b0b";  //企业密钥
-        String url = " + corpId + &corpsecret=" + corpSecret;
-
-        //发送 HTTP 请求获取 Access Token
-        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
-        connection.setRequestMethod("GET");
-        int responseCode = connection.getResponseCode();
-
-        if (responseCode == HttpURLConnection.HTTP_OK) {
-            // 获取响应结果
-            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
-            String inputLine;
-            StringBuffer response = new StringBuffer();
-            while ((inputLine = in.readLine()) != null) {
-                response.append(inputLine);
-            }
-            in.close();
-
-            // 解析响应结果,获取 Access Token
-            JSONObject jsonObject = JSONObject.parseObject(response.toString());
-            String accessToken = jsonObject.getString("access_token");
-            return accessToken;
-
-        } else {
-            // 处理错误情况
-            // ...
-            return null;
-        }
-
-    }
-
-    /**
-     * 获取部门列表
-     * 接下来,我们需要获取钉钉中的部门列表。这可以通过调用钉钉的部门列表 API 来实现。
-     */
-    public void getDepartmentInfo() throws IOException {
-        String accessToken = getAccessToken();
-        String url = "" + accessToken;
-
-        //发送 HTTP 请求获取部门列表
-        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
-        connection.setRequestMethod("GET");
-        int responseCode = connection.getResponseCode();
-
-        if (responseCode == HttpURLConnection.HTTP_OK) {
-            // 获取部门列表
-            BufferedReader departmentIn = new BufferedReader(new InputStreamReader(connection.getInputStream()));
-            String inputLine;
-            StringBuffer response = new StringBuffer();
-            while ((inputLine = departmentIn.readLine()) != null) {
-                response.append(inputLine);
-            }
-            departmentIn.close();
-
-            // 解析部门列表数据
-            JSONObject jsonObject = JSONObject.parseObject(response.toString());
-            JSONArray departmentArr = jsonObject.getJSONArray("department");
-            // 处理部门列表数据
-            // ...
-        } else {
-            // 处理错误情况
-            // ...
-        }
-
-    }
-
-    /**
-     * 获取人员列表
-     * 接下来,我们需要获取钉钉中的人员列表。这可以通过调用钉钉的人员列表 API 来实现。
-     */
-    public void getUserInfo() throws IOException {
-        String accessToken = getAccessToken();
-        Integer departmentId = 0;
-
-        String userUrl = " + accessToken + &department_id=" + departmentId;
-
-        //发送 HTTP 请求获取人员列表
-        HttpURLConnection userConnection = (HttpURLConnection) new URL(userUrl).openConnection();
-        userConnection.setRequestMethod("GET");
-        int userResponseCode = userConnection.getResponseCode();
-
-        if (userResponseCode == HttpURLConnection.HTTP_OK) {
-            // 获取人员列表
-            BufferedReader userIn = new BufferedReader(new InputStreamReader(userConnection.getInputStream()));
-            String userInputLine;
-            StringBuffer response = new StringBuffer();
-            while ((userInputLine = userIn.readLine()) != null) {
-                response.append(userInputLine);
-            }
-            userIn.close();
-
-            // 解析人员列表数据
-            JSONObject jsonObject = JSONObject.parseObject(response.toString());
-            JSONArray userArray = jsonObject.getJSONArray("userlist");
-            // 处理人员列表数据
-            // ...
-        } else {
-            // 处理错误情况
-            // ...
-        }
-
-    }
-
-}

+ 334 - 0
src/main/java/com/test/xiaoshi/test/controller/PdfBoxUtil.java

@@ -0,0 +1,334 @@
+package com.test.xiaoshi.test.controller;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.pdfbox.cos.COSName;
+import org.apache.pdfbox.multipdf.PDFMergerUtility;
+import org.apache.pdfbox.multipdf.Splitter;
+import org.apache.pdfbox.pdmodel.*;
+import org.apache.pdfbox.pdmodel.common.PDRectangle;
+import org.apache.pdfbox.pdmodel.font.PDFont;
+import org.apache.pdfbox.pdmodel.font.PDType0Font;
+import org.apache.pdfbox.pdmodel.graphics.PDXObject;
+import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
+import org.apache.pdfbox.rendering.PDFRenderer;
+import org.apache.pdfbox.text.PDFTextStripper;
+
+import javax.imageio.ImageIO;
+import java.awt.image.BufferedImage;
+import java.io.*;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+public class PdfBoxUtil {
+    public static void main(String args[]) throws IOException {
+        String filePath = "C:\\Users\\Administrator\\Desktop\\1.pdf";
+
+        // 1、读取pdf文件
+//        String content = readPdf(filePath);
+//        System.out.println("读取内容:" + content);
+
+        //2、获取pdf图片
+        getImg(filePath);
+
+        // 3、pdf中插入文字
+//        String inFilePath = "F:\\image_test\\sample.pdf";
+//        String outFilePath = "F:\\image_test\\sample2.pdf";
+//        try {
+//            insertWordContent(inFilePath,outFilePath,1,"插入的小狗文字");
+//        } catch (Exception e) {
+//            e.printStackTrace();
+//        }
+
+        // 4、pdf文件插入图片
+//        String inFilePath = "F:\\image_test\\sample.pdf";
+//        String imagePath = "F:\\image_test\\sun1.jpg";
+//        String outFilePath = "F:\\image_test\\sample3.pdf";
+//        try {
+//            insertImageContent(inFilePath,imagePath,outFilePath,1);
+//        } catch (Exception e) {
+//            e.printStackTrace();
+//        }
+
+        // 5、合并pdf文件
+//        String filePath1 = "F:\\image_test\\sample.pdf";
+//        String filePath2 = "F:\\image_test\\sample2.pdf";
+//        String outFilePath = "F:\\image_test\\sample4.pdf";
+//        List<String> filePathList = new ArrayList<>();
+//        filePathList.add(filePath1);
+//        filePathList.add(filePath2);
+//        try {
+//            mergePdf(filePathList, outFilePath);
+//        } catch (Exception e) {
+//            e.printStackTrace();
+//        }
+
+        // 6、拆分pdf文件
+//        String inFilePath = "F:\\image_test\\sample4.pdf";
+//        String targetPath = "F:\\image_test\\11";
+//        String targetFileName = "aa";
+//        try {
+//            spiltPdf(inFilePath, targetPath, targetFileName);
+//        } catch (Exception e) {
+//            e.printStackTrace();
+//        }
+
+    }
+
+    /**
+     * 读取pdf中文字信息(全部)
+     *
+     * @param inputFile
+     * @return
+     */
+    public static String readPdf(String inputFile) {
+        //创建文档对象
+        PDDocument doc = null;
+        String content = "";
+        try {
+            //加载一个pdf对象
+            doc = PDDocument.load(new File(inputFile));
+            //获取一个PDFTextStripper文本剥离对象
+            PDFTextStripper textStripper = new PDFTextStripper();
+            content = textStripper.getText(doc);
+//            System.out.println("内容:" + content);
+//            System.out.println("全部页数" + doc.getNumberOfPages());
+        } catch (Exception e) {
+            e.printStackTrace();
+        } finally {
+            try {
+                //关闭文档
+                if (doc != null) {
+                    doc.close();
+                }
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+        return content;
+    }
+
+    /**
+     * 插入文字到pdf中
+     *
+     * @param inputFilePath
+     * @param outputFilePath
+     * @param pageNum
+     * @param message
+     * @throws Exception
+     */
+    public static void insertWordContent(String inputFilePath, String outputFilePath, Integer pageNum, String message) throws Exception {
+        File inputPDFFile = new File(inputFilePath);
+        File outputPDFFile = new File(outputFilePath);
+        PDDocument doc = null;
+        try {
+            doc = PDDocument.load(inputPDFFile);
+            PDPageTree allPages = doc.getDocumentCatalog().getPages();
+//            PDFont font = PDType1Font.HELVETICA_BOLD;
+            PDFont font = PDType0Font.load(doc, new File("C:\\Users\\DELL\\Desktop\\FZLTHJW.TTF"));
+            // 字体大小
+            float fontSize = 36.0f;
+            PDPage page = (PDPage) allPages.get(pageNum - 1);
+            PDRectangle pageSize = page.getMediaBox();
+            float stringWidth = font.getStringWidth(message) * fontSize / 1000f;
+            // 计算页面的中心位置
+            int rotation = page.getRotation();
+            boolean rotate = rotation == 90 || rotation == 270;
+            float pageWidth = rotate ? pageSize.getHeight() : pageSize.getWidth();
+            float pageHeight = rotate ? pageSize.getWidth() : pageSize.getHeight();
+            double centeredXPosition = rotate ? pageHeight / 2f : (pageWidth - stringWidth) / 2f;
+            double centeredYPosition = rotate ? (pageWidth - stringWidth) / 2f : pageHeight / 2f;
+            // append the content to the existing stream
+            PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true, true);
+            contentStream.beginText();
+            // 设置字体和字体大小
+            contentStream.setFont(font, fontSize);
+            // 设置字体颜色(如下为红色)
+            contentStream.setNonStrokingColor(255, 0, 0);
+            if (rotate) {
+                // rotate the text according to the page rotation
+                contentStream.setTextRotation(Math.PI / 2, centeredXPosition, centeredYPosition);
+            } else {
+                contentStream.setTextTranslation(centeredXPosition, centeredYPosition);
+            }
+            // 写入文字
+            contentStream.drawString(message);
+            contentStream.endText();
+            contentStream.close();
+            // 保存到新文档中
+            doc.save(outputPDFFile);
+            System.out.println("成功向pdf插入文字");
+        } finally {
+            if (doc != null) {
+                doc.close();
+            }
+        }
+    }
+
+    /**
+     * 在pdf中插入图片
+     *
+     * @param inputFilePath
+     * @param imagePath
+     * @param outputFilePath
+     * @param pageNum
+     * @throws Exception
+     */
+    public static void insertImageContent(String inputFilePath, String imagePath, String outputFilePath, Integer pageNum) throws Exception {
+        File inputPDFFile = new File(inputFilePath);
+        File outputPDFFile = new File(outputFilePath);
+
+        try {
+            PDDocument doc = PDDocument.load(inputPDFFile);
+            PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, doc);
+
+            PDPage page = doc.getPage(0);
+            //注释的这行代码会覆盖原内容,没注释的那行不会覆盖
+//            PDPageContentStream contentStream = new PDPageContentStream(doc, page);
+            PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true, true);
+            contentStream.drawImage(pdImage, 70, 250);
+            contentStream.close();
+            doc.save(outputPDFFile);
+            doc.close();
+            System.out.println("成功插入图片");
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
+
+    /**
+     * 合并pdf文件
+     *
+     * @param pathList
+     * @param targetPDFPath
+     * @throws Exception
+     */
+    public static void mergePdf(List<String> pathList, String targetPDFPath) throws Exception {
+        List<InputStream> inputStreams = new ArrayList<>();
+        for (String path : pathList) {
+            inputStreams.add(new FileInputStream(new File(path)));
+        }
+        PDFMergerUtility mergePdf = new PDFMergerUtility();
+        File file = new File(targetPDFPath);
+
+        if (!file.exists()) {
+            file.delete();
+        }
+
+        mergePdf.addSources(inputStreams);
+        mergePdf.setDestinationFileName(targetPDFPath);
+        mergePdf.mergeDocuments();
+        for (InputStream in : inputStreams) {
+            if (in != null) {
+                in.close();
+            }
+        }
+    }
+
+
+    /**
+     * 将pdf文件分割成多个
+     *
+     * @param sourcePdfPath
+     * @param splitPath
+     * @param splitFileName
+     * @throws Exception
+     */
+    public static void spiltPdf(String sourcePdfPath, String splitPath, String splitFileName) throws Exception {
+        File targetDir = new File(splitPath);
+        if (!targetDir.exists()) {
+            targetDir.mkdirs();
+        }
+        int j = 1;
+        String splitPdf = splitPath + File.separator + splitFileName + "_";
+
+        // Loading an existing PDF document
+        File file = new File(sourcePdfPath);
+        PDDocument document = PDDocument.load(file);
+        // Instantiating Splitter class
+        Splitter splitter = new Splitter();
+        splitter.setStartPage(1);
+        splitter.setSplitAtPage(1);
+        splitter.setEndPage(5);
+        // splitting the pages of a PDF document
+        List<PDDocument> Pages = splitter.split(document);
+        // Creating an iterator
+        Iterator<PDDocument> iterator = Pages.listIterator();
+        // Saving each page as an individual document
+        while (iterator.hasNext()) {
+            PDDocument pd = iterator.next();
+            String pdfName = splitPdf + j++ + ".pdf";
+            pd.save(pdfName);
+        }
+        document.close();
+    }
+
+    public static void getImg(String filePath) throws IOException {
+        PDDocument document = PDDocument.load(new File(filePath));
+        PDPage pdfpage = document.getPage(1);
+        int i = 1;
+        PDResources pdResources = pdfpage.getResources();
+        for (COSName c : pdResources.getXObjectNames()) {
+            PDXObject o = pdResources.getXObject(c);
+            if (o instanceof org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject) {
+                File file = new File(i + ".png");
+                i++;
+                ImageIO.write(((PDImageXObject) o).getImage(), "png", file);
+            }
+        }
+    }
+
+
+    /**
+     * 提取指定PDF页面的图片转换为Base64的List
+     * 注意:图片提取的顺序是PDF创建时图片插入的顺序
+     *
+     * @throws Exception
+     */
+    public static List<String> getImg2(String filePath) {
+        List<String> photos = new ArrayList<>();
+        try (PDDocument document = PDDocument.load(new File(filePath))) {
+            //TODO 下标从0开始,所以-1
+            for (int i = 0; i < document.getNumberOfPages(); i++) {
+                PDPage pdfpage = document.getPage(i);
+                // get resource of pdf
+                PDResources pdResources = pdfpage.getResources();
+                Iterable<COSName> xObjectNames = pdResources.getXObjectNames();
+                Iterator<COSName> iterator = xObjectNames.iterator();
+                while (iterator.hasNext()) {
+                    PDXObject o = pdResources.getXObject(iterator.next());
+                    if (o instanceof PDImageXObject) {
+                        //得到BufferedImage对象
+                        BufferedImage image = ((PDImageXObject) o).getImage();
+                        String base64img = convertimgtoBase64(image);
+                        // 可以打印到本地,查看输出顺序
+                        //String imglocation = "C:\\CER\\AE EMC lab_Report template\\pdf img by page\\";
+                        //File imgfile = new File(imglocation + StringUtil.get32UUID() + ".png");
+                        //ImageIO.write(image, "png", imgfile);
+
+                        photos.add("data:image/jpg;base64," + base64img);
+                    }
+                }
+            }
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return photos;
+    }
+
+    public static String convertimgtoBase64(BufferedImage image) {
+        String png_base64 = "";
+        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
+            ImageIO.write(image, "png", baos);//写入流中
+            byte[] bytes = baos.toByteArray();//转换成字节
+//            png_base64 = new BASE64Encoder().encode(bytes);//jdk1.8写法
+            png_base64 = Base64.encodeBase64String(bytes);//JDK11写法
+//        String png_base64 = Base64.encodeBase64String(bytes).trim();//转换成base64串
+            png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+        return png_base64;
+    }
+
+}

+ 86 - 0
src/main/java/com/test/xiaoshi/test/controller/SaveImagesInPdf.java

@@ -0,0 +1,86 @@
+package com.test.xiaoshi.test.controller;
+
+import org.apache.pdfbox.cos.COSBase;
+import org.apache.pdfbox.cos.COSName;
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.PDPage;
+import org.apache.pdfbox.pdmodel.graphics.PDXObject;
+import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
+import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
+import org.apache.pdfbox.contentstream.operator.Operator;
+import org.apache.pdfbox.contentstream.PDFStreamEngine;
+
+import java.awt.image.BufferedImage;
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+
+import javax.imageio.ImageIO;
+
+/**
+ * This is an example on how to extract images from pdf.
+ */
+public class SaveImagesInPdf extends PDFStreamEngine {
+    /**
+     * Default constructor.
+     *
+     * @throws IOException If there is an error loading text stripper properties.
+     */
+    public SaveImagesInPdf() throws IOException {
+    }
+
+    public int imageNumber = 1;
+
+    /**
+     * @param args The command line arguments.
+     * @throws IOException If there is an error parsing the document.
+     */
+    public static void main(String[] args) throws IOException {
+        PDDocument document = null;
+        String fileName = "C:\\Users\\Administrator\\Desktop\\1.pdf";
+        try {
+            document = PDDocument.load(new File(fileName));
+            SaveImagesInPdf printer = new SaveImagesInPdf();
+            int pageNum = 0;
+            for (PDPage page : document.getPages()) {
+                pageNum++;
+                System.out.println("Processing page: " + pageNum);
+                printer.processPage(page);
+            }
+        } finally {
+            if (document != null) {
+                document.close();
+            }
+        }
+    }
+
+    /**
+     * @param operator The operation to perform.
+     * @param operands The list of arguments.
+     * @throws IOException If there is an error processing the operation.
+     */
+    @Override
+    protected void processOperator(Operator operator, List<COSBase> operands) throws IOException {
+        String operation = operator.getName();
+        if ("Do".equals(operation)) {
+            COSName objectName = (COSName) operands.get(0);
+            PDXObject xobject = getResources().getXObject(objectName);
+            if (xobject instanceof PDImageXObject) {
+                PDImageXObject image = (PDImageXObject) xobject;
+
+                // same image to local
+                BufferedImage bImage = image.getImage();
+                ImageIO.write(bImage, "PNG", new File("image_" + imageNumber + ".png"));
+                System.out.println("Image saved.");
+                imageNumber++;
+
+            } else if (xobject instanceof PDFormXObject) {
+                PDFormXObject form = (PDFormXObject) xobject;
+                showForm(form);
+            }
+        } else {
+            super.processOperator(operator, operands);
+        }
+    }
+
+}