ChatGPT解决这个技术问题 Extra ChatGPT

How do you display code snippets in MS Word preserving format and syntax highlighting?

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.

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" plugin to do this in PhpStorm, WebStorm, PyCharm is awsome!
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 !!
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.
Code Format is unavailable - but Easy Code Formatter here works pretty well: appsource.microsoft.com/en-us/product/office/…
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.

P
PSEUDO

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

Go to Insert tab, Text section, click Object button (it's on the right) Choose OpenDocument Text which will open a new embedded word document Copy and paste your code from Visual Studio / Eclipse inside this embedded word page 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.


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 :-)
Please note tath this requires open/libre office to be installed on your machine.
@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: en.wikipedia.org/wiki/OpenDocument
Can't see that option on Word 2011 on OSX :(
For Word 2011 on OSX use: Insert -> Object...Microsoft Word Document
r
root-11

Download and install Notepad++ and do the following:

Paste your code in the window; Select the programming language from the language menu; Select the text to copy; Right click and select Plugin commands -> Copy Text with Syntax Highlighting; 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.

https://i.stack.imgur.com/woIcU.jpg


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.
Thanks for this hint. Plugins -> NppExport -> Copy RTF to Clipboard also works.
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.
This one works great, couldn't get the Word Document inside the Word Document to play nice. Folks this is the way to go!
@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
J
JohnLBevan

https://i.stack.imgur.com/Fz9Fd.jpg

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


only post i saw where the answer is an add on in word. easiest solution, this should be the accepted answer in 2017!
@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.
No longer available
Found the Easy Code Formatter at the addon list, worked pretty well.
Alternatively, a word add-in called Easy Syntax Highlighter provides language-specific highlighting with multiple themes per language and automatic language detection.
D
Dexter Legaspi

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

https://i.stack.imgur.com/Qik8H.jpg

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

Steps to reproduce:

on Stack Overflow

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

in Word

Insert > Table > 1x1 Paste code (you may need to use Paste Special... > Formatted Text (RTF) from the Edit menu to not lose the syntax hilighting) Table Design > Borders > No Border 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) Select code again > Review > Language > check "Do not check spelling or grammar" Finally add a caption using References > Insert Caption > New Label > name it "Listing" or sth

Sample code thanks to this guy


To add line numbers, you could insert a column to the left and include all line numbers in one cell.
This is my favorite answer, because it allows people reading the document to copy/paste the code.
Under this approach, the code will be labeled as a table when doing auto-captioning.
Loses the pretty syntax highlighting for me on macOS big sur Word 16.50
@spartygw make sure you use "Paste Special -> Formatted Text (RTF)"
G
Golden

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

↑ this app is not available anymore since 2020, here's a new fork tool: https://www.troye.io/planetb/

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 :

https://i.stack.imgur.com/mlfmm.png

Output :

https://i.stack.imgur.com/ByCak.png


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
The only downside is if you want to copy and paste the code, you manually have to remove the line numbers.
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).
This is the only solution here that worked for me - it's definitely the cleanest looking option!
"This application is currently unavailable" :(
J
Jimmy

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


But far from 100% fidelity. The copy process seems to remove a lot of formatting for some reason.
This works very well with Eclipse and OpenOffice Writer, by the way (I don't know of Eclipse/Word or VisualStudio/Writer, 'though).
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.
Using spaces seems to fix any formatting errors. Kind of a pain, but it does work.
Works, but since I have a black theme... results illegible. blog.wekeroad.com/wp-content/uploads/2007/10/codefile.gif
D
Donal Fellows

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...)


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.
Would have been nice to share your style/template?
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, add the "no check" attribute to your style. This works but is a fair amount of work if you want to maintain colors.
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
c
chaos

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


It still won't keep syntax highlighting.
@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.
*** 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.
P
Patrick_870206

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.


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
Higlight is working fine, however the format is getting messed up.
Or just say "copy as HTML" in the edit menu
s
shA.t

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.


You won't keep syntax highlighting.
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".
That's how I do it too with pretty good results, though I also turn off spelling/grammar checking for my "code" style.
Of course you can keep syntax highlighting: Create a Style without a font color
M
Mavi Domates

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.

https://i.stack.imgur.com/OxEwO.png


This seems cool but no way to install it in my word 2016... Error from word all time
@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?
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
That means your Word is in a build version that doesn’t support this addin.
Try updating word if you can, your version seems a bit old.
m
maaw

https://i.stack.imgur.com/scFrH.png

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.

https://i.stack.imgur.com/BNSdu.png


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
Could it be that you're not highlighting the text inside the textbox prior to changing the font size?
@dark32 if I understand your issue correctly, you need to change the line spacing: support.office.com/en-us/article/…
This was working great a week ago, however, as of 12/78/2017 the site markup.su/highlighter no longer works. Hopefully it will be back up soon.
Link is dead again... Just a heads up.
S
Shubham Chadokar

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.

https://i.stack.imgur.com/F5FlN.png


This does not copy colors from vba. May work with other languages.
Never tried VBA. But it depends on IDE theme. Try to change the theme and then paste it.
Yeah. thanks you very much! Just create table 1x1, copy code from VSCode. Done!
C
Colby Africa

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


Requires account on Windows Live or Wordpress or some other of 10 blogging platforms.
G
Gowtham

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.


D
Dimitrios K.

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 ;)


S
Siddarth Kanted

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

I paste the code here so that spaces, tabs and flower brackets are neatly formated http://www.tutorialspoint.com/online_java_formatter.htm Then I paste the code got from step 1 here so that the colors, fonts are added to the code http://markup.su/highlighter/ Then paste the preview code got from step 2 to the MS word. Finally it will look like this

https://i.stack.imgur.com/9WW8s.png


C
Capan

https://i.stack.imgur.com/rNQTi.png


This one i found smartest answer for this question. Thanks!
R
RFAI

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.


I think it is suggested that some description from the link be added to the answer text in case the link dies eventually. meta.stackexchange.com/a/8259
b
bluekeys

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.


i
imesh

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


M
Marawan Mamdouh

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.


This works in MS Word online too. Thanks a lot.
You're welcome.
WARNING (not only just a waste of time) Asks for your phone number and other personal information and then sends you to a broken link
Skip the link, Just go to the insert tab in the office program you use, then click Get Add-ins, and search for "Easy Syntax Highlighter" and add it. @RobHoff
C
ConcernedOfTunbridgeWells

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.


J
Joe Cheng

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


J
Joseph Coco

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*.


Doesn't work when pasting PHP code. Only the start and end brackets are highlighted :( Worked fine for Java though.
P
Pedro Lourenço

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.

https://i.stack.imgur.com/cCmAX.png


O
Ognyan Dimitrov

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.


hilite.me also works on Google docs!
U
Uri

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.


N
Nader Belal

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:

Create a 3x3 table. Select the table, and make its borders invisible ("No Borders" option), and activate "View Gridlines" option. 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). Create a "Paragraph Style" with the name of "Code" just for your code snippets (as mentioned in https://stackoverflow.com/a/25092977/8533804) 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). Apply "Code_numberline" to the first column, and "Code" to the 3 column. Add a fill in the middle column. Save that table style and enjoy!


If you copy and paste code you have to manually split lines to the rows.
Last time I used this method, I didn't have to. May be you need to select various rows.
R
Rob

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.