使用 Apache Poi 输出 docx 中的无限虚假页面

Infinite bogus pages in outpout docx using Apache Poi

所以...基本上我有一个 docx 文件。而且我必须在几个段落中进行一些格式更改,然后保存在一个新文件中。我所做的本质上是跟随。

import scala.collection.JavaConversions._
import org.apache.poi.xwpf.usermodel._

def format( sourceDocumentPath: String, outputDocumentPath: String ) {

  val sourceXWPFDocument = new XWPFDocument( new FileInputStream( sourcePath ) )

  // lets say I have a list of paragraph numbers... I want to format
  val parasToFormat = List( 2, 10, 15, 20 )

  val allParagraphs = sourceXWPFDocument.getParagraphs

  for ( ( paragraph, index ) <- allParagraphs.zipWithIndex ) {
    if( parasToFormat.contains( index ) ) {
      formatParagraph( paragraph )
    }
  }

  val outputDocx = new FileOutputStream( new File( outputDocumentPath ) );
  xwpfDocument.write( outputDocx )
  outputDocx.close()

}

def formatParagraph( paragraph: XWPFParagraph ): Unit = {
  // Do some color changing to few runs
  // Add few runs with new text.
}

大部分情况下一切正常。输出 docx 在我的 Ubuntu.

上的 LibreOffice 中正常打开

但是,当我将此输出 docx 传输到 Windows 系统,并尝试在 MS Word 中打开此输出 docx 时,我得到了无限(不断增长)的垃圾页面。

欢迎Poi社区有识之士踊跃投稿

另外...我的猜测之一是 - 可能是文件中的行结尾混淆了 MS Word。由于 Ubuntu 使用 ( LF - \n ) 行结尾,而 windows 使用 ( CRLF - \r\n )。如果这确实是问题...那么我该如何解决?

尽管...我的代码是在 Scala 中...我认为类似的内容也适用于 Java 代码...大多数 Poi 用户将在 java 社区中.. .所以我也添加了Java标签。

嗯...所以我尝试了各种方法并最终解决了这个问题。

基本上问题是由以下非常简单的事情引起的,

def copyRunFontSizeAttribute( sourceRun: XWPFRun, targetRun: XWPFRun ): Unit = {
  targetRun.setFontSize( sourceRun.getFontSize )
}

不知何故,设置实例 XWPFRun 的字体大小,假设 xWPFRunTargetxWPFRunSource.getFontSize 的 return 值(其中 xWPFRunSource 是另一个XWPFRun 的实例)会导致一些非常奇怪和意外的结果。

所以...目前我删除了我正在执行此操作的所有位 copyRunFontSizeAttribute 解决了问题。