Make .addSection fully declarative

This commit is contained in:
Dolan
2021-03-19 20:53:56 +00:00
parent 4783812044
commit 3299c557a0
86 changed files with 3341 additions and 3278 deletions

8
.nycrc
View File

@ -1,9 +1,9 @@
{ {
"check-coverage": true, "check-coverage": true,
"lines": 98.79, "lines": 98.86,
"functions": 97.54, "functions": 97.86,
"branches": 95.64, "branches": 95.86,
"statements": 98.8, "statements": 98.86,
"include": [ "include": [
"src/**/*.ts" "src/**/*.ts"
], ],

View File

@ -3,24 +3,26 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, Packer, Paragraph, TextRun } from "../build"; import { Document, Packer, Paragraph, TextRun } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
properties: {}, properties: {},
children: [
new Paragraph({
children: [ children: [
new TextRun("Hello World"), new Paragraph({
new TextRun({ children: [
text: "Foo Bar", new TextRun("Hello World"),
bold: true, new TextRun({
}), text: "Foo Bar",
new TextRun({ bold: true,
text: "\tGithub is the best", }),
bold: true, new TextRun({
text: "\tGithub is the best",
bold: true,
}),
],
}), }),
], ],
}), },
], ],
}); });

View File

@ -129,70 +129,76 @@ const achievements = [
class DocumentCreator { class DocumentCreator {
// tslint:disable-next-line: typedef // tslint:disable-next-line: typedef
public create([experiences, educations, skills, achivements]): Document { public create([experiences, educations, skills, achivements]): Document {
const document = new Document(); const document = new Document({
sections: [
{
children: [
new Paragraph({
text: "Dolan Miu",
heading: HeadingLevel.TITLE,
}),
this.createContactInfo(PHONE_NUMBER, PROFILE_URL, EMAIL),
this.createHeading("Education"),
...educations
.map((education) => {
const arr: Paragraph[] = [];
arr.push(
this.createInstitutionHeader(
education.schoolName,
`${education.startDate.year} - ${education.endDate.year}`,
),
);
arr.push(this.createRoleText(`${education.fieldOfStudy} - ${education.degree}`));
document.addSection({ const bulletPoints = this.splitParagraphIntoBullets(education.notes);
children: [ bulletPoints.forEach((bulletPoint) => {
new Paragraph({ arr.push(this.createBullet(bulletPoint));
text: "Dolan Miu", });
heading: HeadingLevel.TITLE,
}),
this.createContactInfo(PHONE_NUMBER, PROFILE_URL, EMAIL),
this.createHeading("Education"),
...educations
.map((education) => {
const arr: Paragraph[] = [];
arr.push(
this.createInstitutionHeader(education.schoolName, `${education.startDate.year} - ${education.endDate.year}`),
);
arr.push(this.createRoleText(`${education.fieldOfStudy} - ${education.degree}`));
const bulletPoints = this.splitParagraphIntoBullets(education.notes); return arr;
bulletPoints.forEach((bulletPoint) => { })
arr.push(this.createBullet(bulletPoint)); .reduce((prev, curr) => prev.concat(curr), []),
}); this.createHeading("Experience"),
...experiences
.map((position) => {
const arr: Paragraph[] = [];
return arr; arr.push(
}) this.createInstitutionHeader(
.reduce((prev, curr) => prev.concat(curr), []), position.company.name,
this.createHeading("Experience"), this.createPositionDateText(position.startDate, position.endDate, position.isCurrent),
...experiences ),
.map((position) => { );
const arr: Paragraph[] = []; arr.push(this.createRoleText(position.title));
arr.push( const bulletPoints = this.splitParagraphIntoBullets(position.summary);
this.createInstitutionHeader(
position.company.name,
this.createPositionDateText(position.startDate, position.endDate, position.isCurrent),
),
);
arr.push(this.createRoleText(position.title));
const bulletPoints = this.splitParagraphIntoBullets(position.summary); bulletPoints.forEach((bulletPoint) => {
arr.push(this.createBullet(bulletPoint));
});
bulletPoints.forEach((bulletPoint) => { return arr;
arr.push(this.createBullet(bulletPoint)); })
}); .reduce((prev, curr) => prev.concat(curr), []),
this.createHeading("Skills, Achievements and Interests"),
return arr; this.createSubHeading("Skills"),
}) this.createSkillList(skills),
.reduce((prev, curr) => prev.concat(curr), []), this.createSubHeading("Achievements"),
this.createHeading("Skills, Achievements and Interests"), ...this.createAchivementsList(achivements),
this.createSubHeading("Skills"), this.createSubHeading("Interests"),
this.createSkillList(skills), this.createInterests("Programming, Technology, Music Production, Web Design, 3D Modelling, Dancing."),
this.createSubHeading("Achievements"), this.createHeading("References"),
...this.createAchivementsList(achivements), new Paragraph(
this.createSubHeading("Interests"), "Dr. Dean Mohamedally Director of Postgraduate Studies Department of Computer Science, University College London Malet Place, Bloomsbury, London WC1E d.mohamedally@ucl.ac.uk",
this.createInterests("Programming, Technology, Music Production, Web Design, 3D Modelling, Dancing."), ),
this.createHeading("References"), new Paragraph("More references upon request"),
new Paragraph( new Paragraph({
"Dr. Dean Mohamedally Director of Postgraduate Studies Department of Computer Science, University College London Malet Place, Bloomsbury, London WC1E d.mohamedally@ucl.ac.uk", text:
), "This CV was generated in real-time based on my Linked-In profile from my personal website www.dolan.bio.",
new Paragraph("More references upon request"), alignment: AlignmentType.CENTER,
new Paragraph({ }),
text: "This CV was generated in real-time based on my Linked-In profile from my personal website www.dolan.bio.", ],
alignment: AlignmentType.CENTER, },
}),
], ],
}); });

View File

@ -17,6 +17,39 @@ import {
UnderlineType, UnderlineType,
} from "../build"; } from "../build";
const table = new Table({
rows: [
new TableRow({
children: [
new TableCell({
children: [new Paragraph("Test cell 1.")],
}),
],
}),
new TableRow({
children: [
new TableCell({
children: [new Paragraph("Test cell 2.")],
}),
],
}),
new TableRow({
children: [
new TableCell({
children: [new Paragraph("Test cell 3.")],
}),
],
}),
new TableRow({
children: [
new TableCell({
children: [new Paragraph("Test cell 4.")],
}),
],
}),
],
});
const doc = new Document({ const doc = new Document({
styles: { styles: {
default: { default: {
@ -124,139 +157,107 @@ const doc = new Document({
}, },
], ],
}, },
}); sections: [
{
const table = new Table({ properties: {
rows: [ top: 700,
new TableRow({ right: 700,
children: [ bottom: 700,
new TableCell({ left: 700,
children: [new Paragraph("Test cell 1.")], },
footers: {
default: new Footer({
children: [
new Paragraph({
text: "1",
style: "normalPara",
alignment: AlignmentType.RIGHT,
}),
],
}), }),
], },
}),
new TableRow({
children: [
new TableCell({
children: [new Paragraph("Test cell 2.")],
}),
],
}),
new TableRow({
children: [
new TableCell({
children: [new Paragraph("Test cell 3.")],
}),
],
}),
new TableRow({
children: [
new TableCell({
children: [new Paragraph("Test cell 4.")],
}),
],
}),
],
});
doc.addSection({
properties: {
top: 700,
right: 700,
bottom: 700,
left: 700,
},
footers: {
default: new Footer({
children: [ children: [
new Paragraph({ new Paragraph({
text: "1", children: [
new ImageRun({
data: fs.readFileSync("./demo/images/pizza.gif"),
transformation: {
width: 100,
height: 100,
},
}),
],
}),
new Paragraph({
text: "HEADING",
heading: HeadingLevel.HEADING_1,
alignment: AlignmentType.CENTER,
}),
new Paragraph({
text: "Ref. :",
style: "normalPara", style: "normalPara",
alignment: AlignmentType.RIGHT, }),
new Paragraph({
text: "Date :",
style: "normalPara",
}),
new Paragraph({
text: "To,",
style: "normalPara",
}),
new Paragraph({
text: "The Superindenting Engineer,(O &M)",
style: "normalPara",
}),
new Paragraph({
text: "Sub : ",
style: "normalPara",
}),
new Paragraph({
text: "Ref. : ",
style: "normalPara",
}),
new Paragraph({
text: "Sir,",
style: "normalPara",
}),
new Paragraph({
text: "BRIEF DESCRIPTION",
style: "normalPara",
}),
table,
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/pizza.gif"),
transformation: {
width: 100,
height: 100,
},
}),
],
}),
new Paragraph({
text: "Test",
style: "normalPara2",
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/pizza.gif"),
transformation: {
width: 100,
height: 100,
},
}),
],
}),
new Paragraph({
text: "Test 2",
style: "normalPara2",
}), }),
], ],
}), },
},
children: [
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/pizza.gif"),
transformation: {
width: 100,
height: 100,
},
}),
],
}),
new Paragraph({
text: "HEADING",
heading: HeadingLevel.HEADING_1,
alignment: AlignmentType.CENTER,
}),
new Paragraph({
text: "Ref. :",
style: "normalPara",
}),
new Paragraph({
text: "Date :",
style: "normalPara",
}),
new Paragraph({
text: "To,",
style: "normalPara",
}),
new Paragraph({
text: "The Superindenting Engineer,(O &M)",
style: "normalPara",
}),
new Paragraph({
text: "Sub : ",
style: "normalPara",
}),
new Paragraph({
text: "Ref. : ",
style: "normalPara",
}),
new Paragraph({
text: "Sir,",
style: "normalPara",
}),
new Paragraph({
text: "BRIEF DESCRIPTION",
style: "normalPara",
}),
table,
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/pizza.gif"),
transformation: {
width: 100,
height: 100,
},
}),
],
}),
new Paragraph({
text: "Test",
style: "normalPara2",
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/pizza.gif"),
transformation: {
width: 100,
height: 100,
},
}),
],
}),
new Paragraph({
text: "Test 2",
style: "normalPara2",
}),
], ],
}); });

View File

@ -3,55 +3,57 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, ImageRun, Packer, Paragraph } from "../build"; import { Document, ImageRun, Packer, Paragraph } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
children: [
new Paragraph("Hello World"),
new Paragraph({
children: [ children: [
new ImageRun({ new Paragraph("Hello World"),
data: fs.readFileSync("./demo/images/pizza.gif"), new Paragraph({
transformation: { children: [
width: 50, new ImageRun({
height: 50, data: fs.readFileSync("./demo/images/pizza.gif"),
}, transformation: {
width: 50,
height: 50,
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/pizza.gif"),
transformation: {
width: 100,
height: 100,
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/pizza.gif"),
transformation: {
width: 250,
height: 250,
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/pizza.gif"),
transformation: {
width: 400,
height: 400,
},
}),
],
}), }),
], ],
}), },
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/pizza.gif"),
transformation: {
width: 100,
height: 100,
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/pizza.gif"),
transformation: {
width: 250,
height: 250,
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/pizza.gif"),
transformation: {
width: 400,
height: 400,
},
}),
],
}),
], ],
}); });

View File

@ -7,23 +7,24 @@ const styles = fs.readFileSync("./demo/assets/custom-styles.xml", "utf-8");
const doc = new Document({ const doc = new Document({
title: "Title", title: "Title",
externalStyles: styles, externalStyles: styles,
}); sections: [
{
doc.addSection({ children: [
children: [ new Paragraph({
new Paragraph({ text: "Cool Heading Text",
text: "Cool Heading Text", heading: HeadingLevel.HEADING_1,
heading: HeadingLevel.HEADING_1, }),
}), new Paragraph({
new Paragraph({ text: 'This is a custom named style from the template "MyFancyStyle"',
text: 'This is a custom named style from the template "MyFancyStyle"', style: "MyFancyStyle",
style: "MyFancyStyle", }),
}), new Paragraph("Some normal text"),
new Paragraph("Some normal text"), new Paragraph({
new Paragraph({ text: "MyFancyStyle again",
text: "MyFancyStyle again", style: "MyFancyStyle",
style: "MyFancyStyle", }),
}), ],
},
], ],
}); });

View File

@ -3,73 +3,75 @@
import * as fs from "fs"; import * as fs from "fs";
import { AlignmentType, Document, Footer, Header, Packer, PageBreak, PageNumber, Paragraph, TextRun } from "../build"; import { AlignmentType, Document, Footer, Header, Packer, PageBreak, PageNumber, Paragraph, TextRun } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
properties: { properties: {
titlePage: true, titlePage: true,
}, },
headers: { headers: {
default: new Header({ default: new Header({
children: [
new Paragraph({
alignment: AlignmentType.RIGHT,
children: [ children: [
new TextRun("My Title "), new Paragraph({
new TextRun({ alignment: AlignmentType.RIGHT,
children: ["Page ", PageNumber.CURRENT], children: [
new TextRun("My Title "),
new TextRun({
children: ["Page ", PageNumber.CURRENT],
}),
],
}), }),
], ],
}), }),
], first: new Header({
}),
first: new Header({
children: [
new Paragraph({
alignment: AlignmentType.RIGHT,
children: [ children: [
new TextRun("First Page Header "), new Paragraph({
new TextRun({ alignment: AlignmentType.RIGHT,
children: ["Page ", PageNumber.CURRENT], children: [
new TextRun("First Page Header "),
new TextRun({
children: ["Page ", PageNumber.CURRENT],
}),
],
}), }),
], ],
}), }),
], },
}), footers: {
}, default: new Footer({
footers: {
default: new Footer({
children: [
new Paragraph({
alignment: AlignmentType.RIGHT,
children: [ children: [
new TextRun("My Title "), new Paragraph({
new TextRun({ alignment: AlignmentType.RIGHT,
children: ["Footer - Page ", PageNumber.CURRENT], children: [
new TextRun("My Title "),
new TextRun({
children: ["Footer - Page ", PageNumber.CURRENT],
}),
],
}), }),
], ],
}), }),
], first: new Footer({
}),
first: new Footer({
children: [
new Paragraph({
alignment: AlignmentType.RIGHT,
children: [ children: [
new TextRun("First Page Footer "), new Paragraph({
new TextRun({ alignment: AlignmentType.RIGHT,
children: ["Page ", PageNumber.CURRENT], children: [
new TextRun("First Page Footer "),
new TextRun({
children: ["Page ", PageNumber.CURRENT],
}),
],
}), }),
], ],
}), }),
},
children: [
new Paragraph({
children: [new TextRun("First Page"), new PageBreak()],
}),
new Paragraph("Second Page"),
], ],
}), },
},
children: [
new Paragraph({
children: [new TextRun("First Page"), new PageBreak()],
}),
new Paragraph("Second Page"),
], ],
}); });

View File

@ -3,15 +3,17 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, Packer, Paragraph } from "../build"; import { Document, Packer, Paragraph } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
children: [ children: [
new Paragraph("Hello World"), new Paragraph("Hello World"),
new Paragraph({ new Paragraph({
text: "Hello World on another page", text: "Hello World on another page",
pageBreakBefore: true, pageBreakBefore: true,
}), }),
],
},
], ],
}); });

View File

@ -3,119 +3,118 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, Footer, Header, Packer, PageNumber, PageNumberFormat, PageOrientation, Paragraph, TextRun } from "../build"; import { Document, Footer, Header, Packer, PageNumber, PageNumberFormat, PageOrientation, Paragraph, TextRun } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
children: [new Paragraph("Hello World")], children: [new Paragraph("Hello World")],
}); },
{
doc.addSection({ headers: {
headers: { default: new Header({
default: new Header({ children: [new Paragraph("First Default Header on another page")],
children: [new Paragraph("First Default Header on another page")], }),
}), },
}, footers: {
footers: { default: new Footer({
default: new Footer({ children: [new Paragraph("Footer on another page")],
children: [new Paragraph("Footer on another page")], }),
}), },
}, properties: {
properties: { pageNumberStart: 1,
pageNumberStart: 1, pageNumberFormatType: PageNumberFormat.DECIMAL,
pageNumberFormatType: PageNumberFormat.DECIMAL, },
}, children: [new Paragraph("hello")],
children: [new Paragraph("hello")], },
}); {
headers: {
doc.addSection({ default: new Header({
headers: { children: [new Paragraph("Second Default Header on another page")],
default: new Header({ }),
children: [new Paragraph("Second Default Header on another page")], },
}), footers: {
}, default: new Footer({
footers: { children: [new Paragraph("Footer on another page")],
default: new Footer({ }),
children: [new Paragraph("Footer on another page")], },
}), size: {
}, orientation: PageOrientation.LANDSCAPE,
size: { },
orientation: PageOrientation.LANDSCAPE, properties: {
}, pageNumberStart: 1,
properties: { pageNumberFormatType: PageNumberFormat.DECIMAL,
pageNumberStart: 1, },
pageNumberFormatType: PageNumberFormat.DECIMAL, children: [new Paragraph("hello in landscape")],
}, },
children: [new Paragraph("hello in landscape")], {
}); headers: {
default: new Header({
doc.addSection({
headers: {
default: new Header({
children: [
new Paragraph({
children: [ children: [
new TextRun({ new Paragraph({
children: ["Page number: ", PageNumber.CURRENT], children: [
new TextRun({
children: ["Page number: ", PageNumber.CURRENT],
}),
],
}), }),
], ],
}), }),
], },
}), size: {
}, orientation: PageOrientation.PORTRAIT,
size: { },
orientation: PageOrientation.PORTRAIT, children: [new Paragraph("Page number in the header must be 2, because it continues from the previous section.")],
}, },
children: [new Paragraph("Page number in the header must be 2, because it continues from the previous section.")], {
}); headers: {
default: new Header({
doc.addSection({
headers: {
default: new Header({
children: [
new Paragraph({
children: [ children: [
new TextRun({ new Paragraph({
children: ["Page number: ", PageNumber.CURRENT], children: [
new TextRun({
children: ["Page number: ", PageNumber.CURRENT],
}),
],
}), }),
], ],
}), }),
], },
}), properties: {
}, pageNumberFormatType: PageNumberFormat.UPPER_ROMAN,
properties: { orientation: PageOrientation.PORTRAIT,
pageNumberFormatType: PageNumberFormat.UPPER_ROMAN, },
orientation: PageOrientation.PORTRAIT,
},
children: [
new Paragraph(
"Page number in the header must be III, because it continues from the previous section, but is defined as upper roman.",
),
],
});
doc.addSection({
headers: {
default: new Header({
children: [ children: [
new Paragraph({ new Paragraph(
"Page number in the header must be III, because it continues from the previous section, but is defined as upper roman.",
),
],
},
{
headers: {
default: new Header({
children: [ children: [
new TextRun({ new Paragraph({
children: ["Page number: ", PageNumber.CURRENT], children: [
new TextRun({
children: ["Page number: ", PageNumber.CURRENT],
}),
],
}), }),
], ],
}), }),
},
size: {
orientation: PageOrientation.PORTRAIT,
},
properties: {
pageNumberFormatType: PageNumberFormat.DECIMAL,
pageNumberStart: 25,
},
children: [
new Paragraph(
"Page number in the header must be 25, because it is defined to start at 25 and to be decimal in this section.",
),
], ],
}), },
},
size: {
orientation: PageOrientation.PORTRAIT,
},
properties: {
pageNumberFormatType: PageNumberFormat.DECIMAL,
pageNumberStart: 25,
},
children: [
new Paragraph("Page number in the header must be 25, because it is defined to start at 25 and to be decimal in this section."),
], ],
}); });

View File

@ -12,41 +12,41 @@ const doc = new Document({
5: { children: [new Paragraph("Test1")] }, 5: { children: [new Paragraph("Test1")] },
6: { children: [new Paragraph("My amazing reference1")] }, 6: { children: [new Paragraph("My amazing reference1")] },
}, },
}); sections: [
{
doc.addSection({
children: [
new Paragraph({
children: [ children: [
new TextRun({ new Paragraph({
children: ["Hello", new FootnoteReferenceRun(1)], children: [
new TextRun({
children: ["Hello", new FootnoteReferenceRun(1)],
}),
new TextRun({
children: [" World!", new FootnoteReferenceRun(2)],
}),
],
}), }),
new TextRun({ new Paragraph({
children: [" World!", new FootnoteReferenceRun(2)], children: [new TextRun("Hello World"), new FootnoteReferenceRun(3)],
}), }),
], ],
}), },
new Paragraph({ {
children: [new TextRun("Hello World"), new FootnoteReferenceRun(3)],
}),
],
});
doc.addSection({
children: [
new Paragraph({
children: [ children: [
new TextRun({ new Paragraph({
children: ["Hello", new FootnoteReferenceRun(4)], children: [
new TextRun({
children: ["Hello", new FootnoteReferenceRun(4)],
}),
new TextRun({
children: [" World!", new FootnoteReferenceRun(5)],
}),
],
}), }),
new TextRun({ new Paragraph({
children: [" World!", new FootnoteReferenceRun(5)], children: [new TextRun("Hello World"), new FootnoteReferenceRun(6)],
}), }),
], ],
}), },
new Paragraph({
children: [new TextRun("Hello World"), new FootnoteReferenceRun(6)],
}),
], ],
}); });

View File

