node-pptx-parser 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Mirza-Glitch
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.MD ADDED
@@ -0,0 +1,212 @@
1
+ # node-pptx-parser
2
+
3
+ A Node.js library for parsing PowerPoint (PPTX) files and extracting text content. This library maintains text formatting, line breaks, and paragraph structures from the original presentation.
4
+
5
+ ## Features
6
+
7
+ - Extract text content from PPTX files with preserved formatting
8
+
9
+ - Parse PPTX structure into manageable JavaScript objects
10
+
11
+ - Access raw XML content of presentation components
12
+
13
+ - Written in TypeScript for type safety
14
+
15
+ - Promise-based API
16
+
17
+ - Preserves line breaks and paragraph formatting
18
+
19
+ - Minimal dependencies
20
+
21
+ ## Installation
22
+
23
+ ```bash
24
+
25
+ npm install node-pptx-parser
26
+ ```
27
+
28
+ ## Usage
29
+
30
+ Once the package is installed you can you it with `import` or `require` statements like this:
31
+
32
+ ```javascript
33
+ // ESM import:
34
+ import PptxParser from "node-pptx-parser";
35
+
36
+ // CommonJs require:
37
+ const PptxParser = require("node-pptx-parser").default;
38
+ ```
39
+
40
+ ### Basic Text Extraction
41
+
42
+ ```typescript
43
+ import PptxParser from "node-pptx-parser";
44
+
45
+ async function main() {
46
+ const parser = new PptxParser("presentation.pptx");
47
+
48
+ try {
49
+ // Extract text from all slides
50
+ const textContent = await parser.extractText();
51
+
52
+ // Print text from each slide
53
+ textContent.forEach((slide) => {
54
+ console.log(`\nSlide ${slide.id}:`);
55
+
56
+ console.log(slide.text.join("\n"));
57
+ });
58
+ } catch (error) {
59
+ console.error("Error:", error.message);
60
+ }
61
+ }
62
+
63
+ main();
64
+ ```
65
+
66
+ ### Advanced Usage - Full Presentation Parsing
67
+
68
+ ```typescript
69
+ import PptxParser from "node-pptx-parser";
70
+
71
+ async function main() {
72
+ const parser = new PptxParser("presentation.pptx");
73
+
74
+ try {
75
+ // Get complete parsed presentation content
76
+ const parsedContent = await parser.parse();
77
+
78
+ // Access presentation structure
79
+ console.log(parsedContent.presentation.parsed);
80
+
81
+ // Access individual slides
82
+ parsedContent.slides.forEach((slide) => {
83
+ console.log(`Slide ${slide.id}:`, slide.parsed);
84
+ });
85
+
86
+ // Access raw XML if needed
87
+ console.log(parsedContent.presentation.xml);
88
+ } catch (error) {
89
+ console.error("Error:", error.message);
90
+ }
91
+ }
92
+
93
+ main();
94
+ ```
95
+
96
+ ## API Reference
97
+
98
+ ### `PptxParser`
99
+
100
+ The main class for parsing PPTX files.
101
+
102
+ #### Constructor
103
+
104
+ ```typescript
105
+
106
+ constructor(filePath: string)
107
+ ```
108
+
109
+ Creates a new instance of PptxParser.
110
+
111
+ - `filePath`: Path to the PPTX file to be parsed
112
+
113
+ #### Methods
114
+
115
+ ##### `parse()`
116
+
117
+ ```typescript
118
+
119
+ async parse(): Promise<ParsedPresentation>
120
+ ```
121
+
122
+ Parses the entire PPTX file and returns its content.
123
+
124
+ - Returns: Promise resolving to a `ParsedPresentation` object containing the complete presentation structure
125
+
126
+ ##### `extractText()`
127
+
128
+ ```typescript
129
+
130
+ async extractText(): Promise<SlideTextContent[]>
131
+ ```
132
+
133
+ Extracts formatted text content from all slides.
134
+
135
+ - Returns: Promise resolving to an array of `SlideTextContent` objects
136
+
137
+ ### Types
138
+
139
+ #### `ParsedPresentation`
140
+
141
+ ```typescript
142
+ interface ParsedPresentation {
143
+ presentation: {
144
+ path: string;
145
+ xml: string;
146
+ parsed: any;
147
+ };
148
+ relationships: {
149
+ path: string;
150
+ xml: string;
151
+ parsed: any;
152
+ };
153
+ slides: ParsedSlide[];
154
+ }
155
+ ```
156
+
157
+ #### `ParsedSlide`
158
+
159
+ ```typescript
160
+ interface ParsedSlide {
161
+ id: string;
162
+ path: string;
163
+ xml: string;
164
+ parsed: any;
165
+ }
166
+ ```
167
+
168
+ #### `SlideTextContent`
169
+
170
+ ```typescript
171
+ interface SlideTextContent extends ParsedSlide {
172
+ text: string[];
173
+ }
174
+ ```
175
+
176
+ ## Error Handling
177
+
178
+ The library throws errors in the following cases:
179
+
180
+ - Invalid PPTX file structure
181
+
182
+ - File reading errors
183
+
184
+ - XML parsing errors
185
+
186
+ Example error handling:
187
+
188
+ ```typescript
189
+ try {
190
+ const parser = new PptxParser("presentation.ppt");
191
+ const content = await parser.extractText();
192
+ } catch (error) {
193
+ if (error.message.includes("Invalid PPTX file structure")) {
194
+ console.error("The PPTX file is corrupted or invalid");
195
+ } else {
196
+ console.error("An error occurred:", error.message);
197
+ }
198
+ }
199
+ ```
200
+
201
+ ## Dependencies
202
+
203
+ - unzipper: For extracting PPTX files
204
+ - xml2js: For parsing XML content
205
+
206
+ ## License
207
+
208
+ MIT
209
+
210
+ ## Contributing
211
+
212
+ Contributions are welcome! Please feel free to submit a Pull Request.
@@ -0,0 +1,239 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const unzipper_1 = __importDefault(require("unzipper"));
16
+ const xml2js_1 = __importDefault(require("xml2js"));
17
+ /**
18
+ * PptxParser - A class for parsing PowerPoint (PPTX) files and extracting their content
19
+ *
20
+ * This parser can:
21
+ * - Extract raw XML content from PPTX files
22
+ * - Parse the XML into JavaScript objects
23
+ * - Extract formatted text content from slides
24
+ * - Preserve line breaks and paragraph formatting
25
+ *
26
+ * PPTX files are essentially ZIP archives containing XML files. The main files we care about are:
27
+ * - presentation.xml: Contains the main presentation structure
28
+ * - _rels/presentation.xml.rels: Contains relationships between presentation parts
29
+ * - slides/slide*.xml: Contains individual slide content
30
+ */
31
+ class PptxParser {
32
+ /**
33
+ * Creates a new instance of PptxParser
34
+ * @param filePath - Path to the PPTX file to be parsed
35
+ */
36
+ constructor(filePath) {
37
+ this.filePath = filePath;
38
+ }
39
+ /**
40
+ * Parses the entire PPTX file and returns its content
41
+ *
42
+ * This method:
43
+ * 1. Opens the PPTX file as a ZIP archive
44
+ * 2. Extracts and parses the presentation.xml
45
+ * 3. Extracts and parses the relationship file
46
+ * 4. Finds and parses all slides
47
+ *
48
+ * @returns Promise<ParsedPresentation> - Object containing parsed presentation data
49
+ * @throws Error if the PPTX file is invalid or cannot be parsed
50
+ */
51
+ parse() {
52
+ return __awaiter(this, void 0, void 0, function* () {
53
+ try {
54
+ const directory = yield unzipper_1.default.Open.file(this.filePath);
55
+ // Find main XML files in the PPTX structure
56
+ const presentationXml = directory.files.find((d) => d.path === "ppt/presentation.xml");
57
+ const slideRelationsXml = directory.files.find((d) => d.path === "ppt/_rels/presentation.xml.rels");
58
+ if (!presentationXml || !slideRelationsXml) {
59
+ throw new Error("Invalid PPTX file structure");
60
+ }
61
+ // Extract and parse the main presentation content
62
+ const presentationContent = yield this.getFileContent(presentationXml);
63
+ const relationshipsContent = yield this.getFileContent(slideRelationsXml);
64
+ const presentationData = yield this.parseXmlContent(presentationContent);
65
+ const relationshipsData = yield this.parseXmlContent(relationshipsContent);
66
+ // Get information about all slides
67
+ const slideRelations = this.getSlideRelations(relationshipsData);
68
+ // Parse each slide in parallel
69
+ const slides = yield Promise.all(slideRelations.map((relation) => __awaiter(this, void 0, void 0, function* () {
70
+ const slideFile = directory.files.find((f) => f.path === `ppt/${relation.target}`);
71
+ if (!slideFile)
72
+ return null;
73
+ const slideContent = yield this.getFileContent(slideFile);
74
+ return {
75
+ id: relation.id,
76
+ path: slideFile.path,
77
+ xml: slideContent,
78
+ parsed: yield this.parseXmlContent(slideContent),
79
+ };
80
+ })));
81
+ return {
82
+ presentation: {
83
+ path: "ppt/presentation.xml",
84
+ xml: presentationContent,
85
+ parsed: presentationData,
86
+ },
87
+ relationships: {
88
+ path: "ppt/_rels/presentation.xml.rels",
89
+ xml: relationshipsContent,
90
+ parsed: relationshipsData,
91
+ },
92
+ slides: slides.filter((slide) => slide !== null),
93
+ };
94
+ }
95
+ catch (error) {
96
+ throw new Error(`Failed to parse PPTX: ${error.message}`);
97
+ }
98
+ });
99
+ }
100
+ /**
101
+ * Extracts content from a file within the PPTX archive
102
+ *
103
+ * @param file - A file from the unzipper library
104
+ * @returns Promise<string> - The file's content as a string
105
+ */
106
+ getFileContent(file) {
107
+ return __awaiter(this, void 0, void 0, function* () {
108
+ return new Promise((resolve, reject) => {
109
+ let data = "";
110
+ file
111
+ .stream()
112
+ .on("data", (chunk) => (data += chunk))
113
+ .on("end", () => resolve(data))
114
+ .on("error", reject);
115
+ });
116
+ });
117
+ }
118
+ /**
119
+ * Parses XML content into a JavaScript object
120
+ *
121
+ * @param xmlContent - Raw XML string to parse
122
+ * @returns Promise<any> - Parsed JavaScript object
123
+ */
124
+ parseXmlContent(xmlContent) {
125
+ return __awaiter(this, void 0, void 0, function* () {
126
+ return new Promise((resolve, reject) => {
127
+ xml2js_1.default.parseString(xmlContent, (err, result) => {
128
+ if (err)
129
+ reject(err);
130
+ else
131
+ resolve(result);
132
+ });
133
+ });
134
+ });
135
+ }
136
+ /**
137
+ * Extracts slide relations from the presentation relationships XML
138
+ *
139
+ * In PPTX files, slides are referenced by relationships in the presentation.xml.rels file.
140
+ * This method finds all slide references in these relationships.
141
+ *
142
+ * @param relationshipsData - Parsed relationship XML data
143
+ * @returns SlideRelation[] - Array of slide relations
144
+ */
145
+ getSlideRelations(relationshipsData) {
146
+ const relationships = relationshipsData["Relationships"]["Relationship"];
147
+ return relationships
148
+ .filter((rel) => rel["$"]["Type"].endsWith("/slide"))
149
+ .map((rel) => ({
150
+ id: rel["$"]["Id"],
151
+ target: rel["$"]["Target"],
152
+ }));
153
+ }
154
+ /**
155
+ * Extracts formatted text content from all slides
156
+ *
157
+ * This is a convenience method that:
158
+ * 1. Parses the entire presentation
159
+ * 2. Extracts text from each slide
160
+ * 3. Preserves formatting and line breaks
161
+ *
162
+ * @returns Promise<SlideTextContent[]> - Array of slide text content
163
+ */
164
+ extractText() {
165
+ return __awaiter(this, void 0, void 0, function* () {
166
+ const parsed = yield this.parse();
167
+ const textContent = [];
168
+ for (const slide of parsed.slides) {
169
+ const slideText = this.extractTextFromSlide(slide.parsed);
170
+ textContent.push(Object.assign(Object.assign({}, slide), { text: slideText }));
171
+ }
172
+ return textContent;
173
+ });
174
+ }
175
+ /**
176
+ * Extracts text content from a single slide while preserving formatting
177
+ *
178
+ * PowerPoint slide XML structure:
179
+ * - p:sp: Shape elements that can contain text
180
+ * - p:txBody: The text body within a shape
181
+ * - a:p: Individual paragraphs
182
+ * - a:r: Text runs within paragraphs
183
+ * - a:t: Actual text content
184
+ * - a:br: Line breaks
185
+ * - a:endParaRPr: Paragraph end markers
186
+ *
187
+ * @param slideData - Parsed slide XML data
188
+ * @returns string[] - Array of text blocks with preserved formatting
189
+ */
190
+ extractTextFromSlide(slideData) {
191
+ const texts = [];
192
+ // Navigate the XML structure to find text elements
193
+ if (slideData["p:sld"] &&
194
+ slideData["p:sld"]["p:cSld"] &&
195
+ slideData["p:sld"]["p:cSld"][0]["p:spTree"]) {
196
+ const spTree = slideData["p:sld"]["p:cSld"][0]["p:spTree"][0];
197
+ if (spTree["p:sp"]) {
198
+ // Process each shape that might contain text
199
+ spTree["p:sp"].forEach((shape) => {
200
+ if (shape["p:txBody"]) {
201
+ shape["p:txBody"].forEach((textBody) => {
202
+ if (textBody["a:p"]) {
203
+ const paragraphTexts = [];
204
+ // Process each paragraph
205
+ textBody["a:p"].forEach((paragraph) => {
206
+ const paragraphText = [];
207
+ // Extract text from runs
208
+ if (paragraph["a:r"]) {
209
+ paragraph["a:r"].forEach((run) => {
210
+ if (run["a:t"]) {
211
+ paragraphText.push(run["a:t"][0]);
212
+ }
213
+ });
214
+ }
215
+ // Handle explicit line breaks
216
+ if (paragraph["a:br"]) {
217
+ paragraphText.push("\n");
218
+ }
219
+ // Handle paragraph breaks
220
+ if (paragraphText.length === 0 || paragraph["a:endParaRPr"]) {
221
+ paragraphText.push("\n");
222
+ }
223
+ if (paragraphText.length > 0) {
224
+ paragraphTexts.push(paragraphText.join(""));
225
+ }
226
+ });
227
+ if (paragraphTexts.length > 0) {
228
+ texts.push(paragraphTexts.join("\n"));
229
+ }
230
+ }
231
+ });
232
+ }
233
+ });
234
+ }
235
+ }
236
+ return texts;
237
+ }
238
+ }
239
+ exports.default = PptxParser;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,220 @@
1
+ import unzipper from "unzipper";
2
+ import xml2js from "xml2js";
3
+ /**
4
+ * PptxParser - A class for parsing PowerPoint (PPTX) files and extracting their content
5
+ *
6
+ * This parser can:
7
+ * - Extract raw XML content from PPTX files
8
+ * - Parse the XML into JavaScript objects
9
+ * - Extract formatted text content from slides
10
+ * - Preserve line breaks and paragraph formatting
11
+ *
12
+ * PPTX files are essentially ZIP archives containing XML files. The main files we care about are:
13
+ * - presentation.xml: Contains the main presentation structure
14
+ * - _rels/presentation.xml.rels: Contains relationships between presentation parts
15
+ * - slides/slide*.xml: Contains individual slide content
16
+ */
17
+ export default class PptxParser {
18
+ filePath;
19
+ /**
20
+ * Creates a new instance of PptxParser
21
+ * @param filePath - Path to the PPTX file to be parsed
22
+ */
23
+ constructor(filePath) {
24
+ this.filePath = filePath;
25
+ }
26
+ /**
27
+ * Parses the entire PPTX file and returns its content
28
+ *
29
+ * This method:
30
+ * 1. Opens the PPTX file as a ZIP archive
31
+ * 2. Extracts and parses the presentation.xml
32
+ * 3. Extracts and parses the relationship file
33
+ * 4. Finds and parses all slides
34
+ *
35
+ * @returns Promise<ParsedPresentation> - Object containing parsed presentation data
36
+ * @throws Error if the PPTX file is invalid or cannot be parsed
37
+ */
38
+ async parse() {
39
+ try {
40
+ const directory = await unzipper.Open.file(this.filePath);
41
+ // Find main XML files in the PPTX structure
42
+ const presentationXml = directory.files.find((d) => d.path === "ppt/presentation.xml");
43
+ const slideRelationsXml = directory.files.find((d) => d.path === "ppt/_rels/presentation.xml.rels");
44
+ if (!presentationXml || !slideRelationsXml) {
45
+ throw new Error("Invalid PPTX file structure");
46
+ }
47
+ // Extract and parse the main presentation content
48
+ const presentationContent = await this.getFileContent(presentationXml);
49
+ const relationshipsContent = await this.getFileContent(slideRelationsXml);
50
+ const presentationData = await this.parseXmlContent(presentationContent);
51
+ const relationshipsData = await this.parseXmlContent(relationshipsContent);
52
+ // Get information about all slides
53
+ const slideRelations = this.getSlideRelations(relationshipsData);
54
+ // Parse each slide in parallel
55
+ const slides = await Promise.all(slideRelations.map(async (relation) => {
56
+ const slideFile = directory.files.find((f) => f.path === `ppt/${relation.target}`);
57
+ if (!slideFile)
58
+ return null;
59
+ const slideContent = await this.getFileContent(slideFile);
60
+ return {
61
+ id: relation.id,
62
+ path: slideFile.path,
63
+ xml: slideContent,
64
+ parsed: await this.parseXmlContent(slideContent),
65
+ };
66
+ }));
67
+ return {
68
+ presentation: {
69
+ path: "ppt/presentation.xml",
70
+ xml: presentationContent,
71
+ parsed: presentationData,
72
+ },
73
+ relationships: {
74
+ path: "ppt/_rels/presentation.xml.rels",
75
+ xml: relationshipsContent,
76
+ parsed: relationshipsData,
77
+ },
78
+ slides: slides.filter((slide) => slide !== null),
79
+ };
80
+ }
81
+ catch (error) {
82
+ throw new Error(`Failed to parse PPTX: ${error.message}`);
83
+ }
84
+ }
85
+ /**
86
+ * Extracts content from a file within the PPTX archive
87
+ *
88
+ * @param file - A file from the unzipper library
89
+ * @returns Promise<string> - The file's content as a string
90
+ */
91
+ async getFileContent(file) {
92
+ return new Promise((resolve, reject) => {
93
+ let data = "";
94
+ file
95
+ .stream()
96
+ .on("data", (chunk) => (data += chunk))
97
+ .on("end", () => resolve(data))
98
+ .on("error", reject);
99
+ });
100
+ }
101
+ /**
102
+ * Parses XML content into a JavaScript object
103
+ *
104
+ * @param xmlContent - Raw XML string to parse
105
+ * @returns Promise<any> - Parsed JavaScript object
106
+ */
107
+ async parseXmlContent(xmlContent) {
108
+ return new Promise((resolve, reject) => {
109
+ xml2js.parseString(xmlContent, (err, result) => {
110
+ if (err)
111
+ reject(err);
112
+ else
113
+ resolve(result);
114
+ });
115
+ });
116
+ }
117
+ /**
118
+ * Extracts slide relations from the presentation relationships XML
119
+ *
120
+ * In PPTX files, slides are referenced by relationships in the presentation.xml.rels file.
121
+ * This method finds all slide references in these relationships.
122
+ *
123
+ * @param relationshipsData - Parsed relationship XML data
124
+ * @returns SlideRelation[] - Array of slide relations
125
+ */
126
+ getSlideRelations(relationshipsData) {
127
+ const relationships = relationshipsData["Relationships"]["Relationship"];
128
+ return relationships
129
+ .filter((rel) => rel["$"]["Type"].endsWith("/slide"))
130
+ .map((rel) => ({
131
+ id: rel["$"]["Id"],
132
+ target: rel["$"]["Target"],
133
+ }));
134
+ }
135
+ /**
136
+ * Extracts formatted text content from all slides
137
+ *
138
+ * This is a convenience method that:
139
+ * 1. Parses the entire presentation
140
+ * 2. Extracts text from each slide
141
+ * 3. Preserves formatting and line breaks
142
+ *
143
+ * @returns Promise<SlideTextContent[]> - Array of slide text content
144
+ */
145
+ async extractText() {
146
+ const parsed = await this.parse();
147
+ const textContent = [];
148
+ for (const slide of parsed.slides) {
149
+ const slideText = this.extractTextFromSlide(slide.parsed);
150
+ textContent.push({
151
+ ...slide,
152
+ text: slideText,
153
+ });
154
+ }
155
+ return textContent;
156
+ }
157
+ /**
158
+ * Extracts text content from a single slide while preserving formatting
159
+ *
160
+ * PowerPoint slide XML structure:
161
+ * - p:sp: Shape elements that can contain text
162
+ * - p:txBody: The text body within a shape
163
+ * - a:p: Individual paragraphs
164
+ * - a:r: Text runs within paragraphs
165
+ * - a:t: Actual text content
166
+ * - a:br: Line breaks
167
+ * - a:endParaRPr: Paragraph end markers
168
+ *
169
+ * @param slideData - Parsed slide XML data
170
+ * @returns string[] - Array of text blocks with preserved formatting
171
+ */
172
+ extractTextFromSlide(slideData) {
173
+ const texts = [];
174
+ // Navigate the XML structure to find text elements
175
+ if (slideData["p:sld"] &&
176
+ slideData["p:sld"]["p:cSld"] &&
177
+ slideData["p:sld"]["p:cSld"][0]["p:spTree"]) {
178
+ const spTree = slideData["p:sld"]["p:cSld"][0]["p:spTree"][0];
179
+ if (spTree["p:sp"]) {
180
+ // Process each shape that might contain text
181
+ spTree["p:sp"].forEach((shape) => {
182
+ if (shape["p:txBody"]) {
183
+ shape["p:txBody"].forEach((textBody) => {
184
+ if (textBody["a:p"]) {
185
+ const paragraphTexts = [];
186
+ // Process each paragraph
187
+ textBody["a:p"].forEach((paragraph) => {
188
+ const paragraphText = [];
189
+ // Extract text from runs
190
+ if (paragraph["a:r"]) {
191
+ paragraph["a:r"].forEach((run) => {
192
+ if (run["a:t"]) {
193
+ paragraphText.push(run["a:t"][0]);
194
+ }
195
+ });
196
+ }
197
+ // Handle explicit line breaks
198
+ if (paragraph["a:br"]) {
199
+ paragraphText.push("\n");
200
+ }
201
+ // Handle paragraph breaks
202
+ if (paragraphText.length === 0 || paragraph["a:endParaRPr"]) {
203
+ paragraphText.push("\n");
204
+ }
205
+ if (paragraphText.length > 0) {
206
+ paragraphTexts.push(paragraphText.join(""));
207
+ }
208
+ });
209
+ if (paragraphTexts.length > 0) {
210
+ texts.push(paragraphTexts.join("\n"));
211
+ }
212
+ }
213
+ });
214
+ }
215
+ });
216
+ }
217
+ }
218
+ return texts;
219
+ }
220
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,87 @@
1
+ import { ParsedPresentation, SlideTextContent } from "./types";
2
+ /**
3
+ * PptxParser - A class for parsing PowerPoint (PPTX) files and extracting their content
4
+ *
5
+ * This parser can:
6
+ * - Extract raw XML content from PPTX files
7
+ * - Parse the XML into JavaScript objects
8
+ * - Extract formatted text content from slides
9
+ * - Preserve line breaks and paragraph formatting
10
+ *
11
+ * PPTX files are essentially ZIP archives containing XML files. The main files we care about are:
12
+ * - presentation.xml: Contains the main presentation structure
13
+ * - _rels/presentation.xml.rels: Contains relationships between presentation parts
14
+ * - slides/slide*.xml: Contains individual slide content
15
+ */
16
+ export default class PptxParser {
17
+ private filePath;
18
+ /**
19
+ * Creates a new instance of PptxParser
20
+ * @param filePath - Path to the PPTX file to be parsed
21
+ */
22
+ constructor(filePath: string);
23
+ /**
24
+ * Parses the entire PPTX file and returns its content
25
+ *
26
+ * This method:
27
+ * 1. Opens the PPTX file as a ZIP archive
28
+ * 2. Extracts and parses the presentation.xml
29
+ * 3. Extracts and parses the relationship file
30
+ * 4. Finds and parses all slides
31
+ *
32
+ * @returns Promise<ParsedPresentation> - Object containing parsed presentation data
33
+ * @throws Error if the PPTX file is invalid or cannot be parsed
34
+ */
35
+ parse(): Promise<ParsedPresentation>;
36
+ /**
37
+ * Extracts content from a file within the PPTX archive
38
+ *
39
+ * @param file - A file from the unzipper library
40
+ * @returns Promise<string> - The file's content as a string
41
+ */
42
+ private getFileContent;
43
+ /**
44
+ * Parses XML content into a JavaScript object
45
+ *
46
+ * @param xmlContent - Raw XML string to parse
47
+ * @returns Promise<any> - Parsed JavaScript object
48
+ */
49
+ private parseXmlContent;
50
+ /**
51
+ * Extracts slide relations from the presentation relationships XML
52
+ *
53
+ * In PPTX files, slides are referenced by relationships in the presentation.xml.rels file.
54
+ * This method finds all slide references in these relationships.
55
+ *
56
+ * @param relationshipsData - Parsed relationship XML data
57
+ * @returns SlideRelation[] - Array of slide relations
58
+ */
59
+ private getSlideRelations;
60
+ /**
61
+ * Extracts formatted text content from all slides
62
+ *
63
+ * This is a convenience method that:
64
+ * 1. Parses the entire presentation
65
+ * 2. Extracts text from each slide
66
+ * 3. Preserves formatting and line breaks
67
+ *
68
+ * @returns Promise<SlideTextContent[]> - Array of slide text content
69
+ */
70
+ extractText(): Promise<SlideTextContent[]>;
71
+ /**
72
+ * Extracts text content from a single slide while preserving formatting
73
+ *
74
+ * PowerPoint slide XML structure:
75
+ * - p:sp: Shape elements that can contain text
76
+ * - p:txBody: The text body within a shape
77
+ * - a:p: Individual paragraphs
78
+ * - a:r: Text runs within paragraphs
79
+ * - a:t: Actual text content
80
+ * - a:br: Line breaks
81
+ * - a:endParaRPr: Paragraph end markers
82
+ *
83
+ * @param slideData - Parsed slide XML data
84
+ * @returns string[] - Array of text blocks with preserved formatting
85
+ */
86
+ private extractTextFromSlide;
87
+ }
@@ -0,0 +1,26 @@
1
+ export interface SlideRelation {
2
+ id: string;
3
+ target: string;
4
+ }
5
+ export interface ParsedSlide {
6
+ id: string;
7
+ path: string;
8
+ xml: string;
9
+ parsed: any;
10
+ }
11
+ export interface ParsedPresentation {
12
+ presentation: {
13
+ path: string;
14
+ xml: string;
15
+ parsed: any;
16
+ };
17
+ relationships: {
18
+ path: string;
19
+ xml: string;
20
+ parsed: any;
21
+ };
22
+ slides: ParsedSlide[];
23
+ }
24
+ export interface SlideTextContent extends ParsedSlide {
25
+ text: string[];
26
+ }
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "node-pptx-parser",
3
+ "version": "1.0.0",
4
+ "description": "A PowerPoint (PPTX) parser that extracts text content with preserved formatting",
5
+ "homepage": "https://github.com/Mirza-Glitch/node-pptx-parser.git",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Mirza-Glitch/node-pptx-parser.git"
9
+ },
10
+ "keywords": [
11
+ "pptx",
12
+ "powerpoint",
13
+ "parser",
14
+ "text",
15
+ "extract"
16
+ ],
17
+ "author": "Mirza-Glitch",
18
+ "main": "./dist/cjs/index.js",
19
+ "module": "./dist/esm/index.mjs",
20
+ "types": "./dist/types/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "require": "./dist/cjs/index.js",
24
+ "import": "./dist/esm/index.mjs"
25
+ }
26
+ },
27
+ "scripts": {
28
+ "build:cjs": "tsc -p tsconfig.cjs.json",
29
+ "build:esm": "tsc -p tsconfig.esm.json && npm run rename:esm",
30
+ "build": "npm run build:cjs && npm run build:esm",
31
+ "clean": "rimraf dist",
32
+ "rename:esm": "bash ./scripts/fix-mjs.sh",
33
+ "prepack": "npm run clean && npm run build"
34
+ },
35
+ "dependencies": {
36
+ "unzipper": "^0.12.3",
37
+ "xml2js": "^0.6.2"
38
+ },
39
+ "devDependencies": {
40
+ "@types/node": "^22.13.4",
41
+ "@types/unzipper": "^0.10.10",
42
+ "@types/xml2js": "^0.4.14",
43
+ "rimraf": "^6.0.1",
44
+ "typescript": "^5.7.3"
45
+ },
46
+ "license": "MIT",
47
+ "files": [
48
+ "dist",
49
+ "LICENSE",
50
+ "README.md"
51
+ ]
52
+ }