Files
docx-js/src/file/styles/external-styles-factory.ts

49 lines
1.7 KiB
TypeScript
Raw Normal View History

2018-10-17 09:15:32 +03:00
import { convertToXmlComponent, ImportedRootElementAttributes, ImportedXmlComponent } from "file/xml-components";
import { Element as XMLElement, xml2js } from "xml-js";
2018-06-09 23:49:01 +01:00
import { Styles } from "./";
export class ExternalStylesFactory {
/**
* Creates new Style based on the given styles.
* Parses the styles and convert them to XmlComponent.
* Example content from styles.xml:
* <?xml version="1.0">
* <w:styles xmlns:mc="some schema" ...>
*
* <w:style w:type="paragraph" w:styleId="Heading1">
* <w:name w:val="heading 1"/>
* .....
* </w:style>
*
* <w:style w:type="paragraph" w:styleId="Heading2">
* <w:name w:val="heading 2"/>
* .....
* </w:style>
*
* <w:docDefaults>Or any other element will be parsed to</w:docDefaults>
*
* </w:styles>
* @param externalStyles context from styles.xml
*/
2018-10-17 09:15:32 +03:00
public newInstance(xmlData: string): Styles {
const xmlObj = xml2js(xmlData, { compact: false }) as XMLElement;
2018-10-17 09:15:32 +03:00
let stylesXmlElement: XMLElement | undefined;
for (const xmlElm of xmlObj.elements || []) {
if (xmlElm.name === "w:styles") {
stylesXmlElement = xmlElm;
}
}
if (stylesXmlElement === undefined) {
throw new Error("can not find styles element");
}
2018-10-17 09:15:32 +03:00
const importedStyle = new Styles(new ImportedRootElementAttributes(stylesXmlElement.attributes));
const stylesElements = stylesXmlElement.elements || [];
for (const childElm of stylesElements) {
importedStyle.push(convertToXmlComponent(childElm) as ImportedXmlComponent);
}
return importedStyle;
}
}