Insert New Paragraph containing Merge Field above Table & Remove Table from Word DOCX Document using Java

Hi Team,

Please share the code for “insert new Paragraph containing the Merge Field above table and remove table”

Thanks & Regards,
Shyamala B

@Shyamu,

Please ZIP and attach the following resources here for testing:

  • Your simplified input Word document
  • Your expected DOCX file showing the desired output. You can create this document by using MS Word. Please also list the complete steps that you performed in MS Word to create the expected document on your end

As soon as you get these pieces of information ready, we will start investigation into your particular scenario/issue and provide you code to achieve the same by using Aspose.Words for .NET.

Hi Team,

I have removed the table inside the Structured Document Tag (node Type: 28) and inserted the merge field for table Content after this structured document tag.

But, i couldn’t remove the empty SDT from document.

Please share the code logic to remove the SDT Tag and refer the attached sample_input and expected out document along with explanation in sample_input document

Thanks & Regards,
ShyamalaBSample_Document.zip (42.1 KB)

@Shyamu,

You can remove such Content Controls (StructuredDocumentTag) from Word document by using the following code:

Document doc = new Document("C:\\temp\\Sample_Input_Document.docx");

foreach (Field field in doc.Range.Fields)
{
    if (field.Type == FieldType.FieldMergeField)
    {
        Paragraph paragraph = (Paragraph)field.Start.GetAncestor(NodeType.Paragraph);

        StructuredDocumentTag structuredDocumentTag = paragraph.PreviousSibling as StructuredDocumentTag;
        if (structuredDocumentTag != null &&
            structuredDocumentTag.ToString(SaveFormat.Text).Trim().Equals("Click here to enter text."))
        {
            structuredDocumentTag.Remove();
        }
    }
}

doc.Save("C:\\temp\\20.11.docx");

Hi Team,

I have modified the code for java and getting the exception while executing it.

	for (Field field : document.getRange().getFields()) {

		if (field.getType() == FieldType.FIELD_MERGE_FIELD) {
			Paragraph paragraph = (Paragraph) field.getStart().getAncestor(NodeType.PARAGRAPH);
			StructuredDocumentTag strdoctag = (StructuredDocumentTag) paragraph.getPreviousSibling();
			try {
				if (strdoctag != null && strdoctag.toString(SaveFormat.TEXT).equals("Click here to enter text.")) {
					strdoctag.remove();
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

Error Message: Exception: com.aspose.words.Paragraph cannot be cast to com.aspose.words.StructuredDocumentTag

Please check this issue and let me know if i missed anything

Thanks & REgards,
Shyamala B

@Shyamu,

The following code of Aspose.Words for Java API works perfectly fine for the documents you shared earlier (see output awjava-20.11.zip (16.1 KB)).

Document doc = new Document("C:\\temp\\Sample_Document\\Sample_Input_Document.docx");

for (Field field : doc.getRange().getFields()) {
    if (field.getType() == FieldType.FIELD_MERGE_FIELD) {
        Paragraph paragraph = (Paragraph) field.getStart().getAncestor(NodeType.PARAGRAPH);

        StructuredDocumentTag structuredDocumentTag = (StructuredDocumentTag) paragraph.getPreviousSibling();
        if (structuredDocumentTag != null &&
                structuredDocumentTag.toString(SaveFormat.TEXT).trim().equals("Click here to enter text.")) {
            structuredDocumentTag.remove();
        }
    }
}

doc.save("C:\\temp\\Sample_Document\\awjava-20.11.docx");

Are you getting this problem with some other source Word document? If yes, then please ZIP and upload that input Word document here for further testing. We will then investigate the issue on our end and provide you more information.

Hi Team,

I have attached the Zip Folder which contains an expected functionality document, input document and Output document.

Please review it and share the root cause of the issue for "why my code is not working"Sample_Document.zip (128.3 KB)
and solution to fix the issue as mentioned in document.

Thanks in advance !!

@Shyamu,

You can get the desired output by using the following code:

Document doc = new Document("C:\\Sample_Document\\Test_input_document.docx");
DocumentBuilder builder = new DocumentBuilder(doc);

NodeCollection<Table> tablenodes = doc.getChildNodes(NodeType.TABLE, true);
ArrayList sdts_to_be_removed = new ArrayList();
for (Table table : tablenodes) {
    if (table.getFirstRow().getFirstCell().getText() != null) {
        String mergeFieldText = table.getFirstRow().getFirstCell().getText().trim();
        if (mergeFieldText.startsWith("Insert")) {
            StructuredDocumentTag contenControl = (StructuredDocumentTag) table.getAncestor(NodeType.STRUCTURED_DOCUMENT_TAG);
            if (contenControl != null) {
                Paragraph para = new Paragraph(doc);
                contenControl.getParentNode().insertAfter(para, contenControl);
                builder.moveTo(para);
                builder.insertField("MERGEFIELD " + mergeFieldText + " \\* MERGEFORMAT");
                sdts_to_be_removed.add(contenControl);
            }
        }
    }
}

for (int i = 0; i < sdts_to_be_removed.size(); i++)
    ((StructuredDocumentTag) sdts_to_be_removed.get(i)).remove();

doc.save("C:\\Sample_Document\\awjava-20.11.docx");