java PPT 转成PDF,中文乱码解决

ppt转成pdf,原理是ppt转成图片,再用图片生产pdf,过程有个问题,不管是ppt还是pptx,都遇到中文乱码,编程方框的问题,其中ppt后缀网上随便找就有解决方案,就是设置字体为统一字体,pptx如果页面是一种中文字体不会有问题,如果一个页面有微软雅黑和宋体,就会导致部分中文方框,怀疑是poi处理的时候,只读取第一种字体,所以导致多个中文字体乱码。

百度和谷歌都找了很久,有看到说apache官网有人说是bug(https://bz.apache.org/bugzilla/show_bug.cgi?id=54880 ),但他们回复说是字体问题,这个问题其实我觉得poi可能可以自己做,读取原来字体设置成当前字体,不过性能应该会有很多消耗,反正我估计很多人跟我一样花费大量时间找解决方案,网上几乎没有现成的方案。自己也是一步步尝试,最终找到解决办法,ppt格式的就不说了网上找得到,pptx后缀的网上我是没找到。

问题前的pptx转成图片:

解决后的pptx转成图片:

解决方法:

图取每个shape,将文字转成统一的字体,网上找到的那段代码不可行,我自己改的方案如下:

             for( XSLFShape shape : slide[i].getShapes() ){
                    if ( shape instanceof XSLFTextShape ){
                        XSLFTextShape txtshape = (XSLFTextShape)shape ;
                        System.out.println("txtshape" + (i+1) + ":"  + txtshape.getShapeName());
                        System.out.println("text:" +txtshape.getText());

                        for ( XSLFTextParagraph textPara : txtshape.getTextParagraphs() ){
                            List<XSLFTextRun> textRunList = textPara.getTextRuns();
                            for(XSLFTextRun textRun: textRunList) {
                                textRun.setFontFamily("宋体");
                            }
                        }
                    }
                }

完整代码如下(除了以上自己的解决方案,大部分是stackoverflow上的代码):

public static void convertPPTToPDF(String sourcepath, String destinationPath, String fileType) throws Exception {
        FileInputStream inputStream = new FileInputStream(sourcepath);
        double zoom = 2;
        AffineTransform at = new AffineTransform();
        at.setToScale(zoom, zoom);
        Document pdfDocument = new Document();
        PdfWriter pdfWriter = PdfWriter.getInstance(pdfDocument, new FileOutputStream(destinationPath));
        PdfPTable table = new PdfPTable(1);
        pdfWriter.open();
        pdfDocument.open();
        Dimension pgsize = null;
        Image slideImage = null;
        BufferedImage img = null;
        if (fileType.equalsIgnoreCase(".ppt")) {
            SlideShow ppt = new SlideShow(inputStream);
            inputStream.close();
            pgsize = ppt.getPageSize();
            Slide slide[] = ppt.getSlides();
            pdfDocument.setPageSize(new Rectangle((float) pgsize.getWidth(), (float) pgsize.getHeight()));
            pdfWriter.open();
            pdfDocument.open();
            for (int i = 0; i < slide.length; i++) {

                TextRun[] truns = slide[i].getTextRuns();
                for ( int k=0;k<truns.length;k++){
                   RichTextRun[] rtruns = truns[k].getRichTextRuns();
                  for(int l=0;l<rtruns.length;l++){
//                       int index = rtruns[l].getFontIndex();
//                        String name = rtruns[l].getFontName();
                        rtruns[l].setFontIndex(1);
                        rtruns[l].setFontName("宋体");
                   }
                }      

                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();
                slideImage = Image.getInstance(img, null);
                table.addCell(new PdfPCell(slideImage, true));
            }
        }
        if (fileType.equalsIgnoreCase(".pptx")) {
            XMLSlideShow ppt = new XMLSlideShow(inputStream);
            pgsize = ppt.getPageSize();
            XSLFSlide slide[] = ppt.getSlides();
            pdfDocument.setPageSize(new Rectangle((float) pgsize.getWidth(), (float) pgsize.getHeight()));
            pdfWriter.open();
            pdfDocument.open();

            for (int i = 0; i < slide.length; i++) {
                for( XSLFShape shape : slide[i].getShapes() ){
                    if ( shape instanceof XSLFTextShape ){
                        XSLFTextShape txtshape = (XSLFTextShape)shape ;
                       // System.out.println("txtshape" + (i+1) + ":"  + txtshape.getShapeName());
                        //System.out.println("text:" +txtshape.getText());

                        for ( XSLFTextParagraph textPara : txtshape.getTextParagraphs() ){
                            List<XSLFTextRun> textRunList = textPara.getTextRuns();
                            for(XSLFTextRun textRun: textRunList) {
                                textRun.setFontFamily("宋体");
                            }
                        }
                    }
                }
                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);

//                FileOutputStream out = new FileOutputStream("src/main/resources/test"+i+".jpg");
//                javax.imageio.ImageIO.write(img, "jpg", out);

                graphics.getPaint();
                slideImage = Image.getInstance(img, null);
                table.addCell(new PdfPCell(slideImage, true));
            }
        }
        pdfDocument.add(table);
        pdfDocument.close();
        pdfWriter.close();
        System.out.println("Powerpoint file converted to PDF successfully");
    }

