word,ppt等office文档转化为pdf进行展示(POI + iText)(亲测有效)

word,ppt等office软件转化为pdf进行展示(POI +iText)(亲测有效)

废话不多说,上代码

1. ppt转化为pdf,利用java的POI和itext进行转化

/**
 * 返回pdf文件
 */
 public File convertPPTToPDF(File file, File toFile) {
        try {
            Document pdfDocument = new Document();
            PdfWriter pdfWriter = PdfWriter.getInstance(pdfDocument, new FileOutputStream(toFile));
            FileInputStream is = new FileInputStream(file);
            double zoom = 2;
            XMLSlideShow ppt = convertPPTToPDFByPPTX(is);
            if (ppt == null) {
                throw new NullPointerException("This PPTX get data is error....");
            }
            Dimension pgsize = ppt.getPageSize();
            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 (int i = 0; i < slide.length; i++) {
                for (XSLFShape shape : slide[i].getShapes()) {
                    if (shape instanceof XSLFTextShape) {
                        XSLFTextShape txtshape = (XSLFTextShape) shape;
                        for (XSLFTextParagraph textPara : txtshape.getTextParagraphs()) {
                            List<XSLFTextRun> textRunList = textPara.getTextRuns();
                            for (XSLFTextRun textRun : textRunList) {
                                textRun.setFontFamily("宋体");
                            }
                        }
                    }
                }
                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 Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
                slide[i].draw(graphics);
                graphics.getPaint();
                com.itextpdf.text.Image slideImage = Image.getInstance(img, null);
                table.addCell(new PdfPCell(slideImage, true));
            }
            pdfDocument.add(table);
            pdfDocument.close();
            pdfWriter.close();
            log.info(file.getAbsolutePath() + "Powerpoint file converted to PDF successfully");
            return toFile;
        } catch (Exception e) {
            log.info(file.getAbsolutePath() + "--->" + e.getMessage());
            return null;
        }

    }

    private XMLSlideShow convertPPTToPDFByPPTX(FileInputStream is) {
        try {
            return new XMLSlideShow(is);
        } catch (IOException e) {
            return null;
        }
    }

2.wordtopdf

/**
 *  word to pdf 
 */
public File convertWordToPDF(File file, File toFile) {
        try {
            // size of pdfDocument
            Document pdfDocument = new Document(PageSize.A3, 72, 72, 72, 72);
            PdfWriter pdfWriter = PdfWriter.getInstance(pdfDocument, new FileOutputStream(toFile));
            FileInputStream input_document = new FileInputStream(file);
            XWPFDocument doc = new XWPFDocument(input_document);
            //72 units=1 inch
            pdfWriter.setInitialLeading(20);
            //get all paragraphs from word docx
            List<XWPFParagraph> plist = doc.getParagraphs();
            //open pdf document for writing
            pdfWriter.open();
            pdfDocument.open();
            for (int i = 0; i < plist.size(); i++) {
                //read through the list of paragraphs
                XWPFParagraph pa = plist.get(i);
                //get all run objects from each paragraph
                List<XWPFRun> runs = pa.getRuns();
                //read through the run objects
                for (int j = 0; j < runs.size(); j++) {
                    XWPFRun run = runs.get(j);
                    //get pictures from the run and add them to the pdf document
                    List<XWPFPicture> piclist = run.getEmbeddedPictures();
                    //traverse through the list and write each image to a file
                    Iterator<XWPFPicture> iterator = piclist.iterator();
                    while (iterator.hasNext()) {
                        XWPFPicture pic = iterator.next();
                        XWPFPictureData picdata = pic.getPictureData();
                        byte[] bytepic = picdata.getData();
                        Image imag = Image.getInstance(bytepic);
                        pdfDocument.add(imag);
                    }
                    // 中文字体的解决 Font_Songti为字体的配置文件
                    BaseFont bf = BaseFont.createFont(fileProperties.getPropertiesByKey("Font_Songti"), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                    Font font = new Font(bf, 15.0f, Font.NORMAL, BaseColor.BLACK);
                    //construct unicode string
                    String text = run.getText(-1);
                    byte[] bs;
                    if (text != null) {
                        bs = text.getBytes();
                        String str = new String(bs);
                        //add string to the pdf document
                        Chunk chObj1 = new Chunk(str, font);
                        pdfDocument.add(chObj1);
                    }

                }
                //output new line
                pdfDocument.add(new Chunk(Chunk.NEWLINE));
            }
            //close pdf document
            pdfDocument.close();
            pdfWriter.close();
            log.info(file.getAbsolutePath() + "Powerpoint file converted to PDF successfully");
            return toFile;
        } catch (Exception e) {
            log.info(file.getAbsolutePath() + "--->" + e.getMessage());
            return null;
        }

    }

3.处理pptx的中文乱码的问题

 for (int i = 0; i < slide.length; i++) {
                for (XSLFShape shape : slide[i].getShapes()) {
                    if (shape instanceof XSLFTextShape) {
                        XSLFTextShape txtshape = (XSLFTextShape) shape;
                        for (XSLFTextParagraph textPara : txtshape.getTextParagraphs()) {
                            List<XSLFTextRun> textRunList = textPara.getTextRuns();
                            for (XSLFTextRun textRun : textRunList) {
                                textRun.setFontFamily("宋体");
                            }
                        }
                    }
                }
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Excel是一种常用的办公软件,可以用来制作各类表格和图表。而PDF是一种便捷的文件格式,具有跨平台、可读性好等特点。因此,将Excel文件换为PDF格式,可以方便地与他人共享和阅读。下面是使用POIiTextPDF库将Excel文件换为PDF的步骤: 1. 导入POIiTextPDF库。这两个库可以通过在工程中引入相应的jar文件来实现。 2. 读取Excel文件并创建一个工作簿。使用POI库的Workbook类可以读取和操作Excel文件。 3. 遍历Excel文件中的每一张表格,并将表格数据写入PDF文件中。使用POI库的Sheet类和Row类来访问表格和行数据。 4. 创建一个PDF文档对象,并设置相关属性。使用iTextPDF库的Document类可以创建PDF文档,并设置页面大小、标题和作者等属性。 5. 将Excel表格数据写入PDF文件中。通过遍历Excel表格中的单元格,并使用iTextPDF库的Paragraph类将数据写入PDF文件。 6. 关闭文档对象,保存并关闭Excel文件。使用iTextPDF库的PdfWriter类将文档对象写入PDF文件,而使用POI库的Workbook类可以保存并关闭Excel文件。 7. 完成换,生成的PDF文件即可在设备上使用。 这就是使用POIiTextPDF库将Excel文件换为PDF的基本步骤。换后的PDF文件可以方便地共享和阅读,方便管理和交流。这个方法非常适用于需要将大量Excel表格换成PDF文档的场景,如报表生成、数据分析等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值