Apache POI - Generated Word document works but invokes a security warning

自闭症网瘾萝莉.ら 提交于 2019-12-25 00:30:24

问题


I'm using Apache POI in a Java project to generate a word document based on a template. Specifically I'm using the HWPFDocument class and both the template and the output file is in the old .doc format (Word 97-2004). The reason why I'm using the old format is that I couldn't find any examples on how to search/replace placeholders in a template with the new .docx format.

The code works just fine and I have no problem opening the generated .doc file on my Mac (Word 2011). But on Windows machines it creates a security warning (protected view) when I open the file. Even worse, when I try to print it (via Desktop.getDesktop().print(File f)) it downright refuses to do so until I've enabled printing for the specific file in question.

Is there any way to avoid these warnings without disabling security features on Windows machines using this project?

Here's the code:

public static void createWordDocument(File template, File output, String[] placeholders, String[] replacements){
    if (placeholders.length == 0 || replacements.length == 0 || placeholders.length != replacements.length){
        System.out.println("Invalid parameters");
    }
    else{
        try {
            InputStream resourceAsStream =  new FileInputStream(template);
            POIFSFileSystem fsfilesystem = new POIFSFileSystem(resourceAsStream);
            HWPFDocument hwpfdoc = new HWPFDocument(fsfilesystem);
            Range range = hwpfdoc.getRange();
            for (int i = 0 ; i < placeholders.length ; i++){
                range.replaceText(placeholders[i], replaceNewLineWithReturn(replacements[i]));
            }
            FileOutputStream fos = new FileOutputStream(output);
            hwpfdoc.write(fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

来源:https://stackoverflow.com/questions/10644523/apache-poi-generated-word-document-works-but-invokes-a-security-warning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!