• word、excel、ppt、pptx转为PDF


    相关引用对象在代码里了

    相关依赖

    <dependency>
        <groupId>org.apache.poigroupId>
            <artifactId>poi-ooxmlartifactId>
            <version>4.0.1version>
        dependency>
    <dependency>
        <groupId>org.apache.poigroupId>
        <artifactId>poiartifactId>
        <version>4.0.1version>
    dependency>
    
    <dependency>
        <groupId>com.documents4jgroupId>
        <artifactId>documents4j-localartifactId>
        <version>1.0.3version>
    dependency>
    <dependency>
        <groupId>com.documents4jgroupId>
        <artifactId>documents4j-transformer-msoffice-wordartifactId>
        <version>1.0.3version>
    dependency>
    
    <dependency>
        <groupId>com.itextpdfgroupId>
        <artifactId>itextpdfartifactId>
        <version>5.2.0version>
        dependency>
    <dependency>
        <groupId>org.apache.poigroupId>
        <artifactId>poi-scratchpadartifactId>
        <version>4.1.2version>
    dependency>
    
    <dependency>
        <groupId>com.itextpdfgroupId>
        <artifactId>itext-asianartifactId>
        <version>5.2.0version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    word转pdf

    	import com.documents4j.api.DocumentType;
    	import com.documents4j.api.IConverter;
    	import com.documents4j.job.LocalConverter;
    	import java.io.*;
    
    
    
    
    	/**
         * 实现word转pdf
         *
         * @param sourcePath 源文件地址 如 D:\\1.doc
         * @param targetPath 目标文件地址 如 D:\\1.pdf
         */
        public static void wordToPdf(String sourcePath, String targetPath) {
            File inputWord = new File(sourcePath);
            File outputFile = new File(targetPath);
            try {
                InputStream docxInputStream = new FileInputStream(inputWord);
                OutputStream outputStream = new FileOutputStream(outputFile);
                IConverter converter = LocalConverter.builder().build();
                converter.convert(docxInputStream)
                        .as(DocumentType.DOCX)
                        .to(outputStream)
                        .as(DocumentType.PDF).schedule().get();
                outputStream.close();
                docxInputStream.close();
    
                log.info("转换完毕 targetPath = {}", outputFile.getAbsolutePath()+",targetPath = " + outputFile.getAbsolutePath());
                converter.shutDown();
            } catch (Exception e) {
                log.error("word转pdf失败:"+e.getMessage(), e);
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    pptx转pdf

    ppt转pdf该方法不适用,可以参考下一个方法

    	import com.itextpdf.text.*;
    	import com.itextpdf.text.pdf.PdfPCell;
    	import com.itextpdf.text.pdf.PdfPTable;
    	import com.itextpdf.text.pdf.PdfWriter;
    	import org.apache.poi.xslf.usermodel.*;
    	import java.awt.*;
    	import java.awt.Color;
    	import java.awt.image.BufferedImage;
    	import java.io.*;
    
    
    
    	/**
         * pptx转为pdf
         * @param sourcePath 源文件地址 如 D:\\1.pptx
         * @param targetPath 目标文件地址 如 D:\\1.pdf
         */
        public static void pptToPdf(String sourcePath,String targetPath) {
            Document document = null;
            XMLSlideShow slideShow = null;
            FileOutputStream fileOutputStream = null;
            PdfWriter pdfWriter = null;
            ByteArrayOutputStream baos = null;
            byte[] resBytes = null;
            try {
                baos=new ByteArrayOutputStream();
                //使用输入流pptx文件
                slideShow = new XMLSlideShow(new FileInputStream(new File(sourcePath)));
                //获取幻灯片的尺寸
                Dimension dimension = slideShow.getPageSize();
                //创建一个写内容的容器
                document = new Document(PageSize.A4, 72, 72, 72, 72);
                //使用输出流写入
                pdfWriter = PdfWriter.getInstance(document, baos);
                //使用之前必须打开
                document.open();
                pdfWriter.open();
                PdfPTable pdfPTable = new PdfPTable(1);
                //获取幻灯片
                java.util.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对象中
                    com.itextpdf.text.Image image = com.itextpdf.text.Image.getInstance(bufferedImage, null);
                    image.scalePercent(50f);
                    // 写入单元格
                    pdfPTable.addCell(new PdfPCell(image, true));
                    document.add(image);
                }
                document.close();
                pdfWriter.close();
                resBytes = baos.toByteArray();
                FileOutputStream outputStream = new FileOutputStream(targetPath);
                outputStream.write(resBytes);
                outputStream.flush();
                outputStream.close();
            } catch (Exception e) {
                log.error("pptx转pdf异常:"+e.getMessage(),e);
            } finally {
                try {
                    if (baos != null) {
                        baos.close();
                    }
                } catch (Exception e) {
                    log.error("pptx转pdf关闭io流异常:"+e.getMessage(),e);
                }
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89

    ppt转pdf

    pptx转pdf该方法不适用,可以参考上一个方法

    	import com.itextpdf.text.Document;
    	import com.itextpdf.text.pdf.PdfPCell;
    	import com.itextpdf.text.pdf.PdfPTable;
    	import com.itextpdf.text.pdf.PdfWriter;
    	import org.apache.poi.hslf.usermodel.HSLFSlide;
    	import org.apache.poi.hslf.usermodel.HSLFSlideShow;
    	import org.apache.poi.xslf.usermodel.XMLSlideShow;
    	import org.apache.poi.xslf.usermodel.XSLFSlide;
    	import java.awt.*;
    	import java.awt.geom.AffineTransform;
    	import java.awt.image.BufferedImage;
    	import java.io.*;
    	import java.util.List;
    
    
    
    	/**
         * pptx转为pdf
         * @param sourcePath 源文件地址 如 D:\\1.ppt
         * @param targetPath 目标文件地址 如 D:\\1.pdf
         */
        public static void ppt2pdf(String sourcePath,String targetPath) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] resBytes = null;
            InputStream inputStream = null;
            try {
                Document pdfDocument = new Document();
                PdfWriter pdfWriter = PdfWriter.getInstance(pdfDocument, baos);
                inputStream = new FileInputStream(new File(sourcePath));
                HSLFSlideShow hslfSlideShow = new HSLFSlideShow(inputStream);
                double zoom = 1; // 该位置我是参考原博主的代码根据自己需要进行修改的,我理解的是这个数越大,ppt转化出的图片越小
                if (hslfSlideShow == null) {
                    XMLSlideShow ppt = new XMLSlideShow(inputStream);
                    if (ppt == null) {
                        throw new NullPointerException("获取ppt文件数据失败");
                    }
                    Dimension pgsize = ppt.getPageSize();
                    java.util.List<XSLFSlide> slide = ppt.getSlides();
                    AffineTransform at = new AffineTransform();
                    at.setToScale(zoom, zoom);
                    pdfDocument.setPageSize(new com.itextpdf.text.Rectangle((float) pgsize.getWidth(),(float) pgsize.getHeight()));
                    pdfWriter.open();
                    pdfDocument.open();
                    PdfPTable table = new PdfPTable(1);
                    for (XSLFSlide xslfSlide : slide) {
                        BufferedImage img = new BufferedImage((int) Math.ceil(pgsize.width * zoom), (int) Math.ceil(pgsize.height * zoom), BufferedImage.TYPE_INT_RGB);
                        Graphics2D graphics = img.createGraphics();
                        graphics.setTransform(at);
    
                        graphics.setPaint(Color.white);
                        graphics.fill(new java.awt.geom.Rectangle2D.Float(0, 0, (float) (pgsize.width * zoom), (float) (pgsize.height * zoom)));// 这个地方如果不乘zoom,则意味着没有铺满
                        xslfSlide.draw(graphics);
                        graphics.getPaint();
                        com.itextpdf.text.Image slideImage = com.itextpdf.text.Image.getInstance(img, null);
                        table.addCell(new PdfPCell(slideImage, true));
                    }
                    ppt.close();
                    pdfDocument.add(table);
                    pdfDocument.close();
                    pdfWriter.close();
                    resBytes = baos.toByteArray();
                    FileOutputStream outputStream = new FileOutputStream(targetPath);
                    outputStream.write(resBytes);
                    outputStream.flush();
                    outputStream.close();
                    return;
                }
                Dimension pgsize = hslfSlideShow.getPageSize();
                List<HSLFSlide> slides = hslfSlideShow.getSlides();
                pdfDocument.setPageSize(new com.itextpdf.text.Rectangle((float) pgsize.getWidth(), (float) pgsize.getHeight()));
                pdfWriter.open();
                pdfDocument.open();
                AffineTransform at = new AffineTransform();
                PdfPTable table = new PdfPTable(1);
                for (HSLFSlide hslfSlide : slides) {
                    BufferedImage img = new BufferedImage((int) Math.ceil(pgsize.width * zoom), (int) Math.ceil(pgsize.height * zoom), BufferedImage.TYPE_INT_RGB);
                    Graphics2D graphics = img.createGraphics();
                    graphics.setTransform(at);
    
                    graphics.setPaint(Color.white);
                    graphics.fill(new java.awt.geom.Rectangle2D.Float(0, 0, (float) (pgsize.width * zoom), (float) (pgsize.height * zoom)));
                    hslfSlide.draw(graphics);
                    graphics.getPaint();
                    com.itextpdf.text.Image slideImage = com.itextpdf.text.Image.getInstance(img, null);
                    table.addCell(new PdfPCell(slideImage, true));
                }
                hslfSlideShow.close();
                pdfDocument.add(table);
                pdfDocument.close();
                pdfWriter.close();
                resBytes = baos.toByteArray();
                FileOutputStream outputStream = new FileOutputStream(targetPath);
                outputStream.write(resBytes);
                outputStream.flush();
                outputStream.close();
            } catch (Exception e) {
                log.error("ppt转为pdf异常:"+e.getMessage(),e);
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99

    excel转pdf

    	import com.itextpdf.text.*;
    	import com.itextpdf.text.Font;
    	import com.itextpdf.text.pdf.BaseFont;
    	import com.itextpdf.text.pdf.PdfPCell;
    	import com.itextpdf.text.pdf.PdfPTable;
    	import com.itextpdf.text.pdf.PdfWriter;
    	import lombok.SneakyThrows;
    	import org.apache.poi.ss.usermodel.*;    
    
    	/**
         *
         * @param sourcePath 源文件地址 如 D:\\1.xlsx
         * @param targetPath 目标文件地址 如 D:\\1.pdf
         */
        @SneakyThrows
        private void excelToPdf(String sourcePath, String targetPath ){
            try (Workbook workbook = WorkbookFactory.create(new File(sourcePath));
                 FileOutputStream fos = new FileOutputStream(targetPath )) {
                // 获取第一个工作表
                Sheet sheet = workbook.getSheetAt(0);
    
                // 创建PDF文档对象
                Document document = new Document(PageSize.A4, 50, 50, 50, 50);
    
                // 创建PDF输出流
                PdfWriter writer = PdfWriter.getInstance(document, fos);
    
                // 打开PDF文档
                document.open();
    
                // 创建PDF表格对象
                PdfPTable table = new PdfPTable(sheet.getRow(0).getLastCellNum());
    
                // 设置表格宽度
                table.setWidthPercentage(100);
    
                // 设置表格标题,Example Table为表格标题
                Paragraph title = new Paragraph("Example Table", new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 16, Font.BOLD));
                title.setAlignment(Element.ALIGN_CENTER);
                document.add(title);
    
                // 添加表格内容
                for (Row row : sheet) {
                    for (Cell cell : row) {
                        PdfPCell pdfCell = new PdfPCell(new Paragraph(cell.getStringCellValue(), new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 12)));
                        pdfCell.setBorderWidth(1f);
                        pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        pdfCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                        table.addCell(pdfCell);
                    }
                }
    
                // 添加表格到PDF文档
                document.add(table);
    
                // 关闭PDF文档
                document.close();
            } catch (IOException | DocumentException e) {
                e.printStackTrace();
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61

    相关文件参考:
    word转pdf : https://gitee.com/wu_ze_wen/word_trans_pdf?_from=gitee_search
    ppt转pdf : https://blog.csdn.net/qq_30436011/article/details/127737553?spm=1001.2101.3001.6650.2&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-2-127737553-blog-127973320.235%5Ev38%5Epc_relevant_anti_t3&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-2-127737553-blog-127973320.235%5Ev38%5Epc_relevant_anti_t3&utm_relevant_index=4

    excel转pdf :
    https://blog.csdn.net/sqL520lT/article/details/131430166
    https://www.cnblogs.com/iyyy/p/9346935.html

  • 相关阅读:
    jmeter接口自动化部署jenkins教程详解
    NLP基础——Bag of Words 词袋法
    json-c 理解记录
    普通物理光学:光栅
    Java项目:基于ssm智能餐厅管理系统
    代码解读:y.view(y.size(0), -1)---tensor张量第一维保持不变,其余维度展平
    力扣-463.岛屿的周长
    向量数据库库Milvus Cloud2.3 运维可靠,秒级故障恢复
    DAY-2 | 哈希表、指针与区间划分:字符种数统计问题
    [ vulhub漏洞复现篇 ] Apche log4j远程代码执行漏洞(CVE-2021-44228)
  • 原文地址:https://blog.csdn.net/weixin_45494557/article/details/133172073