【问题标题】:How to remove a page break?如何删除分页符?
【发布时间】:2023-04-09 08:20:01
【问题描述】:

我有这个简化的代码,它使用 com.aspose.words.DocumentBuilder 从不同的 word 文件创建一个大文档。

for (Document contentDocument : documents) {
    ...
    builder.insertDocument(contentDocument, ImportFormatMode.KEEP_SOURCE_FORMATTING);
    builder.insertBreak(BreakType.PAGE_BREAK);
}

在每个文档之后插入一个分页符。

有没有办法去掉最后一个分页符?

【问题讨论】:

  • 为什么不使用基于索引的 for 并跳过最后一个文档?
  • 是的,我正在考虑这个问题,但不确定我的代码最终会如何。也许循环会改变,或者“插入”部分会以一个单独的方法结束......只是认为这可能是另一个解决方案,只是删除最后一个分页符。

标签: java aspose aspose.words


【解决方案1】:

您可以使用旧版本的循环进行循环。 这里我假设文档是一个列表。

for (int i = 0; i < documents.size(); i++) {
    Document contentDocument = documents.get(i);
    builder.insertDocument(contentDocument, ImportFormatMode.KEEP_SOURCE_FORMATTING);

    if (i < documents.size() - 1) {
         builder.insertBreak(BreakType.PAGE_BREAK);
    }
}

【讨论】:

    【解决方案2】:

    我更喜欢使用 POI,但看看this

    注意以下部分

     private static void removeSectionBreaks(Document doc) throws Exception
    {
        // Loop through all sections starting from the section that precedes the last one
        // and moving to the first section.
        for (int i = doc.getSections().getCount() - 2; i >= 0; i--)
        {
            // Copy the content of the current section to the beginning of the last section.
            doc.getLastSection().prependContent(doc.getSections().get(i));
            // Remove the copied section.
            doc.getSections().get(i).remove();
        }
    }
    

    【讨论】:

      【解决方案3】:

      不会是这样的:

      for (int i=0; i< documents.length; i++) {
          ...
          builder.insertDocument(documents[i], ImportFormatMode.KEEP_SOURCE_FORMATTING);
          if (i == documents.length - 1) {
             continue;
          } 
          builder.insertBreak(BreakType.PAGE_BREAK);
      }
      

      工作?或者避免在每次迭代时进行检查:

      for (int i=0; i< documents.length -1; i++) {
          ...
          builder.insertDocument(documents[i], ImportFormatMode.KEEP_SOURCE_FORMATTING);
          builder.insertBreak(BreakType.PAGE_BREAK);
      }
      builder.insertDocument(documents[documents.length - 1], ImportFormatMode.KEEP_SOURCE_FORMATTING);
      

      提供的解决方案假定documents 是一个数组。

      【讨论】:

        【解决方案4】:

        您可以使用以下代码删除文档的最后一个分页符:

                var doc = new Aspose.Words.Document();
                //last page break in document
                var run = doc.GetChildNodes(NodeType.Run, true)
                        .Cast<Run>().Where(obj => obj.Text.Contains(ControlChar.PageBreak)).LastOrDefault();
                   //Replace Page break chracter with empty string
                    run.Text = run.Text.Replace("" + ControlChar.PageBreak, " ");
        

        【讨论】:

          猜你喜欢
          • 2013-09-03
          • 1970-01-01
          • 1970-01-01
          • 2020-10-14
          • 1970-01-01
          • 2021-02-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多