@ -3,23 +3,25 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, ImageRun, Packer, Paragraph } from "../build"; import { Document, ImageRun, Packer, Paragraph } from "../build";
const doc = new Document();
const imageBase64Data = `iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAMAAAD04JH5AAACzVBMVEUAAAAAAAAAAAAAAAA/AD8zMzMqKiokJCQfHx8cHBwZGRkuFxcqFSonJyckJCQiIiIfHx8eHh4cHBwoGhomGSYkJCQhISEfHx8eHh4nHR0lHBwkGyQjIyMiIiIgICAfHx8mHh4lHh4kHR0jHCMiGyIhISEgICAfHx8lHx8kHh4jHR0hHCEhISEgICAlHx8kHx8jHh4jHh4iHSIhHCEhISElICAkHx8jHx8jHh4iHh4iHSIhHSElICAkICAjHx8jHx8iHh4iHh4hHiEhHSEkICAjHx8iHx8iHx8hHh4hHiEkHSEjHSAjHx8iHx8iHx8hHh4kHiEkHiEjHSAiHx8hHx8hHh4kHiEjHiAjHSAiHx8iHx8hHx8kHh4jHiEjHiAjHiAiICAiHx8kHx8jHh4jHiEjHiAiHiAiHSAiHx8jHx8jHx8jHiAiHiAiHiAiHSAiHx8jHx8jHx8iHiAiHiAiHiAjHx8jHx8jHx8jHx8iHiAiHiAiHiAjHx8jHx8jHx8iHx8iHSAiHiAjHiAjHx8jHx8hHx8iHx8iHyAiHiAjHiAjHiAjHh4hHx8iHx8iHx8iHyAjHSAjHiAjHiAjHh4hHx8iHx8iHx8jHyAjHiAhHh4iHx8iHx8jHyAjHSAjHSAhHiAhHh4iHx8iHx8jHx8jHyAjHSAjHSAiHh4iHh4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GK8XX4VA8QjEd7XrM3M0OXz8YCy+qKBLgq3wqnofiTorF0Ax56Rg1J1elW+BBAsVe+My6iYq7IK6keBdOIseV2qn5Pb8f3MqkWAXf9ThM8c8lAOIotuFsF875lRrH5klRcG0+xcPwQ1oLxfeRAP4heQTnGL78X2rqlw2DK59SXAV/zKaiGMAuko5InCt68mcOan5+ohf+z1pP8lQY/GHZQMV4YD3FpXDp4qerqbF/lBWBswyi+AL+ia+maLgcRRQj4IYlY/UpauqKBsPJAxQF8NM1TRQ/RudSPAD34rK3scOuR8/HGcspxsJfOVS8NZbiGXiUtPgINU3v3WFDmx8pEuG3EiqKKVbCC1vm2iZqap5LAtCtleQf8F9sFYWDohzeJczYyQ4V2bEZFGsQgJRGqqqhS2phHTWn9lDkIhBTqWqxQZ+IsRvtdHY9AvI2VX2hW68nfqGmuQsCEl3JdjfCF8OW1bPdtwhQ0gm2mQzfRE3a7KCYj0BNZJs8+Kxf/r6WtTEI2FIqlsMfFgRB5A6KUnSe/vUkX0AnuvUIt8SjM1m6wWQymUwmk8lkMgXRf5vi8rLQxtUhAAAAAElFTkSuQmCC`;
doc.addSection({ const doc = new Document({
children: [ sections: [
new Paragraph({ {
children: [ children: [
new ImageRun({ new Paragraph({
data: Buffer.from(imageBase64Data, "base64"), children: [
transformation: { new ImageRun({
width: 100, data: Buffer.from(imageBase64Data, "base64"),
height: 100, transformation: {
}, width: 100,
height: 100,
},
}),
],
}), }),
], ],
}), },
], ],
}); });

View File

@ -3,23 +3,25 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, Packer, Paragraph, TextRun } from "../build"; import { Document, Packer, Paragraph, TextRun } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
children: [
new Paragraph({
children: [ children: [
new TextRun("Hello World"), new Paragraph({
new TextRun({ children: [
text: "Foo", new TextRun("Hello World"),
bold: true, new TextRun({
}), text: "Foo",
new TextRun({ bold: true,
text: "\tBar", }),
bold: true, new TextRun({
text: "\tBar",
bold: true,
}),
],
}), }),
], ],
}), },
], ],
}); });

View File

@ -99,90 +99,91 @@ const doc = new Document({
}, },
], ],
}, },
}); sections: [
{
doc.addSection({
children: [
new Paragraph({
text: "Test heading1, bold and italicized",
heading: HeadingLevel.HEADING_1,
}),
new Paragraph("Some simple content"),
new Paragraph({
text: "Test heading2 with double red underline",
heading: HeadingLevel.HEADING_2,
}),
new Paragraph({
text: "Option1",
numbering: {
reference: "my-crazy-numbering",
level: 0,
},
style: "aside",
}),
new Paragraph({
text: "Option5 -- override 2 to 5",
numbering: {
reference: "my-crazy-numbering",
level: 0,
},
}),
new Paragraph({
text: "Option3",
numbering: {
reference: "my-crazy-numbering",
level: 0,
},
}),
new Paragraph({
children: [ children: [
new TextRun({ new Paragraph({
text: "Some monospaced content", text: "Test heading1, bold and italicized",
font: { heading: HeadingLevel.HEADING_1,
name: "Monospace", }),
new Paragraph("Some simple content"),
new Paragraph({
text: "Test heading2 with double red underline",
heading: HeadingLevel.HEADING_2,
}),
new Paragraph({
text: "Option1",
numbering: {
reference: "my-crazy-numbering",
level: 0,
},
style: "aside",
}),
new Paragraph({
text: "Option5 -- override 2 to 5",
numbering: {
reference: "my-crazy-numbering",
level: 0,
}, },
}), }),
], new Paragraph({
}), text: "Option3",
new Paragraph({ numbering: {
text: "An aside, in light gray italics and indented", reference: "my-crazy-numbering",
style: "aside", level: 0,
}), },
new Paragraph({
text: "This is normal, but well-spaced text",
style: "wellSpaced",
}),
new Paragraph({
children: [
new TextRun({
text: "This is a bold run,",
bold: true,
}), }),
new TextRun(" switching to normal "), new Paragraph({
new TextRun({ children: [
text: "and then underlined ", new TextRun({
underline: {}, text: "Some monospaced content",
font: {
name: "Monospace",
},
}),
],
}), }),
new TextRun({ new Paragraph({
text: "and then emphasis-mark ", text: "An aside, in light gray italics and indented",
emphasisMark: {}, style: "aside",
}), }),
new TextRun({ new Paragraph({
text: "and back to normal.", text: "This is normal, but well-spaced text",
style: "wellSpaced",
}),
new Paragraph({
children: [
new TextRun({
text: "This is a bold run,",
bold: true,
}),
new TextRun(" switching to normal "),
new TextRun({
text: "and then underlined ",
underline: {},
}),
new TextRun({
text: "and then emphasis-mark ",
emphasisMark: {},
}),
new TextRun({
text: "and back to normal.",
}),
],
}),
new Paragraph({
style: "Strong",
children: [
new TextRun({
text: "Strong Style",
}),
new TextRun({
text: " - Very strong.",
}),
],
}), }),
], ],
}), },
new Paragraph({
style: "Strong",
children: [
new TextRun({
text: "Strong Style",
}),
new TextRun({
text: " - Very strong.",
}),
],
}),
], ],
}); });

View File

@ -3,101 +3,105 @@
import * as fs from "fs"; import * as fs from "fs";
import { BorderStyle, Document, Packer, Paragraph, Table, TableCell, TableRow } from "../build"; import { BorderStyle, Document, Packer, Paragraph, Table, TableCell, TableRow } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
const table = new Table({ {
rows: [
new TableRow({
children: [ children: [
new TableCell({ new Table({
children: [], rows: [
}), new TableRow({
new TableCell({ children: [
children: [], new TableCell({
}), children: [],
new TableCell({ }),
children: [], new TableCell({
}), children: [],
new TableCell({ }),
children: [], new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
],
}),
new TableRow({
children: [
new TableCell({
children: [],
}),
new TableCell({
children: [new Paragraph("Hello")],
borders: {
top: {
style: BorderStyle.DASH_DOT_STROKED,
size: 3,
color: "red",
},
bottom: {
style: BorderStyle.DOUBLE,
size: 3,
color: "blue",
},
left: {
style: BorderStyle.DASH_DOT_STROKED,
size: 3,
color: "green",
},
right: {
style: BorderStyle.DASH_DOT_STROKED,
size: 3,
color: "#ff8000",
},
},
}),
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
],
}),
new TableRow({
children: [
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
],
}),
new TableRow({
children: [
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
],
}),
],
}), }),
], ],
}), },
new TableRow({
children: [
new TableCell({
children: [],
}),
new TableCell({
children: [new Paragraph("Hello")],
borders: {
top: {
style: BorderStyle.DASH_DOT_STROKED,
size: 3,
color: "red",
},
bottom: {
style: BorderStyle.DOUBLE,
size: 3,
color: "blue",
},
left: {
style: BorderStyle.DASH_DOT_STROKED,
size: 3,
color: "green",
},
right: {
style: BorderStyle.DASH_DOT_STROKED,
size: 3,
color: "#ff8000",
},
},
}),
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
],
}),
new TableRow({
children: [
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
],
}),
new TableRow({
children: [
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
],
}),
], ],
}); });
doc.addSection({ children: [table] });
Packer.toBuffer(doc).then((buffer) => { Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("My Document.docx", buffer); fs.writeFileSync("My Document.docx", buffer);
}); });

View File

@ -10,17 +10,45 @@ const doc = new Document({
creator: "Clippy", creator: "Clippy",
title: "Sample Document", title: "Sample Document",
description: "A brief example of using docx with bookmarks and internal hyperlinks", description: "A brief example of using docx with bookmarks and internal hyperlinks",
}); sections: [
{
doc.addSection({ footers: {
footers: { default: new Footer({
default: new Footer({ children: [
new Paragraph({
children: [
new InternalHyperlink({
child: new TextRun({
text: "Click here!",
style: "Hyperlink",
}),
anchor: "myAnchorId",
}),
],
}),
],
}),
},
children: [ children: [
new Paragraph({
heading: HeadingLevel.HEADING_1,
children: [
new Bookmark({
id: "myAnchorId",
children: [new TextRun("Lorem Ipsum")],
}),
],
}),
new Paragraph("\n"),
new Paragraph(LOREM_IPSUM),
new Paragraph({
children: [new PageBreak()],
}),
new Paragraph({ new Paragraph({
children: [ children: [
new InternalHyperlink({ new InternalHyperlink({
child: new TextRun({ child: new TextRun({
text: "Click here!", text: "Anchor Text",
style: "Hyperlink", style: "Hyperlink",
}), }),
anchor: "myAnchorId", anchor: "myAnchorId",
@ -28,34 +56,7 @@ doc.addSection({
], ],
}), }),
], ],
}), },
},
children: [
new Paragraph({
heading: HeadingLevel.HEADING_1,
children: [
new Bookmark({
id: "myAnchorId",
children: [new TextRun("Lorem Ipsum")],
}),
],
}),
new Paragraph("\n"),
new Paragraph(LOREM_IPSUM),
new Paragraph({
children: [new PageBreak()],
}),
new Paragraph({
children: [
new InternalHyperlink({
child: new TextRun({
text: "Anchor Text",
style: "Hyperlink",
}),
anchor: "myAnchorId",
}),
],
}),
], ],
}); });

View File

@ -3,64 +3,66 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, Packer, Paragraph, Table, TableCell, TableRow, TextRun } from "../build"; import { Document, Packer, Paragraph, Table, TableCell, TableRow, TextRun } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
children: [
new Paragraph({
bidirectional: true,
children: [ children: [
new TextRun({ new Paragraph({
text: "שלום עולם", bidirectional: true,
rightToLeft: true,
}),
],
}),
new Paragraph({
bidirectional: true,
children: [
new TextRun({
text: "שלום עולם",
bold: true,
rightToLeft: true,
}),
],
}),
new Paragraph({
bidirectional: true,
children: [
new TextRun({
text: "שלום עולם",
italics: true,
rightToLeft: true,
}),
],
}),
new Table({
visuallyRightToLeft: true,
rows: [
new TableRow({
children: [ children: [
new TableCell({ new TextRun({
children: [new Paragraph("שלום עולם")], text: "שלום עולם",
}), rightToLeft: true,
new TableCell({
children: [],
}), }),
], ],
}), }),
new TableRow({ new Paragraph({
bidirectional: true,
children: [ children: [
new TableCell({ new TextRun({
children: [], text: "שלום עולם",
bold: true,
rightToLeft: true,
}), }),
new TableCell({ ],
children: [new Paragraph("שלום עולם")], }),
new Paragraph({
bidirectional: true,
children: [
new TextRun({
text: "שלום עולם",
italics: true,
rightToLeft: true,
}),
],
}),
new Table({
visuallyRightToLeft: true,
rows: [
new TableRow({
children: [
new TableCell({
children: [new Paragraph("שלום עולם")],
}),
new TableCell({
children: [],
}),
],
}),
new TableRow({
children: [
new TableCell({
children: [],
}),
new TableCell({
children: [new Paragraph("שלום עולם")],
}),
],
}), }),
], ],
}), }),
], ],
}), },
], ],
}); });

View File

@ -3,79 +3,81 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, ImageRun, Packer, Paragraph, TextRun } from "../build"; import { Document, ImageRun, Packer, Paragraph, TextRun } from "../build";
const doc = new Document();
const imageBase64Data = `iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAMAAAD04JH5AAACzVBMVEUAAAAAAAAAAAAAAAA/AD8zMzMqKiokJCQfHx8cHBwZGRkuFxcqFSonJyckJCQiIiIfHx8eHh4cHBwoGhomGSYkJCQhISEfHx8eHh4nHR0lHBwkGyQjIyMiIiIgICAfHx8mHh4lHh4kHR0jHCMiGyIhISEgICAfHx8lHx8kHh4jHR0hHCEhISEgICAlHx8kHx8jHh4jHh4iHSIhHCEhISElICAkHx8jHx8jHh4iHh4iHSIhHSElICAkICAjHx8jHx8iHh4iHh4hHiEhHSEkICAjHx8iHx8iHx8hHh4hHiEkHSEjHSAjHx8iHx8iHx8hHh4kHiEkHiEjHSAiHx8hHx8hHh4kHiEjHiAjHSAiHx8iHx8hHx8kHh4jHiEjHiAjHiAiICAiHx8kHx8jHh4jHiEjHiAiHiAiHSAiHx8jHx8jHx8jHiAiHiAiHiAiHSAiHx8jHx8jHx8iHiAiHiAiHiAjHx8jHx8jHx8jHx8iHiAiHiAiHiAjHx8jHx8jHx8iHx8iHSAiHiAjHiAjHx8jHx8hHx8iHx8iHyAiHiAjHiAjHiAjHh4hHx8iHx8iHx8iHyAjHSAjHiAjHiAjHh4hHx8iHx8iHx8jHyAjHiAhHh4iHx8iHx8jHyAjHSAjHSAhHiAhHh4iHx8iHx8jHx8jHyAjHSAjHSAiHh4iHh4jHx8jHx8jHyAjHyAhHSAhHSAiHh4iHh4jHx8jHx8jHyAhHyAhHSAiHSAiHh4jHh4jHx8jHx8jHyAhHyAhHSAiHSAjHR4jHh4jHx8jHx8hHyAhHyAiH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lRrH5klRcG0+xcPwQ1oLxfeRAP4heQTnGL78X2rqlw2DK59SXAV/zKaiGMAuko5InCt68mcOan5+ohf+z1pP8lQY/GHZQMV4YD3FpXDp4qerqbF/lBWBswyi+AL+ia+maLgcRRQj4IYlY/UpauqKBsPJAxQF8NM1TRQ/RudSPAD34rK3scOuR8/HGcspxsJfOVS8NZbiGXiUtPgINU3v3WFDmx8pEuG3EiqKKVbCC1vm2iZqap5LAtCtleQf8F9sFYWDohzeJczYyQ4V2bEZFGsQgJRGqqqhS2phHTWn9lDkIhBTqWqxQZ+IsRvtdHY9AvI2VX2hW68nfqGmuQsCEl3JdjfCF8OW1bPdtwhQ0gm2mQzfRE3a7KCYj0BNZJs8+Kxf/r6WtTEI2FIqlsMfFgRB5A6KUnSe/vUkX0AnuvUIt8SjM1m6wWQymUwmk8lkMgXRf5vi8rLQxtUhAAAAAElFTkSuQmCC`;
doc.addSection({ const doc = new Document({
children: [ sections: [
new Paragraph({ {
children: [ children: [
new TextRun("Hello World"), new Paragraph({
new ImageRun({ children: [
data: fs.readFileSync("./demo/images/parrots.bmp"), new TextRun("Hello World"),
transformation: { new ImageRun({
width: 100, data: fs.readFileSync("./demo/images/parrots.bmp"),
height: 100, transformation: {
}, width: 100,
height: 100,
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/image1.jpeg"),
transformation: {
width: 100,
height: 100,
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/dog.png"),
transformation: {
width: 100,
height: 100,
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/cat.jpg"),
transformation: {
width: 100,
height: 100,
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/parrots.bmp"),
transformation: {
width: 100,
height: 100,
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: Buffer.from(imageBase64Data, "base64"),
transformation: {
width: 100,
height: 100,
},
}),
],
}), }),
], ],
}), },
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/image1.jpeg"),
transformation: {
width: 100,
height: 100,
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/dog.png"),
transformation: {
width: 100,
height: 100,
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/cat.jpg"),
transformation: {
width: 100,
height: 100,
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/parrots.bmp"),
transformation: {
width: 100,
height: 100,
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: Buffer.from(imageBase64Data, "base64"),
transformation: {
width: 100,
height: 100,
},
}),
],
}),
], ],
}); });

View File

@ -3,93 +3,95 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, ImageRun, Packer, Paragraph, Table, TableCell, TableRow } from "../build"; import { Document, ImageRun, Packer, Paragraph, Table, TableCell, TableRow } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
const table = new Table({ {
rows: [
new TableRow({
children: [ children: [
new TableCell({ new Table({
children: [], rows: [
}), new TableRow({
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
],
}),
new TableRow({
children: [
new TableCell({
children: [],
}),
new TableCell({
children: [
new Paragraph({
children: [ children: [
new ImageRun({ new TableCell({
data: fs.readFileSync("./demo/images/image1.jpeg"), children: [],
transformation: { }),
width: 100, new TableCell({
height: 100, children: [],
}, }),
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
],
}),
new TableRow({
children: [
new TableCell({
children: [],
}),
new TableCell({
children: [
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/image1.jpeg"),
transformation: {
width: 100,
height: 100,
},
}),
],
}),
],
}),
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
],
}),
new TableRow({
children: [
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
new TableCell({
children: [new Paragraph("Hello")],
}),
new TableCell({
children: [],
}),
],
}),
new TableRow({
children: [
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
new TableCell({
children: [],
}), }),
], ],
}), }),
], ],
}), }),
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
], ],
}), },
new TableRow({
children: [
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
new TableCell({
children: [new Paragraph("Hello")],
}),
new TableCell({
children: [],
}),
],
}),
new TableRow({
children: [
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
new TableCell({
children: [],
}),
],
}),
], ],
}); });
doc.addSection({
children: [table],
});
Packer.toBuffer(doc).then((buffer) => { Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("My Document.docx", buffer); fs.writeFileSync("My Document.docx", buffer);
}); });

View File

@ -4,18 +4,13 @@ import * as fs from "fs";
import { Document, Packer, Paragraph, Table, TableCell, TableRow, WidthType } from "../build"; import { Document, Packer, Paragraph, Table, TableCell, TableRow, WidthType } from "../build";
const styles = fs.readFileSync("./demo/assets/custom-styles.xml", "utf-8"); const styles = fs.readFileSync("./demo/assets/custom-styles.xml", "utf-8");
const doc = new Document({
title: "Title",
externalStyles: styles
});
// Create a table and pass the XML Style // Create a table and pass the XML Style
const table = new Table({ const table = new Table({
style: 'MyCustomTableStyle', style: "MyCustomTableStyle",
width: { width: {
size: 9070, size: 9070,
type: WidthType.DXA type: WidthType.DXA,
}, },
rows: [ rows: [
new TableRow({ new TableRow({
@ -41,8 +36,14 @@ const table = new Table({
], ],
}); });
doc.addSection({ const doc = new Document({
children: [table], title: "Title",
externalStyles: styles,
sections: [
{
children: [table],
},
],
}); });
Packer.toBuffer(doc).then((buffer) => { Packer.toBuffer(doc).then((buffer) => {

View File

@ -3,28 +3,30 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, Packer, Paragraph } from "../build"; import { Document, Packer, Paragraph } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
children: [ children: [
new Paragraph("No border!"), new Paragraph("No border!"),
new Paragraph({ new Paragraph({
text: "I have borders on my top and bottom sides!", text: "I have borders on my top and bottom sides!",
border: { border: {
top: { top: {
color: "auto", color: "auto",
space: 1, space: 1,
value: "single", value: "single",
size: 6, size: 6,
}, },
bottom: { bottom: {
color: "auto", color: "auto",
space: 1, space: 1,
value: "single", value: "single",
size: 6, size: 6,
}, },
}, },
}), }),
],
},
], ],
}); });

View File

@ -47,18 +47,19 @@ const doc = new Document({
}, },
], ],
}, },
}); sections: [
{
doc.addSection({ children: [
children: [ new Paragraph({
new Paragraph({ text: "Hello",
text: "Hello", style: "myWonkyStyle",
style: "myWonkyStyle", }),
}), new Paragraph({
new Paragraph({ text: "World",
text: "World", heading: HeadingLevel.HEADING_2,
heading: HeadingLevel.HEADING_2, }),
}), ],
},
], ],
}); });

View File

@ -3,6 +3,11 @@
import * as fs from "fs"; import * as fs from "fs";
import { File, HeadingLevel, Packer, Paragraph, StyleLevel, TableOfContents } from "../build"; import { File, HeadingLevel, Packer, Paragraph, StyleLevel, TableOfContents } from "../build";
// WordprocessingML docs for TableOfContents can be found here:
// http://officeopenxml.com/WPtableOfContents.php
// Let's define the properties for generate a TOC for heading 1-5 and MySpectacularStyle,
// making the entries be hyperlinks for the paragraph
const doc = new File({ const doc = new File({
styles: { styles: {
paragraphStyles: [ paragraphStyles: [
@ -19,43 +24,38 @@ const doc = new File({
}, },
], ],
}, },
}); sections: [
{
// WordprocessingML docs for TableOfContents can be found here: children: [
// http://officeopenxml.com/WPtableOfContents.php new TableOfContents("Summary", {
hyperlink: true,
// Let's define the properties for generate a TOC for heading 1-5 and MySpectacularStyle, headingStyleRange: "1-5",
// making the entries be hyperlinks for the paragraph stylesWithLevels: [new StyleLevel("MySpectacularStyle", 1)],
}),
doc.addSection({ new Paragraph({
children: [ text: "Header #1",
new TableOfContents("Summary", { heading: HeadingLevel.HEADING_1,
hyperlink: true, pageBreakBefore: true,
headingStyleRange: "1-5", }),
stylesWithLevels: [new StyleLevel("MySpectacularStyle", 1)], new Paragraph("I'm a little text very nicely written.'"),
}), new Paragraph({
new Paragraph({ text: "Header #2",
text: "Header #1", heading: HeadingLevel.HEADING_1,
heading: HeadingLevel.HEADING_1, pageBreakBefore: true,
pageBreakBefore: true, }),
}), new Paragraph("I'm a other text very nicely written.'"),
new Paragraph("I'm a little text very nicely written.'"), new Paragraph({
new Paragraph({ text: "Header #2.1",
text: "Header #2", heading: HeadingLevel.HEADING_2,
heading: HeadingLevel.HEADING_1, }),
pageBreakBefore: true, new Paragraph("I'm a another text very nicely written.'"),
}), new Paragraph({
new Paragraph("I'm a other text very nicely written.'"), text: "My Spectacular Style #1",
new Paragraph({ style: "MySpectacularStyle",
text: "Header #2.1", pageBreakBefore: true,
heading: HeadingLevel.HEADING_2, }),
}), ],
new Paragraph("I'm a another text very nicely written.'"), },
new Paragraph({
text: "My Spectacular Style #1",
style: "MySpectacularStyle",
pageBreakBefore: true,
}),
], ],
}); });

