Java Implementation Web Online Preview Office documents and PDF document instances

Source: Internet
Author: User
Tags ini socket windows support tomcat stringbuffer

1, first we need to find a way to convert office to PDF, find data found OpenOffice This software can convert office to PDF, the software first downloaded, and then remember to install it in that location. Then in the CMD environment into the installation directory of the program directory, enter the command to open OpenOffice:
Soffice-headless-accept= "SOCKET,HOST=127.0.0.1,PORT=8100;URP;"-nofirststartwizard


After the input completes, the task manager can see the Soffice.bin process in Task Manager, this service will start successfully. Of course, converting office2pdf in code we'll need some more rack packs. Download the jodconverter-2.2.2 rack package, and then copy to the Lib directory, the introduction of the rack package can be. This package has the following packages:


There are some items that can be duplicated and handled according to the actual situation.

2, we need to find a way to convert pdf2swf. Find Data Discovery Swftools the software can convert PDFs into SWF files. Just put it down and install it.

3, we need a display SWF file container, found that there are flexpaper this plugin. And the results are good. So we need to download this plugin. There are three JS files required to use this plugin. Respectively are: Jquery.js, Flexpaper_flash.js, Flexpaper_flash_debug.js. The name of the plugin is flexpaperviewer.swf.

The entire project knot is as follows:


The preparation is complete to begin coding below.

Convert class to Docconverter code:

package com.cectsims.util;
  import java.io.bufferedinputstream;
