Files
docx-js/docs/usage/styling-with-xml.md

53 lines
1.8 KiB
Markdown
Raw Normal View History

2018-08-04 03:28:27 +01:00
# Styling with XML
## Setup
1. Create a new word document in Microsoft Word
2021-03-25 19:21:27 +03:00
2. Customize the styles on the Ribbon Bar.
2018-08-04 03:28:27 +01:00
For example, modify the `Normal`, `Heading 1`, `Heading 2` like so:
![image](https://user-images.githubusercontent.com/2917613/41195113-65edebfa-6c1f-11e8-97b4-77de2d60044a.png)
![image](https://user-images.githubusercontent.com/2917613/41195126-ca99c36c-6c1f-11e8-9e58-19e5f69b3b87.png)
2023-09-10 15:57:48 +02:00
*Note*: Font and color selection from the theme are currently not supported.
2018-08-04 03:28:27 +01:00
3. You can even create a totally new `Style`:
![image](https://user-images.githubusercontent.com/2917613/41195135-f0f7862a-6c1f-11e8-8be4-dd6d8fe5be03.png)
![image](https://user-images.githubusercontent.com/2917613/41195139-0ec52130-6c20-11e8-8fae-f6b44b43fdf8.png)
2023-09-10 15:57:48 +02:00
*Note*: When selecting the style type, it is important to consider the component being used.
2018-08-04 03:28:27 +01:00
4. Save
5. Re-name the saved `.docx` file to `.zip` and un-zip
6. Find `styles.xml`
![image](https://user-images.githubusercontent.com/2917613/41195178-bb9ba9c4-6c20-11e8-850e-a7a6ada9a2f6.png)
## Usage
Read the styles using `fs`, and put it into the `Document` object in the constructor:
```ts
2018-08-04 03:28:27 +01:00
const styles = fs.readFileSync("./styles.xml", "utf-8");
const doc = new docx.Document({
title: "Title",
externalStyles: styles,
});
```
You can use paragraphs, `heading1()`, `heading2()` etc and it will be styled according to your `styles.xml` created earlier. You can even use your new style you made by calling the `style` method:
```ts
2018-08-04 03:28:27 +01:00
doc.createParagraph("Cool Heading Text").heading1();
const paragraph = new docx.Paragraph('This is a custom named style from the template "Cool New Style"');
2018-08-04 03:28:27 +01:00
paragraph.style("Cool New Style");
2019-06-25 23:17:56 +01:00
doc.add(paragraph);
2018-08-04 03:28:27 +01:00
doc.createParagraph("Some normal text");
```
2019-08-20 22:23:14 +01:00
Example: https://github.com/dolanmiu/docx/blob/master/demo/13-xml-styles.ts