Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve API #6

Open
urechm opened this issue Jul 6, 2022 · 0 comments
Open

Improve API #6

urechm opened this issue Jul 6, 2022 · 0 comments

Comments

@urechm
Copy link

urechm commented Jul 6, 2022

The API of the library seems a little strange to me. Either the changes were persisted to the template file as well as to the target file or the changes were not persisted at all.

Therefore I make now a copy for my own of the template and then for some reason one has to call document.write(...) otherwise the changes are not persisted to the template file. It would be nice, if the API would be simpler to use.

Here is the code that i used in the end:

    public void processDocxTemplate() {
        if (!TEMPLATE_FILE.isFile()) {
            throw new IllegalArgumentException("The template file does not exist: " + TEMPLATE_FILE);
        }
        if (OUTPUT_FILE.exists()) {
            throw new IllegalArgumentException("The output file does already exist: " + OUTPUT_FILE);
        }
        copyFile(TEMPLATE_FILE, OUTPUT_FILE);
        try (XWPFDocument document = new XWPFDocument(OPCPackage.open(OUTPUT_FILE))) {
            WordReplacer replacer = new WordReplacer(document);
            placeholderToReplacement.forEach(replacer::replaceWordsInText);
            // For some strange reason we need the following write call, otherwise the changes are not persisted.
            document.write(new ByteArrayOutputStream());
        } catch (Exception e) {
            throw new IllegalArgumentException("Failed to processDocxTemplate.", e);
        }
    }

    private void copyFile(File sourceFile, File targetFile) {
        try {
            FileUtils.copyFile(sourceFile, targetFile);
        } catch (Exception e) {
            throw new IllegalArgumentException("Failed to copyFile.", e);
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant