locked
Line break always replace with br RRS feed

  • Question

  • User1487175000 posted

    Hi,

    I am trying to update mergefield in the word document. Value to replace is string and i am add newline in the string.

    When user download the file newline always replace with br. However i want to carriage return instead of br.

    I tried \n, \r\n as well but same result.

                    string replacement = string.Empty;
                    if (replacementList.Count > 0)
                    {
                        foreach (System.Web.UI.WebControls.ListItem item in replacementList)
                        {
                            if (Convert.ToInt32(item.Value) > 0)
                            {
                                replacement += (item.Value + "   " + item.Text) + Environment.NewLine;
                            }
                        }
                    }
                    t.Text = replacement;

    OutPut:
    2   Gluten</br>3   Vegan</br>2   Fisk allergi</br>3   Mjölkprotein</br>

    OutPut should be like this
    2   Gluten
    3   Vegan
    2   Fisk allergi
    3   Mjölkprotein

    Monday, September 9, 2019 9:02 PM

Answers

  • User1487175000 posted

    Hi,

    Thanks i posted my question at word forum as well. But that forum is not so much active.

    Howerver i find how to add line break in the word through code. I should use Break() method to add line break in the string.

    I am new to openXml SDK and currently its very hard for me to udnerstand how the Run are working.  

    Object Text t in my code i get its parent and append with dynamic Text and Break. Its inserted my text.  That means i did not update mergeField i add my Text to mergField parent.

    So i have mergeField and my dynamic text together.  I only want dynamic text not mergeField because user will thing what is that. 

    So i udpated mergeField Text with empty string to not show in the file :)

        private void ReplaceMergeFieldLunchRooms(IEnumerable<FieldCode> fields, string mergeFieldName, List<System.Web.UI.WebControls.ListItem> lunchRoomList)
        {
            try
            {
                var field = fields
                    .Where(f => f.InnerText.Contains(mergeFieldName))
                    .FirstOrDefault();
    
                if (field != null)
                {
                    // Get the Run that contains our FieldCode
                    // Then get the parent container of this Run
                    Run rFldCode = (Run)field.Parent;
    
                    // Get the three (3) other Runs that make up our merge field
                    Run rBegin = rFldCode.PreviousSibling<Run>();
                    Run rSep = rFldCode.NextSibling<Run>();
                    Run rText = rSep.NextSibling<Run>();
                    Run rEnd = rText.NextSibling<Run>();
    
                    // Get the Run that holds the Text element for our merge field
                    // Get the Text element and replace the text content 
                    Text t = rText.GetFirstChild<Text>();
                    t.Text = string.Empty;
                    if (lunchRoomList.Count > 0)
                    {
                        foreach (System.Web.UI.WebControls.ListItem item in lunchRoomList)
                        {
                            t.Parent.Append(new Text(item.Text));
                            t.Parent.Append(new Break());
                        }
                    }
    
                    // Remove all the four (4) Runs for our merge field
                    rFldCode.Remove();
                    rBegin.Remove();
                    rSep.Remove();
                    rEnd.Remove();
                }
            }
            catch (Exception exc)
            {
                log.Error(userName + ": Exception in preparePrintDocument ReplaceMergeFieldWithText: " + exc.Message);
                log.Error(userName + ": Exception in preparePrintDocument ReplaceMergeFieldWithText: " + exc.StackTrace);
                throw new Exception(exc.Message);
            }
        }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, September 11, 2019 8:37 PM

