2248

Does anyone know a way to display code in Microsoft Word documents that preserves coloring and formatting? Preferably, the method would also be unobtrusive and easy to update.

I have tried to include code as regular text which looks awful and gets in the way when editing regular text. I have also tried inserting objects, a WordPad document and Text Box, into the document then putting the code inside those objects. The code looks much better and is easier to avoid while editing the rest of the text. However, these objects can only span one page which makes editing a nightmare when several pages of code need to be added.

Lastly, I know that there are much better editors/formats that have no problem handling this but I am stuck working with MS word.

DubiousPusher
  • 982
  • 1
  • 7
  • 19
Lawrence Barsanti
  • 27,683
  • 10
  • 43
  • 64
  • I have gone with a mixed solution. Copy with RTF formatting, pasting into OpenOffice Writer, removing the background (if there is any) and then pasting the code into MS Word. For some reason I can't remove the background in Word :-( Anyways, the ["Copy on steroids"](http://plugins.jetbrains.com/plugin/7198) plugin to do this in PhpStorm, WebStorm, PyCharm is awsome! – chjortlund Aug 22 '14 at 22:46
  • 4
    Starting with Office 365, I don't know maybe even for Word 2013 or 2016. It has Online Addin called "Code Format" . Install that Office Addin and in your word doc you can just select all code (even multiple pages) and click convert it button from the Code Format addin and it converts it into a formatted color code with line numbers. I could not find the option to format without line numbers though !!! But nevertheless, not too bad !! – Rahul Saini Nov 07 '16 at 19:04
  • Outside of any specific add-in that would dedicate to format code the best solution is to use styles or alternatively images. Styles are meant for formatting. I used to use many forks from Star Office to Libre Office today but I just got into Word and I found how to do it just by exploring the style config. Just use Notepad++ to export RTF then use styles. Some of the things I did is add a border, a background color I like, check "Do not add spacing between the same style" or alike (I have the French GUI so I don't know the exact english caption) and anything you like. – 猫IT Jan 07 '19 at 23:01
  • Code Format is unavailable - but Easy Code Formatter here works pretty well: https://appsource.microsoft.com/en-us/product/office/WA104382008?tab=Overview – Mavi Domates Apr 29 '19 at 16:11
  • Just be careful with online code highlighting tool, once you submit your code, you never know what ll happen to your code. The tool provider may claimed ur code or anything. Just a warning though. – Ram Mar 18 '21 at 11:04

44 Answers44

2219

Here is the best way, for me, to add code inside word:

  1. go to Insert tab, Text section, click object button (it's on the right)
  2. choose OpenDocument Text which will open a new embedded word document
  3. copy and paste your code from Visual Studio / Eclipse inside this embedded word page
  4. save and close

The result looks very nice. Here are the advantages of this method:

  • the code keeps its original layout and colors
  • the code is separated from the rest of the document, as if it was a picture or a chart
  • spelling errors won't be highlighted in the code (this is cool !)

And it takes only few seconds.

Serj Sagan
  • 24,625
  • 17
  • 133
  • 166
gargamel
  • 22,334
  • 1
  • 14
  • 3
  • 3
    Brilliant tip. Just to note, it doesn't work if copying code from IntelliJ (it is copied without syntax highlighting) – Richard Aug 24 '12 at 13:09
  • 24
    Brilliant! I've been fiddling with styles, tables and other workarounds for years. This fixes everything in one go. Note that you also get the bonus of adding a caption to your code. I added a new label type "Listing" for brownie points :-) – Nebula Jan 31 '13 at 12:47
  • 1
    Of course, this approach suffers from a lack of maintainability. What if you were to change your code mid/after writing your Word document. Then you have to apply that trick again to update the code snippet in your document. With LaTeX and the listings package, you'd just point to the source file and your code snippet would be updated the next time you compile your .tex file. No cop/paste involved. Plus, you'd get automatic syntax highlighting and line numbering. – jub0bs Jul 26 '13 at 15:21
  • 1
    I would suggest simply use snipping tool, u get an image and now simply insert that image. – hershey92 Sep 22 '13 at 04:51
  • 8
    Please note tath this requires open/libre office to be installed on your machine. – BetaRide Oct 10 '13 at 06:06
  • 16
    @BetaRide No, it doesn't. I just used this on a document on a machine without OpenOffice installed. OpenDocument refers to a file format with support from MS Office among others: http://en.wikipedia.org/wiki/OpenDocument – Jamie F Oct 10 '13 at 17:51
  • 3
    I have Windows 7, Word 2007 and do not have OpenOffice installed and still I am able to use this approach. My co-worker has Windows Vista, Word 2007 and OpenOffice 3.2 and cannot open the object created by me. He can create his own object, which he can edit not in separate window, but inside the main document (only some rulers are displayed around the object). EDIT: If I convert "openDocument Text" to "MS Word document", now he is able to edit my object. – mirelon Oct 21 '13 at 12:12
  • 53
    Can't see that option on Word 2011 on OSX :( – Matt Gibson Nov 08 '13 at 14:10
  • Not working for me. Maybe because I am getting the code from another server VS? – Si8 Feb 20 '14 at 19:53
  • 46
    For Word 2011 on OSX use: Insert -> Object...Microsoft Word Document – s_t_e_v_e Apr 07 '14 at 17:19
  • 3
    Disadvantage is that you cannot select the text and you cannot copy the text to paste it elsewhere. – Fred Nov 25 '14 at 14:54
  • 6
    If you are copying from Notepad++, then use Plugins -> NppExport -> Copy HTML to Clipboard – Ranhiru Jude Cooray Dec 10 '14 at 04:07
  • 2
    this totally depends on the source from where you copy the code! copying from Microsoft Script Editor doesn't preserv any highlighting at all. – philx_x Apr 02 '15 at 15:00
  • Hello this works awesome however when i cross reference the caption of opendocument text it inserts whole object too – MonsterMMORPG Apr 14 '15 at 12:10
  • Note that this only works when word saves the original formatting of the text. See [this microsoft link](https://support.office.com/en-us/article/Control-the-formatting-when-you-paste-text-20156a41-520e-48a6-8680-fb9ce15bf3d6#bm1). – Tomer Jul 07 '15 at 16:18
  • After pasting it in the Open Document Text page format you can then Copy and Paste it in your MSword document from the ODT document maintaining the original formating and colors. – Tiago Duque Oct 30 '15 at 14:06
  • 5
    how can we display whole code when it is longer than one page. In that case, whole object is shifting to new page and only shows whatever comes in that page. Is it possible that the object doesn't shift to new page and also shows whole code? – user3379410 Apr 25 '16 at 07:20
  • A lot of hoo-ha about `OpenDocument` format. Why don't people just insert a second word document inside the first? `Microsoft Word Document` is in the list as well. The principle works nicely for my needs though. – cartbeforehorse Aug 24 '16 at 10:53
  • 1
    It's not working for me. I have copied my html content from visual studio and pasted it as explained in the solution. It's rendering as plain text (all the html tags) and not showing any kind of formatting. Any Idea what could be the issue in my scenario? – Hemant Kabra Jan 19 '17 at 09:51
  • 1
    Copying and pasting from Visual Studio Code works really well too. The VS Code Dark theme looks bad, so make sure to use the default Light theme. – Kris Krause Mar 17 '17 at 18:33
  • 3
    Other solutions below are better imo. The problem with this solutions is that if you embed code as an object then it is not search-able. Furthermore, if you have code that spans more than one page, then you have to create multiple objects for every page that your code spans. – Luke Purnell Feb 01 '18 at 10:04
  • Plus, this makes your code not selectable so people cannot copy it when shipped as docx or pdf. – Martin Braun Feb 02 '18 at 18:05
  • 1
    Beware, this solution seems to break 'Save as .PDF' feature in Office 365 Word version. Edit: Printing as PDF option is still available, although that's not as comfortable as just saving as .PDF – eduherminio Jun 10 '18 at 20:31
  • 2
    any hints on how to include line numbers with this solution? – Sip Jun 22 '18 at 09:31
  • 1
    Doesn't seem to work as described in the MS Word 365 version. – Christos Karapapas Nov 10 '18 at 03:23
  • Also worth noting, Search does not seem to work if the string you are search for is in the embedded document – Pants May 22 '19 at 18:46
  • This worked for me with Office 2019, but I found Home->Paste->Paste Special->Formatted Text to be slightly better. The look is the same, but the text (code) is editable within the document. +1 – Roberto Oct 23 '19 at 00:09
  • This approach (inserting as OpenOffice Text object) makes it hard to select and copy the code. Just selecting the object and either CTRL-C or right-click--> copy doesn't then allow you to past elsewhere (e.g. in a text editor). – Scott H Jan 15 '20 at 18:42
  • Thanks for the hack brother, this is beautiful! – Soutzikevich Mar 06 '20 at 00:52
  • I did not upvote this as it makes the document heavier, if you have to paste snippets multiple times throughout the document. It will make the document heavier and more time to load or edit. – thatskj Jul 09 '20 at 09:54
  • 1
    Magnificent. Also, some resources may help highlighting the code. For example: http://www.planetb.ca/syntax-highlight-word. Copy an HTML result to document. Voilà! – F8ER Oct 21 '20 at 11:27
1085

Download and install Notepad++ and do the following:

  1. Paste your code in the window;

  2. Select the programming language from the language menu;

  3. Select the text to copy;

  4. Right click and select Plugin commands -> Copy Text with Syntax Highlighting;

  5. Paste it into MS Word and you are good to go!

Update 29/06/2013:

Notepad++ has a plugin called "NppExport" (comes pre-installed) that allows you to copy to RTF, HTML and ALL. It permits dozens of languages, whereas the aforementioned IDEs are limited to a handful each (without other plug-ins).

I use Copy all formats to clipboard and "paste as HTML" in MS word.

screenshot from notepad++

root-11
  • 1,531
  • 1
  • 16
  • 29
Saad
  • 11,809
  • 1
  • 17
  • 12
  • 9
    This worked beautifully. I already had Notepad++ for other code projects, but never thought of using it. Combined with a Word style that added a faint blue background, border, and disabled spell check, it looks pretty good, and is fairly fast for a number of files, as opposed to methods involving file exports and imports. Although I wish there was a way to add it as a field that would automatically check the original .java files for updates, and keep the latest source code in the Word file. – Neil Feb 04 '11 at 18:31
  • 93
    Thanks for this hint. **Plugins -> NppExport -> Copy RTF to Clipboard** also works. – Andrew Huey May 16 '11 at 17:32
  • 1
    @AndyH Thanks! My right-click menu doesn't have *Plugin Commands*. – Error 454 May 20 '11 at 20:52
  • 34
    This worked very well. In Word 2007+, to add a border and disable spell check: 1) select your code; 2) 'Home->Styles->Save selection as new Quick Style' (it is a drop button); 3) Name it 'Code' or similar; 4) Modify; 5) Format->Border (lower left) to add border; 6) Format->Language [X] Do not check spelling or grammar. Now, you can apply the same formatting 'Code' to text pasted from NppExport. – Blazes Jul 31 '11 at 09:52
  • 2
    This one works great, couldn't get the Word Document inside the Word Document to play nice. Folks this is the way to go! – Urda Nov 20 '11 at 23:25
  • 2
    Only disadvantage of this method is that it depends on language's syntax highlight support in Notepad++ (Like for example if you are using Drools). I think the same applies to eclipse, nevertheless both are great methods – zurdo Aug 17 '12 at 14:51
  • Very good suggestion. However you don't get line numbers. Does anyone has a solution for that? – Benny Neugebauer Oct 07 '12 at 14:23
  • In Word 2010, the Style options are found by right clicking on the style in the Styles ribbon and choosing `Modify...` – Bryan Ash Jan 18 '13 at 17:30
  • I like this option better than gargamel's. Not that there's anything wrong with it but because my VS theme is dark and it looks pretty awful in a Word document. – sjeffrey Feb 09 '13 at 19:43
  • This is great as you do not need the big programs like eclipse – Alireza Fattahi Sep 09 '13 at 06:43
  • This way is better simply because one can copy the code right from the Word doc instead of having the object open in a new window in order to copy. – coryj Jan 16 '14 at 17:46
  • By using Column Editor (Alt+C) you could add line numbers for code snippets – DocFoster Jan 23 '14 at 20:32
  • This approach completely lacks maintainability. If I change my source code, I want my document to reflect those changes automatically, not have to copy&paste everything all over again. – jub0bs Feb 08 '14 at 02:47
  • 6
    @BennyNeugebauer : Line Number can be added by configure the Format->Numbering options, Define new number formate, remove the dot in first style. You can get to the Format option by either following @ Blazes 's steps OR in style select the new style->manage styles->Modify – Miranda Feb 13 '14 at 07:20
  • I created an openDocument like the top answer suggested, and pasted the code as described in this answer – Yossi Shasho Mar 18 '14 at 09:35
  • For any simple documents with mere code samples this works amazingly beautifully. – Dionisis Karakasiliotis May 05 '17 at 14:25
  • It's worth to notice that it works only with the 32-bit version of Notepad++ – 0x6B6F77616C74 Jun 30 '17 at 13:12
  • 1
    0x6B6F77616C74: It works on 64-bit also. just download `NppExport` form [here](https://github.com/chcg/NPP_ExportPlugin/releases) and put it in c:/Program File/Notepad++/Plugins. Done – Rahul Jul 17 '17 at 13:57
  • For people using other themes there might be a black/brown/etc background which is unwanted when taking a print out of the code. In that case, head over to "Settings" -> "Style Configurator" and choose the Select Theme drop down menu at the top of the popup window. Choose the "Default" theme in it, and you're good to go. – Gaurang Tandon Oct 17 '17 at 11:39
  • Word likes to change characters like quotes and uses false spell checking here. Not a good solution. – Martin Braun Feb 02 '18 at 18:07
  • 1
    Unfortunately, any attempt to overlay a Word Style (such as "Normal + NoProofing") destroys the coloring. – Carl Witthoft Aug 08 '18 at 13:28
  • If this doesn't work for anyone with NppExport 2.8, use this update: https://github.com/chcg/NPP_ExportPlugin/releases/tag/0.2.9.21 – Broper Aug 09 '19 at 15:21
  • 1
    Does not seem to work with notepad++ v7.7 and MS Word 2016 – Maverick Oct 14 '19 at 15:13
173

enter image description here

Code Format Addin is now available in Office Addins with Office 365 ! Just select the code and click convert it and it converts the code text to formatted color code with line numbers !!!

Bit Rejoice!

Code Format is available here: https://appsource.microsoft.com/en-us/product/office/WA104379501?tab=Overview

JohnLBevan
  • 18,988
  • 5
  • 75
  • 151
Rahul Saini
  • 2,065
  • 1
  • 14
  • 19
  • 16
    only post i saw where the answer is an add on in word. easiest solution, this should be the accepted answer in 2017! – cre8 Jul 12 '17 at 08:31
  • 2
    @schauhan It was never meant to remove spelling errors / warnings. The purpose of this plug-in is to format the code with keyword highlights and indents. – Rahul Saini Nov 15 '17 at 00:28
  • This plugin does not handle HTML mixed with JS properly, the output is entirely wrong and not acceptable. – Martin Braun Feb 02 '18 at 18:10
  • 35
    No longer available – user1085907 Nov 15 '18 at 21:05
  • Yes. I downloaded It a month ago, and It stopped working that day. The author removed it I think. Use Content Mixr instead. – DreTaX Dec 01 '18 at 08:13
  • Yes the Word plugin is no longer available @Fahmi has the viable and good solution (as of now) for this. Online Tool : http://www.planetb.ca/syntax-highlight-word – Rahul Saini Dec 03 '18 at 08:54
  • 10
    Found the [Easy Code Formatter](https://appsource.microsoft.com/en-us/product/office/WA104382008?src=office&tab=Overview) at the addon list, worked pretty well. – silveiralexf Mar 29 '19 at 19:02
  • 2
    Alternatively, a word add-in called [Easy Syntax Highlighter](https://appsource.microsoft.com/en-us/product/office/WA200000011?src=office&tab=Overview) provides language-specific highlighting with multiple themes per language and automatic language detection. – JDG Apr 09 '20 at 09:54
  • "404 Not found." – endolith Nov 11 '20 at 22:09
  • Just checked this out. This package is not longer available, but you can add the "Easy Code Formatter" add-on directly in word! – alexrogo Mar 01 '21 at 17:27
  • Easy code formatter or Easy syntax Highlighter has security flaws! > Add-in capabilities: > When this add-in is used, it > Can read and make changes to your document > Can send data over the Internet – DonAriston May 11 '21 at 23:09
132

After reading a lot of related answers, I came across my own solution, which for me is the most suitable one.

Result looks like this: the final result

As you can see, it is the same syntax highlighting like on Stack Overflow which is quite awesome.

Steps to reproduce:

on Stack Overflow

  1. Goto Ask Question (preferably with Chrome)
  2. Paste Code and add a language tag (e.g. Java) to get syntax hightlighting
  3. Copy code from preview

in Word

  1. Insert > Table > 1x1
  2. Paste code
  3. Table Design > Borders > No Border
  4. Select code > Edit > Find > Replace
    Search Document ^p (Paragraph Mark) Replace With ^l (Manual Line Break)
    (This is required to remove the gaps between some lines)
  5. Select code again > Review > Language > check "Do not check spelling or grammar"
  6. Finally add a caption using References > Insert Caption > New Label > name it "Listing" or sth

Sample code thanks to this guy

Community
  • 1
  • 1
monty.py
  • 1,976
  • 1
  • 10
  • 24
114

There is a nice Online Tool for that : http://www.planetb.ca/syntax-highlight-word

Just copy the generated code and paste it in your word editing software. So far I've tried it on MS Word and WPS Writer, works really well. Doesn't play nice with Firefox but works just fine on Chrome (and IE too, but who wants to use that).

One of the main benefits is that, unlike the Code Format Add-In for Word, it does NOT mess with your code, and respects various languages syntax. I tried many other options offered in other answer but I found this one to be the most efficient (quick and really effective).

There is also another onlinz tool quoted in another answer (markup.su) but I find the planetB output more elegant (although less versatile).

Input :

enter image description here

Output :

enter image description here

Mehdi LAMRANI
  • 10,556
  • 13
  • 74
  • 115
Fahmi
  • 2,019
  • 1
  • 17
  • 15
  • 3
    Just to let others know, the output above is also how it will appear in the Word Document with the line numbers and green border and syntax highlighting – mc805 Sep 28 '18 at 17:12
  • 1
    The only downside is if you want to copy and paste the code, you manually have to remove the line numbers. – Steven Spyrka Feb 04 '19 at 14:04
  • 1
    The line numbers are just a normal Word numbered list, so you can remove them easily once copy/pasted into Word by deselecting the numbered list option (Home>Paragraph>Numbering = None). – Violet Jun 09 '20 at 07:59
  • This is the only solution here that worked for me - it's definitely the cleanest looking option! – Jamie Aug 06 '20 at 09:03
  • "This application is currently unavailable" :( – FLonLon Apr 15 '21 at 14:07
  • @FLonLon yep not sure what happened. Apparently his [twitter](https://twitter.com/jamiebeach) is also suspended. – Fahmi Apr 16 '21 at 17:19
65

I type my code in Visual Studio, and then copy-paste into word. it preserves the colors.

Jimmy
  • 81,547
  • 17
  • 114
  • 135
  • 6
    But far from 100% fidelity. The copy process seems to remove a lot of formatting for some reason. – Frank Krueger Dec 22 '08 at 22:31
  • 3
    This works very well with Eclipse and OpenOffice Writer, by the way (I don't know of Eclipse/Word or VisualStudio/Writer, 'though). – Joachim Sauer Jan 07 '09 at 19:58
  • 1
    I wonder if it depends whether you use tabs or have Visual Studio convert tabs to spaces. I don't notice any issues with spaces. – devuxer Nov 19 '09 at 00:58
  • 1
    Using spaces seems to fix any formatting errors. Kind of a pain, but it does work. – shmeeps Feb 25 '12 at 19:40
  • 2
    Works, but since I have a black theme... results illegible. http://blog.wekeroad.com/wp-content/uploads/2007/10/codefile.gif – EdgarT Sep 05 '12 at 12:35
  • As of Office 2013 and VS 2015, this method works (even with the VS Dark theme) – Levi Fuller Sep 01 '15 at 01:18
  • simply disable "Copy As Html" extension if you use a dark theme and want to remove the dark background on WORD. – zagZzig Nov 16 '18 at 02:14
  • This literally does not work for me. There must be a setting that is wrong. – ggcg Jul 21 '20 at 17:33
  • Visual Studio didn't work for me too, but the idea is good and I used MATLAB for this purpose. The colors are preserved. MATLAB requires the file extension to be .c for correct highlighting, however. – Nail Feb 11 '21 at 22:25
31

When I've done this, I've made extensive use of styles. It helps a lot.

What I do is create a paragraph style (perhaps called "Code Example" or something like that) which uses a monospaced font, carefully chosen tabs, a very light grey background, a thin black border above and below (that helps visibility a lot) and with spelling turned off. I also make sure that inter-line and inter-paragraph spacing are set right. I then create additional character styles on top (e.g., "Comment", "String", "Keyword", "Function Name Decl", "Variable Name Decl") which I layer on top; those set the color and whether the text is bold/italic. It's then pretty simple to go through and mark up a pasted example as being code and have it come out looking really good, and this is works well for short snippets. Long chunks of code probably should not normally be in something that's going to go on a dead tree. :-)

An advantage of doing it this way is that it is easy to adapt to whatever code you're doing; you don't have to rely on some IDE to figure out whatever is going on for you. (The main problem? Printed pages typically aren't as wide as editor windows so wrapping will suck...)

Donal Fellows
  • 120,022
  • 18
  • 134
  • 199
  • Thanks Donal for this information. May ask though, how can I use intents to represent nested code lines? If I use a background color and border for my paragraph, when I use indent the whole block is moving. – m.spyratos Nov 15 '12 at 18:04
  • 7
    Would have been nice to share your style/template? – Eric Ouellet May 06 '15 at 13:49
  • Been doing the same for ages - one big bugbear: whenever I apply the style, Word still red-underlines spelling problems. If I modify-style and select Format->Language, "Do not check spelling and grammar" is checked, and if I now close the format dialog with Ok, the lines will go - but they always appear until I do that. – Rhubarb May 20 '19 at 11:28
26

Try defining a style called 'code' and make it use a small fixed width font, it should look better then.

Use CTRL+SPACEBAR to reset style.

shA.t
  • 15,232
  • 5
  • 47
  • 95
frankodwyer
  • 13,712
  • 8
  • 48
  • 70
  • 20
    You won't keep syntax highlighting. – Uri Dec 22 '08 at 21:50
  • 1
    Syntax highlighting is overrated if we're talking a Word document here. But it is also easily implemented in a VB script that colors all text styled as "Code". – Frank Krueger Dec 22 '08 at 21:51
  • That's how I do it too with pretty good results, though I also turn off spelling/grammar checking for my "code" style. – Clayton Dec 22 '08 at 22:18
  • 2
    Of course you can keep syntax highlighting: [Create a Style without a font color](http://superuser.com/questions/360488/word-2010-create-a-style-without-a-font-color) –  Nov 16 '13 at 19:31
24

Maybe this is overly simple, but have you tried pasting in your code and setting the font on it to Courier New?

chaos
  • 115,791
  • 31
  • 292
  • 308
  • 5
    It still won't keep syntax highlighting. – Sk8erPeter Mar 21 '14 at 13:34
  • @Sk8erPeter: That's not necessarily the case. Copy and paste is more than capable of transferring color information -- it does it all the time when I'd rather it didn't. It depends on whether the source and destination applications both support the same schema for specifying it. – chaos Oct 17 '16 at 15:02
23

In case you're like me and are too lazy or in a hurry and don't want to download additional software, you can use http://markup.su/highlighter/. It's very straight forward and supports several highlight themes and many programming languages. http://markup.su/highlighter/In my case I was using Visual Studio Code, which doesn't allow copying with format due to CSS involved in styling (as reported here).

Copy the text from the Preview box and then in Word go to Insert -> Textbox, paste the Preview from the website, highlight all the text, and then disable spell checking for that textbox.

This is what the code looks like finally.code as seen in Word

maaw
  • 978
  • 8
  • 11
  • Is there a way to change the font size? My code is very big and I want to fit it in few pages in word. Changing font size in word doesn't help – dark32 Nov 25 '16 at 03:49
  • Could it be that you're not highlighting the text inside the textbox prior to changing the font size? – maaw Nov 25 '16 at 18:46
  • It changes the font size, but has no effect on the space between lines – dark32 Nov 26 '16 at 01:02
  • 1
    @dark32 if I understand your issue correctly, you need to change the line spacing: https://support.office.com/en-us/article/Change-the-line-spacing-in-Word-1970e24a-441c-473d-918f-c6805237fbf4 – maaw Dec 06 '16 at 18:32
  • 2
    This was working great a week ago, however, as of 12/78/2017 the site http://markup.su/highlighter/ no longer works. Hopefully it will be back up soon. – Gorgon_Union Dec 08 '17 at 03:00
  • 5
    Link is dead again... Just a heads up. – Zombie Chibi XD May 09 '19 at 16:52
22

If you are using Sublime Text, you can copy the code from Sublime to MS Word preserving the syntax highlighting.

Install the package called SublimeHighlight.

In Sublime, using your cursor, select the code you want to copy, right click it, select 'copy as rtf', and paste into MS Word.

Patrick_870206
  • 607
  • 5
  • 12
  • 3
    This worked perfectly for me. Word extension completely messed up my code and comments, making in unreadable. This actually worked perfectly. I'll add that you can simply go to sublime, hit cmd+shift+P, go to `Install package` and type `highlight` there. It'll install it right away – Claud H Feb 21 '18 at 20:47
22

You can just use PlanetB: http://planetb.ca/syntax-highlight-word

Copy and Past, choose the language and enjoy the result.

Guilherme Fidelis
  • 1,036
  • 11
  • 20
18

I'm using Easy Code Formatter. It's also an Office add-in. It allows you to select the coding style / and has a quick formatting button. Pretty neat.

enter image description here

Mavi Domates
  • 3,886
  • 2
  • 15
  • 39
  • This seems cool but no way to install it in my word 2016... Error from word all time – Jebik Jun 24 '19 at 13:08
  • @Jebik - if you're using a company account, perhaps your admin might have blocked the installations? I'm using it on 2016...What's your build number? – Mavi Domates Jun 25 '19 at 10:08
  • I had the version 16.0.4849.1000. But as i said i have install 2 other supplément. So my compagny don't seem to block installation. It's jsut this extension i can't install. I don't even find it in store to be honest. From word when i open store and look for app this one is not in list – Jebik Jun 26 '19 at 07:48
  • That means your Word is in a build version that doesn’t support this addin. – Mavi Domates Jun 26 '19 at 07:49
  • Try updating word if you can, your version seems a bit old. – Mavi Domates Jun 26 '19 at 07:50
  • If somebody want to disable spell check, then : https://superuser.com/a/256258/681618 – Number945 Nov 08 '20 at 13:35
13

The best way what I found is by using the table.

Create a table with 1x1. Then copy the code and paste it.
If you're using the desktop app then it will inherit the code editor theme color and paste it accordingly, else you can change the table style to any colour.

enter image description here

Shubham Chadokar
  • 1,286
  • 12
  • 34
12

This is a bit indirect, but it works very nicely. Get LiveWriter and install this plugin:

http://lvildosola.blogspot.com/2007/02/code-snippet-plugin-for-windows-live.html

Insert your code using the plugin into a blog post. Select all and copy it to Word.

It looks great and can include line numbers. It also spans pages decently.

HTH

Colby Africa

Colby Africa
  • 1,316
  • 9
  • 13
11

In my experience copy-paste from eclipse and Notepad++ works directly with word.

For some reason I had a problem with a file that didn't preserve coloring. I made a new .java file, copy-paste code to that, then copy-paste to word and it worked...

As the other guys said, create a new paragraph style. What I do is use mono-spaced font like courier new, small size close to 8px for fonts, single spaced with no space between paragraphs, make tab stops small (0.5cm,1cm,..,5cm), put a simple line border around the text and disable grammar checks. That way i achieved the line braking of eclipse so I don't have to do anything more.

Hope I helped ;)

Dimitrios K.
  • 941
  • 12
  • 31
11

Vim has a nifty feature that converts code to HTML format preserving syntax highlighting, font style, background color and even line numbers. Run :TOhtml and vim creates a new buffer containing html markup.

Next, open this html file in a web browser and copy/paste whatever it rendered to Word. Vim tips wiki has more information.

Gowtham
  • 1,405
  • 1
  • 15
  • 24
11

This is the simplest approach I follow. Consider I want to paste java code.

  1. I paste the code here so that spaces, tabs and flower brackets are neatly formated http://www.tutorialspoint.com/online_java_formatter.htm

  2. Then I paste the code got from step 1 here so that the colors, fonts are added to the code http://markup.su/highlighter/

  3. Then paste the preview code got from step 2 to the MS word. Finally it will look like this

enter image description here

Siddarth Kanted
  • 5,182
  • 1
  • 26
  • 19
10

You can use VS code to keep code format and highlighting. Directly copy and paste code from VS.enter image description here

Capan
  • 574
  • 10
  • 25
9

Answer for people trying to resolve this issue in 2019:

Most answers to this question are outdated by now. I wish there was a way to reinspect old questions and answers every now and then!

The method I found for this question that works with Office 365 and its associated programs can be found here.

RFNO
  • 329
  • 2
  • 11
  • I think it is suggested that some description from the link be added to the answer text in case the link dies eventually. https://meta.stackexchange.com/a/8259 – Chintan Pathak Oct 24 '20 at 01:00
8

I'm using Word 2010 and I like copying and paste from a github gist. Just remember to keep source formatting!

I then change the font to DejaVu Sans Mono.

You can opt to copy with or without the numbering.

bluekeys
  • 2,117
  • 1
  • 20
  • 28
7

Use a monospaced font like Lucida Console, which comes with Windows. If you cut/paste from Visual Studio or something that supports syntax highlighting, you can often preserve the colour scheme of the syntax highlighter.

ConcernedOfTunbridgeWells
  • 59,622
  • 15
  • 138
  • 193
7

Copying into Eclipse and paste it in Word is also another option.

imesh
  • 934
  • 1
  • 11
  • 17
6

I was also looking for it and ended up creating something for my code display. Here's a good way:

  • Create a rectangular form and place your text inside.
  • Change the font to Consolas and size ~10.
  • Change the text font to gray near-black (gray 25%, darker 75%)
  • Use darker colors to highlight your text if needed and choose one to be the contour.

enter image description here

Pedro Lourenço
  • 593
  • 6
  • 14
6

If you are using Intellij IDEA, just copy the code from the IDE and paste it in the word document.

Joe Cheng
  • 6,546
  • 3
  • 23
  • 23
6

You can also use SciTE to paste code if you don't want to install heavy IDEs and then download plugins for all the code you're making. Simply choose your language from the language menu, type your code, high-light code, select Edit->Copy as RTF, paste into Word with formatting (default paste).

SciTE supports the following languages but probably has support for others: Abaqus*, Ada, ANS.1 MIB definition files*, APDL, Assembler (NASM, MASM), Asymptote*, AutoIt*, Avenue*, Batch files (MS-DOS), Baan*, Bash*, BlitzBasic*, Bullant*, C/C++/C#, Clarion, cmake*, conf (Apache), CSound, CSS*, D, diff files*, E-Script*, Eiffel*, Erlang*, Flagship (Clipper / XBase), Flash (ActionScript), Fortran*, Forth*, GAP*, Gettext, Haskell, HTML*, HTML with embedded JavaScript, VBScript, PHP and ASP*, Gui4Cli*, IDL - both MSIDL and XPIDL*, INI, properties* and similar, InnoSetup*, Java*, JavaScript*, LISP*, LOT*, Lout*, Lua*, Make, Matlab*, Metapost*, MMIXAL, MSSQL, nnCron, NSIS*, Objective Caml*, Opal, Octave*, Pascal/Delphi*, Perl, most of it except for some ambiguous cases*, PL/M*, Progress*, PostScript*, POV-Ray*, PowerBasic*, PowerShell*, PureBasic*, Python*, R*, Rebol*, Ruby*, Scheme*, scriptol*, Specman E*, Spice, Smalltalk, SQL and PLSQL, TADS3*, TeX and LaTeX, Tcl/Tk*, VB and VBScript*, Verilog*, VHDL*, XML*, YAML*.

Joseph Coco
  • 364
  • 4
  • 11
  • Doesn't work when pasting PHP code. Only the start and end brackets are highlighted :( Worked fine for Java though. – Ren Mar 26 '13 at 16:10
5

There really isn't a clean way to do it, and it could still look fishy based on your exact style settings.

What you could try to do is to first run a code-to-HTML conversion (there are many programs that do that), and then try to open up the HTML file with word, that might hopefully provide you with the formatted and pretty code, and then copy and paste it into your document.

Uri
  • 84,589
  • 46
  • 214
  • 312
5

I have created an easier method using tables, as they are easier to create, manage, and more consistent (with the possibility to save the table's style inside the document itself), but I couldn't find a better way for code colouring scheme, sorry for that.

Steps:

  1. Create a 3x3 table.

  2. Select the table, and make its borders invisible ("No Borders" option), and activate "View Gridlines" option. enter image description here

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

  4. Create a "Paragraph Style" with the name of "Code" just for your code snippets (as mentioned in https://stackoverflow.com/a/25092977/8533804)

  5. Create another "Paragraph Style" with the name of "Code_numberline" that will be based upon the previous created style, but this you will add a numbering line in its definition (this will automate line numbering). enter image description here

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

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

  8. Save that table style and enjoy!

Nader Belal
  • 125
  • 1
  • 9
4

If you are using Android Studio, you can simply copy and paste, and the code aspect is going to be preserved and the colors as well. Simple enough!

Geraldo Neto
  • 2,864
  • 1
  • 22
  • 26
4

The best presentation for code in documents is in a fixed-width font (as it should appear in an IDE), with either a faint, shaded background or a light border to distinguish the block from other text.

Rob
  • 46,632
  • 4
  • 70
  • 91
4

If its Java source code copy it to Visual Studio and then copy it back to Word.

imesh
  • 934
  • 1
  • 11
  • 17
4

A web site for coloration with lots of languages. http://hilite.me/

You can host one yourself since it is open source. The code is on github.

Ognyan Dimitrov
  • 5,392
  • 1
  • 40
  • 64
4

Ok, this is weird, but to address the background color issue I paste in the text as normal, select the whole block, click on the highlighter tool to highlight (even if the highlight is set to "No Color"), and then I can style the text block without the background color of the text remaining white. I am using VS 11 and Word 2010, but the problem has been around for a long time (see http://www.visualstudiodev.com/visual-studio-setup-installation/copypaste-code-from-vs-1305.shtml)

JMBT
  • 41
  • 1
3

From Powershell ISE copy and paste to Word.
Same with Visual Studio.

Andrei Karcheuski
  • 2,546
  • 3
  • 33
  • 38
3

I've read and tried all the posts and I would like to give an overview of all the solutions. The best way is depending on your requirements. If there are only short snippets that are not longer than a page then go with Insert Object. If the code is longer than one page go with RTF Formatting.

Insert Textbox

  • No page break possible
  • Spell check available
  • Formatting can be ruined very quickly
  • In a document with thousands of pages Word 2016 started to make problems. At some point Word always crashed while trying to insert a new Textbox.

Insert Object > Document

  • No page break possible
  • No spell check
  • Formatting and content stays safe

RTF Formatting

Or any other wysiwyg-editor/online tool/library to style the code.

Some plug-ins/add-ons

All down or doesn't work anymore.

Steven Spyrka
  • 668
  • 7
  • 18
2

Just paste your code in MS Words, select it -> then right click -> Numbering. In this case MS Word will interpret your code as marker/numbered list.

Here is the screens:

Screen1.

Screen2.

Code Lღver
  • 15,171
  • 16
  • 51
  • 71
user3528865
  • 61
  • 1
  • 6
2

If you're using TextMate (On OS X), use the "copy as rtf" command. It will place pretty-printed text onto the clipboard. rtf command

From there you can paste into word or anything else.

tim
  • 3,104
  • 27
  • 40
2

A quick approach I use is to use the Snipping Tool (already built in Microsoft tool) with stack overflow's preview.

Once I input my code into an Ask Question box, I then capture the preview and insert it into the MS Word document as a picture.

enter image description here

This above is the result, a picture, (not SO code ) you can put into word.

No worries about formatting, grammar checks, or downloading new software or add-ins!

Chabo
  • 2,119
  • 2
  • 13
  • 28
1

If you already have the document created with plenty of code snippets in it and you are racing against time (as I unfortunately was). Save the file as a .doc as opposed to .docx and voila! Worked for me. Phew!

NOTE: Obviously your document can't have fancy features from > word 2007.

NOTE 2: File size becomes bigger if this is a concern to you.

EaziLuizi
  • 1,509
  • 16
  • 25
1

Simplest solution, for me atleast, is to paste your code into the document, highlight it, then navigate to:

home -> styles -> << click drop down arrow by styles >> -> code

This has the advantage that the code is now searchable within the document (unlike gargamel's solution), as well as being able to format code that is multiple pages.

Luke Purnell
  • 346
  • 2
  • 8
1

Simply right click and paste using the "Keep Source Formatting" option. I do this almost everyday to document my work. Further, you can set the 'default paste' for pasting from various soures in File/Options/Advanced/Cut,CopyPaste. Also useful: enable "Show paste options" in the same section of Word Options.

Note that all of the text properties from your Code Editor's theme (colors, fonts, etc.) will be added to the Stylesheet in your Word doc, so I would recommend that you not make any changes directly to the pasted text as that will add clutter to your stylesheet and subsequent pastes will not match. It will be to your great advantage to do a quick study on using 'Styles' in Word (which are actually CSS). They are very powerful. Using Word's Stylesheet you can make global changes to the pasted text, but it will probably cause subsequent pasted text to add new styles.

Mitch
  • 595
  • 1
  • 7
  • 13
1

You can paste your code into LINQPad. Then copy from LINQPad into MS Word. LINQPad supports following programming languages: C#, VB, SQL, ESQL and F#

Edward Olamisan
  • 1,192
  • 1
  • 14
  • 22
0

Hilite doesn't seem to be mentioned yet in the answers, so: Hilite supports lots of languages (20+), can be used online also via API, and is on Github (so you can clone, modify, and run it on your own if you don't trust the online service). The online version can also be adjusted to one's needs via CSS rules.

I just found it some minutes ago since I needed a tool for copying xQuery into Word, but couldn't find a proper tool for doing so. The source program is baseX and for some reason, its formatting could not be transmitted to Word (also not via Keep format etc. when pasting). Also, many of the given answers are now, i.e. 06/2019, not working anymore or do not support xQuery. Hilite, however, did the job quite well.

Edit: a code block is not part of the result, unfortunatelly, just the highlighting. Nevertheless, it's better than nothing and adjusting the result by adding a block around is still less work than formating every single line by hand

meistermuh
  • 291
  • 1
  • 8
-1

you can simply use this Add-in on any office program.

Go to insert tab, then Get Add-ins, and search for Easy Syntax Highlighter

It supports

  • 185 languages and 89 themes.

  • Automatic language detection.

  • Multi-language code highlighting.