Java office file preview online is a requirement that you may come across in your work. Some companies on the Internet offer this service, but for a fee. If you want to do this for free, you can use OpenOffice.
Use openOffice to convert Word, Excel, PPT, and TXT files into PDF files.
Of course, if you have Adobe Reader XI installed, you can preview the PDF directly by dragging it to the browser page, provided that the browser supports PDF file viewing.
I’m here to introduce the poI implementation of Word, Excel, PPT to PDF streams, so that you can achieve preview on the browser.
1. Download the Apache OpenOffice installation package from the official website, install it, and run it.
Different system installation methods, their own baidu, here do not do too much description.
2. Import dependencies into the PROJECT POM file
<! --openoffice--> <dependency> <groupId>com.artofsolving</groupId> <artifactId>jodconverter</artifactId> The < version > 2.2.1 < / version > < / dependency >Copy the code
3. Tool class code for converting Word, Excel and PPT into PDF streams
import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry; import com.artofsolving.jodconverter.DocumentConverter; import com.artofsolving.jodconverter.DocumentFormat; import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection; import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection; import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; /** * file format conversion tools ** @author Tarzan * @version 1.0 * @since JDK1.8 */ public class FileConvertUtil {/** default conversion file suffix */ private static final String DEFAULT_SUFFIX = "pdf"; /** openoffice_port */ private static final Integer OPENOFFICE_PORT = 8100; /** * method description convert office documents to PDF(processing local files) ** @param sourcePath source file path * @param suffix source file suffix * @return InputStream converted file InputStream * @author tarzan */ public static InputStream convertLocaleFile(String sourcePath, String suffix) throws Exception { File inputFile = new File(sourcePath); InputStream inputStream = new FileInputStream(inputFile); return covertCommonByStream(inputStream, suffix); ** @param netFileUrl network file path * @param suffix file suffix * @return InputStream converted file InputStream * @author tarzan */ public static InputStream convertNetFile(String netFileUrl, String suffix) throws Exception {// Create URL URL URL = new URL(netFileUrl); URLConnection urlconn = url.openConnection(); urlconn.connect(); HttpURLConnection httpconn = (HttpURLConnection) urlconn; int httpResult = httpconn.getResponseCode(); if (httpResult == HttpURLConnection.HTTP_OK) { InputStream inputStream = urlconn.getInputStream(); return covertCommonByStream(inputStream, suffix); } return null; } /** * method description convert files as streams ** @param inputStream source file inputStream * @param suffix source file suffix * @return inputStream converted file inputStream * @author tarzan */ public static InputStream covertCommonByStream(InputStream inputStream, String suffix) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); OpenOfficeConnection connection = new SocketOpenOfficeConnection(OPENOFFICE_PORT); connection.connect(); DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection); DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry(); DocumentFormat targetFormat = formatReg.getFormatByFileExtension(DEFAULT_SUFFIX); DocumentFormat sourceFormat = formatReg.getFormatByFileExtension(suffix); converter.convert(inputStream, sourceFormat, out, targetFormat); connection.disconnect(); return outputStreamConvertInputStream(out); } @author Tarzan */ public static ByteArrayInputStream outputStreamConvertInputStream(final OutputStream out) throws Exception { ByteArrayOutputStream baos=(ByteArrayOutputStream) out; return new ByteArrayInputStream(baos.toByteArray()); } public static void main(String[] args) throws IOException { / / convertNetFile (" http://172.16.10.21/files/home/upload/department/base/201912090541573c6abdf2394d4ae3b7049dcee456d4f7.d oc", ".pdf"); //convert("c:/Users/admin/Desktop/2.pdf", "c:/Users/admin/Desktop/3.pdf"); }}Copy the code
4. Preview method code of serve layer online
/** * @description: system file preview interface * @author: tarzan */ public void onlinePreview(String url, HttpServletResponse Response) throws Exception {// Get the file type. String[] STR = SmartStringutil. split(url,"\\."); If (str.length==0){throw new Exception(" file format is incorrect "); } String suffix = str[str.length-1]; if(! suffix.equals("txt") && ! suffix.equals("doc") && ! suffix.equals("docx") && ! suffix.equals("xls") && ! suffix.equals("xlsx") && ! suffix.equals("ppt") && ! Suffix.equals (" PPTX ")){throw new Exception(" file format does not support preview "); } InputStream in=FileConvertUtil.convertNetFile(url,suffix); OutputStream outputStream = response.getOutputStream(); Byte [] buff =new byte[1024]; // Use n to receive int n; // Continue reading while((n=in.read(buff))! Outputstream. write(buff,0,n); } // Force outputstream.flush (); / / off flow outputStream. Close (); in.close(); }Copy the code
5. Controler layer code
@apioperation (value = "system file onlinePreview by Tarzan ") @postmapping ("/ API /file/onlinePreview") public void onlinePreview(@RequestParam("url") String url, HttpServletResponse response) throws Exception{ fileService.onlinePreview(url,response); }Copy the code
Original link: blog.csdn.net/weixin_4098…
Copyright notice: This article is originally published BY CSDN blogger “Luoyang Taishan”. It is subject to CC 4.0 BY-SA copyright agreement. Please attach the original source link and this statement.
Recent hot articles recommended:
1.1,000+ Java Interview Questions and Answers (2021)
2. Don’t use if/ else on full screen again, try strategy mode, it smells good!!
3. Oh, my gosh! What new syntax is xx ≠ null in Java?
4.Spring Boot 2.6 is out with a lot of new features.
5. “Java Development Manual (Songshan version)” the latest release, quick download!
Feel good, don’t forget to click on + forward oh!