@
目錄- 起因
- 程序
- 確定工具
- 功能拆分
- 讀取Word檔案
- 通過PPT模板創建PPT并填充內容
- 將PPT轉為圖片
- 總結
起因
近期身邊的一位朋友來尋求幫助,她在日常作業時,總是需要做一些重復的事情,所以想著是否能通程序式實作自動化的操作,
具體需求為,每天會收到一份固定格式的Word檔案,然后根據其中的內容,填充到固定的PPT模板中,最終生成圖片輸出,
程序
確定工具
有了需求后,第一件事自然是在網路上查找是否有符合需要的工具使用,筆者之前用過Apache POI來操作過Excel檔案的經歷,因此有印象Apache POI是支持Office檔案的操作,不局限于Excel檔案,于是決定就用它了,(制作后期有看到一些其他的工具框架,比如Spire,但一是因為已經用POI實作了大部分功能,二是因為比如Spire的高級功能是收費的,最侄訓是用POI一條路走到底了)
Apache POI是用Java撰寫的免費開源的跨平臺的 Java API,Apache POI提供API給Java程式對Microsoft Office(Excel、WORD、PowerPoint、Visio等)格式檔案讀和寫的功能(基于OLE2 Compound documents of MS-Office檔案格式 ),POI本身為“Poor Obfuscation Implementation”的首字母縮寫,
其中POI主要有以下功能模塊:
- HSSF - 提供讀寫Microsoft Excel XLS格式檔案的功能,
- XSSF - 提供讀寫Microsoft Excel OOXML XLSX格式檔案的功能,
- HWPF - 提供讀寫Microsoft Word DOC97格式檔案的功能,
- XWPF - 提供讀寫Microsoft Word DOC2003格式檔案的功能,
- HSLF - 提供讀寫Microsoft PowerPoint格式檔案的功能,
- HDGF - 提供讀Microsoft Visio格式檔案的功能,
- HPBF - 提供讀Microsoft Publisher格式檔案的功能,
- HSMF - 提供讀Microsoft Outlook格式檔案的功能,
功能拆分
確定使用的工具之后,便是將需求進行功能性拆分,方便功能的獨立實作,
- 讀取Word檔案,包括文字的顏色屬性,
- 讀取PPT模板,通過模板創建新的PPT,并將Word檔案中讀取的內容填充到新建的PPT檔案中,
- 將PPT檔案轉換為圖片,
讀取Word檔案
Apache POI支持對Word檔案進行讀寫操作,筆者使用的3.17的版本,主要是因為開始查找相關范例的時候,網上的demo多數基于這個版本,雖然版本不是最新的,但足夠實作所需要的功能,(筆者在功能完成后,有嘗試使用最新版的POI,新版的實作與舊版略有不同,會導致已實作的功能報錯,因為時間問題就沒有深究,因此又退回了3.17的版本),POI的Maven依賴如下所示:
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.17</version>
</dependency>
</dependencies>
引入POI庫后,便可以著手進行功能的實作了,下面的示例為讀取本地磁盤的Word檔案,
// 讀取制定路徑下的doc檔案,測驗時使用的是docx檔案
public static ArrayList<WordStrList> readDoc1(String path) throws IOException {
InputStream is = new FileInputStream(path);
XWPFDocument doc = new XWPFDocument(is);
ArrayList<WordStrList> wordLists = new ArrayList<WordStrList>();
List<XWPFParagraph> paras = doc.getParagraphs();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < paras.size(); i++) {
XWPFParagraph para = paras.get(i);
List<XWPFRun> runsLists = para.getRuns();
WordStrList wordList = new WordStrList();
for (XWPFRun run : runsLists) {
// 獲取文本內容及文本顏色
WordStr wordStr = new WordStr(run.toString(), run.getColor());
wordList.add(wordStr);
sb.append(run.toString());
}
wordLists.add(wordList);
sb.setLength(0);
}
System.out.println("Word檔案【"+path+"】加載完畢...");
return wordLists;
}
通過XWPFDocument可以很輕松地讀取到指定的Word檔案,除了Word的文本內容外,還能獲取一些格式屬性,筆者只需要獲取對應文字的顏色即可,
通過PPT模板創建PPT并填充內容
在上一步中,我們可以讀取Word檔案中的內容,加以一定的決議篩選,便可以得到想要往PPT中填充的內容了,
筆者這次的PPT模板非常簡單,分為封面、內容頁、封底,每頁都是一張底圖加一個文本框,因此相對操作比較簡單,參考代碼如下:
public static void createPPTByTemplate(String templatePath, String destPPTPath, ArrayList<WordStrList> contentList) {
InputStream is;
OutputStream os;
XMLSlideShow oPPT;
try {
is = new FileInputStream(templatePath);
os = new FileOutputStream(destPPTPath);
oPPT = new XMLSlideShow(is);
} catch (IOException e) {
throw new RuntimeException(e);
}
XMLSlideShow dPPT = new XMLSlideShow();
// 將新建的PPT頁面大小設定為模板頁面大小
dPPT.setPageSize(oPPT.getPageSize());
// 獲取PPT模板
List<XSLFSlide> slides = oPPT.getSlides();
XSLFSlide baseSlide0 = slides.get(0);
XSLFSlide baseSlide1 = slides.get(1);
XSLFSlide baseSlide2 = slides.get(2);
//創建內容頁
System.out.println("創建內容頁...");
Pattern indexPattern = Pattern.compile("[\\d]+、");
for (int i = 1; i < contentList.size() - 1; i++) {
WordStrList wsl = contentList.get(i);
Matcher matcher = indexPattern.matcher(wsl.toString().substring(0, 5));
XSLFSlide contentSlide = copySlide(dPPT, baseSlide1);
shapeList = contentSlide.getShapes();
for (XSLFShape shape : shapeList) {
if (shape instanceof XSLFTextShape) {
XSLFTextShape temp = (XSLFTextShape) shape;
temp.clearText();
XSLFTextRun xslfTextRun;
WordStr wStr;
if (!matcher.find()) {
String tempStr = wsl.get(0).getStr();
wsl.get(0).setStr(i + "、" + tempStr);
}
for (int j = 0; j < wsl.size(); j++) {
wStr = wsl.get(j);
xslfTextRun = temp.appendText(wStr.getStr(), false);
setText(xslfTextRun, wStr.getColor(), 18.0, "等線");
temp.setHorizontalCentered(true);
}
}
}
}
//將PPT寫出至本地
try {
dPPT.write(os);
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println("PPT【" + destPPTPath + "】生成結束,生成PPT頁數:" + dPPT.getSlides().size() + "頁...");
}
public static XSLFSlide copySlide(XMLSlideShow slideShow, XSLFSlide slide) {
XSLFSlide xslfSlide = slideShow.createSlide();
List<XSLFShape> shapes = slide.getShapes();
for (XSLFShape shape : shapes) {
xslfSlide.importContent(shape.getSheet());
}
return xslfSlide;
}
public static void setText(XSLFTextRun xslfTextRun, String color, double fontSize, String fontFamily) {
xslfTextRun.setFontColor(fromStrToARGB(color));
xslfTextRun.setFontSize(fontSize);
xslfTextRun.setFontFamily(fontFamily);
}
public static Color fromStrToARGB(String str) {
String redStr = str.substring(0, 2);
String greenStr = str.substring(2, 4);
String blueStr = str.substring(4, 6);
int red = Integer.parseInt(redStr, 16);
int green = Integer.parseInt(greenStr, 16);
int blue = Integer.parseInt(blueStr, 16);
Color color = new Color(red, green, blue);
return color;
}
因為筆者原始碼中含有一些自己檔案格式的決議,所以就沒有貼出全部的內容了,這里的PPT創建主要分為幾步,通過 XMLSlideShow 獲取模板檔案、通過XMLSlideShow 創建新的PPT檔案,通過模板向新建PPT檔案中創建新的頁面,將之前讀取到的內容填充至新建PPT中,
將PPT轉為圖片
該功能需要注意的是,按原尺寸繪制的PPT界面會比較模糊,可以通過等比例放大圖片,使生成的圖片更加清晰,
同時,目前該功能無法將第二步代碼生成的PPT進行轉換,可以轉換正常的PPT檔案,因為在拷貝模板的步驟中( public XSLFSlide importContent(XSLFSheet src)),會改變新建PPT頁SlideLayout,最終導致繪制程序報錯,此處目前暫未找到好的方法解決,
public static int converPPTtoImage(String pptPath, String targetImageFileDir,
String imageFormatNameString, int times) {
File orignalPPTFile = new File(pptPath);
//驗證檔案是否為pptx格式
if (!checkIsPPTFile(orignalPPTFile)) {
System.out.print("待轉換檔案格式例外,不是pptx");
return 0;
}
FileInputStream is = null;
int imgCount = 0;
File imgFileDir = new File(targetImageFileDir);
//如果沒有檔案夾就創建檔案夾
createDirIfNotExist(targetImageFileDir);
try {
is = new FileInputStream(orignalPPTFile);
XMLSlideShow xmlSlideShow = new XMLSlideShow(is);
List<XSLFSlideMaster> list = xmlSlideShow.getSlideMasters();
XSLFSlideLayout[] slideLayouts = list.get(0).getSlideLayouts();
is.close();
// 獲取大小
Dimension pgsize = xmlSlideShow.getPageSize();
// 獲取幻燈片
XSLFSlide[] slides = xmlSlideShow.getSlides().toArray(new XSLFSlide[0]);
imgCount = slides.length;
System.out.println("|--3.slides.length--|"+imgCount);
for (int i = 0; i < slides.length; i++) {
// 創建BufferedImage物件,影像的尺寸為原來的每頁的尺寸*倍數times
BufferedImage img = new BufferedImage(pgsize.width * times,
pgsize.height * times, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
graphics.setPaint(Color.white);
graphics.scale(times, times);// 將圖片放大times倍
graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
// 繪制
slides[i].draw(graphics);
//圖片將要存放的路徑
String absolutePath = imgFileDir.getAbsolutePath() + File.separator + (i + 1)
+ "." + imageFormatNameString;
File jpegFile = new File(absolutePath);
//如果圖片存在,則不再生成
if (jpegFile.exists()) {
continue;
}
// 這里設定圖片的存放路徑和圖片的格式(jpeg,png,bmp等等),注意生成檔案路徑
FileOutputStream out = new FileOutputStream(jpegFile);
// 寫入到圖片中去
ImageIO.write(img, imageFormatNameString, out);
out.close();
}
return imgCount;
} catch (Exception e) {
e.printStackTrace();
}
return imgCount;
}
總結
生活中有著很多重復性的作業,也許只要花少量的時間,就可以創建一個自動化的工具來協助我們更高效地完成日常作業,解放一定的時間,并且在制作工具的同時,也可以了解更多的知識,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/519117.html
標籤:其他
