Java implements online preview, supports doc/docx/pptx/ppt/xls/xlsx format to pdf for online preview

Abstract: In the process of the project, it is proposed that the doc should be previewed online and the pagination function should be realized.

Disadvantages of front-end implementation: 1. Only docx files can be previewed, not compatible with doc, and the back-end is forced to convert doc to docx files, and the front-end cannot realize preview. 2. The front end cannot perform paging display.

1. The back-end implementation needs to introduce the jar package. The following is the common jar analysis:

Based on Openoffice Based on libreOffice Based on Office Based on Pio + Itext Based on Aspose
Cross-platform Cross-platform Cross-platform Windows only Cross-platform Cross-platform
Whether to install software Openoffice needs to be installed libreOffice needs to be installed MicrosoftOffice needs to be installed No No
Is there a fee Free Free Software charges Free Jar package charges (crackable)
Advantages Cross-platform documentation Conversion distortion is small. Cross-platform conversions are relatively fast. For Office, it can guarantee less distortion, especially the cross-platform conversion speed of Word documents. Support cross-platform.

No need to install software, less distortion.

Disadvantages Need to install additional software Need to install additional software, low efficiency

No cross-platform need to install Office Office charges Different Office versions have different effects (unstable)

The style distortion is particularly serious and the efficiency is extremely low. The technology is complicated fees (but can be cracked), even if you pay, the source code is not provided (official website)

On the whole, Aspose-based is the optimal way, and the following is the implementation method.

Two, realize

1. jar package reference

 <!--file to pdf tool class-->
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-words</artifactId>
            <version>15.8.0</version>
        </dependency>
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-cells</artifactId>
            <version>8.5.2</version>
        </dependency>
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-slides</artifactId>
            <version>15.9.0</version>
        </dependency>

2. Tools

import com.aspose.cells.Workbook;
import com.aspose.slides.Presentation;
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;

import java.io.*;

/**
 * @Classname OnlinePreviewUtil
 * @Description TODO
 * @Date 2023/8/8 10:15
 * @Created by laity2020
 * @Author:Yan
 */
public class OnlinePreviewUtil {

    /**
     * file conversion
     *
     * @param source: source file address such as: C://test/test.doc, target: converted file path such as C://test/pdf
     * @return
     */
    public static String officeToPdf(InputStream source, OutputStream target, String fileName) {

        String fileExt = fileName. substring(fileName. lastIndexOf(".") + 1);
        if ("doc".equals(fileExt) || "docx".equals(fileExt)) {
            doc2pdf(source, target);
        }
        if ("xls".equals(fileExt) || "xlsx".equals(fileExt)) {
            excel2pdf(source, target);
        }
        if ("ppt".equals(fileExt) || "pptx".equals(fileExt)) {
            ppt2pdf(source, target);
        }

        if ("doc,docx,xls,xlsx,ppt,pptx".indexOf(fileExt) > 0) {
            return target + File. separator + (fileName. replace(fileExt, "pdf"));
        }
        return null;
    }

    /**
     * @description: Verify ExcelLicense
     */
    public static boolean getExcelLicense() {
        boolean result = false;
        try {
            // license.xml should be placed in ..\WebRoot\WEB-INF\classes path
            InputStream is = OnlinePreviewUtil.class.getClassLoader().getResourceAsStream("license.xml");
            com.aspose.cells.License aposeLic = new com.aspose.cells.License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @description: Verify PPTtlLicense
     */
    public static boolean getPPTLicense() {
        boolean result = false;
        try {
            // license.xml should be placed in ..\WebRoot\WEB-INF\classes path
            InputStream is = OnlinePreviewUtil.class.getClassLoader().getResourceAsStream("license.xml");
            com.aspose.slides.License aposeLic = new com.aspose.slides.License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @description: Verify License
     */
    public static boolean getDocLicense() {
        boolean result = false;
        try {
            // license.xml should be placed in ..\WebRoot\WEB-INF\classes path
            InputStream is = OnlinePreviewUtil.class.getClassLoader().getResourceAsStream("license.xml");
            com.aspose.words.License aposeLic = new com.aspose.words.License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @description: doc to pdf
     * @params: source: source file, target: converted file
     */
    public static void doc2pdf(InputStream source, OutputStream target) {
        // Verify License If not verified, the converted pdf document will have a watermark
        if (!getDocLicense()) {
            return;
        }
        try {
            Document doc = new Document(source);
            doc.save(target, com.aspose.words.SaveFormat.PDF);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * @description: convert excel to pdf
     * @params: source: source file address, target: converted file path, fileExt: suffix
     */
    public static void excel2pdf(InputStream source, OutputStream target) {
        // Verify License If not verified, the converted pdf document will have a watermark
        if (!getExcelLicense()) {
            return;
        }
        try {
            // original excel path
            Workbook wb = new Workbook(source);
            wb.save(target, com.aspose.cells.SaveFormat.PDF);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @description: ppt to pdf
     * @params: source: source file address, target: converted file path, fileExt: suffix
     */
    public static void ppt2pdf(InputStream source, OutputStream target) {
        // Verify License If not verified, the converted pdf document will have a watermark
        if (!getPPTLicense()) {
            return;
        }
        try {
            //Enter the pdf path
            Presentation pres = new Presentation(source);
            pres. save(target, SaveFormat. PDF);
            target. close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

3. xml configuration file

<License>
    <Data>
        <Products>
            <Product>Aspose.Total for Java</Product>
            <Product>Aspose. Words for Java</Product>
        </Products>
        <EditionType>Enterprise</EditionType>
        <SubscriptionExpiry>20991231</SubscriptionExpiry>
        <LicenseExpiry>20991231</LicenseExpiry>
        <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
    </Data>
    <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo + d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoo hTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>

4. For the calling method, I use the form of file stream to reduce the generation of files.

 OnlinePreviewUtil.officeToPdf(inputStream, outputStream(),realName);

Note: 1. In this process, the editor tried many methods, because the project uses poi, and introduces dom4j, itextpdf and fr.opensagres.poi.xwpf.converter.pdf-gae Sometimes the conversion of the file to pdf fails due to jar package conflicts. The above is a perfect way to achieve no poi conflicts, so it is recorded.

2. The Windows deployment is normal, but the fonts will be garbled after the Linux download, because there are no Windows fonts on Linux. The solution is as follows:

1. Upload the font of C:\Windows\Fonts on windows to the /usr/share/fonts/ directory of linux, and then execute it on linux

cd /usr/share/fonts/Chinese/

mkfontscale (create fonts.scale file of fonts, which is used to control font rotation and scaling)

mkfontdir (creates the fonts.dir file of the font, which is used to control the bold and italic generation of the font)

fc-cache (refresh font cache)

Finally, add FontSettings.setFontsFolder(“/usr/share/fonts/”, true); before doc.save.

The jar download is attached at the end.

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Java skill treeHomepageOverview 126650 people are studying systematically