Delete page on basis of condition

Issue.zip (54.1 KB)

Hi,

I need to remove page dynamically on basis of some condition. If table value is not present then need to remove full page. By using below code I can remove node so in result I could see all nodes are removed (only 1 is left
-Dont’ know why) Now I wanted to remove that page as well.

String PageText = "";
LayoutCollector lc = new LayoutCollector(doc);
int pages = lc.GetEndPageIndex(doc.LastSection.Body.LastParagraph);
for (int i = 1; i <= pages; i++)
{
    ArrayList nodes = GetNodesByPage(i, doc);
    foreach (Paragraph para in nodes)
    {
        PageText += para.ToString(SaveFormat.Text).Trim();
    }
    //Empty Page
    if (PageText == "")
    {
        foreach (Node node in nodes)
        {
            node.Remove();
        }
    }
    else if (!PageText.Contains("XSID"))
    {
        foreach (Node node in nodes)
        {
            node.Remove();
        }
    }
    nodes.Clear();
    PageText = "";
}

@dipikawani

Thanks for your inquiry. In your case, we suggest you following solution.

  1. Split the document’s pages into separate documents. Please check PageSplitter utility in Aspose.Words for .NET examples repository at GitHub.
  2. Join the generated documents except the one that you want to delete.

My Aspose version is 8.2. So pageSplitter is not support to it. And Join document function can’t use. As we need to use standard templates

@dipikawani

Thanks for your inquiry. Please note that we do not provide support for older released versions of Aspose.Words. Moreover, we do not provide any fixes or patches for old versions of Aspose products either. All fixes and new features are always added to new versions of our products.

We always encourage our customers to use the latest version of Aspose.Words as it contains newly introduced features, enhancements, and fixes to the issues that were reported earlier.

You can try the following method to join documents. Below code example shows how to manually append the content from one document to the end of another document.

/// <summary>
/// A manual implementation of the Document.AppendDocument function which shows the general 
/// steps of how a document is appended to another.
/// </summary>
/// <param name="dstDoc">The destination document where to append to.</param>
/// <param name="srcDoc">The source document.</param>
/// <param name="mode">The import mode to use when importing content from another document.</param>
public void AppendDocument(Document dstDoc, Document srcDoc, ImportFormatMode mode)
{
    // Loop through all sections in the source document. 
    // Section nodes are immediate children of the Document node so we can just enumerate the Document.
    foreach (Section srcSection in srcDoc)
    {
        // Because we are copying a section from one document to another, 
        // it is required to import the Section node into the destination document.
        // This adjusts any document-specific references to styles, lists, etc.
        //
        // Importing a node creates a copy of the original node, but the copy
        // is ready to be inserted into the destination document.
        Node dstSection = dstDoc.ImportNode(srcSection, true, mode);
        // Now the new section node can be appended to the destination document.
        dstDoc.AppendChild(dstSection);
    }
}

Thanks for reply.
I have Aspose.cell with 8.2.2.0 and Aspose with 15.12.0.0.

Let me know weather I can use PageSplitter or not?

@dipikawani

Thanks for your inquiry. Yes, you can use PageSplitter utility with Aspose.Words 15.12.

image.png (11.6 KB)

I tried to use DocumentPageSplittetr, but may be missing some references. Please let me know which reference should I refer for the same. How to resolved this issue?

@dipikawani

Thanks for your inquiry. We have attached the Visual Studio project of PageSplitter utility with this post for your kind reference. AsposeWordsOldVersion.zip (78.5 KB)

Please add Aspose.Words reference to this project. Hope this helps you.

Thanks for sharing. but its giving error to below line :

lic.SetLicense(@“Aspose.Total.lic”);

@dipikawani

Thanks for your inquiry. Please share the error detail that you are facing. We will then provide you more information about your query.

I got blank page in pageSetter. Not I wanted to delete that particular blank page .

Wto.AgIms.UI.HandleMergeFields.DocumentPageSplitter splitter = new Wto.AgIms.UI.HandleMergeFields.DocumentPageSplitter(doc);
for (int page = 1; page <= doc.PageCount; page++)
{
    Document pageDoc = splitter.GetDocumentOfPage(page);
    //I wanted to delete page here. But I'm not getting page empty as its taking header and footer value as well.    //  pageDoc.RemoveAllChildren();
    pageDoc.Remove();
}

@dipikawani

Thanks for your inquiry. Please try the latest version of Aspose.Words for .NET 18.9.

If you still face problem, please ZIP and attach your input Word document here for testing. We will investigate the issue on our side and provide you more information.

Issue.zip (54.2 KB)

Please let me know how to delete 4th page from attached file by using below statement
Document pageDoc = splitter.GetDocumentOfPage(page);

@dipikawani

Thanks for your inquiry. Unfortunately, the PageSplitter utility does not split the 4th page of the document. We are investigating this issue and will get back to you soon.

I’ m creating document where I’m using dynamic tags in word file filling data in dynamic tags. like below :
<<<table1?>>
<<>>
now I wanted to keep table one on one page and table two another page. (If data for table1/table2 not available, it should not display any blank page).
Please find attachement.

  1. Template (which contain dynamic tags)
  2. Required output Issue.zip (47.6 KB)

@dipikawani

Thanks for your inquiry. In your case, we suggest you following solution.

  1. The <> and <> are in two different paragraphs. If the data for <> and <> is not available, please remove these paragraphs using Node.Remove method.
  2. If the data is available for these tags, please set the value of ParagraphFormat.PageBreakBefore property as true for these two paragraphs.

