Java Web Online Preview--Reference two __HTML5

Source: Internet
Author: User
Tags java web log4j

http://blog.csdn.net/qq_28533563/article/details/72676425

The blogger offers 2 different ideas,

The main implementation is (Openoffice+swftools+flexpaper) and (Aspose+pdfjs preview).

The first is the implementation of the previous article, the second is the main realization of the blogger


Back up the original:

Java Implementation Online preview attachment office convert PDF

Because the project is to do OA this piece, there are many accessories need to realize online preview attachment, on the Internet also read a lot of relevant information. The main implementation is (Openoffice+swftools+flexpaper) and (Aspose+pdfjs preview).

Main steps:
1. You need to convert the document to a PDF file first.
2. Preview pdf file with Pdfjs

Conversion steps:
* Convert ppt, Word, Excel, txt type files to PDF using Openoffice/aspose

Preview Step:
* High-version browser, using Pdf.js to preview the PDF file directly
* Low version browser, use Swftools to convert PDF file to swf file, then use Flexpaper to preview SWF (without this step)

Component installation:
Aspose
Because the conversion effect of OpenOffice is not very good, here is the choice of aspose
Download the Java version of Aspose at Aspose website, the main choice
* Aspose.words
* Aspose.cells (Excel)
* Aspose.slides (PPT)
* Aspose.pdf
Once the download is complete, you can refer to the jar package in the project.

Function implementation:
All of the component versions used here are:
Name version
Aspose.words 16.8.0
Aspose.cells 9.0.0
Aspose.slides 116.7.0
Aspose.pdf 11.8.0
Convert Document to PDF

Using Aspose for document conversion is straightforward, by introducing the appropriate jar package, invoking the Save method, and converting to PDF.

Attention:
1. When using Aspose, each module (words,cells) may have the same class, such as License class, SaveOptions class, SaveFormat class. And in the use of their own modules, we must use the corresponding module of the class, this pit I have climbed.
When using Aspose, you need to call the Set license method before each conversion operation.

Package com.ybg.pf.oamodule.work.module.convert.util;

Import Org.apache.log4j.Logger;
Import Java.io.FileInputStream;

