plutext / docx4j

JAXB-based Java library for Word docx, Powerpoint pptx, and Excel xlsx files
https://www.docx4java.org/
2.11k stars 1.2k forks source link

Don't call shutdown method, after calling Documents4jLocalServices.export() method #416

Open lomoya90 opened 4 years ago

lomoya90 commented 4 years ago

My app closes MS office word app and throw an IllegalStateException, when I stop my app.

        File output = new File(System.getProperty("user.dir") + "/1.pdf");
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(output);
            Documents4jLocalServices exporter = new Documents4jLocalServices();
            exporter.export(new File(System.getProperty("user.dir") + "/1.docx"), fos,
                    DocumentType.MS_WORD);
        } catch (FileNotFoundException | Docx4JException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

Exception:

java.lang.IllegalStateException: Shutdown in progress
    at java.lang.ApplicationShutdownHooks.remove(ApplicationShutdownHooks.java:82)
    at java.lang.Runtime.removeShutdownHook(Runtime.java:239)
    at com.documents4j.job.ConverterAdapter.deregisterShutdownHook(ConverterAdapter.java:121)
    at com.documents4j.job.ConverterAdapter.cleanUp(ConverterAdapter.java:107)
    at com.documents4j.job.ConverterAdapter.shutDown(ConverterAdapter.java:98)
    at com.documents4j.job.LocalConverter.shutDown(LocalConverter.java:109)
    at com.documents4j.job.ConverterAdapter$ConverterShutdownHook.run(ConverterAdapter.java:134)

After tracing the source code, I found that the converter in documents4j needs to be shut down after it is used up, but the corresponding shutdown method is not found in the local package. I used reflection and closed the converter, but when I ended my program, it would still turn off the office word program in my computer.

The reflection code is :

try {
            Field converter = exporter.getClass().getDeclaredField("converter");
            converter.setAccessible(true);
            Object converterObj = converter.get(exporter);
            Method shutdown = converterObj.getClass().getDeclaredMethod("shutDown");
            shutdown.invoke(converterObj);
        } catch (Exception e) {
            e.printStackTrace();
        } 

How to code so that not close my Office Word program?

sssunnn1 commented 2 years ago

Hi @lomoya90 Have you managed to solve the shutdown problem without closing MS Word.

Thank you for your help.