DocX icon indicating copy to clipboard operation
DocX copied to clipboard

keep format

Open helmbrandt opened this issue 6 months ago • 3 comments

im using docX to replace strings in documents, but the formatting (size, font)of the original text string is not kept, why is that

helmbrandt avatar Jun 20 '25 09:06 helmbrandt

the docx properies can descript the size and font and others.you can do it by yourself

quliting avatar Jun 24 '25 02:06 quliting

Hello

We were not able to reproduce the issue you described using the latest DocX release.

If we load this document for example : Document.docx, we can find and replace placeholders like [LOCATION] using two methods:

  • One using a regex-based function handler (ReplaceTextHandlerFunc).
  • One using explicit string matching with StringReplaceTextOptions.

And the placeholders formatting that uses "Avenir Next LT Pro Demi" font name with 16 font size and bold is always kept.

Here's our code snippet :

// Dictionary holding placeholder keys and their replacement values
private static Dictionary<string, string> m_replacePatterns = new Dictionary<string, string>()
{
    { "LOCATION", "the old market square" },
    { "CHARACTER_NAME", "Elena" },
    { "OBJECT", "compass" },
    { "COLOR", "emerald green" },
    { "WEATHER", "fog" },
    { "CITY_NAME", "Virelia" }
};

public static void TextActions()
{
    Console.WriteLine("\tTextActions()");

    // Load the existing Word document from the specified directory
    using (var document = DocX.Load(ParagraphSample.ParagraphSampleResourcesDirectory + @"Document.docx"))
    {
        // Configure replacement options using a regex pattern for placeholders like [PLACEHOLDER]
        var functionReplaceTextOptions = new FunctionReplaceTextOptions()
        {
            FindPattern = @"\[(.*?)\]", // Match [PLACEHOLDER]
            RegexMatchHandler = ParagraphSample.ReplaceTextHandlerFunc, // Callback to get replacement text
            RegExOptions = RegexOptions.IgnoreCase // Case-insensitive matching
        };

        // Get the first paragraph of the document (original source for cloning)
        var p = document.Paragraphs?.FirstOrDefault();

        // Add spacing and insert a clone of the paragraph for a second replacement approach
        document.InsertParagraph().SpacingAfter(100);
        var p2 = document.InsertParagraph(p);

        // Apply placeholder replacement using the regex-based handler on the first paragraph
        p.ReplaceText(functionReplaceTextOptions);

        // Apply direct string replacement for each key on the cloned paragraph
        foreach (var pair in m_replacePatterns)
        {
            var stringReplaceTextOptions = new StringReplaceTextOptions()
            {
                SearchValue = $"[{pair.Key}]",
                NewValue = pair.Value
            };

            p2.ReplaceText(stringReplaceTextOptions);
        }

        // Save the modified document to the output directory
        document.SaveAs(ParagraphSample.ParagraphSampleOutputDirectory + @"Document_Updated.docx");

        Console.WriteLine("\tCreated: Document_Updated.docx\n");
    }
}

// Callback function for regex match replacement.
// Receives the placeholder key (e.g., "LOCATION") and returns its replacement value if found.
private static string ReplaceTextHandlerFunc(string findStr)
{
    if (m_replacePatterns.ContainsKey(findStr))
    {
        return m_replacePatterns[findStr];
    }

    // If the placeholder isn't found in the dictionary, return it unchanged
    return findStr;
}

Input :

Image

Output :

Image

If the issue persists on your end, please attach a repro sample here and we will investiguate further.

-Thank you

Evance-XceedDev avatar Jun 27 '25 13:06 Evance-XceedDev

i dont know what happened but it seems to be a problem with my docx files, all new docx files work

helmbrandt avatar Jul 01 '25 16:07 helmbrandt