Using Flexpaper to achieve online preview of PDF files

Source: Internet
Author: User
Tags cos documentation text to pdf

Java+flexpaper+swftools Imitation Library document online reading

Reproduced from: http://my.oschina.net/stephenzou/blog/144489


I. The idea of online reading of documents
1. Convert ppt, Word, Excel, text to PDF with OpenOffice
2. Convert the generated PDF to SWF using Swftool and then use Flexplayer to achieve online preview playback
Ii. preparatory work
1. Installation OpenOffice, website download address: http://www.openoffice.org/download/index.html, the latest version of 3.4.1, I use the version of 3.3.0:http:// Pan.baidu.com/share/link?shareid=1181746637&uk=1913152192#dir/path=%2f%e8%bd%af%e4%bb%b6%e5%b7%a5%e5%85%b7
2. Start the OpenOffice service, cmd command into the OpenOffice installation directory under the program directory, type the following command
Soffice "-ACCEPT=SOCKET,HOST=LOCALHOST,PORT=8100;URP; Staroffice.servicemanager "-nologo-headless-nofirststartwizard

References: http://blog.csdn.net/hbcui1984/article/details/5109169
3. Download jodconverter:http://sourceforge.net/projects/jodconverter/files/, the project mainly uses the Lib directory of the jar package.
4. Download and install swftools:http://www.swftools.org/download.html, download EXE file installation complete
5. Download Flexplayer
http://pan.baidu.com/share/link?shareid=1181746637&uk=1913152192#dir/path=%2F%E8%BD%AF%E4%BB%B6%E5%B7%A5% E5%85%b7
Website Download Address: http://flexpaper.devaldi.com/download/, version of 2.1.5, and 1.5.1 there is a big difference, did not use the latest version.

third, software development
1. Create a new Web project and introduce a jar package
Read the DEPENDENCIES.txt in the Jodconverter/lib directory to see which jar packs you need to add



Create a new Officeonline project, introduce the corresponding jar package (using Cos for document upload, Cos.jar need to download another), will flexpaper_1.5.1_ Flash.zip after extracting the JS directory into the project, FLEXPAPERVIEWER.SWF also introduced in


2. New Docconverter.java
Note: Depending on the swftools installation path, you need to modify the Pdf2swf.exe path in the pdf2swf () method, the path I install is in D disk
The main () test modifies the test according to its own document path.

Package com.util;
Import Java.io.BufferedReader;
Import Java.io.File;
Import java.io.IOException;
Import Java.io.InputStream;
 
