none
Automating Word - Inserting and Resizing a Header Image RRS feed

  • Question

  • Using VB.Net 2010 (Pro) to create a Word 20xx doc file.

    My company has changed logos for the new year, so I have to modify the VB.Net app to insert the new logo where the old one was.  The problem is the two image files are different sizes.  To make the new logo match the same height as the old (so the page formatting will remain the same).  

    Here's my original (working) code:

    With m_oDoc.Sections(1).Headers(Word_WdHeaderFooterIndex_wdHeaderFooterFirstPage).Range
        .InlineShapes.AddPicture(sLogoFilePathName)
    End With 
    
    


    The new code, based on woking code elsewhere in my app that modifies image size though not in the header:

    With m_oDoc.Sections(1).Headers(Word_WdHeaderFooterIndex_wdHeaderFooterFirstPage).Range
        Dim shp As Object = .InlineShapes.AddPicture(sLogoFilePathName)
        shp.LockAspectRatio = 1
        shp.Height = m_oWord.InchesToPoints(0.72)
    End With 
    
    


    The code fails at the line the sets the height.

    What's wrong and how can I adjust the height of the image in the header?

    TIA


    Clif
    • Moved by Mike Feng Friday, January 6, 2012 10:36 AM Word (From:Visual Basic Interop and Upgrade)
    Wednesday, January 4, 2012 7:50 PM

