Java实现word文档转换pdf文档

前言

1、aspose是什么?

自己去官网看吧,功能很多,各种文档之间的互相转换

2、接口

2.1、word转pdf的主要实现接口

    /*
     * 将doc文件返回成pdf的二进制文件
     * @param fileName doc 或者 docx的文件的路径
     * @param in
     */
    public static byte[] transform(String fileName, InputStream in)  {
        byte[] bytes = null;
        try {
            getLicense();  //这一步是授权 window系统的话不需要这一步也没有问题,linnux系统没有这一步转换的文件回乱码;
            if (fileName.endsWith(".doc") || fileName.endsWith(".docx") || fileName.endsWith(".rtf")) {
                final com.aspose.words.Document doc = new com.aspose.words.Document(in);
                in.close();
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                doc.save(stream, com.aspose.words.SaveFormat.PDF);
                bytes = stream.toByteArray();
            }
        } catch (Exception ex) {
            return bytes;
        }
        return bytes;
    }

2.2、完成授权(否则会中文乱码)

    /*
     *  aspose授权
     */
    public static boolean getLicense() {
        try {
            final String xml = "<License>\r\n  <Data>\r\n    <Products>\r\n      <Product>Aspose.Total for Java</Product>\r\n      <Product>Aspose.Words for Java</Product>\r\n    </Products>"
                    + "\r\n    <EditionType>Enterprise</EditionType>\r\n    <SubscriptionExpiry>20991231</SubscriptionExpiry>\r\n    <LicenseExpiry>20991231</LicenseExpiry>\r\n    "
                    + "<SerialNumber>23dcc79f-44ec-4a23-be3a-03c1632404e9</SerialNumber>\r\n  </Data>\r\n  <Signature>2sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKd"
                    + "jV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\r\n</License>\r\n";
            final InputStream is = new ByteArrayInputStream(xml.getBytes());
            final License lic = new License();
            lic.setLicense(is);
            is.close();
             registerFonts();//注册字体
        } catch (Exception e) {
            return false;
        }
        return true;
    }

2.3、注册字体

    /*
     * 注册中文字段,否则会中文乱码
     */
    public static void registerFonts() throws Exception {
        String path = SwordFileUtils.getSwordRootPath();
        int lastNum = path.lastIndexOf("WEB-INF");
        if(lastNum !=-1){
            path = path.substring(0, lastNum - 1);
        }else if(path.lastIndexOf("APP-INF") != -1){
            path = path.substring(0, path.lastIndexOf("APP-INF") - 1);
        }
        final String fontPath = path + File.separator+"swordweb"+File.separator+"biz"+File.separator+"wordtopdf"+File.separator+"fonts";
        FontSettings.setFontsFolder(fontPath, false);
    }

3、总结

其中最主要的部分是引入的包,可以联系我,或者网上找一找很多的

猜你喜欢

转载自blog.csdn.net/qq_42722951/article/details/101352411