136

I have to write some documents that will include source code examples. Some of the examples will be written from the IDE, and others would be written in place. My examples are primarily in Java.

As someone who is used to LaTeX, doing this in Word is extremely painful. However, I am bound to Word for this. The only options I have seen are:

  1. Write or copy into the document, then use a fixed type font, arrange formatting and hope that Word didn't uppercase stuff for you. Needless to say, this looks like crap.
  2. Copy and paste screenshots of source code from the IDE. At least I keep colors. However, if I change my font size, I'm screwed. I'm also screwed across page boundaries. And let's admit it, Word is not great at managing multiple images on a document.
  3. Write HTML (not really an option here)

Is there some better (and ideally portable) way to do this? Is there at least some sort of verbatim style similar to the LaTeX environment? Is there at least some pretty printer that I could copy-and-paste as RTF?

Todd Main
  • 31,359
  • 10
  • 76
  • 141
Uri
  • 84,589
  • 46
  • 214
  • 312
  • Russel: Not sure I understand. – Uri Jul 15 '10 at 02:38
  • In general never assume that Word won't mangle your text at whim (1). Absent a real publishing tool, I'd opt for (2). – msw Jul 15 '10 at 02:41
  • 2
    I think this is probably more appropriate for superuser. Just because the thing you're inserting into the document happens to be code doesn't make this a programming question. – danben Jul 15 '10 at 02:42
  • How about tools ala Latex2Word, Pdf2Word (made up names)? – Hamish Grubijan Jul 15 '10 at 02:48
  • 2
    @danben: I guess. I just figured that code examples in word documents is something that most programmers end up doing in their day to day work. – Uri Jul 15 '10 at 02:52
  • Sorry @Uri - I meant screen capture. – Russell Jul 15 '10 at 03:48
  • 1
    Are you bound to Word-the-program or Word-the-file-format? – Ken Jul 31 '10 at 17:15
  • 5
    possible duplicate of [How do you display code snippets in MS Word preserving format and syntax highlighting?](http://stackoverflow.com/questions/387453/how-do-you-display-code-snippets-in-ms-word-preserving-format-and-syntax-highlig) – jerone Jan 15 '15 at 13:03
  • Here is another answer with [Notepad++](https://superuser.com/questions/39571/how-do-i-easily-highlight-the-syntax-of-php-code-in-word/39600#39600) – Ognyan Dimitrov May 28 '20 at 15:09

15 Answers15

196

I absolutely hate and despise working for free for Microsoft, given how after all those billions of dollars they STILL do not to have proper guides about stuff like this with screenshots on their damn website.

Anyways, here is a quick guide in Word 2010, using Notepad++ for syntax coloring, and a TextBox which can be captioned:

  1. Choose Insert / Text Box / Simple Text Box
    01word
  2. A default text box is inserted
    02word
  3. Switch to NPP, choose the language for syntax coloring of your code, go to Plugins / NPPExport / Copy RTF to clipboard
    03npp
  4. Switch back to word, and paste into the text box - it may be too small ...
    04word
  5. ... so you may have to change its size
    05word
  6. Having selected the text box, right-click on it, then choose Insert Caption ...
    06word
  7. In the Caption menu, if you don't have one already, click New Label, and set the new label to "Code", click OK ...
    07word
  8. ... then in the Caption dialog, switch the label to Code, and hit OK
    08word
  9. Finally, type your caption in the newly created caption box
    09word
sdaau
  • 32,015
  • 34
  • 178
  • 244
  • When you cross reference caption it inserts entire code itself to how to solve this problem? – MonsterMMORPG Apr 14 '15 at 12:08
  • 1
    In Word 2013 the text is code is paste as plain text, no way to keep the format of Notepad++ – Jose Nobile Jan 19 '17 at 04:56
  • 2
    @JoseNobile you need to use the NppExport plugin in Notepad++ – NeilenMarais Jan 24 '17 at 13:53
  • 2
    It also works with Android Studio, Visual Studio and Eclipse. – Teocci Mar 28 '17 at 01:04
  • I initially used the same technique but have since changed to using a table of 1x1 because I found that text boxes are an f'ing pain to position. I tried "top and bottom" so the text would be only before and after, and Word would magically move the box up or down, sometimes the caption would not be visible, ah what a pain. Started using tables today based on another SO QA, so far working well. I create a new caption label type "Listing". – Oliver Oct 19 '17 at 19:23
  • Drawback of this technique: You need to position and check for alignment for every single box you add. Better use styles which include precise regularity in the document layout. I can't add a picture in a comment but it just looks like in IT books. Benefit of your method is unlike using styles which are not specific objects you seem to be able to add a caption easily but I bet you can do such thing quite easily too semi-manually by creating a separate style which would give you easy control on things. – 猫IT Jan 07 '19 at 23:08
30

I recently came across this post and found some useful hints. However, I ended up using an entirely different approach which suited my needs. I am sharing the approach and my reasoning of why I chose this approach. The post is longer than I would have liked, but I believe screenshots are always helpful. Hopefully, the answer would be useful to someone.

My requirements were the following:

  1. Add code snippets to a word document, with syntax highlighting for easier visibility and differentiation of code and other text.
  2. Code snippet shall be inline with other text.
  3. Code snippet shall break across pages smoothly without any extra effort.
  4. Code snippet shall have a nice border.
  5. Code snippet shall have spell-check disabled.

My Approach is as listed below:

  1. Use external tool to achieve syntax highlighting requirement 1 above. One could use notepad plus plus as described above. However, I use the tool present here - http://www.planetb.ca/syntax-highlight-word. This gives me the option to use line number, as well as very nice syntax highlighting (Please use Google Chrome for this step, because syntax highlight is not copied when using Mozilla Firefox, as also pointed out by couple of user comments). Steps to achieve syntax highlighting are listed below:
  2. To achieve requirements 2, 3 and 4 above, use table in Microsoft word, to insert the code snippet. Steps are listed below:

    • Insert a table with single column.
    • Paste the copied text from step 1. in the table column. I have kept the line numbers to show how well this works with Microsoft word.
    • Apply border, as you like. I have used size 1pt. Resulting Microsoft word snippet will appear as shown in screenshot below. Note how nicely it breaks across the page - NO extra effort needed to manage this, which you would face if inserting "OpenDocument Text" object or if using "Simple TextBox". Syntax-highlighted code snippet pasted in Microsoft Word Table
  3. To achieve requirement 5, follow the steps below:

    • Select the entire table or the text.
    • Go to Review tab. Under Language, choose "Proofing Language". A new pop-up will be presented.
    • Select "Do not check spelling or grammar". Then, click OK. Disable spell-check
    • Resulting text has spell-check disabled. Final result is shown in the image below and meets all the requirements. Final Result - meets all the 5 requirements.

Please provide if you have any feedback or improvements or run into any issues with the approach.

abhishek
  • 519
  • 5
  • 12
  • 2
    Thanks! Looks great... I had to use Google Chrome because Mozilla Firefox wasn't copying the syntax highlighting. – loveMeansNothing Jun 21 '16 at 17:47
  • I think this is the best solution. One more tip: if you don't want the spell-check but your not writing in English, insert the code as an Open Document Text object. Go to INSERT - OBJECT - and choose OpenDocument Text. Insert the code into the opened document and then save and close. The code is displayed as above but the spelling is ignored entirely. The only drawback may be that the number doesnt work correctly, if you want to include it into the caption for the listing. Havent checked that. – user3629892 Sep 21 '16 at 14:03
  • @user3629892 I thought that with Open Document you can't wrap nicely across different pages. – maracuja-juice Nov 02 '16 at 07:41
  • Is there any possibility to get that beautiful border as well for line numbers while copying to word. – Paramesh Korrakuti Dec 26 '17 at 12:25
  • Hi @ParameshKorrakuti, If by the border you mean the 'light grey colored background behind the numbers' shown on the syntax highlighter website, then I have not been successful at achieving that. Once you paste it in word, it loses the grey background. That is because, the website is using html and css to achieve the background color (see the .dp-highlighter section in css). In microsoft word, one line can possibly have only one background color scheme. Hope that answers your question. If this does not then, please provide a screenshot of what you are referring to and ill check. – abhishek Jan 14 '18 at 06:17
  • Hi! Nice method! I've been trying for couple of days to get this right now! Do you know how to assign a caption under the code that can be referenced like the 'image' caption in Word? I tried using a 'textbox', but that's not very straight forward! – RFNO Jul 14 '19 at 06:44
  • Hi @RFNO - Wikihow has an article describing step-by-step process of adding "table captions" -- https://www.wikihow.com/Add-a-Caption-to-a-Table-in-Word. You could follow the steps from aforementioned article and at Step 5, instead of using "Table" as label type, create a new label type called "Source Code" (for instance) and use numbered caption as described in the remainder of the steps 6 to 8, in the wikihow article. I have tried this and it works great - I am able to see "Source Code" as a new "Reference Type" in the Cross-References, which can be linked from anywhere in the word document. – abhishek Aug 16 '19 at 05:00
  • Great solution, but gee 3 page write up on how to insert a piece of code into Word! This speaks a lot of how modern / relevant Word is. – RusI Sep 06 '19 at 07:05
  • Thank you for your post, maybe consider a little edit for the web browser as @loveMeansNothing said in the first comment. Thank you very much for your comment, that was an important comment and should be edited into the main text in my opinion :) – Capt.Krusty Dec 10 '19 at 08:50
  • 1
    @Capt.Krusty - In point 1, bullet point 1 and 5, I had already mentioned to use Chrome. But, I will go ahead and add "Google Chrome" as you and loveMeansNothing suggested. – abhishek Dec 14 '19 at 17:34
22

You need to define a style in your Word document and use that for source code. I usually have a style called "Code" which has a monospaced font in a small point size, fixed size tabs, single line spacing, no before/after paragraph spacing, etc. You only need to define this style once and then reuse it. You paste in your source code and apply the "Code" style to it.

Note that some editors (e.g. Xcode on the Mac) add RTF as well as text to the clipboard when copying/pasting between applications - Word recognises RTF and helpfully retains the formatting, syntax colouring, etc.

Source code in Xcode:

enter image description here

Copied and pasted to Word:

enter image description here

(Note: it's a good idea to disable spell-checking in your "Code" style in Word.)

Paul R
  • 195,989
  • 32
  • 353
  • 519
  • This however does not automatically add style to keywords, numbers, strings etc. – Bart Jan 29 '16 at 12:46
  • @Bart: in general, no, but for those who use Xcode (for Mac OS X, iOS, etc development) the clipboard contains RTF with all the syntax colouring etc, and Word accepts this. It's possible that there are other editors which also have this useful feature, but I'm not aware of them. – Paul R Jan 29 '16 at 13:00
  • RTF works, yes, I've used this in the past as well using Notepad++ to Word. However, it would be very nice if there were a way to add a _real_ code style, i.e. one that does syntax highlighting automatically. Quite a shame nothing like that seems to exist. Granted, there are some add-ons you can install which can highlight on demand, but I have yet to find one which can easily re-style all your code blocks with a different style if you want. – Bart Feb 01 '16 at 21:39
  • I don't think this supports captioning does it? – Oliver Oct 19 '17 at 19:24
  • @Schollii: I think captions can only be applied to “objects” in Word. I guess you could put the code in a 1x1 table, which would then make it an object ? – Paul R Oct 19 '17 at 21:06
  • Oh yes, I hadn’t noticed that. – Paul R Oct 20 '17 at 05:25
11

It kind of depends on the IDE. Both Visual Studio and Eclipse, for example, will allow you to copy as RTF and paste into Word, keeping all your formatting.

Notepad++ has a plugin called "NppExport" (comes pre-installed) that allows you to copy to RTF, though I don't care much for Notepad++'s syntax highlighting (it'd definitely be passable though). What it does do is support dozens of languages, whereas the aforementioned IDEs are limited to a handful each (without other plug-ins).

Cᴏʀʏ
  • 97,417
  • 19
  • 158
  • 183
  • 1
    I've had good luck with both VS and Eclipse in doing just this- using the IDE's editor to do the syntax coloring (and any formatting I like), then cutting and pasting directly into word. I typically follow it up with setting the font across the snippet to a fixed width font (it didn't always come across for me) – heckj Jul 15 '10 at 05:46
5

Use this - http://hilite.me/

hilite.me converts your code snippets into pretty-printed HTML format, easily embeddable into blog posts, emails and websites.

How: Just copy the source code to the left pane, select the language and the color scheme, and click "Highlight!". The HTML from the right pane can now be pasted to your blog or email, no external CSS or Javascript files are required.

For Microsoft Word document: Copy the the content from the Preview section and paste to your Microsoft Word document.

3 sections : Source Code , HTML and Preview

3

This is related to this answer: https://stackoverflow.com/a/2653406/931265 Creating an object solved all of my problems.

Insert > Object > Opendocument Text

This will open a document window, paste your text, format it how you want, and close it.

The result is a figure. Right click the object, and select 'add a caption'.

You can now make cross references, create a table of figures.

Community
  • 1
  • 1
rickfoosusa
  • 949
  • 16
  • 22
2

On a Mac I find this solution with vim to be wonderful:

https://github.com/zerowidth/vim-copy-as-rtf

qed
  • 19,750
  • 16
  • 99
  • 168
2

If you are still looking for an simple way to add code snippets.

you can easily go to [Insert] > [Object] > [Opendocument Text] > paste your code > Save and Close.

You could also put this into a macro and add it to your easy access bar.

notes:

  • This will only take up to one page of code.
  • Your Code will not be autocorrected.
  • You can only interact with it by double-clicking it.
Meatyflesh
  • 21
  • 4
2

There is an easy way if you want simple code formatting.

  1. Open word> Insert tab> click on "Get Add-ins"
  2. search for "Content mixer" 3.click on "Add"

Then content mixer add will open automatically and you can copy paste your code in there and click on "Insert" to insert it in word doc.

Hitesh Bisht
  • 378
  • 1
  • 3
  • 11
2

These answers look outdated and quite tedious compared to the web add-in solution; which is available for products since Office 2013.

I'm using Easy Code Formatter, which allows you to codify the text in-place. It also gives you line-numbering options, highlighting, different styles and the styles are open sourced here: https://github.com/armhil/easy-code-formatter-styles so you could extend the styling yourself. To install - open Microsoft Word, go to Insert Tab / click "Get Add-ins" and search for "Easy Code Formatter"

enter image description here enter image description here enter image description here

Mavi Domates
  • 3,886
  • 2
  • 15
  • 39
  • Interesting plugin, but it has two drawbacks: 1) As can be seen from the screenshots, it doesn't disable the spelling checker 2) When I tried to download it, it wants me to share my personal details with the developer. Not gonna happen! – Dave C May 27 '21 at 09:04
1

You can use Open Xml Sdk for this. If you have the code in html with color and formatting. You can use altchunks to add it to the word documents. Refer this post Add HTML String to OpenXML (*.docx) Document Hope this helps!

Community
  • 1
  • 1
Mohamed Alikhan
  • 1,189
  • 9
  • 14
1

This is what i did.

End results : enter image description here

https://stackoverflow.com/a/25092977/1161594

Community
  • 1
  • 1
USer22999299
  • 4,180
  • 7
  • 36
  • 66
1

You can using Plugin Syntax Highlight in Ms.Word https://store.office.com/syntax-highlighter-WA104315019.aspx?assetid=WA104315019 . i follow that step and it's work

ynz
  • 548
  • 3
  • 9
1

In Word, it is possible to paste code that uses color to differentiate comments from code using "Paste Keep Source Formatting." However, if you use the pasted code to create a new style, Word automatically strips the color coded text and changes them to be black (or whatever the auto default color is). Since applying a style is the best way to ensure compliance with document format requirements, Word is not very useful for documenting software programs. Unfortunately, I don't recall Open Office being any better. The best work-around is to use the default simple text box.

1

I have tried all your methods, but they didn't work for me, in fact I have created an easier method using MS Word Tables.

Pros:

  1. More beautiful
  2. Easier to manage & more consistent
  3. Are less prone to problems
  4. No need for external plugins or MS Word micro coding.
  5. Easier to handle by simple users (such as myself).

Cons: It will not maintain code colouring although someone could improve my trick.

Steps:

  1. Insert a 3x3 table, in my case I always make the total width of the table equals the free page's width (3 rows minimum to test the tables style).

  2. Use invisible borders ("No Borders" option), and activate "View Gridlines" option. it should have this aspect. Be ware that those lines are for you to see the table's grid, and the will not be printed.

enter image description here

  1. Make the adjustments to cells' spacing and columns' width to get the aspect you like. (You will have to get in "Table Properties" for fine tuning). enter image description here

  2. Create a "Paragraph Style" with the name of "Code" just for your code snippets (check https://stackoverflow.com/a/25092977/8533804 to get the idea, you don't have to follow all of it)

  3. Create another "Paragraph Style" with the name of "Code_numberline" that will be based upon the previous created style. enter image description here

  4. In the newly created "Code_numberline" add the numbering style that you like (this will automate line numbering). enter image description here

  5. Apply "Code_numberline" to the first column, and "Code" to the 3 column. enter image description here

  6. Add a fill in the middle column. enter image description here

  7. Save that table style and enjoy!

Nader Belal
  • 125
  • 1
  • 9
  • Great until, you said _Save that table style_. – Martin of Hessle Dec 18 '18 at 09:26
  • @MartinofHessle, well for extended documents where you'll populate it with code snippets in many places the option of saving this tables style is a time saver, besides it permits you to modify the table style throughout the document hassle free, like in my case where I have a style for the IDE and IDLE ... on other hand, if you are using only one table, then you may omit the last step – Nader Belal Dec 19 '18 at 11:35
  • I agree with the why. It was the how to say it to normal.dot to make it persist which would have been a useful addition. I figured it out but it wasn't obvious. – Martin of Hessle Dec 19 '18 at 16:10
  • @MartinofHessle pardon me, but I didn't understand your last statement. Could you repeat it again in simpler terms ? – Nader Belal Dec 19 '18 at 17:09
  • 1
    Sorry typo, should have been **how to save it to normal.dot**. – Martin of Hessle Dec 20 '18 at 12:15