Convert WORD to PDF in Java

Development environment: windows. Please be sure to do this operation in the windows operating system, because word needs to be converted to pdf on the server.

Please install word on your computer, pay attention to installing word, not wps (this is very important).

Please install the word to pdf plug-in on your computer: "Software name: SaveAsPDFandXPS", download address: http://download.csdn.net/download/tiandixuanwuliang/10006993

Please put the dll file that the system needs to call in the bin directory of jre in the java environment, for example: C:\Program Files\Java\jdk1.7.0_13\bin\jacob-1.18-x64.dll, (please pay attention to your computer 32 Bit or 64 bit) download address: http://download.csdn.net/download/tiandixuanwuliang/10007003

Put jacob.jar in the C:\Windows\System32 directory. At the same time, it is introduced into the project file.

The usage in the project is as follows:

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Convert word file to PDF
 *
 * @author Tepu
 */
public class Word2Pdf {
    /**
     * Pending changes are not saved.
     */
    static final int wdDoNotSaveChanges = 0;
    /**
     * word to PDF format
     */
    static final int wdFormatPDF = 17;
    /**
     * ppt to PDF format
     */
    static final int ppSaveAsPDF = 32;

    public static void main(String[] args) {
        String source1 = "E:\\work\\wc_rcs\\target\\rcs\\report\\test.doc";
        String target1 = "E:\\work\\wc_rcs\\target\\rcs\\report\\test.pdf";
        Word2Pdf.word2pdf(source1, target1);
    }

    public static void word2pdf(String source, String target) {
        System.out.println("启动Word");
        long start = System.currentTimeMillis();
        ActiveXComponent app = null;
        try {
            app = new ActiveXComponent("Word.Application");
            app.setProperty("Visible", false);

            Dispatch docs = app.getProperty("Documents").toDispatch();
            System.out.println("Open document" + source);
            Dispatch doc = Dispatch.call(docs, "Open", source, false, true).toDispatch();

            System.out.println("Convert document to PDF " + target);
            File tofile = new File(target);
            if (tofile.exists()) {
                tofile.delete();
            }
            Dispatch.call(doc,"SaveAs", target, wdFormatPDF);

            Dispatch.call(doc, "Close", false);
            long end = System.currentTimeMillis();
            System.out.println("Conversion completed.. Time: " + (end - start) + "ms.");
        } catch (Exception e) {
            System.out.println("========Error: Document conversion failed: " + e.getMessage());
        } finally {
            if (app != null) {
                app.invoke("Quit", wdDoNotSaveChanges);
            }
        }
    }

    public void ppt2pdf(String source, String target) {
        System.out.println("Start PPT");
        long start = System.currentTimeMillis();
        ActiveXComponent app = null;
        try {
            app = new ActiveXComponent("Powerpoint.Application");
            Dispatch presentations = app.getProperty("Presentations").toDispatch();
            System.out.println("Open document" + source);
            Dispatch presentation = Dispatch.call(presentations,"Open",true, true, false).toDispatch();

            System.out.println("Convert document to PDF " + target);
            File tofile = new File(target);
            if (tofile.exists()) {
                tofile.delete();
            }
            Dispatch.call(presentation,"SaveAs", target, ppSaveAsPDF);

            Dispatch.call(presentation, "Close");
            long end = System.currentTimeMillis();
            System.out.println("Conversion completed.. Time: " + (end - start) + "ms.");
        } catch (Exception e) {
            System.out.println("========Error: Document conversion failed: " + e.getMessage());
        } finally {
            if (app != null) {
                app.invoke("Quit");
            }
        }
    }

    public void excel2pdf(String source, String target) {
        System.out.println("启动Excel");
        long start = System.currentTimeMillis();
        // start excel(Excel.Application)
        ActiveXComponent app = new ActiveXComponent("Excel.Application");
        try {
            app.setProperty("Visible", false);
            Dispatch workbooks = app.getProperty("Workbooks").toDispatch();
            System.out.println("Open document" + source);
            Dispatch workbook = Dispatch.invoke(workbooks, "Open", Dispatch.Method,
                    new Object[] { source, new Variant(false), new Variant(false) }, new int[3]).toDispatch();
            Dispatch.invoke(workbook, "SaveAs", Dispatch.Method,
                    new Object[] { target, new Variant(57), new Variant(false), new Variant(57), new Variant(57),
                            new Variant(false), new Variant(true), new Variant(57), new Variant(true),
                            new Variant(true), new Variant(true) },
                    new int[1]);
            Variant f = new Variant(false);
            System.out.println("Convert document to PDF " + target);
            Dispatch.call(workbook, "Close", f);
            long end = System.currentTimeMillis();
            System.out.println("Conversion completed.. Time: " + (end - start) + "ms.");
        } catch (Exception e) {
            System.out.println("========Error: Document conversion failed: " + e.getMessage());
        } finally {
            if (app != null) {
                app.invoke("Quit", new Variant[] {});
            }
        }
    }

    public boolean imgToPdf(String imgFilePath, String pdfFilePath) throws IOException {
        File file = new File(imgFilePath);
        if (file.exists()) {
            Document document = new Document();
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(pdfFilePath);
                PdfWriter.getInstance(document, fos);

                // Add some information about the PDF document, such as author, subject, etc.
                document.addAuthor("arui");
                document.addSubject("test pdf.");
                // set the size of the document
                document.setPageSize(PageSize.A4);
                // open the document
                document.open();
                // write a text
                // document.add(new Paragraph("JUST TEST ..."));
                // read an image
                Image image = Image.getInstance(imgFilePath);
                float imageHeight = image.getScaledHeight();
                float imageWidth = image.getScaledWidth();
                int i = 0;
                while (imageHeight > 500 || imageWidth > 500) {
                    image.scalePercent(100 - i);
                    i++;
                    imageHeight = image.getScaledHeight();
                    imageWidth = image.getScaledWidth();
                    System.out.println("imageHeight->" + imageHeight);
                    System.out.println("imageWidth->" + imageWidth);
                }

                image.setAlignment(Image.ALIGN_CENTER);
                // //Set the absolute position of the image
                // image.setAbsolutePosition(0, 0);
                // image.scaleAbsolute(500, 400);
                // insert an image
                document.add(image);
            } catch (DocumentException de) {
                System.out.println(de.getMessage());
            } catch (IOException ioe) {
                System.out.println(ioe.getMessage());
            }
            document.close();
            fos.flush();
            fos.close();
            return true;
        } else {
            return false;
        }
    }
}

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325470891&siteId=291194637