Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically search + replace in a .doc

If I'm given a .doc file with special tags in it such as [first_name], how do I go about replacing all occurrences of it with something like "Clark"? A simple binary replacement only works if the replacement string is the exact same length.

Haskell, C, and C++ answers would be best, but any compiled language would do. I'd also prefer to do this without an external library since it has to be deployed on Windows and Linux and cross-platform dependency handling is a bitch.

To summarize...

.doc -> magic program -> .doc with strings replaced
like image 789
Clark Gaebel Avatar asked Aug 09 '26 06:08

Clark Gaebel


2 Answers

You could use the Word COM component ("Word.Application") on Windows to open the file, do the replacements, save the file, and close it. However, this is Windows-only and can be buggy.

Another thing you could do is use the OpenOffice.org command line interface to convert the file to the ODF format, unzip the file (ODF is mostly zipped XML), do the replacements with the files inside, re-zip the file, and re-convert it to .doc format. However, OpenOffice.org doesn't always read Word files correctly (especially if there is a lot of complex formatting) and it can make it harder to distribute (users must either have OpenOffice.org or you must distribute it with your program).

Also, if you have a file in the .docx format, you can unzip it, do the replacements, and re-zip it.

like image 59
jhartz Avatar answered Aug 10 '26 22:08

jhartz


First read the Word Document Specification.

If that hasn't terrified you, then you should find it fairly straightforward to figure out how to read and write it. It must be possible; Word manages to do it most of the time.

like image 30
Mike Seymour Avatar answered Aug 10 '26 20:08

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!