1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

.net Interop.Word insert from docx without screwing up formatting

Discussion in 'Programming/Internet' started by Broco, Sep 12, 2018.

  1. Broco

    Broco Guest

    I have an issue I've stuck with for over a year now. I made a Forms application in VB.net which allows the user to type in some information and select items which represent docx-files with tables with special formatting, pictures and other formatting querks in them.

    At the end the software creates a Word document via Office.Interop, using the information the user provided in text fields in the Forms and the items they selected (e.g. it creates a table in Word, listing the user's selections with some extra info) and then appends the content from multiple docx-files depending on the user's selection to the document created via Interop.

    The problem is: To achieve this I had to use a pretty dirty method: I open the respective docx-files, select all content (Range.Wholestory()) and copy it (Range.Copy()). Then I insert this content from the clipboard into my newly created document with the following option:

    Selection.PasteAndFormat (wdFormatOriginalFormatting)


    This produces a satisfactory result but it feels super dirty since it uses the user's clipboard (which I save at the beginning of the runtime and restore at the end).

    I originially tried to use the Selection.InsertFile-Method and tried this again today but it completely screws the formatting.

    When the content of the docx is inserted this way it neither has the formatting of the original docx nor the one of the file I created with the program. E.g. the SpaceBefore and SpaceAfter values are wrong, even if I explicitly define them in my created file. Changing the formatting afterwards is no option since the source files contain a lot of special formatting and can change all the time.

    Another factor which makes it hard: I cannot save the file before it is presented to the user, using tmp folder is not an option in the environment this application is deployed into, so basicyally everything happens in RAM.

    Summary:

    Basically what I want is to create the same outcome as with my "Copy and Paste" method utilizing the OriginalFormatting WITHOUT using the clipboard. The problem is, the InsertFile-Method doesn't provide an option for the formatting.

    Any idea or help would be greatly appreciated.

    Login To add answer/comment
     

Share This Page