All replies

  • Hi Clif,

    I have moved this thread to Word forum for better support.

    Best regards,


    Mike Feng
    MSDN Community Support | Feedback to us
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Friday, January 6, 2012 10:36 AM
  • It would be helpful to know the error message however I see a coding error in Word_WdHeaderFooterIndex_wdHeaderFooterFirstPage

    Those underscores should be periods.


    Kind Regards, Rich ... http://greatcirclelearning.com
    Friday, January 6, 2012 1:04 PM
  • It would be helpful to know the error message however I see a coding error in Word_WdHeaderFooterIndex_wdHeaderFooterFirstPage

    Those underscores should be periods.


    Kind Regards, Rich ... http://greatcirclelearning.com

    No, actually they are properly underscores.  Due to situation beyond my control, I am using late binding so, instead of using the internal Word constants (which is unrecognized when using late binding), I created a list of constants in a "bas" module.  To retain some simblane of consistancy, I replaced what would have been periods with underscores.  That way, if I needed code snippets from a developer website, it would be easier to modify the snippet top suit my code.
    Clif
    Friday, January 6, 2012 1:11 PM
  • Okay so what is the error message you are getting because I tried your code in VBA (with additions for references) and it worked perfectly.

    Sub AddImageToHeader()
        Dim sLogoFilePathName As String
        sLogoFilePathName = "C:\Users\<my name>\Pictures\NewFile.jpg"
        Dim m_oDoc As Word.Document
        Set m_oDoc = Word.ActiveDocument
        Dim m_oWord As Object
        Set m_oWord = Word.Application
        With m_oDoc.Sections(1).Headers(Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage).Range
            Dim shp As Object
            Set shp = .InlineShapes.AddPicture(sLogoFilePathName)
            shp.LockAspectRatio = 1
            shp.Height = m_oWord.InchesToPoints(0.72)
        End With
    End Sub
    
    

     


    Kind Regards, Rich ... http://greatcirclelearning.com
    Friday, January 6, 2012 1:24 PM
  • Okay so what is the error message you are getting because I tried your code in VBA (with additions for references) and it worked perfectly.


    Perhaps you should try it in VB.Net 2010 Pro.

    I don't actually get a VB error, I get a Word error (but not very clear).  Here are the screen shots:

    The error report contents screen looks like this:

     

    You should probably know that I have Word 2010 installed on my development machine, but I'm developing for Word 2003 and Word 2010.


    Clif
    Friday, January 6, 2012 2:03 PM
  • Hi Cliff

    It's very difficult to figure out what may be wrong if the only code we see is a wrapper around the Word API...

    FWIW your code is causing Word to crash, which means it's either doing something very wrong, or there's a problem in the document.

    Headers and Footers are managed by section breaks, and section breaks are notorious for being vulnerable to document corruption.

    So the first thing I'd try is to perform the actions your code should be performing "by hand", the way an end-user would. I'd insert the graphic, then I'd try to re-size it. If Word crashes when you do this, then you know for sure you're dealing with damaged document files.


    Cindy Meister, VSTO/Word MVP
    Friday, January 6, 2012 2:13 PM
    Moderator
  • Hi Cliff

    It's very difficult to figure out what may be wrong if the only code we see is a wrapper around the Word API...

    FWIW your code is causing Word to crash, which means it's either doing something very wrong, or there's a problem in the document.

    Headers and Footers are managed by section breaks, and section breaks are notorious for being vulnerable to document corruption.

    So the first thing I'd try is to perform the actions your code should be performing "by hand", the way an end-user would. I'd insert the graphic, then I'd try to re-size it. If Word crashes when you do this, then you know for sure you're dealing with damaged document files.


    Cindy Meister, VSTO/Word MVP

    Since I am creating the document from scratch, I don't believe it's corrupted.  As far as doing it "by hand", Rich Michaels has done so already and has reported no errors.
    Clif
    Friday, January 6, 2012 2:20 PM
  • Hi Cliff

    <<Since I am creating the document from scratch, I don't believe it's corrupted.  As far as doing it "by hand", Rich Michaels has done so already and has reported no errors.>>

    It wasn't clear that you were creating these documents from scratch. Normally, one would use a template that contains all the things that are standard for a particular type of document. I was under the impression that you might be updating files generated in an earlier version of Word.

    Still, something you're doing could be damaging the file - Rich wouldn't see that since he'd be testing on a document generated by Word. Comment out the problem line then try re-sizing the graphic manually and see what happens.

    If that works without problems then we need to see the wrappers handling the late binding for you to have any chance of figuring out where the "disconnect" might be. This certainly isn't a bug in the Word APIs.


    Cindy Meister, VSTO/Word MVP
    Friday, January 6, 2012 2:24 PM
    Moderator
  • In the very first line of my OP, I said specifically that I was creating a doc file using VB.Net.

    I tried resizing the image outside of VB.Net (ie, opening up the Word file and manually resizing both through the menu option and dragging.  No errors.

    I'm curious as to how you are positive this isn't a bug in Word.  No one yet has created a Word document through VB.Net and tried my code to see what happens.  Perhaps I have discovered a bug.


    Clif
    Friday, January 6, 2012 2:32 PM
  • Hi Cliff,

    The only thing I did "by hand" was open a new blank document and set the header/footer to having a different first page.  I did that because it's what your code specified. Beyond that all I did was execute the macro.

    If you are programatically generating the document, is your code setting the different first page option on the Section 1 header?  That shouldn't cause Word to crash but it's also something to verify.


    Kind Regards, Rich ... http://greatcirclelearning.com
    Friday, January 6, 2012 2:33 PM
  • Hi Cliff,

    If you are actually creating a "doc" formatted file and not a "docx", that maybe part of the issue.

    Try another test but create a docx formatted document. 


    Kind Regards, Rich ... http://greatcirclelearning.com
    Friday, January 6, 2012 2:48 PM
  • Here is the entire code group that "adds" the header (with string edits to remove proprietary info):

    'Add Headers and footers
    m_oDoc.Sections(1).PageSetup.DifferentFirstPageHeaderFooter = True
    With m_oDoc.Sections(1).Headers(Word_WdHeaderFooterIndex_wdHeaderFooterFirstPage).Range
        .Font.Name = "Arial Narrow"
        .Font.Size = 9
        With My.MySettings.Default
            If m_cJobData.State <> "IN" Then
                sText = .ThisCompany
            Else
                sText = .ThisCompany_Indiana
            End If
            sText &= ", " & .ThisAddress1
            If .ThisAddress2.Trim() <> "" Then
                sText &= ", " & .ThisAddress2
            End If
            sText &= " " & .ThisCity & ", " & .ThisState & " " & .ThisZipCode
            If .ThisPhone.Trim() <> "" Then
                sText &= ", Ph. " & formatPhoneNumber(.ThisPhone, PhoneNumberStyle.Dots)
            End If
            If .ThisFax.Trim() <> "" Then
                sText &= ", Fax " & formatPhoneNumber(.ThisFax, PhoneNumberStyle.Dots)
            End If
        End With
        .Text = sText
        .ParagraphFormat.Alignment = Word_WdParagraphAlignment_wdAlignParagraphLeft
        .InlineShapes.AddHorizontalLineStandard()
        .InlineShapes.AddPicture(sLogoFilePathName)
    End With
    With m_oDoc.Sections(1).Footers(Word_WdHeaderFooterIndex_wdHeaderFooterFirstPage)
        .Range.Font.Name = "Arial Narrow"
        .Range.Font.Size = 9
        .Range.Font.Italic = False
        .Range.Text = "Document No. XXX-XXX-888X" & vbTab & vbTab & "Revision Date: 07/05/11"
        .Range.InlineShapes.AddHorizontalLineStandard()
    End With
    
    oRange = m_oDoc.Sections(1).Headers(Word_WdHeaderFooterIndex_wdHeaderFooterPrimary).Range
    sText = "Xxxxxxxxxx Xxxxxxxx Report" & vbCrLf
    oRange.Text = sText
    oRange.Font.Name = "Arial Narrow"
    oRange.Font.Size = 9
    oRange.Font.Bold = True
    oRange.ParagraphFormat.Alignment = Word_WdParagraphAlignment_wdAlignParagraphRight
    oRange.Collapse(Direction:=Word_WdCollapseDirection_wdCollapseEnd)
    sText = m_cJobData.CustomerName & vbCrLf & m_sCustomerName.Trim() & " Site ID: " & m_cJobData.SiteID & vbCrLf & Now().ToString("MMMM d, yyyy")
    oRange.Text = sText
    oRange.Font.Name = "Arial Narrow"
    oRange.Font.Size = 9
    oRange.Font.Bold = False
    oRange.ParagraphFormat.Alignment = Word_WdParagraphAlignment_wdAlignParagraphRight
    oRange.Collapse(Direction:=Word_WdCollapseDirection_wdCollapseEnd)
    oRange.ParagraphFormat.Borders(Word_WdBorderType_wdBorderBottom).LineStyle = Word_WdLineStyle_wdLineStyleSingle
    
    With m_oDoc.Sections(1).Footers(Word_WdHeaderFooterIndex_wdHeaderFooterPrimary)
        Dim para As Object 'Word.Paragraph
        Dim rng As Object 'Word.Range
        .Range.Font.Name = "Arial Narrow"
        .Range.Font.Size = 9
        para = .Range.Paragraphs.Last
        rng = para.Range
        rng.Text = "Document No. XXX-XXX-888X" & vbTab & vbTab & "Revision Date: 07/05/11" & vbTab
        rng.Collapse(Word_WdCollapseDirection_wdCollapseEnd)
        m_oDoc.Fields.Add(rng, Word_WdFieldType_wdFieldPage)
        .Range.InlineShapes.AddHorizontalLineStandard()
    End With
    


    sLogoFilePathName is a valid path to a png file.


    Clif
    Friday, January 6, 2012 2:49 PM
  • Hi Cliff,

    If you are actually creating a "doc" formatted file and not a "docx", that maybe part of the issue.

    Try another test but create a docx formatted document. 


    Kind Regards, Rich ... http://greatcirclelearning.com

    I am neither creating a doc or a docx file at the point in code where the error is occuring.  The doc/docx part does not come into account until I go to save the document, which is after the document is created.
    Clif
    Friday, January 6, 2012 2:54 PM
  • Hello Clif,

    >>Perhaps you should try it in VB.Net 2010 Pro

    I also tried the code which Rich provided, but couldn't reproduce the problem in VB.net 2010 Pro. Does the problem happens on both 2003 and 2010? Is the issue specific to Word 2003? I recommend you reinstall Office 2003 to see whether it works well.

    Best Wishes!

    Tuesday, January 10, 2012 4:52 AM
  • While I'm creating documents for Word 2003, I don't have Word 2003 installed on my machine (hence the reason for late-binding).

    What I ended up doing was having the "art department" create a (physically) smaller image that works without needing to resize in code.

    Thanks for everyone's help, though.


    Clif
    Tuesday, January 10, 2012 1:10 PM