Import Java.io.InputStreamReader;
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;  public class Docconverter {private static final int environment = 1;//Environment 1:windows,2:linux (involving pdf2swf path issues) Private
    String filestring;
    private string OutputPath = "";//input path, if not set, output in default location private string FileName;
    Private File Pdffile;
    Private File Swffile;
 
    Private File docfile;
    Public Docconverter (String filestring) {ini (filestring); * * * Reset file @param filestring */public void Setfile (String filestring) {ini (filestring)
    ;
  }
 
    /*   * Initialize @param filestring */private void ini (String filestring) {this.filestring = filestring;
        FileName = filestring.substring (0, Filestring.lastindexof ("."));
        Docfile = new File (filestring);
        Pdffile = new File (FileName + ". pdf");
    Swffile = new File (FileName + ". swf");
            * * Convert PDF @param file/private void Doc2pdf () throws Exception {if (docfile.exists ()) { if (!pdffile.exists ()) {openofficeconnection connection = new Socketopenofficeconnection (8100
                );
                    try {connection.connect ();
                    Documentconverter converter = new Openofficedocumentconverter (connection);
                    Converter.convert (Docfile, pdffile);
                    Close the connection connection.disconnect ();
                System.out.println ("****pdf conversion successful, PDF output:" + pdffile.getpath () + "* * *"); catch (JAVA.NEt.
                    Connectexception e) {//ToDo auto-generated catch block E.printstacktrace (); System.out.println ("****swf conversion exception, OpenOffice Service not started.)
                    ****");
                Throw e; catch (Com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) {E.printstacktrac
                    E ();
                    System.out.println ("****swf Converter exception, failed to read conversion file * * * *");
                Throw e;
                    catch (Exception e) {e.printstacktrace ();
                Throw e;
            } else {System.out.println ("* * * has been converted to PDF, no need to convert * * *)");
        } else {System.out.println ("****swf converter exception, document that needs to be converted does not exist, cannot convert * * *"); } * * Convert to SWF/private void pdf2swf () throws Exception {Runtime r = Runtime.getruntim
        E ();
                if (!swffile.exists ()) {if (pdffile.exists ()) {if (Environment = 1)//Windows environment Processing {try {//Here according to Swftools installation Road The path needs to be changed accordingly process P = r.exec ("D:/swftools/pdf2swf.exe" + pdffile.getpath () + "-O" + swffile.get
                        Path () + "-T 9");
                        System.out.print (Loadstream (P.getinputstream ()));
                        System.err.print (Loadstream (P.geterrorstream ()));
                        System.out.print (Loadstream (P.getinputstream ()));
                        System.err.println ("****swf conversion successful, file output:" + swffile.getpath () + "* * *");
                        if (pdffile.exists ()) {pdffile.delete ();
                        } catch (Exception e) {e.printstacktrace ();
                    Throw e;
                        } else if (Environment = 2)//Linux environment processing {try { Process p = r.exec ("pdf2swf" +Pdffile.getpath () + "-O" + swffile.getpath () + "-T 9");
                        System.out.print (Loadstream (P.getinputstream ()));
                        System.err.print (Loadstream (P.geterrorstream ()));
                        System.err.println ("****swf conversion successful, file output:" + swffile.getpath () + "* * *");
                        if (pdffile.exists ()) {pdffile.delete ();
                        } catch (Exception e) {e.printstacktrace ();
                    Throw e;
            }} else {System.out.println ("****pdf does not exist, cannot convert * * *");
        } else {System.out.println ("****swf already exists without conversion * * *");
        } static String Loadstream (InputStream in) throws IOException {int ptr = 0; Replace the InputStream byte stream with the BufferedReader character streams 2013-07-17 modify BufferedReader reader = new BufferedReader (New Inputstreamread
       ER (in)); StringBuilder buffer = new StringBuilder ();
        while (ptr = Reader.read ())!=-1) {buffer.append ((char) PTR);
    return buffer.tostring (); * * * Conversion Main method/public boolean conver () {if (swffile.exists ()) {System.out.print
            ln ("****swf converter begins to work, the file has been converted to swf****");
        return true;
        } if (Environment = = 1) {System.out.println ("****swf converter to start work, currently set to run Environment windows****");
        else {System.out.println ("****swf converter to start work, current set to run Environment linux****");
            try {doc2pdf ();
        Pdf2swf ();
            catch (Exception e) {//todo:auto-generated catch block E.printstacktrace ();
        return false;
        } if (Swffile.exists ()) {return true;
        else {return false; } * * Returns the file path @param S/public String Getswfpath () {if (swffile.exists()) {String tempstring = Swffile.getpath ();
            tempstring = Tempstring.replaceall ("\\\\", "/");
        return tempstring;
        else {return ""; }/* * Set Output path */public void Setoutputpath (String outputpath) {This.outputpath = output
        Path; if (!outputpath.equals (")) {String realname = filename.substring (Filename.lastindexof ("/"), Filename.lastind
            Exof ("."));
            if (Outputpath.charat (outputpath.length ()) = = '/') {swffile = new File (OutputPath + realname + ". swf");
            else {swffile = new File (OutputPath + realname + ". swf"); }} public static void Main (String s[]) {docconverter d = new Docconverter ("E:/tddownload/tes
        T.doc ");
    D.conver (); }
}


Run Result:


3. New documentupload.jsp

<%@ 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" >  

4. New docuploadconvertaction.jsp

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%> <% @page import=" java.io.* "%> <% @page import=" Java.util.Enumeration "%> <% @page import=" com.oreilly.servlet.MultipartRequest "%> <% @page import=" Com.oreilly.servlet.multipart.DefaultFileRenamePolicy "%> <% @page import=" Com.util.DocConverter "%> <%/ /file upload using Cos component upload, can replace for commons-fileupload upload, file upload, save in Upload folder//Get file upload path String savedirectory = Application.getrealpa
    Th ("/") + "upload";
    Print Upload path information System.out.println (savedirectory);
    Maximum 50m int maxpostsize = 50 * 1024 * 1024 per file;
    Using the COS default naming strategy, add 1,2,3 after the duplicate name ... if you do not add a DFP to overwrite defaultfilerenamepolicy DFP = new Defaultfilerenamepolicy (); Response encoding for "UTF-8", while using the default file name conflict resolution strategy, upload, if not add DFP rename multipartrequest multi = new Multipartrequest (Request,
    Savedirectory, Maxpostsize, "UTF-8", DFP);
    Multipartrequest multi = new Multipartrequest (Request, Savedirectory, maxpostsize, "UTF-8");Output feedback Information Enumeration files = Multi.getfilenames ();
        while (Files.hasmoreelements ()) {System.err.println ("CCC");
        String name = (string) files.nextelement ();
        File f = multi.getfile (name);
            if (f!= null) {String fileName = multi.getfilesystemname (name);
            Gets the extension of the uploaded file String extname = filename.substring (Filename.lastindexof (".") + 1);
            File full path String lastfilename = savedirectory + "\" + fileName;
            Gets the name of the file that needs to be converted, replacing ' \ ' in the pathname with '/' String converfilename = Savedirectory.replaceall ("\\\\", "/") + "/" + fileName;
            System.out.println (Converfilename);
            Invokes the transformation class Docconverter and passes the file that needs to be converted to the constructor method of the class Docconverter d = new Docconverter (converfilename);
            Call the Conver method to start the conversion, first execute doc2pdf () convert the Office file to PDF, and then execute pdf2swf () to convert the PDF to SWF;
            D.conver ();
          Call the Getswfpath () method to print the converted SWF file path System.out.println (D.getswfpath ());  Generates a SWF relative path to pass to the flexpaper player String swfpath = "Upload" + d.getswfpath (). substring (D.getswfpath (). Lastindexo
            F ("/"));
            System.out.println (Swfpath);
            Put the relative path into the Sessio to save the Session.setattribute ("Swfpath", Swfpath);
            Out.println ("uploaded file:" + lastfilename);
            Out.println ("File type" + Extname);
        Out.println (" 


5. New documentview.jsp

<%@ page language= "java" contenttype= "text/html;
Charset=utf-8 "pageencoding=" UTF-8 "%> <% String Swffilepath = Session.getattribute (" Swfpath "). ToString (); %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >  

Flexpaperviewer parameter setting corresponding documentation: HTTP://FLEXPAPER.DEVALDI.COM/DOCS_PARAMETERS.JSP

6. Post-deployment visits: http://localhost:8080/OfficeOnline/documentUpload.jsp


Preview after successful upload:

7. If the SWF cannot be previewed, please visit the http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04a.html# 119065 set the folder that generated the SWF as a trusted file.
8. Reference: http://blog.csdn.net/hil2000/article/details/8459940
Http://www.cnblogs.com/star-studio/archive/2011/12/09/2281807.html
File Chinese name garbled solution: http://blog.csdn.net/kunoy/article/details/7903258

Iv. Other optimization
Solve Flexpaper search text can not highlight the problem: http://my.oschina.net/dianfusoft/blog/125450
Flexpaper go to the introduction to watermark, etc.: http://blog.csdn.net/zengraoli/article/details/7827840

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.