View File

@ -57,225 +57,226 @@ const doc = new Document({
}, },
], ],
}, },
}); sections: [
{
doc.addSection({ children: [
children: [ new Paragraph({
new Paragraph({ text: "line with contextual spacing",
text: "line with contextual spacing", numbering: {
numbering: { reference: "my-crazy-reference",
reference: "my-crazy-reference", level: 0,
level: 0, },
}, contextualSpacing: true,
contextualSpacing: true, spacing: {
spacing: { before: 200,
before: 200, },
}, }),
}), new Paragraph({
new Paragraph({ text: "line with contextual spacing",
text: "line with contextual spacing", numbering: {
numbering: { reference: "my-crazy-reference",
reference: "my-crazy-reference", level: 0,
level: 0, },
}, contextualSpacing: true,
contextualSpacing: true, spacing: {
spacing: { before: 200,
before: 200, },
}, }),
}), new Paragraph({
new Paragraph({ text: "line without contextual spacing",
text: "line without contextual spacing", numbering: {
numbering: { reference: "my-crazy-reference",
reference: "my-crazy-reference", level: 0,
level: 0, },
}, contextualSpacing: false,
contextualSpacing: false, spacing: {
spacing: { before: 200,
before: 200, },
}, }),
}), new Paragraph({
new Paragraph({ text: "line without contextual spacing",
text: "line without contextual spacing", numbering: {
numbering: { reference: "my-crazy-reference",
reference: "my-crazy-reference", level: 0,
level: 0, },
}, contextualSpacing: false,
contextualSpacing: false, spacing: {
spacing: { before: 200,
before: 200, },
}, }),
}), new Paragraph({
new Paragraph({ text: "Step 1 - Add sugar",
text: "Step 1 - Add sugar", numbering: {
numbering: { reference: "my-number-numbering-reference",
reference: "my-number-numbering-reference", level: 0,
level: 0, },
}, }),
}), new Paragraph({
new Paragraph({ text: "Step 2 - Add wheat",
text: "Step 2 - Add wheat", numbering: {
numbering: { reference: "my-number-numbering-reference",
reference: "my-number-numbering-reference", level: 0,
level: 0, },
}, }),
}), new Paragraph({
new Paragraph({ text: "Step 3 - Put in oven",
text: "Step 3 - Put in oven", numbering: {
numbering: { reference: "my-number-numbering-reference",
reference: "my-number-numbering-reference", level: 0,
level: 0, },
}, }),
}), new Paragraph({
new Paragraph({ text: "Next",
text: "Next", heading: HeadingLevel.HEADING_2,
heading: HeadingLevel.HEADING_2, }),
}), new Paragraph({
new Paragraph({ text: "test",
text: "test", numbering: {
numbering: { reference: "padded-numbering-reference",
reference: "padded-numbering-reference", level: 0,
level: 0, instance: 2,
instance: 2, },
}, }),
}), new Paragraph({
new Paragraph({ text: "test",
text: "test", numbering: {
numbering: { reference: "padded-numbering-reference",
reference: "padded-numbering-reference", level: 0,
level: 0, instance: 2,
instance: 2, },
}, }),
}), new Paragraph({
new Paragraph({ text: "Next",
text: "Next", heading: HeadingLevel.HEADING_2,
heading: HeadingLevel.HEADING_2, }),
}), new Paragraph({
new Paragraph({ text: "test",
text: "test", numbering: {
numbering: { reference: "padded-numbering-reference",
reference: "padded-numbering-reference", level: 0,
level: 0, instance: 3,
instance: 3, },
}, }),
}), new Paragraph({
new Paragraph({ text: "test",
text: "test", numbering: {
numbering: { reference: "padded-numbering-reference",
reference: "padded-numbering-reference", level: 0,
level: 0, instance: 3,
instance: 3, },
}, }),
}), new Paragraph({
new Paragraph({ text: "test",
text: "test", numbering: {
numbering: { reference: "padded-numbering-reference",
reference: "padded-numbering-reference", level: 0,
level: 0, instance: 3,
instance: 3, },
}, }),
}), new Paragraph({
new Paragraph({ text: "Next",
text: "Next", heading: HeadingLevel.HEADING_2,
heading: HeadingLevel.HEADING_2, }),
}), new Paragraph({
new Paragraph({ text: "test",
text: "test", numbering: {
numbering: { reference: "padded-numbering-reference",
reference: "padded-numbering-reference", level: 0,
level: 0, },
}, }),
}), new Paragraph({
new Paragraph({ text: "test",
text: "test", numbering: {
numbering: { reference: "padded-numbering-reference",
reference: "padded-numbering-reference", level: 0,
level: 0, },
}, }),
}), new Paragraph({
new Paragraph({ text: "test",
text: "test", numbering: {
numbering: { reference: "padded-numbering-reference",
reference: "padded-numbering-reference", level: 0,
level: 0, },
}, }),
}), new Paragraph({
new Paragraph({ text: "test",
text: "test", numbering: {
numbering: { reference: "padded-numbering-reference",
reference: "padded-numbering-reference", level: 0,
level: 0, },
}, }),
}), new Paragraph({
new Paragraph({ text: "test",
text: "test", numbering: {
numbering: { reference: "padded-numbering-reference",
reference: "padded-numbering-reference", level: 0,
level: 0, },
}, }),
}), new Paragraph({
new Paragraph({ text: "test",
text: "test", numbering: {
numbering: { reference: "padded-numbering-reference",
reference: "padded-numbering-reference", level: 0,
level: 0, },
}, }),
}), new Paragraph({
new Paragraph({ text: "test",
text: "test", numbering: {
numbering: { reference: "padded-numbering-reference",
reference: "padded-numbering-reference", level: 0,
level: 0, },
}, }),
}), new Paragraph({
new Paragraph({ text: "test",
text: "test", numbering: {
numbering: { reference: "padded-numbering-reference",
reference: "padded-numbering-reference", level: 0,
level: 0, },
}, }),
}), new Paragraph({
new Paragraph({ text: "test",
text: "test", numbering: {
numbering: { reference: "padded-numbering-reference",
reference: "padded-numbering-reference", level: 0,
level: 0, },
}, }),
}), new Paragraph({
new Paragraph({ text: "test",
text: "test", numbering: {
numbering: { reference: "padded-numbering-reference",
reference: "padded-numbering-reference", level: 0,
level: 0, },
}, }),
}), new Paragraph({
new Paragraph({ text: "test",
text: "test", numbering: {
numbering: { reference: "padded-numbering-reference",
reference: "padded-numbering-reference", level: 0,
level: 0, },
}, }),
}), new Paragraph({
new Paragraph({ text: "test",
text: "test", numbering: {
numbering: { reference: "padded-numbering-reference",
reference: "padded-numbering-reference", level: 0,
level: 0, },
}, }),
}), new Paragraph({
new Paragraph({ text: "test",
text: "test", numbering: {
numbering: { reference: "padded-numbering-reference",
reference: "padded-numbering-reference", level: 0,
level: 0, },
}, }),
}), new Paragraph({
new Paragraph({ text: "test",
text: "test", numbering: {
numbering: { reference: "padded-numbering-reference",
reference: "padded-numbering-reference", level: 0,
level: 0, },
}, }),
}), ],
},
], ],
}); });

View File

@ -117,136 +117,137 @@ const doc = new Document({
}, },
], ],
}, },
}); sections: [
{
doc.addSection({ children: [
children: [ new Paragraph({
new Paragraph({ text: "Hey you",
text: "Hey you", numbering: {
numbering: { reference: "my-crazy-numbering",
reference: "my-crazy-numbering", level: 0,
level: 0, },
}, }),
}), new Paragraph({
new Paragraph({ text: "What's up fam",
text: "What's up fam", numbering: {
numbering: { reference: "my-crazy-numbering",
reference: "my-crazy-numbering", level: 1,
level: 1, },
}, }),
}), new Paragraph({
new Paragraph({ text: "Hello World 2",
text: "Hello World 2", numbering: {
numbering: { reference: "my-crazy-numbering",
reference: "my-crazy-numbering", level: 1,
level: 1, },
}, }),
}), new Paragraph({
new Paragraph({ text: "Yeah boi",
text: "Yeah boi", numbering: {
numbering: { reference: "my-crazy-numbering",
reference: "my-crazy-numbering", level: 2,
level: 2, },
}, }),
}), new Paragraph({
new Paragraph({ text: "Hey you",
text: "Hey you", bullet: {
bullet: { level: 0,
level: 0, },
}, }),
}), new Paragraph({
new Paragraph({ text: "What's up fam",
text: "What's up fam", bullet: {
bullet: { level: 1,
level: 1, },
}, }),
}), new Paragraph({
new Paragraph({ text: "Hello World 2",
text: "Hello World 2", bullet: {
bullet: { level: 2,
level: 2, },
}, }),
}), new Paragraph({
new Paragraph({ text: "Yeah boi",
text: "Yeah boi", bullet: {
bullet: { level: 3,
level: 3, },
}, }),
}), new Paragraph({
new Paragraph({ text: "101 MSXFM",
text: "101 MSXFM", numbering: {
numbering: { reference: "my-crazy-numbering",
reference: "my-crazy-numbering", level: 3,
level: 3, },
}, }),
}), new Paragraph({
new Paragraph({ text: "back to level 1",
text: "back to level 1", numbering: {
numbering: { reference: "my-crazy-numbering",
reference: "my-crazy-numbering", level: 1,
level: 1, },
}, }),
}), new Paragraph({
new Paragraph({ text: "back to level 0",
text: "back to level 0", numbering: {
numbering: { reference: "my-crazy-numbering",
reference: "my-crazy-numbering", level: 0,
level: 0, },
}, }),
}), new Paragraph({
new Paragraph({ text: "Custom Bullet points",
text: "Custom Bullet points", heading: HeadingLevel.HEADING_1,
heading: HeadingLevel.HEADING_1, }),
}), new Paragraph({
new Paragraph({ text: "What's up fam",
text: "What's up fam", numbering: {
numbering: { reference: "my-unique-bullet-points",
reference: "my-unique-bullet-points", level: 0,
level: 0, },
}, }),
}), new Paragraph({
new Paragraph({ text: "Hey you",
text: "Hey you", numbering: {
numbering: { reference: "my-unique-bullet-points",
reference: "my-unique-bullet-points", level: 0,
level: 0, },
}, }),
}), new Paragraph({
new Paragraph({ text: "What's up fam",
text: "What's up fam", numbering: {
numbering: { reference: "my-unique-bullet-points",
reference: "my-unique-bullet-points", level: 1,
level: 1, },
}, }),
}), new Paragraph({
new Paragraph({ text: "Hello World 2",
text: "Hello World 2", numbering: {
numbering: { reference: "my-unique-bullet-points",
reference: "my-unique-bullet-points", level: 2,
level: 2, },
}, }),
}), new Paragraph({
new Paragraph({ text: "Yeah boi",
text: "Yeah boi", numbering: {
numbering: { reference: "my-unique-bullet-points",
reference: "my-unique-bullet-points", level: 3,
level: 3, },
}, }),
}), new Paragraph({
new Paragraph({ text: "my Awesome numbering",
text: "my Awesome numbering", numbering: {
numbering: { reference: "my-unique-bullet-points",
reference: "my-unique-bullet-points", level: 4,
level: 4, },
}, }),
}), new Paragraph({
new Paragraph({ text: "Back to level 1",
text: "Back to level 1", numbering: {
numbering: { reference: "my-unique-bullet-points",
reference: "my-unique-bullet-points", level: 1,
level: 1, },
}, }),
}), ],
},
], ],
}); });

View File

@ -12,16 +12,21 @@ fs.readFile(filePath, (err, data) => {
} }
importDotx.extract(data).then((templateDocument) => { importDotx.extract(data).then((templateDocument) => {
const doc = new Document(undefined, { const doc = new Document(
template: templateDocument, {
}); sections: [
{
doc.addSection({ properties: {
properties: { titlePage: templateDocument.titlePageIsDefined,
titlePage: templateDocument.titlePageIsDefined, },
children: [new Paragraph("Hello World")],
},
],
}, },
children: [new Paragraph("Hello World")], {
}); template: templateDocument,
},
);
Packer.toBuffer(doc).then((buffer) => { Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("My Document.docx", buffer); fs.writeFileSync("My Document.docx", buffer);

View File

@ -3,74 +3,76 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, HeadingLevel, Packer, Paragraph, Table, TableCell, TableRow, VerticalAlign, TextDirection } from "../build"; import { Document, HeadingLevel, Packer, Paragraph, Table, TableCell, TableRow, VerticalAlign, TextDirection } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
const table = new Table({ {
rows: [
new TableRow({
children: [ children: [
new TableCell({ new Table({
children: [new Paragraph({}), new Paragraph({})], rows: [
verticalAlign: VerticalAlign.CENTER, new TableRow({
}), children: [
new TableCell({ new TableCell({
children: [new Paragraph({}), new Paragraph({})], children: [new Paragraph({}), new Paragraph({})],
verticalAlign: VerticalAlign.CENTER, verticalAlign: VerticalAlign.CENTER,
}), }),
new TableCell({ new TableCell({
children: [new Paragraph({ text: "bottom to top" }), new Paragraph({})], children: [new Paragraph({}), new Paragraph({})],
textDirection: TextDirection.BOTTOM_TO_TOP_LEFT_TO_RIGHT, verticalAlign: VerticalAlign.CENTER,
}), }),
new TableCell({ new TableCell({
children: [new Paragraph({ text: "top to bottom" }), new Paragraph({})], children: [new Paragraph({ text: "bottom to top" }), new Paragraph({})],
textDirection: TextDirection.TOP_TO_BOTTOM_RIGHT_TO_LEFT, textDirection: TextDirection.BOTTOM_TO_TOP_LEFT_TO_RIGHT,
}),
new TableCell({
children: [new Paragraph({ text: "top to bottom" }), new Paragraph({})],
textDirection: TextDirection.TOP_TO_BOTTOM_RIGHT_TO_LEFT,
}),
],
}),
new TableRow({
children: [
new TableCell({
children: [
new Paragraph({
text:
"Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah",
heading: HeadingLevel.HEADING_1,
}),
],
}),
new TableCell({
children: [
new Paragraph({
text: "This text should be in the middle of the cell",
}),
],
verticalAlign: VerticalAlign.CENTER,
}),
new TableCell({
children: [
new Paragraph({
text: "Text above should be vertical from bottom to top",
}),
],
verticalAlign: VerticalAlign.CENTER,
}),
new TableCell({
children: [
new Paragraph({
text: "Text above should be vertical from top to bottom",
}),
],
verticalAlign: VerticalAlign.CENTER,
}),
],
}),
],
}), }),
], ],
}), },
new TableRow({
children: [
new TableCell({
children: [
new Paragraph({
text:
"Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah Blah",
heading: HeadingLevel.HEADING_1,
}),
],
}),
new TableCell({
children: [
new Paragraph({
text: "This text should be in the middle of the cell",
}),
],
verticalAlign: VerticalAlign.CENTER,
}),
new TableCell({
children: [
new Paragraph({
text: "Text above should be vertical from bottom to top",
}),
],
verticalAlign: VerticalAlign.CENTER,
}),
new TableCell({
children: [
new Paragraph({
text: "Text above should be vertical from top to bottom",
}),
],
verticalAlign: VerticalAlign.CENTER,
}),
],
}),
], ],
}); });
doc.addSection({
children: [table],
});
Packer.toBuffer(doc).then((buffer) => { Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("My Document.docx", buffer); fs.writeFileSync("My Document.docx", buffer);
}); });

View File

@ -17,8 +17,6 @@ import {
WidthType, WidthType,
} from "../build"; } from "../build";
const doc = new Document();
const table = new Table({ const table = new Table({
rows: [ rows: [
new TableRow({ new TableRow({
@ -376,30 +374,33 @@ const table8 = new Table({
type: WidthType.PERCENTAGE, type: WidthType.PERCENTAGE,
}, },
}); });
const doc = new Document({
doc.addSection({ sections: [
children: [ {
table, children: [
new Paragraph({ table,
text: "Another table", new Paragraph({
heading: HeadingLevel.HEADING_2, text: "Another table",
}), heading: HeadingLevel.HEADING_2,
table2, }),
new Paragraph({ table2,
text: "Another table", new Paragraph({
heading: HeadingLevel.HEADING_2, text: "Another table",
}), heading: HeadingLevel.HEADING_2,
table3, }),
new Paragraph("Merging columns 1"), table3,
table4, new Paragraph("Merging columns 1"),
new Paragraph("Merging columns 2"), table4,
table5, new Paragraph("Merging columns 2"),
new Paragraph("Merging columns 3"), table5,
table6, new Paragraph("Merging columns 3"),
new Paragraph("Merging columns 4"), table6,
table7, new Paragraph("Merging columns 4"),
new Paragraph("Merging columns 5"), table7,
table8, new Paragraph("Merging columns 5"),
table8,
],
},
], ],
}); });

View File

@ -3,42 +3,44 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, Packer, Paragraph, SequentialIdentifier, TextRun } from "../build"; import { Document, Packer, Paragraph, SequentialIdentifier, TextRun } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
children: [
new Paragraph({
children: [ children: [
new TextRun("Hello World 1->"), new Paragraph({
new SequentialIdentifier("Caption"), children: [
new TextRun(" text after sequencial caption 2->"), new TextRun("Hello World 1->"),
new SequentialIdentifier("Caption"), new SequentialIdentifier("Caption"),
new TextRun(" text after sequencial caption 2->"),
new SequentialIdentifier("Caption"),
],
}),
new Paragraph({
children: [
new TextRun("Hello World 1->"),
new SequentialIdentifier("Label"),
new TextRun(" text after sequencial caption 2->"),
new SequentialIdentifier("Label"),
],
}),
new Paragraph({
children: [
new TextRun("Hello World 1->"),
new SequentialIdentifier("Another"),
new TextRun(" text after sequencial caption 3->"),
new SequentialIdentifier("Label"),
],
}),
new Paragraph({
children: [
new TextRun("Hello World 2->"),
new SequentialIdentifier("Another"),
new TextRun(" text after sequencial caption 4->"),
new SequentialIdentifier("Label"),
],
}),
], ],
}), },
new Paragraph({
children: [
new TextRun("Hello World 1->"),
new SequentialIdentifier("Label"),
new TextRun(" text after sequencial caption 2->"),
new SequentialIdentifier("Label"),
],
}),
new Paragraph({
children: [
new TextRun("Hello World 1->"),
new SequentialIdentifier("Another"),
new TextRun(" text after sequencial caption 3->"),
new SequentialIdentifier("Label"),
],
}),
new Paragraph({
children: [
new TextRun("Hello World 2->"),
new SequentialIdentifier("Another"),
new TextRun(" text after sequencial caption 4->"),
new SequentialIdentifier("Label"),
],
}),
], ],
}); });

View File

