使用Docx4j操作PPT指南系列(一)
—— pptx文檔的生成與添加新頁
寫在最前
由于項目需要系統生成ppt文檔,在開源技術中標明了docx4j。docx4j操作ppt的文檔幾乎沒有(中文的就更加鳳毛麟角了),所有的東西隻能自己去摸索,是以才有了這一系列的文檔,也算是抛磚引玉,受限于項目使用場景,本系列僅對項目中使用的一些功能進行描述,我想差不多能夠涵蓋基本的功能,歡迎各位看官與我進行交流,共同進步。
準備工作
下載下傳位址:
Maven配置:
<code><</code><code>dependency</code><code>></code>
<code><</code><code>groupId</code><code>>org.docx4j</</code><code>groupId</code><code>></code>
<code><</code><code>artifactId</code><code>>docx4j</</code><code>artifactId</code><code>></code>
<code><</code><code>version</code><code>>2.7.1</</code><code>version</code><code>></code>
<code></</code><code>dependency</code><code>></code>
注意:docx4j主要用于操作Office2007版本。
建立ppt文檔
public class CreatePPTX
{
public static void main(String[] args)
throws Exception
{
String outputfilepath = "c://pptx-test.pptx";
// 建立文檔的主體
PresentationMLPackage presentationMLPackage = PresentationMLPackage.createPackage();
// 擷取MainPresentationPart,實際上使用
// presentationMLPackage.getMainPresentationPart(); 方法也可以
MainPresentationPart pp = (MainPresentationPart)presentationMLPackage.getParts().getParts().get(new PartName("/ppt/presentation.xml"));
// 擷取布局資訊,實際上是擷取幻燈片母版的布局頁,這個功能很重要。
// 建立一個新頁時必須應用一個布局
// "/ppt/slideLayouts/slideLayout1.xml"這個是母版頁的id,具體要看母版中有多少布
// 局樣式,是1、2、3、4依次排列的
SlideLayoutPart layoutPart = (SlideLayoutPart)presentationMLPackage.getParts().getParts().get(new PartName("/ppt/slideLayouts/slideLayout1.xml"));
// 建立一個新頁,一定要帶上布局頁資訊,否則打開ppt時會報錯,
// 并且自動指定一個預設的布局樣式
// "/ppt/slides/slide1.xml" 每一頁的partName不能重複
SlidePart slidePart = PresentationMLPackage.createSlidePart(pp, layoutPart, new PartName("/ppt/slides/slide1.xml"));
// 儲存成檔案
presentationMLPackage.save(new File(outputfilepath));
System.out.println("\n\n done .. saved " + outputfilepath);
}
}
個人建議不要直接建立新的ppt檔案,一般對于企業來說都會有幾種特定的ppt模闆,直接使用這些模闆可以節省大量的時間,而且封面頁以及母版的布局都是定制好的,隻需要用就可以了。
唯一代碼上有所差別,是從一個檔案中加載的,如下:
PresentationMLPackage presentationMLPackage = PresentationMLPackage.load(new File(
PSMSConstants.REPORT_PPT2007_TEMPLATE_PATH));
OK, 在這一部分内容中,應該以及掌握了使用docx4j建立pptx檔案以及添加内容頁的方法,在下一部分中,将介紹如何向内容頁中添加文本和圖形等内容。
本文轉自william_xu 51CTO部落格,原文連結:http://blog.51cto.com/williamx/758955,如需轉載請自行聯系原作者