Insert or Paste formatted source code into a Word Document

21 Apr, 2013
Updated
22 Dec, 2012
Created

How often were you required to paste some sort of source code into a word document and realized that how difficult it is to keep the correct formatting and indentation?

Well there are a lot of ways you could use to achieve the desired output. However, there is a simple way to achieve this which works for me always. So here’s the trick.

The Steps

  • Step 1:

    Here’s some sample C# code written in Visual Studio 2012. I want to paste this code block into a word document.

    vs-sample-code-001

  • Step 2:

    Here’s the word document that I want to paste my formatted code.

    word-sample-001

  • Step 3:

    Place your cursor at the point where you want to place your code. Select the “INSERT” tab on the ribbon and click on the “Insert Object” icon.

    word-sample-002

  • Step 4:

    The “Object” dialog box will appear. From the “Create New” tab of the dialog box, select the “OpenDocument Text” option and click “OK”.

    word-sample-003

  • Step 5:

    A new word document will open. Paste your code in this new document. Save and close the document.

    word-sample-004

  • Step 6:

    Your original document will look as below. If you want, you can double click on the object and edit the code again. Once done, you just need to save the document and it will update the code within your document.

    word-sample-005

  • Step 7:

    As a last and optional step, you might want to fix the layout of the object to wrap with the text. To do this, right click on the object and select “Format Object”. The “Format Object” dialog box appears. Click on the “Layout” tab and select the wrapping style as “In line with text”. Your final code will look as below.

    word-sample-006