Replace Tables in Word DOCX Document with Merge Fields using Java | Remove Table & Insert New Paragraph with Merge Field

Hi Team,

I am trying to remove a table and replace a Mergefield there at the sama position where the table was present.

Here is the below sample code,

String filePathSDT = "C:\\Users\\wb541348\\Project\\TestDoc.docx";
		InputStream instreamSDT =new FileInputStream(filePathSDT);
		Document doc = new Document(filePathSDT);
		DocumentBuilder builder = new DocumentBuilder(doc);
		
		NodeCollection<Table> tablenodes = doc.getChildNodes(NodeType.TABLE, true);
		
		
		for(Table table : tablenodes) {
			
			builder.moveTo(table.getPreviousSibling());
			table.remove();
			
			builder.insertField("MERGEFIELD " + "Test" + " \\* MERGEFORMAT");
		}
		
		doc.save("C:\\Users\\wb541348\\Project\\Result.docx");

Above code executes properly at times , and it fails at times with Null pointer exception at builder.moveTo(table.getPreviousSibling());

Please let me know how to handle them, What if I dint have a previous sibling and How should I remove the table and replace a MergeField there in those cases.

I mean, I need to remove the table and place a Mergefield exactly at the same position where I removed the Table.
As there is a section break before the table. I am getting a Null pointer exception for the below,
Table.getPreviousSibling();

Basically, I want to move the cursor before the table , and I am not able to do it as there are no node before the table except for a section break. Please find below screenshot.
image.png (3.4 KB)

Thanks,
Prasanna Shanmuganathan

@pshanmuganathan,

The following code should replace the Table with Merge Field (i.e. remove Table and insert new Paragraph at the same place containing the Merge Field):

Document doc = new Document("D:\\temp\\table.docx");
DocumentBuilder builder = new DocumentBuilder(doc);

Paragraph para = new Paragraph(doc);
int i = 0;
for (Table table : (Iterable<Table>) doc.getChildNodes(NodeType.TABLE, true))
{
    Paragraph tempPara = (Paragraph)para.deepClone(false);
    table.getParentNode().insertAfter(tempPara, table);
    builder.moveTo(tempPara);
    builder.insertField("MERGEFIELD " + "Test" + i + " \\* MERGEFORMAT");
    i++;

    table.remove();
}
doc.save("D:\\temp\\awjava-18.11.docx");

A post was split to a new topic: Insert new Paragraph containing the Merge Field above table and remove table