# PptxGenJS 好的,我們繼續進階學習 **PptxGenJS**,這次我會從**基礎 → 進階**帶你熟悉常用功能,並給出實際程式碼示例,讓你能快速上手。 --- ## **1️⃣ 建立簡報基本結構** ```javascript import pptxgen from "pptxgenjs"; // 建立簡報實例 let pptx = new pptxgen(); // 設定簡報版面 (可省略,預設 16:9) pptx.defineLayout({ name:'WIDE', width:10, height:5.625 }); // 新增投影片 let slide = pptx.addSlide(); // 新增文字 slide.addText("Hello PptxGenJS!", { x:1, y:1, fontSize:24, color:'363636' }); // 下載檔案 pptx.writeFile("example.pptx"); ``` 💡 `defineLayout` 可自訂簡報大小(單位:英吋)。 --- ## **2️⃣ 加入圖片** ```javascript slide.addImage({ path: "https://via.placeholder.com/300x200", x: 1, y: 2, w: 3, h: 2 }); ``` * 支援 **URL**、**Base64 Data URL** 或本地檔案(Node.js)。 --- ## **3️⃣ 新增表格** ```javascript slide.addTable([ [ { text:"Name", options:{ bold:true } }, { text:"Age", options:{ bold:true } } ], [ "John", 30 ], [ "Alice", 25 ] ], { x: 1, y: 4, w: 5, border: { pt:1, color:'000000' }, fill: 'F1F1F1' }); ``` * 每格可以有不同 `options` (字型、顏色、對齊)。 --- ## **4️⃣ 新增圖表 (Charts)** ```javascript let dataChart = [ { name: "Sales", labels: ["Jan", "Feb", "Mar"], values: [30, 50, 70] } ]; slide.addChart(pptx.ChartType.bar, dataChart, { x: 6, y: 1, w: 3, h: 3, chartTitle: "Monthly Sales" }); ``` * `ChartType` 有:`bar`, `line`, `pie`, `area`, `scatter`, `bubble`, `radar`。 --- ## **5️⃣ 新增形狀與線條** ```javascript slide.addShape(pptx.ShapeType.rect, { x: 1, y: 1, w: 3, h: 1, fill: { color: "FF0000" }, line: { color: "000000", width: 2 } }); slide.addShape(pptx.ShapeType.line, { x: 1, y: 2, w: 3, h: 0, line: { color: "00FF00", width: 1 } }); ``` * `ShapeType` 提供矩形、圓形、箭頭、線段等。 --- ## **6️⃣ 超連結與點擊跳轉** ```javascript slide.addText("前往 Google", { x: 1, y: 5, w: 3, h: 0.5, hyperlink: { url: "https://google.com" }, color: "0000FF", underline: true }); ``` * 可設定 `hyperlink: { slide:2 }` 在簡報內部跳轉。 --- ## **7️⃣ 使用母片 (Master Slide)** 可以定義統一版面樣式: ```javascript pptx.defineSlideMaster({ title: 'MASTER1', bkgd: 'FFFFFF', objects: [ { text:'公司簡報', options:{ x:0.5, y:0.2, fontSize:18, bold:true } } ], slideNumber: { x: 9.5, y: 5.3, color: '888888' } }); let slide2 = pptx.addSlide({ master:'MASTER1' }); slide2.addText("第二頁內容", { x:1, y:1 }); ``` --- ## **8️⃣ 下載與儲存** * **前端瀏覽器下載** ```javascript pptx.writeFile("MyPresentation.pptx"); ``` * **Node.js 儲存至檔案** ```javascript pptx.writeFile({ fileName: "ServerGenerated.pptx" }); ``` --- ## ✅ 小技巧 1. **座標單位固定為英吋**(建議先定義簡報寬高再規劃位置)。 2. 可用 `pptx.SlideWidth`、`pptx.SlideHeight` 動態計算置中位置,例如: ```javascript let centerX = (pptx.SlideWidth - 3) / 2; slide.addText("置中", { x:centerX, y:2, w:3 }); ``` 3. 支援自動換行、段落、文字對齊等細節控制。 --- 要不要我接下來幫你做一份 **「PptxGenJS 常用功能快速參考表(所有 API 屬性、可用參數清單)」**,讓你複製就能用?