1. 程式人生 > >java實現office檔案的線上預覽

java實現office檔案的線上預覽

參考文章:PDF技術(一)-Java實現Office系列檔案轉PDF檔案

利用aspose.jar來實現將檔案轉pdf,再傳前臺,實現預覽。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import org.apache.log4j.Logger;

import com.aspose.cells.CellsHelper;
import com.aspose.cells.Workbook;
import com.aspose.cells.Worksheet;

import com.aspose.words.FontSettings;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;

import wt.log4j.LogR;

/**
* @功能描述 aspose Excel轉pdf
*/
public class OfficeToPdf {
	
	private static final String FONT = File.separator + "util" + File.separator
			+ "fonts" + File.separator ;//字型資料夾
	private static final Logger LOGGER = LogR.getLogger(DocController.class.getName());
	 public static void main(String[] args) throws IOException, DocumentException{
    	 excel2pdf("D:/logs/SpringBoot.xls");
//    	 doc2pdf("d:/logs/SpringBoot.docx");
//    	 text2pdf("d://logs//123.txt","d://logs//SpringBoot.pdf");
    	}
	 /**
	 * 簽名驗證
	 * @return
	 * @throws IOException 
	 * @throws Exception 
	 */
    public static boolean getWordLicense() throws IOException {
        boolean result = false;
        InputStream is = null;
        try {
            is = OfficeToPdf.class.getResourceAsStream("license.xml"); //  license.xml應放在..\WebRoot\WEB-INF\classes路徑下
            com.aspose.words.License aposeLic = new com.aspose.words.License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        	if (is != null) {
        		is.close();
        	}
        }
        return result;
    }
	 
	 
	/**
	 * Excel簽名驗證
	 * @return
	 * @throws IOException 
	 * @throws Exception 
	 */
    public static boolean getExcelLicense() throws IOException {
        boolean result = false;
        InputStream is = null;
        try {
            is = OfficeToPdf.class.getResourceAsStream("license.xml"); //  license.xml應放在..\WebRoot\WEB-INF\classes路徑下
            com.aspose.cells.License aposeLic = new com.aspose.cells.License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        	if (is != null) {
        		is.close();
        	}
        }
        return result;
    }
	/**
	 * excel轉PDF
	 * @return
	 * @throws IOException 
	 * @throws Exception 
	 */
    public static void excel2pdf(String fileName) throws IOException {
        if (!getExcelLicense()) {          // 驗證License 若不驗證則轉化出的pdf文件會有水印產生
            return;
        }
        FileOutputStream fileOS = null;
        try { 	
            long old = System.currentTimeMillis();          
            Workbook wb = new Workbook(fileName);// 原始excel路徑
            fileName = fileName.substring(0,fileName.lastIndexOf(".")+1) + "pdf";
            File file = new File(fileName);// 輸出路徑
            for (int i = 0;i<wb.getWorksheets().getCount();i++){
            	Worksheet worksheet = wb.getWorksheets().get(i);
            	worksheet.getPageSetup().setZoom(50);//設定縮放比例       
            }   
            
            CellsHelper.setFontDir(FONT);  //這裡應該是字型路徑
            
            fileOS = new FileOutputStream(file);            
            wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);
            fileOS.close();
            long now = System.currentTimeMillis();
            LOGGER.info("共耗時:" + ((now - old) / 1000.0) + "秒\n\n");//轉化過程耗時
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        	if (fileOS!=null){
        		fileOS.close();
        	}
        }
    }
	
    /**
	 * doc轉PDF
	 * @param filename
	 * @return
	 * @throws IOException 
	 * @throws Exception 
	 */
    public static void doc2pdf(String filename) throws IOException {
        if (!getWordLicense()) {          // 驗證License 若不驗證則轉化出的pdf文件會有水印產生
            return;
        }
        FileOutputStream os = null;
        try {
            long old = System.currentTimeMillis();
            com.aspose.words.Document doc = new com.aspose.words.Document(filename);     //Address是將要被轉化的word文件          
            filename = filename.substring(0,filename.lastIndexOf(".")+1) + "pdf";
            File file = new File(filename);  //新建一個空白pdf文件
            os = new FileOutputStream(file);
            //設定字型來源
            FontSettings.setFontsFolder(FONT, true);
//          doc.save("d:/logs/機構案例庫入口配置檔案.html", SaveFormat.HTML);//轉html格式
            
            doc.save(os, com.aspose.words.SaveFormat.PDF);//全面支援DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互轉換
            long now = System.currentTimeMillis();
            LOGGER.info("共耗時:" + ((now - old) / 1000.0) + "秒\n\n");//轉化過程耗時
            os.close();
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        	if (os != null){
        		os.close();
        	}
        }
  
    }
    /**
	 * txt轉pdf
	 * @param doc
	 * @return
	 * @throws Exception 
	 */
	public static void text2pdf(String text, String pdf) throws DocumentException, IOException {
		com.itextpdf.text.Document document = new com.itextpdf.text.Document();
		OutputStream os = new FileOutputStream(new File(pdf));
		PdfWriter.getInstance(document, os);
		document.open();
		BaseFont baseFont = BaseFont.createFont(FONT +"simsun.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		Font font = new Font(baseFont);
		InputStreamReader isr = new InputStreamReader(new FileInputStream(new File(text)), "GBK");
		BufferedReader bufferedReader = new BufferedReader(isr);
		String str = "";
		while ((str = bufferedReader.readLine()) != null) {
			document.add(new Paragraph(str, font));
		}
		document.close();
		bufferedReader.close();
		isr.close();
		os.close();
	}
	
}