Site icon Ryadel

Displaying Code Snippets in Microsoft Word with Syntax Highlighting

Visualizzare frammenti di codice sorgente in Microsoft Word con Syntax Highlighting

Finding a way to decently show our source code on the web recently became a rather trivial task thanks to many JavaScript + CSS based libraries such as highlightjs, PrismJS, Prettify, SyntaxHighlighter & more. It's not so easy to achieve the same results inside a text-editing software such as MS Word, to the point that I've seen more than few devs adopting the awful & dreadful screenshot method, which consist in blindly capture a portion of their developer framework GUI and then embedding it as an image inside the Word document.

Should we do that? Of course no! There is at least one better way to do that, which also is far less intrusive (and size-intensive) and also gives us the chance to modify/review our code snippet after it has been pasted. Let's see how we can do it.

  • Open MS Word and place the cursor where you want to paste the snippet.
  • Go to the Insert tab, from there click to the Object... button close to the right-end of the toolbar. A popup will show up: select OpenDocument Text.
  • A new "embedded" document will appear: go to your favourite Developer Framework, such as Visual Studio, Eclipse, Android Studio, Notepad++ or the one doing the highlight the way you want it to be. Copy the code from there and paste it to the new document.
  • Save and close the new document.

Your efforts will be rewarded with something like that:

code-snippet-in-ms-word

This solution, other than being visually nice, grants you the following benefits:

  • the source code will be entirely editable.
  • all the layout, coloring, spaces, tabs, linefeeds from the developer framework will be kept.
  • the code will be treated like a separated, embedded element, just like images and charts, so you'll be able to move, resize, shape, applying borders, shadows, background color and basically anything else you want to and/or Word allows.
  • the code won't be affected by grammar checker, meaning that spelling errors won't be highlighted in the code: no red underlining, yay!
  • it takes only few seconds to do it  - you'll love that if you need to insert multiple snippets.
  • It works on all Word builds since 2007: Word 2007, Word 2010, Word 2013 and newer versions.

If you find an even better way, please let me know.

Meanwhile... Happy coding!

Exit mobile version