import java.io.file;
import java.io.ioexception;
import java.io.inputstream;
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;    /**  * doc docx format conversion    */public class docconverter {     private static final int environment = 1;//  Environment  
1:windows 2:linux     private String fileString;//  (only involves pdf2swf path issues)     private String outputPath =  "";//  input path &nbsp, if not set, output on default   Location     private string filenamE
    private File pdfFile;
    private File swfFile;
    private File docFile;       public docconverter (string filestring)  {    
    ini (filestring);
        system.out.println ("File path" +filestring);
   &nbsp.}       /**      * *  reset File      *      *  @param  filestring    
  *            32.      */    public void setfile (String fileString)  {        ini (filestring);    &nbsp}        /**      *&Nbsp; *  initialization      *      *  @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");
   &NBSP}       /**      *   convert to PDF      *   &NBsp;  *  @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)  {      
              e.printstacktrace ();                      system.out.println ("****swf Converter exception,openoffice  service not started!)
****");                   
  throw e;                 } catch   (com.artofsolving.jodconverter.openoffice.connection.openofficeexception e)  {                     
E.printstacktrace ();                      systeM.out.println ("****swf converter exception, read conversion file   failed * * *");                   
  throw e;                 } catch   (exception e)  {             
       e.printstacktrace ();                   
  throw e;                 }              } else {                 SYSTEM.OUT.PRINTLN ("* * * has been converted to PDF, no need to be converted
 **** ");            &NBSP}         } else {     
       system.out.println ("****swf converter exception, document that needs to be converted does not exist,  cannot convert * * *)";        &NBSP}     }       /**  *  Convert to  swf */     @SuppressWarnings ("unused")      private void pdf2swf ()  throws exception {       
 runtime r = runtime.getruntime ();         if  (!swffile.exists ())  {             if  (Pdffile.exists ())  {                 if  (environment == 1)  {// windows Environmental Treatment                     try {                          process p = r.exec ("d:/program/swfttools/pdf2swf.exe " + pdfFile.getPath ()  
+  " -o " + swffile.getpath ()  +  " -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 succeeded, file output: " +swffile.getpath ()  
+  "* * * *");                          if  (Pdffile.exists ()) {                          
   pdffile.delete ();                          }                      } catch  (ioexception e)  {                &Nbsp;        e.printstacktrace ();                   
      throw e;                      }                 }  else if  (ENVIRONMENT == 2)  {// linux Environmental treatment                      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 succeeded, 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 * * * *");        &NBSP}     }       static  string loadstream (inputstream in)  throws ioexception {    
    int ptr = 0;
        in = new bufferedinputstream (in);
        stringbuffer buffer = new stringbuffer ();         while  ((Ptr = in.read ())  != -1)   {            buffer.append ((char)  ptR);         }         return 
Buffer.tostring ();
   &NBSP}       /**      * *  conversion Main method      */     @SuppressWarnings ("unused")      Public boolean conver ()  {        if  ( Swffile.exists ())  {            
System.out.println ("****swf converter to start work, the file has been converted to  swf****");
            return true;        &NBSP}         if  ( environment == 1)  {            
System.out.println ("****swf converter to start work, currently set up running environment  windows****");         } else {           
 system.out.println ("****swf converter to start work, currently set up running environment  linux****");
        }         try {
            doc2pdf ();
            pdf2swf ();         } catch  (exception e)  {   
           e.printstacktrace ();
              return false;         }          System.out.println ("Does the file exist?)
"+swffile);         if  (Swffile.exists ())  {             SYSTEM.OUT.PRINTLN ("existence");
            return true;         } else {       
     system.out.println ("does not exist");
            return false;
       &NBSP}     }       /**      * return file path             *  @param            */    public string  getswfpath () {        if  (this.swfFile.exists ()) {             String tempString = 
Swffile.getpath ();             tempstring = tempstring.replaceall ("\\\\",  "/")
;             system.out.println ("Last file path is" +
tempstring);
            return tempString;         } else {       
     return  "file does not exist";
       &NBSP}     }       /**      *  Set Output path      *      *   @param  outputpath      */    public void  Setoutputpath (String outputpath) {        this.outputpath =
 outputPath;         if  (!OUTPUTPAth.equals ("")  {            String  Realname = filename.substring (Filename.lastindexof ("/"),        
             filename.lastindexof ("."));             if  (Outputpath.charat ( Outputpath.length ())  ==  '/')  {                 swffile = new file (outputpath + realname +
  ". SwF");             } else {                 swfFile = new 
File (outputpath + realname +  ". swf");             }         }    &nbsp}} 


Calling a transformation class requires only the path parameters of Word, PTT, Excel, and PDF files. The JSP code for the

Show online preview is as follows:

<% @page  language= "java"  contenttype= "Text/html; charset=utf-8"  pageencoding= "UTF-8"%
> <%    string swffilepath=session.getattribute ("Swfpath"). ToString ();
   system.out.println ("Show path" +swffilepath);  %> <! doctype html public  "-//w3c//dtd html 4.01 transitional//en" > 


There may be online previews can only achieve 10 pages of the situation, you need to put renderingorder: ' Flash ', set to flash to achieve more than 10 pages of online preview. Swffilepat is the path to the converted file.

Note the problem:

1, found that the error is generally OpenOffice service is not open.
2, the Linux environment will exist in Chinese garbled problem, Linux is not like Windows support so many fonts, need to install many fonts, and the location of the font to link to the location of the flexpaper. In the use of pdf2swf plus parameter-s languagedir=/usr/local/xpdf-chinese-simplified/. Specific some of the parameters please Baidu.


Java Convert Office document PDF document to SWF file online preview


first step, install OpenOffice.org

OpenOffice.org is a set of sun's open source office suites that can be executed on operating systems such as Widows,linux,solaris.

The main modules are writer (text document), impress (presentation), Calc (spreadsheet), Draw (Drawing), Math (formula), Base (database)

The author downloads is OpenOffice.org 3.3.0. Download the direct installation can be done.

However, we also need to start OpenOffice server. There are two ways of doing this:

1. To start the OpenOffice server as a command-line, the disadvantage is that each time the system reboots, the OpenOffice server needs to be started manually.

2. Will OpenOffice server as the operating system service startup, since become the system services, you can set the boot automatically started.

Let's first look at the first way,

1. Start OpenOffice Server as a command line

Under the cmd command, the CD Opeonofiice installation path/program such as: cd c:\program files\openoffice.org 3\program\soffice-headless-accept= "socket, host=127.0.0.1,port=8100;urp; "-nofirststartwizard


2. Start in a system-service manner

Here we also need Windows Resource Kit tools to set the OpenOffice server as a system service.

Windows Resource Kit Tools is developed by Microsoft specifically for managers, developers, and advanced users, including managing active directories, Group Policy, TCP/IP networking, registry, system security, monitoring, and so on, involving Windows Server 2003 Many other aspects of the operating system are not normally installed tool components. The release of Resource Kit tools for XP enables XP users to also use Resource Kit tools to handle these issues.

Download Windows Resource Kit Tools and we do the default installation.

1. Open windows Resource Kit Tools

In the command shell, execute the following commands:

"C:\Program files\windows Resource kits\tools\instsrv" Openofficeunoserver "C:\Program files\windows Resource kits\ Tools\srvany.exe "

Open Administrative Tools-> Services can find openofficeunoserver-named services

2. Open registry to find the following path

HKEY_LOCAL_MACHINE-> SYSTEM->controlset001->services->openofficeunoserver

New item Parameters, under which two string values are added:

Key:application

Value:c:\program files\openoffice.org 3\program\soffice.exe



Key:appparameters

Value:-invisible-headless-accept=socket,host=127.0.0.1,port=8100;urp; -nofirststartwizard



3. In the service console, start the OpenOffice service

4. Use the following command in CMD to see if 8100 is listening: Netstat-anop TCP

This way, OpenOffice3.0 is running on the Windows system as a service. (Use cmd command: NETSTAT-ANP TCP to see if Port 8100 is working)

You can then connect OpenOffice via a socket to use some of the services provided by OpenOffice, such as file conversion services, MS Office transfer PDF, and so on.

Open Source Project Jodconverter is a Java component that combines OpenOffice for document conversion.

There is also a command-line tool Swftools, which converts PDFs into SWF-formatted documents for IE guest 舳.

In addition, we can use the bat file to quickly implement the configuration, before running, please modify the corresponding directory parameters:

OpenOffice Service.bat File

"C:\Program files\windows Resource kits\tools\instsrv" Openofficeunoserver "C:\Program files\windows Resource kits\ Tools\srvany.exe "
REG ADD hkey_local_machine\system\controlset001\services\openofficeunoserver\parameters/ve/d
REG ADD hkey_local_machine\system\controlset001\services\openofficeunoserver\parameters/v application/t reg_sz/d "C : \program Files\openoffice.org 3\program\soffice.exe "
REG ADD hkey_local_machine\system\controlset001\services\openofficeunoserver\parameters/v appparameters/t reg_sz/d "-INVISIBLE-HEADLESS-ACCEPT=SOCKET,HOST=127.0.0.1,PORT=8100;URP; -nofirststartwizard "


Step two, use Jodconverter to convert Office documents to PDF

Jodconverter is a Java openducument file converter that can transform many file formats, using

OpenOffice to perform the conversion work, it can do the following conversion work:

1.Microsoft Office format conversion to openducument and openducument to Microsoft office

2.OpenDucument conversion to Pdf,word, Excel, PowerPoint conversion to pdf,rtf to PDF, and so on.

It is an open source project.


My project was developed under the MyEclipse.

Download the latest version of jodconverter-2.2.2 and import the Lib folder package into the Lib folder of your Docconverter project.

(Assuming your project is Docconverter)

New Doc2pdfutil.java

package com.iori.webapp.util;
import java.io.file;   import java.io.ioexception; import java.net.connectexception;   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;     public  class doc2pdfutil extends java.lang.thread  {     private  File inputFile;//  files that need to be converted          private file  outputFile;//  output Files                 Public doc2pdfutil (File inputfile, file outputfile) &NBsp {            this.inputFile = inputFile; 
           this.outputFile = outputFile;       }              public  void doctopdf ()  {            Date 
Start = new date ();                       openofficeconnection connection = new  socketopenofficeconnection (8100);            try  {                 Connection.connect ();                 documentconverter cOnverter = new openofficedocumentconverter (connection);                 converter.convert (Inputfile, outputfile);             } catch  (Connectexception cex)  {                 Cex.printstacktrace ();            } finally {                 // close  the connection                 if  (connection != null)  {                     connection.disconnect ();                     connection = null;                 }             }        }               /**         *  because the service is thread-unsafe, ... Need to start thread           */       public  Void run ()  {            this.doctopdf ();         }               Public file getinputfile ()  {            
return inputfile;        }              public void setinputfile (file inputfile)  {             this.inputFile = inputFile;        }               public file getoutputfile ()
 {            return outputFile;        }              public  void setoutputfile (file outputfile)  {         
   this.outputFile = outputFile;        }             /**        *   Test Main method         *  @param  args         */     public static void main (String[] args)  {          file inputfile = new file ("c://temp//333.")
XLS ");          file outputfile = new file ("C://temp
333.pdf ");          doc2pdfutil dp=new doc2pdfutil (InputFile,
OutputFile);
         dp.start ();      } }


in Doc2pdfutil.java, the right key property->run as->java application, outputs the test results for main.

execute in JSP

New mydoc2pdftest.jsp

<%@ page import= "java.io.*"%> <%@ page import= " com.artofsolving.jodconverter.openoffice.connection.* "%> <%@ page import=" com.artofsolving.jodconverter.openoffice.connection.* "%> <%@ page import=" Com.artofsolving.jodconverter.openoffice.converter.* "%> <%@ page import=" Com.artofsolving.jodconverter.* "%> <%@ page import=" java.util.* "%> <%@ page  Import= "com.iori.webapp.util.*"%>   <% file inputfile = new file ("c://temp//333.
XLS ");
File outputfile = new file ("C://temp//333.pdf");
Doc2pdfutil dp=new doc2pdfutil (Inputfile,outputfile);
Dp.start (); %> <!--  The following HTML can be removed  --> 


Step three, using Swftools to convert PDF to SWF

Recommended Download swftools-0.9.1, the author initially downloaded the latest version of the swftools-1.0 version. Seemingly error in conversion, what components are missing.

To continue the author's Docconverter project. The author uses the development environment is MyEclipse 9.0.

New Pdf2swfutil.java

package com.iori.webapp.util;
import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstream;
import java.io.inputstreamreader;   public class pdf2swfutil {         /**        *  Use the Swftools tool to convert PDF to SWF, after converted SWF file with the same name as PDF         *  @author  iori       *  @param  fileDir  PDF file storage path (including filename)        *  @param  exePath  Converter Installation path         *  @throws  ioexception       */  &NBSP;&NBSP;&NBSP;PUBLIC&NBSP;STATIC&NBSP;SYNCHRONIZED&NBSP;VOID&NBSP;PDF2SWF (String fileDir, String  exepath)  throws ioexception {        //file path           string filePath = filedir.substring (0, filedir.lastindexof ("/"));         //filename with no suffix           string filename = filedir.substring ((Filepath.length ()  + 1), 
Filedir.lastindexof ("."));
        Process pro = null;         if  (Iswindowssystem ())  {             //If it is a Windows system                //Command line command                String cmd = exePath +  " \" " + fileDir + "
\ " -o \" " + filePath + "/" + fileName + ". swf\ "";             //runtReturns the created Process object after the IME executes               pro =
 runtime.getruntime (). exec (CMD);         } else {             //if it is a Linux system, the path cannot have spaces, and must not be in double quotes, otherwise the process cannot be created       
        String[] cmd = new String[3];
            cmd[0] = exePath;
            cmd[1] = fileDir;             cmd[2] = filepath +
  "/"  + fileName +  ". SwF";             //runtime after execution returns the created Process object                pro = runtime.getruntime (). exec (CMD);         }         // To read the output of CMD again, or not flush the generated file (multi-threaded)          new dooutput (
Pro.getinputstream ()). Start ();
        new dooutput (Pro.geterrorstream ()). Start ();         try {             //calls the Waitfor method to block the current process until CMD finishes executing          
    pro.waitfor ();         } catch  (interruptedexception e)  { 
          e.printstacktrace (); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}     }           /**       *  Judge whetheris Windows operating system        *  @author  iori        *  @return       */    private static  Boolean iswindowssystem ()  {        string p =
 system.getproperty ("Os.name");         return p.tolowercase (). IndexOf ("Windows")  >=
 0 ? true : false; &NBSP;&NBSP;&NBSP;&NBSP}          /**      
 *  multithreaded Inner class        *  read the standard output stream and error output stream of the CMD process while reading the conversion, because if the stream is not read, the process will deadlock        *  @author  iori       */     private static class dooutput extends thread {         public inputstream is;               //Construction Method           public dooutput (inputstream is)  {     
       this.is = is;         }                public void run ()  {             bufferedreader br = new bufferedreader (New InputStreamReader (
this.is));
            String str = null;             try {                 //here there is no convection content to handle, just read it again                    while  ((Str = br.readline ())  !=
 null);             } catch  (Ioexception e)  {                
E.printstacktrace ();             } finally {                 if  (br !=  NULL)  {                     try {            
            br.close ();                      } catch  (ioexception e)  {            
            e.printstacktrace ();                   
  }                 }             }        &NBSP;&NBSP}     }          /**        *  Test Main method        *  @param  args        */    public static void main (String[] args)  {        //Converter Installation path           string exepath =  "C:/program files/swftools/pdf2swf.exe";         try {        
    pdf2swfutil.pdf2swf ("C:/temp/333.pdf",  exepath);         } catch  (ioexception e)  {   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.ERR.PRINTLN ("Conversion error!")
");
            e.printstacktrace ();         }    &nbsp}}


