From 099c86ab5fabea429eb226fbff179f0317ec755c Mon Sep 17 00:00:00 2001 From: Michael Williamson Date: Sat, 30 Mar 2013 22:26:18 +0000 Subject: Read style names from paragraph properties --- lib/docx-reader.js | 34 ++++++++++++++++++++++- tests/docx-reader.tests.js | 20 +++++++++++++ tests/test-data/paragraphStyles/word/document.xml | 21 ++++++++++++++ 3 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 tests/test-data/paragraphStyles/word/document.xml diff --git a/lib/docx-reader.js b/lib/docx-reader.js index 3078d2f..606c61b 100644 --- a/lib/docx-reader.js +++ b/lib/docx-reader.js @@ -53,7 +53,30 @@ function readXmlElement(element) { var xmlElementReaders = { "w:p": function(element) { var children = readXmlElements(element.children); - return new documents.Paragraph(children); + var properties; + var propertiesElement = _.find(children, isParagraphProperties); + if (propertiesElement) { + properties = propertiesElement.properties; + } + + return new documents.Paragraph( + children.filter(negate(isParagraphProperties)), + properties + ); + }, + "w:pPr": function(element) { + var properties = { + }; + + var styleElement = element.first("w:pStyle"); + if (styleElement) { + properties.styleName = styleElement.attributes["w:val"]; + } + + return { + type: "paragraphProperties", + properties: properties + }; }, "w:r": function(element) { var children = readXmlElements(element.children); @@ -72,3 +95,12 @@ function notNull(value) { return value !== null; } +function isParagraphProperties(element) { + return element.type === "paragraphProperties"; +} + +function negate(predicate) { + return function(value) { + return !predicate(value); + }; +} diff --git a/tests/docx-reader.tests.js b/tests/docx-reader.tests.js index b7e1c29..c486f3b 100644 --- a/tests/docx-reader.tests.js +++ b/tests/docx-reader.tests.js @@ -25,4 +25,24 @@ describe("docx-reader", function() { assert.deepEqual(expectedDocument, result); }); }); + + test("can read paragraph styles", function() { + var docxFile = createFakeDocxFile({ + "word/document.xml": testData("paragraphStyles/word/document.xml") + }); + return docxReader.read(docxFile).then(function(result) { + var paragraph = result.children[0]; + assert.deepEqual({styleName: "Heading1"}, paragraph.properties); + }); + }); + + test("paragraph properties are not included as child of paragraph", function() { + var docxFile = createFakeDocxFile({ + "word/document.xml": testData("paragraphStyles/word/document.xml") + }); + return docxReader.read(docxFile).then(function(result) { + var paragraph = result.children[0]; + assert.equal(1, paragraph.children.length); + }); + }); }); diff --git a/tests/test-data/paragraphStyles/word/document.xml b/tests/test-data/paragraphStyles/word/document.xml new file mode 100644 index 0000000..f7ab26d --- /dev/null +++ b/tests/test-data/paragraphStyles/word/document.xml @@ -0,0 +1,21 @@ + + + + + + + + + Hello. + + + + + + + + + + + + -- cgit v1.2.3