java - PDFBox 程序无法从 pdf 中正确读取非英文字符

标签 java pdfbox pdf-reader

iText 程序替换为 PDFBox 程序来读取 pdf 文件。

            public static void main(String[] args) {  

                // TODO Auto-generated method stub 
                PDDocument     pd;  
                BufferedWriter wr;  

                try {  
                    File input = new File("C:\\test\\ExtractTextFromThis.pdf");    // The PDF file from where you would like to extract  
                    File output = new File("C:\\test\\OutPut.txt");    // The text file where you are going to store the extracted data  

//加载文档。

                    pd = PDDocument.load(input);  // load document
                    pd.setAllSecurityToBeRemoved(true);  

//尝试检查语言

                        System.out.println(pd.getDocumentCatalog().getLanguage());
                        PDFTextStripper stripper = new PDFTextStripper("UTF-8");  // Initializing PDFTextStripper Object with UTF-8 encoding.

       //          PDFTextStripperByArea stripper = new PDFTextStripperByArea("UTF-16");
                    // Please provide example for this. In attached document,I want to extract text from rectangle. There are 30 boxes.

                    wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output)));  
                    stripper.writeText(pd, wr);
                    System.out.println(stripper.getText(pd));  
                    String text = stripper.getText(pd);  
                    char[] cArr = text.toCharArray();  

// Here is the problem. It's not printing characters of Kannada language within its UTF Range. 
//printing chracters -- their integer value --  their Hexadecimal value  
                    for (int i = 1; i < 130; i++) {  
                        System.out.println(cArr[i] + "\t" + (int) cArr[i] + "\t" + Integer.toHexString(cArr[i]));  
                    }  

                    if (pd != null) {  
                        pd.close();  
                    }  

                    wr.close();  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  

最佳答案

您似乎认为 iText 的缺点实际上是您提取页面内容的算法的误解:

您假设内容流中的字符串实际上是 Unicode 编码的。它们不一定是这样,而且通常尤其是非 ASCII 字符也不是这样。翻译信息(如果有的话!)包含在字体字典中。

此外,您假设所有文本字符串都直接包含在内容流中。这不一定是真的:内容流可以引用其他对象,而这些对象又可以包含您的代码找不到的文本。

并且您还假设页面的内容条目是单个间接流。它实际上也可以是它们的数组。

我建议您改用解析器包中 iText 的文本解析类,它会考虑所有这些事情和更多内容。

关于java - PDFBox 程序无法从 pdf 中正确读取非英文字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13162632/

相关文章:

java - pdfbox 按照什么顺序解析 pdf 文件? (假设一页中有超过1列)

android - 渲染/显示和播放嵌入 pdf、Android 的 youtube 视频

php - Google document api iframe 带宽限制

java - 使用java字符串的两个日期语句之间的SQL

java - 我们可以使用 iText/PDFBox 或 java 中的任何其他 PDF 库创建动态 XFA 表单吗?

java - 我可以在 Java 中使用自绑定(bind)泛型和子类化来避免这种未经检查的强制转换吗?

java - 使用java比较两个pdf文件(方法)

java - 如何定位使用jasperreport生成的pdf中的位置来放置签名?

java - 在 IntelliJ 中调试 Web 容器

java - 通用对类