@dipikawani

dipikawani:

Please let me know how to delete 4th page from attached file by using below statement

Thanks for your patience. Please use the following code example to remove the specific page from the document. Please get the code of “RenderedDocument” in Aspose.Words for .NET examples repository at GitHub.

This code example does the following steps.

  1. Finds the text of the first line of 4th and 5th pages.
  2. Bookmark the content of the 4th page.
  3. Remove the content of bookmark.

Hope this helps you.

int remove_page = 4;
Document doc = new Document(MyDir + "orignal(RefPage4).Docx");
// Create a new RenderedDocument class from a Document object.
RenderedDocument layoutDoc = new RenderedDocument(doc);
//Find the text of first line of page 4
RenderedPage page = layoutDoc.Pages[remove_page - 1];
LayoutCollection<LayoutEntity> lines = page.GetChildEntities(LayoutEntityType.Line, true);
String startTxt = lines[0].Text.Replace("¶\r\n", "");
//Find the text of first line of page 5
page = layoutDoc.Pages[remove_page];
lines = page.GetChildEntities(LayoutEntityType.Line, true);
String endTxt = lines[0].Text.Replace("¶\r\n", "");
//Find the text of page 4 and 5 and bookmark the content of page 4.
FindAndInsertBookmark start = new FindAndInsertBookmark("bookmark", true);
FindAndInsertBookmark end = new FindAndInsertBookmark("bookmark", false);
doc.Range.Replace(startTxt, "", new FindReplaceOptions() { ReplacingCallback = start });
doc.Range.Replace(endTxt, "", new FindReplaceOptions() { ReplacingCallback = end });
//Remove the content of 4th page 
doc.Range.Bookmarks["bookmark"].Text = "";
doc.Save(MyDir + "output.docx");
public class FindAndInsertBookmark : IReplacingCallback
{
    string bmname;
    Boolean isStart;
    DocumentBuilder builder;
    public FindAndInsertBookmark(string bmname, Boolean isStart)
    {
        this.bmname = bmname;
        this.isStart = isStart;
    }

    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
    {
        // This is a Run node that contains either the beginning or the complete match.
        Node currentNode = e.MatchNode;
        if (builder == null)
            builder = new DocumentBuilder((Document)currentNode.Document);
        // The first (and may be the only) run can contain text before the match, 
        // in this case it is necessary to split the run.
        if (e.MatchOffset > 0)
            currentNode = SplitRun((Run)currentNode, e.MatchOffset);
        ArrayList runs = new ArrayList();
        // Find all runs that contain parts of the match string.
        int remainingLength = e.Match.Value.Length;
        while (
            (remainingLength > 0) &&
            (currentNode != null) &&
            (currentNode.GetText().Length <= remainingLength))
        {
            runs.Add(currentNode);
            remainingLength = remainingLength - currentNode.GetText().Length;
            // Select the next Run node. 
            // Have to loop because there could be other nodes such as BookmarkStart etc.
            do
            {
                currentNode = currentNode.NextSibling;
            }
            while ((currentNode != null) && (currentNode.NodeType != NodeType.Run));
        }
        // Split the last run that contains the match if there is any text left.
        if ((currentNode != null) && (remainingLength > 0))
        {
            SplitRun((Run)currentNode, remainingLength);
            runs.Add(currentNode);
        }
        if (isStart)
        {
            Run run = (Run)runs[0];
            run.ParentNode.InsertBefore(new BookmarkStart(run.Document, bmname), run);
        }
        else
        {
            Run run = (Run)runs[0];
            run.ParentNode.InsertBefore(new BookmarkEnd(run.Document, bmname), run);
        }
        // Signal to the replace engine to do nothing because we have already done all what we wanted.
        return ReplaceAction.Skip;
    }

    /// <summary>
    /// Splits text of the specified run into two runs.
    /// Inserts the new run just after the specified run.
    /// </summary>
    private static Run SplitRun(Run run, int position)
    {
        Run afterRun = (Run)run.Clone(true);
        afterRun.Text = run.Text.Substring(position);
        run.Text = run.Text.Substring(0, position);
        run.ParentNode.InsertAfter(afterRun, run);
        return afterRun;
    }
}

Thank you so much for your reply. That’s really appreciated.
Now I wanted to give some font style to header

In design I’m applying (HTML Define format) font like Caption_.
After that in Mail Merge controller Applying below line :

if (PageText.Contains(caption1[0]) || PageText.ToUpper().Contains(caption2[0]))
{
    para.ParagraphFormat.StyleName = "Caption";
}

Still It’s taking Caption_ only.

I wanted caption style-name

@dipikawani

Thanks for your inquiry. Please call Paragraph.ParagraphFormat.ClearFormatting() method before setting the style name.

If you still face the problem, please ZIP and attach your input, output and expected output documents here for our reference. We will investigate the issue and provide you more information on it.

Thanks for reply. This works for me. Now I wanted to apply end line at the end of document. Horizontal alignment must be centre.

if (annex == null)
{
    builder.MoveToDocumentEnd();
    builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
    builder.Writeln(GlobalConstants.Doc_Endline);
}

With above code I can apply end-line at end of document but with no alignment. I want it with centre alignment.
In attachment one file is Original what I’m getting from above code . and one file what I expected.