使用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;
}
原文地址:https://www.cnblogs.com/oumae/p/15368623.html