in Pdf2swfutil.java, the right key property->run as->java application, outputs the test results for main.

execute in JSP

New mypdf2swftest.jsp

<%@ page import= "java.io.*"%> <%@ page import= " com.artofsolving.jodconverter.openoffice.connection.* "%> <%@ page import=" com.artofsolving.jodconverter.openoffice.connection.* "%> <%@ page import=" Com.artofsolving.jodconverter.openoffice.converter.* "%> <%@ page import=" Com.artofsolving.jodconverter.* "%> <%@ page import=" java.util.* "%> <%@ page  Import= "com.iori.webapp.util.*"%>   <%/Converter installation path string exepath =  "C:/program files"
/swftools/pdf2swf.exe "; try {    pdf2swfutil.pdf2swf ("C:/temp/333.pdf",  exepath);}  catch  (ioexception e)  {    system.err.println ("Conversion error!")
");
    e.printstacktrace (); %>   <!--  The following HTML can be removed  --> 


In the project Docconverter root directory, right-click Properties->run as->myeclipse Server application

Publish to the root of the Tomcat 6.0 that was previously installed, and then use the URL path to access: Http://localhost:8080/DocConverter/MyPDF2SWFTest.jsp for testing.


Step fourth, Office documents are converted to PDF and further to SWF

There are a lot of Office documents on the web that turn Pdf,pdf into SWF, but they're all single-step. There is less information about converting together.

