word、ppt、excel、txt转pdf——第二篇ppt、pptx

该文章描述了一个Java程序,首先使用ApachePOI库将PPT或PPTX文件转换为PNG图像,然后通过旋转每张图片90度避免多张幻灯片挤在同一PDF页面。接着,程序利用iTextPDF库将这些图片合并成PDF文件,并对PDF中的每一页进行逆时针90度旋转,确保每个幻灯片都在单独的PDF页面上。
摘要由CSDN通过智能技术生成

ppt转pdf(直接转会出现多张幻灯片在一页问题,所以先转照片,再转pdf)

引用的jar,下面给出两个poi和pdf操作的maven配置,fastjson2和fastjson都可以。其他jar就不列出了。

        <!-- org.apache.poi.xslf.usermodel引用 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.2</version>            
        </dependency>
        <!-- org.apache.poi.hslf.usermodel引用 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>5.2.2</version>           
        </dependency>
			<!-- pdf操作引用 -->
	    <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13.3</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.21</version>
        </dependency>
import com.alibaba.fastjson2.JSONArray;
import org.apache.poi.xslf.usermodel.*;
import org.apache.poi.hslf.usermodel.*;
import java.awt.image.BufferedImage;
import org.apache.poi.util.IOUtils;
import java.awt.geom.Rectangle2D;
import java.awt.*;
import java.io.*;

具体代码如下
1.ppt转图片并把每一张向右旋转90度

package util;

import com.alibaba.fastjson2.JSONArray;
import org.apache.poi.xslf.usermodel.*;
import org.apache.poi.hslf.usermodel.*;
import java.awt.image.BufferedImage;
import org.apache.poi.util.IOUtils;
import java.awt.geom.Rectangle2D;
import java.awt.*;
import java.io.*;

public class PptToImg {
    public static JSONArray pptToImage(String filePath, String target, String type) throws Exception {
        if (type.equals("ppt")) {
            return pptImage(filePath, target);
        } else if (type.equals("pptx")) {
            return pptxImage(filePath, target);
        }
        return null;
    }