@ -16,8 +16,6 @@ import {
WidthType, WidthType,
} from "../build"; } from "../build";
const doc = new Document();
const table = new Table({ const table = new Table({
rows: [ rows: [
new TableRow({ new TableRow({
@ -57,8 +55,12 @@ const table = new Table({
layout: TableLayoutType.FIXED, layout: TableLayoutType.FIXED,
}); });
doc.addSection({ const doc = new Document({
children: [table], sections: [
{
children: [table],
},
],
}); });
Packer.toBuffer(doc).then((buffer) => { Packer.toBuffer(doc).then((buffer) => {

View File

@ -22,79 +22,80 @@ const doc = new Document({
], ],
}, },
}, },
}); sections: [
{
doc.addSection({ footers: {
footers: { default: new Footer({
default: new Footer({ children: [
new Paragraph({
children: [
new TextRun("Click here for the "),
new ExternalHyperlink({
child: new TextRun({
text: "Footer external hyperlink",
style: "Hyperlink",
}),
link: "http://www.example.com",
}),
],
}),
],
}),
},
headers: {
default: new Footer({
children: [
new Paragraph({
children: [
new TextRun("Click here for the "),
new ExternalHyperlink({
child: new TextRun({
text: "Header external hyperlink",
style: "Hyperlink",
}),
link: "http://www.google.com",
}),
],
}),
],
}),
},
children: [ children: [
new Paragraph({ new Paragraph({
children: [ children: [
new TextRun("Click here for the "),
new ExternalHyperlink({ new ExternalHyperlink({
child: new TextRun({ child: new TextRun({
text: "Footer external hyperlink", text: "Anchor Text",
style: "Hyperlink", style: "Hyperlink",
}), }),
link: "http://www.example.com", link: "http://www.example.com",
}), }),
new FootnoteReferenceRun(1),
], ],
}), }),
],
}),
},
headers: {
default: new Footer({
children: [
new Paragraph({ new Paragraph({
children: [ children: [
new TextRun("Click here for the "),
new ExternalHyperlink({ new ExternalHyperlink({
child: new TextRun({ child: new ImageRun({
text: "Header external hyperlink", data: fs.readFileSync("./demo/images/image1.jpeg"),
style: "Hyperlink", transformation: {
width: 100,
height: 100,
},
}), }),
link: "http://www.google.com", link: "http://www.google.com",
}), }),
new ExternalHyperlink({
child: new TextRun({
text: "BBC News Link",
style: "Hyperlink",
}),
link: "https://www.bbc.co.uk/news",
}),
], ],
}), }),
], ],
}), },
},
children: [
new Paragraph({
children: [
new ExternalHyperlink({
child: new TextRun({
text: "Anchor Text",
style: "Hyperlink",
}),
link: "http://www.example.com",
}),
new FootnoteReferenceRun(1),
],
}),
new Paragraph({
children: [
new ExternalHyperlink({
child: new ImageRun({
data: fs.readFileSync("./demo/images/image1.jpeg"),
transformation: {
width: 100,
height: 100,
},
}),
link: "http://www.google.com",
}),
new ExternalHyperlink({
child: new TextRun({
text: "BBC News Link",
style: "Hyperlink",
}),
link: "https://www.bbc.co.uk/news",
}),
],
}),
], ],
}); });

View File

@ -3,8 +3,6 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, Header, ImageRun, Packer, Paragraph, Table, TableCell, TableRow } from "../build"; import { Document, Header, ImageRun, Packer, Paragraph, Table, TableCell, TableRow } from "../build";
const doc = new Document();
const table = new Table({ const table = new Table({
rows: [ rows: [
new TableRow({ new TableRow({
@ -69,13 +67,17 @@ const table = new Table({
}); });
// Adding same table in the body and in the header // Adding same table in the body and in the header
doc.addSection({ const doc = new Document({
headers: { sections: [
default: new Header({ {
headers: {
default: new Header({
children: [table],
}),
},
children: [table], children: [table],
}), },
}, ],
children: [table],
}); });
Packer.toBuffer(doc).then((buffer) => { Packer.toBuffer(doc).then((buffer) => {

View File

@ -3,49 +3,51 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, Header, ImageRun, Packer, Paragraph } from "../build"; import { Document, Header, ImageRun, Packer, Paragraph } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
headers: { headers: {
default: new Header({ default: new Header({
children: [
new Paragraph({
children: [ children: [
new ImageRun({ new Paragraph({
data: fs.readFileSync("./demo/images/image1.jpeg"), children: [
transformation: { new ImageRun({
width: 100, data: fs.readFileSync("./demo/images/image1.jpeg"),
height: 100, transformation: {
}, width: 100,
height: 100,
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/pizza.gif"),
transformation: {
width: 100,
height: 100,
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/image1.jpeg"),
transformation: {
width: 100,
height: 100,
},
}),
],
}), }),
], ],
}), }),
new Paragraph({ },
children: [ children: [new Paragraph("Hello World")],
new ImageRun({ },
data: fs.readFileSync("./demo/images/pizza.gif"), ],
transformation: {
width: 100,
height: 100,
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/image1.jpeg"),
transformation: {
width: 100,
height: 100,
},
}),
],
}),
],
}),
},
children: [new Paragraph("Hello World")],
}); });
Packer.toBuffer(doc).then((buffer) => { Packer.toBuffer(doc).then((buffer) => {

View File

@ -4,44 +4,48 @@ import * as fs from "fs";
// import { Document, Packer, Paragraph } from "../build"; // import { Document, Packer, Paragraph } from "../build";
import { Document, ImageRun, Packer, Paragraph, TextWrappingSide, TextWrappingType } from "../build"; import { Document, ImageRun, Packer, Paragraph, TextWrappingSide, TextWrappingType } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
children: [ children: [
new Paragraph( new Paragraph(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vehicula nec nulla vitae efficitur. Ut interdum mauris eu ipsum rhoncus, nec pharetra velit placerat. Sed vehicula libero ac urna molestie, id pharetra est pellentesque. Praesent iaculis vehicula fringilla. Duis pretium gravida orci eu vestibulum. Mauris tincidunt ipsum dolor, ut ornare dolor pellentesque id. Integer in nulla gravida, lacinia ante non, commodo ex. Vivamus vulputate nisl id lectus finibus vulputate. Ut et nisl mi. Cras fermentum augue arcu, ac accumsan elit euismod id. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed ac posuere nisi. Pellentesque tincidunt vehicula bibendum. Phasellus eleifend viverra nisl.", "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vehicula nec nulla vitae efficitur. Ut interdum mauris eu ipsum rhoncus, nec pharetra velit placerat. Sed vehicula libero ac urna molestie, id pharetra est pellentesque. Praesent iaculis vehicula fringilla. Duis pretium gravida orci eu vestibulum. Mauris tincidunt ipsum dolor, ut ornare dolor pellentesque id. Integer in nulla gravida, lacinia ante non, commodo ex. Vivamus vulputate nisl id lectus finibus vulputate. Ut et nisl mi. Cras fermentum augue arcu, ac accumsan elit euismod id. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed ac posuere nisi. Pellentesque tincidunt vehicula bibendum. Phasellus eleifend viverra nisl.",
), ),
new Paragraph( new Paragraph(
"Proin ac purus faucibus, porttitor magna ut, cursus nisl. Vivamus ante purus, porta accumsan nibh eget, eleifend dignissim odio. Integer sed dictum est, aliquam lacinia justo. Donec ultrices auctor venenatis. Etiam interdum et elit nec elementum. Pellentesque nec viverra mauris. Etiam suscipit leo nec velit fringilla mattis. Pellentesque justo lacus, sodales eu condimentum in, dapibus finibus lacus. Morbi vitae nibh sit amet sem molestie feugiat. In non porttitor enim.", "Proin ac purus faucibus, porttitor magna ut, cursus nisl. Vivamus ante purus, porta accumsan nibh eget, eleifend dignissim odio. Integer sed dictum est, aliquam lacinia justo. Donec ultrices auctor venenatis. Etiam interdum et elit nec elementum. Pellentesque nec viverra mauris. Etiam suscipit leo nec velit fringilla mattis. Pellentesque justo lacus, sodales eu condimentum in, dapibus finibus lacus. Morbi vitae nibh sit amet sem molestie feugiat. In non porttitor enim.",
), ),
new Paragraph( new Paragraph(
"Ut eget diam cursus quam accumsan interdum at id ante. Ut mollis mollis arcu, eu scelerisque dui tempus in. Quisque aliquam, augue quis ornare aliquam, ex purus ultrices mauris, ut porta dolor dolor nec justo. Nunc a tempus odio, eu viverra arcu. Suspendisse vitae nibh nec mi pharetra tempus. Mauris ut ullamcorper sapien, et sagittis sapien. Vestibulum in urna metus. In scelerisque, massa id bibendum tempus, quam orci rutrum turpis, a feugiat nisi ligula id metus. Praesent id dictum purus. Proin interdum ipsum nulla.", "Ut eget diam cursus quam accumsan interdum at id ante. Ut mollis mollis arcu, eu scelerisque dui tempus in. Quisque aliquam, augue quis ornare aliquam, ex purus ultrices mauris, ut porta dolor dolor nec justo. Nunc a tempus odio, eu viverra arcu. Suspendisse vitae nibh nec mi pharetra tempus. Mauris ut ullamcorper sapien, et sagittis sapien. Vestibulum in urna metus. In scelerisque, massa id bibendum tempus, quam orci rutrum turpis, a feugiat nisi ligula id metus. Praesent id dictum purus. Proin interdum ipsum nulla.",
), ),
new Paragraph( new Paragraph({
new ImageRun({ children: [
data: fs.readFileSync("./demo/images/pizza.gif"), new ImageRun({
transformation: { data: fs.readFileSync("./demo/images/pizza.gif"),
width: 200, transformation: {
height: 200, width: 200,
}, height: 200,
floating: { },
horizontalPosition: { floating: {
offset: 2014400, horizontalPosition: {
}, offset: 2014400,
verticalPosition: { },
offset: 2014400, verticalPosition: {
}, offset: 2014400,
wrap: { },
type: TextWrappingType.SQUARE, wrap: {
side: TextWrappingSide.BOTH_SIDES, type: TextWrappingType.SQUARE,
}, side: TextWrappingSide.BOTH_SIDES,
margins: { },
top: 201440, margins: {
bottom: 201440, top: 201440,
}, bottom: 201440,
}, },
}), },
), }),
],
}),
],
},
], ],
}); });

View File

@ -3,64 +3,70 @@
import * as fs from "fs"; import * as fs from "fs";
import { AlignmentType, Document, Footer, Header, Packer, PageBreak, PageNumber, PageNumberFormat, Paragraph, TextRun } from "../build"; import { AlignmentType, Document, Footer, Header, Packer, PageBreak, PageNumber, PageNumberFormat, Paragraph, TextRun } from "../build";
const doc = new Document({}); const doc = new Document({
sections: [
doc.addSection({ {
headers: { properties: {
default: new Header({ page: {
children: [ pageNumbers: {
new Paragraph({ start: 1,
formatType: PageNumberFormat.DECIMAL,
},
},
},
headers: {
default: new Header({
children: [ children: [
new TextRun("Foo Bar corp. "), new Paragraph({
new TextRun({ children: [
children: ["Page Number ", PageNumber.CURRENT], new TextRun("Foo Bar corp. "),
}), new TextRun({
new TextRun({ children: ["Page Number ", PageNumber.CURRENT],
children: [" to ", PageNumber.TOTAL_PAGES], }),
new TextRun({
children: [" to ", PageNumber.TOTAL_PAGES],
}),
],
}), }),
], ],
}), }),
], },
}), footers: {
}, default: new Footer({
footers: {
default: new Footer({
children: [
new Paragraph({
alignment: AlignmentType.CENTER,
children: [ children: [
new TextRun("Foo Bar corp. "), new Paragraph({
new TextRun({ alignment: AlignmentType.CENTER,
children: ["Page Number: ", PageNumber.CURRENT], children: [
}), new TextRun("Foo Bar corp. "),
new TextRun({ new TextRun({
children: [" to ", PageNumber.TOTAL_PAGES], children: ["Page Number: ", PageNumber.CURRENT],
}),
new TextRun({
children: [" to ", PageNumber.TOTAL_PAGES],
}),
],
}), }),
], ],
}), }),
},
children: [
new Paragraph({
children: [new TextRun("Hello World 1"), new PageBreak()],
}),
new Paragraph({
children: [new TextRun("Hello World 2"), new PageBreak()],
}),
new Paragraph({
children: [new TextRun("Hello World 3"), new PageBreak()],
}),
new Paragraph({
children: [new TextRun("Hello World 4"), new PageBreak()],
}),
new Paragraph({
children: [new TextRun("Hello World 5"), new PageBreak()],
}),
], ],
}), },
},
properties: {
pageNumberStart: 1,
pageNumberFormatType: PageNumberFormat.DECIMAL,
},
children: [
new Paragraph({
children: [new TextRun("Hello World 1"), new PageBreak()],
}),
new Paragraph({
children: [new TextRun("Hello World 2"), new PageBreak()],
}),
new Paragraph({
children: [new TextRun("Hello World 3"), new PageBreak()],
}),
new Paragraph({
children: [new TextRun("Hello World 4"), new PageBreak()],
}),
new Paragraph({
children: [new TextRun("Hello World 5"), new PageBreak()],
}),
], ],
}); });

View File

@ -3,8 +3,6 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, Packer, Paragraph, Table, TableCell, TableRow, WidthType } from "../build"; import { Document, Packer, Paragraph, Table, TableCell, TableRow, WidthType } from "../build";
const doc = new Document();
const table = new Table({ const table = new Table({
columnWidths: [3505, 5505], columnWidths: [3505, 5505],
rows: [ rows: [
@ -114,14 +112,18 @@ const table3 = new Table({
], ],
}); });
doc.addSection({ const doc = new Document({
children: [ sections: [
new Paragraph({ text: "Table with skewed widths" }), {
table, children: [
new Paragraph({ text: "Table with equal widths" }), new Paragraph({ text: "Table with skewed widths" }),
table2, table,
new Paragraph({ text: "Table without setting widths" }), new Paragraph({ text: "Table with equal widths" }),
table3, table2,
new Paragraph({ text: "Table without setting widths" }),
table3,
],
},
], ],
}); });

View File

@ -3,24 +3,28 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, HeadingLevel, LineNumberRestartFormat, Packer, Paragraph } from "../build"; import { Document, HeadingLevel, LineNumberRestartFormat, Packer, Paragraph } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
properties: { properties: {
lineNumberCountBy: 1, lineNumbers: {
lineNumberRestart: LineNumberRestartFormat.CONTINUOUS, countBy: 1,
}, restart: LineNumberRestartFormat.CONTINUOUS,
children: [ },
new Paragraph({ },
text: "Hello", children: [
heading: HeadingLevel.HEADING_1, new Paragraph({
}), text: "Hello",
new Paragraph( heading: HeadingLevel.HEADING_1,
"Himenaeos duis luctus nullam fermentum lobortis potenti vivamus non dis, sed facilisis ultricies scelerisque aenean risus hac senectus. Adipiscing id venenatis justo ante gravida placerat, ac curabitur dis pellentesque proin bibendum risus, aliquam porta taciti vulputate primis. Tortor ipsum fermentum quam vel convallis primis nisl praesent tincidunt, lobortis quisque felis vitae condimentum class ut sem nam, aenean potenti pretium ac amet lacinia himenaeos mi. Aliquam nisl turpis hendrerit est morbi malesuada, augue interdum mus inceptos curabitur tristique, parturient feugiat sodales nulla facilisi. Aliquam non pulvinar purus nulla ex integer, velit faucibus vitae at bibendum quam, risus elit aenean adipiscing posuere.", }),
), new Paragraph(
new Paragraph( "Himenaeos duis luctus nullam fermentum lobortis potenti vivamus non dis, sed facilisis ultricies scelerisque aenean risus hac senectus. Adipiscing id venenatis justo ante gravida placerat, ac curabitur dis pellentesque proin bibendum risus, aliquam porta taciti vulputate primis. Tortor ipsum fermentum quam vel convallis primis nisl praesent tincidunt, lobortis quisque felis vitae condimentum class ut sem nam, aenean potenti pretium ac amet lacinia himenaeos mi. Aliquam nisl turpis hendrerit est morbi malesuada, augue interdum mus inceptos curabitur tristique, parturient feugiat sodales nulla facilisi. Aliquam non pulvinar purus nulla ex integer, velit faucibus vitae at bibendum quam, risus elit aenean adipiscing posuere.",
"Sed laoreet id mattis egestas nam mollis elit lacinia convallis dui tincidunt ultricies habitant, pharetra per maximus interdum neque tempor risus efficitur morbi imperdiet senectus. Lectus laoreet senectus finibus inceptos donec potenti fermentum, ultrices eleifend odio suscipit magnis tellus maximus nibh, ac sit nullam eget felis himenaeos. Diam class sem magnis aenean commodo faucibus id proin mi, nullam sodales nec mus parturient ornare ad inceptos velit hendrerit, bibendum placerat eleifend integer facilisis urna dictumst suspendisse.", ),
), new Paragraph(
"Sed laoreet id mattis egestas nam mollis elit lacinia convallis dui tincidunt ultricies habitant, pharetra per maximus interdum neque tempor risus efficitur morbi imperdiet senectus. Lectus laoreet senectus finibus inceptos donec potenti fermentum, ultrices eleifend odio suscipit magnis tellus maximus nibh, ac sit nullam eget felis himenaeos. Diam class sem magnis aenean commodo faucibus id proin mi, nullam sodales nec mus parturient ornare ad inceptos velit hendrerit, bibendum placerat eleifend integer facilisis urna dictumst suspendisse.",
),
],
},
], ],
}); });

View File

@ -3,8 +3,6 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, Packer, Paragraph, Table, TableCell, TableRow } from "../build"; import { Document, Packer, Paragraph, Table, TableCell, TableRow } from "../build";
const doc = new Document();
const table = new Table({ const table = new Table({
rows: [ rows: [
new TableRow({ new TableRow({
@ -252,8 +250,12 @@ const table2 = new Table({
], ],
}); });
doc.addSection({ const doc = new Document({
children: [table, new Paragraph(""), table2], sections: [
{
children: [table, new Paragraph(""), table2],
},
],
}); });
Packer.toBuffer(doc).then((buffer) => { Packer.toBuffer(doc).then((buffer) => {

View File

@ -3,83 +3,88 @@
import * as fs from "fs"; import * as fs from "fs";
import { AlignmentType, Document, Header, Packer, PageBreak, PageNumber, PageNumberSeparator, Paragraph, TextRun } from "../build"; import { AlignmentType, Document, Header, Packer, PageBreak, PageNumber, PageNumberSeparator, Paragraph, TextRun } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
headers: { headers: {
default: new Header({ default: new Header({
children: [
new Paragraph({
alignment: AlignmentType.RIGHT,
children: [ children: [
new TextRun("My Title "), new Paragraph({
new TextRun({ alignment: AlignmentType.RIGHT,
children: ["Page ", PageNumber.CURRENT], children: [
new TextRun("My Title "),
new TextRun({
children: ["Page ", PageNumber.CURRENT],
}),
],
}), }),
], ],
}), }),
], first: new Header({
}),
first: new Header({
children: [
new Paragraph({
alignment: AlignmentType.RIGHT,
children: [ children: [
new TextRun("First Page Header "), new Paragraph({
new TextRun({ alignment: AlignmentType.RIGHT,
children: ["Page ", PageNumber.CURRENT], children: [
new TextRun("First Page Header "),
new TextRun({
children: ["Page ", PageNumber.CURRENT],
}),
],
}), }),
], ],
}), }),
], },
}),
},
children: [
new Paragraph({
children: [new TextRun("First Page"), new PageBreak()],
}),
new Paragraph("Second Page"),
],
});
doc.addSection({
properties: {
pageNumberStart: 1,
pageNumberSeparator: PageNumberSeparator.EM_DASH
},
headers: {
default: new Header({
children: [ children: [
new Paragraph({ new Paragraph({
alignment: AlignmentType.RIGHT, children: [new TextRun("First Page"), new PageBreak()],
}),
new Paragraph("Second Page"),
],
},
{
properties: {
page: {
pageNumbers: {
start: 1,
separator: PageNumberSeparator.EM_DASH,
},
},
},
headers: {
default: new Header({
children: [ children: [
new TextRun("My Title "), new Paragraph({
new TextRun({ alignment: AlignmentType.RIGHT,
children: ["Page ", PageNumber.CURRENT], children: [
new TextRun("My Title "),
new TextRun({
children: ["Page ", PageNumber.CURRENT],
}),
],
}), }),
], ],
}), }),
], first: new Header({
}),
first: new Header({
children: [
new Paragraph({
alignment: AlignmentType.RIGHT,
children: [ children: [
new TextRun("First Page Header of Second section"), new Paragraph({
new TextRun({ alignment: AlignmentType.RIGHT,
children: ["Page ", PageNumber.CURRENT], children: [
new TextRun("First Page Header of Second section"),
new TextRun({
children: ["Page ", PageNumber.CURRENT],
}),
],
}), }),
], ],
}), }),
},
children: [
new Paragraph({
children: [new TextRun("Third Page"), new PageBreak()],
}),
new Paragraph("Fourth Page"),
], ],
}), },
},
children: [
new Paragraph({
children: [new TextRun("Third Page"), new PageBreak()],
}),
new Paragraph("Fourth Page"),
], ],
}); });

View File

@ -3,8 +3,6 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, Packer, Paragraph, Table, TableCell, TableRow } from "../build"; import { Document, Packer, Paragraph, Table, TableCell, TableRow } from "../build";
const doc = new Document();
const table = new Table({ const table = new Table({
rows: [ rows: [
new TableRow({ new TableRow({
@ -75,8 +73,12 @@ const table = new Table({
], ],
}); });
doc.addSection({ const doc = new Document({
children: [table], sections: [
{
children: [table],
},
],
}); });
Packer.toBuffer(doc).then((buffer) => { Packer.toBuffer(doc).then((buffer) => {

View File

@ -3,51 +3,51 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, Packer, Paragraph } from "../build"; import { Document, Packer, Paragraph } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
properties: { properties: {
column: { column: {
space: 708, space: 708,
count: 2, count: 2,
},
},
children: [
new Paragraph("This text will be split into 2 columns on a page."),
new Paragraph(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
),
],
}, },
}, {
children: [ properties: {
new Paragraph("This text will be split into 2 columns on a page."), column: {
new Paragraph( space: 708,
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", count: 3,
), },
], },
}); children: [
new Paragraph("This text will be split into 3 columns on a page."),
doc.addSection({ new Paragraph(
properties: { "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
column: { ),
space: 708, ],
count: 3,
}, },
}, {
children: [ properties: {
new Paragraph("This text will be split into 3 columns on a page."), column: {
new Paragraph( space: 708,
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.", count: 2,
), separate: true,
], },
}); },
children: [
doc.addSection({ new Paragraph("This text will be split into 2 columns on a page."),
properties: { new Paragraph(
column: { "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
space: 708, ),
count: 2, ],
separate: true,
}, },
},
children: [
new Paragraph("This text will be split into 2 columns on a page."),
new Paragraph(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
),
], ],
}); });

View File

@ -3,31 +3,33 @@
import * as fs from "fs"; import * as fs from "fs";
import { AlignmentType, Document, Header, Packer, Paragraph, TextRun } from "../build"; import { AlignmentType, Document, Header, Packer, Paragraph, TextRun } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
headers: { headers: {
default: new Header({ default: new Header({
children: [
new Paragraph({
alignment: AlignmentType.RIGHT,
children: [ children: [
new TextRun({ new Paragraph({
text: "Hello World", alignment: AlignmentType.RIGHT,
color: "red", children: [
bold: true, new TextRun({
size: 24, text: "Hello World",
font: { color: "red",
name: "Garamond", bold: true,
}, size: 24,
highlight: "yellow", font: {
name: "Garamond",
},
highlight: "yellow",
}),
],
}), }),
], ],
}), }),
], },
}), children: [],
}, },
children: [], ],
}); });
Packer.toBuffer(doc).then((buffer) => { Packer.toBuffer(doc).then((buffer) => {

View File

@ -3,59 +3,61 @@
import * as fs from "fs"; import * as fs from "fs";
import { AlignmentType, Document, Header, Packer, Paragraph, ShadingType, TextRun } from "../build"; import { AlignmentType, Document, Header, Packer, Paragraph, ShadingType, TextRun } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
headers: { headers: {
default: new Header({ default: new Header({
children: [
new Paragraph({
alignment: AlignmentType.RIGHT,
children: [ children: [
new TextRun({ new Paragraph({
text: "Hello World", alignment: AlignmentType.RIGHT,
color: "red", children: [
bold: true, new TextRun({
size: 24, text: "Hello World",
font: { color: "red",
name: "Garamond", bold: true,
}, size: 24,
font: {
name: "Garamond",
},
shading: {
type: ShadingType.REVERSE_DIAGONAL_STRIPE,
color: "00FFFF",
fill: "FF0000",
},
}),
],
}),
new Paragraph({
shading: { shading: {
type: ShadingType.REVERSE_DIAGONAL_STRIPE, type: ShadingType.DIAGONAL_CROSS,
color: "00FFFF", color: "00FFFF",
fill: "FF0000", fill: "FF0000",
}, },
children: [
new TextRun({
text: "Hello World for entire paragraph",
}),
],
}), }),
], ],
}), }),
},
children: [
new Paragraph({ new Paragraph({
shading: {
type: ShadingType.DIAGONAL_CROSS,
color: "00FFFF",
fill: "FF0000",
},
children: [ children: [
new TextRun({ new TextRun({
text: "Hello World for entire paragraph", emboss: true,
text: "Embossed text - hello world",
}),
new TextRun({
imprint: true,
text: "Imprinted text - hello world",
}), }),
], ],
}), }),
], ],
}), },
},
children: [
new Paragraph({
children: [
new TextRun({
emboss: true,
text: "Embossed text - hello world",
}),
new TextRun({
imprint: true,
text: "Imprinted text - hello world",
}),
],
}),
], ],
}); });

View File

