Maybe 发表于 2024-6-21 17:36:51

PPT导出-模板和自定义处理方案

本帖最后由 Maybe 于 2024-6-21 17:38 编辑

​ 两种方式:1.自定义样式导出2.根据模板导出
1.自定义设置样式导出PPT

   public static void main(String[] args) throws IOException {
      XMLSlideShow ppt = new XMLSlideShow();
      // 创建幻灯片
      XSLFSlide slide = ppt.createSlide();

      // 创建文本框
      XSLFTextBox textBox = slide.createTextBox();
      // x y设置距离w h 设置大小
      textBox.setAnchor(new Rectangle2D.Double(30,0, 600, 50));
      // 设置文本框的内容
      textBox.addNewTextParagraph().addNewTextRun().setText("姓名");


      // 创建文本框
      XSLFTextBox textBox1 = slide.createTextBox();
      // x y设置距离w h 设置大小
      textBox1.setAnchor(new Rectangle2D.Double(30,50, 600, 50));
      // 设置文本框的内容
      textBox1.addNewTextParagraph().addNewTextRun().setText("年龄");
      // 创建文本框
      XSLFTextBox textBox11 = slide.createTextBox();
      // x y设置距离w h 设置大小
      textBox11.setAnchor(new Rectangle2D.Double(250,50, 600, 50));
      // 设置文本框的内容
      textBox11.addNewTextParagraph().addNewTextRun().setText("性别");

      // 创建文本框
      XSLFTextBox textBox2 = slide.createTextBox();
      // x y设置距离w h 设置大小
      textBox2.setAnchor(new Rectangle2D.Double(30,100, 600, 50));
      // 设置文本框的内容
      textBox2.addNewTextParagraph().addNewTextRun().setText("时间");
      // 创建文本框
      XSLFTextBox textBox22 = slide.createTextBox();
      // x y设置距离w h 设置大小
      textBox22.setAnchor(new Rectangle2D.Double(250,100, 600, 50));
      // 设置文本框的内容
      textBox22.addNewTextParagraph().addNewTextRun().setText("地点");

      // 创建文本框
      XSLFTextBox textBox3 = slide.createTextBox();
      // x y设置距离w h 设置大小
      textBox3.setAnchor(new Rectangle2D.Double(30,150, 600, 50));
      // 设置文本框的内容
      textBox3.addNewTextParagraph().addNewTextRun().setText("事件"
      // 创建文本框
      XSLFTextBox textBox33 = slide.createTextBox();
      // x y设置距离w h 设置大小
      textBox33.setAnchor(new Rectangle2D.Double(250,150, 600, 50));
      // 设置文本框的内容
      textBox33.addNewTextParagraph().addNewTextRun().setText("备注");


      // 插入图片
      // 获取图片的file对象
      File file = new File("C:\\图片.png");
      // 获取字节流
      byte[] bt = FileUtils.readFileToByteArray(file);
      XSLFPictureData idx = ppt.addPicture(bt, PictureData.PictureType.PNG);
      // 插入图片
      XSLFPictureShape pic = slide.createPicture(idx);
      pic.setAnchor(new Rectangle2D.Double(30,200,350,150));


      // 写入ppt中
      ppt.write(new FileOutputStream("输出PPT"+".pptx"));
    }

2.模板处理
import com.oppo.ipd.plm.mechanical.web.structure.PPTExport.bean.WeekAnalyseModel;
import org.apache.commons.io.FileUtils;
import org.apache.poi.sl.usermodel.Shape;
import org.apache.poi.sl.usermodel.*;
import org.apache.poi.xslf.usermodel.XSLFTextRun;
import org.apache.poi.xslf.usermodel.XSLFTextShape;

import java.awt.*;
import java.io.*;
import java.net.URL;
import java.util.Iterator;

/**
* <p>PowerPoint文件工具基类
* <p>
* <p>通用的PowerPoint文件工具基类,可用于从PowerPoint文档中抽取文本信息
*/
public class BasePowerPointFileUtil {



    /**
   * 渲染、绘制文本框
   *
   * @param shape
   * @param data
   */
    public static void renderShapeAndPicture(Shape shape, WeekAnalyseModel data, String rankType) {
      //判断是否是文本框
      if (shape instanceof TextShape) {
            BasePowerPointFileUtil.replace(shape, data,rankType);
      } else if (shape instanceof GroupShape) {
            Iterator groupShapes = ((GroupShape) shape).iterator();
            while (groupShapes.hasNext()) {
                Shape groupShape = (Shape) groupShapes.next();
                BasePowerPointFileUtil.renderShapeAndPicture(groupShape, data,rankType);
            }
      } else if (shape instanceof TableShape) {
            TableShape tableShape = ((TableShape) shape);
            int column = tableShape.getNumberOfColumns();
            int row = tableShape.getNumberOfRows();
            for (int r = 0; r < row; r++) {
                for (int c = 0; c < column; c++) {
                  BasePowerPointFileUtil.replace(tableShape.getCell(r, c), data,rankType);
                }
            }
      } else if (shape instanceof PictureShape) {
            //判断是否是图片框
            PictureShape pictureShape = (PictureShape) shape;
            PictureData pictureData = pictureShape.getPictureData();
            byte[] bytes = BufferStreamForByte(URLToFile(data.getPictureURL()), 1024);
            try {
                pictureData.setData(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
      }

    }


    /**
   * 替换模板PPT中的值
   *
   * @param shape
   * @param weekAnalyseModel
   */
    public static void replace(Shape shape, WeekAnalyseModel weekAnalyseModel,String rankType) {
      //List<WeekAnalyseModel>是我们项目自己定义的model,可改成其他业务的model
      if (shape instanceof TextShape) {

            String replaceText = ((XSLFTextShape) shape).getText();
            XSLFTextRun xslfTextRun = null;
            //替换数据的业务逻辑,待优化
            switch (replaceText) {
                case "{name}":
                  xslfTextRun = ((XSLFTextShape) shape).setText(weekAnalyseModel.getName());
                  break;
                case "{person}":
                  xslfTextRun = ((XSLFTextShape) shape).setText(weekAnalyseModel.getPerson());
                  break;

            }

            //空值过滤,设置样式
            if (xslfTextRun != null) {
                if (rankType.equals("未定义")||rankType.equals("未定义")){
                  setTextStyle(xslfTextRun);
                }else if (rankType.equals("未定义")||rankType.equals("未定义")){
                  setTextStyleCertificate(xslfTextRun);
                }
            }
      }
    }

    /**
   * 设置字体样式
   *
   * @param xslfTextRun
   */
    private static void setTextStyle(XSLFTextRun xslfTextRun) {
      xslfTextRun.setFontFamily("等线(正文)");
      Color color = new Color(255, 255, 255);
      xslfTextRun.setFontColor(color);
      xslfTextRun.setFontSize(40.0);
      xslfTextRun.setBold(true);
    }

    /**
   * 设置证书字体样式
   *
   * @param xslfTextRun
   */
    private static void setTextStyleCertificate(XSLFTextRun xslfTextRun) {
      xslfTextRun.setFontFamily("宋体");
      Color color = new Color(0, 0, 0);
      xslfTextRun.setFontColor(color);
      xslfTextRun.setFontSize(32.0);
      xslfTextRun.setBold(true);
    }

    /**
   * 将文件转为字节数组
   * @param file
   * @param size
   * @return
   */
    public static byte[] BufferStreamForByte(File file, int size) {
      byte[] content = null;
      try {
            BufferedInputStream bis = null;
            ByteArrayOutputStream out = null;
            try {
                FileInputStream input = new FileInputStream(file);
                bis = new BufferedInputStream(input, size);
                byte[] bytes = new byte;
                int len;
                out = new ByteArrayOutputStream();
                while ((len = bis.read(bytes)) > 0) {
                  out.write(bytes, 0, len);
                }

                bis.close();
                content = out.toByteArray();
            } finally {
                if (bis != null) {
                  bis.close();
                }
                if (out != null) {
                  out.close();
                }
            }
      } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
      }
      return content;

    }

    /**
   * 读取网络中的图片
   * @param url https://www.kziyue.com/wp-content/uploads/2019/06/5bca-hxyuaph9825616.jpg
   * @return
   */
    public static File URLToFile(String url){
      File file1 = new File("replace.png");
      try {

            URL url1 = new URL(url);
            FileUtils.copyURLToFile(url1,file1);

      } catch (IOException e) {
            e.printStackTrace();
      }
      File absoluteFile = file1.getAbsoluteFile();
      return file1;
    }


}


3.内容实体类
import lombok.Data;

@Data
public class WeekAnalyseModel {

    private String name;
    private String pictureURL;
    private String person;
}

4.测试代码:
   public static void main(String[] args) throws Exception {
      //载入数据
      WeekAnalyseModel weekAnalyseModel=new WeekAnalyseModel();
      weekAnalyseModel.setName("数据来源1");
      weekAnalyseModel.setPerson("数据来源1");
      weekAnalyseModel.setPictureURL("http://dev.itqu.net/1.jpg");


      WeekAnalyseModel weekAnalyseModel2=new WeekAnalyseModel();
      weekAnalyseModel2.setName("数据来源2");
      weekAnalyseModel2.setPerson("数据来源2");
      weekAnalyseModel2.setPictureURL("http://dev.itqu.net/2.jpg");

      WeekAnalyseModel weekAnalyseModel3=new WeekAnalyseModel();
      weekAnalyseModel3.setName("数据来源3");
      weekAnalyseModel3.setPerson("数据来源3");
      weekAnalyseModel3.setPictureURL("http://dev.itqu.net/3.jpg");

      ArrayList arrayList=new ArrayList();
      arrayList.add(weekAnalyseModel);
      arrayList.add(weekAnalyseModel2);
      arrayList.add(weekAnalyseModel3);

      //载入模板ppt,创建模板副本
      InputStream inputStream = new FileInputStream("model.pptx");
      copyFile("model.pptx","model-copy.pptx");
      InputStream inputStreamCopy = new FileInputStream("model-copy.pptx");

      RenderPowerPointTemplate.renderPowerPointTemplateOfCertificate(inputStreamCopy,arrayList,"out");


    }

    private static void copyFile(String source, String copy) {
      Path sourcePath = Paths.get(source);
      Path destinationPath = Paths.get(copy);
      try {
            Files.copy(sourcePath, destinationPath,StandardCopyOption.REPLACE_EXISTING);
      } catch (FileAlreadyExistsException e) {
            // 目标文件已经存在
      } catch (IOException e) {
            // 发生了其他错误
            e.printStackTrace();
      }
    }



Edithpab 发表于 2024-11-3 04:23:00

super online casino x78qcp


You definitely made the point!
online casino with signup bonus aussie casinos online gta online free car casino
gta online casino private dealer online casino new york rsweeps online casino at home
casino panama online slotocash casino no deposit bonus codes casino online bonos sin deposito
best online casino refer a friend bonus online casino michigan 2020 new online casinos
my live online casino best apps for sports betting resorts casino online coupon code

Edithpab 发表于 2024-11-3 06:46:55

5 star online casino w56bvf

Edithpab ??? 2024-11-3 04:23
You definitely made the point!
online casino with signup bonus aussie casinos online gta online f ...


Cheers! Terrific information.
offerte casino online casino credit card casino free online stream
ndbc online casino online casino real money indiana online online casino
online casino max bet horse race betting 777 bet online casino login
gsn casino online indiana online casino best casino online payouts
casinos usa online poker sites real money legal online casinos in pa

Edithpab 发表于 2024-11-3 12:04:43

jocuri casino gratis online a29vql

You stated it exceptionally well!
gta v online casino car this week best minnesota online casinos betsafe online casino
online casino with fish tables red dog casino 100 no deposit bonus codes online casinos with no deposit bonuses
the pokies online casino nba sports betting australian online casinos with no deposit bonus
online casino real money pennsylvania casino slots online arizona online casino
online casino real money in india no deposit online casino riversweeps online casino 777 download

Edithpab 发表于 2024-11-3 17:03:14

free online casino no deposit bonus codes i84kue

Edithpab ??? 2024-11-3 04:23
You definitely made the point!
online casino with signup bonus aussie casinos online gta online f ...


You have made your point pretty clearly!.
online casinos with no deposit bonus codes safe casino games mafia 7777 casino online
casino online con bonus di benvenuto senza deposito cafe casino bonus codes las vegas casinos online slots
online casino self exclusion best apps for sports betting casino online 2021
online casino 100 bonus best online poker rooms igri online casino
online casino in Г¶sterreich blackjack online real money baccarat online usa casino bonus

Edithpab 发表于 2024-11-3 17:28:15

best nj online casino bonus s68wvp

You actually revealed this effectively.
casino igre online free best online casino illinois real money free bonus casino games online
best online casino australia reviews mlb best bet online casinos tanzania
online casino payment system online craps casino online games that pay real money
us online casino sites red dog casino no deposit bonus codes online casino canada no deposit
casino online santa rosa la pampa ducky luck casino new online casino october 2023

Edithpab 发表于 2024-11-3 17:33:40

online casino for blackjack b790cy

Edithpab ??? 2024-11-3 04:23
You definitely made the point!
online casino with signup bonus aussie casinos online gta online f ...


Superb information. Many thanks!
best promo codes for online casinos casino online games real money online casino legit sites
online casino courses real money online casino north carolina skycity online casino sign up
hungary online casino online betting are there any recordings of casino radio las vegas online
how to win from online casinos cafe casino no deposit wind creek online casino pa promo code
online casino bezahlen mit handy soccer betting sites in usa online casino roulette kostenlos

Edithpab 发表于 2024-11-3 22:04:27

ruleta online casino gran madrid d96kiz

Edithpab ??? 2024-11-3 17:03
You have made your point pretty clearly!.
online casinos with no deposit bonus codes safe casin ...


Reliable knowledge. Kudos!
snelst uitbetalende online casino app for betting casino royale 2006 full movie online
best online casinos in australia casino in new zealand ainsworth online casinos
ocean monster online casino online bingo sites grand casino games online
online casinos reddit red dog casino 100 free chip best payout online casino uk
cleopatra casino game free online new pa online casino online casino no deposit no download

Edithpab 发表于 2024-11-4 03:10:38

online free casino t86vjo


Nicely put, Thanks a lot.
yaamava online casino login san manuel mobile gambling app casino heist gta online payout
new online casinos for usa players bet soccer online stripper casino online
gta online kicked out of casino casino in auckland new zealand echeck deposit online casino
q casino online real money slot machines casino greek online
top 5 online casino real money crash gambling real money 21 casino online

Edithpab 发表于 2024-11-4 03:24:56

australian online casinos that accept paysafe v13dsb

Edithpab ??? 2024-11-4 03:10
Nicely put, Thanks a lot.
yaamava online casino login san manuel mobile gambling app casino heist ...


Thank you! I enjoy this.
online roulette casino australia las atlantis reviews casino online zonder registratie
riversweeps 777 online casino download real slot machines for real money schweizer online casino legal
online casino live tables online casinos north carolina draft kings online casino
gala casino online contact number tennessee online casinos best maine online casino sites
888 live casino online lucky tiger casino new pa casino online
页: [1] 2 3 4
查看完整版本: PPT导出-模板和自定义处理方案