MS Word customization header story range empty paragraph tag issue RRS feed

  • Question

  • Hi All,

    When I only re size the word document headerStoryRange without inserting any variable(variable is placed into mainTextStoryRange). After customization header shifts down by few pixels due to which the mainTextStoryRange variable also shifts.

    I searched for this and found that code inserts an empty paragraph tag into the header story range.

    Is there any way so that I can remove or prevent the code to insert the blank paragraph into the header story range.

    Please help!

    Thanks in Advance!


    • Moved by CoolDadTx Tuesday, January 21, 2014 3:16 PM Office related
    Tuesday, January 21, 2014 12:00 PM

All replies

  • Hi,

    Which type of project are you developing?

    How do you resize the header story range of a Word document, would you mind sharing the steps or the code to help us to reproduce your issue?

    According to your description, when the header story range of a Word document shifts without inserting any paragraph into its main Text Story Range, the code inserts a blank paragraph tag into the header story range. And you want to present the code from doing that or remove the blank paragraph.

    If I understand correctly, I think the issue may be more related to your Word document and how the code runs. So could you provide the sample document and code to help us troubleshoot?

    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Wednesday, January 22, 2014 5:39 AM
  • Actually we prepare a template word document in that document we place the variables, some times user re size the header of the document manually and upload it to our website. We a logged in user download the document then we replace the variables with the logged in user information.

    I can't add the document or document image, it says that your outlook account is not verified(can you please help in verifying my outlook account).

    Here is the code that i am using :

    private static void searchAndReplaceInStory(Microsoft.Office.Interop.Word.Application app, Microsoft.Office.Interop.Word.Range rngStory, string strSearch, string strReplace, string filePath, string LogoName, ref object linktoFile, ref object SaveWithDoc, float height, float width)
                // Define an object to pass to the API for missing parameters
                object Missing = System.Type.Missing;

                rngStory.Find.Text = strSearch;
                rngStory.Find.Replacement.Text = strReplace;

                if (app.ActiveDocument.Name.Substring(app.ActiveDocument.Name.IndexOf('.'), app.ActiveDocument.Name.Length - app.ActiveDocument.Name.IndexOf('.')).Equals(".doc", StringComparison.OrdinalIgnoreCase))
                    using (Image Img = Image.FromFile(filePath + LogoName))
                    {//Image Img = Image.FromFile(filePath + LogoName);
                        InlineShape i = rngStory.InlineShapes.AddPicture(filePath + LogoName, ref linktoFile, ref SaveWithDoc, ref Missing);
                        if (Img.Width / Img.Height <= 1)
                            i.ScaleWidth = (height - 10) * ((Img.Width / Img.Height) == 0 ? 1 : (Img.Width / Img.Height));
                            i.ScaleHeight = height - 10;

                    rngStory.InlineShapes.AddPicture(filePath + LogoName, ref linktoFile, ref SaveWithDoc, ref Missing);

                rngStory.Find.Wrap = WdFindWrap.wdFindContinue;

                object arg1 = Missing; // Find Pattern
                object arg2 = Missing; //MatchCase
                object arg3 = Missing; //MatchWholeWord
                object arg4 = Missing; //MatchWildcards
                object arg5 = Missing; //MatchSoundsLike
                object arg6 = Missing; //MatchAllWordForms
                object arg7 = Missing; //Forward
                object arg8 = Missing; //Wrap
                object arg9 = Missing; //Format
                object arg10 = Missing; //ReplaceWith
                object arg11 = WdReplace.wdReplaceAll; //Replace
                object arg12 = Missing; //MatchKashida
                object arg13 = Missing; //MatchDiacritics
                object arg14 = Missing; //MatchAlefHamza
                object arg15 = Missing; //MatchControl

                rngStory.Find.Execute(ref arg1, ref arg2, ref arg3, ref arg4, ref arg5, ref arg6, ref arg7, ref arg8, ref arg9, ref arg10, ref arg11, ref arg12, ref arg13, ref arg14, ref arg15);

            // Main routine to find text and replace it,
            public static void FindReplaceAnywhere(Microsoft.Office.Interop.Word.Application app, string findText, string replaceText, string filePath, string LogoName, ref object linktoFile, ref object SaveWithDoc)
                // http://forums.asp.net/p/1501791/3739871.aspx
                var doc = app.ActiveDocument;

                // Fix the skipped blank Header/Footer problem
                //    http://msdn.microsoft.com/en-us/library/aa211923(office.11).aspx
                Microsoft.Office.Interop.Word.WdStoryType lngJunk = doc.Sections[1].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.StoryType;

                // Iterate through all story types in the current document
                foreach (Microsoft.Office.Interop.Word.Range rngStory in doc.StoryRanges)
                    // Iterate through all linked stories
                    var internalRangeStory = rngStory;
                        //searchAndReplaceInStory(internalRangeStory, findText, replaceText, filePath, LogoName, ref linktoFile, ref SaveWithDoc);
                            //   6 , 7 , 8 , 9 , 10 , 11 -- http://msdn.microsoft.com/en-us/library/aa211923(office.11).aspx
                            switch (internalRangeStory.StoryType)
                                case Microsoft.Office.Interop.Word.WdStoryType.wdTextFrameStory:
                                case Microsoft.Office.Interop.Word.WdStoryType.wdMainTextStory:
                                case Microsoft.Office.Interop.Word.WdStoryType.wdEvenPagesHeaderStory: // 6
                                case Microsoft.Office.Interop.Word.WdStoryType.wdPrimaryHeaderStory:   // 7
                                case Microsoft.Office.Interop.Word.WdStoryType.wdEvenPagesFooterStory: // 8
                                case Microsoft.Office.Interop.Word.WdStoryType.wdPrimaryFooterStory:   // 9
                                case Microsoft.Office.Interop.Word.WdStoryType.wdFirstPageHeaderStory: // 10
                                case Microsoft.Office.Interop.Word.WdStoryType.wdFirstPageFooterStory: // 11

                                    if (internalRangeStory.ShapeRange.Count > 0)
                                        foreach (Microsoft.Office.Interop.Word.Shape oShp in internalRangeStory.ShapeRange)
                                            if (oShp.Name.Contains("Text Box") == true && oShp.TextFrame.HasText != 0 && oShp.TextFrame.TextRange.Text.ToLower().Contains(findText.ToLower()))
                                                searchAndReplaceInStory(app, oShp.TextFrame.TextRange, findText, replaceText, filePath, LogoName, ref linktoFile, ref SaveWithDoc, oShp.Height, oShp.Width);
                            // On Error Resume Next
                        // ON ERROR GOTO 0 -- http://www.harding.edu/fmccown/vbnet_csharp_comparison.html

                        // Get next linked story (if any)
                        internalRangeStory = internalRangeStory.NextStoryRange;
                    } while (internalRangeStory != null); // http://www.harding.edu/fmccown/vbnet_csharp_comparison.html

    • Edited by AnilVish Monday, January 27, 2014 8:56 AM
    Monday, January 27, 2014 8:54 AM
  • Hi AnilVish

    If your code queries a Header/Footer in any way - and performing a Find in the StoryRange will do so, then the result is that the Header/Footer Story Range is activated (exists in the document, where before it did not) and it will contain a paragraph mark.

    The paragraph mark will be formatted with the Header or Footer style, which will require that extra amount of space.

    Word is performing as designed.

    Your code would have to avoid addressing the Header/Footer StoryRanges. The object model provides no direct way to determine this. However, assuming the documents are generated in a "standard" way, the following VBA code can tell you if a Header Part is present in the document ZIP package. Any new document that's never had a header definied will NOT contain such a part, so the function returns "0" (otherwise it returns the first location in the string where search string can be found):

    Instr(ActiveDocument.Content.WordOpenXML, "header1.xml")

    The C# equivalent to InStr is Contains, so you'd start with DocumentObject.Content.WordOpenXML.Contains

    Depending on how these documents originate and their history, the above may not be consistent enough. If that's the case, the only thing I can suggest would be to test each StoryRange whether it's a Header/Footer. If it is, check the Range.Text.Length. If that is > 1 then the Header/Footer contains content (besides the paragraph mark). If it's <=1 then you have an "empty" Header/Footer and the problem you want to avoid. In this case, try formatting the text with a font size of 1 and make sure there's no SpaceBefore or SpaceAfter paragraph formatting. OR you can format the Range.Font.Visible = 0 (false). 

    That should make the resizing minimal, but you need to be aware this could cause problems for the user if they later want to insert a Header or Footer.

    Please note that an alternate approach would be to leverage the Office Open XML file format directly, possibly using the Open XML SDK. In this manner you would avoid running into any of Word automatisms - no chance of a Header/Footer being added automatically. But you'd also probably want an alternative to Find/Replace - some kind of "marker" rather than text.

    Cindy Meister, VSTO/Word MVP, my blog

    Monday, January 27, 2014 4:27 PM
  • Hi,

    The solutions that you have suggested is not working when i use the code "Range.Text.Length. If that is > 1", then too it iterates through the header and footer story ranges.

    For another solution that you have provided "Range.Font.Visible = 0", there is no such property to set the visibility.

    Please suggest me any other solution for this!

    Thanks in Advance!

    Wednesday, February 12, 2014 11:20 AM
  • Sorry, Range.Font.Hidden = true

    And I did suggest another approach in my previous reply...

    Cindy Meister, VSTO/Word MVP, my blog

    Wednesday, February 12, 2014 6:48 PM