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

标签 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.
}

在大多数情况下一切正常。输出 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 的返回值(其中 xWPFRunSourceXWPFRun 的另一个实例)会导致一些非常奇怪和意外的结果。

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

关于java - 使用 Apache Poi 输出 docx 中的无限虚假页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29489552/

相关文章:

java - 构建叶图 - 成对的祖先列表(父 - 子)

java - 如何在 Scala 中获取字符串的最后一个元音及其后面的任何单词?

scala - 映射选项中的键/值[映射]

scala - SBT 范围可以用于特定代码块的自定义 libraryDependencies 吗?

java - 由 Apache POI 创建时 excel 文件中的兼容模式

java - 3.13 版中缺少 Apache POI hslf?

java - 使 Apache Poi Word 文件可通过 URL 下载

java - 使用反射替换 java.net.URL URLStreamHandlerFactory 是个好主意吗?

java - 我怎样才能在java中处理声音?

java - 通过查询参数选择 Jersey 方法