@ -3,8 +3,6 @@
import * as fs from "fs"; import * as fs from "fs";
import { AlignmentType, Document, Footer, Header, Packer, PageBreak, PageNumber, PageNumberFormat, Paragraph, TextRun } from "../build"; import { AlignmentType, Document, Footer, Header, Packer, PageBreak, PageNumber, PageNumberFormat, Paragraph, TextRun } from "../build";
const doc = new Document();
const header = new Header({ const header = new Header({
children: [ children: [
new Paragraph({ new Paragraph({
@ -26,39 +24,50 @@ const footer = new Footer({
children: [new Paragraph("Foo Bar corp. ")], children: [new Paragraph("Foo Bar corp. ")],
}); });
doc.addSection({ const doc = new Document({
headers: { sections: [
default: header, {
}, properties: {
footers: { page: {
default: footer, pageNumbers: {
}, start: 1,
properties: { formatType: PageNumberFormat.DECIMAL,
pageNumberStart: 1, },
pageNumberFormatType: PageNumberFormat.DECIMAL, },
}, },
children: [ headers: {
new Paragraph({ default: header,
children: [new TextRun("Section 1"), new PageBreak(), new TextRun("Section 1"), new PageBreak()], },
}), footers: {
], default: footer,
}); },
children: [
doc.addSection({ new Paragraph({
headers: { children: [new TextRun("Section 1"), new PageBreak(), new TextRun("Section 1"), new PageBreak()],
default: header, }),
}, ],
footers: { },
default: footer, {
}, properties: {
properties: { page: {
pageNumberStart: 1, pageNumbers: {
pageNumberFormatType: PageNumberFormat.DECIMAL, start: 1,
}, formatType: PageNumberFormat.DECIMAL,
children: [ },
new Paragraph({ },
children: [new TextRun("Section 2"), new PageBreak(), new TextRun("Section 2"), new PageBreak()], },
}), headers: {
default: header,
},
footers: {
default: footer,
},
children: [
new Paragraph({
children: [new TextRun("Section 2"), new PageBreak(), new TextRun("Section 2"), new PageBreak()],
}),
],
},
], ],
}); });

View File

@ -3,26 +3,28 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, Packer, Paragraph, SectionVerticalAlignValue, TextRun } from "../build"; import { Document, Packer, Paragraph, SectionVerticalAlignValue, TextRun } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
properties: { properties: {
verticalAlign: SectionVerticalAlignValue.CENTER, verticalAlign: SectionVerticalAlignValue.CENTER,
}, },
children: [
new Paragraph({
children: [ children: [
new TextRun("Hello World"), new Paragraph({
new TextRun({ children: [
text: "Foo Bar", new TextRun("Hello World"),
bold: true, new TextRun({
}), text: "Foo Bar",
new TextRun({ bold: true,
text: "\tGithub is the best", }),
bold: true, new TextRun({
text: "\tGithub is the best",
bold: true,
}),
],
}), }),
], ],
}), },
], ],
}); });

View File

@ -15,8 +15,6 @@ import {
VerticalAlign, VerticalAlign,
} from "../build"; } from "../build";
const doc = new Document();
const table = new Table({ const table = new Table({
rows: [ rows: [
new TableRow({ new TableRow({
@ -160,7 +158,9 @@ const noBorderTable = new Table({
], ],
}); });
doc.addSection({ children: [table, new Paragraph("Hello"), noBorderTable] }); const doc = new Document({
sections: [{ children: [table, new Paragraph("Hello"), noBorderTable] }],
});
Packer.toBuffer(doc).then((buffer) => { Packer.toBuffer(doc).then((buffer) => {
fs.writeFileSync("My Document.docx", buffer); fs.writeFileSync("My Document.docx", buffer);

View File

@ -12,120 +12,122 @@ import {
VerticalPositionRelativeFrom, VerticalPositionRelativeFrom,
} from "../build"; } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
children: [
new Paragraph("Hello World"),
new Paragraph({
children: [ children: [
new ImageRun({ new Paragraph("Hello World"),
data: fs.readFileSync("./demo/images/image1.jpeg"), new Paragraph({
transformation: { children: [
width: 100, new ImageRun({
height: 100, data: fs.readFileSync("./demo/images/image1.jpeg"),
}, transformation: {
width: 100,
height: 100,
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/dog.png").toString("base64"),
transformation: {
width: 100,
height: 100,
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/cat.jpg"),
transformation: {
width: 100,
height: 100,
flip: {
vertical: true,
},
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/parrots.bmp"),
transformation: {
width: 150,
height: 150,
flip: {
horizontal: true,
},
rotation: 225,
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/pizza.gif"),
transformation: {
width: 200,
height: 200,
flip: {
horizontal: true,
vertical: true,
},
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/pizza.gif"),
transformation: {
width: 200,
height: 200,
rotation: 45,
},
floating: {
zIndex: 10,
horizontalPosition: {
offset: 1014400,
},
verticalPosition: {
offset: 1014400,
},
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/cat.jpg"),
transformation: {
width: 200,
height: 200,
},
floating: {
zIndex: 5,
horizontalPosition: {
relative: HorizontalPositionRelativeFrom.PAGE,
align: HorizontalPositionAlign.RIGHT,
},
verticalPosition: {
relative: VerticalPositionRelativeFrom.PAGE,
align: VerticalPositionAlign.BOTTOM,
},
},
}),
],
}), }),
], ],
}), },
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/dog.png").toString("base64"),
transformation: {
width: 100,
height: 100,
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/cat.jpg"),
transformation: {
width: 100,
height: 100,
flip: {
vertical: true,
},
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/parrots.bmp"),
transformation: {
width: 150,
height: 150,
flip: {
horizontal: true,
},
rotation: 225,
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/pizza.gif"),
transformation: {
width: 200,
height: 200,
flip: {
horizontal: true,
vertical: true,
},
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/pizza.gif"),
transformation: {
width: 200,
height: 200,
rotation: 45,
},
floating: {
zIndex: 10,
horizontalPosition: {
offset: 1014400,
},
verticalPosition: {
offset: 1014400,
},
},
}),
],
}),
new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/cat.jpg"),
transformation: {
width: 200,
height: 200,
},
floating: {
zIndex: 5,
horizontalPosition: {
relative: HorizontalPositionRelativeFrom.PAGE,
align: HorizontalPositionAlign.RIGHT,
},
verticalPosition: {
relative: VerticalPositionRelativeFrom.PAGE,
align: VerticalPositionAlign.BOTTOM,
},
},
}),
],
}),
], ],
}); });

View File

@ -3,8 +3,6 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, HeadingLevel, ImageRun, Packer, Paragraph, Table, TableCell, TableRow, VerticalAlign } from "../build"; import { Document, HeadingLevel, ImageRun, Packer, Paragraph, Table, TableCell, TableRow, VerticalAlign } from "../build";
const doc = new Document();
const table = new Table({ const table = new Table({
rows: [ rows: [
new TableRow({ new TableRow({
@ -66,24 +64,28 @@ const table = new Table({
], ],
}); });
doc.addSection({ const doc = new Document({
children: [ sections: [
new Paragraph({ {
text: "Hello World",
heading: HeadingLevel.HEADING_1,
}),
table,
new Paragraph({
children: [ children: [
new ImageRun({ new Paragraph({
data: fs.readFileSync("./demo/images/pizza.gif"), text: "Hello World",
transformation: { heading: HeadingLevel.HEADING_1,
width: 100, }),
height: 100, table,
}, new Paragraph({
children: [
new ImageRun({
data: fs.readFileSync("./demo/images/pizza.gif"),
transformation: {
width: 100,
height: 100,
},
}),
],
}), }),
], ],
}), },
], ],
}); });

View File

@ -25,30 +25,31 @@ const doc = new Document({
}, },
], ],
}, },
}); sections: [
{
doc.addSection({
children: [
new Paragraph({
children: [ children: [
new TextRun({ new Paragraph({
text: "Foo bar", children: [
style: "myRedStyle", new TextRun({
text: "Foo bar",
style: "myRedStyle",
}),
],
}),
new Paragraph({
children: [
new TextRun({
text: "First Word",
style: "strong",
}),
new TextRun({
text:
" - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
}),
],
}), }),
], ],
}), },
new Paragraph({
children: [
new TextRun({
text: "First Word",
style: "strong",
}),
new TextRun({
text:
" - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
}),
],
}),
], ],
}); });

View File

@ -18,17 +18,18 @@ const doc = new Document({
}, },
], ],
}, },
}); sections: [
{
doc.addSection({ children: [
children: [ new Paragraph({
new Paragraph({ text: "KFCを食べるのが好き",
text: "KFCを食べるのが好き", heading: HeadingLevel.HEADING_1,
heading: HeadingLevel.HEADING_1, }),
}), new Paragraph({
new Paragraph({ text: "こんにちは",
text: "こんにちは", }),
}), ],
},
], ],
}); });

View File

@ -41,47 +41,48 @@ const doc = new Document({
}, },
], ],
}, },
}); sections: [
{
doc.addSection({
children: [
new Paragraph({
text: "中文和英文 Chinese and English",
heading: HeadingLevel.HEADING_1,
}),
new Paragraph({
text: "中文和英文 Chinese and English",
}),
new Paragraph({
children: [ children: [
new TextRun({ new Paragraph({
text: "中文和英文 Chinese and English", text: "中文和英文 Chinese and English",
font: { eastAsia: "SimSun" }, // set eastAsia to "SimSun". heading: HeadingLevel.HEADING_1,
// The ascii characters will use the default font ("Times") specified in paragraphStyles }),
new Paragraph({
text: "中文和英文 Chinese and English",
}),
new Paragraph({
children: [
new TextRun({
text: "中文和英文 Chinese and English",
font: { eastAsia: "SimSun" }, // set eastAsia to "SimSun".
// The ascii characters will use the default font ("Times") specified in paragraphStyles
}),
],
}),
new Paragraph({
text: `店様付旅母正役基社発破班。発治治京岡局本因追意金紀統責郵滴尽。立功日庁重天富評界明済不着法返祉経正引行。載区列防新目治日群付無人道言越名。界安無死専体風木人教録覧訃。女問堂容県作先芸便効証帯債土全極的日。能山中岡仕関攻井季接店線幌温後率事阜止。成間路行究今式歌像祉帯式媛読徹。安行息古入出文侵監株登部席内文第珍鶴問用。
編竹入俳多応日氏陸福芸北供動。情績拠僧肺軍油能認郷翌南対韓短東食束兵晶。政予任習口佐所当止市告号。悩申無式立医毎部観潟訴菱権。発臼背郎上予配光記芸注然出。梨場株以政囲下球品材県動政押婚面見。米共試使落帳遅毅間三子開。問与大八地芸第線体架辺今死。押構草齢戦重最変社豪記目盗連報準周込。系貸劇様重鷲始能質村異社学動導勤。
残様的荻仲刺局標績供質球就雄。考和母問者役尊紙推新経革個事編安観。益学北日著楽車山勢流泉四犯投台戒設対臨百。危謄初治穴委済本索労刊回。月写政覧女事棋違年終索情響白子泉転企堀社。江遊著西高開面毎分芸責成創査全判調目止懇。原育会夏作売望人転乱融抜心。制川供健水示囲阜厚高右断季人役。持面必日暮気管像冬間影図健行格阪。
来入工速会健評下町慮大貸社一見園外申憶。服豊舞入面沢交使奥見記写意岩。北観提女刊液城共五擦相売田合是由読。回歳売苦定記点郎意増賛治北渡本応。受送文携村陸情静了申注際。順負子研済老上変女産第内無費携投展達。東初乗回動合語学待聴暮沢流全場導敷記賞次。更物中備著後渡売第部時禁新田木下昨。備護起織服久権意全海馬適応。
幸速団供地信討川安矛場消学年。去茂玉東今要出約元教負限載始今簡。編掲証的情仕渡室手映法部始。紙反語清阪曜税受知選謝個印観聞。教人超死準無者参生撤技真価椿景破市見国。左需臓道力趣暮際丁高会近部敗岡力当社。壊態毒期波超長写島断兆国世行共絞私報。反野番点図択女撃脱案情王援。減属考論月院催者門料約覧市戦。
山部午金査投立集争教殺巣作世動北部応。通負考隙問粛中帯閉要程規化小。橋棋互界時引就現省竹去子無系容米。竹転起日本新田強済購書区庁集作容同会窓教。文公神転待究挙登投川選囲針能楽路断出歌。祥新現寄公史真玉属元始員金抜関前百衝能。国眺暮囲世嘘面外営国内報夜九掲事春葉。来月刊台先良理著自供法投。通渡請当月学安首一押実展介況。
法優分独込右得里記域目順供進乗。憂婚転峰大写医投社曲題任能務熱県展覧港専。栄余歯真著改追事作果石芸。青感将南便再転領鈴投提鉄索競虎師体物想。牲打迎達携度開技書催掲安去変念座。革混疑生採就枢当住回県組北意寛。爆新和級掲交象温十賛展木開有結日。新海辺小除京物興量写界裁上。文師建関面取質也底沼画者図空医心無季。
高館湯転名気業以際置講詰方活礎組調軽際。発変東作訪乃小化理利提目気。極季本問号面帯勤戦行新禁情堀郎携。座所転再祥業必変昌今歩佐王立抗後養崩。支物猪躍芸整縦焦供防続相護治時語朝分刊定。綿田幸崎責本欲間載神調崎答志政報与速美載。飯治止稿原先明画森群進見情幕。女民館終調質並伝車慌供科。支田国傷自動献疑討医足公成公主断的望。
責開児食福実帰治師今策今。水重寺圧医観送連東者秒途。選央力律式開作掲写様階組戦写型紙。式国販時天遣国出難共前次領体康稲住転。査見保重議原速群者内月正連。爾天膨装芸別巨平運数準三浜念載創県奈飛提。素京発揮田談気党示見象定電類代級。善返跡国有話権入猛府週亡辞馬脳。関残主祐雪塚去集村完海関文受載表川護照立。
発闘美慎健育旅布容広互無秋認天歌媛芸。転器合読県増認会賞倒点系。食気母服絵知去祝芸車報熱勝。能貿月更障文的欠賞現覇声敏施会。懲病写昼法族業律記聡生開緊楽暮護。東地二員者説盟治害討面提。第北乗査庭年近的禁疑報方店記必迷都流通。聞有力前愛院梨野関業前訳本清滋補。蒲読火死勝広保会婚際気二由保国。用君込村需起相点選紙拡氏訃不。`,
}), }),
], ],
}), },
new Paragraph({
text: `店様付旅母正役基社発破班。発治治京岡局本因追意金紀統責郵滴尽。立功日庁重天富評界明済不着法返祉経正引行。載区列防新目治日群付無人道言越名。界安無死専体風木人教録覧訃。女問堂容県作先芸便効証帯債土全極的日。能山中岡仕関攻井季接店線幌温後率事阜止。成間路行究今式歌像祉帯式媛読徹。安行息古入出文侵監株登部席内文第珍鶴問用。
編竹入俳多応日氏陸福芸北供動。情績拠僧肺軍油能認郷翌南対韓短東食束兵晶。政予任習口佐所当止市告号。悩申無式立医毎部観潟訴菱権。発臼背郎上予配光記芸注然出。梨場株以政囲下球品材県動政押婚面見。米共試使落帳遅毅間三子開。問与大八地芸第線体架辺今死。押構草齢戦重最変社豪記目盗連報準周込。系貸劇様重鷲始能質村異社学動導勤。
残様的荻仲刺局標績供質球就雄。考和母問者役尊紙推新経革個事編安観。益学北日著楽車山勢流泉四犯投台戒設対臨百。危謄初治穴委済本索労刊回。月写政覧女事棋違年終索情響白子泉転企堀社。江遊著西高開面毎分芸責成創査全判調目止懇。原育会夏作売望人転乱融抜心。制川供健水示囲阜厚高右断季人役。持面必日暮気管像冬間影図健行格阪。
来入工速会健評下町慮大貸社一見園外申憶。服豊舞入面沢交使奥見記写意岩。北観提女刊液城共五擦相売田合是由読。回歳売苦定記点郎意増賛治北渡本応。受送文携村陸情静了申注際。順負子研済老上変女産第内無費携投展達。東初乗回動合語学待聴暮沢流全場導敷記賞次。更物中備著後渡売第部時禁新田木下昨。備護起織服久権意全海馬適応。
幸速団供地信討川安矛場消学年。去茂玉東今要出約元教負限載始今簡。編掲証的情仕渡室手映法部始。紙反語清阪曜税受知選謝個印観聞。教人超死準無者参生撤技真価椿景破市見国。左需臓道力趣暮際丁高会近部敗岡力当社。壊態毒期波超長写島断兆国世行共絞私報。反野番点図択女撃脱案情王援。減属考論月院催者門料約覧市戦。
山部午金査投立集争教殺巣作世動北部応。通負考隙問粛中帯閉要程規化小。橋棋互界時引就現省竹去子無系容米。竹転起日本新田強済購書区庁集作容同会窓教。文公神転待究挙登投川選囲針能楽路断出歌。祥新現寄公史真玉属元始員金抜関前百衝能。国眺暮囲世嘘面外営国内報夜九掲事春葉。来月刊台先良理著自供法投。通渡請当月学安首一押実展介況。
法優分独込右得里記域目順供進乗。憂婚転峰大写医投社曲題任能務熱県展覧港専。栄余歯真著改追事作果石芸。青感将南便再転領鈴投提鉄索競虎師体物想。牲打迎達携度開技書催掲安去変念座。革混疑生採就枢当住回県組北意寛。爆新和級掲交象温十賛展木開有結日。新海辺小除京物興量写界裁上。文師建関面取質也底沼画者図空医心無季。
高館湯転名気業以際置講詰方活礎組調軽際。発変東作訪乃小化理利提目気。極季本問号面帯勤戦行新禁情堀郎携。座所転再祥業必変昌今歩佐王立抗後養崩。支物猪躍芸整縦焦供防続相護治時語朝分刊定。綿田幸崎責本欲間載神調崎答志政報与速美載。飯治止稿原先明画森群進見情幕。女民館終調質並伝車慌供科。支田国傷自動献疑討医足公成公主断的望。
責開児食福実帰治師今策今。水重寺圧医観送連東者秒途。選央力律式開作掲写様階組戦写型紙。式国販時天遣国出難共前次領体康稲住転。査見保重議原速群者内月正連。爾天膨装芸別巨平運数準三浜念載創県奈飛提。素京発揮田談気党示見象定電類代級。善返跡国有話権入猛府週亡辞馬脳。関残主祐雪塚去集村完海関文受載表川護照立。
発闘美慎健育旅布容広互無秋認天歌媛芸。転器合読県増認会賞倒点系。食気母服絵知去祝芸車報熱勝。能貿月更障文的欠賞現覇声敏施会。懲病写昼法族業律記聡生開緊楽暮護。東地二員者説盟治害討面提。第北乗査庭年近的禁疑報方店記必迷都流通。聞有力前愛院梨野関業前訳本清滋補。蒲読火死勝広保会婚際気二由保国。用君込村需起相点選紙拡氏訃不。`,
}),
], ],
}); });

View File

