Use OpenOffice to PDF, detailed

Source: Internet
Author: User
Tags getmessage

Recently because of the project needs, the Word document to the PDF online preview, because there has been no contact with this piece, so it took nearly four days to figure out.

The main purpose of writing this article is to deepen your memory, and at the same time make it easier to use later.

(Recently used this feature, found that this article has a lot of problems, have been modified, sorry)

The tools needed are OpenOffice

http://www.openoffice.org/

After the OpenOffice installation is successful, you need to open the CMD command-line input under the Porgram file under the installation directory

Soffice-headless-accept= "SOCKET,HOST=127.0.0.1,PORT=8100;URP;"-nofirststartwizard

A two-OpenOffice process is started and can be seen by opening task Manager.

Required Java package jodconverter download address http://sourceforge.net/projects/jodconverter/files/JODConverter/

Pom.xml

<!--https://mvnrepository.com/artifact/com.artofsolving/jodconverter-maven-plugin-->
<dependency >
<groupId>com.artofsolving</groupId>
<artifactid>jodconverter-maven-plugin</ Artifactid>
<version>2.2.1</version></dependency>

Here you need to explain in detail the installation of OpenOffice, preferably the default installation path

After the installation, we started doing business. 、

First we have to write an upload page (name at random, I wrote the JSP page)

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" Utf-8 "%> <!
DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" > In this side I was added Bootstar,bootstar can be downloaded in Baidu.

In its up55 said I downloaded the upload icon on the web, for the page to look good point

And then there's controller.

This method is a way to jump to the JSP

@RequestMapping ("/othre") public String Otre () {return "Otre";}

This method is the method of uploading @RequestMapping (value = "/upload", methods = requestmethod.post) @ResponseBody public String Uplo  
                AD (@RequestParam ("file") Multipartfile file) throws IOException {if (!file.isempty ()) {try {  
                Here is just a simple example where the file is output directly to the project path.  
                  
         
                In the actual project, the file needs to be output to the specified location, requiring additional code processing. Bufferedoutputstream out = new Bufferedoutputstream (New FileOutputStream ("d:/pdf/" +file.getorig  
                Inalfilename ()));  
                System.out.println (File.getoriginalfilename ());  
                Out.write (File.getbytes ());  
                Out.flush ();  
            Out.close ();  
                catch (FileNotFoundException e) {e.printstacktrace ();  
            Return "Upload failed," + e.getmessage ();  
                catch (IOException e) {e.printstacktrace ();  
            Return "Upload failed," + e.getmessage (); }//Call Doc2htmluTil tool class Doc2htmlutil coc2htmlutil = Doc2htmlutil.getdoc2htmlutilinstance ();  
            File file1 = null;  
            FileInputStream fileinputstream = null; 

            Here is the path to the transferred file File1 = new file ("d:/pdf/" +file.getoriginalfilename ());  

FileInputStream = new FileInputStream (file1);  
            For later convenience, the file name is intercepted directly, which facilitates subsequent operations int i = File.getoriginalfilename (). LastIndexOf (".");
            String substring = file.getoriginalfilename (). substring (i);  
            All of the above paths and the following road strength can be customized coc2htmlutil.file2pdf (FileInputStream, "d:/ss", substring);  
              
              
            Doc2htmlutil doc = new Doc2htmlutil ();  
              
              
        Return "upload success";  
        else {return "upload failed because the file is empty." }  
    }

The tool class for Word transfer PDF is called in controller, and the following is the tool class

Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import java.net.ConnectException;
Import Java.text.SimpleDateFormat;

Import Java.util.Date;
Import Com.artofsolving.jodconverter.DocumentConverter;
Import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
Import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
Import Com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter; /** * Use Jodconverter (OpenOffice Services) to convert files (*.doc, *.docx, *.xls, *.ppt) to HTML or PDF format, * Check that the OpenOffice service is turned on before use. OpenOffice process Name: Soffice.exe |
 Soffice.bin * * * @author yjclsx//** * uses Jodconverter (OpenOffice service) to convert files (*.doc, *.docx, *.xls, *.ppt) to HTML or PDF format, * Please check that the OpenOffice service is open before use, OpenOffice process name: Soffice.exe | Soffice.bin * * @author yjclsx/public class Doc2htmlutil {private static Doc2htmlutil doc2Htmlutil; /** * Get Doc2htmlutil instance/public static synchronized Doc2htmlutil getdoc2htmlutilinstance () {if
        C2htmlutil = = null) {Doc2htmlutil = new doc2htmlutil ();
    return doc2htmlutil;  /** * Convert file into PDF * * @param fromfileinputstream: * @throws ioexception/Public String File2pdf (InputStream fromfileinputstream, String tofilepath,string type) throws IOException {Date date = new Dat
        E ();
        SimpleDateFormat SDF = new SimpleDateFormat ("Yyyymmddhhmmss");
        String Timesuffix = Sdf.format (date);
        String docfilename = null;
        String htmfilename = null;
            if (". doc". Equals (Type)) {docfilename = "doc_" + Timesuffix + ". Doc";
        Htmfilename = "Doc_" + Timesuffix + ". pdf";
            }else if (". docx". Equals (Type)) {docfilename = "docx_" + Timesuffix + ". docx";
        Htmfilename = "Docx_" + Timesuffix + ". pdf"; }else IF (". xls". Equals (Type)) {docfilename = "Xls_" + Timesuffix + ". xls";
        Htmfilename = "Xls_" + Timesuffix + ". pdf";
            }else if (". ppt". Equals (Type)) {docfilename = "Ppt_" + Timesuffix + ". ppt";
        Htmfilename = "Ppt_" + Timesuffix + ". pdf";
        }else{return null;
        The file Htmloutputfile = new file (Tofilepath + File.separatorchar + htmfilename);
        File Docinputfile = new file (Tofilepath + File.separatorchar + docfilename);
        if (htmloutputfile.exists ()) Htmloutputfile.delete ();
        Htmloutputfile.createnewfile ();
        if (docinputfile.exists ()) Docinputfile.delete ();
        Docinputfile.createnewfile (); /** * Build input file by Fromfileinputstream/try {outputstream OS = new FileOutputStream (doc
            Inputfile);
            int bytesread = 0;
            byte[] buffer = new byte[1024 * 8]; while ((Bytesread = fromfileinputstReam.read (buffer))!=-1) {os.write (buffer, 0, bytesread);
            } os.close ();
        Fromfileinputstream.close ();
        The catch (IOException e) {} openofficeconnection connection = new socketopenofficeconnection (8100);
        try {connection.connect (); The catch (Connectexception e) {System.err.println ("File conversion error), please check that the OpenOffice service is started."
        ");
        }//Convert Documentconverter converter = new Openofficedocumentconverter (connection);
        Converter.convert (Docinputfile, htmloutputfile);
        Connection.disconnect ();                                                                
        Delete Word file Docinputfile.delete () after the conversion is complete;
    return htmfilename; public static void Main (string[] args) throws IOException {Doc2htmlutil Coc2htmlutil = Getdoc2htmlutilinst
        Ance ();
        File file = null;
        
 FileInputStream fileinputstream = null;       File = new file ("C:/users/machenike/desktop/xxx.doc");

        FileInputStream = new FileInputStream (file);

    Coc2htmlutil.file2pdf (FileInputStream, "e:/360", "Doc"); }

}

After the modified code has been able to convert the PDF, if there are any questions can be left at the bottom of the message, I will promptly reply, thank you for your support.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.