### Clone Repository and Install Dependencies Source: https://github.com/singerla/pptx-automizer/blob/main/docs/index.html These commands guide a user through cloning the pptx-automizer repository from GitHub and subsequently installing its dependencies using Yarn. This is the recommended approach for users who wish to explore the project's inner workings or run their own tests. ```bash git clone git@github.com:singerla/pptx-automizer.git cd pptx-automizer yarn install ``` -------------------------------- ### JavaScript Example: Automating PowerPoint Presentations Source: https://github.com/singerla/pptx-automizer/blob/main/docs/index.html A comprehensive JavaScript example demonstrating the core functionalities of pptx-automizer. It covers initializing the automizer, loading presentation templates, adding slides, and modifying elements within slides, including shapes and charts. The example also shows how to write the final presentation to a file. ```javascript import Automizer, { modify } from "pptx-automizer" // First, let's set some preferences const automizer = new Automizer({ templateDir: `my/pptx/templates`, outputDir: `my/pptx/output` }) // Now we can start and load a pptx template. // Each addSlide will append to any existing slide in RootTemplate.pptx. let pres = automizer.loadRoot(`RootTemplate.pptx`) // We want to make some more files available and give them a handy label. .load(`SlideWithShapes.pptx`, 'shapes') .load(`SlideWithGraph.pptx`, 'graph') // Skipping the second argument will not set a label. .load(`SlideWithImages.pptx`) // addSlide takes two arguments: The first will specify the source // presentation's label to get the template from, the second will set the // slide number to require. pres.addSlide('graph', 1) .addSlide('shapes', 1) .addSlide(`SlideWithImages.pptx`, 2) // You can also select and import a single element from a template slide. // The desired shape will be identified by its name from slide-xml's // 'p:cNvPr'-element. pres.addSlide('SlideWithImages.pptx', 1, (slide) => { // Pass the template name, the slide number, the element's name and // (optionally) a callback function to directly modify the child nodes // of slide.addElement('shapes', 2, 'Arrow', (element) => { element.getElementsByTagName('a:t')[0] .firstChild .data = 'Custom content' }) }) // It is possible to modify an existing element on a newly added slide. pres.addSlide('shapes', 2, (slide) => { slide.modifyElement('Drum', [ // You can use some of the builtin modifiers to edit a shape's xml: modify.setPosition({x: 1000000, h:5000000, w:5000000}), // Log your target xml into the console: modify.dump ]) }) // Modify an existing chart on an added slide. pres.addSlide('charts', 2, (slide) => { slide.modifyElement('ColumnChart', [ // Use an object like this to inject the new chart data. // Additional series and categories will be copied from // previous sibling. modify.setChartData({ series: [ { label: 'series 1' }, { label: 'series 2' }, { label: 'series 3' }, ], categories: [ { label: 'cat 2-1', values: [ 50, 50, 20 ] }, { label: 'cat 2-2', values: [ 14, 50, 20 ] }, { label: 'cat 2-3', values: [ 15, 50, 20 ] }, { label: 'cat 2-4', values: [ 26, 50, 20 ] } ] }) // Please notice: If your template has more data than your data // object, automizer will remove these nodes. ]) }) // Finally, we want to write the output file. pres.write(`myPresentation.pptx`).then(summary => { console.log(summary) }) ``` -------------------------------- ### Install pptx-automizer with npm or yarn Source: https://github.com/singerla/pptx-automizer/blob/main/docs/index.html Instructions for adding the pptx-automizer package to an existing project using either npm or yarn package managers. This ensures the latest version is installed. ```bash yarn add pptx-automizer ``` ```bash npm install pptx-automizer ``` -------------------------------- ### Install Dependencies with Yarn Source: https://github.com/singerla/pptx-automizer/blob/main/docs/index.html This command installs the necessary dependencies for the pptx-automizer project when using Yarn as the package manager. It's a prerequisite for running the project or its development mode. ```bash yarn install ``` -------------------------------- ### Initialize and Use pptx-automizer for Presentation Generation (TypeScript) Source: https://github.com/singerla/pptx-automizer/blob/main/README.md This snippet shows how to initialize the pptx-automizer library with configuration options such as template directories, output directory, and verbosity. It demonstrates loading multiple presentation templates, adding slides from these templates to a root presentation, and then writing the final presentation to a file. It also includes examples of getting a stream or the underlying JSZip instance for further manipulation. ```typescript import Automizer from 'pptx-automizer'; // First, let's set some preferences! const automizer = new Automizer({ // this is where your template pptx files are coming from: templateDir: `my/pptx/templates`, // use a fallback directory for e.g. generic templates: templateFallbackDir: `my/pptx/fallback-templates`, // specify the directory to write your final pptx output files: outputDir: `my/pptx/output`, // turn this to true if you want to generally use // Powerpoint's creationIds instead of slide numbers // or shape names: useCreationIds: false, // Always use the original slideMaster and slideLayout of any // imported slide: autoImportSlideMasters: true, // truncate root presentation and start with zero slides removeExistingSlides: true, // activate `cleanup` to eventually remove unused files: cleanup: false, // Set a value from 0-9 to specify the zip-compression level. // The lower the number, the faster your output file will be ready. // Higher compression levels produce smaller files. compression: 0, // You can enable 'archiveType' and set mode: 'fs'. // This will extract all templates and output to disk. // It will not improve performance, but it can help debugging: // You don't have to manually extract pptx contents, which can // be annoying if you need to look inside your files. // archiveType: { // mode: 'fs', // baseDir: `${__dirname}/../__tests__/pptx-cache`, // workDir: 'tmpWorkDir', // cleanupWorkDir: true, // }, // use a callback function to track pptx generation process. // statusTracker: myStatusTracker, // Use 1 to show warnings or 2 for detailed information // 0 disables logging verbosity: 1, // Remove all unused placeholders to prevent unwanted overlays: cleanupPlaceholders: false, // Use a customized version of pptxGenJs if required: // pptxGenJs: PptxGenJS, }); // Now we can start and load a pptx template. // With removeExistingSlides set to 'false', each addSlide will append to // any existing slide in RootTemplate.pptx. Otherwise, we are going to start // with a truncated root template. let pres = automizer .loadRoot('RootTemplate.pptx') // We want to make some more files available and give them a handy label. .load('SlideWithShapes.pptx', 'shapes') .load('SlideWithGraph.pptx', 'graph') // Skipping the second argument will not set a label. .load('SlideWithImages.pptx'); // Get useful information about loaded templates: /* const presInfo = await pres.getInfo(); const mySlides = presInfo.slidesByTemplate('shapes'); const mySlide = presInfo.slideByNumber('shapes', 2); const myShape = presInfo.elementByName('shapes', 2, 'Cloud'); */ // addSlide takes two arguments: The first will specify the source // presentation's label to get the template from, the second will set the // slide number to require. pres .addSlide('graph', 1) .addSlide('shapes', 1) .addSlide('SlideWithImages.pptx', 2); // Finally, we want to write the output file. pres.write('myPresentation.pptx').then((summary) => { console.log(summary); }); // It is also possible to get a ReadableStream. // stream() accepts JSZip.JSZipGeneratorOptions for 'nodebuffer' type. const stream = await pres.stream({ compressionOptions: { level: 9, }, }); // You can e.g. output the pptx archive to stdout instead of writing a file: stream.pipe(process.stdout); // If you need any other output format, you can eventually access // the underlying JSZip instance: const finalJSZip = await pres.getJSZip(); // Convert the output to whatever needed: const base64 = await finalJSZip.generateAsync({ type: 'base64' }); ``` -------------------------------- ### ModifyTableHelper Class Methods Source: https://github.com/singerla/pptx-automizer/blob/main/docs/classes/modifytablehelper.html This section outlines the static methods available in the ModifyTableHelper class, including their parameters, return types, and usage examples. ```APIDOC ## Static Methods of ModifyTableHelper ### `adjustHeight(data: TableData)` #### Description Adjusts the height of a table based on the provided data. #### Method Static #### Parameters - **data** (TableData) - Required - The data object containing information for height adjustment. #### Returns (element: XmlDocument | Element) => void - A function that takes an XML document or element and applies height adjustments. Returns void. #### Example ```typescript import { TableData, XmlDocument, Element } from './types'; // Assuming types are defined // Assuming 'modifyTableHelper' is imported const adjustHeightFunction = modifyTableHelper.adjustHeight(tableData); // To apply the adjustment to an element: // adjustHeightFunction(xmlElement); ``` ### `adjustWidth(data: TableData)` #### Description Adjusts the width of a table based on the provided data. #### Method Static #### Parameters - **data** (TableData) - Required - The data object containing information for width adjustment. #### Returns (element: XmlDocument | Element) => void - A function that takes an XML document or element and applies width adjustments. Returns void. #### Example ```typescript import { TableData, XmlDocument, Element } from './types'; // Assuming types are defined // Assuming 'modifyTableHelper' is imported const adjustWidthFunction = modifyTableHelper.adjustWidth(tableData); // To apply the adjustment to an element: // adjustWidthFunction(xmlElement); ``` ### `setTable(data: TableData)` #### Description Sets the content and properties of a table using the provided data. #### Method Static #### Parameters - **data** (TableData) - Required - The data object containing information for setting the table. #### Returns (element: XmlDocument | Element) => void - A function that takes an XML document or element and sets the table. Returns void. #### Example ```typescript import { TableData, XmlDocument, Element } from './types'; // Assuming types are defined // Assuming 'modifyTableHelper' is imported const setTableFunction = modifyTableHelper.setTable(tableData); // To apply the setting to an element: // setTableFunction(xmlElement); ``` ### `setTableData(data: TableData)` #### Description Sets the data content of an existing table. #### Method Static #### Parameters - **data** (TableData) - Required - The data object containing the table data to be set. #### Returns (element: XmlDocument | Element) => void - A function that takes an XML document or element and sets the table data. Returns void. #### Example ```typescript import { TableData, XmlDocument, Element } from './types'; // Assuming types are defined // Assuming 'modifyTableHelper' is imported const setTableDataFunction = modifyTableHelper.setTableData(tableData); // To apply the data setting to an element: // setTableDataFunction(xmlElement); ``` ### Constructor #### `constructor()` #### Description Initializes a new instance of the ModifyTableHelper class. #### Method Constructor #### Returns [ModifyTableHelper](modifytablehelper.html) - A new instance of ModifyTableHelper. #### Example ```typescript // Assuming 'ModifyTableHelper' is imported const tableHelper = new ModifyTableHelper(); ``` ``` -------------------------------- ### Run Development Mode Source: https://github.com/singerla/pptx-automizer/blob/main/docs/index.html This command starts the development mode for the pptx-automizer project using Yarn. In this mode, changes saved in `src/dev.ts` will trigger console output and generate a PPTX file in the destination folder, facilitating rapid development and testing. ```bash yarn dev ``` -------------------------------- ### Loop Through Slides and Apply Modifications (TypeScript) Source: https://github.com/singerla/pptx-automizer/blob/main/README.md This comprehensive TypeScript example shows how to load a presentation template, iterate through its slides, and apply specific modifications to each slide based on predefined callbacks. It utilizes `pptx-automizer` to manage templates, retrieve slide information, and write the modified presentation. ```typescript import Automizer, { CmToDxa, ISlide, ModifyColorHelper, ModifyShapeHelper, ModifyTextHelper, } from 'pptx-automizer'; const run = async () => { const automizer = new Automizer({ templateDir: `path/to/pptx-templates`, outputDir: `path/to/pptx-output`, removeExistingSlides: true, }); let pres = automizer .loadRoot(`SlideWithShapes.pptx`) .load(`SlideWithShapes.pptx`, 'myTemplate'); const myTemplates = await pres.getInfo(); const mySlides = myTemplates.slidesByTemplate(`myTemplate`); type CallbackBySlideNumber = { slideNumber: number; callback: (slide: ISlide) => void; }; const callbacks: CallbackBySlideNumber[] = [ { slideNumber: 2, callback: (slide: ISlide) => { slide.modifyElement('Cloud', [ ModifyTextHelper.setText('My content'), ModifyShapeHelper.setPosition({ h: CmToDxa(5), }), ModifyColorHelper.solidFill({ type: 'srgbClr', value: 'cccccc', }), ]); }, }, ]; const getCallbacks = (slideNumber: number) => { return callbacks.find((callback) => callback.slideNumber === slideNumber) ?.callback; }; mySlides.forEach((mySlide) => { pres.addSlide('myTemplate', mySlide.number, getCallbacks(mySlide.number)); }); pres.write(`myOutputPresentation.pptx`).then((summary) => { console.log(summary); }); }; run().catch((error) => { console.error(error); }); ``` -------------------------------- ### Add a Chart from Scratch using PptxGenJS (Node.js) Source: https://github.com/singerla/pptx-automizer/blob/main/README.md Shows how to add a chart element to a presentation from scratch using PptxGenJS, integrated within pptx-automizer. This example highlights the capability to create complex chart types dynamically. Requires Node.js and the pptx-automizer library. ```javascript const pptx = require('pptx-automizer'); const fs = require('fs'); async function addChartFromScratch() { const pres = await pptx.load('./template.pptx'); const slide = pres.slides[1]; // Assuming the second slide is the target const chartData = [ { name: 'Category 1', values: [10, 20, 30] }, { name: 'Category 2', values: [15, 25, 35] }, ]; const chartArgs = { x: 1, y: 1, w: 6, h: 4, chart: 'bar', title: 'Sample Bar Chart', data: chartData }; slide.addChart(chartArgs); await pres.writeFile({ filepath: './output_with_chart.pptx' }); console.log('Presentation with PptxGenJS chart generated!'); } addChartFromScratch(); ``` -------------------------------- ### Generate Text Shape with PptxGenJS Source: https://github.com/singerla/pptx-automizer/blob/main/README.md This TypeScript example demonstrates how to generate a text shape from scratch on a PowerPoint slide using the `pptxGenJS` wrapper provided by the library. It utilizes the `slide.generate` method and `pptxGenJSSlide.addText` to define the text content and its position and styling. ```typescript pres.addSlide('empty', 1, (slide) => { // Use pptxgenjs to add text from scratch: slide.generate((pptxGenJSSlide) => { pptxGenJSSlide.addText('Test 1', { x: 1, y: 1, h: 5, w: 10, color: '363636', }); }, 'custom object name'); }); ``` -------------------------------- ### Set Bubble Chart Data with ModifyChartHelper Source: https://github.com/singerla/pptx-automizer/blob/main/docs/classes/modifycharthelper.html This method is used to set data for bubble charts. It takes ChartData as input and returns a function to modify chart elements. See __tests__/modify-chart-bubbles.test.js for examples. ```typescript static setChartBubbles(data: ChartData): (element: XmlDocument | Element, chart?: Document, workbook?: Workbook) => void ``` -------------------------------- ### Set Default Chart Data with ModifyChartHelper Source: https://github.com/singerla/pptx-automizer/blob/main/docs/classes/modifycharthelper.html This method is used to set data for default chart types. It accepts ChartData and returns a function to update chart elements. Refer to __tests__/modify-existing-chart.test.js for usage examples. ```typescript static setChartData(data: ChartData): (element: XmlDocument | Element, chart?: Document, workbook?: Workbook) => void ``` -------------------------------- ### Get All Slide Numbers from a Template (TypeScript) Source: https://github.com/singerla/pptx-automizer/blob/main/README.md This concise snippet shows how to quickly retrieve an array of all slide numbers associated with a specific template file using the `getAllSlideNumbers` method. This is useful for iterating through slides when only their numbers are needed. ```typescript const slideNumbers = await pres .getTemplate('myTemplate.pptx') .getAllSlideNumbers(); for (const slideNumber of slideNumbers) { // do the thing } ``` -------------------------------- ### Set Vertical Line Chart Data with ModifyChartHelper Source: https://github.com/singerla/pptx-automizer/blob/main/docs/classes/modifycharthelper.html This method is designed to set data for vertical line charts. It takes ChartData and returns a function capable of modifying chart elements. See __tests__/modify-chart-vertical-lines.test.js for detailed examples. ```typescript static setChartVerticalLines(data: ChartData): (element: XmlDocument | Element, chart?: Document, workbook?: Workbook) => void ``` -------------------------------- ### Set Bubble Chart Data in PPTX Source: https://github.com/singerla/pptx-automizer/blob/main/docs/modules.html Modifies bubble chart data within a PowerPoint presentation. It takes chart data and an XML element representing the chart, optionally accepting chart and workbook objects. Refer to `__tests__/modify-chart-bubbles.test.js` for usage examples. ```typescript setChartBubbles: (data: ChartData) => (element: XmlDocument | Element, chart?: Document, workbook?: Workbook) => void ``` -------------------------------- ### Get Slide and Shape Creation IDs Source: https://github.com/singerla/pptx-automizer/blob/main/README.md Retrieves a list of available creation IDs for slides and shapes from loaded PowerPoint templates. This function is essential for identifying elements by their unique IDs, especially when templates are dynamic. It returns a nested structure containing template names, slide numbers, and associated shape creation IDs. ```typescript const pres = automizer .loadRoot(`RootTemplate.pptx`) .load(`SlideWithShapes.pptx`, 'shapes'); const creationIds = await pres.setCreationIds(); // This is going to print the slide creationId and a list of all // shapes from slide #1 in `SlideWithShapes.pptx` (aka `shapes`). console.log( creationIds .find((template) => template.name === 'shapes') .slides.find((slide) => slide.number === 1), ); // Find the corresponding slide-creationId and -number on top of this list. ``` -------------------------------- ### Remove Elements from PowerPoint Slides Source: https://github.com/singerla/pptx-automizer/blob/main/README.md This code example demonstrates how to remove existing elements like charts, images, or shapes from PowerPoint slides. It chains `addSlide` calls to specify the target slides and then uses `slide.removeElement` to delete the specified element by its name. It also shows how to remove and re-add an image. ```typescript // Remove existing charts, images or shapes from added slide. pres .addSlide('charts', 2, (slide) => { slide.removeElement('ColumnChart'); }) .addSlide('images', 2, (slide) => { slide.removeElement('imageJPG'); slide.removeElement('Textfeld 5'); slide.addElement('images', 2, 'imageJPG'); }); ``` -------------------------------- ### Modify PowerPoint Charts with Data Source: https://github.com/singerla/pptx-automizer/blob/main/README.md This code example shows how to modify an existing chart on a PowerPoint slide by updating its data. It uses `modify.setChartData` to inject new series and category data. If the template has more data than provided, extra nodes are removed; if more data is provided, new nodes are cloned from the first existing one. ```typescript // Modify an existing chart on an added slide. pres.addSlide('charts', 2, (slide) => { slide.modifyElement('ColumnChart', [ // Use an object like this to inject the new chart data. // Additional series and categories will be copied from // previous sibling. modify.setChartData({ series: [ { label: 'series 1' }, { label: 'series 2' }, { label: 'series 3' }, ], categories: [ { label: 'cat 2-1', values: [50, 50, 20] }, { label: 'cat 2-2', values: [14, 50, 20] }, { label: 'cat 2-3', values: [15, 50, 20] }, { label: 'cat 2-4', values: [26, 50, 20] }, ], }), ]); }); ``` -------------------------------- ### Run Unit Tests for pptx-automizer Source: https://github.com/singerla/pptx-automizer/blob/main/docs/index.html Commands to execute the unit tests and test coverage reports for the pptx-automizer package. These commands are run from the project's root directory. ```bash yarn test ``` ```bash yarn test-coverage ``` -------------------------------- ### Automizer Class Constructor Source: https://github.com/singerla/pptx-automizer/blob/main/docs/classes/default.html Creates an instance of the pptx-automizer. It accepts an optional AutomizerParams object for configuration. This is the main entry point for interacting with the pptx-automizer library. ```typescript new default(params?: AutomizerParams): [default](default.html) ``` -------------------------------- ### Load Root Presentation Template Source: https://github.com/singerla/pptx-automizer/blob/main/docs/classes/default.html Loads a presentation file and designates it as the root template. The root template serves as the base for all subsequent operations. ```APIDOC ## POST /automizer/loadRoot ### Description Load a pptx file and set it as root template. ### Method POST ### Endpoint /automizer/loadRoot ### Parameters #### Query Parameters - **location** (string) - Required - Filename or path to the template. Will be prefixed with 'templateDir' ### Request Example ```json { "location": "path/to/root_template.pptx" } ``` ### Response #### Success Response (200) - **Automizer Instance** (object) - Returns an instance of Automizer with the specified root template. #### Response Example ```json { "message": "Root template loaded successfully" } ``` ``` -------------------------------- ### Load Presentation Template (Internal) Source: https://github.com/singerla/pptx-automizer/blob/main/docs/classes/default.html An internal method for loading a presentation file, either as a root template or a regular template file. Allows aliasing templates with a specified name. ```APIDOC ## POST /automizer/loadTemplate ### Description Loads a pptx file either as a root template as a template file. A name can be specified to give templates an alias. ### Method POST ### Endpoint /automizer/loadTemplate ### Parameters #### Query Parameters - **location** (string) - Required - Path to the template file. - **name** (string) - Optional - Alias for the template. ### Request Example ```json { "location": "path/to/template.pptx", "name": "AliasTemplate" } ``` ### Response #### Success Response (200) - **Template Object** (object) - Represents the loaded template. #### Response Example ```json { "message": "Template loaded successfully" } ``` ``` -------------------------------- ### Load Presentation Template Source: https://github.com/singerla/pptx-automizer/blob/main/docs/classes/default.html Loads a presentation template from a specified location. This method can optionally assign a name to the loaded template for easier reference. If no name is provided, the template is named after its location. ```APIDOC ## POST /automizer/load ### Description Loads a template pptx file. ### Method POST ### Endpoint /automizer/load ### Parameters #### Query Parameters - **location** (string) - Required - Filename or path to the template. Will be prefixed with 'templateDir' - **name** (string) - Optional - Optional: A short name for the template. If skipped, the template will be named by its location. ### Request Example ```json { "location": "path/to/template.pptx", "name": "MyTemplate" } ``` ### Response #### Success Response (200) - **Automizer Instance** (object) - Returns an instance of Automizer representing the loaded template. #### Response Example ```json { "message": "Template loaded successfully" } ``` ``` -------------------------------- ### Add pptx-automizer Package with npm (Shell) Source: https://github.com/singerla/pptx-automizer/blob/main/README.md Command to add the pptx-automizer library as a dependency to an existing project using npm. ```shell npm install pptx-automizer ``` -------------------------------- ### TypeScript: Load PPTX Template Source: https://github.com/singerla/pptx-automizer/blob/main/docs/classes/default.html Loads a PPTX file as a template. This function can load either a root template or a regular template file, with an optional alias for the template. It handles the file location and naming conventions. Dependencies include the project's internal module structure. ```typescript /** * Loads a pptx file either as a root template as a template file. A name can be specified to give templates an alias. * @param location Filename or path to the template. * @param name Optional: A short name for the template. If skipped, the template will be named by its location. * @returns Instance of Automizer */ loadTemplate(location: string, name?: string): Automizer; /** * Load a template pptx file. * @param location Filename or path to the template. Will be prefixed with 'templateDir' * @param name Optional: A short name for the template. If skipped, the template will be named by its location. * @returns Instance of Automizer */ load(location: string, name?: string): Automizer; /** * Load a pptx file and set it as root template. * @param location Filename or path to the template. Will be prefixed with 'templateDir' * @returns Instance of Automizer */ loadRoot(location: string): Automizer; ``` -------------------------------- ### Modify Chart Vertical Lines - TypeScript Source: https://github.com/singerla/pptx-automizer/blob/main/docs/modules.html Sets the data for vertical line charts to modify their appearance. This function is intended for use with ChartData objects and operates on XML document elements representing charts. Refer to the associated test file for usage examples. ```typescript setChartVerticalLines: (data: ChartData) => (element: XmlDocument | Element, chart?: Document, workbook?: Workbook) => void ``` -------------------------------- ### Add pptx-automizer Package with Yarn (Shell) Source: https://github.com/singerla/pptx-automizer/blob/main/README.md Command to add the pptx-automizer library as a dependency to an existing project using Yarn. ```shell yarn add pptx-automizer ``` -------------------------------- ### Run Unit Tests with Yarn Source: https://github.com/singerla/pptx-automizer/blob/main/README.md Execute all unit tests for the pptx-automizer project using the Yarn package manager. This command verifies the functionality of the library's components. ```shell yarn test ``` -------------------------------- ### Write Presentation Modifications Source: https://github.com/singerla/pptx-automizer/blob/main/docs/classes/default.html Writes all accumulated imports and modifications to a specified file location. This action finalizes the changes made to the presentation. ```APIDOC ## POST /automizer/write ### Description Write all imports and modifications to a file. ### Method POST ### Endpoint /automizer/write ### Parameters #### Query Parameters - **location** (string) - Required - Filename or path for the file. Will be prefixed with 'outputDir' ### Request Example ```json { "location": "output/modified_presentation.pptx" } ``` ### Response #### Success Response (200) - **AutomizerSummary** (object) - A summary object detailing the write operation, including any statistics or confirmation. #### Response Example ```json { "message": "Presentation written successfully", "details": { "slides_modified": 5, "elements_added": 10 } } ``` ``` -------------------------------- ### Static dump Method - ModifyHelper Source: https://github.com/singerla/pptx-automizer/blob/main/docs/classes/modifyhelper.html The 'dump' method is a static utility within ModifyHelper used to print an XML document or element to the console. It takes an XmlDocument, Document, or Element as input and returns void. This is useful for debugging XML structures. ```typescript /** * Dump current element to console. * @param element XmlDocument | Document | Element * @returns void */ public static dump(element: XmlDocument | Document | Element): void; ``` -------------------------------- ### ModifyHelper - dump Method Source: https://github.com/singerla/pptx-automizer/blob/main/docs/classes/modifyhelper.html The 'dump' method is a static method of the ModifyHelper class. It is used to log the current element to the console. This is useful for debugging and inspecting the structure of XML elements. ```APIDOC ## Static dump ### Description Dump current element to console. ### Method STATIC ### Endpoint N/A (Class Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **element** (XmlDocument | Document | Element) - Required - The XML element to be dumped. ### Request Example ```json { "element": "..." } ``` ### Response #### Success Response (200) void #### Response Example ```json { "message": "Element dumped to console." } ``` ``` -------------------------------- ### Import and Modify Presentation using xmldom (Node.js) Source: https://github.com/singerla/pptx-automizer/blob/main/README.md Demonstrates how to use pptx-automizer with xmldom to modify existing .pptx files. This approach is suitable for detailed XML-level manipulation of presentation elements. Dependencies include Node.js and the pptx-automizer library. ```javascript const pptx = require('pptx-automizer'); const fs = require('fs'); async function modifyPresentation() { const pres = await pptx.load('./template.pptx'); // Example: Modify text of a shape named 'Title' pres.slides.forEach(slide => { slide.shapes.forEach(shape => { if (shape.name === 'Title') { shape.text = 'New Title Text'; } }); }); await pres.writeFile({ filepath: './output.pptx' }); console.log('Presentation modified successfully!'); } modifyPresentation(); ``` -------------------------------- ### TypeScript: Write PPTX Modifications Source: https://github.com/singerla/pptx-automizer/blob/main/docs/classes/default.html Writes all accumulated imports and modifications to a specified file location. The output path is prefixed with 'outputDir'. This function returns a Promise that resolves with an AutomizerSummary object detailing the write operation. Ensure the output directory is correctly configured. ```typescript /** * Write all imports and modifications to a file. * @param location Filename or path for the file. Will be prefixed with 'outputDir' * @returns Promise * summary object. */ write(location: string): Promise; ``` -------------------------------- ### Dump XML Element to Console Source: https://github.com/singerla/pptx-automizer/blob/main/docs/modules.html Dumps the current XML element to the console for debugging purposes. It takes an XML document or element as input and outputs its structure. This is helpful for inspecting the state of the presentation's XML. ```typescript dump: (element: XmlDocument | Document | Element) => void ``` -------------------------------- ### Run Test Coverage with Yarn Source: https://github.com/singerla/pptx-automizer/blob/main/README.md Generate a code coverage report for the pptx-automizer project using Yarn. This helps in identifying which parts of the codebase are covered by tests. ```shell yarn test-coverage ``` -------------------------------- ### Automizer.addSlide Method Source: https://github.com/singerla/pptx-automizer/blob/main/docs/classes/default.html Adds a slide to the presentation using a template. You can specify the template name, slide number, and an optional callback function that executes after the slide is added, receiving the newly created slide as an argument. Returns the Automizer instance for chaining. ```typescript addSlide(name: string, slideNumber: number, callback?: (slide: Slide) => void): [default](default.html) ``` -------------------------------- ### Generate Shapes with PptxGenJS (Node.js) Source: https://github.com/singerla/pptx-automizer/blob/main/README.md Illustrates generating shapes from scratch within an existing .pptx template using PptxGenJS, which is wrapped by pptx-automizer. This allows for dynamic content creation using PptxGenJS's extensive API. Requires Node.js and the pptx-automizer library. ```javascript const pptx = require('pptx-automizer'); const fs = require('fs'); async function generateWithPptxGenJs() { const pres = await pptx.load('./template.pptx'); const slide = pres.slides[0]; // Assuming the first slide is the target // Use PptxGenJS to add a new shape (e.g., a text box) const pptxgen = new pptx.PptxGenJS(); const textArgs = { x: 1, y: 1, w: 5, h: 1, text: 'Dynamically Generated Text', fontSize: 24, color: '363636' }; slide.addText(textArgs); await pres.writeFile({ filepath: './output_with_pptxgenjs.pptx' }); console.log('Presentation with PptxGenJS elements generated!'); } generateWithPptxGenJs(); ``` -------------------------------- ### Check Presentation Template Type Source: https://github.com/singerla/pptx-automizer/blob/main/docs/classes/default.html A private utility method to determine if a given template object is a default PresTemplate or a RootPresTemplate. ```APIDOC ## POST /automizer/isPresTemplate ### Description Determines whether template is root or default template. ### Method POST ### Endpoint /automizer/isPresTemplate ### Parameters #### Request Body - **template** (object) - Required - The template object to check. Can be of type RootPresTemplate or PresTemplate. ### Request Example ```json { "template": { /* template object details */ } } ``` ### Response #### Success Response (200) - **isPresTemplate** (boolean) - Returns true if the template is a PresTemplate, false otherwise. #### Response Example ```json { "isPresTemplate": true } ``` ``` -------------------------------- ### Configure pptx-automizer to Auto-Import Slide Masters Source: https://github.com/singerla/pptx-automizer/blob/main/README.md Shows how to set the `autoImportSlideMasters` option to `true` in the Automizer configuration. This ensures that all required slide masters and layouts are automatically imported, which can be helpful if dealing with complex or mismatched presentation structures. ```typescript import Automizer from 'pptx-automizer'; const automizer = new Automizer({ // ... // Always use the original slideMaster and slideLayout of any // imported slide: autoImportSlideMasters: true, // ... }); ``` -------------------------------- ### Automizer.getTemplate Method Source: https://github.com/singerla/pptx-automizer/blob/main/docs/classes/default.html Retrieves a PresTemplate object from the internal templates list by its name. This method is used internally to access loaded templates. ```typescript getTemplate(name: string): PresTemplate ``` -------------------------------- ### Set Table Data - TypeScript Source: https://github.com/singerla/pptx-automizer/blob/main/docs/modules.html Sets the data for a table within a presentation. It accepts TableData and returns a function that operates on an XML document element representing the table. ```typescript setTable: (data: TableData) => (element: XmlDocument | Element) => void ``` -------------------------------- ### Configure Automizer with Creation IDs Source: https://github.com/singerla/pptx-automizer/blob/main/README.md Initializes the pptx-automizer with the `useCreationIds` option set to `true`. This configuration ensures that both slides and shapes are managed using their respective `creationId` properties, providing stable element identification even when slides are reordered or renamed. ```typescript const automizer = new Automizer({ templateDir: `${__dirname}/pptx-templates`, outputDir: `${__dirname}/pptx-output`, // turn this to true and use creationIds for both, slides and shapes useCreationIds: true, }); ``` -------------------------------- ### Add Slide and Element using Creation IDs Source: https://github.com/singerla/pptx-automizer/blob/main/README.md Shows how to add a slide and an element to a presentation using their respective `creationId` values in TypeScript. This method is recommended when `useCreationIds` is set to `true`, ensuring accurate placement and identification of content. ```typescript // Whenever `useCreationIds` was set to true, you need to replace slide numbers // by `creationId`, too: await pres.addSlide('shapes', 4167997312, (slide) => { // slide is now #1 of `SlideWithShapes.pptx` slide.addElement('shapes', 273148976, { creationId: '{E43D12C3-AD5A-4317-BC00-FDED287C0BE8}', name: 'Drum', }); // 'Drum' is from #2 of `SlideWithShapes.pptx`, see __tests__ dir for an // example. }); ``` -------------------------------- ### Modify Table Data and Appearance Source: https://github.com/singerla/pptx-automizer/blob/main/docs/modules.html Provides functions to adjust the height and width of tables based on provided data. It also includes a method to set table data and dump the table element. These functions are useful for ensuring tables fit content and are correctly formatted. They operate on XmlDocument, Document, or Element types. ```typescript adjustHeight: (data: TableData) => (element: XmlDocument | Element) => void; adjustWidth: (data: TableData) => (element: XmlDocument | Element) => void; dump: (element: XmlDocument | Document | Element) => void; setTable: (data: TableData) => (element: XmlDocument | Element) => void; setTableData: (data: TableData) => (element: XmlDocument | Element) => void; ``` -------------------------------- ### Implement Custom Status Tracking in pptx-automizer Source: https://github.com/singerla/pptx-automizer/blob/main/README.md Details how to implement a custom status tracker callback for the Automizer. This allows monitoring the progress of large presentation creation by logging status information and the completion percentage. ```typescript import Automizer, { StatusTracker } from 'pptx-automizer'; // If you want to track the steps of creation process, // you can use a custom callback: const myStatusTracker = (status: StatusTracker) => { console.log(status.info + ' (' + status.share + '%)'); }; const automizer = new Automizer({ // ... statusTracker: myStatusTracker, }); ``` -------------------------------- ### Create New Hyperlinked Text Shapes (TypeScript) Source: https://github.com/singerla/pptx-automizer/blob/main/README.md This code illustrates how to generate new text shapes with hyperlinks from scratch using `pptxGenJS`. It shows the creation of both external website links and internal slide links, specifying positioning and formatting like font size. ```typescript slide.generate((pptxGenJSSlide) => { pptxGenJSSlide.addText(`External Link`, { hyperlink: { url: 'https://github.com' }, x: 1, y: 1, w: 2.5, h: 0.5, fontSize: 12, }); }); slide.generate((pptxGenJSSlide) => { pptxGenJSSlide.addText(`Go to slide 3`, { hyperlink: { slide: 3 }, x: 1, y: 1, w: 2.5, h: 0.5, fontSize: 12, }); }); ``` -------------------------------- ### Sort Output Slides by Appending to Existing Slides Source: https://github.com/singerla/pptx-automizer/blob/main/README.md Demonstrates how to control the order of slides in the output presentation. This method appends slides based on the order of `addSlide` calls. It initializes the Automizer with template and output directories and can optionally remove existing slides. ```typescript import Automizer from 'pptx-automizer'; const automizer = new Automizer({ templateDir: `my/pptx/templates`, outputDir: `my/pptx/output`, // truncate root presentation and start with zero slides removeExistingSlides: true, }); let pres = automizer .loadRoot(`RootTemplate.pptx`) // We load this twice to make it available for sorting slide .load(`RootTemplate.pptx`, 'root') .load(`SlideWithShapes.pptx`, 'shapes') .load(`SlideWithGraph.pptx`, 'graph'); pres .addSlide('root', 1) // First slide will be taken from root .addSlide('graph', 1) .addSlide('shapes', 1) .addSlide('root', 3) // Third slide from root will be appended .addSlide('root', 2); // Second and third slide will switch position pres.write(`mySortedPresentation.pptx`).then((summary) => { console.log(summary); }); ``` -------------------------------- ### Set Table Data - TypeScript Source: https://github.com/singerla/pptx-automizer/blob/main/docs/classes/modifytablehelper.html This method populates a table element with data. It receives TableData and returns a function capable of modifying the table element with the provided data. This is a core function for dynamically generating tables in presentations. The function operates on XmlDocument or Element types. ```typescript static setTableData(data: TableData): (element: XmlDocument | Element) => void ``` -------------------------------- ### Modify Image Source and Size in Presentation Source: https://github.com/singerla/pptx-automizer/blob/main/README.md Explains how to load external media files and use them to update existing images in a presentation. It covers setting a new image source using `ModifyImageHelper.setRelationTarget` and adjusting shape properties like size with `ModifyShapeHelper.setPosition`. ```typescript const automizer = new Automizer({ // ... // Specify a directory to import external media files from: mediaDir: `path/to/media`, }); const pres = automizer .loadRoot(`RootTemplate.pptx`) // load one or more files from mediaDir .loadMedia([`feather.png`, `test.png`] /* or use a custom dir */) // and/or use a custom dir .loadMedia(`icon.png`, 'path/to/icons') .load(`SlideWithImages.pptx`, 'images'); pres.addSlide('images', 2, (slide) => { slide.modifyElement('imagePNG', [ // Override the original media source of element 'imagePNG' // by an imported file: ModifyImageHelper.setRelationTarget('feather.png'), // You might need to update size ModifyShapeHelper.setPosition({ w: CmToDxa(5), h: CmToDxa(3), }), ]); }); ``` -------------------------------- ### Set Shape and Text Properties Source: https://github.com/singerla/pptx-automizer/blob/main/docs/modules.html Allows setting attributes for shape elements, including tag name, attribute name, and value. It also provides functionality to set the position of a shape and to set solid fill for an element. These methods are crucial for styling and positioning shapes within a presentation. ```typescript setAttribute: (tagName: string, attribute: string, value: string | number, count?: number) => (element: XmlDocument) => void; setPosition: (pos: ShapeCoordinates) => (element: XmlDocument | Element) => void; setSolidFill: (element: XmlDocument | Element) => void; ``` -------------------------------- ### Convert HTML to Presentation Text Contents Source: https://github.com/singerla/pptx-automizer/blob/main/README.md Demonstrates converting an HTML string into presentation text content, suitable for slides. The HTML is flattened and transformed into a format compatible with `MultiText`. This uses the `modify.htmlToMultiText` function. ```typescript import { modify } from 'pptx-automizer'; const html = '' + '
    ' + '
  • bullet 1 level 1
  • ' + '
' + ''; pres.addSlide('TextReplace.pptx', 1, (slide) => { slide.modifyElement('setText', modify.htmlToMultiText(html)); }); ``` -------------------------------- ### Set Solid Fill for Shape - TypeScript Source: https://github.com/singerla/pptx-automizer/blob/main/docs/modules.html Applies a solid fill to a modified shape. This function takes an XML document element representing the shape as its parameter and returns void. ```typescript setSolidFill: (element: XmlDocument | Element) => void ```