maven配置:

<dependency>
      <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
    <!--  <version>3.13</version> -->
     <version>3.9</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
       <!--  <version>3.10-FINAL</version> -->
       <version>3.9</version>
    </dependency>

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

    <dependency>
      <groupId>com.itextpdf.tool</groupId>
      <artifactId>xmlworker</artifactId>
      <version>5.5.7</version>
    </dependency>
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-scratchpad</artifactId>
      <!--  <version>3.12</version> -->
       <version>3.9</version>
    </dependency>

参考资料:

http://www.tutorialspoint.com/apache_poi_ppt/apache_poi_ppt_quick_guide.htm

文章转载自 开源中国社区[https://www.oschina.net]

时间: 2024-08-01 21:50:57

java PPT 转成PDF,中文乱码解决的相关文章

Java Web开发项目中中文乱码解决方法汇总_java

Java Web项目中,解决中文乱码方法总结如下 第一种情况:调用jsp页面中文显示乱码问题描述:通过浏览器调用jsp页面,在浏览器中显示的中文内容出现乱码. 解决方法:首先确认本jsp在编辑器中保存文件内容时,使用的是utf-8的编码格式,然后在jsp页面的开始处添加<%@ pageEncoding="utf-8"%>就可以解决这种中文乱码问题 第二种情况:调用servlet页面显示乱码问题描述:通过浏览器调用servlet,servlet在浏览器中显示的内容出现乱码.

JAVA URL和URLConnection及中文乱码解决方法

 也不多说什么了,就拿urlconnection类举个例子吧,做一个获取网站源码的代码 public class urldemo {  public static void main(string[] args) {   scanner scan = new scanner(system.in);            system.out.println("请输入网址:");   string urlstr ="http://"+scan.next();   tr

dhtmlxgrid导出为excel/pdf中文乱码,怎么解决??

问题描述 dhtmlxgrid导出为excel/pdf中文乱码,怎么解决?? 使用dhtmlgrid显示数据正常,但是使用导出功能时出现中文乱码,请问是怎么回事呢?下载官网上的例子,导出excel后并没有出现乱码问题 解决方案 ASPxPivotGrid导出pdf中文乱码reporting services导出pdf中文乱码解决解决tableexport导出到excel中有关中文乱码的问题

【技术贴】java插入mysql中文乱码解决|java插入mysql数据库显示问号?

[技术贴]java插入mysql中文乱码解决|java插入mysql数据库显示问号?   在你要连接到mysql 的代码里写上?useUnicode=true&characterEncoding=UTF-8" 比如 "jdbc:mysql://localhost:3306/chenluancl1?useUnicode=true&characterEncoding=UTF-8", "root","密码"

linux下使用iText生成pdf中文乱码 怎么解决啊

问题描述 linux下使用iText生成pdf中文乱码 怎么解决啊 生成的是乱码 而且是一坨. iText在linux环境下,怎么用啊.

将ppt转换成pdf的方法

  1.在PowerPoint2007任意打开一个PPT文档,然后单击"Office按钮",选择"另存为",在保存文档副本中选择"查找其他格式的加载项";(这是第一次使用的情况,要将文件保存为 PDF 或 XPS 格式,必须首先安装用于 2007 Microsoft Office system 的"另存为 PDF 或 XPS"加载项.如果有"PDF或XPS"选项,可直接看本教程第二页,以下可不看)(如下图)

ppt转换成pdf转换器怎么使用

怎么把ppt转换成pdf?对于这个问题,想必很多用户都想知道答案吧,为了能帮助大家解决这个问题,这里小编给大家介绍一款迅捷ppt转换成pdf转换器,通过这款转换器,大家可以轻松解决ppt转换成pdf问题.下面我们一起来看看迅捷 ppt转换成pdf转换器怎么使用吧! 迅捷ppt转换成pdf转换器操作教程: 步骤1:打开安装好的迅捷ppt转换成pdf转换器,选择"ppt转PDF"转换模式. 步骤2:点击软件中的"添加文件"按钮,将需要转换的ppt文件添加到软件中,用户也

python 中文乱码解决方法

比如我从网上下载一些信息或写个电子邮件程序下载到本地,以记事本(txt) 形式写入并保存在本地计算机,为什么看到只是英文和乱码的?该怎样做呢? 答 乱码原因: 因为你的文件声明为utf-8,并且也应该是用utf-8的编码保存的源文件.但是windows的本地默认编码是cp936,也就是gbk编码,所以在控制台直接打印utf-8的字符串当然是乱码了. 解决方法: 在控制台打印的地方用一个转码就ok了,打印的时候这么写: print myname.decode('utf-8').encode('gb

ajax中文乱码解决方法总结

ajax乱码解决办法一: 在服务器指定发送数据的格式: 在jsp文件中: response.setContentType("text/text;charset=UTF-8");//返回的是txt文本文件 或是 response.setContentType("text/xml;charset=UTF-8");//返回的xml文件 PHP:header("Content-Type:text/html;charset=GB2312"); ajax乱码