开发者

How can I output .doc files with bolded and colored text

I need to output text to a .doc file. I am currently just outputting to a file like usual and using a .doc at the end of the file name

开发者_如何学GoFile.open('output_file.doc', 'a+') {|x| x.write(str)}

The issue is I want to make some of the text red and bold. How can this be achieved? I am using ruby, but I can easily switch to jruby thanks to the amazingness that is rvm, so if there are java libraries for this, that'd be great as well.


The short answer: use .rtf and then convert to .doc using word or open office. The following .rtf file (writes "normal text red text more normal text." and colors and bolds the red text):

{\rtf1\ansi\ansicpg1252\cocoartf1038\cocoasubrtf350 {\fonttbl\f0\fswiss\fcharset0 Helvetica;} {\colortbl;\red255\green255\blue255;\red255\green0\blue0;} \margl1440\margr1440\vieww13280\viewh10420\viewkind0 \pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural\pardirnatural

\f0\fs24 \cf0 normal text \b \cf2 red text \b0 \cf0 more normal text.}

The long answer:

Strings are just plain ascii text, so there is no command that can make them bold. This is a property of all files in general, not just how Ruby works with files.

What text-editors do is use key strings within the file as commands to render the text in a certain way. For example, double asterisk surrounds bold text in the Stack Overflow editor. The file format of a file determines these rules.

.rtf is a basic file format that has the features you want and is easy to convert to .doc using msword or open office. THe advantage to .rtf is that it is human readable. So you can write an rtf file with red text, rename it .txt and open in a text editor and see what "decorations" the red font added. Play around with the parameters

If you are curious, the complete .rtf specifications can be found here: http://www.biblioscape.com/rtf15_spec.htm

What's all the garbage at the top? That is header stuff. Fortunately you don't need to add more header material to add more text.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