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

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

maven依赖:


	
        com.itextpdf
        itext7-core
        7.2.3
	

主要代码块:

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 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 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);
    }
}

你可能感兴趣的:(iText,pdf,pdf,java,后端)