Aspose java insertdocument styling issues

Hi, i have a problem with keeping style when inserting a temporary doc into a bookmark

I made a test case for you:
I take the content of a bookmark(source), create a temporary doc. At this point, the style is not correct in the temporary document.
When reinserting into the destination bookmark, i lose the style!
Here in my scenario in source file the document style is Arial 8 but when i tried to replace document data in source it is taking arial 10 as styling and this causing issue.

Since i am unable to upload word documents from my office laptop i am sending files as a pdf format.

source.docx : Source file that contains my bookmarks(The bookmarks which are there in the footer is causing issues. ex : {{termsheet.Disclaimer1_Indicative.docx#!IsFinal}})
source.pdf (9.3 KB)

result.docx : Result that i get after the process

wanted.docx: This is my desired result!

temp.docx: Content of the temporary generated doc file
disclaimer.pdf (2.6 KB)
InsertDocument Logic :

Thank you!
result_document.pdf (46.2 KB)
source.pdf (9.30 KB)
InsertDocument_code.pdf (19.2 KB)
disclaimer.pdf (2.59 KB)
expected_doc.pdf (43.2 KB)

@priyanka9 Unfortunately, it is not possible to test the scenario and reproduce the problem with PDF documents. Could you please zip and attach your source MS word documents here for testing? We will check the issue and provide you more information.

Hi Alex,
Thanks for your reply. Here are the documents which you are expecting.
source.docx :
source.docx (25.5 KB)
disclaimer.docx : Content of the temporary generated doc file
disclaimer.docx (18.0 KB)
result.docx : Result that i get after the process
result_document.docx (32.9 KB)
expected_doc.docx:* This is my desired result!
expected_doc.docx (41.0 KB)

Can you please refer below code for insertdocument logic .
InsertDocumentLogic.docx (16.8 KB)

@priyanka9 Why do not you use a built-in DocumentBuilder.insertDocument method? I have tested with the following simple code and placeholder is properly replaced:

Document doc = new Document("C:\\Temp\\source.docx");
FindReplaceOptions opt = new FindReplaceOptions();
opt.setReplacingCallback(new ReplaceWithDocumentCallback());
doc.getRange().replace("{{ts.PBRiskRating.docx#IsPB}}",  "C:\\Temp\\disclaimer.docx", opt);
doc.save("C:\\Temp\\out.docx");
public class ReplaceWithDocumentCallback implements IReplacingCallback {
    
    /**
     * This method is called by the Aspose.Words find and replace engine for each match.
     */
    @Override
    public int replacing(ReplacingArgs e) throws Exception {
        
        Document doc = (Document)e.getMatchNode().getDocument();
        
        // This is a Run node that contains either the beginning or the complete match.
        Node currentNode = e.getMatchNode();
        
        // 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.getMatchOffset() > 0)
            currentNode = splitRun((Run)currentNode, e.getMatchOffset());
        
        // This array is used to store all nodes of the match for further deleting.
        ArrayList<Run> runs = new ArrayList<Run>();
        
        // Find all runs that contain parts of the match string.
        int remainingLength = e.getMatch().group().length();
        while (
                remainingLength > 0 &&
                        currentNode != null &&
                        currentNode.getText().length() <= remainingLength)
        {
            runs.add((Run)currentNode);
            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.getNextSibling();
            } while (currentNode != null && currentNode.getNodeType() != 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((Run)currentNode);
        }
        
        // Create DocumentBuilder to insert HTML.
        DocumentBuilder builder = new DocumentBuilder(doc);
        // Move builder to the first run.
        builder.moveTo(runs.get(0));
        builder.insertDocument(new Document(e.getReplacement()), ImportFormatMode.KEEP_SOURCE_FORMATTING);
        
        Paragraph currentParagraph = builder.getCurrentParagraph();
        // Delete matched runs
        for (Run run : runs)
            run.remove();
        // Remove current paragraph if it is empty.
        if(!currentParagraph.hasChildNodes())
            currentParagraph.remove();
        
        // Signal to the replace engine to do nothing because we have already done all what we wanted.
        return ReplaceAction.SKIP;
    }
    
    private static Run splitRun(Run run, int position)
    {
        Run afterRun = (Run)run.deepClone(true);
        run.getParentNode().insertAfter(afterRun, run);
        afterRun.setText(run.getText().substring(position));
        run.setText(run.getText().substring(0, position));
        return afterRun;
    }
}

Hi Alex,
The code which i provided for insertDocument if you see we are using built-in DocumentBuilder.insertDocument only and on top of that we added some logic according to our requirements to preserve custom styles for child documents.

@priyanka9 Unfortunately, I cannot run your code since some methods implementation are not provided. If possible please create a simple application that will allow us to reproduce the problem?
Also, please try using the code provided above on your side. As I can see styling is properly preserved and no additional logic is required.

Hi Alex,
Actually when we debug the issue we observed we are getting different paragraph styling name with wrong font size from the parent paragraph of the document (source.doc).
Ex : In the above attached source.doc document in below section the paragraph font style name is arial and size is 8.

But when we are replaing the document in source that time parent paragraph style font size is showing wrong.

Paragraph parentParagraph = (Paragraph) currentNode.getParentNode();
Style paragraphStyle = parentParagraph.getParagraphFormat().getStyle();
Style subParagraphStyle = subDoc.getStyles().addCopy(paragraphStyle);

Can you please let us know why its not taking actual parent paragraph font size while reading the document ?

@priyanka9 Aspose.Words returns current font size specified in the style applied to the paragraph. but you should note that actual font size of the text can be different from font size specified in style, since it can be changed in the node properties itself. If you look at the style properties, you will see font size is 10, but font is explicitly changed to 8:


You can also see this in run properties:

<w:p w:rsidR="00C75E1C" w:rsidRPr="00FE749F" w:rsidP="009A16BB">
	<w:pPr>
		<w:pStyle w:val="Normal0" />
		<w:rPr>
			<w:sz w:val="16" />
			<w:szCs w:val="16" />
		</w:rPr>
	</w:pPr>
	<w:r w:rsidRPr="005608F0">
		<w:rPr>
			<w:sz w:val="16" />
		</w:rPr>
		<w:t xml:space="preserve">* </w:t>
	</w:r>

Ok Thanks Alex for your reply.

Actually somehow we changed the font size of the paragraph text to Arial 8 and we fixed our issue for now.

@priyanka9 IT is perfect that you managed to resolve the problem. Please feel free to ask in case of any issues, we are always glad to help you.