IText7提取pdf页面内容文本,并兼容中文字体,修复提取中文乱码问题

6 篇文章 0 订阅

首先正常情况下的文本提取很简单

maven依赖:

<dependencies>
	<dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itext7-core</artifactId>
        <version>7.2.3</version>
	</dependency>
</dependencies>

主要代码块:

public static void main(String args[]){
    PdfReader pr = new PdfReader(input);
    PdfDocument pd = new PdfDocument(pr);
    LocationTextExtractionStrategy strategy = new LocationTextExtractionStrategy();
    PdfCanvasProcessor parser = new PdfCanvasProcessor(strategy);
    parser.processPageContent(pd.getPage(1));
    String text = strategy.getResultantText();
    System.out.println(text);

}        

如果使用上述代码直接读取的文本,包含了新宋体等字体样式的话,那么文本内容就会乱码,通过查看 PdfCanvasProcessor 类的源码,发现构造有一个重载的构造方法,可以自定义传入IContentOperator,再通过定位IContentOperator对应的additionalContentOperators参数的相关源码,可以发现有一个key为“Tf”,Value为SetTextFontOperator的在里边。

通过debug可以发现,字体是通过这个一对来处理的,那么我们就可以仿照SetTextFontOperator的内容,加上我们自定义字体的逻辑判断,然后通过传入additionalContentOperators参数去覆盖“Tf”对应的SetTextFontOperator来实现;

具体实现如下:

以window的宋体为例

public static void main(String args[]){
    PdfReader pr = new PdfReader(input);
    PdfDocument pd = new PdfDocument(pr);
    LocationTextExtractionStrategy strategy = new LocationTextExtractionStrategy();
    Map<String, IContentOperator> operatorMap = new HashMap<>();
    operatorMap.put("Tf", new LocalTextFontOperator());
    PdfCanvasProcessor parser = new PdfCanvasProcessor(strategy, operatorMap);
    parser.processPageContent(pd.getPage(1));
    String text = strategy.getResultantText();
    System.out.println(text);

}        
private static class LocalTextFontOperator implements IContentOperator{
    private LocalTextFontOperator (){}
    public void invoke(PdfCanvasProcessor processor, PdfLiteral operator, List<PdfObject> operands){
        PdfName fontResourceName = (PdfName) operands.get(0);
        float size = ((PdfNumber) operands.get(1)).floatValue();
        PdfDictionary fontsDictionary = processor.getResources().getResource(PdfName.Font);
        PdfDictionary fontDict = fontsDictionary.getAsDictionary(fontResourceName);
        PdfFont font = processor.getFont(fontDict);
        if(font.getFontProgram().toString().contains("SimSun")){
            font = PdfFontFactory.createFont("C:\\Windows\\Fonts\\simsun.ttc,0", PdfEncodings.IDENTITY_H);
        }
        processor.getGraphicsState().setFont(font);
        processor.getGraphicsState().setFontSize(size);
    }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值