2657

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.

ashleedawg
  • 20,365
  • 9
  • 72
  • 105
Lawrence Barsanti
  • 31,929
  • 10
  • 46
  • 68
  • 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
  • 10
    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
  • Also the Easy Code Formatter is not working anymore. – westr Sep 02 '21 at 11:46
  • https://syntax-highlighter.k26.ch/ This site works great! – Nicicalu Mar 21 '22 at 12:18

44 Answers44

2675

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

Advantages

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.

PSEUDO
  • 113
  • 4
  • 13
gargamel
  • 26,918
  • 1
  • 17
  • 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
  • 31
    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
  • 17
    @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
  • 64
    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
  • 58
    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
  • 8
    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 – Furkan Gözükara 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
  • 15
    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
  • 4
    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. – laker93 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
  • 4
    any hints on how to include line numbers with this solution? – Sip Jun 22 '18 at 09:31
  • 3
    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 – Yogi Oct 23 '19 at 00:09
  • 1
    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
  • 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à! – Artfaith Oct 21 '20 at 11:27
  • 1
    I get an error in Word 2021 on Windows requiring installation of OfficeLibre. – Charles Kenyon Jan 24 '22 at 16:04
  • 2
    *** IMPORTANT for VS users: A LOT of these answers work. HOWEVER, Most will NOT work if you don't have correct options set in Visual Studio. In order to copy COLOR coding from Visual studio, you need to go to ***Tools > Option > Text Editor > Advanced > make sure the 'Copy rich text on copy/cut' check box is selected***. Once you do this, pretty much any of the answers to this question work. – Fractal Jan 24 '22 at 17:40
  • 1
    In Sublime text there is an option to copy as HTML in the edit menu (note you need to select your language in the view menu first). This is useful if you don't use Eclipse or MS code editing tools. – geneorama Mar 21 '22 at 19:16
  • Using this method with the NotePad++ method was optimal! – iinertiaii Jul 20 '22 at 15:44
  • I like the outcome, but it has a great contra: it can't be easily copy-pasted while this would be very useful in case I need to write a guide with come command line. – Andrea de'Rose Sep 05 '22 at 08:22
  • https://syntax-highlighter.k26.ch After some tweaking I was able to get the site working again. – Nicicalu May 24 '23 at 19:40
1213

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,727
  • 1
  • 19
  • 33
Saad
  • 13,269
  • 1
  • 19
  • 12
  • 10
    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
  • 98
    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
  • 37
    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
  • 3
    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 Code 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 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 – Mzq 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
  • In Word, paste with "keep source formatting". The code will look even better if we change the default font from "Courier New" to "Consolas". – Feiming Chen Jun 30 '22 at 14:13
  • Using the text object with this method is optimal. – iinertiaii Jul 20 '22 at 15:45
  • When I started reading this answer I expected it to continue as "Download Notepad++... and use it instead of Word". – chessofnerd Jun 16 '23 at 07:02
164

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 (you may need to use Paste Special... > Formatted Text (RTF) from the Edit menu to not lose the syntax hilighting)
  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

Dexter Legaspi
  • 3,192
  • 1
  • 35
  • 26
monty.py
  • 2,511
  • 1
  • 17
  • 29
155

There is a nice Online Tool for that : https://www.troye.io/planetb/

Just copy the generated code and paste it into 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 answers but I found this one to be the most efficient (quick and really effective).

There is also another online 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

Menuka Ishan
  • 5,164
  • 3
  • 50
  • 66
Fahmi
  • 2,607
  • 1
  • 20
  • 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
  • 2
    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
  • 2
    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
  • This works as expected, however, it is not possible to copy and reuse the code in word document in a straight way. – sancelot Nov 25 '21 at 09:16
  • This site does not have JSON. For JSON, I use http://www.bodurov.com/JsonFormatter/ – Jay Imerman Feb 23 '22 at 22:11
  • @Fahmi Troye.io also seems down. This one is working: https://syntax-highlighter.k26.ch/ – Nicicalu Mar 21 '22 at 12:16
  • @Violet When I apply your suggesting, Home>Paragraph>Numbering = None to undo the numbering, the entire formatting is lost. I want to remove the numbering but not the formatting. – JohnC Jun 27 '22 at 18:43
  • This is absolutely fantastic. For a part time coder like me, this gets the documentation process breeze. – Apricot Nov 23 '22 at 01:49
  • @FLonLon This one works: https://syntax-highlighter.k26.ch – Nicicalu May 24 '23 at 19:41
  • 3
    site no longer working. – Vicer Aug 07 '23 at 03:53
90

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

Jimmy
  • 89,068
  • 17
  • 119
  • 137
  • 9
    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
  • 3
    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. –  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
  • In case you have a dark theme in VScode, then create one-cell table in MS-word, assign it a dark-grey backgroud (e.g. 25% of white, that is almost black) and paste code there – Ruslan Zhomir Aug 17 '21 at 16:33
