1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
public class DocxToPdf {
/**
* code modified by
* date modification : 27/02/2023
* Word to PDF
* @param fileName
* @param toFileName
* @return
*/
ProgressBar1 barreprog ;
static Logger logger;
FileHandler fh;
public DocxToPdf(String fileName,String toFileName) {
sendToLog() ;
word2Pdf(fileName, toFileName);
}
public static int word2Pdf(String fileName,String toFileName){
System.out.println("Start word...");
logger.info("Start word...");
Long start = System.currentTimeMillis();
ActiveXComponent app = null;
Dispatch doc = null ;
try {
logger.info("new ActiveXComponent(\"word.Application\")...");
app = new ActiveXComponent("word.Application");
logger.info("app.setProperty(\"Visible\", new Variant(false))");
app.setProperty("Visible", new Variant(false));
logger.info("Open the word file");
Dispatch docs = app.getProperty("Documents").toDispatch();
logger.info("Dispatch.invoke ... create Word object");
doc = Dispatch.invoke(docs,"Open",Dispatch.Method,new Object[]{
fileName, new Variant(false),new Variant(true) },new int[1]).toDispatch();
System.out.println("Open document..."+ fileName);
logger.info("Open document..."+ fileName);
System.out.println("Convert document to PDF..."+ toFileName);
logger.info("Convert document to PDF..."+ toFileName);
File tofile = new File(toFileName);
if (tofile.exists()){
tofile.delete();
}
System.out.println("Dispatch.invoke - SaveAs ... "+ doc);
logger.info("Dispatch.invoke - SaveAs ... " + doc);
Dispatch.invoke(doc,"SaveAs", Dispatch.Method,new Object[]{
toFileName,new Variant(17)},new int[1]);
Long end = System.currentTimeMillis();
System.out.println("Conversion completed... Time: "+ (end-start) + "ms.");
logger.info("Conversion completed... Time: "+ (end-start) + "ms.");
}catch (Exception e){
e.printStackTrace();
System.out.println("=========Error: Document conversion failed:" + e.getMessage());
logger.info("=========Error: Document conversion failed:" + e.getMessage());
System.exit(1);
}catch (Throwable t){
t.printStackTrace();
System.exit(1);
}finally {
//Close word
Dispatch.call(doc,"Close",false);
System.out.println("Close document");
//logger.info("Close document");
if (app != null){
app.invoke("Quit",new Variant[]{});
}
//If there is no such sentence, the winword.exe process will not be closed
ComThread.Release();
return 1;
}
} |
Partager