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

Sar*_*ngh 11 java scala 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.
}
Run Code Online (Sandbox Code Playgroud)

在大多数情况下,一切都很好.输出docx在我的Ubuntu上的LibreOffice中打开了.

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

任何来自Poi社区的智者的猜测都是值得欢迎的.

另外......我的一个猜测是 - 可能是文件中的行结尾让MS Word感到困惑.因为Ubuntu使用(LF - \n)行结尾而Windows使用(CRLF - \r\n).如果这实际上是问题......那么我该如何解决呢?

虽然......我的代码在Scala中...我认为类似的应该也适用于Java代码...而且大多数Poi用户都将在java社区......所以我也在添加Java标签.

Sar*_*ngh 3

嗯……所以我尝试了各种方法,终于解决了这个问题。

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

def copyRunFontSizeAttribute( sourceRun: XWPFRun, targetRun: XWPFRun ): Unit = {
  targetRun.setFontSize( sourceRun.getFontSize )
}
Run Code Online (Sandbox Code Playgroud)

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

所以...目前我删除了所有我正在做的copyRunFontSizeAttribute事情解决了问题的部分。