java - Apache POI 镜像阿拉伯语单词

标签 java apache-poi arabic arabic-support

我正在用 java 开发一个阿拉伯语 OCR 应用程序,它提取图像中的阿拉伯语文本,然后将文本保存到 Microsoft Word 文件中,为此我使用 Apache-POI 库。

我的问题是,当我提取一些文本时,单词的顺序很好,但是当我将其保存在 Word 文件中时,单词的顺序有点困惑,看起来是镜像的

例如: Extracting

但是将其保存为 Word 后:

这是保存Word文件的代码:

public class SavingStringAsWordDoc {


    File f=theGUI.toBeSavedWord;

    public void saveAsWorddd (){
        String st=TesseractPerformer.toBeShown;

        try(FileOutputStream fout=new FileOutputStream(f);XWPFDocument docfile=new XWPFDocument()){

            XWPFParagraph paraTit=docfile.createParagraph();
            paraTit.setAlignment(ParagraphAlignment.LEFT);
            XWPFRun paraTitRun=paraTit.createRun();
            paraTitRun.setBold(true);
            paraTitRun.setFontSize(15);
            paraTit.setAlignment(ParagraphAlignment.RIGHT);
            docfile.createParagraph().createRun().setText(st);  //content to be written
            docfile.write(fout); //adding to output stream
        } catch(IOException e){
            System.out.println("IO ERROR:"+e);
        }
    }

我注意到一件事可能有助于理解这个问题: 如果我复制Word文件中的困惑文本,然后通过选择“仅保留文本”粘贴选项来粘贴它,它会修复段落的顺序 enter image description here

最佳答案

这需要双向文本方向支持(bidi),并且默认情况下在 apache poi 的 XWPF 中尚未实现。但底层对象 org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr 支持这一点。因此,我们必须从 XWPFParagraph 获取这个底层对象,然后设置 Bidi 开启。

示例:

import java.io.File;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STOnOff;

public class CreateWord {

 public static void main(String[] args) throws Exception {

  String content = Files.readString(new File("ArabicTextFile.txt").toPath(), StandardCharsets.UTF_16);

  XWPFDocument document = new XWPFDocument();

  XWPFParagraph paragraph = document.createParagraph();

  // set bidirectional text support on
  CTP ctp = paragraph.getCTP();
  CTPPr ctppr = ctp.getPPr();
  if (ctppr == null) ctppr = ctp.addNewPPr();
  ctppr.addNewBidi().setVal(STOnOff.ON);

  XWPFRun run=paragraph.createRun(); 
  run.setBold(true);
  run.setFontSize(22);
  run.setText(content);

  FileOutputStream out = new FileOutputStream("CreateWord.docx");
  document.write(out);
  out.close();
  document.close();

 }
}

我的ArabicTextFile.txt包含文本

我的世界,我的世界,我的世界

采用 UTF-16 编码 (Unicode)。

Word 中的结果:

enter image description here

关于java - Apache POI 镜像阿拉伯语单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57850543/

相关文章:

drupal - 用于阿拉伯语 PDF 的 Solr

java - Primefaces 日历 - 使用 EL 禁用特定日期

java - 在 Spring Autowiring 时指定 map 的键

objective-c - JObjC.jar 是做什么用的?

java - 从给定纬度和经度的固定距离生成随机地理点

java - 如何一次导出/生成两个文件?

java - 强制只读 Apache POI 中的第一张表

php - 验证阿拉伯语和英语输入字段

html - 在上下文字符上应用样式会破坏单词

使用 apache poi 3.9 的 Java 程序在 XML 构建文件中遇到错误