All replies

  • User475983607 posted

    Most likely the item.Text has the the <br />.   Have you tried setting a break point and verifying the data and the code?  Secondly, this is an ASP.NET forum not MS Word.  Are you trying to build a Word document using HTML markup?

    Monday, September 9, 2019 10:46 PM
  • User288213138 posted

    Hi Shahid Majeed,

    if (replacementList.Count > 0)
                    {
                        foreach (System.Web.UI.WebControls.ListItem item in replacementList)

    According to the code you posted, I cannot reproduce your problem.

    can you tell me what method do you use to read word document? and what's a replacementList?

    please post more details code about your question.

    Best regards,

    Sam

    Tuesday, September 10, 2019 5:32 AM
  • User1487175000 posted

    Hi,

    Here is my complete method, where i create new document from template document and then update mergeField in newly created document.

    Strange behaviour i notice: When i file downloaded and open then file shows <br> however i close the file and go to download path and open the file from there then i did not see <br> in the file instead <br> i see white space. Still no line break.

        private void setupDocument()
        {
            try
            {
                string documentLanguage = language.Equals("English") ? "English" : "Swedish";
                docName = "~/Media/bookingDocs/" + documentLanguage + "_Doc_" + bookingID + ".docx";
                string generatedFile = HttpContext.Current.Server.MapPath(docName);
                File.Copy(getTemplateFilePath(), generatedFile, true);
                Dictionary<string, string> keyValues = new Dictionary<string, string>();
                keyValues.Add("MainRoomName", doc.MainRoom);
                keyValues.Add("LunchRoomName", doc.LunchRoomName);
                keyValues.Add("BookingStartEndTime", doc.BookingTime);
                keyValues.Add("TotalGuest", doc.TotalGuest);
                keyValues.Add("BreakfastServingTime", doc.BreakfastServingTime);
                keyValues.Add("LunchServingTime", doc.LunchServingTime);
                keyValues.Add("CoffeServingTime", doc.CoffeServingTime);
                keyValues.Add("CompanyName", doc.CompanyName);
    
                using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(generatedFile, true))
                {
                    var mergeFields = wordDoc.MainDocumentPart.RootElement.Descendants<FieldCode>();
                    foreach (KeyValuePair<string, string> keys in keyValues)
                    {
                        ReplaceMergeFieldWithText(mergeFields, keys.Key, keys.Value);
                    }
    
                    // update mergeField for specialFood 
                    ReplaceMergeFieldWithText(mergeFields, "BookingSpecialFoodList", doc.ListOfSpecialFood);
    
                    wordDoc.MainDocumentPart.Document.Save();
                }
            }
            catch (Exception exc)
            {
                log.Error(userName + ": Exception in preparePrintDocument setupDocument: " + exc.Message);
                log.Error(userName + ": Exception in preparePrintDocument setupDocument: " + exc.StackTrace);
                throw new Exception(exc.Message);
            }
        }
        private void ReplaceMergeFieldWithText(IEnumerable<FieldCode> fields, string mergeFieldName, List<System.Web.UI.WebControls.ListItem> replacementList)
        {
            try
            {
                var field = fields
                    .Where(f => f.InnerText.Contains(mergeFieldName))
                    .FirstOrDefault();
    
                if (field != null)
                {
                    // Get the Run that contains our FieldCode
                    // Then get the parent container of this Run
                    Run rFldCode = (Run)field.Parent;
    
                    // Get the three (3) other Runs that make up our merge field
                    Run rBegin = rFldCode.PreviousSibling<Run>();
                    Run rSep = rFldCode.NextSibling<Run>();
                    Run rText = rSep.NextSibling<Run>();
                    Run rEnd = rText.NextSibling<Run>();
    
                    // Get the Run that holds the Text element for our merge field
                    // Get the Text element and replace the text content 
                    Text t = rText.GetFirstChild<Text>();
                    string replacement = string.Empty;
                    if (replacementList.Count > 0)
                    {
                        foreach (System.Web.UI.WebControls.ListItem item in replacementList)
                        {
                            if (Convert.ToInt32(item.Value) > 0)
                            {
                                replacement += (item.Value + "   " + item.Text) + Environment.NewLine;
                            }
                        }
                    }
                    t.Text = replacement;
    
                    // Remove all the four (4) Runs for our merge field
                    rFldCode.Remove();
                    rBegin.Remove();
                    rSep.Remove();
                    rEnd.Remove();
                }
            }
            catch (Exception exc)
            {
                log.Error(userName + ": Exception in preparePrintDocument ReplaceMergeFieldWithText: " + exc.Message);
                log.Error(userName + ": Exception in preparePrintDocument ReplaceMergeFieldWithText: " + exc.StackTrace);
                throw new Exception(exc.Message);
            }
        }

    Tuesday, September 10, 2019 2:44 PM
  • User288213138 posted

    Hi Shahid Majeed,

    please try below code:

    foreach (System.Web.UI.WebControls.ListItem item in replacementList)
                    {
                        if (Convert.ToInt32(item.Value) > 0)
                        {
                            StringBuilder sb = new StringBuilder();
                            sb.Append(item.Value+" "+item.Text);
                            sb.Append(Environment.NewLine);                      
                            replacement += sb;                        
                        }
                    }

    About mergefield , I suggest you post question in Microsoft Office Forums

    Best regards,

    Sam

    Wednesday, September 11, 2019 9:21 AM
  • User1487175000 posted

    Hi,

    Thanks i posted my question at word forum as well. But that forum is not so much active.

    Howerver i find how to add line break in the word through code. I should use Break() method to add line break in the string.

    I am new to openXml SDK and currently its very hard for me to udnerstand how the Run are working.  

    Object Text t in my code i get its parent and append with dynamic Text and Break. Its inserted my text.  That means i did not update mergeField i add my Text to mergField parent.

    So i have mergeField and my dynamic text together.  I only want dynamic text not mergeField because user will thing what is that. 

    So i udpated mergeField Text with empty string to not show in the file :)

        private void ReplaceMergeFieldLunchRooms(IEnumerable<FieldCode> fields, string mergeFieldName, List<System.Web.UI.WebControls.ListItem> lunchRoomList)
        {
            try
            {
                var field = fields
                    .Where(f => f.InnerText.Contains(mergeFieldName))
                    .FirstOrDefault();
    
                if (field != null)
                {
                    // Get the Run that contains our FieldCode
                    // Then get the parent container of this Run
                    Run rFldCode = (Run)field.Parent;
    
                    // Get the three (3) other Runs that make up our merge field
                    Run rBegin = rFldCode.PreviousSibling<Run>();
                    Run rSep = rFldCode.NextSibling<Run>();
                    Run rText = rSep.NextSibling<Run>();
                    Run rEnd = rText.NextSibling<Run>();
    
                    // Get the Run that holds the Text element for our merge field
                    // Get the Text element and replace the text content 
                    Text t = rText.GetFirstChild<Text>();
                    t.Text = string.Empty;
                    if (lunchRoomList.Count > 0)
                    {
                        foreach (System.Web.UI.WebControls.ListItem item in lunchRoomList)
                        {
                            t.Parent.Append(new Text(item.Text));
                            t.Parent.Append(new Break());
                        }
                    }
    
                    // Remove all the four (4) Runs for our merge field
                    rFldCode.Remove();
                    rBegin.Remove();
                    rSep.Remove();
                    rEnd.Remove();
                }
            }
            catch (Exception exc)
            {
                log.Error(userName + ": Exception in preparePrintDocument ReplaceMergeFieldWithText: " + exc.Message);
                log.Error(userName + ": Exception in preparePrintDocument ReplaceMergeFieldWithText: " + exc.StackTrace);
                throw new Exception(exc.Message);
            }
        }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, September 11, 2019 8:37 PM