### ZipHandler - Extract PPTX Archive & Parse XML Source: https://context7.com/airpptx/airppt-parser/llms.txt Demonstrates loading a PPTX file using ZipHandler, parsing presentation-level XML attributes, retrieving theme information, accessing slide data and relationships, and extracting embedded media files as base64. Used for advanced file operations beyond the main parser API. ```javascript const ZipHandler = require("airppt-parser/js/helpers/ziphandler").default; const fs = require("fs"); async function extractPresentationData() { try { await ZipHandler.loadZip("./presentation.pptx"); const presentation = await ZipHandler.parseSlideAttributes("ppt/presentation.xml"); console.log("Slide count:", presentation["p:presentation"]["p:sldIdLst"][0]["p:sldId"].length); const theme = await ZipHandler.parseSlideAttributes("ppt/theme/theme1.xml"); const colorScheme = theme["a:theme"]["a:themeElements"][0]["a:clrScheme"][0]; console.log("Theme colors:", Object.keys(colorScheme)); const slide1 = await ZipHandler.parseSlideAttributes("ppt/slides/slide1.xml"); const slideRelations = await ZipHandler.parseSlideAttributes("ppt/slides/_rels/slide1.xml.rels"); const imageBase64 = await ZipHandler.getFileInZip("ppt/media/image1.png"); const imageBuffer = Buffer.from(imageBase64, 'base64'); fs.writeFileSync("extracted-image.png", imageBuffer); console.log("Extraction complete"); } catch (error) { console.error("Failed to extract data:", error); } } extractPresentationData(); ``` -------------------------------- ### Parse PowerPoint PPTX File with AirParser Class Source: https://context7.com/airpptx/airppt-parser/llms.txt Demonstrates how to initialize the AirParser class with a PPTX file path and use the ParsePowerPoint method to extract slide data. The method returns structured data including global presentation settings, theme information, and parsed PowerPoint elements. Error handling is included for failed parsing operations. ```javascript const { AirParser } = require("airppt-parser"); // Initialize parser with PPTX file path const pptParser = new AirParser("./presentation.pptx"); // Parse a specific slide (slide numbers start at 1) async function parseSlide() { try { const result = await pptParser.ParsePowerPoint(1); // Result structure console.log({ slideShowGlobals: result.slideShowGlobals, // Global presentation settings slideShowTheme: result.slideShowTheme, // Theme colors and styles powerPointElements: result.powerPointElements, // Array of parsed elements inputPath: result.inputPath // Original file path }); // Access individual elements result.powerPointElements.forEach(element => { console.log(`Element: ${element.name}`); console.log(`Type: ${element.shapeType}`); console.log(`Position: x=${element.elementPosition.x}, y=${element.elementPosition.y}`); if (element.paragraph) { console.log(`Text: ${element.paragraph.text}`); } }); return result; } catch (error) { console.error("Failed to parse PowerPoint:", error); throw error; } } parseSlide(); ``` -------------------------------- ### Process PowerpointElement - Convert Units & Extract Properties Source: https://context7.com/airpptx/airppt-parser/llms.txt Demonstrates how to access and transform PowerpointElement data, including converting EMU (English Metric Units) coordinates to pixels, parsing font sizes from hundredths of points, and extracting text styling attributes like bold formatting. ```javascript function processElement(element) { const pixelX = element.elementPosition.x / 914400 * 96; const pixelY = element.elementPosition.y / 914400 * 96; const pixelWidth = element.elementOffsetPosition.cx / 914400 * 96; const pixelHeight = element.elementOffsetPosition.cy / 914400 * 96; const fontSize = element.paragraph?.textCharacterProperties?.size / 100; const isBold = element.paragraph?.textCharacterProperties?.fontAttributes?.includes("Bold"); return { position: { x: pixelX, y: pixelY }, dimensions: { width: pixelWidth, height: pixelHeight }, text: element.paragraph?.text, fontSize: fontSize, bold: isBold, backgroundColor: `#${element.shape?.fill?.fillColor}` }; } ``` -------------------------------- ### Resolve Colors and Fills with ColorParser (JavaScript) Source: https://context7.com/airpptx/airppt-parser/llms.txt Resolves colors from various sources including solid RGB colors, theme colors, and image fills. It handles opacity values and translates PowerPoint's color scheme references to actual hex values. Requires a theme object for proper color resolution. ```javascript const ColorParser = require("airppt-parser/js/parsers/colorparser").default; // Color handling example function analyzeColors(elements, theme) { // Set theme for color resolution ColorParser.setSlideShowTheme(theme); elements.forEach(element => { const shape = element.shape; // Fill type and color if (shape.fill.fillType === "Solid") { const rgb = hexToRgb(shape.fill.fillColor); console.log(`Fill: RGB(${rgb.r}, ${rgb.g}, ${rgb.b})`); // Apply opacity const alpha = shape.opacity; if (alpha < 1) { console.log(`Opacity: ${(alpha * 100).toFixed(0)}%`); console.log(`RGBA: rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${alpha})`); } } else if (shape.fill.fillType === "Image") { console.log(`Fill: Image (${shape.fill.fillColor})`); } // Border color if (shape.border) { console.log(`Border: #${shape.border.color}`); } // Text color if (element.paragraph?.textCharacterProperties) { const textColor = element.paragraph.textCharacterProperties.fillColor; console.log(`Text: #${textColor}`); } }); } function hexToRgb(hex) { const result = /^([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; } ``` -------------------------------- ### Process PowerPoint Slide Elements with JavaScript Source: https://context7.com/airpptx/airppt-parser/llms.txt This snippet demonstrates how to use the PowerpointElementParser to load a PPTX file, parse slide elements (shapes and images), and convert them into PowerpointElement objects. It relies on ZipHandler for file operations and AirPPT-parser for parsing logic. Outputs parsed element details to the console. ```javascript const PowerpointElementParser = require("airppt-parser/js/parsers/elementparser").default; const ZipHandler = require("airppt-parser/js/helpers/ziphandler").default; async function parseSlideElements() { // Load PPTX and get global data await ZipHandler.loadZip("./presentation.pptx"); const globals = await ZipHandler.parseSlideAttributes("ppt/presentation.xml"); const theme = await ZipHandler.parseSlideAttributes("ppt/theme/theme1.xml"); // Initialize element parser const elementParser = new PowerpointElementParser(globals, theme); // Get slide data const slide = await ZipHandler.parseSlideAttributes("ppt/slides/slide1.xml"); const relations = await ZipHandler.parseSlideAttributes("ppt/slides/_rels/slide1.xml.rels"); // Extract shapes and images const shapes = slide["p:sld"]["p:cSld"][0]["p:spTree"][0]["p:sp"] || []; const images = slide["p:sld"]["p:cSld"][0]["p:spTree"][0]["p:pic"] || []; const allElements = shapes.concat(images); // Parse each element const parsedElements = []; for (const rawElement of allElements) { const element = elementParser.getProcessedElement(rawElement, relations); if (element) { parsedElements.push(element); console.log(`Parsed: ${element.name} (${element.shapeType})`); } else { console.log("Skipped unrenderable element"); } } return parsedElements; } parseSlideElements(); ``` -------------------------------- ### Parse Paragraph Text and Formatting with ParagraphParser (JavaScript) Source: https://context7.com/airpptx/airppt-parser/llms.txt Extracts text content, character properties (font, size, color), and paragraph properties (alignment) from presentation elements. It handles multiple text runs and font attributes like bold, italic, and underline, generating CSS styles. ```javascript const ParagraphParser = require("airppt-parser/js/parsers/paragraphparser").default; // Working with parsed text elements function processTextElements(elements) { const textElements = elements.filter(el => el.paragraph !== null); textElements.forEach(element => { const para = element.paragraph; // Text content console.log(`Text: "${para.text}"`); // Font information if (para.textCharacterProperties) { const props = para.textCharacterProperties; // Font size conversion: stored in hundredths of a point const fontSize = props.size / 100; console.log(`Font: ${props.font}, Size: ${fontSize}pt`); console.log(`Color: #${props.fillColor}`); // Font attributes const attributes = props.fontAttributes || []; const styles = []; if (attributes.includes("Bold")) styles.push("bold"); if (attributes.includes("Italics")) styles.push("italic"); if (attributes.includes("Underline")) styles.push("underline"); if (attributes.includes("StrikeThrough")) styles.push("strikethrough"); if (styles.length > 0) { console.log(`Styles: ${styles.join(", ")}`); } } // Alignment if (para.paragraphProperties) { console.log(`Alignment: ${para.paragraphProperties.alignment}`); } // Generate CSS const css = generateTextCSS(element); console.log(`CSS: ${css}`); }); } function generateTextCSS(element) { if (!element.paragraph?.textCharacterProperties) return ""; const props = element.paragraph.textCharacterProperties; const paraProps = element.paragraph.paragraphProperties; const attrs = props.fontAttributes || []; return ` font-family: "${props.font}", sans-serif; font-size: ${props.size / 100}pt; color: #${props.fillColor}; font-weight: ${attrs.includes("Bold") ? "bold" : "normal"}; font-style: ${attrs.includes("Italics") ? "italic" : "normal"}; text-decoration: ${attrs.includes("Underline") ? "underline" : "none"}; text-align: ${paraProps?.alignment?.toLowerCase() || "left"}; `.trim().replace(/\s+/g, " "); } ``` -------------------------------- ### Process Slide Links and Extract Assets with SlideRelationsParser Source: https://context7.com/airpptx/airppt-parser/llms.txt The SlideRelationsParser class helps resolve and process hyperlinks to external URLs and internal asset references (like images) within presentation slides. It takes slide elements and their relationships as input. The `extractImage` function specifically handles fetching image assets from the presentation's zip archive and converting them into data URIs. ```javascript const SlideRelationsParser = require("airppt-parser/js/parsers/relparser").default; async function processLinks(elements, slideRelations) { // Set slide relationships SlideRelationsParser.setSlideRelations(slideRelations); elements.forEach(element => { if (element.links) { console.log(`Element: ${element.name}`); if (element.links.Type === "External") { // External hyperlink console.log(` Link type: Hyperlink`); console.log(` URL: ${element.links.Uri}`); console.log(` HTML: ${element.paragraph?.text || element.name}`); } else if (element.links.Type === "Asset") { // Internal asset (image, video, etc.) console.log(` Link type: Asset`); console.log(` Path: ${element.links.Uri}`); // Extract asset if it's an image if (element.specialityType === "Image") { extractImage(element.links.Uri); } } } }); } async function extractImage(imagePath) { const ZipHandler = require("airppt-parser/js/helpers/ziphandler").default; try { // Get image as base64 const imageBase64 = await ZipHandler.getFileInZip(imagePath); // Convert to data URI for HTML const ext = imagePath.split('.').pop().toLowerCase(); const mimeTypes = { 'png': 'image/png', 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'gif': 'image/gif' }; const dataUri = `data:${mimeTypes[ext] || 'image/png'};base64,${imageBase64}`; console.log(` Data URI generated (${imageBase64.length} chars)`); return dataUri; } catch (error) { console.error(`Failed to extract image: ${error}`); return null; } } ``` -------------------------------- ### Parse PowerPoint Slide to JSON using airppt-parser Source: https://github.com/airpptx/airppt-parser/blob/master/README.md Demonstrates how to use the AirParser class from the 'airppt-parser' package to parse a specific slide from a PowerPoint file. It takes the file path and slide number as input and returns a Promise that resolves to an array of PowerPoint Elements and associated metadata. ```javascript let { AirParser } = require("airppt-parser"); let pptParser = new AirParser("./sample.pptx"); waitForParsing(); async function waitForParsing() { //pass in the slide number and wait let result = await pptParser.ParsePowerPoint(1); //returns an array of Powerpoint Elements and some extra MetaData console.log(result); } ``` -------------------------------- ### PowerpointElement Interface - JavaScript Structure Source: https://context7.com/airpptx/airppt-parser/llms.txt Defines the complete structure of a parsed slide element including shape properties, text formatting, positioning in EMUs (English Metric Units), borders, fills, and hyperlinks. Every shape, text box, or image is converted to this standardized format for consistent processing. ```javascript const exampleElement = { name: "Rectangle1", shapeType: "rect", specialityType: "None", elementPosition: { x: 914400, y: 1828800 }, elementOffsetPosition: { cx: 2743200, cy: 914400 }, paragraph: { text: "Hello World", textCharacterProperties: { fontAttributes: ["Bold", "Italics"], font: "Calibri", size: 1800, fillColor: "000000" }, paragraphProperties: { alignment: "Left" } }, shape: { border: { thickness: 12700, color: "000000", type: "solid", radius: null }, fill: { fillType: "Solid", fillColor: "FFFFFF" }, opacity: 1 }, links: { Type: "External", Uri: "https://example.com" }, raw: {} }; ``` -------------------------------- ### PowerPointElement Interface Definition Source: https://github.com/airpptx/airppt-parser/blob/master/README.md Defines the structure of a PowerPointElement, representing a single element on a slide. It includes properties for name, shape type, position, offsets, and specific details for text paragraphs, shapes, font styles, and links. The 'raw' property holds the original parsed data. ```typescript export interface PowerpointElement { name: string; shapeType: ElementType; specialityType: SpecialityType; elementPosition: { x: number, y: number }; elementOffsetPosition: { cx: number, cy: number }; paragraph?: { text: string, textCharacterProperties: { fontAttributes: FontAttributes[], font: string, size: number, fillColor: string }, paragraphProperties: { alignment: TextAlignment } }; shape?: { border?: { thickness: number, color: string, type: BorderType, radius?: number }, fill: { fillType: FillType, fillColor: string }, opacity: number }; fontStyle?: { font: string, fontSize: number, fontColor: string }; links?: { Type: LinkType, Uri: string }; raw: any; } ``` -------------------------------- ### Safely Access Nested XML Properties with CheckValidObject Source: https://context7.com/airpptx/airppt-parser/llms.txt The `CheckValidObject` utility provides a robust way to access nested properties within complex XML structures obtained from parsing. It prevents errors by returning `undefined` if any part of the specified path does not exist, allowing for safe default value assignment or conditional logic. This is crucial for handling potentially incomplete or varied XML schemas. ```javascript const { CheckValidObject } = require("airppt-parser/js/helpers/checkobj"); // Safe property access in complex XML structures function extractOptionalProperties(xmlObject) { // Instead of chaining optional operators or try-catch // Use CheckValidObject with a path string // Access nested properties safely const fontSize = CheckValidObject(xmlObject, '["a:rPr"][0]["$"].sz') || 1200; const fontFamily = CheckValidObject(xmlObject, '["a:rPr"][0]["a:latin"][0]["$"]["typeface"]') || "Arial"; const fillColor = CheckValidObject(xmlObject, '["p:spPr"][0]["a:solidFill"]["0"]["a:srgbClr"]["0"]["$"]["val"]') || "FFFFFF"; const borderWidth = CheckValidObject(xmlObject, '["p:spPr"][0]["a:ln"][0]["$"]["w"]') || 1000; // Deep array access const themeColor = CheckValidObject(xmlObject, '["a:schemeClr"][0]["$"]["val"]'); const alphaValue = CheckValidObject(xmlObject, '["a:alpha"][0]["$"]["val"]'); return { fontSize, fontFamily, fillColor, borderWidth, themeColor, alphaValue }; } // Practical usage in parsing function parseTextProperties(element) { const text = CheckValidObject(element, '["p:txBody"][0]["a:p"][0]["a:r"][0]["a:t"][0]'); const isBold = CheckValidObject(element, '["p:txBody"][0]["a:p"][0]["a:r"][0]["a:rPr"][0]["$"]["b"]') === 1; const isItalic = CheckValidObject(element, '["p:txBody"][0]["a:p"][0]["a:r"][0]["a:rPr"][0]["$"]["i"]') === 1; const isUnderline = CheckValidObject(element, '["p:txBody"][0]["a:p"][0]["a:r"][0]["a:rPr"][0]["$"]["u"]') !== undefined; if (!text) { console.log("No text found in element"); return null; } return { text, bold: isBold, italic: isItalic, underline: isUnderline }; } ``` -------------------------------- ### Analyze PowerPoint Shape Properties with JavaScript Source: https://context7.com/airpptx/airppt-parser/llms.txt This snippet shows how to use the ShapeParser to analyze properties of parsed PowerPoint elements, such as shape type, fill color, opacity, and border details. It iterates through an array of elements and logs specific attributes to the console. It handles both regular shapes and images. ```javascript const ShapeParser = require("airppt-parser/js/parsers/shapeparser").default; // Example of parsed shape data function analyzeShapes(elements) { elements.forEach(element => { // Shape type mapping const shapeTypes = { 'rect': 'Rectangle', 'ellipse': 'Ellipse/Circle', 'roundRect': 'Rounded Rectangle', 'triangle': 'Triangle', 'rtTriangle': 'Right Triangle', 'parallelogram': 'Parallelogram', 'trapezoid': 'Trapezoid', 'diamond': 'Diamond', 'pentagon': 'Pentagon', 'hexagon': 'Hexagon', 'star5': '5-Point Star', 'arrow': 'Arrow' }; console.log(`Shape: ${shapeTypes[element.shapeType] || element.shapeType}`); // Check if image if (element.specialityType === "Image") { console.log(` Image source: ${element.shape.fill.fillColor}`); } else { // Regular shape fill console.log(` Fill: #${element.shape.fill.fillColor}`); console.log(` Opacity: ${element.shape.opacity}`); // Border information if (element.shape.border) { console.log(` Border: ${element.shape.border.thickness / 12700}pt ${element.shape.border.type}`); console.log(` Border color: #${element.shape.border.color}`); } else { console.log(` Border: none`); } } }); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.