One problem with conversion is that when you convert to PDF, the conversion process takes a while to succeed, and how to control the conversion of the SWF after the successful conversion of the PDF.

And how to do multiple document bulk conversions.


Fortunately, I still found a translation of the same code:

New Docconverter.java

package com.iori.webapp.util;
import java.io.bufferedinputstream;
import java.io.file;
import java.io.ioexception;
import java.io.inputstream;
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;  /*  * doc docx format conversion  *  @author  administrator  */public class  docconverter {    private static final int environment=1;//
Environmental 1:windows 2:linux (involving pdf2swf path issues)     private String fileString;     private string outputpath= "";//input path, output in default position if not set     
private string filename;     private file pdffile;
    private File swfFile;
    private File docFile;         public docconverter (string filestring)      {        ini (filestring);     }          /*      *  re-Setup  file       *  @param  filestring      */    public void  setfile (string filestring)     {        
INI (filestring);
&NBSP;&NBSP;&NBSP;&NBSP}         /*      *  initialization      *  @param  filestring      */     private void ini (string filestring) &NBSP;&NBSP;&NBSP;&NBSp {        this.fileString=fileString;      
   filename=filestring.substring (0,filestring.lastindexof ("."));
        docfile=new file (filestring);
        pdffile=new file (filename+ ". pdf");
        swffile=new file (filename+ ". swf"); &NBSP;&NBSP;&NBSP;&NBSP}         /*      *  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);             &nbsP;       //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.printstacktrace ();                      System.out.println ("****swf Converter exception, failed to read conversion file * * * *");                   
  throw e;                 }   
              catch (Exception e)                 {                     
E.printstacktrace ();                   
  throw e;                 }              }              else             {   &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("* * *
has been converted to PDF, no longer required to convert * * *);             }        &NBSP;&NBSP}         else          {            system.out.println ("* * *
SWF Converter exception, the document needs to be converted does not exist, cannot convert * * *); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}     }          /*      *  Convert to SwF      */     private void pdf2swf ()  throws exception     {    
    runtime r=runtime.getruntime ();  &nbSp;      if (!swffile.exists ())         {             if (Pdffile.exists ())              {                 if (environment==1)//windows Environmental treatment                  {                     try {                          process p=r.exec ("c:/program files/swftools/pdf2swf.exe " +pdfFile.getPath () + " 
-o  "+swffile.getpath () +"  -t 9 ");             &nbSp;           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 Environmental treatment                  {    
                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 * * * *");            &nBSP;}
        }         else {             system.out.println ("****swf already exists no need to convert * * *
*"); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}     }          static string loadstream (inputstream in)  throws ioexception      {        int ptr=0;       
  in=new bufferedinputstream (in);
        stringbuffer buffer=new stringbuffer ();                 while (Ptr=in.read () )         {         !=-1)
   buffer.append ((char) PTR);         }         return buffer.tostring (); &NBSP;&NBSP;&NBSP;&NBSP}         /*      *  Convert Main method      */    public boolean conver ()      {        if (swffile.exists ())          {            
System.out.println ("****swf converter to start work, the file has been converted to swf****");
            return true;         }                  if (environment==1)         {             system.out.println ("****swf converter to start work, currently set up the running environment Windows**** ");
        }         else {             system.out.println ("****swf converter begins to work,
Currently set up running 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; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}     }          /*      *  return file path      *  @param  s       */    public string getswfpath ()      {        if (swffile.exists ())          {            
String tempstring =swffile.getpath ();             tempstring=tempstring.replaceall ("\\\\
", "/");
            return tempString; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}         else{ 
           return  ""; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}     }          /*      *  Set Output path      */     Public void setoutputpath (String outputpath)     {    
    this.outputPath=outputPath;         if (!outputpath.equals (""))          {             string realname=filename.substring (FileName.lastIndexOf ("/"),
Filename.lastindexof ("."));             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 ("c:/
Temp/111.ppt ");
        d.conver (); &NBSP;&NBSP;&NBSP;&NBSP}}


In Docconverter.java, the right key property->run as->java application, outputs the test results of main. The author carries on the individual conversion, and the batch conversion, all tests feasible.

As for why the full conversion of PDF and SWF is successful, there is no control associated with the above issues in the code. The author in the expected results, occasionally will be silly, do not continue to delve into.


Step Fifth, Flexpaper browsing SWF documents online

Flexpaper is an Open-source lightweight component that displays various documents in a browser and is designed to work with pdf2swf.

Makes it possible to display PDFs in Flex, and this process does not require support from the PDF software environment. It can be used as a library for flex.

In addition, you can also convert some documents such as word, PPT, etc. into PDF, and then realize online browsing.

Flexpaper_1.2.4_flash: No printing function

Flexpaper_1.4.7_flash: Printing function, right button printing

Here we do not need to let the user print, so the author chooses Flexpaper_1.2.4_flash.

Flexpaper Project has demo demo, here I do not more than described.

In a comprehensive, a complete online document browsing program.


Attach: Use itext to convert JPG, JPEG, PNG to PDF

Other, use Itext to convert jpg/jpeg/png to PDF

Itext is a well-known open source site SourceForge a project that is used to generate a PDF document of a Java class library. Not only can you generate PDF or RTF documents through Itext, but you can convert XML and HTML files to PDF files. 1. In Enterprise information systems, report processing has always accounted for a more important role, itext--a Java component to generate a PDF report, by using JSP or JavaBean on the server to generate a PDF report, the client uses a super connection to display or download the generated report, so that a good solution The report processing problem of B/s system is decided. 2. Support text, tables, graphics operations, can be easily combined with the Servlet.

To continue the author's Docconverter project. The development environment is MyEclipse 9.0. The author downloads is iText5.0.4.

New Jpg2pdfutil.java

package com.iori.webapp.util;
import java.io.file;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import java.io.ioexception;
  import com.lowagie.text.document;
import com.lowagie.text.documentexception;
import com.lowagie.text.image;
import com.lowagie.text.pdf.pdfwriter;     public class jpg2pdfutil {    private String 
inputfilestring;
    private String outputFileString;       public jpg2pdfutil (String inputfile, string outputfile)  {           this.inputFileString = inputFile;            this.outputFileString = outputFile;               }      public
 void imgtopdf ()    {        //Create a Document object     
    document doc = new document ();         try {                //defines the location of the output file            
    pdfwriter.getinstance (Doc, new fileoutputstream (outputFileString));             //Open documents                 doc.open ();                //set font   to support Chinese                 //basefont bfchinese = basefont.createfont ("STSong-Light",
  "Unigb-ucs2-h",  basefont.not_embedded);             // Font FontChinese =  New font (bfchinese, 12, font.normal);                //Add pictures              to the document   /*//The following is a multi-graph synthesis of a PDF, temporarily not used             for ( int i=1;i<32;i++)             {                 //Get Pictures ~ ~ ~ Picture format:                  image jpg1 =  image.getinstance ("c:/" +i+ ". jpg");  //the path of the original picture                  //get the height of the picture              &nbSp;   float heigth=jpg1.height ();                 float 
Width=jpg1.width ();                 
System.out.println ("Heigth" +i+ "----" +heigth);                 
System.out.println ("width" +i+ "-----" +width);                 //reasonable compression, h>w, Press W to compress or press W to compress                 //
Int percent=getpercent (Heigth, width);
                //Unified by width compression                 int 
Percent=getpercent2 (Heigth, width);                 //Set Picture Center display    
             jpg1.setalignment (Image.MIDDLE);                 //directly set the size of the picture ~ ~ ~ ~ ~ ~ ~ The third solution, compressed                 by fixed ratio
 //jpg1.scaleabsolute (210.0f, 297.0f);
                //the proportions of a picture by percentage                 
Jpg1.scalepercent (percent);//representation is the proportion of the original image;
                //can set the ratio of high and wide images                 //
Jpg1.scalepercent (50, 100);    &nbSp;            doc.add (JPG1);             }              */                         //Add pictures        to the document         //Get Pictures ~ ~ ~ Picture format:              image jpg1 = image.getinstance (inputfilestring)  //The path of the original picture              //get the height of the picture      
       float heigth=jpg1.height ();
            float width=jpg1.width ();             systEm.out.println ("heigth----" +heigth);             system.out.println ("width-----" +width)
;             //reasonable compression, h>w, press the W compression, otherwise press the W compression   
          //int percent=getpercent (Heigth, width);             //Unified According to width compression     
        int percent=getpercent2 (Heigth, width);             //Set Picture Center display     
        jpg1.setalignment (Image.middle);
            //directly set the size of the picture ~~~~~~~ the third solution, compressed by a fixed ratio             //jpg1.scaleabsolute (210.0f, 
297.0f);             //the proportion of pictures by percentage       
      jpg1.scalepercent (percent);//representation is the proportion of the original image;             //can set the ratio of high and wide images     
        //jpg1.scalepercent (50, 100);
            doc.add (JPG1);                                      //closing documents and releasing resources
               doc.close ();           } catch  (filenotfoundexception e)  {                e.printstacktrace ();            } catch  (documentexception e)  {                e.printstacktrace ();            } catch  (ioexception e)  { 
              e.printstacktrace ();  
        }      }     /**      *  The first solution      *  when you do not change the shape of the picture, judge that, if h>w, press H to compress , otherwise, in the case of W>h or w=h, press width      *  @param  h      *   @param  w      *  @return      */         public int getpercent (float h,float w)      {        int p=0;
        float p2=0.0f;
        if (h>w)         {
            p2=297/h*100; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}         else          {           
 p2=210/w*100;         }         p=math.round (
P2);
        return p;
&NBSP;&NBSP;&NBSP;&NBSP}     /**      *  Second solution, unified by width compression      *  the effect is that all the pictures are equal in width, and the effect is the best      * @ to the customer. Param args      * * &NBSP;&NBSP;&NBSP;&NBSP;PUBLIC&NBSP;INT&NBSP;GETPERCENT2 (FLOAT&NBSP;H,FLOAT&NBSP;W)     {
        int p=0;
        float p2=0.0f;
        p2=530/w*100;
        p=math.round (p2);
        return p; &NBSP;&NBSP;&NBSP;&NBSP}     /**      *  The third solution is direct compression, uneasy pixel proportions , all compressed to a fixed value, such as 210*297      *      *  @param  args       */    public static void main (String[] args)  {        jpg2pdfutil pt=new jpg2pdfutil ("c:/temp/
Ddd.jpg "," c:/temp/ddd.pdf ");
        pt.imgtopdf (); &NBSP;&NBSP;&NBSP;&NBSP}}


In Jpg2pdfutil.java, the right key property->run as->java application, outputs the test results of main.

Executing in a JSP

New myjpg2pdftest.jsp

<%@ page import= "java.io.*"%>
<%@ page import= "java.util.*"%>
<%@ page import= " Com.iori.webapp.util.* "%>
<%
jpg2pdfutil pt=new jpg2pdfutil (" C:/temp/333.jpg "," c:/temp/333.pdf ");
Pt.imgtopdf ();
%>
<!--below these HTML can be removed-->


In the project Docconverter root directory, right-click Properties->run as->myeclipse Server application

Publish to the root of the Tomcat 6.0 that was previously installed, and then use the URL path to access: Http://localhost:8080/DocConverter/MyDOC2PDFTest.jsp for testing.


Appendix II: FAQ

1.txt conversion SWF, the occurrence of Chinese garbled.

TXT conversion to UTF-8 encoding, or TXT format manually changed to ODT, upload will not happen garbled. From the root of the solution, temporarily even ... Don't want to tangle these chicken feathers for the time being.

2. An encrypted PDF may cause a conversion to SWF failure.

3.Microsoft Excel supports text-type values in formula operations, while OpenOffice.org Calc does not support

There is no solution to this problem, please manually modify the value of this type in Excel to numeric values.

4. Some Excel has an overly rich style (most of the cells with no data are populated with various styles), that is, using professional Adobe Acrobat 7 (or 9) Pro for conversion,

A PDF that would have expected to produce a 20-30-page, resulting in a 800-900-page PDF. This type of document is converted online, and it is unavoidable that it will result in the conversion of deadlocks.

Please delete unnecessary, unnecessary styles in your Excel document, or you have more flexibility.

5. Some Chinese PDF files converted to SWF, there are garbled (especially some professional periodicals)

1. Download xpdf:xpdf-chinese-simplified.tar.gz

2. Download font: Gkai00mp.rar

3. Modify the ADD-TO-XPDFRC file in the Xpdf-chinese-simplified directory. Set the path inside to its own path:

#-----Begin Chinese Simplified Support package (2011-SEP-02)
Cidtounicode ADOBE-GB1 C:\xpdf-chinese-simplified\Adobe-GB1.cidToUnicode
Unicodemap ISO-2022-CN C:\xpdf-chinese-simplified\ISO-2022-CN.unicodeMap
Unicodemap EUC-CN C:\xpdf-chinese-simplified\EUC-CN.unicodeMap
Unicodemap GBK C:\xpdf-chinese-simplified\GBK.unicodeMap
Cmapdir ADOBE-GB1 C:\xpdf-chinese-simplified\CMap
Tounicodedir C:\xpdf-chinese-simplified\CMap
Fontdir C:\WINDOWS\Fonts
DISPLAYCIDFONTTT ADOBE-GB1 C:\xpdf-chinese-simplified\CMap\gkai00mp.ttf
#fontFileCC Adobe-gb1/usr/..../gkai00mp.ttf
#-----End Chinese Simplified support package

4. Referring to the above code, add the "-S languagedir=d:\\xpdf\\xpdf-chinese-simplified" parameter to the call pdf2swf command.

Pdf2swfutil.java

String cmd = exepath + "\" "+ Filedir +" \ "o" "+ FilePath +"/"+ FileName +". swf\ "-T 9-s Languagedir=c:\\xpdf-chi Nese-simplified ";

Such a garbled problem is solved.


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.