@ -22,270 +22,272 @@ import {
TextRun, TextRun,
} from "../build"; } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
properties: {}, properties: {},
children: [
new Paragraph({
children: [ children: [
new Math({ new Paragraph({
children: [ children: [
new MathRun("2+2"), new Math({
new MathFraction({
numerator: [new MathRun("hi")],
denominator: [new MathRun("2")],
}),
],
}),
new TextRun({
text: "Foo Bar",
bold: true,
}),
],
}),
new Paragraph({
children: [
new Math({
children: [
new MathFraction({
numerator: [
new MathRun("1"),
new MathRadical({
children: [new MathRun("2")],
}),
],
denominator: [new MathRun("2")],
}),
],
}),
],
}),
new Paragraph({
children: [
new Math({
children: [
new MathSum({
children: [new MathRun("test")],
}),
new MathSum({
children: [
new MathSuperScript({
children: [new MathRun("e")],
superScript: [new MathRun("2")],
}),
],
subScript: [new MathRun("i")],
}),
new MathSum({
children: [
new MathRadical({
children: [new MathRun("i")],
}),
],
subScript: [new MathRun("i")],
superScript: [new MathRun("10")],
}),
],
}),
],
}),
new Paragraph({
children: [
new Math({
children: [
new MathSuperScript({
children: [new MathRun("test")],
superScript: [new MathRun("hello")],
}),
],
}),
],
}),
new Paragraph({
children: [
new Math({
children: [
new MathSubScript({
children: [new MathRun("test")],
subScript: [new MathRun("hello")],
}),
],
}),
],
}),
new Paragraph({
children: [
new Math({
children: [
new MathSubScript({
children: [new MathRun("x")],
subScript: [
new MathSuperScript({
children: [new MathRun("y")],
superScript: [new MathRun("2")],
}),
],
}),
],
}),
],
}),
new Paragraph({
children: [
new Math({
children: [
new MathSubSuperScript({
children: [new MathRun("test")],
superScript: [new MathRun("hello")],
subScript: [new MathRun("world")],
}),
],
}),
],
}),
new Paragraph({
children: [
new Math({
children: [
new MathPreSubSuperScript({
children: [new MathRun("test")],
superScript: [new MathRun("hello")],
subScript: [new MathRun("world")],
}),
],
}),
],
}),
new Paragraph({
children: [
new Math({
children: [
new MathSubScript({
children: [ children: [
new MathRun("2+2"),
new MathFraction({ new MathFraction({
numerator: [new MathRun("1")], numerator: [new MathRun("hi")],
denominator: [new MathRun("2")], denominator: [new MathRun("2")],
}), }),
], ],
subScript: [new MathRun("4")], }),
new TextRun({
text: "Foo Bar",
bold: true,
}), }),
], ],
}), }),
], new Paragraph({
}),
new Paragraph({
children: [
new Math({
children: [ children: [
new MathSubScript({ new Math({
children: [ children: [
new MathRadical({ new MathFraction({
numerator: [
new MathRun("1"),
new MathRadical({
children: [new MathRun("2")],
}),
],
denominator: [new MathRun("2")],
}),
],
}),
],
}),
new Paragraph({
children: [
new Math({
children: [
new MathSum({
children: [new MathRun("test")],
}),
new MathSum({
children: [
new MathSuperScript({
children: [new MathRun("e")],
superScript: [new MathRun("2")],
}),
],
subScript: [new MathRun("i")],
}),
new MathSum({
children: [
new MathRadical({
children: [new MathRun("i")],
}),
],
subScript: [new MathRun("i")],
superScript: [new MathRun("10")],
}),
],
}),
],
}),
new Paragraph({
children: [
new Math({
children: [
new MathSuperScript({
children: [new MathRun("test")],
superScript: [new MathRun("hello")],
}),
],
}),
],
}),
new Paragraph({
children: [
new Math({
children: [
new MathSubScript({
children: [new MathRun("test")],
subScript: [new MathRun("hello")],
}),
],
}),
],
}),
new Paragraph({
children: [
new Math({
children: [
new MathSubScript({
children: [new MathRun("x")],
subScript: [
new MathSuperScript({
children: [new MathRun("y")],
superScript: [new MathRun("2")],
}),
],
}),
],
}),
],
}),
new Paragraph({
children: [
new Math({
children: [
new MathSubSuperScript({
children: [new MathRun("test")],
superScript: [new MathRun("hello")],
subScript: [new MathRun("world")],
}),
],
}),
],
}),
new Paragraph({
children: [
new Math({
children: [
new MathPreSubSuperScript({
children: [new MathRun("test")],
superScript: [new MathRun("hello")],
subScript: [new MathRun("world")],
}),
],
}),
],
}),
new Paragraph({
children: [
new Math({
children: [
new MathSubScript({
children: [ children: [
new MathFraction({ new MathFraction({
numerator: [new MathRun("1")], numerator: [new MathRun("1")],
denominator: [new MathRun("2")], denominator: [new MathRun("2")],
}), }),
], ],
degree: [new MathRun("4")], subScript: [new MathRun("4")],
}),
],
subScript: [new MathRun("x")],
}),
],
}),
],
}),
new Paragraph({
children: [
new Math({
children: [
new MathRadical({
children: [new MathRun("4")],
}),
],
}),
],
}),
new Paragraph({
children: [
new Math({
children: [
new MathFunction({
name: [
new MathSuperScript({
children: [new MathRun("cos")],
superScript: [new MathRun("-1")],
}),
],
children: [new MathRun("100")],
}),
new MathRun("×"),
new MathFunction({
name: [new MathRun("sin")],
children: [new MathRun("360")],
}),
new MathRun("= x"),
],
}),
],
}),
new Paragraph({
children: [
new Math({
children: [
new MathRoundBrackets({
children: [
new MathFraction({
numerator: [new MathRun("1")],
denominator: [new MathRun("2")],
}),
],
}),
new MathSquareBrackets({
children: [
new MathFraction({
numerator: [new MathRun("1")],
denominator: [new MathRun("2")],
}),
],
}),
new MathCurlyBrackets({
children: [
new MathFraction({
numerator: [new MathRun("1")],
denominator: [new MathRun("2")],
}),
],
}),
new MathAngledBrackets({
children: [
new MathFraction({
numerator: [new MathRun("1")],
denominator: [new MathRun("2")],
}), }),
], ],
}), }),
], ],
}), }),
], new Paragraph({
}),
new Paragraph({
children: [
new Math({
children: [ children: [
new MathFraction({ new Math({
numerator: [ children: [
new MathSubScript({
children: [
new MathRadical({
children: [
new MathFraction({
numerator: [new MathRun("1")],
denominator: [new MathRun("2")],
}),
],
degree: [new MathRun("4")],
}),
],
subScript: [new MathRun("x")],
}),
],
}),
],
}),
new Paragraph({
children: [
new Math({
children: [
new MathRadical({ new MathRadical({
children: [new MathRun("4")], children: [new MathRun("4")],
}), }),
], ],
denominator: [new MathRun("2a")], }),
],
}),
new Paragraph({
children: [
new Math({
children: [
new MathFunction({
name: [
new MathSuperScript({
children: [new MathRun("cos")],
superScript: [new MathRun("-1")],
}),
],
children: [new MathRun("100")],
}),
new MathRun("×"),
new MathFunction({
name: [new MathRun("sin")],
children: [new MathRun("360")],
}),
new MathRun("= x"),
],
}),
],
}),
new Paragraph({
children: [
new Math({
children: [
new MathRoundBrackets({
children: [
new MathFraction({
numerator: [new MathRun("1")],
denominator: [new MathRun("2")],
}),
],
}),
new MathSquareBrackets({
children: [
new MathFraction({
numerator: [new MathRun("1")],
denominator: [new MathRun("2")],
}),
],
}),
new MathCurlyBrackets({
children: [
new MathFraction({
numerator: [new MathRun("1")],
denominator: [new MathRun("2")],
}),
],
}),
new MathAngledBrackets({
children: [
new MathFraction({
numerator: [new MathRun("1")],
denominator: [new MathRun("2")],
}),
],
}),
],
}),
],
}),
new Paragraph({
children: [
new Math({
children: [
new MathFraction({
numerator: [
new MathRadical({
children: [new MathRun("4")],
}),
],
denominator: [new MathRun("2a")],
}),
],
}), }),
], ],
}), }),
], ],
}), },
], ],
}); });

View File

@ -7,24 +7,25 @@ const doc = new Document({
background: { background: {
color: "C45911", color: "C45911",
}, },
}); sections: [
{
doc.addSection({ properties: {},
properties: {},
children: [
new Paragraph({
children: [ children: [
new TextRun("Hello World"), new Paragraph({
new TextRun({ children: [
text: "Foo Bar", new TextRun("Hello World"),
bold: true, new TextRun({
}), text: "Foo Bar",
new TextRun({ bold: true,
text: "\tGithub is the best", }),
bold: true, new TextRun({
text: "\tGithub is the best",
bold: true,
}),
],
}), }),
], ],
}), },
], ],
}); });

View File

@ -40,46 +40,47 @@ const doc = new Document({
}, },
], ],
}, },
}); sections: [
{
doc.addSection({ children: [
children: [ new Paragraph({
new Paragraph({ text: "How to make cake",
text: "How to make cake", heading: HeadingLevel.HEADING_1,
heading: HeadingLevel.HEADING_1, }),
}), new Paragraph({
new Paragraph({ text: "Step 1 - Add sugar",
text: "Step 1 - Add sugar", numbering: {
numbering: { reference: "my-number-numbering-reference",
reference: "my-number-numbering-reference", level: 0,
level: 0, },
}, }),
}), new Paragraph({
new Paragraph({ text: "Step 2 - Add wheat",
text: "Step 2 - Add wheat", numbering: {
numbering: { reference: "my-number-numbering-reference",
reference: "my-number-numbering-reference", level: 0,
level: 0, },
}, }),
}), new Paragraph({
new Paragraph({ text: "Step 2a - Stir the wheat in a circle",
text: "Step 2a - Stir the wheat in a circle", numbering: {
numbering: { reference: "my-number-numbering-reference",
reference: "my-number-numbering-reference", level: 1,
level: 1, },
}, }),
}), new Paragraph({
new Paragraph({ text: "Step 3 - Put in oven",
text: "Step 3 - Put in oven", numbering: {
numbering: { reference: "my-number-numbering-reference",
reference: "my-number-numbering-reference", level: 0,
level: 0, },
}, }),
}), new Paragraph({
new Paragraph({ text: "How to make cake",
text: "How to make cake", heading: HeadingLevel.HEADING_1,
heading: HeadingLevel.HEADING_1, }),
}), ],
},
], ],
}); });

View File

@ -3,88 +3,86 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, Packer, Paragraph, TextRun, SectionType } from "../build"; import { Document, Packer, Paragraph, TextRun, SectionType } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
properties: {}, properties: {},
children: [
new Paragraph({
children: [ children: [
new TextRun("Hello World"), new Paragraph({
new TextRun({ children: [
text: "Foo Bar", new TextRun("Hello World"),
bold: true, new TextRun({
text: "Foo Bar",
bold: true,
}),
],
}), }),
], ],
}), },
], {
}); properties: {
type: SectionType.CONTINUOUS,
doc.addSection({ },
properties: {
type: SectionType.CONTINUOUS,
},
children: [
new Paragraph({
children: [ children: [
new TextRun("Hello World"), new Paragraph({
new TextRun({ children: [
text: "Foo Bar", new TextRun("Hello World"),
bold: true, new TextRun({
text: "Foo Bar",
bold: true,
}),
],
}), }),
], ],
}), },
], {
}); properties: {
type: SectionType.ODD_PAGE,
doc.addSection({ },
properties: {
type: SectionType.ODD_PAGE,
},
children: [
new Paragraph({
children: [ children: [
new TextRun("Hello World"), new Paragraph({
new TextRun({ children: [
text: "Foo Bar", new TextRun("Hello World"),
bold: true, new TextRun({
text: "Foo Bar",
bold: true,
}),
],
}), }),
], ],
}), },
], {
}); properties: {
type: SectionType.EVEN_PAGE,
doc.addSection({ },
properties: {
type: SectionType.EVEN_PAGE,
},
children: [
new Paragraph({
children: [ children: [
new TextRun("Hello World"), new Paragraph({
new TextRun({ children: [
text: "Foo Bar", new TextRun("Hello World"),
bold: true, new TextRun({
text: "Foo Bar",
bold: true,
}),
],
}), }),
], ],
}), },
], {
}); properties: {
type: SectionType.NEXT_PAGE,
doc.addSection({ },
properties: {
type: SectionType.NEXT_PAGE,
},
children: [
new Paragraph({
children: [ children: [
new TextRun("Hello World"), new Paragraph({
new TextRun({ children: [
text: "Foo Bar", new TextRun("Hello World"),
bold: true, new TextRun({
text: "Foo Bar",
bold: true,
}),
],
}), }),
], ],
}), },
], ],
}); });

View File

@ -3,44 +3,46 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, Footer, Header, Packer, Paragraph } from "../build"; import { Document, Footer, Header, Packer, Paragraph } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
properties: { properties: {
header: 100, header: 100,
footer: 50, footer: 50,
}, },
headers: { headers: {
default: new Header({ default: new Header({
children: [ children: [
new Paragraph({ new Paragraph({
text: "Header text", text: "Header text",
indent: { indent: {
left: -400, left: -400,
}, },
}),
new Paragraph({
text: "Some more header text",
indent: {
left: -600,
},
}),
],
}), }),
new Paragraph({ },
text: "Some more header text", footers: {
indent: { default: new Footer({
left: -600, children: [
}, new Paragraph({
text: "Footer text",
indent: {
left: -400,
},
}),
],
}), }),
], },
}), children: [new Paragraph("Hello World")],
}, },
footers: { ],
default: new Footer({
children: [
new Paragraph({
text: "Footer text",
indent: {
left: -400,
},
}),
],
}),
},
children: [new Paragraph("Hello World")],
}); });
Packer.toBuffer(doc).then((buffer) => { Packer.toBuffer(doc).then((buffer) => {

View File

@ -3,35 +3,41 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, HeadingLevel, Packer, Paragraph, TextRun } from "../build"; import { Document, HeadingLevel, Packer, Paragraph, TextRun } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
margins: { properties: {
top: 0, page: {
right: 0, margin: {
bottom: 0, top: 0,
left: 0, right: 0,
}, bottom: 0,
children: [ left: 0,
new Paragraph({ },
},
},
children: [ children: [
new TextRun("Hello World"), new Paragraph({
new TextRun({ children: [
text: "Foo bar", new TextRun("Hello World"),
bold: true, new TextRun({
text: "Foo bar",
bold: true,
}),
new TextRun({
text: "\tGithub is the best",
bold: true,
}),
],
}), }),
new TextRun({ new Paragraph({
text: "\tGithub is the best", text: "Hello World",
bold: true, heading: HeadingLevel.HEADING_1,
}), }),
new Paragraph("Foo bar"),
new Paragraph("Github is the best"),
], ],
}), },
new Paragraph({
text: "Hello World",
heading: HeadingLevel.HEADING_1,
}),
new Paragraph("Foo bar"),
new Paragraph("Github is the best"),
], ],
}); });

View File

@ -26,6 +26,27 @@ import {
Note that this setting enables to track *new changes* after teh file is generated, so this example will still show inserted and deleted text runs when you remove it. Note that this setting enables to track *new changes* after teh file is generated, so this example will still show inserted and deleted text runs when you remove it.
*/ */
const paragraph = new Paragraph({
children: [
new TextRun("This is a simple demo "),
new TextRun({
text: "on how to ",
}),
new InsertedTextRun({
text: "mark a text as an insertion ",
id: 0,
author: "Firstname Lastname",
date: "2020-10-06T09:00:00Z",
}),
new DeletedTextRun({
text: "or a deletion.",
id: 1,
author: "Firstname Lastname",
date: "2020-10-06T09:00:00Z",
}),
],
});
const doc = new Document({ const doc = new Document({
footnotes: { footnotes: {
1: { 1: {
@ -53,96 +74,76 @@ const doc = new Document({
features: { features: {
trackRevisions: true, trackRevisions: true,
}, },
}); sections: [
{
const paragraph = new Paragraph({ properties: {},
children: [
new TextRun("This is a simple demo "),
new TextRun({
text: "on how to ",
}),
new InsertedTextRun({
text: "mark a text as an insertion ",
id: 0,
author: "Firstname Lastname",
date: "2020-10-06T09:00:00Z",
}),
new DeletedTextRun({
text: "or a deletion.",
id: 1,
author: "Firstname Lastname",
date: "2020-10-06T09:00:00Z",
}),
],
});
doc.addSection({
properties: {},
children: [
paragraph,
new Paragraph({
children: [
new TextRun("This is a demo "),
new DeletedTextRun({
break: 1,
text: "in order",
color: "red",
bold: true,
size: 24,
font: {
name: "Garamond",
},
shading: {
type: ShadingType.REVERSE_DIAGONAL_STRIPE,
color: "00FFFF",
fill: "FF0000",
},
id: 2,
author: "Firstname Lastname",
date: "2020-10-06T09:00:00Z",
}),
new InsertedTextRun({
text: "to show how to ",
bold: false,
id: 3,
author: "Firstname Lastname",
date: "2020-10-06T09:05:00Z",
}),
new TextRun({
bold: true,
children: ["\tuse Inserted and Deleted TextRuns.", new FootnoteReferenceRun(1)],
}),
],
}),
],
footers: {
default: new Footer({
children: [ children: [
paragraph,
new Paragraph({ new Paragraph({
alignment: AlignmentType.CENTER,
children: [ children: [
new TextRun("Awesome LLC"), new TextRun("This is a demo "),
new TextRun({
children: ["Page Number: ", PageNumber.CURRENT],
}),
new DeletedTextRun({ new DeletedTextRun({
children: [" to ", PageNumber.TOTAL_PAGES], break: 1,
id: 4, text: "in order",
color: "red",
bold: true,
size: 24,
font: {
name: "Garamond",
},
shading: {
type: ShadingType.REVERSE_DIAGONAL_STRIPE,
color: "00FFFF",
fill: "FF0000",
},
id: 2,
author: "Firstname Lastname", author: "Firstname Lastname",
date: "2020-10-06T09:05:00Z", date: "2020-10-06T09:00:00Z",
}), }),
new InsertedTextRun({ new InsertedTextRun({
children: [" from ", PageNumber.TOTAL_PAGES], text: "to show how to ",
bold: true, bold: false,
id: 5, id: 3,
author: "Firstname Lastname", author: "Firstname Lastname",
date: "2020-10-06T09:05:00Z", date: "2020-10-06T09:05:00Z",
}), }),
new TextRun({
bold: true,
children: ["\tuse Inserted and Deleted TextRuns.", new FootnoteReferenceRun(1)],
}),
], ],
}), }),
], ],
}), footers: {
}, default: new Footer({
children: [
new Paragraph({
alignment: AlignmentType.CENTER,
children: [
new TextRun("Awesome LLC"),
new TextRun({
children: ["Page Number: ", PageNumber.CURRENT],
}),
new DeletedTextRun({
children: [" to ", PageNumber.TOTAL_PAGES],
id: 4,
author: "Firstname Lastname",
date: "2020-10-06T09:05:00Z",
}),
new InsertedTextRun({
children: [" from ", PageNumber.TOTAL_PAGES],
bold: true,
id: 5,
author: "Firstname Lastname",
date: "2020-10-06T09:05:00Z",
}),
],
}),
],
}),
},
},
],
}); });
Packer.toBuffer(doc).then((buffer) => { Packer.toBuffer(doc).then((buffer) => {

View File

@ -3,66 +3,68 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, FrameAnchorType, HorizontalPositionAlign, Packer, Paragraph, TextRun, VerticalPositionAlign } from "../build"; import { Document, FrameAnchorType, HorizontalPositionAlign, Packer, Paragraph, TextRun, VerticalPositionAlign } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
properties: {}, properties: {},
children: [
new Paragraph({
frame: {
position: {
x: 1000,
y: 3000,
},
width: 4000,
height: 1000,
anchor: {
horizontal: FrameAnchorType.MARGIN,
vertical: FrameAnchorType.MARGIN,
},
alignment: {
x: HorizontalPositionAlign.CENTER,
y: VerticalPositionAlign.TOP,
},
},
border: {
top: {
color: "auto",
space: 1,
value: "single",
size: 6,
},
bottom: {
color: "auto",
space: 1,
value: "single",
size: 6,
},
left: {
color: "auto",
space: 1,
value: "single",
size: 6,
},
right: {
color: "auto",
space: 1,
value: "single",
size: 6,
},
},
children: [ children: [
new TextRun("Hello World"), new Paragraph({
new TextRun({ frame: {
text: "Foo Bar", position: {
bold: true, x: 1000,
}), y: 3000,
new TextRun({ },
text: "\tGithub is the best", width: 4000,
bold: true, height: 1000,
anchor: {
horizontal: FrameAnchorType.MARGIN,
vertical: FrameAnchorType.MARGIN,
},
alignment: {
x: HorizontalPositionAlign.CENTER,
y: VerticalPositionAlign.TOP,
},
},
border: {
top: {
color: "auto",
space: 1,
value: "single",
size: 6,
},
bottom: {
color: "auto",
space: 1,
value: "single",
size: 6,
},
left: {
color: "auto",
space: 1,
value: "single",
size: 6,
},
right: {
color: "auto",
space: 1,
value: "single",
size: 6,
},
},
children: [
new TextRun("Hello World"),
new TextRun({
text: "Foo Bar",
bold: true,
}),
new TextRun({
text: "\tGithub is the best",
bold: true,
}),
],
}), }),
], ],
}), },
], ],
}); });

View File

@ -3,29 +3,31 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, LineRuleType, Packer, Paragraph, TextRun } from "../build"; import { Document, LineRuleType, Packer, Paragraph, TextRun } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
properties: {}, properties: {},
children: [
new Paragraph({
spacing: {
after: 5000,
before: 5000,
},
children: [new TextRun("Hello World")],
}),
new Paragraph({
spacing: {
line: 2000,
lineRule: LineRuleType.AUTO,
},
children: [ children: [
new TextRun( new Paragraph({
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed turpis ex, aliquet et faucibus quis, euismod in odio. Fusce gravida tempor nunc sed lacinia. Nulla sed dolor fringilla, fermentum libero ut, egestas ex. Donec pellentesque metus non orci lacinia bibendum. Cras porta ex et mollis hendrerit. Suspendisse id lectus suscipit, elementum lacus eu, convallis felis. Fusce sed bibendum dolor, id posuere ligula. Aliquam eu elit ut urna eleifend vestibulum. Praesent condimentum at turpis sed scelerisque. Suspendisse porttitor metus nec vestibulum egestas. Sed in eros sapien. Morbi efficitur placerat est a consequat. Nunc bibendum porttitor mi nec tempus. Morbi dictum augue porttitor nisi sodales sodales.", spacing: {
), after: 5000,
before: 5000,
},
children: [new TextRun("Hello World")],
}),
new Paragraph({
spacing: {
line: 2000,
lineRule: LineRuleType.AUTO,
},
children: [
new TextRun(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed turpis ex, aliquet et faucibus quis, euismod in odio. Fusce gravida tempor nunc sed lacinia. Nulla sed dolor fringilla, fermentum libero ut, egestas ex. Donec pellentesque metus non orci lacinia bibendum. Cras porta ex et mollis hendrerit. Suspendisse id lectus suscipit, elementum lacus eu, convallis felis. Fusce sed bibendum dolor, id posuere ligula. Aliquam eu elit ut urna eleifend vestibulum. Praesent condimentum at turpis sed scelerisque. Suspendisse porttitor metus nec vestibulum egestas. Sed in eros sapien. Morbi efficitur placerat est a consequat. Nunc bibendum porttitor mi nec tempus. Morbi dictum augue porttitor nisi sodales sodales.",
),
],
}),
], ],
}), },
], ],
}); });

View File

@ -5,63 +5,64 @@ import { Document, Footer, Header, Packer, PageBreak, Paragraph, TextRun } from
const doc = new Document({ const doc = new Document({
evenAndOddHeaderAndFooters: true, evenAndOddHeaderAndFooters: true,
}); sections: [
{
doc.addSection({ headers: {
headers: { default: new Header({
default: new Header({ children: [
new Paragraph({
text: "Odd Header text",
}),
new Paragraph({
text: "Odd - Some more header text",
}),
],
}),
even: new Header({
children: [
new Paragraph({
text: "Even header text",
}),
new Paragraph({
text: "Even - Some more header text",
}),
],
}),
},
footers: {
default: new Footer({
children: [
new Paragraph({
text: "Odd Footer text",
}),
],
}),
even: new Footer({
children: [
new Paragraph({
text: "Even Cool Footer text",
}),
],
}),
},
children: [ children: [
new Paragraph({ new Paragraph({
text: "Odd Header text", children: [new TextRun("Hello World 1"), new PageBreak()],
}), }),
new Paragraph({ new Paragraph({
text: "Odd - Some more header text", children: [new TextRun("Hello World 2"), new PageBreak()],
}),
new Paragraph({
children: [new TextRun("Hello World 3"), new PageBreak()],
}),
new Paragraph({
children: [new TextRun("Hello World 4"), new PageBreak()],
}),
new Paragraph({
children: [new TextRun("Hello World 5"), new PageBreak()],
}), }),
], ],
}), },
even: new Header({
children: [
new Paragraph({
text: "Even header text",
}),
new Paragraph({
text: "Even - Some more header text",
}),
],
}),
},
footers: {
default: new Footer({
children: [
new Paragraph({
text: "Odd Footer text",
}),
],
}),
even: new Footer({
children: [
new Paragraph({
text: "Even Cool Footer text",
}),
],
}),
},
children: [
new Paragraph({
children: [new TextRun("Hello World 1"), new PageBreak()],
}),
new Paragraph({
children: [new TextRun("Hello World 2"), new PageBreak()],
}),
new Paragraph({
children: [new TextRun("Hello World 3"), new PageBreak()],
}),
new Paragraph({
children: [new TextRun("Hello World 4"), new PageBreak()],
}),
new Paragraph({
children: [new TextRun("Hello World 5"), new PageBreak()],
}),
], ],
}); });

View File

