aspose-words、itextpdf完美解决java将word、excel、ppt、图片转换为pdf文件

这篇具有很好参考价值的文章主要介绍了aspose-words、itextpdf完美解决java将word、excel、ppt、图片转换为pdf文件。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

我是傲骄鹿先生,沉淀、学习、分享、成长。

如果你觉得文章内容还可以的话,希望不吝您的「一键三连」,文章里面有不足的地方希望各位在评论区补充疑惑、见解以及面试中遇到的奇葩问法

面对日常开发过程中,将各种文件转换为pdf文件的问题,总是让人头疼,这次终于完美解决了!

最好的效果无非就是在不限制文件大小、保持文件格式的情况下将文件转换为pdf格式文件,而且转换完成的文件不带水印,这样的效果应该可以满足很多需求了,之前在遇到这个问题的时候是使用spire.doc实现的,但效果很不好,每一页都是带水印的。下面将这是的方法展示给大家供大家参考。

一、集成aspose-words

实现文档转换为pdf文件需要的包是aspose-words-15.8.0,如果大家找不到包可以私信我,这里就不做链接了。

1、集成aspose-words-15.8.0

因为项目中使用的是阿里云的maven仓库,不能进行导包,就需要手动的将包导入到项目中。如图所示,将包放入到项目中。

java ppt转pdf,Spring Boot  2.x,word,pdf

包的位置是与src并列的位置,然后在pom文件中进行配置:

java ppt转pdf,Spring Boot  2.x,word,pdf

除了上面手动导入的包之外,还有其他用的包,在pom文件中添加即可。

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>4.1.2</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.4.3</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>

        <dependency>
            <groupId>org.docx4j</groupId>
            <artifactId>docx4j</artifactId>
            <version>3.2.2</version>
        </dependency>


        <!-- 下面的依赖是为了报其他错误的 -->
        <dependency>
            <groupId>org.apache.xmlbeans</groupId>
            <artifactId>xmlbeans</artifactId>
            <version>5.0.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-compress</artifactId>
            <version>1.19</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.1</version>
        </dependency>

        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>SparseBitSet</artifactId>
            <version>1.2</version>
        </dependency>


        <!-- 修改com.aspose.cells专用包 -->
        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.26.0-GA</version>
        </dependency>

二、编写工具类

package com.dtech.common.utils.file;

import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import org.apache.poi.hslf.usermodel.*;
import org.apache.poi.xslf.usermodel.*;

import java.awt.*;
import java.awt.Font;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;


/**
 * java将word、excel、ppt、图片转换为pdf文件
 */
