Unfortunately, I don't think, that you will be able easily to read and edit a word file (
.docx my assumption) by means of the native apex. It definitely contains some workarounds.
The reason for that is
.docx is not just a plain text file, actually, it is an archive file with folders, subfolders, and mainly
.xml files. Just try to open
.docx file by means of any archive software, you'll be surprised to see something like this:
word here is the main folder, which actually stores the content:
A big problem? Yes, very big, but not the end of the world. Here are steps which you need to perform:
- Get the blob of the file (no problems)
- Unarchive blob of
docx file (problem, apex do not have native support to work with archive files)
- Find the correct
.xml file of the
word folder, where is stored text which you would like to edit. (could be very tricky, but pay attention to the
- Replace found text with desired.
- Archive this file back with done changes (problem).
- Save the file as a blob to the custom object record.
Which possible workarounds can we have:
(2) if your code is running only on the back-end without UI interaction, you can try to use
Zippex (Video), (GitHub). This is an open-source library to work with archives in apex. If you do have UI-interaction, you can try to use
jszip (How to use JSZip). It works with lwc.
(3) I recommend you manually to find peace of the file which should be replaced and to find some dependency, some specific combination of
xml tags. You can use native
xml apex parsers to find the location of text which should be replaced. You just need to find it and determine the rule.
(5) You can still try to use
jszip for making an archive of the updated files.
That's it. Not very easy, but with big workarounds it is possible.
To be honest, I don't like this solution natively in Apex. It is better to find another one. For example, you can send this file to the external API, whereby means of other programming languages you can easily work with
.docx files (there are already available libraries for that,
python-docx for python), update it according to needs externally, and just save the response of this request in salesforce.