使用pdfbox刪除pdf指定文字內容


1.思路:
  • 使用pdfbox加載出頁面所有的token
  • COSString類型存儲的是文字信息
  • 由於獲取的中文是亂碼,無法直接匹配,
  • 找到要去除的文字對應的亂碼,獲取其字節數組信息,然后據此進行匹配清除
2.添加依賴pdfbox
<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.24</version>
</dependency>

3.代碼

public static void handlePdfBook(String pdfPath) {
    try (PDDocument pdfDocument = PDDocument.load(new File(pdfPath))) {
        //加載PDF文件
        //處理PDF中的每一頁
        for (PDPage page : pdfDocument.getPages()) {
            //解析PDF,找出其中有"xxxx"文字的token也就是COSString元素,找到后把值改掉即可
            PDFStreamParser parser = new PDFStreamParser(page);
            parser.parse();
            List<Object> tokens = parser.getTokens();
            for (Object o : tokens) {
                if (o instanceof COSString) {
                    COSString cs = (COSString) o;
                    byte[] byte1 = cs.toString().getBytes();
                    byte[] byte2 = getTargetByte();
                    // 比較byte[]是否一致,若相同則將當前token設置為空
                    if (Arrays.equals(byte1, byte2)) {
                        cs.setValue(new byte[0]);
                    }
                }
            }
            //將修改后的token要存進page中去,即修改page中原來的tokens
            PDStream updatedStream = new PDStream(pdfDocument);
            OutputStream out = updatedStream.createOutputStream(COSName.FLATE_DECODE);
            ContentStreamWriter tokenWriter = new ContentStreamWriter(out);
            tokenWriter.writeTokens(tokens);
            out.close();
            page.setContents(updatedStream);
        }
        //將修改后的PDF保存
        pdfDocument.save(pdfPath.replace(".pdf", "-修改.dpf"));
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

public static byte[] getTargetByte() {
    // 找一頁容易獲取待清除文字的頁面
    File src = new File("F:\\PDF\\SQL\\頁面1.pdf");
    try (PDDocument pdfDocument = PDDocument.load(src)) {
        PDFStreamParser parser = new PDFStreamParser(pdfDocument.getPage(0));
        parser.parse();
        List<Object> tokens = parser.getTokens();
        for (Object o : tokens) {
            if (o instanceof COSString) {
                COSString cs = (COSString) o;
                // 獲取待清除內容的byte[]
                return cs.toString().getBytes();
            }
        }
    } catch (Exception e) {
        System.out.println(src.getParentFile().getName());
        System.out.println(e.getMessage());
    }
    return null;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM