Recently do a project, need to convert Excel file to PDF file, after I look up data, nothing but two ways: 1 Poi+itext 2 Jacob to invoke Excel save function.
The first approach is to use POI to read the contents of Excel and write it to a PDF file. Implementation difficulty is a bit large, mainly because Excel sheet structure is not fixed, content is not fixed, there may be pictures, etc., resulting in reading Excel more complex, the real implementation is still more complex.
The second way is to use Jacob to invoke the ability to save the Excel file as a PDF. The main is familiar with Jacob's API. No need for sophisticated programming skills.
This article uses the second approach, which requires the installation of Office,pdf software in the current environment. It is recommended that you install the Office 2010 version. If you install version 07, you will also need to install an Excel plugin (SaveAsPDFandXPS.exe), which is Microsoft's official link, as follows: Microsoft official
Package com.bplead.module.sign.util;
Import com.jacob.activeX.ActiveXComponent;
Import Com.jacob.com.Dispatch;
Import com.jacob.com.Variant;
public class Transfertool {
public static void Els2pdf (String els,string pdf) {
SYSTEM.OUT.PRINTLN ("Starting Excel ...");
Long start = System.currenttimemillis ();
Activexcomponent app = new Activexcomponent ("Excel.Application");
try {
App.setproperty ("Visible", false);
Dispatch workbooks = App.getproperty ("workbooks"). Todispatch ();
SYSTEM.OUT.PRINTLN ("Opening document:" + els);
Dispatch workbook = dispatch.invoke (workbooks, "Open", Dispatch.method, New Object[]{els, new variant (FALSE), new variant (false)}, new Int[3]). Todispatch ();
Dispatch.invoke (Workbook, "SaveAs", Dispatch.method, new object[] {
PDF, new variant, new Variant (FALSE),
New Variant (new variant), new variant (FALSE),
New Variant (TRUE), new variant (TRUE),
New Variant (TRUE), new Variant (TRUE)}, new int[1]);
Variant F = new Variant (FALSE);
System.out.println ("to PDF" + pdf);
Dispatch.call (Workbook, "Close", f);
Long end = System.currenttimemillis ();
System.out.println ("completed.") Used: "+ (End-start)/1000 +" s ");
catch (Exception e) {
System.out.println ("========error:operation fail:" + e.getmessage ());
}finally {
if (app!= null) {
App.invoke ("Quit", new variant[] {});
}
}
}
public static void Main (string[] args) {
Els2pdf ("F:projecttemplate.xlsx", "f:pdf.pdf");
}
}
To run the above environment, you need to download Jacob's package, which also contains 2 DLL files, one is Jacob-1.17-x64.dll, this is 64-bit, and one is Jacob-1.17-x86.dll file, this is 32-bit. The jar package is included in the Classpath directory, and the DLL file is included in the Jre/bin directory