public class PdfConverUtil {
    /**
     * @param inputStream  源文件输入流
     * @param outputStream pdf文件输出流
     **/
    public static boolean imgToPdf(InputStream inputStream, OutputStream outputStream) {

        Document document = null;
        try {
            // 创建文档,设置PDF页面的大小 A2-A9, 个人觉得A3最合适
            document = new Document(PageSize.A3, 20, 20, 20, 20);
            // 新建pdf文档,具体逻辑看.getInstance方法
            PdfWriter.getInstance(document, outputStream);
            document.open();
            document.newPage();
            // 将文件流转换为字节流,便于格式转换
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int length = 0 ;
            while (-1 != (length = bufferedInputStream.read(bytes))) {
                byteArrayOutputStream.write(bytes, 0, length);
            }
            // 处理img图片
            Image image = Image.getInstance(byteArrayOutputStream.toByteArray());
            float height = image.getHeight();
            float width = image.getWidth();
            float percent = 0.0f;
            // 设置像素或者长宽高,将会影响图片的清晰度,因为只是对图片放大或缩小
            if (height > width) {
                // A4 - A9
                percent = PageSize.A4.getHeight() / height * 100;
            } else {
                percent = PageSize.A4.getWidth() / width * 100;
            }
            image.setAlignment(Image.MIDDLE);
            image.scalePercent(percent);
            // 将图片放入文档中,完成pdf转换
            document.add(image);
//            System.out.println("image转换完毕");
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (document != null) {
                    document.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    /**
     * @param inputStream  源文件输入流
     * @param outputStream pdf文件输出流
     **/
    public static boolean wordTopdfByAspose(InputStream inputStream, OutputStream outputStream) {
        // 验证License 若不验证则转化出的pdf文档会有水印产生
        if (!getLicense()) {
            return false;
        }
        try {
            // 将源文件保存在com.aspose.words.Document中,具体的转换格式依靠里面的save方法
            com.aspose.words.Document doc = new com.aspose.words.Document(inputStream);

            // 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,EPUB, XPS, SWF 相互转换
            doc.save(outputStream, SaveFormat.PDF);
//            System.out.println("word转换完毕");
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }finally {
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;

    }

    // 官方文档的要求 无需理会
    public static boolean getLicense() {
        boolean result = false;
        try {
            String s = "<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/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature></License>";
            ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @param inputStream  源文件输入流
     * @param outputStream pdf文件输出流
     **/
    public static boolean excelToPdf(InputStream inputStream, OutputStream outputStream) {
        // 验证License 若不验证则转化出的pdf文档会有水印产生
        if (!getExeclLicense()) {
            return false;
        }
        try {
            com.aspose.cells.Workbook wb = new com.aspose.cells.Workbook(inputStream);// 原始excel路径
            com.aspose.cells.PdfSaveOptions pdfSaveOptions = new com.aspose.cells.PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(false);

            int[] autoDrawSheets={3};
            //当excel中对应的sheet页宽度太大时,在PDF中会拆断并分页。此处等比缩放。
            autoDraw(wb,autoDrawSheets);
            int[] showSheets={0};
            //隐藏workbook中不需要的sheet页。
            printSheetPage(wb,showSheets);
            wb.save(outputStream, pdfSaveOptions);
            outputStream.flush();
            outputStream.close();
            System.out.println("excel转换完毕");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }


    /**
     * 设置打印的sheet 自动拉伸比例
     * @param wb
     * @param page 自动拉伸的页的sheet数组
     */
    public static void autoDraw(com.aspose.cells.Workbook wb,int[] page){
        if(null!=page&&page.length>0){
            for (int i = 0; i < page.length; i++) {
                wb.getWorksheets().get(i).getHorizontalPageBreaks().clear();
                wb.getWorksheets().get(i).getVerticalPageBreaks().clear();
            }
        }
    }

    /**
     * 隐藏workbook中不需要的sheet页。
     *
     * @param wb
     * @param page 显示页的sheet数组
     */
    public static void printSheetPage(com.aspose.cells.Workbook wb, int[] page) {
        for (int i = 1; i < wb.getWorksheets().getCount(); i++) {
            wb.getWorksheets().get(i).setVisible(false);
        }
        if (null == page || page.length == 0) {
            wb.getWorksheets().get(0).setVisible(true);
        } else {
            for (int i = 0; i < page.length; i++) {
                wb.getWorksheets().get(i).setVisible(true);
            }
        }
    }

    public static boolean getExeclLicense() {
        boolean result = false;
        try {
            String s = "<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/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature></License>";
            ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());
            com.aspose.cells.License aposeLic = new com.aspose.cells.License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * pptToPdf
     * @param inputStream
     * @param outputStream
     * @return
     */
    public static boolean pptToPdf(InputStream inputStream, OutputStream outputStream) {
        Document document = null;
        HSLFSlideShow hslfSlideShow = null;
        PdfWriter pdfWriter = null;

        try {
            hslfSlideShow = new HSLFSlideShow(inputStream);
            // 获取ppt文件页面
            Dimension dimension = hslfSlideShow.getPageSize();
            document = new Document();
            // pdfWriter实例
            pdfWriter = PdfWriter.getInstance(document, outputStream);
            document.open();
            PdfPTable pdfPTable = new PdfPTable(1);
            List<HSLFSlide> hslfSlideList = hslfSlideShow.getSlides();
            for (int i=0; i < hslfSlideList.size(); i++) {
                HSLFSlide hslfSlide = hslfSlideList.get(i);
                // 设置字体, 解决中文乱码
                for (HSLFShape shape : hslfSlide.getShapes()) {
                    HSLFTextShape textShape = (HSLFTextShape) shape;

                    for (HSLFTextParagraph textParagraph : textShape.getTextParagraphs()) {
                        for (HSLFTextRun textRun : textParagraph.getTextRuns()) {
                            textRun.setFontFamily("宋体");
                        }
                    }
                }
                BufferedImage bufferedImage = new BufferedImage((int)dimension.getWidth(), (int)dimension.getHeight(), BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics2d = bufferedImage.createGraphics();
                graphics2d.setPaint(Color.white);
                graphics2d.setFont(new Font("宋体", Font.PLAIN, 12));
                hslfSlide.draw(graphics2d);
                graphics2d.dispose();

                Image image = Image.getInstance(bufferedImage, null);
                image.scalePercent(50f);
                // 写入单元格
                pdfPTable.addCell(new PdfPCell(image, true));
                document.add(image);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (document != null) {
                document.close();
            }
            if (pdfWriter != null) {
                pdfWriter.close();
            }
        }
//        System.out.println("ppt转换完毕");
        return true;
    }

    /**
     *  pptxToPdf
     * @param inputStream
     * @param outputStream
     * @return
     */
    public static boolean pptxToPdf(InputStream inputStream, OutputStream outputStream) {
        Document document = null;
        XMLSlideShow slideShow = null;
        PdfWriter pdfWriter = null;
        try {

            slideShow = new XMLSlideShow(inputStream);
            Dimension dimension = slideShow.getPageSize();
            document = new Document();
            pdfWriter = PdfWriter.getInstance(document, outputStream);
            document.open();
            PdfPTable pdfPTable = new PdfPTable(1);
            List<XSLFSlide> slideList = slideShow.getSlides();
            for (int i = 0, row = slideList.size(); i < row; i++) {
                XSLFSlide slide = slideList.get(i);
                // 设置字体, 解决中文乱码
                for (XSLFShape shape : slide.getShapes()) {
                    XSLFTextShape textShape = (XSLFTextShape) shape;
                    for (XSLFTextParagraph textParagraph : textShape.getTextParagraphs()) {
                        for (XSLFTextRun textRun : textParagraph.getTextRuns()) {
                            textRun.setFontFamily("宋体");
                        }
                    }
                }
                BufferedImage bufferedImage = new BufferedImage((int)dimension.getWidth(), (int)dimension.getHeight(), BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics2d = bufferedImage.createGraphics();
                graphics2d.setPaint(Color.white);
                graphics2d.setFont(new Font("宋体", Font.PLAIN, 12));
                slide.draw(graphics2d);
                graphics2d.dispose();
                Image image = Image.getInstance(bufferedImage, null);
                image.scalePercent(50f);

                // 写入单元格
                pdfPTable.addCell(new PdfPCell(image, true));
                document.add(image);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (document != null) {
                document.close();
            }
            if (pdfWriter != null) {
                pdfWriter.close();
            }
        }
        System.out.println("pptx转换完毕");
        return true;
    }
}

 三、使用工具类进行文件转换

完成工具类编写就可以进行文件转换了,这里根据业务,将word文件进行上传服务器,然后在将服务器的word文件转换为pdf文件,访问端即可进行pdf文件预览了。


续:将代码打包上传至服务器后,转换完成的pdf文件是乱码

在window下没有问题但是在linux下有问题,说明不是代码或者输入输出流编码的问题,原因是两个平台环境的问题。说明linux环境中缺少相应的字体以供使用,可能会导致导出的文件字体乱码,或者更新域错乱问题。解决办法如下:更新字体

1、在linux环境下安装win字体,将win机器的C:\Windows\Fonts目录下的全部文件拷贝到linux服务器字体安装目录下,然后执行以下命令更新字体缓存。

java ppt转pdf,Spring Boot  2.x,word,pdf

2、linux服务器字体文件是在/usr/share/fonts文件夹下的,在fonts文件夹下新建一个文件夹chinese,然后把window环境中的字体上传到服务器中

java ppt转pdf,Spring Boot  2.x,word,pdf

3、执行命令,让字体生效

cd /usr/share/fonts 
sudo fc-cache -fv

 4、修改代码,设置字体

java ppt转pdf,Spring Boot  2.x,word,pdf

系列文章持续更新,微信搜一搜「傲骄鹿先生 」,回复【面试】有准备的一线大厂面试资料。文章来源地址https://www.toymoban.com/news/detail-773830.html

到了这里,关于aspose-words、itextpdf完美解决java将word、excel、ppt、图片转换为pdf文件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Java【代码 16】将word、excel文件转换为pdf格式和将pdf文档转换为image格式工具类分享(Gitee源码)aspose转换中文乱码问题处理

    感谢小伙伴儿的分享: ● 不羁 ● 郭中天 整合调整后的工具类Gitee地址:https://gitee.com/yuanzhengme/java_application_aspose_demo ● WordToPdfUtil用于将word文档转换为pdf格式的工具类 ● ExcelToPdfUtil用于将excel文档转换为pdf格式的工具类 ● PdfToImageUtil用于将pdf文档转换为image格式的工具类

    2024年01月24日
    浏览(49)
  • 【工具插件类教学】Unity通过Aspose读取并显示打开PDF,PPT,Excel,Word

    目录 一、获取Aspose支持.Net的DLL 二、导入Unity的Plugin文件夹 三、分别编写四种文件的读取显示

    2024年02月02日
    浏览(40)
  • Java的POI-word模板生成目录自动更新--完美解决

    目录问题: 解决word模板目录在第一次打开不更新就不显示目录问题的原因:之前是通过动态替换域代码toc的形式,生成了一段域代码放置在Word的目录行,打开的时候无法直接触发渲染和更新。 方案:通过插入-文档组件-域组件-目录和索引,将当前的模板的目录直接生成到文

    2024年02月11日
    浏览(27)
  • Java将Word转换成PDF-aspose

    本文将演示用aspose-word.jar包来实现将Word转换成PDF,且可以保留图表和图片。 在公司OA项目开发中, 需要将word版本的合同模板上传,业务员只能下载pdf版本合同模板,需要实现将Word转换成PDF,并且动态填充项目编号以及甲乙方信息等。 Aspose.Words for Java是一个原生库,为开发

    2024年02月07日
    浏览(39)
  • Java版Word开发工具Aspose.Words基础教程:检测文件格式并检查格式兼容性

    Aspose.Words for Java是功能丰富的文字处理API,开发人员可以在自己的Java应用程序中嵌入生成,修改,转换,呈现和打印Microsoft Word支持的所有格式的功能。它不依赖于Microsoft Word,但是它提供了Microsoft Word通过其API支持的功能。 Aspose.Words for Java最新下载 https://www.evget.com/product/

    2024年02月14日
    浏览(33)
  • itextpdf实现word模板生成文件

    使用word模板生成文件,如下图,将左侧的模板生成为右侧的填充word文档。 引入依赖 创建模板,创建一份template2.docx文件,内容如下 编写代码 编写测试用例,并执行测试用例 生成得到被填充出来的文件。

    2024年02月11日
    浏览(33)
  • Java 使用 poi 和 aspose 实现 word 模板数据写入并转换 pdf 增加水印

    本项目所有源码和依赖资源都在文章顶部链接,有需要可以下载使用 1. 需求描述 从指定位置读取一个 word 模板 获取业务数据并写入该 word 模板,生成新的 word 文档 将新生成的 word 文档转换为 pdf 格式 对 pdf 文档添加水印 2. 效果预览 word 模板 带水印的 pdf 文档 3. 实现思路

    2024年02月08日
    浏览(36)
  • Word控件 Aspose.words for.NET 授权须知

    Aspose.Words 是一种高级Word文档处理API,用于执行各种文档管理和操作任务。API支持生成,修改,转换,呈现和打印文档,而无需在跨平台应用程序中直接使用Microsoft Word。此外, Aspose API支持流行文件格式处理,并允许将各类文档导出或转换为固定布局文件格式和最常用的图像

    2024年02月04日
    浏览(36)
  • 使用Aspose.Words将word转PDF并且去水印。

    😜 作           者 :是江迪呀 ✒️ 本文 : Java 、 工具类 、 转换 、 word转pdf 、 Aspose.Words 、 后端 ☀️ 每日   一言 : 只要思想不滑坡,办法总比困难多。 在我们日常开发中经常会有将 word文档 转为 PDF 的场景,有很多种方法我最倾向的的是使用 Aspose.Words ,原

    2024年02月11日
    浏览(40)
  • Aspose导出word使用记录

    背景 :Aspose系列的控件,功能实现都比较强大,可以实现多样化的报表设计及输出。 通过这次业务机会,锂宝碳审核中业务功需要实现Word文档表格的动态导出功能,因此学习了相关内容,在学习和参考了官方API文档的帮助下,将学习和简单的使用记录在wiki中。下面由我来简

    2024年02月10日
    浏览(40)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包