@ -3,13 +3,19 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, Packer, PageOrientation, Paragraph } from "../build"; import { Document, Packer, PageOrientation, Paragraph } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
size: { properties: {
orientation: PageOrientation.LANDSCAPE, page: {
}, size: {
children: [new Paragraph("Hello World")], orientation: PageOrientation.LANDSCAPE,
},
},
},
children: [new Paragraph("Hello World")],
},
],
}); });
Packer.toBuffer(doc).then((buffer) => { Packer.toBuffer(doc).then((buffer) => {

View File

@ -3,20 +3,22 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, Footer, Header, Packer, Paragraph } from "../build"; import { Document, Footer, Header, Packer, Paragraph } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
headers: { headers: {
default: new Header({ default: new Header({
children: [new Paragraph("Header text")], children: [new Paragraph("Header text")],
}), }),
}, },
footers: { footers: {
default: new Footer({ default: new Footer({
children: [new Paragraph("Footer text")], children: [new Paragraph("Footer text")],
}), }),
}, },
children: [new Paragraph("Hello World")], children: [new Paragraph("Hello World")],
},
],
}); });
Packer.toBuffer(doc).then((buffer) => { Packer.toBuffer(doc).then((buffer) => {

View File

@ -3,44 +3,46 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, Footer, Header, ImageRun, Packer, Paragraph } from "../build"; import { Document, Footer, Header, ImageRun, Packer, Paragraph } from "../build";
const doc = new Document(); const doc = new Document({
sections: [
doc.addSection({ {
headers: { headers: {
default: new Header({ default: new Header({
children: [
new Paragraph({
children: [ children: [
new ImageRun({ new Paragraph({
data: fs.readFileSync("./demo/images/pizza.gif"), children: [
transformation: { new ImageRun({
width: 100, data: fs.readFileSync("./demo/images/pizza.gif"),
height: 100, transformation: {
}, width: 100,
height: 100,
},
}),
],
}), }),
], ],
}), }),
], },
}), footers: {
}, default: new Footer({
footers: {
default: new Footer({
children: [
new Paragraph({
children: [ children: [
new ImageRun({ new Paragraph({
data: fs.readFileSync("./demo/images/pizza.gif"), children: [
transformation: { new ImageRun({
width: 100, data: fs.readFileSync("./demo/images/pizza.gif"),
height: 100, transformation: {
}, width: 100,
height: 100,
},
}),
],
}), }),
], ],
}), }),
], },
}), children: [new Paragraph("Hello World")],
}, },
children: [new Paragraph("Hello World")], ],
}); });
Packer.toBuffer(doc).then((buffer) => { Packer.toBuffer(doc).then((buffer) => {

View File

@ -14,26 +14,28 @@
function generate() { function generate() {
const doc = new docx.Document(); const doc = new docx.Document();
doc.addSection({ const doc = new Document({
children: [ sections: [
new docx.Paragraph({ {
children: [ children: [
new docx.TextRun("Hello World"), new docx.Paragraph({
new docx.TextRun({ children: [
text: "Foo Bar", new docx.TextRun("Hello World"),
bold: true, new docx.TextRun({
}), text: "Foo Bar",
new docx.TextRun({ bold: true,
text: "\tGithub is the best", }),
bold: true, new docx.TextRun({
text: "\tGithub is the best",
bold: true,
}),
],
}), }),
], ],
}), },
], ],
}); });
docx.Packer.toBlob(doc).then((blob) => { docx.Packer.toBlob(doc).then((blob) => {
console.log(blob); console.log(blob);
saveAs(blob, "example.docx"); saveAs(blob, "example.docx");

View File

@ -24,28 +24,27 @@ import { ... } from "docx";
import * as fs from "fs"; import * as fs from "fs";
import { Document, Packer, Paragraph, TextRun } from "docx"; import { Document, Packer, Paragraph, TextRun } from "docx";
// Create document
const doc = new Document();
// Documents contain sections, you can have multiple sections per document, go here to learn more about sections // Documents contain sections, you can have multiple sections per document, go here to learn more about sections
// This simple example will only contain one section // This simple example will only contain one section
doc.addSection({ const doc = new Document({
properties: {}, sections: [{
children: [ properties: {},
new Paragraph({ children: [
children: [ new Paragraph({
new TextRun("Hello World"), children: [
new TextRun({ new TextRun("Hello World"),
text: "Foo Bar", new TextRun({
bold: true, text: "Foo Bar",
}), bold: true,
new TextRun({ }),
text: "\tGithub is the best", new TextRun({
bold: true, text: "\tGithub is the best",
}), bold: true,
], }),
}), ],
], }),
],
}];
}); });
// Used to export the file into a .docx file // Used to export the file into a .docx file

View File

@ -57,12 +57,14 @@ text.contents = "Hello World";
**Do** **Do**
```ts ```ts
doc.addSection({ const doc = new Document({
children: [ sections: [{
new Paragraph({ children: [
children: [new TextRun("Hello World")], new Paragraph({
}), children: [new TextRun("Hello World")],
], }),
],
}];
}); });
``` ```

View File

@ -6,21 +6,23 @@
To make a bullet point, simply make a paragraph into a bullet point: To make a bullet point, simply make a paragraph into a bullet point:
```ts ```ts
doc.addSection({ const doc = new Document({
children: [ sections: [{
new Paragraph({ children: [
text: "Bullet points", new Paragraph({
bullet: { text: "Bullet points",
level: 0 //How deep you want the bullet to be bullet: {
} level: 0 //How deep you want the bullet to be
}), }
new Paragraph({ }),
text: "Are awesome", new Paragraph({
bullet: { text: "Are awesome",
level: 0 bullet: {
} level: 0
}) }
], })
],
}];
}); });
``` ```

View File

@ -5,30 +5,32 @@
Every Section has a sections which you can define its Headers and Footers: Every Section has a sections which you can define its Headers and Footers:
```ts ```ts
doc.addSection({ const doc = new Document({
headers: { sections: [{
default: new Header({ // The standard default header headers: {
children: [], default: new Header({ // The standard default header
}), children: [],
first: new Header({ // The first header }),
children: [], first: new Header({ // The first header
}), children: [],
even: new Header({ // The header on every other page }),
children: [], even: new Header({ // The header on every other page
}), children: [],
}, }),
footers: { },
default: new Footer({ // The standard default footer footers: {
children: [], default: new Footer({ // The standard default footer
}), children: [],
first: new Footer({ // The first footer }),
children: [], first: new Footer({ // The first footer
}), children: [],
even: new Footer({ // The footer on every other page }),
children: [], even: new Footer({ // The footer on every other page
}), children: [],
}, }),
children: [], },
children: [],
}];
}); });
``` ```

View File

@ -37,20 +37,14 @@ const image = new ImageRun({
Add it into the document by adding the image into a paragraph: Add it into the document by adding the image into a paragraph:
```ts ```ts
doc.addSection({ const doc = new Document({
children: [new Paragraph(image)], sections: [{
}); children: [
``` new Paragraph({
children: [image],
Or: }),
],
```ts }];
doc.addSection({
children: [
new Paragraph({
children: [image],
}),
],
}); });
``` ```
@ -59,16 +53,22 @@ doc.addSection({
Adding images can be easily done by creating an instance of `ImageRun`. This can be added in a `Paragraph` or `Hyperlink`: Adding images can be easily done by creating an instance of `ImageRun`. This can be added in a `Paragraph` or `Hyperlink`:
```ts ```ts
const image = new ImageRun({ const doc = new Document({
data: [IMAGE_BUFFER], sections: [{
transformation: { children: [
width: [IMAGE_SIZE], new Paragraph({
height: [IMAGE_SIZE], children: [
}, new ImageRun({
}); data: [IMAGE_BUFFER],
transformation: {
doc.addSection({ width: [IMAGE_SIZE],
children: [new Paragraph(image)], height: [IMAGE_SIZE],
},
}),
],
}),
],
}];
}); });
``` ```

View File

@ -35,20 +35,24 @@ const paragraph = new Paragraph({
After you create the paragraph, you must add the paragraph into a `section`: After you create the paragraph, you must add the paragraph into a `section`:
```ts ```ts
doc.addSection({ const doc = new Document({
children: [paragraph], sections: [{
children: [paragraph],
}];
}); });
``` ```
Or the preferred convension, define the paragraph inside the section and remove the usage of variables: Or the preferred convension, define the paragraph inside the section and remove the usage of variables:
```ts ```ts
doc.addSection({ const doc = new Document({
children: [ sections: [{
new Paragraph({ children: [
children: [new TextRun("Lorem Ipsum Foo Bar"), new TextRun("Hello World")], new Paragraph({
}), children: [new TextRun("Lorem Ipsum Foo Bar"), new TextRun("Hello World")],
], }),
],
}];
}); });
``` ```

View File

@ -11,12 +11,14 @@ For example, you could have one section which is portrait with a header and foot
This creates a simple section in a document with one paragraph inside: This creates a simple section in a document with one paragraph inside:
```ts ```ts
doc.addSection({ const doc = new Document({
children: [ sections: [{
new Paragraph({ children: [
children: [new TextRun("Hello World")], new Paragraph({
}), children: [new TextRun("Hello World")],
], }),
],
}];
}); });
``` ```
@ -35,14 +37,16 @@ Setting the section type determines how the contents of the section will be plac
- `ODD_PAGE` - `ODD_PAGE`
```ts ```ts
doc.addSection({ const doc = new Document({
properties: { sections: [{
type: SectionType.CONTINUOUS, properties: {
} type: SectionType.CONTINUOUS,
children: [ }
new Paragraph({ children: [
children: [new TextRun("Hello World")], new Paragraph({
}), children: [new TextRun("Hello World")],
], }),
],
}];
}); });
``` ```

View File

@ -19,8 +19,10 @@ const table = new Table({
Then add the table in the `section` Then add the table in the `section`
```ts ```ts
doc.addSection({ const doc = new Document({
children: [table], sections: [{
children: [table],
}];
}); });
``` ```

View File

@ -1,38 +1,10 @@
import { expect } from "chai"; import { expect } from "chai";
import { File, HeadingLevel, Media, Paragraph } from "file"; import { Media } from "file";
import { ImageReplacer } from "./image-replacer"; import { ImageReplacer } from "./image-replacer";
describe("ImageReplacer", () => { describe("ImageReplacer", () => {
let file: File;
beforeEach(() => {
file = new File({
creator: "Dolan Miu",
revision: "1",
lastModifiedBy: "Dolan Miu",
});
file.addSection({
children: [
new Paragraph({
text: "title",
heading: HeadingLevel.TITLE,
}),
new Paragraph({
text: "Hello world",
heading: HeadingLevel.HEADING_1,
}),
new Paragraph({
text: "heading 2",
heading: HeadingLevel.HEADING_2,
}),
new Paragraph("test text"),
],
});
});
describe("#replace()", () => { describe("#replace()", () => {
it("should replace properly", () => { it("should replace properly", () => {
const imageReplacer = new ImageReplacer(); const imageReplacer = new ImageReplacer();

View File

@ -8,16 +8,17 @@ import { Compiler } from "./next-compiler";
describe("Compiler", () => { describe("Compiler", () => {
let compiler: Compiler; let compiler: Compiler;
let file: File;
beforeEach(() => { beforeEach(() => {
file = new File();
compiler = new Compiler(); compiler = new Compiler();
}); });
describe("#compile()", () => { describe("#compile()", () => {
it("should pack all the content", async function () { it("should pack all the content", async function () {
this.timeout(99999999); this.timeout(99999999);
const file = new File({
sections: [],
});
const zipFile = compiler.compile(file); const zipFile = compiler.compile(file);
const fileNames = Object.keys(zipFile.files).map((f) => zipFile.files[f].name); const fileNames = Object.keys(zipFile.files).map((f) => zipFile.files[f].name);
@ -38,24 +39,27 @@ describe("Compiler", () => {
}); });
it("should pack all additional headers and footers", async function () { it("should pack all additional headers and footers", async function () {
file.addSection({ const file = new File({
headers: { sections: [
default: new Header(), {
}, headers: {
footers: { default: new Header(),
default: new Footer(), },
}, footers: {
children: [], default: new Footer(),
}); },
children: [],
file.addSection({ },
headers: { {
default: new Header(), headers: {
}, default: new Header(),
footers: { },
default: new Footer(), footers: {
}, default: new Footer(),
children: [], },
children: [],
},
],
}); });
this.timeout(99999999); this.timeout(99999999);
@ -80,12 +84,15 @@ describe("Compiler", () => {
// This test is required because before, there was a case where Document was formatted twice, which was inefficient // This test is required because before, there was a case where Document was formatted twice, which was inefficient
// This also caused issues such as running prepForXml multiple times as format() was ran multiple times. // This also caused issues such as running prepForXml multiple times as format() was ran multiple times.
const paragraph = new Paragraph(""); const paragraph = new Paragraph("");
const doc = new File(); const file = new File({
sections: [
doc.addSection({ {
properties: {}, properties: {},
children: [paragraph], children: [paragraph],
},
],
}); });
// tslint:disable-next-line: no-string-literal // tslint:disable-next-line: no-string-literal
const spy = sinon.spy(compiler["formatter"], "format"); const spy = sinon.spy(compiler["formatter"], "format");

View File

@ -14,23 +14,24 @@ describe("Packer", () => {
creator: "Dolan Miu", creator: "Dolan Miu",
revision: "1", revision: "1",
lastModifiedBy: "Dolan Miu", lastModifiedBy: "Dolan Miu",
}); sections: [
{
file.addSection({ children: [
children: [ new Paragraph({
new Paragraph({ text: "title",
text: "title", heading: HeadingLevel.TITLE,
heading: HeadingLevel.TITLE, }),
}), new Paragraph({
new Paragraph({ text: "Hello world",
text: "Hello world", heading: HeadingLevel.HEADING_1,
heading: HeadingLevel.HEADING_1, }),
}), new Paragraph({
new Paragraph({ text: "heading 2",
text: "heading 2", heading: HeadingLevel.HEADING_2,
heading: HeadingLevel.HEADING_2, }),
}), new Paragraph("test text"),
new Paragraph("test text"), ],
},
], ],
}); });
}); });

View File

@ -3,12 +3,14 @@ import { ICustomPropertyOptions } from "../custom-properties";
import { IDocumentBackgroundOptions } from "../document"; import { IDocumentBackgroundOptions } from "../document";
import { DocumentAttributes } from "../document/document-attributes"; import { DocumentAttributes } from "../document/document-attributes";
import { ISectionOptions } from "../file";
import { INumberingOptions } from "../numbering"; import { INumberingOptions } from "../numbering";
import { Paragraph } from "../paragraph"; import { Paragraph } from "../paragraph";
import { IStylesOptions } from "../styles"; import { IStylesOptions } from "../styles";
import { Created, Creator, Description, Keywords, LastModifiedBy, Modified, Revision, Subject, Title } from "./components"; import { Created, Creator, Description, Keywords, LastModifiedBy, Modified, Revision, Subject, Title } from "./components";
export interface IPropertiesOptions { export interface IPropertiesOptions {
readonly sections: ISectionOptions[];
readonly title?: string; readonly title?: string;
readonly subject?: string; readonly subject?: string;
readonly creator?: string; readonly creator?: string;
@ -34,7 +36,7 @@ export interface IPropertiesOptions {
} }
export class CoreProperties extends XmlComponent { export class CoreProperties extends XmlComponent {
constructor(options: IPropertiesOptions) { constructor(options: Omit<IPropertiesOptions, "sections">) {
super("cp:coreProperties"); super("cp:coreProperties");
this.root.push( this.root.push(
new DocumentAttributes({ new DocumentAttributes({

View File

@ -14,8 +14,12 @@ describe("Body", () => {
describe("#addSection", () => { describe("#addSection", () => {
it("should add section with default parameters", () => { it("should add section with default parameters", () => {
body.addSection({ body.addSection({
width: 10000, page: {
height: 10000, size: {
width: 10000,
height: 10000,
},
},
}); });
const tree = new Formatter().format(body); const tree = new Formatter().format(body);

View File

@ -1,7 +1,7 @@
import { IContext, IXmlableObject, XmlComponent } from "file/xml-components"; import { IContext, IXmlableObject, XmlComponent } from "file/xml-components";
import { Paragraph, ParagraphProperties, TableOfContents } from "../.."; import { Paragraph, ParagraphProperties, TableOfContents } from "../..";
import { SectionProperties, SectionPropertiesOptions } from "./section-properties/section-properties"; import { ISectionPropertiesOptions, SectionProperties } from "./section-properties/section-properties";
export class Body extends XmlComponent { export class Body extends XmlComponent {
private readonly sections: SectionProperties[] = []; private readonly sections: SectionProperties[] = [];
@ -18,7 +18,7 @@ export class Body extends XmlComponent {
* - last section should be direct child of body * - last section should be direct child of body
* @param options new section options * @param options new section options
*/ */
public addSection(options: SectionPropertiesOptions): void { public addSection(options: ISectionPropertiesOptions): void {
const currentSection = this.sections.pop() as SectionProperties; const currentSection = this.sections.pop() as SectionProperties;
this.root.push(this.createSectionParagraph(currentSection)); this.root.push(this.createSectionParagraph(currentSection));

View File

@ -8,18 +8,18 @@ export enum LineNumberRestartFormat {
} }
export interface ILineNumberAttributes { export interface ILineNumberAttributes {
readonly lineNumberCountBy?: number; readonly countBy?: number;
readonly lineNumberStart?: number; readonly start?: number;
readonly lineNumberRestart?: LineNumberRestartFormat; readonly restart?: LineNumberRestartFormat;
readonly lineNumberDistance?: number; readonly distance?: number;
} }
export class LineNumberAttributes extends XmlAttributeComponent<ILineNumberAttributes> { export class LineNumberAttributes extends XmlAttributeComponent<ILineNumberAttributes> {
protected readonly xmlKeys = { protected readonly xmlKeys = {
lineNumberCountBy: "w:countBy", countBy: "w:countBy",
lineNumberStart: "w:start", start: "w:start",
lineNumberRestart: "w:restart", restart: "w:restart",
lineNumberDistance: "w:distance", distance: "w:distance",
}; };
} }
@ -28,10 +28,10 @@ export class LineNumberType extends XmlComponent {
super("w:lnNumType"); super("w:lnNumType");
this.root.push( this.root.push(
new LineNumberAttributes({ new LineNumberAttributes({
lineNumberCountBy: countBy, countBy: countBy,
lineNumberStart: start, start: start,
lineNumberRestart: restart, restart: restart,
lineNumberDistance: dist, distance: dist,
}), }),
); );
} }

View File

@ -26,16 +26,16 @@ export enum PageNumberSeparator {
} }
export interface IPageNumberTypeAttributes { export interface IPageNumberTypeAttributes {
readonly pageNumberStart?: number; readonly start?: number;
readonly pageNumberFormatType?: PageNumberFormat; readonly formatType?: PageNumberFormat;
readonly pageNumberSeparator?: PageNumberSeparator; readonly separator?: PageNumberSeparator;
} }
export class PageNumberTypeAttributes extends XmlAttributeComponent<IPageNumberTypeAttributes> { export class PageNumberTypeAttributes extends XmlAttributeComponent<IPageNumberTypeAttributes> {
protected readonly xmlKeys = { protected readonly xmlKeys = {
pageNumberStart: "w:start", start: "w:start",
pageNumberFormatType: "w:fmt", formatType: "w:fmt",
pageNumberSeparator: "w:chapSep", separator: "w:chapSep",
}; };
} }
@ -44,9 +44,9 @@ export class PageNumberType extends XmlComponent {
super("w:pgNumType"); super("w:pgNumType");
this.root.push( this.root.push(
new PageNumberTypeAttributes({ new PageNumberTypeAttributes({
pageNumberStart: start, start: start,
pageNumberFormatType: numberFormat, formatType: numberFormat,
pageNumberSeparator: separator, separator: separator,
}), }),
); );
} }

View File

@ -19,34 +19,46 @@ describe("SectionProperties", () => {
const media = new Media(); const media = new Media();
const properties = new SectionProperties({ const properties = new SectionProperties({
width: 11906, page: {
height: 16838, size: {
top: convertInchesToTwip(1), width: 11906,
right: convertInchesToTwip(1), height: 16838,
bottom: convertInchesToTwip(1), },
left: convertInchesToTwip(1), margin: {
header: 708, top: convertInchesToTwip(1),
footer: 708, right: convertInchesToTwip(1),
gutter: 0, bottom: convertInchesToTwip(1),
mirror: false, left: convertInchesToTwip(1),
header: 708,
footer: 708,
gutter: 0,
mirror: false,
},
pageNumbers: {
start: 10,
formatType: PageNumberFormat.CARDINAL_TEXT,
},
},
column: { column: {
space: 708, space: 708,
count: 1, count: 1,
separate: true, separate: true,
}, },
linePitch: convertInchesToTwip(0.25), grid: {
headers: { linePitch: convertInchesToTwip(0.25),
},
headerWrapperGroup: {
default: new HeaderWrapper(media, 100), default: new HeaderWrapper(media, 100),
}, },
footers: { footerWrapperGroup: {
even: new FooterWrapper(media, 200), even: new FooterWrapper(media, 200),
}, },
pageNumberStart: 10,
pageNumberFormatType: PageNumberFormat.CARDINAL_TEXT,
titlePage: true, titlePage: true,
verticalAlign: SectionVerticalAlignValue.TOP, verticalAlign: SectionVerticalAlignValue.TOP,
}); });
const tree = new Formatter().format(properties); const tree = new Formatter().format(properties);
expect(Object.keys(tree)).to.deep.equal(["w:sectPr"]); expect(Object.keys(tree)).to.deep.equal(["w:sectPr"]);
expect(tree["w:sectPr"]).to.be.an.instanceof(Array); expect(tree["w:sectPr"]).to.be.an.instanceof(Array);
expect(tree["w:sectPr"][0]).to.deep.equal({ "w:pgSz": { _attr: { "w:h": 16838, "w:w": 11906, "w:orient": "portrait" } } }); expect(tree["w:sectPr"][0]).to.deep.equal({ "w:pgSz": { _attr: { "w:h": 16838, "w:w": 11906, "w:orient": "portrait" } } });
@ -98,7 +110,11 @@ describe("SectionProperties", () => {
it("should create section properties with changed options", () => { it("should create section properties with changed options", () => {
const properties = new SectionProperties({ const properties = new SectionProperties({
top: 0, page: {
margin: {
top: 0,
},
},
}); });
const tree = new Formatter().format(properties); const tree = new Formatter().format(properties);
expect(Object.keys(tree)).to.deep.equal(["w:sectPr"]); expect(Object.keys(tree)).to.deep.equal(["w:sectPr"]);
@ -122,7 +138,11 @@ describe("SectionProperties", () => {
it("should create section properties with changed options", () => { it("should create section properties with changed options", () => {
const properties = new SectionProperties({ const properties = new SectionProperties({
bottom: 0, page: {
margin: {
bottom: 0,
},
},
}); });
const tree = new Formatter().format(properties); const tree = new Formatter().format(properties);
expect(Object.keys(tree)).to.deep.equal(["w:sectPr"]); expect(Object.keys(tree)).to.deep.equal(["w:sectPr"]);
@ -146,8 +166,12 @@ describe("SectionProperties", () => {
it("should create section properties with changed options", () => { it("should create section properties with changed options", () => {
const properties = new SectionProperties({ const properties = new SectionProperties({
width: 0, page: {
height: 0, size: {
width: 0,
height: 0,
},
},
}); });
const tree = new Formatter().format(properties); const tree = new Formatter().format(properties);
expect(Object.keys(tree)).to.deep.equal(["w:sectPr"]); expect(Object.keys(tree)).to.deep.equal(["w:sectPr"]);
@ -171,8 +195,12 @@ describe("SectionProperties", () => {
it("should create section properties with page borders", () => { it("should create section properties with page borders", () => {
const properties = new SectionProperties({ const properties = new SectionProperties({
pageBorders: { page: {
offsetFrom: PageBorderOffsetFrom.PAGE, borders: {
pageBorders: {
offsetFrom: PageBorderOffsetFrom.PAGE,
},
},
}, },
}); });
const tree = new Formatter().format(properties); const tree = new Formatter().format(properties);
@ -185,7 +213,11 @@ describe("SectionProperties", () => {
it("should create section properties with page number type, but without start attribute", () => { it("should create section properties with page number type, but without start attribute", () => {
const properties = new SectionProperties({ const properties = new SectionProperties({
pageNumberFormatType: PageNumberFormat.UPPER_ROMAN, page: {
pageNumbers: {
formatType: PageNumberFormat.UPPER_ROMAN,
},
},
}); });
const tree = new Formatter().format(properties); const tree = new Formatter().format(properties);
expect(Object.keys(tree)).to.deep.equal(["w:sectPr"]); expect(Object.keys(tree)).to.deep.equal(["w:sectPr"]);
@ -217,10 +249,12 @@ describe("SectionProperties", () => {
it("should create section properties line number type", () => { it("should create section properties line number type", () => {
const properties = new SectionProperties({ const properties = new SectionProperties({
lineNumberCountBy: 2, lineNumbers: {
lineNumberStart: 2, countBy: 2,
lineNumberRestart: LineNumberRestartFormat.CONTINUOUS, start: 2,
lineNumberDistance: 4, restart: LineNumberRestartFormat.CONTINUOUS,
distance: 4,
},
}); });
const tree = new Formatter().format(properties); const tree = new Formatter().format(properties);
expect(Object.keys(tree)).to.deep.equal(["w:sectPr"]); expect(Object.keys(tree)).to.deep.equal(["w:sectPr"]);

View File

@ -1,4 +1,6 @@
// http://officeopenxml.com/WPsection.php // http://officeopenxml.com/WPsection.php
// tslint:disable: no-unnecessary-initializer
import { convertInchesToTwip } from "convenience-functions"; import { convertInchesToTwip } from "convenience-functions";
import { FooterWrapper } from "file/footer-wrapper"; import { FooterWrapper } from "file/footer-wrapper";
import { HeaderWrapper } from "file/header-wrapper"; import { HeaderWrapper } from "file/header-wrapper";
@ -21,7 +23,7 @@ import { IPageSizeAttributes, PageOrientation } from "./page-size/page-size-attr
import { TitlePage } from "./title-page/title-page"; import { TitlePage } from "./title-page/title-page";
import { Type } from "./type/section-type"; import { Type } from "./type/section-type";
import { SectionType } from "./type/section-type-attributes"; import { SectionType } from "./type/section-type-attributes";
import { ISectionVerticalAlignAttributes, SectionVerticalAlign } from "./vertical-align"; import { SectionVerticalAlign, SectionVerticalAlignValue } from "./vertical-align";
export interface IHeaderFooterGroup<T> { export interface IHeaderFooterGroup<T> {
readonly default?: T; readonly default?: T;
@ -29,89 +31,71 @@ export interface IHeaderFooterGroup<T> {
readonly even?: T; readonly even?: T;
} }
interface IHeadersOptions { export interface ISectionPropertiesOptions {
readonly headers?: IHeaderFooterGroup<HeaderWrapper>; readonly page?: {
} readonly size?: IPageSizeAttributes;
readonly margin?: IPageMarginAttributes;
interface IFootersOptions { readonly pageNumbers?: IPageNumberTypeAttributes;
readonly footers?: IHeaderFooterGroup<FooterWrapper>; readonly borders?: IPageBordersOptions;
}
interface ITitlePageOptions {
readonly titlePage?: boolean;
}
export type SectionPropertiesOptions = IPageSizeAttributes &
IPageMarginAttributes &
IDocGridAttributesProperties &
IHeadersOptions &
IFootersOptions &
IPageNumberTypeAttributes &
ILineNumberAttributes &
IPageBordersOptions &
ITitlePageOptions &
ISectionVerticalAlignAttributes & {
readonly column?: {
readonly space?: number;
readonly count?: number;
readonly separate?: boolean;
};
readonly type?: SectionType;
}; };
// Need to decouple this from the attributes readonly grid?: IDocGridAttributesProperties;
readonly headerWrapperGroup?: IHeaderFooterGroup<HeaderWrapper>;
readonly footerWrapperGroup?: IHeaderFooterGroup<FooterWrapper>;
readonly lineNumbers?: ILineNumberAttributes;
readonly titlePage?: boolean;
readonly verticalAlign?: SectionVerticalAlignValue;
readonly column?: {
readonly space?: number;
readonly count?: number;
readonly separate?: boolean;
};
readonly type?: SectionType;
}
export class SectionProperties extends XmlComponent { export class SectionProperties extends XmlComponent {
public readonly width: number; constructor({
public readonly rightMargin: number; page: {
public readonly leftMargin: number; size: { width = 11906, height = 16838, orientation = PageOrientation.PORTRAIT } = {},
margin: {
constructor( top = convertInchesToTwip(1),
{ right = convertInchesToTwip(1),
width = 11906, bottom = convertInchesToTwip(1),
height = 16838, left = convertInchesToTwip(1),
top = convertInchesToTwip(1), header = 708,
right = convertInchesToTwip(1), footer = 708,
bottom = convertInchesToTwip(1), gutter = 0,
left = convertInchesToTwip(1), mirror = false,
header = 708, } = {},
footer = 708, pageNumbers: {
gutter = 0, start: pageNumberStart = undefined,
mirror = false, formatType: pageNumberFormatType = undefined,
column = {}, separator: pageNumberSeparator = undefined,
linePitch = 360, } = {},
orientation = PageOrientation.PORTRAIT, borders: {
headers, pageBorders = undefined,
footers, pageBorderTop = undefined,
pageNumberFormatType, pageBorderRight = undefined,
pageNumberStart, pageBorderBottom = undefined,
pageNumberSeparator, pageBorderLeft = undefined,
lineNumberCountBy, } = {},
lineNumberStart, } = {},
lineNumberRestart, grid: { linePitch = 360 } = {},
lineNumberDistance, headerWrapperGroup = {},
pageBorders, footerWrapperGroup = {},
pageBorderTop, lineNumbers: { countBy: lineNumberCountBy, start: lineNumberStart, restart: lineNumberRestart, distance: lineNumberDistance } = {},
pageBorderRight, titlePage = false,
pageBorderBottom, verticalAlign,
pageBorderLeft, column: { space = 708, count = 1, separate = false } = {},
titlePage = false, type,
verticalAlign, }: ISectionPropertiesOptions = {}) {
type,
}: SectionPropertiesOptions = { column: {} },
) {
super("w:sectPr"); super("w:sectPr");
this.leftMargin = left;
this.rightMargin = right;
this.width = width;
this.root.push(new PageSize(width, height, orientation)); this.root.push(new PageSize(width, height, orientation));
this.root.push(new PageMargin(top, right, bottom, left, header, footer, gutter, mirror)); this.root.push(new PageMargin(top, right, bottom, left, header, footer, gutter, mirror));
this.root.push(new Columns(column.space ? column.space : 708, column.count ? column.count : 1, column.separate ?? false)); this.root.push(new Columns(space, count, separate));
this.root.push(new DocumentGrid(linePitch)); this.root.push(new DocumentGrid(linePitch));
this.addHeaders(headers); this.addHeaders(headerWrapperGroup);
this.addFooters(footers); this.addFooters(footerWrapperGroup);
this.root.push(new PageNumberType(pageNumberStart, pageNumberFormatType, pageNumberSeparator)); this.root.push(new PageNumberType(pageNumberStart, pageNumberFormatType, pageNumberSeparator));
@ -144,65 +128,61 @@ export class SectionProperties extends XmlComponent {
} }
} }
private addHeaders(headers?: IHeaderFooterGroup<HeaderWrapper>): void { private addHeaders(headers: IHeaderFooterGroup<HeaderWrapper>): void {
if (headers) { if (headers.default) {
if (headers.default) { this.root.push(
this.root.push( new HeaderReference({
new HeaderReference({ headerType: HeaderReferenceType.DEFAULT,
headerType: HeaderReferenceType.DEFAULT, headerId: headers.default.View.ReferenceId,
headerId: headers.default.View.ReferenceId, }),
}), );
); }
}
if (headers.first) { if (headers.first) {
this.root.push( this.root.push(
new HeaderReference({ new HeaderReference({
headerType: HeaderReferenceType.FIRST, headerType: HeaderReferenceType.FIRST,
headerId: headers.first.View.ReferenceId, headerId: headers.first.View.ReferenceId,
}), }),
); );
} }
if (headers.even) { if (headers.even) {
this.root.push( this.root.push(
new HeaderReference({ new HeaderReference({
headerType: HeaderReferenceType.EVEN, headerType: HeaderReferenceType.EVEN,
headerId: headers.even.View.ReferenceId, headerId: headers.even.View.ReferenceId,
}), }),
); );
}
} }
} }
private addFooters(footers?: IHeaderFooterGroup<FooterWrapper>): void { private addFooters(footers: IHeaderFooterGroup<FooterWrapper>): void {
if (footers) { if (footers.default) {
if (footers.default) { this.root.push(
this.root.push( new FooterReference({
new FooterReference({ footerType: FooterReferenceType.DEFAULT,
footerType: FooterReferenceType.DEFAULT, footerId: footers.default.View.ReferenceId,
footerId: footers.default.View.ReferenceId, }),
}), );
); }
}
if (footers.first) { if (footers.first) {
this.root.push( this.root.push(
new FooterReference({ new FooterReference({
footerType: FooterReferenceType.FIRST, footerType: FooterReferenceType.FIRST,
footerId: footers.first.View.ReferenceId, footerId: footers.first.View.ReferenceId,
}), }),
); );
} }
if (footers.even) { if (footers.even) {
this.root.push( this.root.push(
new FooterReference({ new FooterReference({
footerType: FooterReferenceType.EVEN, footerType: FooterReferenceType.EVEN,
footerId: footers.even.View.ReferenceId, footerId: footers.even.View.ReferenceId,
}), }),
); );
}
} }
} }
} }

View File

@ -1,11 +1,9 @@
import { XmlAttributeComponent } from "file/xml-components"; import { XmlAttributeComponent } from "file/xml-components";
import { SectionVerticalAlignValue } from "./vertical-align"; import { SectionVerticalAlignValue } from "./vertical-align";
export interface ISectionVerticalAlignAttributes { export class SectionVerticalAlignAttributes extends XmlAttributeComponent<{
readonly verticalAlign?: SectionVerticalAlignValue; readonly verticalAlign?: SectionVerticalAlignValue;
} }> {
export class SectionVerticalAlignAttributes extends XmlAttributeComponent<ISectionVerticalAlignAttributes> {
protected readonly xmlKeys = { protected readonly xmlKeys = {
verticalAlign: "w:val", verticalAlign: "w:val",
}; };

View File

@ -1,40 +1,26 @@
import { expect } from "chai"; import { expect } from "chai";
import * as sinon from "sinon";
import { Formatter } from "export/formatter"; import { Formatter } from "export/formatter";
import { File } from "./file"; import { File } from "./file";
import { Footer, Header } from "./header"; import { Footer, Header } from "./header";
import { Paragraph } from "./paragraph"; import { Paragraph } from "./paragraph";
import { Table, TableCell, TableRow } from "./table";
import { TableOfContents } from "./table-of-contents";
describe("File", () => { describe("File", () => {
describe("#constructor", () => { describe("#constructor", () => {
it("should create with correct headers and footers by default", () => {
const doc = new File();
doc.addSection({
children: [],
});
const tree = new Formatter().format(doc.Document.View.Body);
expect(tree["w:body"][0]["w:sectPr"][4]["w:headerReference"]._attr["w:type"]).to.equal("default");
expect(tree["w:body"][0]["w:sectPr"][5]["w:footerReference"]._attr["w:type"]).to.equal("default");
});
it("should create with correct headers and footers", () => { it("should create with correct headers and footers", () => {
const doc = new File(); const doc = new File({
sections: [
doc.addSection({ {
headers: { headers: {
default: new Header(), default: new Header(),
}, },
footers: { footers: {
default: new Footer(), default: new Footer(),
}, },
children: [], children: [],
},
],
}); });
const tree = new Formatter().format(doc.Document.View.Body); const tree = new Formatter().format(doc.Document.View.Body);
@ -44,16 +30,18 @@ describe("File", () => {
}); });
it("should create with first headers and footers", () => { it("should create with first headers and footers", () => {
const doc = new File(); const doc = new File({
sections: [
doc.addSection({ {
headers: { headers: {
first: new Header(), first: new Header(),
}, },
footers: { footers: {
first: new Footer(), first: new Footer(),
}, },
children: [], children: [],
},
],
}); });
const tree = new Formatter().format(doc.Document.View.Body); const tree = new Formatter().format(doc.Document.View.Body);
@ -62,20 +50,22 @@ describe("File", () => {
}); });
it("should create with correct headers", () => { it("should create with correct headers", () => {
const doc = new File(); const doc = new File({
sections: [
doc.addSection({ {
headers: { headers: {
default: new Header(), default: new Header(),
first: new Header(), first: new Header(),
even: new Header(), even: new Header(),
}, },
footers: { footers: {
default: new Footer(), default: new Footer(),
first: new Footer(), first: new Footer(),
even: new Footer(), even: new Footer(),
}, },
children: [], children: [],
},
],
}); });
const tree = new Formatter().format(doc.Document.View.Body); const tree = new Formatter().format(doc.Document.View.Body);
@ -90,11 +80,13 @@ describe("File", () => {
}); });
it("should add child", () => { it("should add child", () => {
const doc = new File(undefined, undefined, [ const doc = new File({
{ sections: [
children: [new Paragraph("test")], {
}, children: [new Paragraph("test")],
]); },
],
});
const tree = new Formatter().format(doc.Document.View.Body); const tree = new Formatter().format(doc.Document.View.Body);
@ -171,69 +163,13 @@ describe("File", () => {
}); });
}); });
describe("#addSection", () => {
it("should call the underlying document's add a Paragraph", () => {
const file = new File();
const spy = sinon.spy(file.Document.View, "add");
file.addSection({
children: [new Paragraph({})],
});
expect(spy.called).to.equal(true);
});
it("should call the underlying document's add when adding a Table", () => {
const file = new File();
const spy = sinon.spy(file.Document.View, "add");
file.addSection({
children: [
new Table({
rows: [
new TableRow({
children: [
new TableCell({
children: [new Paragraph("hello")],
}),
],
}),
],
}),
],
});
expect(spy.called).to.equal(true);
});
it("should call the underlying document's add when adding an Image (paragraph)", () => {
const file = new File();
const spy = sinon.spy(file.Document.View, "add");
// tslint:disable-next-line:no-any
file.addSection({
children: [new Paragraph("")],
});
expect(spy.called).to.equal(true);
});
});
describe("#addSection", () => {
it("should call the underlying document's add", () => {
const file = new File();
const spy = sinon.spy(file.Document.View, "add");
file.addSection({
children: [new TableOfContents()],
});
expect(spy.called).to.equal(true);
});
});
describe("#addTrackRevisionsFeature", () => { describe("#addTrackRevisionsFeature", () => {
it("should call the underlying document's add", () => { it("should call the underlying document's add", () => {
const file = new File({ const file = new File({
features: { features: {
trackRevisions: true, trackRevisions: true,
}, },
sections: [],
}); });
// tslint:disable-next-line: no-unused-expression no-string-literal // tslint:disable-next-line: no-unused-expression no-string-literal
@ -249,6 +185,7 @@ describe("File", () => {
children: [new Paragraph("hello")], children: [new Paragraph("hello")],
}, },
}, },
sections: [],
}); });
const tree = new Formatter().format(wrapper.FootNotes.View); const tree = new Formatter().format(wrapper.FootNotes.View);
@ -435,6 +372,7 @@ describe("File", () => {
styles: { styles: {
default: {}, default: {},
}, },
sections: [],
}); });
const tree = new Formatter().format(doc.Styles); const tree = new Formatter().format(doc.Styles);
@ -454,6 +392,7 @@ describe("File", () => {
it("should create with even and odd headers and footers", () => { it("should create with even and odd headers and footers", () => {
const doc = new File({ const doc = new File({
evenAndOddHeaderAndFooters: true, evenAndOddHeaderAndFooters: true,
sections: [],
}); });
const tree = new Formatter().format(doc.Settings); const tree = new Formatter().format(doc.Settings);

View File

@ -3,13 +3,7 @@ import { ContentTypes } from "./content-types/content-types";
import { CoreProperties, IPropertiesOptions } from "./core-properties"; import { CoreProperties, IPropertiesOptions } from "./core-properties";
import { CustomProperties } from "./custom-properties"; import { CustomProperties } from "./custom-properties";
import { DocumentWrapper } from "./document-wrapper"; import { DocumentWrapper } from "./document-wrapper";
import { import { FooterReferenceType, HeaderReferenceType, ISectionPropertiesOptions } from "./document/body/section-properties";
FooterReferenceType,
HeaderReferenceType,
IPageSizeAttributes,
SectionPropertiesOptions,
} from "./document/body/section-properties";
import { IPageMarginAttributes } from "./document/body/section-properties/page-margin/page-margin-attributes";
import { IFileProperties } from "./file-properties"; import { IFileProperties } from "./file-properties";
import { FooterWrapper, IDocumentFooter } from "./footer-wrapper"; import { FooterWrapper, IDocumentFooter } from "./footer-wrapper";
import { FootnotesWrapper } from "./footnotes-wrapper"; import { FootnotesWrapper } from "./footnotes-wrapper";
@ -37,9 +31,7 @@ export interface ISectionOptions {
readonly first?: Footer; readonly first?: Footer;
readonly even?: Footer; readonly even?: Footer;
}; };
readonly size?: IPageSizeAttributes; readonly properties?: ISectionPropertiesOptions;
readonly margins?: IPageMarginAttributes;
readonly properties?: SectionPropertiesOptions;
readonly children: (Paragraph | Table | TableOfContents)[]; readonly children: (Paragraph | Table | TableOfContents)[];
} }
@ -61,16 +53,14 @@ export class File {
private readonly appProperties: AppProperties; private readonly appProperties: AppProperties;
private readonly styles: Styles; private readonly styles: Styles;
constructor( constructor(options: IPropertiesOptions, fileProperties: IFileProperties = {}) {
options: IPropertiesOptions = { this.coreProperties = new CoreProperties({
creator: "Un-named", ...options,
revision: "1", creator: options.creator ?? "Un-named",
lastModifiedBy: "Un-named", revision: options.revision ?? "1",
}, lastModifiedBy: options.lastModifiedBy ?? "Un-named",
fileProperties: IFileProperties = {}, });
sections: ISectionOptions[] = [],
) {
this.coreProperties = new CoreProperties(options);
this.numbering = new Numbering( this.numbering = new Numbering(
options.numbering options.numbering
? options.numbering ? options.numbering
@ -78,6 +68,7 @@ export class File {
config: [], config: [],
}, },
); );
this.fileRelationships = new Relationships(); this.fileRelationships = new Relationships();
this.customProperties = new CustomProperties(options.customProperties ?? []); this.customProperties = new CustomProperties(options.customProperties ?? []);
this.appProperties = new AppProperties(); this.appProperties = new AppProperties();
@ -131,12 +122,8 @@ export class File {
} }
} }
for (const section of sections) { for (const section of options.sections) {
this.documentWrapper.View.Body.addSection(section.properties ? section.properties : {}); this.addSection(section);
for (const child of section.children) {
this.documentWrapper.View.add(child);
}
} }
if (options.footnotes) { if (options.footnotes) {
@ -153,28 +140,25 @@ export class File {
} }
} }
public addSection({ public verifyUpdateFields(): void {
headers = { default: new Header() }, if (this.documentWrapper.View.getTablesOfContents().length) {
footers = { default: new Header() }, this.settings.addUpdateFields();
margins = {}, }
size = {}, }
properties,
children, private addSection({ headers = {}, footers = {}, children, properties }: ISectionOptions): void {
}: ISectionOptions): void {
this.documentWrapper.View.Body.addSection({ this.documentWrapper.View.Body.addSection({
...properties, ...properties,
headers: { headerWrapperGroup: {
default: headers.default ? this.createHeader(headers.default) : undefined, default: headers.default ? this.createHeader(headers.default) : undefined,
first: headers.first ? this.createHeader(headers.first) : undefined, first: headers.first ? this.createHeader(headers.first) : undefined,
even: headers.even ? this.createHeader(headers.even) : undefined, even: headers.even ? this.createHeader(headers.even) : undefined,
}, },
footers: { footerWrapperGroup: {
default: footers.default ? this.createFooter(footers.default) : undefined, default: footers.default ? this.createFooter(footers.default) : undefined,
first: footers.first ? this.createFooter(footers.first) : undefined, first: footers.first ? this.createFooter(footers.first) : undefined,
even: footers.even ? this.createFooter(footers.even) : undefined, even: footers.even ? this.createFooter(footers.even) : undefined,
}, },
...margins,
...size,
}); });
for (const child of children) { for (const child of children) {
@ -182,12 +166,6 @@ export class File {
} }
} }
public verifyUpdateFields(): void {
if (this.documentWrapper.View.getTablesOfContents().length) {
this.settings.addUpdateFields();
}
}
private createHeader(header: Header): HeaderWrapper { private createHeader(header: Header): HeaderWrapper {
const wrapper = new HeaderWrapper(this.media, this.currentRelationshipId++); const wrapper = new HeaderWrapper(this.media, this.currentRelationshipId++);

View File

@ -6,7 +6,11 @@ describe("Index", () => {
describe("Document", () => { describe("Document", () => {
it("should instantiate the Document", () => { it("should instantiate the Document", () => {
// tslint:disable-next-line: no-unused-expression // tslint:disable-next-line: no-unused-expression
expect(new Document()).to.be.ok; expect(
new Document({
sections: [],
}),
).to.be.ok;
}); });
}); });
}); });