    /**
     * 将pptx转成图片
     */
    public static JSONArray pptxImage(String filePath, String target) throws Exception {
        FileInputStream fileInputStream;
        try {
            fileInputStream = new FileInputStream(filePath);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        XMLSlideShow ppt = new XMLSlideShow(fileInputStream);
        Dimension pgSize = ppt.getPageSize();
        int pageSize = ppt.getSlides().size();
        JSONArray imgFiles = new JSONArray();
        for (int i = 0; i < pageSize; i++) {
            //防止中文乱码
            handlerPPTXEncoding(ppt, i);
            BufferedImage img = new BufferedImage(pgSize.width, pgSize.height, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = img.createGraphics();
            // clear the drawing area
            graphics.setPaint(Color.white);
            graphics.fill(new Rectangle2D.Float(0, 0, pgSize.width, pgSize.height));
            // render
            ppt.getSlides().get(i).draw(graphics);
            // save the output
            String file = target + CommonUtils.randomUUID() + ".png";
            FileOutputStream out = new FileOutputStream(file);
            javax.imageio.ImageIO.write(img, "png", out);
            IOUtils.closeQuietly(out);
            String newfile = target + CommonUtils.randomUUID() + ".png";
            ImageRotateUtils.rotateClockwise90(file, newfile);
            imgFiles.add(newfile);
            CommonUtils.deleteFileByPath(file);
        }
        IOUtils.closeQuietly(fileInputStream);
        return imgFiles;
    }

    /**
     * 将ppt转成图片,保存在同一目录的image目录下
     */
    public static JSONArray pptImage(String filePath, String target) throws IOException {
        FileInputStream fileInputStream;
        try {
            fileInputStream = new FileInputStream(filePath);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        HSLFSlideShow ppt = new HSLFSlideShow(fileInputStream);
        Dimension pgSize = ppt.getPageSize();
        JSONArray imgFiles = new JSONArray();
        for (int i = 0; i < ppt.getSlides().size(); i++) {
            // 防止中文乱码
            handlerPPTEncoding(ppt, i);
            BufferedImage img = new BufferedImage(pgSize.width, pgSize.height, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = img.createGraphics();
            // clear the drawing area
            graphics.setPaint(Color.white);
            graphics.fill(new Rectangle2D.Float(0, 0, pgSize.width, pgSize.height));
            // render
            ppt.getSlides().get(i).draw(graphics);
            // save the output
            String file = target + CommonUtils.randomUUID() + ".png";
            FileOutputStream out = new FileOutputStream(file);
            javax.imageio.ImageIO.write(img, "png", out);
            IOUtils.closeQuietly(out);
            String newfile = target + CommonUtils.randomUUID() + ".png";
            ImageRotateUtils.rotateClockwise90(file, newfile);
            imgFiles.add(newfile);
            CommonUtils.deleteFileByPath(file);
        }
        return imgFiles;
    }


    private static void handlerPPTEncoding(HSLFSlideShow ppt, int index) {
        for (HSLFShape shape : ppt.getSlides().get(index).getShapes()) {
            if (shape instanceof HSLFTextShape) {
                HSLFTextShape tsh = (HSLFTextShape) shape;
                for (HSLFTextParagraph p : tsh) {
                    for (HSLFTextRun r : p) {
                        String fontFamily = "宋体";
                        r.setFontFamily(fontFamily);
                    }
                }
            }
        }
    }

    private static void handlerPPTXEncoding(XMLSlideShow ppt, int index) {
        for (XSLFShape shape : ppt.getSlides().get(index).getShapes()) {
            if (shape instanceof XSLFTextShape) {
                XSLFTextShape tsh = (XSLFTextShape) shape;
                for (XSLFTextParagraph p : tsh) {
                    for (XSLFTextRun r : p) {
                        String fontFamily = "宋体";
                        r.setFontFamily(fontFamily);
                    }
                }
            }
        }
    }
}

2.生成pdf并把pdf每一页向左旋转90度(两次旋转后每个幻灯片就会在单独在一页pdf上)

package util;

import com.itextpdf.text.pdf.PdfDictionary;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfSmartCopy;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfNumber;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.Document;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * PDF工具类
 */
public class PdfRateUtils {

    /**
     * 旋转PDF文件
     *
     * @param sourceFile 源PDF文件路径
     * @param targetFile 目标PDF文件路径
     * @param angle      旋转角度
     */
    public static void rotate(String sourceFile, String targetFile, int angle) {
        PdfReader reader = null;
        Document document = null;
        FileOutputStream outputStream = null;
        try {
            // 读取源文件
            reader = new PdfReader(sourceFile);
            // 创建新的文档
            document = new Document();
            // 创建目标PDF文件
            outputStream = new FileOutputStream(targetFile);
            PdfCopy pdfCopy = new PdfSmartCopy(document, outputStream);
            // 获取源文件的页数
            int pages = reader.getNumberOfPages();
            document.open();
            PdfDictionary pdfDictionary;
            // 注意此处的页码是从1开始
            for (int page = 1; page <= pages; page++) {
                pdfDictionary = reader.getPageN(page);
                pdfDictionary.put(PdfName.ROTATE, new PdfNumber(angle));
                pdfCopy.addPage(pdfCopy.getImportedPage(reader, page));
            }
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (document != null) {
                document.close();
            }
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 按页码旋转PDF文件
     *
     * @param sourceFile      源PDF文件路径
     * @param targetFile      目标PDF文件路径
     * @param angle           旋转角度
     * @param rotatedPageNums 需要旋转的页码
     */
    public static void rotate(String sourceFile, String targetFile, int angle, List<Integer> rotatedPageNums) {
        PdfReader reader = null;
        Document document = null;
        FileOutputStream outputStream = null;
        try {
            // 读取源文件
            reader = new PdfReader(sourceFile);
            // 创建新的文档
            document = new Document();
            // 创建目标PDF文件
            outputStream = new FileOutputStream(targetFile);
            PdfCopy pdfCopy = new PdfSmartCopy(document, outputStream);
            // 获取源文件的页数
            int pages = reader.getNumberOfPages();
            document.open();
            PdfDictionary pdfDictionary;
            // 注意此处的页码是从1开始
            for (int page = 1; page <= pages; page++) {
                pdfDictionary = reader.getPageN(page);
                if (null == rotatedPageNums || rotatedPageNums.isEmpty()) {
                    pdfDictionary.put(PdfName.ROTATE, new PdfNumber(angle));
                } else if (rotatedPageNums.contains(page)) {
                    pdfDictionary.put(PdfName.ROTATE, new PdfNumber(angle));
                }
                pdfCopy.addPage(pdfCopy.getImportedPage(reader, page));
            }
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (document != null) {
                document.close();
            }
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 起始结束页码旋转PDF文件
     *
     * @param sourceFile  源PDF文件路径
     * @param targetFile  目标PDF文件路径
     * @param angle       旋转角度
     * @param fromPageNum 起始页码
     * @param toPageNum   结束页码
     */
    public static void rotate(String sourceFile, String targetFile, int angle, int fromPageNum, int toPageNum) {
        PdfReader reader = null;
        Document document = null;
        FileOutputStream outputStream = null;
        try {
            // 读取源文件
            reader = new PdfReader(sourceFile);
            // 创建新的文档
            document = new Document();
            // 创建目标PDF文件
            outputStream = new FileOutputStream(targetFile);
            PdfCopy pdfCopy = new PdfSmartCopy(document, outputStream);
            // 获取源文件的页数
            int pages = reader.getNumberOfPages();
            document.open();
            PdfDictionary pdfDictionary;
            // 注意此处的页码是从1开始
            for (int page = 1; page <= pages; page++) {
                pdfDictionary = reader.getPageN(page);
                // 如果页面是在起始页码和结束页码之间的,则进行旋转
                if (page >= fromPageNum && page <= toPageNum) {
                    pdfDictionary.put(PdfName.ROTATE, new PdfNumber(angle));
                }
                pdfCopy.addPage(pdfCopy.getImportedPage(reader, page));
            }
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (document != null) {
                document.close();
            }
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 旋转PDF文件中的所有横版
     *
     * @param sourceFile 源PDF文件路径
     * @param targetFile 目标PDF文件路径
     * @param angle      旋转角度
     */
    public static void rotateHorizontal(String sourceFile, String targetFile, int angle) {
        PdfReader reader = null;
        Document document = null;
        FileOutputStream outputStream = null;
        try {
            // 读取源文件
            reader = new PdfReader(sourceFile);
            // 创建新的文档
            document = new Document();
            // 创建目标PDF文件
            outputStream = new FileOutputStream(targetFile);
            PdfCopy pdfCopy = new PdfSmartCopy(document, outputStream);

            // 获取源文件的页数
            int pages = reader.getNumberOfPages();
            document.open();
            PdfDictionary pdfDictionary;
            // 注意此处的页码是从1开始
            for (int page = 1; page <= pages; page++) {
                pdfDictionary = reader.getPageN(page);
                // 根据页面的宽度
                float pageWidth = reader.getPageSize(page).getWidth();
                if (pageWidth > 600F) {
                    pdfDictionary.put(PdfName.ROTATE, new PdfNumber(angle));
                }
                pdfCopy.addPage(pdfCopy.getImportedPage(reader, page));
            }
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (document != null) {
                document.close();
            }
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 旋转PDF文件中的所有竖版
     *
     * @param sourceFile 源PDF文件路径
     * @param targetFile 目标PDF文件路径
     * @param angle      旋转角度
     */
    public static void rotateVertical(String sourceFile, String targetFile, int angle) {
        PdfReader reader = null;
        Document document = null;
        FileOutputStream outputStream = null;
        try {
            // 读取源文件
            reader = new PdfReader(sourceFile);
            // 创建新的文档
            document = new Document();
            // 创建目标PDF文件
            outputStream = new FileOutputStream(targetFile);
            PdfCopy pdfCopy = new PdfSmartCopy(document, outputStream);
            // 获取源文件的页数
            int pages = reader.getNumberOfPages();
            document.open();
            PdfDictionary pdfDictionary;
            // 注意此处的页码是从1开始
            for (int page = 1; page <= pages; page++) {
                pdfDictionary = reader.getPageN(page);
                // 根据页面的高度
                float pageHeight = reader.getPageSize(page).getHeight();
                if (pageHeight > 600F) {
                    pdfDictionary.put(PdfName.ROTATE, new PdfNumber(angle));
                }
                pdfCopy.addPage(pdfCopy.getImportedPage(reader, page));
            }
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (document != null) {
                document.close();
            }
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //测试方法
    public static void main(String[] args) throws Exception {
        String oldPath = "D:\\in.ppt";//待转换的ppt文件
        String target = "D:\\"; //照片存放目录
        String type = "ppt";    //ppt和pptx
        String ratePath = "D:\\in.pdf";//旋转前pdf
        String rePath = "D:\\out.pdf";//旋转后pdf
        JSONArray jappt = PptToImg.pptToImage(oldPath, target,type);
        ImgToPDF.imgChangePDF(jappt, ratePath);
        PdfRateUtils.rotate(ratePath, rePath, -90);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值