32

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
  • 133,037
  • 18
  • 149
  • 215
  • 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
  • 8
    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
  • @Rhubarb, add the "no check" attribute to your style. This works but is a fair amount of work if you want to maintain colors. – Charles Kenyon Jan 24 '22 at 16:33
  • Copy from Visual Studio/SSMS/Notepad++ to get the colours. Then make and save this style in word: Font: (Default) Consolas, 9.5 pt, Do not check spelling or grammar, Indent: Left: 2.54 cm Right: 2.54 cm Line spacing: single, Space Before: 16 pt After: 16 pt, Don't add space between paragraphs of the same style, Level 9 Pattern: Clear (Custom Color(RGB(242,242,242))), Don't adjust space between Latin and Asian text, Don't adjust space between Asian text and numbers, Style: Linked, Automatically update, Show in the Styles gallery Based on: Normal – pholcroft Jun 08 '22 at 09:35
30

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
  • 4,262
  • 2
  • 26
  • 45
  • 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
28

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

chaos
  • 122,029
  • 33
  • 303
  • 309
  • 9
    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
  • *** IMPORTANT*** for VS users: A LOT of these answers work. HOWEVER, Most will NOT work if you don't have correct options set in Visual Studio. In order to copy COLOR coding from Visual studio, you need to go to ***Tools > Option > Text Editor > Advanced > make sure the 'Copy rich text on copy/cut' check box is selected***. Once you do this, pretty much any of the answers to this question work. – Fractal Jan 24 '22 at 17:41
27

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
  • 16,580
  • 5
  • 54
  • 111
frankodwyer
  • 13,948
  • 9
  • 50
  • 70
  • 21
    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
26

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 G.
  • 697
  • 7
  • 13
  • 4
    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 – vladli Feb 21 '18 at 20:47
  • Higlight is working fine, however the format is getting messed up. – AndroidDev Nov 02 '21 at 08:03
  • Or just say "copy as HTML" in the edit menu – geneorama Mar 21 '22 at 19:14
24

The best way 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 color.

enter image description here

UPDATE ------------------

From Word 2021, you can directly paste the code and it will preserve the formatting. No need to create the table. Thank you @RdC1965 for mentioning this.

Shubham Chadokar
  • 2,520
  • 1
  • 24
  • 45
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
  • 1,276
  • 13
  • 13
  • 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
13

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,465
  • 1
  • 15
  • 26
13

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,356
  • 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.
  • 1,008
  • 13
  • 36
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,738
  • 1
  • 29
  • 20
10

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

Capan
  • 686
  • 1
  • 14
  • 32
10

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.

Marawan Mamdouh
  • 584
  • 1
  • 6
  • 15
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.

RFAI
  • 459
  • 4
  • 17
  • 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

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
  • 64,444
  • 15
  • 143
  • 197
7

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,217
  • 1
  • 22
  • 30
7

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

imesh
  • 1,374
  • 1
  • 15
  • 18
6

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

Joe Cheng
  • 8,804
  • 3
  • 26
  • 25
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
  • 404
  • 6
  • 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
6

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
  • 6,026
  • 1
  • 48
  • 70
5

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
  • 605
  • 7
  • 16
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
  • 88,451
  • 51
  • 221
  • 321
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
  • 157
  • 3
  • 10
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
  • 3,670
  • 1
  • 30
  • 33
4

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

Andrei Karcheuski
  • 3,116
  • 3
  • 38
  • 39
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
  • 47,999
  • 5
  • 74
  • 91
4

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

imesh
  • 1,374
  • 1
  • 15
  • 18
4

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
  • 678
  • 7
  • 18
4

For people looking for a tool in 2023. Here's a tool which works with Word 2016 and 2019.

https://syntax-highlighter.k26.ch/

I made it, because there were many tools like it and all of them were going offline or stopped working. If you have feedback or problems, please create a GitHub issue. It's also very simple, small and fits into one HTML file. You can download or clone the repo and host it yourself.

Nicicalu
  • 759
  • 7
  • 16
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

Create a 'code' style. To do this:

  1. In 'Home' tab in the 'Styles' box, click drop down arrow and 'Create a Style'
  2. name it 'code'
  3. click Modify
  4. Format

Then format as you wish (suggested options)

  1. Paragraph -> Line and Page Breaks -> Keep lines together
  2. Border -> Shading -> Fill -> grey

Then once your code style has been created. 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.

laker93
  • 498
  • 4
  • 9
  • And which style(s) do you recommend? – JohnC Jun 27 '22 at 18:44
  • seems that the code style is not a default style. You can however create a code style yourself. For example, you may choose the following options: 1. click drop down arrow and 'Create a Style'. 2. name it 'code'. 3.click modify. 4. Format 5. paragraph -> wrap 6. border -> shading -> fill grey. – laker93 Mar 02 '23 at 10:24
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,573
  • 16
  • 56
  • 75
user3528865
  • 71
  • 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,559
  • 1
  • 33
  • 46
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,842
  • 3
  • 17
  • 32
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,557
  • 1
  • 16
  • 25
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
  • 641
  • 1
  • 10
  • 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
  • 800
  • 1
  • 18
  • 28
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
  • 393
  • 3
  • 11
0
  • What I do is I use Google Backup and Sync and put the docx file in the folder that syncs with Google Drive.
  • Then Open the file in chrome as google drive has functionality to parse docx file.
  • Then run this plugin https://workspace.google.com/marketplace/app/code_blocks/100740430168 which formats the code in different languages with good theme.
  • Once done save it and open the docx file in the system once it is synced.
Rohit Salecha
  • 893
  • 11
  • 9