Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Edit Word Documents using Java
Edit Word Documents using Java
1. Java API for Editing Word Documents
2. Edit Word Documents using Java
//Input file
String inputFilePath = "C:\\Files\\Sample.docx";
//Load the document with load options
WordProcessingLoadOptions wordLoadOptions = new WordProcessingLoadOptions();
wordLoadOptions.setPassword("some password"); // Password if required
Editor editor = new Editor(inputFilePath, wordLoadOptions);
// Specify Edit Options
WordProcessingEditOptions editOptions = new WordProcessingEditOptions();
editOptions.setEnableLanguageInformation(true);
editOptions.setEnablePagination(true);
//Open input document to edit
EditableDocument beforeEdit = editor.edit(editOptions);
//Grab document content and associated resources from editable document
String content = beforeEdit.getContent();
List<IImageResource> images = beforeEdit.getImages();
List<FontResourceBase> fonts = beforeEdit.getFonts();
List<CssText> stylesheets = beforeEdit.getCss();
//Get document as a single base64-encoded String, where all resources (images, fonts, etc) are embedded inside this String along with main textual content
String allEmbeddedInsideString = beforeEdit.getEmbeddedHtml();
//Edit the content
String allEmbeddedInsideStringEdited = allEmbeddedInsideString.replace("Subtitle", "Edited subtitle");
//Create a new EditableDocument instance from edited content and resources
EditableDocument afterEdit = EditableDocument.fromMarkup(allEmbeddedInsideStringEdited, null);
//output document path
String outputPath = "C:\\Files\\Sample_output.docx";
//Save options
WordProcessingSaveOptions saveOptions = new WordProcessingSaveOptions(WordProcessingFormats.Docx);
//Finally, save to path
editor.save(afterEdit, outputPath, saveOptions);
//Dispose the objects
beforeEdit.dispose();
afterEdit.dispose();
editor.dispose();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment