Quicktip – Microsoft Word: How to Paste/Format Code?






4.67/5 (2 votes)
How to paste/format code in Microsoft Word
Introduction
Have you ever tried to paste code into a Word document? Ugly! It loses formatting, wraps code around, loses syntax coloring, etc. Today, I tried to document my sample Java/JSP code in Word. I wanted to intersperse code with additional comments explaining the code for other developers, the way some web pages do it. I tried pasting code into Word, it lost formatting and also syntax coloring. I searched good old Google and landed on this page in Stackoverflow (SOF). Out of the several tips, the one using NotePad++ (Npp) caught my attention.
Export to HTML using Npp
I use Npp both at work and home and it’s a great tool. Why not use it? I had an older version. I downloaded and installed version 6.2. They have added few more plugins and options. Now, I can colorize JSP code (though I don’t like their choice of colors for HTML elements). Per tip in SOF, I tried Npp Export plugin to copy RTF to Clipboard option. This didn’t work OK (colors ran in Word). I tried the other options. Of all, the “Export to HTML” option worked out the best for me. Colors softened in HTML. Then I just opened the HTML file in Word, saved as Word and got down to business with documenting the code. To add flavor, I added a Style called “Code” in Word to customize further. I added “box” to this style and the results are shown below.
Adding Line Numbers
NppExport does not add line #s by default (There is a “feature request” opened for this issue!). I poked around the web for line #s in Npp and found this tip. Essentially, use TextFx Tools to Insert line #s into the file in Npp. Then do the Export like above. Bingo! I’ve got formatted/syntax highlighted code with line #s pasted into Word document. And one more kudos to Npp for a job well done!
Fig 1 – Sample code snippet formatted in Word with description around it
Filed under: CodeProject, Misc
Tagged: documenting code, Notepad++, Npp, Word