Import Java.io.InputStream; /** * Aspose Registration Tool * * @author zhumin * @version 1.0.0 * May 16, 2017 15:58 * @since Jdk1.7/public class A

    Sposelicenseutil {private static InputStream InputStream = null;

    private static Logger Logger = Logger.getlogger (Asposelicenseutil.class); /** * Get License Input stream * * @return/private static InputStream Getlicenseinput () {Classloa
        Der Contextclassloader = Thread.CurrentThread (). Getcontextclassloader ();
            try {String path = Contextclassloader.getresource ("License.xml"). Touri (). GetPath ();

        InputStream = new FileInputStream (path);
        catch (Exception e) {logger.error ("License not found!", e);
    return inputstream; /** * Set License * * @return TRUE indicates that license was successfully set, false indicates failure/PUBlic static Boolean Setwordslicense () {InputStream licenseinput = Getlicenseinput (); if (licenseinput!= null) {try {com.aspose.words.License aposelic = new Com.aspose.words.Lic
                Ense ();
                Aposelic.setlicense (Licenseinput);
            return aposelic.getislicensed ();
            catch (Exception e) {logger.error ("Set words License error!", e);
    return false; /** * Set License * * @return TRUE indicates that license was set successfully, false indicates failure/public static Boolean Setcells
        License () {InputStream licenseinput = Getlicenseinput (); if (licenseinput!= null) {try {com.aspose.cells.License aposelic = new Com.aspose.cells.Lic
                Ense ();
                Aposelic.setlicense (Licenseinput);
            return true;
            catch (Exception e) {logger.error ("Set cells License error!", e);
    }    return false; /** * Set License * * @return TRUE indicates that license was set successfully, false indicates failure/public static Boolean Setslide
        Slicense () {InputStream licenseinput = Getlicenseinput (); if (licenseinput!= null) {try {com.aspose.slides.License aposelic = new COM.ASPOSE.SLIDES.L
                Icense ();
                Aposelic.setlicense (Licenseinput);
            return aposelic.islicensed ();
            catch (Exception e) {logger.error ("set PPT license error!", e);
    return false; /** * Set aspose PDF License * @return True indicates that the setting was successful, false indicates setting failed/public static Boolean Setpdflicen
        Se () {InputStream licenseinput = Getlicenseinput (); if (licenseinput!= null) {try {com.aspose.pdf.License aposelic = new Com.aspose.pdf.License
                ();
                Aposelic.setlicense (Licenseinput);
return true;            catch (Exception e) {logger.error ("set PDF license error!", e);
    return false;
 }
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 5 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114-115

Word Document Conversion Code instance:

Package Com.ybg.pf.oamodule.work.module.convert.service.impl;
Import com.aspose.words.Document;
Import com.aspose.words.PdfSaveOptions;
Import Com.aspose.words.SaveFormat;
Import Com.ybg.pf.oamodule.work.module.convert.domain.ConvertStatus;
Import Com.ybg.pf.oamodule.work.module.convert.service.File2PdfService;
Import Com.ybg.pf.oamodule.work.module.convert.util.AsposeLicenseUtil;

Import Org.apache.log4j.Logger;
Import Java.io.InputStream;

Import Java.io.OutputStream; /** * Convert doc document to PDF file * * * * @author zhumin * @version * * May 16, 2017 15:58 * @since Jdk1.7/public CLA

    SS Doc2pdfserviceimpl implements File2pdfservice {private Logger Logger = Logger.getlogger (GetClass ());
            @Override public convertstatus convert2pdf (InputStream inputstream, OutputStream outputstream) {try {

if (Asposelicenseutil.setwordslicense ()) {Document doc = new document (InputStream); Insertwatermarktext (Doc, "watermark Watermark"); Add toWatermark Pdfsaveoptions pdfsaveoptions = new Pdfsaveoptions ();
                Pdfsaveoptions.setsaveformat (saveformat.pdf); Pdfsaveoptions.getoutlineoptions (). Setheadingsoutlinelevels (3); Setting a Level 3 doc bookmark needs to be saved to the heading in PDF pdfsaveoptions.getoutlineoptions (). Setexpandedoutlinelevels (1);
                Set the default expand Level 1 Doc.save (OutputStream, pdfsaveoptions) in the PDF;
                Inputstream.close ();
                Outputstream.flush ();
                Outputstream.close ();
            return convertstatus.success;
            else {return convertstatus.license_error;
        The catch (Exception e) {return convertstatus.convert_doc2pdf_error;
 }
    }

}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54

Other formats are not attached below will provide code downloads.

Preview Process: First in the background to download the attachment to the project specified temporary directory, in the read download file converted to PDF storage to the temporary directory


This is the directory structure: convertfile attachment Download storage Directory outputfilepdf Store directory

Package com.ybg.pf.oamodule.common.util;
Import Com.ybg.pf.framework.library.util.FileRWUtils;
Import Com.ybg.pf.framework.library.util.LogUtil;
Import Com.ybg.pf.oamodule.work.module.convert.domain.ConvertStatus;
Import Com.ybg.pf.oamodule.work.module.convert.service.File2PdfService;
Import Com.ybg.pf.oamodule.work.module.convert.service.impl.Doc2PdfServiceImpl;
Import Com.ybg.pf.oamodule.work.module.convert.service.impl.Excel2PdfServiceImpl;
Import Com.ybg.pf.oamodule.work.module.convert.service.impl.PPT2PdfServiceImpl;

Import Org.apache.commons.lang.StringUtils;
Import java.io.*;
Import java.net.HttpURLConnection;

Import Java.net.URL;
 /** * Created by the Administrator on 2017/5/11.

    * Online Preview Tool class * File Download tool */public class Previewutils {//conversion service private static File2pdfservice Fileconvertservice;  /** * Office Conversion PDF * @param filename needs to be converted file name * @return * @throws Exception/public static Convertstatus officeconversionpdf (String fileName) throws Exception{//Get file suffix String suffix = filename.substring (Filename.lastindexof (".")
        +1,filename.length ());
        String fileNames = filename.substring (0,filename.lastindexof (".")); Instantiate the corresponding service layer according to the suffix of the file type (stringutils.equalsignorecase (suffix, "docx") | |
        Stringutils.equalsignorecase (suffix, "Doc")) {Fileconvertservice = new Doc2pdfserviceimpl (); }else if (stringutils.equalsignorecase (suffix, "pptx") | |
        Stringutils.equalsignorecase (suffix, "ppt")) {Fileconvertservice = new Ppt2pdfserviceimpl (); }else if (stringutils.equalsignorecase (suffix, "xlsx") | |
        Stringutils.equalsignorecase (suffix, "xls")) {Fileconvertservice = new Excel2pdfserviceimpl ();
        } convertstatus convertstatus = null;
        Gets the path file Officefile = new file (Savepath () +file.separator+filename) where the document needs to be converted; File outputfile = new file (Outpdfpath (fileNames) +file.separator+ filenames+ ". pdf");//pdf save path//If file is PDFCopy directly to the specified directory if (stringutils.equalsignorecase (suffix, "pdf") without converting to {filerwutils.copyfile (Officefile.getpath
            (), Outpdfpath (FileNames));
        return convertstatus;
            } if (!outputfile.exists ()) {InputStream InputStream = new FileInputStream (officefile);
            OutputStream outputstream = new FileOutputStream (outputfile);
        Start conversion convertstatus = Fileconvertservice.convert2pdf (InputStream, OutputStream);
    return convertstatus;
     /** * According to the PDF file name to obtain a PDF storage address * @param filename PDF file name * @return * no plus. Touri () It is possible that the Chinese path will be garbled plus get error */public static string Outpdfpath (String fileName) throws exception{string pathName = Previewutils.class.
        getClassLoader (). GetResource (""). GetPath ();
        File save location If folder does not exist create folder file Savedir = new file (pathname+file.separator+ "outputfile");
        if (!savedir.exists ()) {Savedir.mkdir (); } return SAVedir.getpath (); /** * Get File Save path * @return/public static string Savepath () {String pathName = Previewut
        Ils.class.getClassLoader (). GetResource (""). GetPath ();
        File save location If folder does not exist create folder file Savedir = new file (pathname+file.separator+ "Convertfile");
        if (!savedir.exists ()) {Savedir.mkdir ();
    return Savedir.getpath (); /** * Download the file from the network URL * @param urlstr download Address * @param filename * @param savepath Save Address * @th
        Rows IOException */public static Boolean Downloadfromurl (String urlstr,string filename,string savepath) {
        File File = new file (savepath+file.separator+filename);
        Whether the file already exists if (file.exists ()) {return true;
            try {URL url = new URL (urlstr);
            HttpURLConnection conn = (httpurlconnection) url.openconnection ();
          Set the timeout time to 30 seconds conn.setconnecttimeout (30*1000);  Prevent screen program crawl and return 403 error Conn.setrequestproperty ("User-agent", "mozilla/4.0" (compatible; MSIE 5.0; Windows NT;
            Digext) ");
            Get input stream InputStream InputStream = Conn.getinputstream ();
            Get own array byte[] GetData = Readinputstream (InputStream);
            FileOutputStream fos = new FileOutputStream (file);
            if (GetData = = null) {return false;
            } fos.write (GetData);
            if (fos!=null) {fos.close ();
            } if (Inputstream!=null) {inputstream.close ();
            } if (Conn.getresponsecode () = = HTTPURLCONNECTION.HTTP_OK) {return true;
        The catch (IOException e) {logutil.error ("Error in attachment download conversion PDF!", E);
    return false; /** * Get byte array from input stream * @param inputstream * @return * @throws ioexception * * Public Stati C byte[] Readinputstream (inpuTstream InputStream) throws IOException {byte[] buffer = new byte[1024];
        int len = 0;
        Bytearrayoutputstream BOS = new Bytearrayoutputstream ();
        while (len = inputstream.read (buffer))!=-1) {bos.write (buffer, 0, Len);
        } bos.close ();
    return Bos.tobytearray ();
 }


}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 5, 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 11 9 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148-149 150 151 152 153 154 155

Because we want to integrate into our own project, so here directly copy the viewer.html page, modify for our engineering needs of view_pdfjs.jsp, which made some changes to remove some unwanted features
Below is my revised preview page effect chart:

<%@ page import= "com.ybg.pf.oamodule.common.constant.JspCommonConstant"%> <%@ page contenttype= "text/html";
Charset=utf-8 "Language=" java%> <% String qiyehaoprojectpath = Jspcommonconstant.getprojectbasepath (); %> <! DOCTYPE html> <!--Copyright Foundation Mozilla licensed under the Apache License, Version 2.0 ("License")
;
You are not to use this file except in compliance with the License. Obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 unless required by applicable Agreed to in writing, software distributed under the License was distributed on a ' as is ' basis, without warranties OR CON
Ditions of any KIND, either express or implied.

The License for the specific language governing permissions and limitations under the License. Adobe CMap are covered by their own copyright but the same license:copyright 1990-2015 adobe Systems Incorpora

Ted. Https://github.com/adobe-type-tools/cmap-resOurces-->   

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.