Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.
Python aianthropicautomationclaude-codeclaude-skillscloudflaredevtoolsproductivityreactskillstailwindvite
feat(office): Add templates and API references (Phase 5)
Jez3744a1e96429
diff --git a/skills/office/references/docx-api.md b/skills/office/references/docx-api.mdnew file mode 100644index 00000000..6ccbf76e--- /dev/null+++ b/skills/office/references/docx-api.md@@ -0,0 +1,210 @@+# docx npm - Quick API Reference++**Package**: `docx` | **Version**: 9.5.0+ | **Docs**: https://docx.js.org++## Installation++```bash+npm install docx+```++## Core Imports++```typescript+import {+ Document,+ Packer,+ Paragraph,+ TextRun,+ Table,+ TableRow,+ TableCell,+ HeadingLevel,+ AlignmentType,+ WidthType,+ BorderStyle,+ ImageRun,+} from 'docx';+```++## Document Structure++```typescript+const doc = new Document({+ creator: 'Author Name',+ title: 'Document Title',+ description: 'Description',+ sections: [{+ children: [+ // Paragraphs, Tables, etc.+ ],+ }],+});+```++## Paragraph++```typescript+// Simple text+new Paragraph({ text: 'Hello World' })++// With heading+new Paragraph({+ text: 'Title',+ heading: HeadingLevel.HEADING_1,+ alignment: AlignmentType.CENTER,+})++// With formatted runs+new Paragraph({+ children: [+ new TextRun('Normal text'),+ new TextRun({ text: 'Bold', bold: true }),+ new TextRun({ text: 'Italic', italics: true }),+ new TextRun({ text: 'Colored', color: 'FF0000' }),+ new TextRun({ text: 'Sized', size: 24 }), // Half-points (24 = 12pt)+ ],+})++// With indent+new Paragraph({+ text: '• Bullet point',+ indent: { left: 720 }, // Twips (720 = 0.5 inch)+})+```++## TextRun Options++| Option | Type | Description |+|--------|------|-------------|+| `text` | string | The text content |+| `bold` | boolean | Bold text |+| `italics` | boolean | Italic text |+| `underline` | object | `{ type: UnderlineType.SINGLE }` |+| `color` | string | Hex color without # (e.g., 'FF0000') |+| `size` | number | Font size in half-points (24 = 12pt) |+| `font` | string | Font family name |+| `highlight` | string | Highlight color |+| `strike` | boolean | Strikethrough |++## HeadingLevel++```typescript+HeadingLevel.TITLE+HeadingLevel.HEADING_1+HeadingLevel.HEADING_2+HeadingLevel.HEADING_3+HeadingLevel.HEADING_4+HeadingLevel.HEADING_5+HeadingLevel.HEADING_6+```++## AlignmentType++```typescript+AlignmentType.LEFT+AlignmentType.CENTER+AlignmentType.RIGHT+AlignmentType.JUSTIFIED+```++## Table++```typescript+new Table({+ width: { size: 100, type: WidthType.PERCENTAGE },+ rows: [+ new TableRow({+ children: [+ new TableCell({+ children: [new Paragraph({ text: 'Cell 1' })],+ width: { size: 50, type: WidthType.PERCENTAGE },+ borders: {+ top: { style: BorderStyle.SINGLE, size: 1, color: 'CCCCCC' },+ bottom: { style: BorderStyle.SINGLE, size: 1, color: 'CCCCCC' },+ left: { style: BorderStyle.SINGLE, size: 1, color: 'CCCCCC' },+ right: { style: BorderStyle.SINGLE, size: 1, color: 'CCCCCC' },+ },+ shading: { fill: 'F0F0F0' },+ }),+ new TableCell({+ children: [new Paragraph({ text: 'Cell 2' })],+ }),+ ],+ }),+ ],+})+```++## WidthType++```typescript+WidthType.PERCENTAGE // Percentage of page width+WidthType.DXA // Twips (1/20 of a point)+WidthType.AUTO // Auto width+```++## BorderStyle++```typescript+BorderStyle.SINGLE+BorderStyle.DOUBLE+BorderStyle.DASHED+BorderStyle.DOTTED+BorderStyle.NONE+```++## Images++```typescript+import { readFileSync } from 'fs';++new Paragraph({+ children: [+ new ImageRun({+ data: readFileSync('image.png'),+ transformation: { width: 200, height: 100 },+ type: 'png', // or 'jpg'+ }),+ ],+})+```++## Export (CRITICAL: Async!)++```typescript+// Node.js - save to file+import { writeFileSync } from 'fs';+const buffer = await Packer.toBuffer(doc); // MUST await!+writeFileSync('output.docx', buffer);++// Cloudflare Workers - HTTP response+const buffer = await Packer.toBuffer(doc);+return new Response(buffer, {+ headers: {+ 'Content-Type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',+ 'Content-Disposition': 'attachment; filename="document.docx"',+ },+});++// Browser - Blob for download+const blob = await Packer.toBlob(doc);+const url = URL.createObjectURL(blob);+```++## Common Mistakes++| Mistake | Fix |+|---------|-----|+| `Packer.toBuffer(doc)` without await | Always `await Packer.toBuffer(doc)` |+| Color with # (`'#FF0000'`) | Omit # (`'FF0000'`) |+| Size in points | Size is half-points (multiply by 2) |+| Indent in inches | Indent is twips (multiply by 1440) |++## Units Reference++| Unit | Conversion |+|------|------------|+| Points to half-points | × 2 |+| Inches to twips | × 1440 |+| cm to twips | × 567 |diff --git a/skills/office/references/pdf-lib-api.md b/skills/office/references/pdf-lib-api.mdnew file mode 100644index 00000000..2eda3122--- /dev/null+++ b/skills/office/references/pdf-lib-api.md@@ -0,0 +1,363 @@+# pdf-lib - Quick API Reference++**Package**: `pdf-lib` | **Version**: 1.17.1+ | **Docs**: https://pdf-lib.js.org++## Installation++```bash+npm install pdf-lib+```++## Core Imports++```typescript+import {+ PDFDocument,+ StandardFonts,+ rgb,+ PageSizes,+ degrees,+ grayscale,+} from 'pdf-lib';+```++## Create Document++```typescript+const pdfDoc = await PDFDocument.create();+```++## Load Existing PDF++```typescript+// From bytes+const pdfDoc = await PDFDocument.load(existingPdfBytes);++// From base64+const pdfDoc = await PDFDocument.load(base64String);++// Ignore encryption (for copying pages)+const pdfDoc = await PDFDocument.load(bytes, { ignoreEncryption: true });+```++## Document Metadata++```typescript+pdfDoc.setTitle('Document Title');+pdfDoc.setAuthor('Author Name');+pdfDoc.setSubject('Subject');+pdfDoc.setKeywords(['keyword1', 'keyword2']);+pdfDoc.setProducer('Producer App');+pdfDoc.setCreator('Creator App');+pdfDoc.setCreationDate(new Date());+pdfDoc.setModificationDate(new Date());+```++## Pages++```typescript+// Add page with custom size+const page = pdfDoc.addPage([612, 792]); // Width x Height in points++// Add page with preset size+const page = pdfDoc.addPage(PageSizes.Letter);+const page = pdfDoc.addPage(PageSizes.A4);++// Get page dimensions+const { width, height } = page.getSize();++// Get existing page+const page = pdfDoc.getPage(0); // 0-indexed++// Get page count+const pageCount = pdfDoc.getPageCount();++// Remove page+pdfDoc.removePage(0);++// Insert page at index+pdfDoc.insertPage(0, page);+```++## Page Sizes (Width x Height in points)++| Size | Dimensions | Inches |+|------|------------|--------|+| `PageSizes.Letter` | [612, 792] | 8.5" × 11" |+| `PageSizes.A4` | [595.28, 841.89] | 210mm × 297mm |+| `PageSizes.Legal` | [612, 1008] | 8.5" × 14" |+| `PageSizes.Tabloid` | [792, 1224] | 11" × 17" |+| `PageSizes.A3` | [841.89, 1190.55] | 297mm × 420mm |+| `PageSizes.A5` | [419.53, 595.28] | 148mm × 210mm |++**Note**: 72 points = 1 inch++## Fonts++```typescript+// Embed standard font+const helvetica = await pdfDoc.embedFont(StandardFonts.Helvetica);+const helveticaBold = await pdfDoc.embedFont(StandardFonts.HelveticaBold);+const timesRoman = await pdfDoc.embedFont(StandardFonts.TimesRoman);+const courier = await pdfDoc.embedFont(StandardFonts.Courier);++// Embed custom font+import { readFileSync } from 'fs';+const fontBytes = readFileSync('path/to/font.ttf');+const customFont = await pdfDoc.embedFont(fontBytes);++// Get font metrics+const textWidth = font.widthOfTextAtSize('Hello', 12);+const textHeight = font.heightAtSize(12);+```++## Standard Fonts++```typescript+StandardFonts.Helvetica+StandardFonts.HelveticaBold+StandardFonts.HelveticaOblique+StandardFonts.HelveticaBoldOblique+StandardFonts.TimesRoman+StandardFonts.TimesRomanBold+StandardFonts.TimesRomanItalic+StandardFonts.TimesRomanBoldItalic+StandardFonts.Courier+StandardFonts.CourierBold+StandardFonts.CourierOblique+StandardFonts.CourierBoldOblique+StandardFonts.Symbol+StandardFonts.ZapfDingbats+```++## Colors++```typescript+// RGB (values 0-1)+const red = rgb(1, 0, 0);+const green = rgb(0, 1, 0);+const blue = rgb(0, 0, 1);+const custom = rgb(0.2, 0.4, 0.8);++// Grayscale (0 = black, 1 = white)+const black = grayscale(0);+const gray = grayscale(0.5);+const white = grayscale(1);+```++## Draw Text++```typescript+page.drawText('Hello World', {+ x: 50,+ y: 700, // From BOTTOM of page!+ size: 12,+ font: helvetica,+ color: rgb(0, 0, 0),+ opacity: 1,+ rotate: degrees(0), // Rotation angle+ lineHeight: 14, // For multi-line text+ maxWidth: 500, // Wrap text at width+});+```++## Draw Shapes++```typescript+// Rectangle+page.drawRectangle({+ x: 50,+ y: 500,+ width: 200,+ height: 100,+ color: rgb(0.9, 0.9, 0.9), // Fill color+ borderColor: rgb(0, 0, 0), // Border color+ borderWidth: 1,+ opacity: 1,+ borderOpacity: 1,+});++// Circle+page.drawCircle({+ x: 150, // Center X+ y: 400, // Center Y+ size: 50, // Radius+ color: rgb(1, 0, 0),+ borderColor: rgb(0, 0, 0),+ borderWidth: 1,+});++// Ellipse+page.drawEllipse({+ x: 150,+ y: 300,+ xScale: 100, // Horizontal radius+ yScale: 50, // Vertical radius+ color: rgb(0, 1, 0),+});++// Line+page.drawLine({+ start: { x: 50, y: 200 },+ end: { x: 200, y: 200 },+ thickness: 2,+ color: rgb(0, 0, 0),+ opacity: 1,+ dashArray: [5, 3], // Optional: dashed line+});++// Square (convenience)+page.drawSquare({+ x: 50,+ y: 100,+ size: 50,+ color: rgb(0, 0, 1),+});+```++## Draw Images++```typescript+// Embed PNG+const pngImage = await pdfDoc.embedPng(pngBytes);++// Embed JPG+const jpgImage = await pdfDoc.embedJpg(jpgBytes);++// Draw image+page.drawImage(pngImage, {+ x: 50,+ y: 500,+ width: 200,+ height: 100,+ opacity: 1,+ rotate: degrees(0),+});++// Get image dimensions+const { width, height } = pngImage.size();+const scaled = pngImage.scale(0.5); // Scale to 50%+```++## Copy Pages from Another PDF++```typescript+const srcPdf = await PDFDocument.load(srcBytes);+const destPdf = await PDFDocument.create();++// Copy specific pages+const [page1, page3] = await destPdf.copyPages(srcPdf, [0, 2]);+destPdf.addPage(page1);+destPdf.addPage(page3);++// Copy all pages+const pages = await destPdf.copyPages(srcPdf, srcPdf.getPageIndices());+pages.forEach(page => destPdf.addPage(page));+```++## Form Fields (AcroForms)++```typescript+// Get form+const form = pdfDoc.getForm();++// Get text field+const nameField = form.getTextField('name');+nameField.setText('John Doe');++// Get checkbox+const checkbox = form.getCheckBox('agree');+checkbox.check();+// checkbox.uncheck();++// Get dropdown+const dropdown = form.getDropdown('country');+dropdown.select('USA');++// Get radio group+const radio = form.getRadioGroup('gender');+radio.select('male');++// Flatten form (make fields uneditable)+form.flatten();+```++## Export++```typescript+// Get as Uint8Array+const pdfBytes = await pdfDoc.save();++// Node.js - save to file+import { writeFileSync } from 'fs';+writeFileSync('output.pdf', pdfBytes);++// Cloudflare Workers - HTTP response+const pdfBytes = await pdfDoc.save();+return new Response(pdfBytes, {+ headers: {+ 'Content-Type': 'application/pdf',+ 'Content-Disposition': 'attachment; filename="document.pdf"',+ },+});++// Browser - download+const blob = new Blob([pdfBytes], { type: 'application/pdf' });+const url = URL.createObjectURL(blob);++// Get as base64+const base64 = await pdfDoc.saveAsBase64();+const dataUri = await pdfDoc.saveAsBase64({ dataUri: true });+```++## Coordinate System++**CRITICAL**: PDF coordinate origin is at **BOTTOM-LEFT**, not top-left!++```+(0, height) -------- (width, height)+ | |+ | PDF Page |+ | |+ (0, 0) ---------- (width, 0)+```++To position from top:+```typescript+const { height } = page.getSize();+const yFromTop = height - 50; // 50 points from top+page.drawText('Near top', { x: 50, y: yFromTop, ... });+```++## Common Mistakes++| Mistake | Fix |+|---------|-----|+| Y coordinate from top | Calculate from bottom: `height - y` |+| RGB values 0-255 | RGB values are 0-1 (divide by 255) |+| Forgot await on embed | Always `await pdfDoc.embedFont()` |+| Forgot await on save | Always `await pdfDoc.save()` |+| Wrong image format | Use `embedPng` for PNG, `embedJpg` for JPG |++## Units Reference++| Unit | Points |+|------|--------|+| 1 inch | 72 |+| 1 cm | 28.35 |+| 1 mm | 2.835 |++## Measure Text for Layout++```typescript+const text = 'Hello World';+const fontSize = 12;+const textWidth = font.widthOfTextAtSize(text, fontSize);+const textHeight = font.heightAtSize(fontSize);++// Center text horizontally+const x = (pageWidth - textWidth) / 2;++// Right-align text+const x = pageWidth - textWidth - margin;+```diff --git a/skills/office/references/xlsx-api.md b/skills/office/references/xlsx-api.mdnew file mode 100644index 00000000..9b3f59bf--- /dev/null+++ b/skills/office/references/xlsx-api.md@@ -0,0 +1,234 @@+# SheetJS (xlsx) - Quick API Reference++**Package**: `xlsx` | **Version**: 0.18.5+ | **Docs**: https://docs.sheetjs.com++## Installation++```bash+npm install xlsx+```++## Core Import++```typescript+import * as XLSX from 'xlsx';+```++## Workbook Creation++```typescript+const wb = XLSX.utils.book_new();+```++## Sheet from Array of Arrays++```typescript+const data = [+ ['Name', 'Age', 'City'], // Header row+ ['Alice', 30, 'New York'],+ ['Bob', 25, 'London'],+];++const ws = XLSX.utils.aoa_to_sheet(data);+XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');+```++## Sheet from JSON++```typescript+const jsonData = [+ { name: 'Alice', age: 30, city: 'New York' },+ { name: 'Bob', age: 25, city: 'London' },+];++const ws = XLSX.utils.json_to_sheet(jsonData);+XLSX.utils.book_append_sheet(wb, ws, 'Employees');+```++## Formulas++```typescript+const data = [+ ['Item', 'Qty', 'Price', 'Total'],+ ['Widget', 10, 5, { f: 'B2*C2' }], // Formula: =B2*C2+ ['Gadget', 5, 12, { f: 'B3*C3' }],+ ['', '', 'Sum:', { f: 'SUM(D2:D3)' }], // Formula: =SUM(D2:D3)+];++const ws = XLSX.utils.aoa_to_sheet(data);+```++**Note**: Formulas are written to file but calculated when opened in Excel/Sheets.++## Cross-Sheet References++```typescript+// Reference another sheet in formula+{ f: 'Sheet2!A1' } // Single cell+{ f: "SUM(Sheet2!A1:A10)" } // Range+{ f: "Details!D7" } // Named sheet+```++## Column Widths++```typescript+ws['!cols'] = [+ { wch: 20 }, // Column A: 20 characters wide+ { wch: 10 }, // Column B: 10 characters wide+ { wch: 15 }, // Column C: 15 characters wide+];+```++## Merge Cells++```typescript+ws['!merges'] = [+ { s: { r: 0, c: 0 }, e: { r: 0, c: 3 } }, // Merge A1:D1+ // s = start (row, col), e = end (row, col)+ // r = row (0-indexed), c = column (0-indexed)+];+```++## Row Heights++```typescript+ws['!rows'] = [+ { hpt: 30 }, // Row 1: 30 points tall+ { hpt: 20 }, // Row 2: 20 points tall+];+```++## Add Data to Existing Sheet++```typescript+// Append at specific origin+XLSX.utils.sheet_add_aoa(ws, newData, { origin: 'A5' });++// Append at next empty row+const range = XLSX.utils.decode_range(ws['!ref'] || 'A1');+const startRow = range.e.r + 1;+XLSX.utils.sheet_add_aoa(ws, newData, { origin: startRow });+```++## Read Existing Workbook++```typescript+// From file (Node.js)+const wb = XLSX.readFile('input.xlsx');++// From buffer+const wb = XLSX.read(buffer, { type: 'buffer' });++// From base64+const wb = XLSX.read(base64String, { type: 'base64' });+```++## Get Sheet Data++```typescript+// Sheet names+const sheetNames = wb.SheetNames; // ['Sheet1', 'Sheet2']++// Get sheet by name+const ws = wb.Sheets['Sheet1'];++// Convert to JSON+const data = XLSX.utils.sheet_to_json(ws);++// Convert to array of arrays+const aoa = XLSX.utils.sheet_to_json(ws, { header: 1 });++// Convert to CSV+const csv = XLSX.utils.sheet_to_csv(ws);+```++## Export++```typescript+// Node.js - save to file+XLSX.writeFile(wb, 'output.xlsx');++// Get as Buffer (Node.js / Workers)+const buffer = XLSX.write(wb, { type: 'buffer', bookType: 'xlsx' });++// HTTP Response (Cloudflare Workers)+const buffer = XLSX.write(wb, { type: 'buffer', bookType: 'xlsx' });+return new Response(buffer, {+ headers: {+ 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',+ 'Content-Disposition': 'attachment; filename="spreadsheet.xlsx"',+ },+});++// Get as base64 (Browser)+const b64 = XLSX.write(wb, { type: 'base64', bookType: 'xlsx' });++// Get as binary string+const bstr = XLSX.write(wb, { type: 'binary', bookType: 'xlsx' });+```++## Book Types++| Type | Extension | Description |+|------|-----------|-------------|+| `xlsx` | .xlsx | Excel 2007+ XML |+| `xlsm` | .xlsm | Excel with macros |+| `xlsb` | .xlsb | Excel binary |+| `xls` | .xls | Excel 97-2004 |+| `csv` | .csv | Comma-separated |+| `txt` | .txt | Tab-separated |+| `html` | .html | HTML table |++## Cell Reference Utilities++```typescript+// Encode cell address+XLSX.utils.encode_cell({ r: 0, c: 0 }); // 'A1'+XLSX.utils.encode_cell({ r: 1, c: 2 }); // 'C2'++// Decode cell address+XLSX.utils.decode_cell('A1'); // { r: 0, c: 0 }+XLSX.utils.decode_cell('C2'); // { r: 1, c: 2 }++// Encode range+XLSX.utils.encode_range({ s: { r: 0, c: 0 }, e: { r: 5, c: 3 } }); // 'A1:D6'++// Decode range+XLSX.utils.decode_range('A1:D6');+```++## Direct Cell Access++```typescript+// Read cell+const cell = ws['A1'];+console.log(cell.v); // Value+console.log(cell.f); // Formula (if any)++// Write cell directly+ws['E1'] = { v: 'Hello', t: 's' }; // t: 's' = string+ws['E2'] = { v: 42, t: 'n' }; // t: 'n' = number+ws['E3'] = { f: 'SUM(A1:A10)' }; // Formula++// Update range after direct cell access+ws['!ref'] = 'A1:E10'; // Must include all cells+```++## Cell Types++| Type | Code | Description |+|------|------|-------------|+| String | `s` | Text value |+| Number | `n` | Numeric value |+| Boolean | `b` | true/false |+| Date | `d` | Date object |+| Error | `e` | Error value |++## Common Mistakes++| Mistake | Fix |+|---------|-----|+| Formula without quotes in JSON | Use object: `{ f: 'SUM(A:A)' }` |+| Forgetting to update `!ref` | Always update after direct cell access |+| Column index 1-based | Columns are 0-indexed (A=0, B=1) |+| Row index 1-based | Rows are 0-indexed (1=0, 2=1) |diff --git a/skills/office/scripts/verify-deps.sh b/skills/office/scripts/verify-deps.shnew file mode 100755index 00000000..dae94558--- /dev/null+++ b/skills/office/scripts/verify-deps.sh@@ -0,0 +1,100 @@+#!/bin/bash+# Verify document generation library versions+# Usage: ./verify-deps.sh [--install]+#+# Checks latest versions of:+# - docx (Word documents)+# - xlsx (Excel spreadsheets)+# - pdf-lib (PDF generation)++set -e++# Colors for output+RED='\033[0;31m'+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+BLUE='\033[0;34m'+NC='\033[0m' # No Color++echo -e "${BLUE}=== Office Document Libraries Version Check ===${NC}\n"++# Expected minimum versions+DOCX_MIN="9.5.0"+XLSX_MIN="0.18.5"+PDFLIB_MIN="1.17.1"++check_version() {+ local pkg=$1+ local min=$2+ local latest++ latest=$(npm view "$pkg" version 2>/dev/null || echo "unknown")++ if [ "$latest" = "unknown" ]; then+ echo -e "${RED}✗ $pkg: Could not fetch version${NC}"+ return 1+ fi++ echo -e "${GREEN}✓ $pkg${NC}"+ echo " Latest: $latest"+ echo " Minimum: $min"++ # Version comparison (simple check - assumes semver)+ if [ "$(printf '%s\n' "$min" "$latest" | sort -V | head -n1)" = "$min" ]; then+ echo -e " Status: ${GREEN}OK${NC}"+ else+ echo -e " Status: ${YELLOW}Update available${NC}"+ fi+ echo ""+}++echo -e "${YELLOW}Checking npm registry for latest versions...${NC}\n"++# Check each library+check_version "docx" "$DOCX_MIN"+check_version "xlsx" "$XLSX_MIN"+check_version "pdf-lib" "$PDFLIB_MIN"++# Optional: Check if installed in current project+if [ -f "package.json" ]; then+ echo -e "${BLUE}=== Local Installation Check ===${NC}\n"++ for pkg in docx xlsx pdf-lib; do+ installed=$(npm list "$pkg" --depth=0 2>/dev/null | grep "$pkg@" | sed 's/.*@//' || echo "not installed")+ if [ "$installed" != "not installed" ]; then+ echo -e "${GREEN}✓ $pkg@$installed installed${NC}"+ else+ echo -e "${YELLOW}○ $pkg not installed${NC}"+ fi+ done+ echo ""+fi++# Install option+if [ "$1" = "--install" ]; then+ echo -e "${BLUE}=== Installing Libraries ===${NC}\n"++ if command -v pnpm &> /dev/null; then+ echo "Using pnpm..."+ pnpm add docx xlsx pdf-lib+ elif command -v npm &> /dev/null; then+ echo "Using npm..."+ npm install docx xlsx pdf-lib+ else+ echo -e "${RED}No package manager found!${NC}"+ exit 1+ fi++ echo -e "\n${GREEN}✓ Libraries installed${NC}"+fi++echo -e "${BLUE}=== Workers Compatibility ===${NC}\n"+echo "All libraries are compatible with Cloudflare Workers:"+echo " - docx: Pure JavaScript, no Node.js APIs"+echo " - xlsx: Pure JavaScript (use 'xlsx' not 'xlsx-style')"+echo " - pdf-lib: Explicitly supports Workers runtime"+echo ""+echo -e "${GREEN}Documentation:${NC}"+echo " - docx: https://docx.js.org"+echo " - xlsx: https://docs.sheetjs.com"+echo " - pdf-lib: https://pdf-lib.js.org"diff --git a/skills/office/templates/docx-basic.ts b/skills/office/templates/docx-basic.tsnew file mode 100644index 00000000..0b580248--- /dev/null+++ b/skills/office/templates/docx-basic.ts@@ -0,0 +1,305 @@+/**+ * DOCX Basic Template - Word Document Generation+ *+ * Creates a professional document with:+ * - Title and headings+ * - Formatted paragraphs+ * - Tables with styling+ * - Images+ *+ * Works in: Node.js, Cloudflare Workers, Browser+ *+ * Usage:+ * npm install docx+ * npx tsx docx-basic.ts+ */++import {+ Document,+ Packer,+ Paragraph,+ TextRun,+ Table,+ TableRow,+ TableCell,+ WidthType,+ HeadingLevel,+ AlignmentType,+ BorderStyle,+ ImageRun,+} from 'docx';+import { writeFileSync, readFileSync } from 'fs';++// =============================================================================+// DOCUMENT CREATION+// =============================================================================++async function createDocument() {+ const doc = new Document({+ // Document metadata+ creator: 'Your Company',+ title: 'Sample Report',+ description: 'A sample document created with docx',++ sections: [+ {+ children: [+ // ---------------------------------------------------------------------+ // TITLE+ // ---------------------------------------------------------------------+ new Paragraph({+ text: 'Monthly Sales Report',+ heading: HeadingLevel.TITLE,+ alignment: AlignmentType.CENTER,+ }),++ new Paragraph({+ children: [+ new TextRun({+ text: 'January 2026',+ italics: true,+ color: '666666',+ }),+ ],+ alignment: AlignmentType.CENTER,+ }),++ // Spacer+ new Paragraph({ text: '' }),++ // ---------------------------------------------------------------------+ // HEADING 1+ // ---------------------------------------------------------------------+ new Paragraph({+ text: 'Executive Summary',+ heading: HeadingLevel.HEADING_1,+ }),++ // ---------------------------------------------------------------------+ // FORMATTED PARAGRAPHS+ // ---------------------------------------------------------------------+ new Paragraph({+ children: [+ new TextRun('This report summarizes the sales performance for '),+ new TextRun({ text: 'January 2026', bold: true }),+ new TextRun('. Overall, we achieved '),+ new TextRun({ text: '115%', bold: true, color: '00AA00' }),+ new TextRun(' of our monthly target.'),+ ],+ }),++ new Paragraph({+ children: [+ new TextRun({+ text: 'Key highlights include:',+ italics: true,+ }),+ ],+ }),++ // Bullet points (using simple paragraphs with bullet character)+ new Paragraph({+ text: '• Revenue increased by 23% compared to last month',+ indent: { left: 720 }, // 720 twips = 0.5 inch+ }),+ new Paragraph({+ text: '• New customer acquisitions up 18%',+ indent: { left: 720 },+ }),+ new Paragraph({+ text: '• Customer retention rate at 94%',+ indent: { left: 720 },+ }),++ // Spacer+ new Paragraph({ text: '' }),++ // ---------------------------------------------------------------------+ // HEADING 2+ // ---------------------------------------------------------------------+ new Paragraph({+ text: 'Sales by Region',+ heading: HeadingLevel.HEADING_2,+ }),++ // ---------------------------------------------------------------------+ // TABLE+ // ---------------------------------------------------------------------+ createSalesTable(),++ // Spacer+ new Paragraph({ text: '' }),++ // ---------------------------------------------------------------------+ // HEADING 2+ // ---------------------------------------------------------------------+ new Paragraph({+ text: 'Conclusion',+ heading: HeadingLevel.HEADING_2,+ }),++ new Paragraph({+ children: [+ new TextRun(+ 'The strong performance this month positions us well for Q1 targets. '+ ),+ new TextRun({+ text: 'Recommended actions',+ bold: true,+ }),+ new TextRun(+ ' include increasing marketing spend in the APAC region and expanding the sales team in EMEA.'+ ),+ ],+ }),++ // ---------------------------------------------------------------------+ // FOOTER NOTE+ // ---------------------------------------------------------------------+ new Paragraph({ text: '' }),+ new Paragraph({+ children: [+ new TextRun({+ text: 'Report generated automatically on ' ++ new Date().toISOString().split('T')[0],+ size: 20, // 10pt (size is in half-points)+ color: '999999',+ }),+ ],+ alignment: AlignmentType.RIGHT,+ }),+ ],+ },+ ],+ });++ return doc;+}++// =============================================================================+// TABLE HELPER+// =============================================================================++function createSalesTable(): Table {+ const data = [+ ['Region', 'Target', 'Actual', 'Variance'],+ ['North America', '$500,000', '$575,000', '+15%'],+ ['EMEA', '$300,000', '$342,000', '+14%'],+ ['APAC', '$200,000', '$178,000', '-11%'],+ ['LATAM', '$100,000', '$121,000', '+21%'],+ ['Total', '$1,100,000', '$1,216,000', '+10.5%'],+ ];++ return new Table({+ width: { size: 100, type: WidthType.PERCENTAGE },+ rows: data.map((row, rowIndex) =>+ new TableRow({+ children: row.map(+ (cell, cellIndex) =>+ new TableCell({+ children: [+ new Paragraph({+ children: [+ new TextRun({+ text: cell,+ bold: rowIndex === 0 || rowIndex === data.length - 1,+ color:+ cellIndex === 3 && rowIndex > 0+ ? cell.startsWith('+')+ ? '00AA00'+ : 'CC0000'+ : '000000',+ }),+ ],+ alignment:+ cellIndex === 0 ? AlignmentType.LEFT : AlignmentType.RIGHT,+ }),+ ],+ borders: {+ top: { style: BorderStyle.SINGLE, size: 1, color: 'CCCCCC' },+ bottom: { style: BorderStyle.SINGLE, size: 1, color: 'CCCCCC' },+ left: { style: BorderStyle.SINGLE, size: 1, color: 'CCCCCC' },+ right: { style: BorderStyle.SINGLE, size: 1, color: 'CCCCCC' },+ },+ shading:+ rowIndex === 0+ ? { fill: 'F0F0F0' }+ : rowIndex === data.length - 1+ ? { fill: 'E8F4E8' }+ : undefined,+ })+ ),+ })+ ),+ });+}++// =============================================================================+// IMAGE HELPER (uncomment if you have an image)+// =============================================================================++// function createImageParagraph(imagePath: string): Paragraph {+// const imageBuffer = readFileSync(imagePath);+// return new Paragraph({+// children: [+// new ImageRun({+// data: imageBuffer,+// transformation: { width: 200, height: 100 },+// type: 'png', // or 'jpg'+// }),+// ],+// });+// }++// =============================================================================+// EXPORT FUNCTIONS+// =============================================================================++/**+ * Save to file (Node.js only)+ */+async function saveToFile(doc: Document, filename: string) {+ const buffer = await Packer.toBuffer(doc);+ writeFileSync(filename, buffer);+ console.log(`✅ Saved: ${filename}`);+}++/**+ * Get as Response (Cloudflare Workers)+ */+async function toResponse(doc: Document, filename: string): Promise<Response> {+ const buffer = await Packer.toBuffer(doc);+ return new Response(buffer, {+ headers: {+ 'Content-Type':+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',+ 'Content-Disposition': `attachment; filename="${filename}"`,+ },+ });+}++/**+ * Get as Blob (Browser)+ */+async function toBlob(doc: Document): Promise<Blob> {+ return await Packer.toBlob(doc);+}++// =============================================================================+// MAIN+// =============================================================================++async function main() {+ console.log('Creating Word document...');++ const doc = await createDocument();+ await saveToFile(doc, 'report.docx');++ console.log('Done! Open report.docx to view.');+}++// Run if executed directly+main().catch(console.error);++// Export for use as module+export { createDocument, saveToFile, toResponse, toBlob };diff --git a/skills/office/templates/pdf-basic.ts b/skills/office/templates/pdf-basic.tsnew file mode 100644index 00000000..2186f1a2--- /dev/null+++ b/skills/office/templates/pdf-basic.ts@@ -0,0 +1,370 @@+/**+ * PDF Basic Template - PDF Generation+ *+ * Creates a PDF with:+ * - Text with custom fonts+ * - Images+ * - Shapes and lines+ * - Multiple pages+ *+ * Works in: Node.js, Cloudflare Workers, Browser+ *+ * Usage:+ * npm install pdf-lib+ * npx tsx pdf-basic.ts+ */++import { PDFDocument, StandardFonts, rgb, PageSizes } from 'pdf-lib';+import { writeFileSync, readFileSync } from 'fs';++// =============================================================================+// CONSTANTS+// =============================================================================++// Common page sizes (width x height in points, 72 points = 1 inch)+const PAGE_SIZES = {+ LETTER: PageSizes.Letter, // [612, 792] - 8.5" x 11"+ A4: PageSizes.A4, // [595.28, 841.89] - 210mm x 297mm+ LEGAL: [612, 1008] as [number, number], // 8.5" x 14"+};++// Colors+const COLORS = {+ black: rgb(0, 0, 0),+ white: rgb(1, 1, 1),+ gray: rgb(0.5, 0.5, 0.5),+ lightGray: rgb(0.9, 0.9, 0.9),+ primary: rgb(0.2, 0.4, 0.8), // Blue+ success: rgb(0.2, 0.6, 0.2), // Green+ danger: rgb(0.8, 0.2, 0.2), // Red+};++// =============================================================================+// DOCUMENT CREATION+// =============================================================================++async function createDocument(): Promise<PDFDocument> {+ const pdfDoc = await PDFDocument.create();++ // Set document metadata+ pdfDoc.setTitle('Monthly Report');+ pdfDoc.setAuthor('Your Company');+ pdfDoc.setSubject('Sales Report for January 2026');+ pdfDoc.setCreationDate(new Date());++ // Embed fonts+ const helvetica = await pdfDoc.embedFont(StandardFonts.Helvetica);+ const helveticaBold = await pdfDoc.embedFont(StandardFonts.HelveticaBold);++ // -------------------------------------------------------------------------+ // PAGE 1: Title Page+ // -------------------------------------------------------------------------+ const page1 = pdfDoc.addPage(PAGE_SIZES.LETTER);+ const { width, height } = page1.getSize();++ // Header bar+ page1.drawRectangle({+ x: 0,+ y: height - 100,+ width: width,+ height: 100,+ color: COLORS.primary,+ });++ // Title+ page1.drawText('Monthly Sales Report', {+ x: 50,+ y: height - 60,+ size: 28,+ font: helveticaBold,+ color: COLORS.white,+ });++ // Subtitle+ page1.drawText('January 2026', {+ x: 50,+ y: height - 85,+ size: 14,+ font: helvetica,+ color: rgb(0.8, 0.9, 1),+ });++ // Main content area+ const contentY = height - 150;++ page1.drawText('Executive Summary', {+ x: 50,+ y: contentY,+ size: 18,+ font: helveticaBold,+ color: COLORS.black,+ });++ // Horizontal line+ page1.drawLine({+ start: { x: 50, y: contentY - 10 },+ end: { x: width - 50, y: contentY - 10 },+ thickness: 1,+ color: COLORS.lightGray,+ });++ // Body text+ const bodyText = [+ 'This report summarizes the sales performance for January 2026.',+ 'Overall, we achieved 115% of our monthly target.',+ '',+ 'Key Highlights:',+ '• Revenue increased by 23% compared to last month',+ '• New customer acquisitions up 18%',+ '• Customer retention rate at 94%',+ ];++ let textY = contentY - 40;+ for (const line of bodyText) {+ page1.drawText(line, {+ x: 50,+ y: textY,+ size: 12,+ font: helvetica,+ color: COLORS.black,+ });+ textY -= 20;+ }++ // Stats boxes+ const statsY = textY - 40;+ const boxWidth = 150;+ const boxHeight = 80;+ const stats = [+ { label: 'Revenue', value: '$1.2M', color: COLORS.success },+ { label: 'Growth', value: '+23%', color: COLORS.primary },+ { label: 'Customers', value: '1,245', color: COLORS.primary },+ ];++ stats.forEach((stat, i) => {+ const boxX = 50 + i * (boxWidth + 20);++ // Box background+ page1.drawRectangle({+ x: boxX,+ y: statsY,+ width: boxWidth,+ height: boxHeight,+ color: COLORS.lightGray,+ borderColor: stat.color,+ borderWidth: 2,+ });++ // Value+ page1.drawText(stat.value, {+ x: boxX + 15,+ y: statsY + 45,+ size: 24,+ font: helveticaBold,+ color: stat.color,+ });++ // Label+ page1.drawText(stat.label, {+ x: boxX + 15,+ y: statsY + 15,+ size: 12,+ font: helvetica,+ color: COLORS.gray,+ });+ });++ // Footer+ page1.drawText('Confidential - Internal Use Only', {+ x: 50,+ y: 30,+ size: 10,+ font: helvetica,+ color: COLORS.gray,+ });++ page1.drawText('Page 1 of 2', {+ x: width - 100,+ y: 30,+ size: 10,+ font: helvetica,+ color: COLORS.gray,+ });++ // -------------------------------------------------------------------------+ // PAGE 2: Data Table+ // -------------------------------------------------------------------------+ const page2 = pdfDoc.addPage(PAGE_SIZES.LETTER);++ page2.drawText('Sales by Region', {+ x: 50,+ y: height - 50,+ size: 18,+ font: helveticaBold,+ color: COLORS.black,+ });++ // Table+ const tableData = [+ ['Region', 'Target', 'Actual', 'Variance'],+ ['North America', '$500,000', '$575,000', '+15%'],+ ['EMEA', '$300,000', '$342,000', '+14%'],+ ['APAC', '$200,000', '$178,000', '-11%'],+ ['LATAM', '$100,000', '$121,000', '+21%'],+ ];++ const tableX = 50;+ let tableY = height - 100;+ const colWidths = [150, 100, 100, 100];+ const rowHeight = 25;++ tableData.forEach((row, rowIndex) => {+ let cellX = tableX;++ // Row background+ if (rowIndex === 0) {+ page2.drawRectangle({+ x: tableX,+ y: tableY - 5,+ width: colWidths.reduce((a, b) => a + b, 0),+ height: rowHeight,+ color: COLORS.primary,+ });+ }++ row.forEach((cell, colIndex) => {+ const textColor =+ rowIndex === 0+ ? COLORS.white+ : colIndex === 3+ ? cell.startsWith('+')+ ? COLORS.success+ : COLORS.danger+ : COLORS.black;++ page2.drawText(cell, {+ x: cellX + 5,+ y: tableY,+ size: 11,+ font: rowIndex === 0 ? helveticaBold : helvetica,+ color: textColor,+ });++ cellX += colWidths[colIndex];+ });++ tableY -= rowHeight;+ });++ // Footer+ page2.drawText('Page 2 of 2', {+ x: width - 100,+ y: 30,+ size: 10,+ font: helvetica,+ color: COLORS.gray,+ });++ return pdfDoc;+}++// =============================================================================+// EXPORT FUNCTIONS+// =============================================================================++/**+ * Save to file (Node.js only)+ */+async function saveToFile(pdfDoc: PDFDocument, filename: string) {+ const pdfBytes = await pdfDoc.save();+ writeFileSync(filename, pdfBytes);+ console.log(`✅ Saved: ${filename}`);+}++/**+ * Get as Uint8Array (all environments)+ */+async function toBytes(pdfDoc: PDFDocument): Promise<Uint8Array> {+ return await pdfDoc.save();+}++/**+ * Get as Response (Cloudflare Workers)+ */+async function toResponse(+ pdfDoc: PDFDocument,+ filename: string+): Promise<Response> {+ const pdfBytes = await pdfDoc.save();+ return new Response(pdfBytes, {+ headers: {+ 'Content-Type': 'application/pdf',+ 'Content-Disposition': `attachment; filename="${filename}"`,+ },+ });+}++/**+ * Get as base64 (Browser)+ */+async function toBase64(pdfDoc: PDFDocument): Promise<string> {+ const pdfBytes = await pdfDoc.save();+ // Convert Uint8Array to base64+ let binary = '';+ for (let i = 0; i < pdfBytes.length; i++) {+ binary += String.fromCharCode(pdfBytes[i]);+ }+ return btoa(binary);+}++// =============================================================================+// UTILITY: Add image to PDF+// =============================================================================++async function addImageToPdf(+ pdfDoc: PDFDocument,+ pageIndex: number,+ imageBytes: Uint8Array,+ options: { x: number; y: number; width: number; height: number; type: 'png' | 'jpg' }+) {+ const page = pdfDoc.getPage(pageIndex);+ const image =+ options.type === 'png'+ ? await pdfDoc.embedPng(imageBytes)+ : await pdfDoc.embedJpg(imageBytes);++ page.drawImage(image, {+ x: options.x,+ y: options.y,+ width: options.width,+ height: options.height,+ });+}++// =============================================================================+// MAIN+// =============================================================================++async function main() {+ console.log('Creating PDF document...');++ const pdfDoc = await createDocument();+ await saveToFile(pdfDoc, 'report.pdf');++ console.log('Done! Open report.pdf to view.');+}++// Run if executed directly+main().catch(console.error);++// Export for use as module+export {+ createDocument,+ saveToFile,+ toBytes,+ toResponse,+ toBase64,+ addImageToPdf,+ PAGE_SIZES,+ COLORS,+};diff --git a/skills/office/templates/workers-pdf.ts b/skills/office/templates/workers-pdf.tsnew file mode 100644index 00000000..f2b78400--- /dev/null+++ b/skills/office/templates/workers-pdf.ts@@ -0,0 +1,389 @@+/**+ * Cloudflare Workers PDF Generation+ *+ * Two approaches:+ * 1. pdf-lib: Programmatic PDF creation (included below)+ * 2. Browser Rendering: HTML→PDF with full CSS (requires paid plan)+ *+ * Usage:+ * wrangler dev+ * curl http://localhost:8787/invoice/123 > invoice.pdf+ */++import { Hono } from 'hono';+import { PDFDocument, StandardFonts, rgb } from 'pdf-lib';++// =============================================================================+// TYPES+// =============================================================================++interface Env {+ // For Browser Rendering (optional, paid feature)+ BROWSER?: Fetcher;+}++interface InvoiceData {+ invoiceNumber: string;+ date: string;+ customerName: string;+ customerEmail: string;+ items: Array<{+ description: string;+ quantity: number;+ unitPrice: number;+ }>;+}++// =============================================================================+// APP SETUP+// =============================================================================++const app = new Hono<{ Bindings: Env }>();++// =============================================================================+// ROUTE 1: Generate Invoice PDF with pdf-lib+// =============================================================================++app.get('/invoice/:id', async (c) => {+ const invoiceId = c.req.param('id');++ // In production, fetch this from your database+ const invoiceData: InvoiceData = {+ invoiceNumber: `INV-${invoiceId}`,+ date: new Date().toISOString().split('T')[0],+ customerName: 'Acme Corporation',+ customerEmail: '[email protected]',+ items: [+ { description: 'Web Development Services', quantity: 40, unitPrice: 150 },+ { description: 'UI/UX Design', quantity: 20, unitPrice: 125 },+ { description: 'Hosting (Annual)', quantity: 1, unitPrice: 500 },+ ],+ };++ const pdfBytes = await generateInvoicePdf(invoiceData);++ return new Response(pdfBytes, {+ headers: {+ 'Content-Type': 'application/pdf',+ 'Content-Disposition': `attachment; filename="${invoiceData.invoiceNumber}.pdf"`,+ },+ });+});++// =============================================================================+// ROUTE 2: HTML to PDF with Browser Rendering (requires binding)+// =============================================================================++app.get('/report/:id', async (c) => {+ const reportId = c.req.param('id');++ // Check if Browser Rendering is available+ if (!c.env.BROWSER) {+ return c.json(+ {+ error: 'Browser Rendering not configured',+ hint: 'Add browser binding to wrangler.jsonc',+ },+ 501+ );+ }++ // For Browser Rendering, you'd use Puppeteer:+ // const puppeteer = await import('@cloudflare/puppeteer');+ // const browser = await puppeteer.launch(c.env.BROWSER);+ // const page = await browser.newPage();+ // await page.setContent(htmlContent);+ // const pdf = await page.pdf({ format: 'A4' });+ // await browser.close();++ // Placeholder response+ return c.json({+ message: 'Browser Rendering endpoint',+ reportId,+ note: 'Implement with @cloudflare/puppeteer for HTML→PDF',+ });+});++// =============================================================================+// PDF GENERATION FUNCTION+// =============================================================================++async function generateInvoicePdf(data: InvoiceData): Promise<Uint8Array> {+ const pdfDoc = await PDFDocument.create();+ const page = pdfDoc.addPage([612, 792]); // Letter size+ const { width, height } = page.getSize();++ // Fonts+ const helvetica = await pdfDoc.embedFont(StandardFonts.Helvetica);+ const helveticaBold = await pdfDoc.embedFont(StandardFonts.HelveticaBold);++ // Colors+ const black = rgb(0, 0, 0);+ const gray = rgb(0.5, 0.5, 0.5);+ const primary = rgb(0.2, 0.4, 0.8);++ // -------------------------------------------------------------------------+ // HEADER+ // -------------------------------------------------------------------------++ // Company name+ page.drawText('Your Company Name', {+ x: 50,+ y: height - 50,+ size: 20,+ font: helveticaBold,+ color: primary,+ });++ // Invoice label+ page.drawText('INVOICE', {+ x: width - 150,+ y: height - 50,+ size: 24,+ font: helveticaBold,+ color: black,+ });++ // Invoice details+ page.drawText(`Invoice #: ${data.invoiceNumber}`, {+ x: width - 150,+ y: height - 75,+ size: 10,+ font: helvetica,+ color: gray,+ });++ page.drawText(`Date: ${data.date}`, {+ x: width - 150,+ y: height - 90,+ size: 10,+ font: helvetica,+ color: gray,+ });++ // -------------------------------------------------------------------------+ // CUSTOMER INFO+ // -------------------------------------------------------------------------++ page.drawText('Bill To:', {+ x: 50,+ y: height - 120,+ size: 10,+ font: helveticaBold,+ color: gray,+ });++ page.drawText(data.customerName, {+ x: 50,+ y: height - 135,+ size: 12,+ font: helvetica,+ color: black,+ });++ page.drawText(data.customerEmail, {+ x: 50,+ y: height - 150,+ size: 10,+ font: helvetica,+ color: gray,+ });++ // -------------------------------------------------------------------------+ // TABLE HEADER+ // -------------------------------------------------------------------------++ const tableTop = height - 200;+ const colWidths = [250, 80, 100, 100];+ const cols = ['Description', 'Qty', 'Unit Price', 'Amount'];++ // Header background+ page.drawRectangle({+ x: 50,+ y: tableTop - 5,+ width: width - 100,+ height: 25,+ color: rgb(0.95, 0.95, 0.95),+ });++ // Header text+ let colX = 50;+ cols.forEach((col, i) => {+ page.drawText(col, {+ x: colX + 5,+ y: tableTop,+ size: 10,+ font: helveticaBold,+ color: black,+ });+ colX += colWidths[i];+ });++ // -------------------------------------------------------------------------+ // TABLE ROWS+ // -------------------------------------------------------------------------++ let rowY = tableTop - 30;+ let subtotal = 0;++ for (const item of data.items) {+ const amount = item.quantity * item.unitPrice;+ subtotal += amount;++ colX = 50;++ // Description+ page.drawText(item.description, {+ x: colX + 5,+ y: rowY,+ size: 10,+ font: helvetica,+ color: black,+ });+ colX += colWidths[0];++ // Quantity+ page.drawText(item.quantity.toString(), {+ x: colX + 5,+ y: rowY,+ size: 10,+ font: helvetica,+ color: black,+ });+ colX += colWidths[1];++ // Unit Price+ page.drawText(`$${item.unitPrice.toFixed(2)}`, {+ x: colX + 5,+ y: rowY,+ size: 10,+ font: helvetica,+ color: black,+ });+ colX += colWidths[2];++ // Amount+ page.drawText(`$${amount.toFixed(2)}`, {+ x: colX + 5,+ y: rowY,+ size: 10,+ font: helvetica,+ color: black,+ });++ rowY -= 25;+ }++ // -------------------------------------------------------------------------+ // TOTALS+ // -------------------------------------------------------------------------++ const tax = subtotal * 0.1; // 10% tax+ const total = subtotal + tax;++ rowY -= 20;++ // Line+ page.drawLine({+ start: { x: width - 250, y: rowY + 15 },+ end: { x: width - 50, y: rowY + 15 },+ thickness: 1,+ color: rgb(0.8, 0.8, 0.8),+ });++ // Subtotal+ page.drawText('Subtotal:', {+ x: width - 200,+ y: rowY,+ size: 10,+ font: helvetica,+ color: gray,+ });+ page.drawText(`$${subtotal.toFixed(2)}`, {+ x: width - 100,+ y: rowY,+ size: 10,+ font: helvetica,+ color: black,+ });++ rowY -= 20;++ // Tax+ page.drawText('Tax (10%):', {+ x: width - 200,+ y: rowY,+ size: 10,+ font: helvetica,+ color: gray,+ });+ page.drawText(`$${tax.toFixed(2)}`, {+ x: width - 100,+ y: rowY,+ size: 10,+ font: helvetica,+ color: black,+ });++ rowY -= 25;++ // Total+ page.drawText('Total:', {+ x: width - 200,+ y: rowY,+ size: 14,+ font: helveticaBold,+ color: black,+ });+ page.drawText(`$${total.toFixed(2)}`, {+ x: width - 100,+ y: rowY,+ size: 14,+ font: helveticaBold,+ color: primary,+ });++ // -------------------------------------------------------------------------+ // FOOTER+ // -------------------------------------------------------------------------++ page.drawText('Thank you for your business!', {+ x: 50,+ y: 80,+ size: 12,+ font: helvetica,+ color: gray,+ });++ page.drawText('Payment due within 30 days.', {+ x: 50,+ y: 60,+ size: 10,+ font: helvetica,+ color: gray,+ });++ return await pdfDoc.save();+}++// =============================================================================+// EXPORT+// =============================================================================++export default app;++/**+ * wrangler.jsonc configuration:+ *+ * {+ * "name": "invoice-generator",+ * "main": "src/index.ts",+ * "compatibility_date": "2024-01-01",+ * "compatibility_flags": ["nodejs_compat"],+ *+ * // Optional: For HTML→PDF with Browser Rendering (paid feature)+ * "browser": {+ * "binding": "BROWSER"+ * }+ * }+ */diff --git a/skills/office/templates/xlsx-basic.ts b/skills/office/templates/xlsx-basic.tsnew file mode 100644index 00000000..07a5a43e--- /dev/null+++ b/skills/office/templates/xlsx-basic.ts@@ -0,0 +1,206 @@+/**+ * XLSX Basic Template - Excel Spreadsheet Generation+ *+ * Creates a workbook with:+ * - Multiple sheets+ * - Data from arrays and JSON+ * - Formulas+ * - Column widths+ *+ * Works in: Node.js, Cloudflare Workers, Browser+ *+ * Usage:+ * npm install xlsx+ * npx tsx xlsx-basic.ts+ */++import * as XLSX from 'xlsx';+import { writeFileSync } from 'fs';++// =============================================================================+// WORKBOOK CREATION+// =============================================================================++function createWorkbook(): XLSX.WorkBook {+ const wb = XLSX.utils.book_new();++ // -------------------------------------------------------------------------+ // SHEET 1: Summary (from array of arrays)+ // -------------------------------------------------------------------------+ const summaryData = [+ ['Monthly Sales Summary'],+ [''],+ ['Metric', 'Value'],+ ['Total Revenue', { f: 'Details!D7' }], // Formula referencing other sheet+ ['Total Units', { f: 'Details!C7' }],+ ['Average Price', { f: 'Details!D7/Details!C7' }],+ [''],+ ['Report Date', new Date().toISOString().split('T')[0]],+ ];++ const summarySheet = XLSX.utils.aoa_to_sheet(summaryData);++ // Set column widths+ summarySheet['!cols'] = [+ { wch: 20 }, // Column A+ { wch: 15 }, // Column B+ ];++ // Merge cells for title (A1:B1)+ summarySheet['!merges'] = [{ s: { r: 0, c: 0 }, e: { r: 0, c: 1 } }];++ XLSX.utils.book_append_sheet(wb, summarySheet, 'Summary');++ // -------------------------------------------------------------------------+ // SHEET 2: Details (from array of arrays with formulas)+ // -------------------------------------------------------------------------+ const detailsData = [+ ['Product', 'Category', 'Units Sold', 'Revenue'],+ ['Widget A', 'Electronics', 150, 4500],+ ['Widget B', 'Electronics', 200, 5000],+ ['Gadget X', 'Accessories', 75, 1875],+ ['Gadget Y', 'Accessories', 120, 2400],+ ['Service Z', 'Services', 50, 2500],+ ['TOTAL', '', { f: 'SUM(C2:C6)' }, { f: 'SUM(D2:D6)' }],+ ];++ const detailsSheet = XLSX.utils.aoa_to_sheet(detailsData);++ // Set column widths+ detailsSheet['!cols'] = [+ { wch: 15 }, // Product+ { wch: 15 }, // Category+ { wch: 12 }, // Units+ { wch: 12 }, // Revenue+ ];++ XLSX.utils.book_append_sheet(wb, detailsSheet, 'Details');++ // -------------------------------------------------------------------------+ // SHEET 3: From JSON data+ // -------------------------------------------------------------------------+ const jsonData = [+ { id: 1, name: 'Alice', department: 'Sales', salary: 75000 },+ { id: 2, name: 'Bob', department: 'Engineering', salary: 95000 },+ { id: 3, name: 'Carol', department: 'Marketing', salary: 70000 },+ { id: 4, name: 'David', department: 'Engineering', salary: 90000 },+ { id: 5, name: 'Eve', department: 'Sales', salary: 72000 },+ ];++ const employeesSheet = XLSX.utils.json_to_sheet(jsonData);++ // Set column widths+ employeesSheet['!cols'] = [+ { wch: 5 }, // id+ { wch: 15 }, // name+ { wch: 15 }, // department+ { wch: 12 }, // salary+ ];++ XLSX.utils.book_append_sheet(wb, employeesSheet, 'Employees');++ return wb;+}++// =============================================================================+// EXPORT FUNCTIONS+// =============================================================================++/**+ * Save to file (Node.js only)+ */+function saveToFile(wb: XLSX.WorkBook, filename: string) {+ XLSX.writeFile(wb, filename);+ console.log(`✅ Saved: ${filename}`);+}++/**+ * Get as Buffer (Cloudflare Workers / Node.js)+ */+function toBuffer(wb: XLSX.WorkBook): Buffer {+ return XLSX.write(wb, { type: 'buffer', bookType: 'xlsx' }) as Buffer;+}++/**+ * Get as Response (Cloudflare Workers)+ */+function toResponse(wb: XLSX.WorkBook, filename: string): Response {+ const buffer = toBuffer(wb);+ return new Response(buffer, {+ headers: {+ 'Content-Type':+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',+ 'Content-Disposition': `attachment; filename="${filename}"`,+ },+ });+}++/**+ * Get as base64 (Browser download)+ */+function toBase64(wb: XLSX.WorkBook): string {+ return XLSX.write(wb, { type: 'base64', bookType: 'xlsx' });+}++// =============================================================================+// UTILITY: Add data to existing sheet+// =============================================================================++function appendDataToSheet(+ wb: XLSX.WorkBook,+ sheetName: string,+ newData: unknown[][]+) {+ const ws = wb.Sheets[sheetName];+ if (!ws) throw new Error(`Sheet "${sheetName}" not found`);++ // Find the next empty row+ const range = XLSX.utils.decode_range(ws['!ref'] || 'A1');+ const startRow = range.e.r + 1;++ // Add new data+ XLSX.utils.sheet_add_aoa(ws, newData, { origin: startRow });+}++// =============================================================================+// UTILITY: Read existing workbook+// =============================================================================++function readWorkbook(filename: string): XLSX.WorkBook {+ return XLSX.readFile(filename);+}++function sheetToJson<T>(wb: XLSX.WorkBook, sheetName: string): T[] {+ const ws = wb.Sheets[sheetName];+ if (!ws) throw new Error(`Sheet "${sheetName}" not found`);+ return XLSX.utils.sheet_to_json(ws);+}++// =============================================================================+// MAIN+// =============================================================================++function main() {+ console.log('Creating Excel workbook...');++ const wb = createWorkbook();+ saveToFile(wb, 'report.xlsx');++ console.log('Done! Open report.xlsx to view.');+ console.log('Note: Formulas will calculate when opened in Excel.');+}++// Run if executed directly+main();++// Export for use as module+export {+ createWorkbook,+ saveToFile,+ toBuffer,+ toResponse,+ toBase64,+ appendDataToSheet,+ readWorkbook,+ sheetToJson,+};