java 实现 ppt或pptx文件转换PDF文件 -- poi

前提:

由于ppt和pptx文件格式不同,ppt是基于二进制的文件,而pptx是基于xml文件, 也是就pptx是2007年后出现的新的ppt版本,对这两种文件处理方式转换PDF其实都差不多,只是要注意接收文件ppt或pptx以及获取两种文件内容 需要的类处理,即使用POI 里面的XMLSlide 和 HSLFSlide 进行分别处理。
关于中文乱码问题已修复

maven依赖都使用poi 4.1.2版本:

		<!--  poi -->
	    <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>
		
       <!-- itextpdf -->
        <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>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.6.0</version>
        </dependency>

ppt/pptx转换pdf:

import cn.hutool.core.util.StrUtil;

import java.awt.*;
import java.awt.image.BufferedImage;

import org.apache.poi.xslf.usermodel.*;
import org.apache.poi.hslf.usermodel.*;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.Image;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * 类名称:PdfConvertUtil
 * 类描述:转为为PDF工具类
*/
public final class PdfConverUtil {

/**
	 * pptToPdf
	 * @param pptPath PPT文件路径
	 * @param pdfDir 生成的PDF文件路径
	 * @return
	 */
	public static boolean pptToPdf(String pptPath, String pdfDir) {

        if (StrUtil.isEmpty(pptPath)) {
            throw new RuntimeException("word文档路径不能为空");
        }

        if (StrUtil.isEmpty(pdfDir)) {
            throw new RuntimeException("pdf目录不能为空");
        }
        
        
        String pdfPath = pdfDir + StrUtil.sub(pptPath, pptPath.lastIndexOf(StrUtil.BACKSLASH), pptPath.lastIndexOf(StrUtil.DOT)) + StrUtil.DOT + "pdf";

        Document document = null;
        HSLFSlideShow hslfSlideShow = null;
        FileOutputStream fileOutputStream = null;
        PdfWriter pdfWriter = null;

        try {
            hslfSlideShow = new HSLFSlideShow(new FileInputStream(pptPath));

            // 获取ppt文件页面
            Dimension dimension = hslfSlideShow.getPageSize();

            fileOutputStream = new FileOutputStream(pdfPath);

            document = new Document();
            
            // pdfWriter实例
            pdfWriter = PdfWriter.getInstance(document, fileOutputStream);

            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()) {
                      if (shape instanceof HSLFTextShape) {
                        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 java.awt.Font("宋体", java.awt.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 {
            try {
                if (document != null) {
                    document.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
                if (pdfWriter != null) {
                    pdfWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

	/**
	 *
	 * @Title: pptxToPdf
	 * @param pptPath PPT文件路径
	 * @param pdfDir 生成的PDF文件路径
	 */
	public static boolean pptxToPdf(String pptPath, String pdfDir) {

		if (StrUtil.isEmpty(pptPath)) {
			throw new RuntimeException("word文档路径不能为空");
		}

		if (StrUtil.isEmpty(pdfDir)) {
			throw new RuntimeException("pdf目录不能为空");
		}

		String pdfPath = pdfDir + StrUtil.sub(pptPath, pptPath.lastIndexOf(StrUtil.BACKSLASH), pptPath.lastIndexOf(StrUtil.DOT)) + StrUtil.DOT + "pdf";

		Document document = null;

		XMLSlideShow slideShow = null;


		FileOutputStream fileOutputStream = null;

		PdfWriter pdfWriter = null;


		try {

			slideShow = new XMLSlideShow(new FileInputStream(pptPath));

			Dimension dimension = slideShow.getPageSize();

			fileOutputStream = new FileOutputStream(pdfPath);

			document = new Document();

			pdfWriter = PdfWriter.getInstance(document, fileOutputStream);

			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()) {
                    if (shape instanceof XSLFTextShape) {
                        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 java.awt.Font("宋体", java.awt.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 {
			try {
				if (document != null) {
					document.close();
				}
				if (fileOutputStream != null) {
					fileOutputStream.close();
				}
				if (pdfWriter != null) {
					pdfWriter.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return true;
	}

}

测试:

public static void main(String[] args) {
		boolean successful = false;
	   // ppt to pdf
		successful = PdfConvertUtil.pptToPdf("D:\\360_js\\abc1.ppt", "D:\\360_js")
		
		// pptx to pdf
	//	 successful = PdfConvertUtil.pptxToPdf("D:\\360_js\\测321pt.pptx", "D:\\360_js");
		 
	   System.out.println("转换" + (successful ? "成功" : "失败"));
	   }

在这里插入图片描述

  • 3
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 50
    评论
实现PPTPDF,可以使用Apache POI和Apache PDFBox两个Java库。具体步骤如下: 1. 使用Apache POI读取PPT文件,获取每一页的内容和样式信息。 2. 创建一个PDF文档对象,使用Apache PDFBox。 3. 将每一页的内容和样式信息写入PDF文档对象中。 4. 保存PDF文档对象到本地文件。 以下是一个简单的PPTPDFJava代码示例: ```java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.hslf.usermodel.HSLFSlideShow; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.rendering.PDFRenderer; import org.apache.pdfbox.tools.imageio.ImageIOUtil; public class PptToPdfConverter { public static void convert(String pptFilePath, String pdfFilePath) throws IOException { // 读取PPT文件 HSLFSlideShow ppt = new HSLFSlideShow(new FileInputStream(pptFilePath)); // 创建PDF文档对象 PDDocument pdf = new PDDocument(); // 遍历PPT每一页,将内容写入PDF文档对象中 for (int i = 0; i < ppt.getSlides().size(); i++) { PDPage page = new PDPage(); pdf.addPage(page); PDPageContentStream contentStream = new PDPageContentStream(pdf, page); contentStream.drawImage(new PDFRenderer(ppt.getSlides().get(i)).renderImageWithDPI(300), 0, 0); contentStream.close(); } // 保存PDF文档对象 pdf.save(pdfFilePath); pdf.close(); // 释放PPT文件资源 ppt.close(); } public static void main(String[] args) throws IOException { String pptFilePath = "test.ppt"; String pdfFilePath = "test.pdf"; convert(pptFilePath, pdfFilePath); } } ``` 该代码使用了Apache POI的HSLFSlideShow类读取PPT文件,使用了Apache PDFBox的PDDocument类创建PDF文档对象和PDPage类创建PDF页面对象,使用了PDFRenderer类将PPT页面转换PDF页面,使用了PDPageContentStream类将PDF页面写入PDF文档对象中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 50
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值