Mandatory Sections

This commit is contained in:
Dolan Miu
2019-07-31 08:48:02 +01:00
parent bf80311ef7
commit ac5b15d0e3
63 changed files with 1194 additions and 1588 deletions

View File

@ -1,39 +1,45 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head>
<script src="../build/index.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.js"></script>
</head>
<head> <body>
<script src="../build/index.js"></script> <h1>DOCX browser Word document generation</h1>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.js"></script>
</head>
<body> <button type="button" onclick="generate()">Click to generate document</button>
<h1>DOCX browser Word document generation</h1> <script>
function generate() {
const doc = new Document();
<button type="button" onclick="generate()">Click to generate document</button> doc.addSection({
children: [
new Paragraph({
children: [
new TextRun("Hello World"),
new TextRun({
text: "Foo Bar",
bold: true,
}),
new TextRun({
text: "Github is the best",
bold: true,
}).tab(),
],
}),
],
});
<script> const packer = new Packer();
function generate() {
const doc = new Document();
const paragraph = new Paragraph("Hello World");
const institutionText = new TextRun("Foo Bar").bold();
const dateText = new TextRun("Github is the best").tab().bold();
paragraph.addRun(institutionText);
paragraph.addRun(dateText);
doc.add(paragraph);
const packer = new Packer();
packer.toBlob(doc).then(blob => {
console.log(blob);
saveAs(blob, "example.docx");
console.log("Document created successfully");
});
}
</script>
</body>
packer.toBlob(doc).then((blob) => {
console.log(blob);
saveAs(blob, "example.docx");
console.log("Document created successfully");
});
}
</script>
</body>
</html> </html>

View File

@ -5,19 +5,24 @@ import { Document, Packer, Paragraph, TextRun } from "../build";
const doc = new Document(); const doc = new Document();
const paragraph = new Paragraph("Hello World"); doc.addSection({
const institutionText = new TextRun({ properties: {},
text: "Foo Bar", children: [
bold: true, new Paragraph({
children: [
new TextRun("Hello World"),
new TextRun({
text: "Foo Bar",
bold: true,
}),
new TextRun({
text: "Github is the best",
bold: true,
}).tab(),
],
}),
],
}); });
const dateText = new TextRun({
text: "Github is the best",
bold: true,
}).tab();
paragraph.addRun(institutionText);
paragraph.addRun(dateText);
doc.add(paragraph);
const packer = new Packer(); const packer = new Packer();

View File

@ -127,97 +127,86 @@ const achievements = [
]; ];
class DocumentCreator { class DocumentCreator {
public create(data: object[]): Document { // tslint:disable-next-line: typedef
// tslint:disable-next-line:no-any public create([experiences, educations, skills, achivements]): Document {
const experiences = data[0] as any[];
// tslint:disable-next-line:no-any
const educations = data[1] as any[];
const skills = data[2] as object[];
const achivements = data[3] as object[];
const document = new Document(); const document = new Document();
document.add(
new Paragraph({
text: "Dolan Miu",
heading: HeadingLevel.TITLE,
}),
);
document.add(this.createContactInfo(PHONE_NUMBER, PROFILE_URL, EMAIL)); document.addSection({
document.add(this.createHeading("Education")); 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}`));
for (const education of educations) { const bulletPoints = this.splitParagraphIntoBullets(education.notes);
document.add( bulletPoints.forEach((bulletPoint) => {
this.createInstitutionHeader(education.schoolName, `${education.startDate.year} - ${education.endDate.year}`), arr.push(this.createBullet(bulletPoint));
); });
document.add(this.createRoleText(`${education.fieldOfStudy} - ${education.degree}`));
const bulletPoints = this.splitParagraphIntoBullets(education.notes); return arr;
bulletPoints.forEach((bulletPoint) => { })
document.add(this.createBullet(bulletPoint)); .reduce((prev, curr) => prev.concat(curr), []),
}); this.createHeading("Experience"),
} ...experiences
.map((position) => {
const arr: Paragraph[] = [];
document.add(this.createHeading("Experience")); arr.push(
this.createInstitutionHeader(
position.company.name,
this.createPositionDateText(position.startDate, position.endDate, position.isCurrent),
),
);
arr.push(this.createRoleText(position.title));
for (const position of experiences) { const bulletPoints = this.splitParagraphIntoBullets(position.summary);
document.add(
this.createInstitutionHeader( bulletPoints.forEach((bulletPoint) => {
position.company.name, arr.push(this.createBullet(bulletPoint));
this.createPositionDateText(position.startDate, position.endDate, position.isCurrent), });
return arr;
})
.reduce((prev, curr) => prev.concat(curr), []),
this.createHeading("Skills, Achievements and Interests"),
this.createSubHeading("Skills"),
this.createSkillList(skills),
this.createSubHeading("Achievements"),
...this.createAchivementsList(achivements),
this.createSubHeading("Interests"),
this.createInterests("Programming, Technology, Music Production, Web Design, 3D Modelling, Dancing."),
this.createHeading("References"),
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",
), ),
); new Paragraph("More references upon request"),
document.add(this.createRoleText(position.title)); 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,
}),
],
});
const bulletPoints = this.splitParagraphIntoBullets(position.summary);
bulletPoints.forEach((bulletPoint) => {
document.add(this.createBullet(bulletPoint));
});
}
document.add(this.createHeading("Skills, Achievements and Interests"));
document.add(this.createSubHeading("Skills"));
document.add(this.createSkillList(skills));
document.add(this.createSubHeading("Achievements"));
for (const achievementParagraph of this.createAchivementsList(achivements)) {
document.add(achievementParagraph);
}
document.add(this.createSubHeading("Interests"));
document.add(this.createInterests("Programming, Technology, Music Production, Web Design, 3D Modelling, Dancing."));
document.add(this.createHeading("References"));
document.add(
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",
),
);
document.add(new Paragraph("More references upon request"));
document.add(
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,
}),
);
return document; return document;
} }
public createContactInfo(phoneNumber: string, profileUrl: string, email: string): Paragraph { public createContactInfo(phoneNumber: string, profileUrl: string, email: string): Paragraph {
const paragraph = new Paragraph({ return new Paragraph({
alignment: AlignmentType.CENTER, alignment: AlignmentType.CENTER,
children: [
new TextRun(`Mobile: ${phoneNumber} | LinkedIn: ${profileUrl} | Email: ${email}`),
new TextRun("Address: 58 Elm Avenue, Kent ME4 6ER, UK").break(),
],
}); });
const contactInfo = new TextRun(`Mobile: ${phoneNumber} | LinkedIn: ${profileUrl} | Email: ${email}`);
const address = new TextRun("Address: 58 Elm Avenue, Kent ME4 6ER, UK").break();
paragraph.addRun(contactInfo);
paragraph.addRun(address);
return paragraph;
} }
public createHeading(text: string): Paragraph { public createHeading(text: string): Paragraph {
@ -236,36 +225,32 @@ class DocumentCreator {
} }
public createInstitutionHeader(institutionName: string, dateText: string): Paragraph { public createInstitutionHeader(institutionName: string, dateText: string): Paragraph {
const paragraph = new Paragraph({ return new Paragraph({
tabStop: { tabStop: {
maxRight: {}, maxRight: {},
}, },
children: [
new TextRun({
text: institutionName,
bold: true,
}),
new TextRun({
text: dateText,
bold: true,
}).tab(),
],
}); });
const institution = new TextRun({
text: institutionName,
bold: true,
});
const date = new TextRun({
text: dateText,
bold: true,
}).tab();
paragraph.addRun(institution);
paragraph.addRun(date);
return paragraph;
} }
public createRoleText(roleText: string): Paragraph { public createRoleText(roleText: string): Paragraph {
const paragraph = new Paragraph({}); return new Paragraph({
const role = new TextRun({ children: [
text: roleText, new TextRun({
italics: true, text: roleText,
italics: true,
}),
],
}); });
paragraph.addRun(role);
return paragraph;
} }
public createBullet(text: string): Paragraph { public createBullet(text: string): Paragraph {
@ -279,36 +264,28 @@ class DocumentCreator {
// tslint:disable-next-line:no-any // tslint:disable-next-line:no-any
public createSkillList(skills: any[]): Paragraph { public createSkillList(skills: any[]): Paragraph {
const paragraph = new Paragraph({}); return new Paragraph({
const skillConcat = skills.map((skill) => skill.name).join(", ") + "."; children: [new TextRun(skills.map((skill) => skill.name).join(", ") + ".")],
});
paragraph.addRun(new TextRun(skillConcat));
return paragraph;
} }
// tslint:disable-next-line:no-any // tslint:disable-next-line:no-any
public createAchivementsList(achivements: any[]): Paragraph[] { public createAchivementsList(achivements: any[]): Paragraph[] {
const arr: Paragraph[] = []; return achivements.map(
(achievement) =>
for (const achievement of achivements) { new Paragraph({
const paragraph = new Paragraph({ text: achievement.name,
text: achievement.name, bullet: {
bullet: { level: 0,
level: 0, },
}, }),
}); );
arr.push(paragraph);
}
return arr;
} }
public createInterests(interests: string): Paragraph { public createInterests(interests: string): Paragraph {
const paragraph = new Paragraph({}); return new Paragraph({
children: [new TextRun(interests)],
paragraph.addRun(new TextRun(interests)); });
return paragraph;
} }
public splitParagraphIntoBullets(text: string): string[] { public splitParagraphIntoBullets(text: string): string[] {

View File

@ -1,14 +1,9 @@
// Setting styles with JavaScript configuration // Setting styles with JavaScript configuration
// Import from 'docx' rather than '../build' if you install from npm // Import from 'docx' rather than '../build' if you install from npm
import * as fs from "fs"; import * as fs from "fs";
import { AlignmentType, Document, HeadingLevel, Packer, Paragraph, Table } from "../build"; import { AlignmentType, Document, Footer, HeadingLevel, Media, Packer, Paragraph, Table } from "../build";
const doc = new Document(undefined, { const doc = new Document();
top: 700,
right: 700,
bottom: 700,
left: 700,
});
doc.Styles.createParagraphStyle("Heading1", "Heading 1") doc.Styles.createParagraphStyle("Heading1", "Heading 1")
.basedOn("Normal") .basedOn("Normal")
@ -83,76 +78,7 @@ doc.Styles.createParagraphStyle("ListParagraph", "List Paragraph")
.quickFormat() .quickFormat()
.basedOn("Normal"); .basedOn("Normal");
doc.createImage(fs.readFileSync("./demo/images/pizza.gif")); const image = Media.addImage(doc, fs.readFileSync("./demo/images/pizza.gif"));
doc.add(
new Paragraph({
text: "HEADING",
heading: HeadingLevel.HEADING_1,
alignment: AlignmentType.CENTER,
}),
);
doc.Footer.add(
new Paragraph({
text: "1",
style: "normalPara",
alignment: AlignmentType.RIGHT,
}),
);
doc.add(
new Paragraph({
text: "Ref. :",
style: "normalPara",
}),
);
doc.add(
new Paragraph({
text: "Date :",
style: "normalPara",
}),
);
doc.add(
new Paragraph({
text: "To,",
style: "normalPara",
}),
);
doc.add(
new Paragraph({
text: "The Superindenting Engineer,(O &M)",
style: "normalPara",
}),
);
doc.add(
new Paragraph({
text: "Sub : ",
style: "normalPara",
}),
);
doc.add(
new Paragraph({
text: "Ref. : ",
style: "normalPara",
}),
);
doc.add(
new Paragraph({
text: "Sir,",
style: "normalPara",
}),
);
doc.add(
new Paragraph({
text: "BRIEF DESCRIPTION",
style: "normalPara",
}),
);
const table = new Table({ const table = new Table({
rows: 4, rows: 4,
@ -163,27 +89,78 @@ table
.getCell(0) .getCell(0)
.add(new Paragraph("Pole No.")); .add(new Paragraph("Pole No."));
doc.add(table); const image1 = Media.addImage(doc, fs.readFileSync("./demo/images/pizza.gif"));
const image2 = Media.addImage(doc, fs.readFileSync("./demo/images/pizza.gif"));
const arrboth = [ doc.addSection({
{ properties: {
image: "./demo/images/pizza.gif", top: 700,
comment: "Test", right: 700,
bottom: 700,
left: 700,
}, },
{ footers: {
image: "./demo/images/pizza.gif", default: new Footer({
comment: "Test 2", children: [
new Paragraph({
text: "1",
style: "normalPara",
alignment: AlignmentType.RIGHT,
}),
],
}),
}, },
]; children: [
new Paragraph(image),
arrboth.forEach((item) => {
doc.createImage(fs.readFileSync(item.image));
doc.add(
new Paragraph({ new Paragraph({
text: item.comment, 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(image1),
new Paragraph({
text: "Test",
style: "normalPara2", style: "normalPara2",
}), }),
); new Paragraph(image2),
new Paragraph({
text: "Test 2",
style: "normalPara2",
}),
],
}); });
const packer = new Packer(); const packer = new Packer();

View File

@ -1,22 +1,18 @@
// Scaling images // Scaling images
// Import from 'docx' rather than '../build' if you install from npm // Import from 'docx' rather than '../build' if you install from npm
import * as fs from "fs"; import * as fs from "fs";
import { Document, Packer, Paragraph } from "../build"; import { Document, Media, Packer, Paragraph } from "../build";
const doc = new Document(); const doc = new Document();
const paragraph = new Paragraph("Hello World"); const image = Media.addImage(doc, fs.readFileSync("./demo/images/pizza.gif"), 50, 50);
doc.add(paragraph); const image2 = Media.addImage(doc, fs.readFileSync("./demo/images/pizza.gif"), 100, 100);
const image3 = Media.addImage(doc, fs.readFileSync("./demo/images/pizza.gif"), 250, 250);
const image4 = Media.addImage(doc, fs.readFileSync("./demo/images/pizza.gif"), 400, 400);
const image = doc.createImage(fs.readFileSync("./demo/images/pizza.gif")); doc.addSection({
const image2 = doc.createImage(fs.readFileSync("./demo/images/pizza.gif")); children: [new Paragraph("Hello World"), new Paragraph(image), new Paragraph(image2), new Paragraph(image3), new Paragraph(image4)],
const image3 = doc.createImage(fs.readFileSync("./demo/images/pizza.gif")); });
const image4 = doc.createImage(fs.readFileSync("./demo/images/pizza.gif"));
image.scale(0.5);
image2.scale(1);
image3.scale(2.5);
image4.scale(4);
const packer = new Packer(); const packer = new Packer();

View File

@ -9,25 +9,23 @@ const doc = new Document({
externalStyles: styles, externalStyles: styles,
}); });
doc.add(new Paragraph({ doc.addSection({
text: "Cool Heading Text", children: [
heading: HeadingLevel.HEADING_1, new Paragraph({
})); text: "Cool Heading Text",
heading: HeadingLevel.HEADING_1,
const paragraph = new Paragraph({ }),
text: 'This is a custom named style from the template "MyFancyStyle"', new Paragraph({
style: "MyFancyStyle", text: 'This is a custom named style from the template "MyFancyStyle"',
style: "MyFancyStyle",
}),
new Paragraph("Some normal text"),
new Paragraph({
text: "MyFancyStyle again",
style: "MyFancyStyle",
}),
],
}); });
doc.add(paragraph);
doc.add(new Paragraph("Some normal text"));
doc.add(new Paragraph({
text: "MyFancyStyle again",
style: "MyFancyStyle",
}));
doc.add(paragraph);
const packer = new Packer(); const packer = new Packer();

View File

@ -1,36 +1,37 @@
// Page numbers // Page numbers
// Import from 'docx' rather than '../build' if you install from npm // Import from 'docx' rather than '../build' if you install from npm
import * as fs from "fs"; import * as fs from "fs";
import { AlignmentType, Document, Packer, Paragraph, TextRun } from "../build"; import { AlignmentType, Document, Header, Packer, Paragraph, TextRun } from "../build";
const doc = new Document(); const doc = new Document();
doc.add( doc.addSection({
new Paragraph({ headers: {
text: "First Page", default: new Header({
}).pageBreak(), children: [
); new Paragraph({
doc.add(new Paragraph("Second Page")); alignment: AlignmentType.RIGHT,
children: [new TextRun("My Title "), new TextRun("Page ").pageNumber()],
const pageNumber = new TextRun("Page ").pageNumber(); }),
],
const pageoneheader = new Paragraph({ }),
text: "First Page Header ", first: new Header({
alignment: AlignmentType.RIGHT, children: [
new Paragraph({
alignment: AlignmentType.RIGHT,
children: [new TextRun("First Page Header "), new TextRun("Page ").pageNumber()],
}),
],
}),
},
children: [
new Paragraph({
text: "First Page",
}).pageBreak(),
new Paragraph("Second Page"),
],
}); });
pageoneheader.addRun(pageNumber);
const firstPageHeader = doc.createFirstPageHeader();
firstPageHeader.add(pageoneheader);
const pagetwoheader = new Paragraph({
text: "My Title ",
alignment: AlignmentType.RIGHT,
});
pagetwoheader.addRun(pageNumber);
doc.Header.add(pagetwoheader);
const packer = new Packer(); const packer = new Packer();
packer.toBuffer(doc).then((buffer) => { packer.toBuffer(doc).then((buffer) => {

View File

@ -5,15 +5,16 @@ import { Document, Packer, Paragraph } from "../build";
const doc = new Document(); const doc = new Document();
const paragraph = new Paragraph("Hello World"); doc.addSection({
const paragraph2 = new Paragraph({ children: [
text: "Hello World on another page", new Paragraph("Hello World"),
pageBreakBefore: true, new Paragraph({
text: "Hello World on another page",
pageBreakBefore: true,
}),
],
}); });
doc.add(paragraph);
doc.add(paragraph2);
const packer = new Packer(); const packer = new Packer();
packer.toBuffer(doc).then((buffer) => { packer.toBuffer(doc).then((buffer) => {

View File

@ -1,27 +1,26 @@
// Multiple sections and headers // Multiple sections and headers
// Import from 'docx' rather than '../build' if you install from npm // Import from 'docx' rather than '../build' if you install from npm
import * as fs from "fs"; import * as fs from "fs";
import { Document, Packer, PageNumberFormat, PageOrientation, Paragraph, TextRun } from "../build"; import { Document, Footer, Header, Packer, PageNumberFormat, PageOrientation, Paragraph, TextRun } from "../build";
const doc = new Document(); const doc = new Document();
const paragraph = new Paragraph("Hello World").pageBreak(); doc.addSection({
children: [new Paragraph("Hello World").pageBreak()],
doc.add(paragraph); });
const header = doc.createHeader();
header.add(new Paragraph("Header on another page"));
const footer = doc.createFooter();
footer.add(new Paragraph("Footer on another page"));
doc.addSection({ doc.addSection({
headers: {
default: new Header({
children: [new Paragraph("First Default Header on another page")],
}),
},
footers: {
default: new Footer({
children: [new Paragraph("Footer on another page")],
}),
},
properties: { properties: {
headers: {
default: header,
},
footers: {
default: footer,
},
pageNumberStart: 1, pageNumberStart: 1,
pageNumberFormatType: PageNumberFormat.DECIMAL, pageNumberFormatType: PageNumberFormat.DECIMAL,
}, },
@ -29,39 +28,53 @@ doc.addSection({
}); });
doc.addSection({ doc.addSection({
headers: {
default: new Header({
children: [new Paragraph("Second Default Header on another page")],
}),
},
footers: {
default: new Footer({
children: [new Paragraph("Footer on another page")],
}),
},
size: {
orientation: PageOrientation.LANDSCAPE,
},
properties: { properties: {
headers: {
default: header,
},
footers: {
default: footer,
},
pageNumberStart: 1, pageNumberStart: 1,
pageNumberFormatType: PageNumberFormat.DECIMAL, pageNumberFormatType: PageNumberFormat.DECIMAL,
orientation: PageOrientation.LANDSCAPE,
}, },
children: [new Paragraph("hello in landscape")], children: [new Paragraph("hello in landscape")],
}); });
const header2 = doc.createHeader();
const pageNumber = new TextRun("Page number: ").pageNumber();
header2.add(new Paragraph({}).addRun(pageNumber));
doc.addSection({ doc.addSection({
properties: { headers: {
headers: { default: new Header({
default: header2, children: [
}, new Paragraph({
children: [new TextRun("Page number: ").pageNumber()],
}),
],
}),
},
size: {
orientation: PageOrientation.PORTRAIT, 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.")],
}); });
doc.addSection({ doc.addSection({
headers: {
default: new Header({
children: [
new Paragraph({
children: [new TextRun("Page number: ").pageNumber()],
}),
],
}),
},
properties: { properties: {
headers: {
default: header2,
},
pageNumberFormatType: PageNumberFormat.UPPER_ROMAN, pageNumberFormatType: PageNumberFormat.UPPER_ROMAN,
orientation: PageOrientation.PORTRAIT, orientation: PageOrientation.PORTRAIT,
}, },
@ -73,13 +86,21 @@ doc.addSection({
}); });
doc.addSection({ doc.addSection({
headers: {
default: new Header({
children: [
new Paragraph({
children: [new TextRun("Page number: ").pageNumber()],
}),
],
}),
},
size: {
orientation: PageOrientation.PORTRAIT,
},
properties: { properties: {
headers: {
default: header2,
},
pageNumberFormatType: PageNumberFormat.DECIMAL, pageNumberFormatType: PageNumberFormat.DECIMAL,
pageNumberStart: 25, pageNumberStart: 25,
orientation: PageOrientation.PORTRAIT,
}, },
children: [ 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."), 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

@ -5,11 +5,9 @@ import { Document, Packer, Paragraph } from "../build";
const doc = new Document(); const doc = new Document();
const paragraph = new Paragraph("Hello World").referenceFootnote(1); doc.addSection({
const paragraph2 = new Paragraph("Hello World").referenceFootnote(2); children: [new Paragraph("Hello World").referenceFootnote(1), new Paragraph("Hello World").referenceFootnote(2)],
});
doc.add(paragraph);
doc.add(paragraph2);
doc.createFootnote(new Paragraph("Test")); doc.createFootnote(new Paragraph("Test"));
doc.createFootnote(new Paragraph("My amazing reference")); doc.createFootnote(new Paragraph("My amazing reference"));

View File

@ -1,14 +1,21 @@
// Insert image from a buffer // Insert image from a buffer
// Import from 'docx' rather than '../build' if you install from npm // Import from 'docx' rather than '../build' if you install from npm
import * as fs from "fs"; import * as fs from "fs";
import { Document, Packer } from "../build"; import { Document, Media, Packer, Paragraph } from "../build";
const doc = new Document(); const doc = new Document();
const imageBase64Data = `iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAMAAAD04JH5AAACzVBMVEUAAAAAAAAAAAAAAAA/AD8zMzMqKiokJCQfHx8cHBwZGRkuFxcqFSonJyckJCQiIiIfHx8eHh4cHBwoGhomGSYkJCQhISEfHx8eHh4nHR0lHBwkGyQjIyMiIiIgICAfHx8mHh4lHh4kHR0jHCMiGyIhISEgICAfHx8lHx8kHh4jHR0hHCEhISEgICAlHx8kHx8jHh4jHh4iHSIhHCEhISElICAkHx8jHx8jHh4iHh4iHSIhHSElICAkICAjHx8jHx8iHh4iHh4hHiEhHSEkICAjHx8iHx8iHx8hHh4hHiEkHSEjHSAjHx8iHx8iHx8hHh4kHiEkHiEjHSAiHx8hHx8hHh4kHiEjHiAjHSAiHx8iHx8hHx8kHh4jHiEjHiAjHiAiICAiHx8kHx8jHh4jHiEjHiAiHiAiHSAiHx8jHx8jHx8jHiAiHiAiHiAiHSAiHx8jHx8jHx8iHiAiHiAiHiAjHx8jHx8jHx8jHx8iHiAiHiAiHiAjHx8jHx8jHx8iHx8iHSAiHiAjHiAjHx8jHx8hHx8iHx8iHyAiHiAjHiAjHiAjHh4hHx8iHx8iHx8iHyAjHSAjHiAjHiAjHh4hHx8iHx8iHx8jHyAjHiAhHh4iHx8iHx8jHyAjHSAjHSAhHiAhHh4iHx8iHx8jHx8jHyAjHSAjHSAiHh4iHh4jHx8jHx8jHyAjHyAhHSAhHSAiHh4iHh4jHx8jHx8jHyAhHyAhHSAiHSAiHh4jHh4jHx8jHx8jHyAhHyAhHSAiHSAjHR4jHh4jHx8jHx8hHyAhHyAiHSAjHSAjHR4jHh4jHx8hHx8hHyAhHyAiHyAjHSAjHR4jHR4hHh4hHx8hHyA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5InCt68mcOan5+ohf+z1pP8lQY/GHZQMV4YD3FpXDp4qerqbF/lBWBswyi+AL+ia+maLgcRRQj4IYlY/UpauqKBsPJAxQF8NM1TRQ/RudSPAD34rK3scOuR8/HGcspxsJfOVS8NZbiGXiUtPgINU3v3WFDmx8pEuG3EiqKKVbCC1vm2iZqap5LAtCtleQf8F9sFYWDohzeJczYyQ4V2bEZFGsQgJRGqqqhS2phHTWn9lDkIhBTqWqxQZ+IsRvtdHY9AvI2VX2hW68nfqGmuQsCEl3JdjfCF8OW1bPdtwhQ0gm2mQzfRE3a7KCYj0BNZJs8+Kxf/r6WtTEI2FIqlsMfFgRB5A6KUnSe/vUkX0AnuvUIt8SjM1m6wWQymUwmk8lkMgXRf5vi8rLQxtUhAAAAAElFTkSuQmCC`;
// doc.createImage(Buffer.from(imageBase64Data, 'base64')); const image = Media.addImage(doc, Buffer.from(imageBase64Data, "base64"), 100, 100);
doc.createImage(Buffer.from(imageBase64Data, "base64"), 100, 100);
doc.addSection({
children: [
new Paragraph({
children: [image],
}),
],
});
const packer = new Packer(); const packer = new Packer();

View File

@ -5,19 +5,23 @@ import { Document, Packer, Paragraph, TextRun } from "../build";
const doc = new Document(); const doc = new Document();
const paragraph = new Paragraph("Hello World"); doc.addSection({
const institutionText = new TextRun({ children: [
text: "Foo", new Paragraph({
bold: true, children: [
new TextRun("Hello World"),
new TextRun({
text: "Foo",
bold: true,
}),
new TextRun({
text: "Bar",
bold: true,
}).tab(),
],
}),
],
}); });
const dateText = new TextRun({
text: "Bar",
bold: true,
}).tab();
paragraph.addRun(institutionText);
paragraph.addRun(dateText);
doc.add(paragraph);
const packer = new Packer(); const packer = new Packer();

View File

@ -46,96 +46,76 @@ doc.Styles.createParagraphStyle("ListParagraph", "List Paragraph")
const numberedAbstract = doc.Numbering.createAbstractNumbering(); const numberedAbstract = doc.Numbering.createAbstractNumbering();
numberedAbstract.createLevel(0, "lowerLetter", "%1)", "left"); numberedAbstract.createLevel(0, "lowerLetter", "%1)", "left");
doc.add(
new Paragraph({
text: "Test heading1, bold and italicized",
heading: HeadingLevel.HEADING_1,
}),
);
doc.add(new Paragraph("Some simple content"));
doc.add(
new Paragraph({
text: "Test heading2 with double red underline",
heading: HeadingLevel.HEADING_2,
}),
);
const letterNumbering = doc.Numbering.createConcreteNumbering(numberedAbstract); const letterNumbering = doc.Numbering.createConcreteNumbering(numberedAbstract);
const letterNumbering5 = doc.Numbering.createConcreteNumbering(numberedAbstract); const letterNumbering5 = doc.Numbering.createConcreteNumbering(numberedAbstract);
letterNumbering5.overrideLevel(0, 5); letterNumbering5.overrideLevel(0, 5);
doc.add( doc.addSection({
new Paragraph({ children: [
text: "Option1", new Paragraph({
numbering: { text: "Test heading1, bold and italicized",
num: letterNumbering, heading: HeadingLevel.HEADING_1,
level: 0, }),
}, new Paragraph("Some simple content"),
}), new Paragraph({
); text: "Test heading2 with double red underline",
doc.add( heading: HeadingLevel.HEADING_2,
new Paragraph({ }),
text: "Option5 -- override 2 to 5", new Paragraph({
numbering: { text: "Option1",
num: letterNumbering, numbering: {
level: 0, num: letterNumbering,
}, level: 0,
}),
);
doc.add(
new Paragraph({
text: "Option3",
numbering: {
num: letterNumbering,
level: 0,
},
}),
);
doc.add(
new Paragraph({}).addRun(
new TextRun({
text: "Some monospaced content",
font: {
name: "Monospace",
}, },
}), }),
), new Paragraph({
); text: "Option5 -- override 2 to 5",
numbering: {
doc.add( num: letterNumbering,
new Paragraph({ level: 0,
text: "An aside, in light gray italics and indented", },
style: "aside", }),
}), new Paragraph({
); text: "Option3",
doc.add( numbering: {
new Paragraph({ num: letterNumbering,
text: "This is normal, but well-spaced text", level: 0,
style: "wellSpaced", },
}), }),
); new Paragraph({}).addRun(
const para = new Paragraph({}); new TextRun({
doc.add(para); text: "Some monospaced content",
// Showing the different ways to create a TextRun font: {
para.addRun( name: "Monospace",
new TextRun({ },
text: "This is a bold run,", }),
bold: true, ),
}), new Paragraph({
); text: "An aside, in light gray italics and indented",
para.addRun(new TextRun(" switching to normal ")); style: "aside",
para.addRun( }),
new TextRun({ new Paragraph({
text: "and then underlined ", text: "This is normal, but well-spaced text",
underline: {}, style: "wellSpaced",
}), }),
); new Paragraph({
para.addRun( children: [
new TextRun({ new TextRun({
text: "and back to normal.", text: "This is a bold run,",
}), bold: true,
); }),
new TextRun(" switching to normal "),
new TextRun({
text: "and then underlined ",
underline: {},
}),
new TextRun({
text: "and back to normal.",
}),
],
}),
],
});
const packer = new Packer(); const packer = new Packer();

View File

@ -10,7 +10,7 @@ const table = new Table({
columns: 4, columns: 4,
}); });
doc.add(table); doc.addSection({ children: [table] });
table table
.getCell(2, 2) .getCell(2, 2)
.add(new Paragraph("Hello")) .add(new Paragraph("Hello"))

View File

@ -3,7 +3,7 @@
import * as fs from "fs"; import * as fs from "fs";
import { Document, HeadingLevel, Packer, Paragraph } from "../build"; import { Document, HeadingLevel, Packer, Paragraph } from "../build";
const loremIpsum = const LOREM_IPSUM =
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam mi velit, convallis convallis scelerisque nec, faucibus nec leo. Phasellus at posuere mauris, tempus dignissim velit. Integer et tortor dolor. Duis auctor efficitur mattis. Vivamus ut metus accumsan tellus auctor sollicitudin venenatis et nibh. Cras quis massa ac metus fringilla venenatis. Proin rutrum mauris purus, ut suscipit magna consectetur id. Integer consectetur sollicitudin ante, vitae faucibus neque efficitur in. Praesent ultricies nibh lectus. Mauris pharetra id odio eget iaculis. Duis dictum, risus id pellentesque rutrum, lorem quam malesuada massa, quis ullamcorper turpis urna a diam. Cras vulputate metus vel massa porta ullamcorper. Etiam porta condimentum nulla nec tristique. Sed nulla urna, pharetra non tortor sed, sollicitudin molestie diam. Maecenas enim leo, feugiat eget vehicula id, sollicitudin vitae ante."; "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam mi velit, convallis convallis scelerisque nec, faucibus nec leo. Phasellus at posuere mauris, tempus dignissim velit. Integer et tortor dolor. Duis auctor efficitur mattis. Vivamus ut metus accumsan tellus auctor sollicitudin venenatis et nibh. Cras quis massa ac metus fringilla venenatis. Proin rutrum mauris purus, ut suscipit magna consectetur id. Integer consectetur sollicitudin ante, vitae faucibus neque efficitur in. Praesent ultricies nibh lectus. Mauris pharetra id odio eget iaculis. Duis dictum, risus id pellentesque rutrum, lorem quam malesuada massa, quis ullamcorper turpis urna a diam. Cras vulputate metus vel massa porta ullamcorper. Etiam porta condimentum nulla nec tristique. Sed nulla urna, pharetra non tortor sed, sollicitudin molestie diam. Maecenas enim leo, feugiat eget vehicula id, sollicitudin vitae ante.";
const doc = new Document({ const doc = new Document({
@ -16,21 +16,19 @@ const anchorId = "anchorID";
// First create the bookmark // First create the bookmark
const bookmark = doc.createBookmark(anchorId, "Lorem Ipsum"); const bookmark = doc.createBookmark(anchorId, "Lorem Ipsum");
// That has header styling
doc.add(
new Paragraph({
heading: HeadingLevel.HEADING_1,
}).addBookmark(bookmark),
);
doc.add(new Paragraph("\n"));
doc.add(new Paragraph(loremIpsum));
doc.add(new Paragraph({}).pageBreak());
// Now the link back up to the bookmark
const hyperlink = doc.createInternalHyperLink(anchorId, `Click me!`); const hyperlink = doc.createInternalHyperLink(anchorId, `Click me!`);
doc.add(new Paragraph({}).addHyperLink(hyperlink));
doc.addSection({
children: [
new Paragraph({
heading: HeadingLevel.HEADING_1,
}).addBookmark(bookmark),
new Paragraph("\n"),
new Paragraph(LOREM_IPSUM),
new Paragraph({}).pageBreak(),
new Paragraph({}).addHyperLink(hyperlink),
],
});
const packer = new Packer(); const packer = new Packer();

View File

@ -5,37 +5,39 @@ import { Document, Packer, Paragraph, TextRun } from "../build";
const doc = new Document(); const doc = new Document();
const paragraph1 = new Paragraph({ doc.addSection({
bidirectional: true, children: [
new Paragraph({
bidirectional: true,
children: [
new TextRun({
text: "שלום עולם",
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,
}),
],
}),
],
}); });
const textRun1 = new TextRun({
text: "שלום עולם",
rightToLeft: true,
});
paragraph1.addRun(textRun1);
doc.add(paragraph1);
const paragraph2 = new Paragraph({
bidirectional: true,
});
const textRun2 = new TextRun({
text: "שלום עולם",
bold: true,
rightToLeft: true,
});
paragraph2.addRun(textRun2);
doc.add(paragraph2);
const paragraph3 = new Paragraph({
bidirectional: true,
});
const textRun3 = new TextRun({
text: "שלום עולם",
italics: true,
rightToLeft: true,
});
paragraph3.addRun(textRun3);
doc.add(paragraph3);
const packer = new Packer(); const packer = new Packer();

View File

@ -1,13 +1,10 @@
// This demo adds an image to the Media cache, and then insert to the document afterwards // This demo adds an image to the Media cache, and then insert to the document afterwards
// Import from 'docx' rather than '../build' if you install from npm // Import from 'docx' rather than '../build' if you install from npm
import * as fs from "fs"; import * as fs from "fs";
import { Document, Media, Packer, Paragraph } from "../build"; import { Document, Media, Packer, Paragraph, TextRun } from "../build";
const doc = new Document(); const doc = new Document();
const paragraph = new Paragraph("Hello World");
doc.add(paragraph);
const image = Media.addImage(doc, fs.readFileSync("./demo/images/image1.jpeg")); const image = Media.addImage(doc, fs.readFileSync("./demo/images/image1.jpeg"));
const image2 = Media.addImage(doc, fs.readFileSync("./demo/images/dog.png")); const image2 = Media.addImage(doc, fs.readFileSync("./demo/images/dog.png"));
const image3 = Media.addImage(doc, fs.readFileSync("./demo/images/cat.jpg")); const image3 = Media.addImage(doc, fs.readFileSync("./demo/images/cat.jpg"));
@ -17,15 +14,18 @@ const image5 = Media.addImage(doc, fs.readFileSync("./demo/images/pizza.gif"));
const imageBase64Data = `iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAMAAAD04JH5AAACzVBMVEUAAAAAAAAAAAAAAAA/AD8zMzMqKiokJCQfHx8cHBwZGRkuFxcqFSonJyckJCQiIiIfHx8eHh4cHBwoGhomGSYkJCQhISEfHx8eHh4nHR0lHBwkGyQjIyMiIiIgICAfH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r6WtTEI2FIqlsMfFgRB5A6KUnSe/vUkX0AnuvUIt8SjM1m6wWQymUwmk8lkMgXRf5vi8rLQxtUhAAAAAElFTkSuQmCC`;
const image6 = Media.addImage(doc, Buffer.from(imageBase64Data, "base64"), 100, 100); const image6 = Media.addImage(doc, Buffer.from(imageBase64Data, "base64"), 100, 100);
// I am adding an image to the paragraph rather than the document to make the image inline doc.addSection({
paragraph.addImage(image5); children: [
new Paragraph({
doc.add(image); children: [new TextRun("Hello World"), image5],
doc.add(image2); }),
doc.add(image3); new Paragraph(image),
doc.add(image4); new Paragraph(image2),
doc.add(image5); new Paragraph(image3),
doc.add(image6); new Paragraph(image4),
new Paragraph(image6),
],
});
const packer = new Packer(); const packer = new Packer();

View File

@ -10,7 +10,9 @@ const table = new Table({
columns: 4, columns: 4,
}); });
doc.add(table); doc.addSection({
children: [table],
});
table.getCell(2, 2).add(new Paragraph("Hello")); table.getCell(2, 2).add(new Paragraph("Hello"));

View File

@ -5,30 +5,29 @@ import { Document, Packer, Paragraph } from "../build";
const doc = new Document(); const doc = new Document();
const paragraph = new Paragraph("No border!"); doc.addSection({
children: [
doc.add(paragraph); new Paragraph("No border!"),
new Paragraph({
const borderParagraph = 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, },
}, },
}, }),
],
}); });
doc.add(borderParagraph);
const packer = new Packer(); const packer = new Packer();
packer.toBuffer(doc).then((buffer) => { packer.toBuffer(doc).then((buffer) => {

View File

@ -4,12 +4,10 @@ import * as fs from "fs";
import { Document, HeadingLevel, Packer, Paragraph } from "../build"; import { Document, HeadingLevel, Packer, Paragraph } from "../build";
const doc = new Document(); const doc = new Document();
const myStyles = doc.Styles;
// The first argument is an ID you use to apply the style to paragraphs // The first argument is an ID you use to apply the style to paragraphs
// The second argument is a human-friendly name to show in the UI // The second argument is a human-friendly name to show in the UI
myStyles doc.Styles.createParagraphStyle("myWonkyStyle", "My Wonky Style")
.createParagraphStyle("myWonkyStyle", "My Wonky Style")
.basedOn("Normal") .basedOn("Normal")
.next("Normal") .next("Normal")
.color("990000") .color("990000")
@ -17,8 +15,7 @@ myStyles
.indent({ left: 720 }) // 720 TWIP === 720 / 20 pt === .5 in .indent({ left: 720 }) // 720 TWIP === 720 / 20 pt === .5 in
.spacing({ line: 276 }); // 276 / 240 = 1.15x line spacing .spacing({ line: 276 }); // 276 / 240 = 1.15x line spacing
myStyles doc.Styles.createParagraphStyle("Heading2", "Heading 2")
.createParagraphStyle("Heading2", "Heading 2")
.basedOn("Normal") .basedOn("Normal")
.next("Normal") .next("Normal")
.quickFormat() .quickFormat()
@ -27,18 +24,18 @@ myStyles
.underline("double", "FF0000") .underline("double", "FF0000")
.spacing({ before: 240, after: 120 }); // TWIP for both .spacing({ before: 240, after: 120 }); // TWIP for both
doc.add( doc.addSection({
new Paragraph({ children: [
text: "Hello", new Paragraph({
style: "myWonkyStyle", text: "Hello",
}), style: "myWonkyStyle",
); }),
doc.add( new Paragraph({
new Paragraph({ text: "World",
text: "World", heading: HeadingLevel.HEADING_2,
heading: HeadingLevel.HEADING_2, }),
}), ],
); // Uses the Heading2 style });
const packer = new Packer(); const packer = new Packer();

View File

@ -18,39 +18,40 @@ doc.Styles.createParagraphStyle("MySpectacularStyle", "My Spectacular Style")
// Let's define the properties for generate a TOC for heading 1-5 and MySpectacularStyle, // Let's define the properties for generate a TOC for heading 1-5 and MySpectacularStyle,
// making the entries be hyperlinks for the paragraph // making the entries be hyperlinks for the paragraph
const toc = new TableOfContents("Summary", {
hyperlink: true, doc.addSection({
headingStyleRange: "1-5", children: [
stylesWithLevels: [new StyleLevel("MySpectacularStyle", 1)], new TableOfContents("Summary", {
hyperlink: true,
headingStyleRange: "1-5",
stylesWithLevels: [new StyleLevel("MySpectacularStyle", 1)],
}),
new Paragraph({
text: "Header #1",
heading: HeadingLevel.HEADING_1,
pageBreakBefore: true,
}),
new Paragraph("I'm a little text very nicely written.'"),
new Paragraph({
text: "Header #2",
heading: HeadingLevel.HEADING_1,
pageBreakBefore: true,
}),
new Paragraph("I'm a other text very nicely written.'"),
new Paragraph({
text: "Header #2.1",
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,
}),
],
}); });
doc.addTableOfContents(toc);
doc.add(new Paragraph({
text: "Header #1",
heading: HeadingLevel.HEADING_1,
pageBreakBefore: true,
}));
doc.add(new Paragraph("I'm a little text very nicely written.'"));
doc.add(new Paragraph({
text: "Header #2",
heading: HeadingLevel.HEADING_1,
pageBreakBefore: true,
}));
doc.add(new Paragraph("I'm a other text very nicely written.'"));
doc.add(new Paragraph({
text: "Header #2.1",
heading: HeadingLevel.HEADING_2,
}));
doc.add(new Paragraph("I'm a another text very nicely written.'"));
doc.add(new Paragraph({
text: "My Spectacular Style #1",
style: "MySpectacularStyle",
pageBreakBefore: true,
}));
const packer = new Packer(); const packer = new Packer();
packer.toBuffer(doc).then((buffer) => { packer.toBuffer(doc).then((buffer) => {

View File

@ -1,66 +1,65 @@
// Numbered lists // Numbered lists
// Import from 'docx' rather than '../build' if you install from npm // Import from 'docx' rather than '../build' if you install from npm
import * as fs from "fs"; import * as fs from "fs";
import { Document, Indent, Numbering, Packer, Paragraph } from "../build"; import { Document, Numbering, Packer, Paragraph } from "../build";
const doc = new Document(); const doc = new Document();
const numbering = new Numbering(); const numbering = new Numbering();
const abstractNum = numbering.createAbstractNumbering(); const abstractNum = numbering.createAbstractNumbering();
abstractNum.createLevel(0, "upperRoman", "%1", "start").addProperty(new Indent({ left: 720, hanging: 260 })); abstractNum.createLevel(0, "upperRoman", "%1", "start").indent({ left: 720, hanging: 260 });
const concrete = numbering.createConcreteNumbering(abstractNum); const concrete = numbering.createConcreteNumbering(abstractNum);
const item1 = new Paragraph({ doc.addSection({
text: "line with contextual spacing", children: [
numbering: { new Paragraph({
num: concrete, text: "line with contextual spacing",
level: 0, numbering: {
}, num: concrete,
contextualSpacing: true, level: 0,
spacing: { },
before: 200, contextualSpacing: true,
}, spacing: {
before: 200,
},
}),
new Paragraph({
text: "line with contextual spacing",
numbering: {
num: concrete,
level: 0,
},
contextualSpacing: true,
spacing: {
before: 200,
},
}),
new Paragraph({
text: "line without contextual spacing",
numbering: {
num: concrete,
level: 0,
},
contextualSpacing: false,
spacing: {
before: 200,
},
}),
new Paragraph({
text: "line without contextual spacing",
numbering: {
num: concrete,
level: 0,
},
contextualSpacing: false,
spacing: {
before: 200,
},
}),
],
}); });
const item2 = new Paragraph({
text: "line with contextual spacing",
numbering: {
num: concrete,
level: 0,
},
contextualSpacing: true,
spacing: {
before: 200,
},
});
const item3 = new Paragraph({
text: "line without contextual spacing",
numbering: {
num: concrete,
level: 0,
},
contextualSpacing: false,
spacing: {
before: 200,
},
});
const item4 = new Paragraph({
text: "line without contextual spacing",
numbering: {
num: concrete,
level: 0,
},
contextualSpacing: false,
spacing: {
before: 200,
},
});
doc.add(item1);
doc.add(item2);
doc.add(item3);
doc.add(item4);
const packer = new Packer(); const packer = new Packer();

View File

@ -1,82 +1,75 @@
// Numbering and bullet points example // Numbering and bullet points example
// Import from 'docx' rather than '../build' if you install from npm // Import from 'docx' rather than '../build' if you install from npm
import * as fs from "fs"; import * as fs from "fs";
import { Document, Indent, Numbering, Packer, Paragraph } from "../build"; import { Document, Numbering, Packer, Paragraph } from "../build";
const doc = new Document(); const doc = new Document();
const numbering = new Numbering(); const numbering = new Numbering();
const abstractNum = numbering.createAbstractNumbering(); const abstractNum = numbering.createAbstractNumbering();
abstractNum.createLevel(0, "upperRoman", "%1", "start").addProperty(new Indent({ left: 720, hanging: 260 })); abstractNum.createLevel(0, "upperRoman", "%1", "start").indent({ left: 720, hanging: 260 });
abstractNum.createLevel(1, "decimal", "%2.", "start").addProperty(new Indent({ left: 1440, hanging: 980 })); abstractNum.createLevel(1, "decimal", "%2.", "start").indent({ left: 1440, hanging: 980 });
abstractNum.createLevel(2, "lowerLetter", "%3)", "start").addProperty(new Indent({ left: 14402160, hanging: 1700 })); abstractNum.createLevel(2, "lowerLetter", "%3)", "start").indent({ left: 14402160, hanging: 1700 });
const concrete = numbering.createConcreteNumbering(abstractNum); const concrete = numbering.createConcreteNumbering(abstractNum);
const topLevelP = new Paragraph({ doc.addSection({
text: "Hey you", children: [
numbering: { new Paragraph({
num: concrete, text: "Hey you",
level: 0, numbering: {
}, num: concrete,
level: 0,
},
}),
new Paragraph({
text: "What's up fam",
numbering: {
num: concrete,
level: 1,
},
}),
new Paragraph({
text: "Hello World 2",
numbering: {
num: concrete,
level: 1,
},
}),
new Paragraph({
text: "Yeah boi",
numbering: {
num: concrete,
level: 2,
},
}),
new Paragraph({
text: "Hey you",
bullet: {
level: 0,
},
}),
new Paragraph({
text: "What's up fam",
bullet: {
level: 1,
},
}),
new Paragraph({
text: "Hello World 2",
bullet: {
level: 2,
},
}),
new Paragraph({
text: "Yeah boi",
bullet: {
level: 3,
},
}),
],
}); });
const subP = new Paragraph({
text: "What's up fam",
numbering: {
num: concrete,
level: 1,
},
});
const secondSubP = new Paragraph({
text: "Hello World 2",
numbering: {
num: concrete,
level: 1,
},
});
const subSubP = new Paragraph({
text: "Yeah boi",
numbering: {
num: concrete,
level: 2,
},
});
doc.add(topLevelP);
doc.add(subP);
doc.add(secondSubP);
doc.add(subSubP);
const bullet1 = new Paragraph({
text: "Hey you",
bullet: {
level: 0,
},
});
const bullet2 = new Paragraph({
text: "What's up fam",
bullet: {
level: 1,
},
});
const bullet3 = new Paragraph({
text: "Hello World 2",
bullet: {
level: 2,
},
});
const bullet4 = new Paragraph({
text: "Yeah boi",
bullet: {
level: 3,
},
});
doc.add(bullet1);
doc.add(bullet2);
doc.add(bullet3);
doc.add(bullet4);
const packer = new Packer(); const packer = new Packer();

View File

@ -12,16 +12,16 @@ fs.readFile(filePath, (err, data) => {
} }
importDotx.extract(data).then((templateDocument) => { importDotx.extract(data).then((templateDocument) => {
// This any needs fixing const doc = new Document(undefined, {
const sectionProps = {
titlePage: templateDocument.titlePageIsDefined,
} as any;
const doc = new Document(undefined, sectionProps, {
template: templateDocument, template: templateDocument,
}); });
const paragraph = new Paragraph("Hello World");
doc.add(paragraph); doc.addSection({
properties: {
titlePage: templateDocument.titlePageIsDefined,
},
children: [new Paragraph("Hello World")],
});
const packer = new Packer(); const packer = new Packer();
packer.toBuffer(doc).then((buffer) => { packer.toBuffer(doc).then((buffer) => {

View File

@ -1,7 +1,7 @@
// Example of how you would create a table and add data to it // Example of how you would create a table and add data to it
// Import from 'docx' rather than '../build' if you install from npm // Import from 'docx' rather than '../build' if you install from npm
import * as fs from "fs"; import * as fs from "fs";
import { Document, HeadingLevel, Packer, Paragraph, VerticalAlign, Table } from "../build"; import { Document, HeadingLevel, Packer, Paragraph, Table, VerticalAlign } from "../build";
const doc = new Document(); const doc = new Document();
@ -10,8 +10,6 @@ const table = new Table({
columns: 2, columns: 2,
}); });
doc.add(table);
table table
.getCell(1, 1) .getCell(1, 1)
.add(new Paragraph("This text should be in the middle of the cell")) .add(new Paragraph("This text should be in the middle of the cell"))
@ -25,6 +23,10 @@ table.getCell(1, 0).add(
}), }),
); );
doc.addSection({
children: [table],
});
const packer = new Packer(); const packer = new Packer();
packer.toBuffer(doc).then((buffer) => { packer.toBuffer(doc).then((buffer) => {

View File

@ -5,24 +5,15 @@ import { Document, HeadingLevel, Packer, Paragraph, ShadingType, Table, WidthTyp
const doc = new Document(); const doc = new Document();
let table = new Table({ const table = new Table({
rows: 2, rows: 2,
columns: 2, columns: 2,
}); });
doc.add(table);
table.getCell(0, 0).add(new Paragraph("Hello")); table.getCell(0, 0).add(new Paragraph("Hello"));
table.getRow(0).mergeCells(0, 1); table.getRow(0).mergeCells(0, 1);
doc.add( const table2 = new Table({
new Paragraph({
text: "Another table",
heading: HeadingLevel.HEADING_2,
}),
);
table = new Table({
rows: 2, rows: 2,
columns: 3, columns: 3,
width: 100, width: 100,
@ -30,9 +21,7 @@ table = new Table({
columnWidths: [1000, 1000, 1000], columnWidths: [1000, 1000, 1000],
}); });
doc.add(table); table2
table
.getCell(0, 0) .getCell(0, 0)
.add(new Paragraph("World")) .add(new Paragraph("World"))
.setMargins({ .setMargins({
@ -43,14 +32,7 @@ table
}); });
table.getRow(0).mergeCells(0, 2); table.getRow(0).mergeCells(0, 2);
doc.add( const table3 = new Table({
new Paragraph({
text: "Another table",
heading: HeadingLevel.HEADING_2,
}),
);
table = new Table({
rows: 2, rows: 2,
columns: 4, columns: 4,
width: 7000, width: 7000,
@ -63,12 +45,10 @@ table = new Table({
}, },
}); });
doc.add(table); table3.getCell(0, 0).add(new Paragraph("Foo"));
table3.getCell(0, 1).add(new Paragraph("v"));
table.getCell(0, 0).add(new Paragraph("Foo")); table3
table.getCell(0, 1).add(new Paragraph("v"));
table
.getCell(1, 0) .getCell(1, 0)
.add(new Paragraph("Bar1")) .add(new Paragraph("Bar1"))
.setShading({ .setShading({
@ -76,7 +56,7 @@ table
val: ShadingType.REVERSE_DIAGONAL_STRIPE, val: ShadingType.REVERSE_DIAGONAL_STRIPE,
color: "auto", color: "auto",
}); });
table table3
.getCell(1, 1) .getCell(1, 1)
.add(new Paragraph("Bar2")) .add(new Paragraph("Bar2"))
.setShading({ .setShading({
@ -84,7 +64,7 @@ table
val: ShadingType.PERCENT_95, val: ShadingType.PERCENT_95,
color: "auto", color: "auto",
}); });
table table3
.getCell(1, 2) .getCell(1, 2)
.add(new Paragraph("Bar3")) .add(new Paragraph("Bar3"))
.setShading({ .setShading({
@ -92,7 +72,7 @@ table
val: ShadingType.PERCENT_10, val: ShadingType.PERCENT_10,
color: "e2df0b", color: "e2df0b",
}); });
table table3
.getCell(1, 3) .getCell(1, 3)
.add(new Paragraph("Bar4")) .add(new Paragraph("Bar4"))
.setShading({ .setShading({
@ -101,18 +81,32 @@ table
color: "auto", color: "auto",
}); });
table.getRow(0).mergeCells(0, 3); table3.getRow(0).mergeCells(0, 3);
doc.add(new Paragraph("hi")); const table4 = new Table({
table = new Table({
rows: 2, rows: 2,
columns: 2, columns: 2,
width: 100, width: 100,
widthUnitType: WidthType.PERCENTAGE, widthUnitType: WidthType.PERCENTAGE,
}); });
doc.add(table); doc.addSection({
children: [
table,
new Paragraph({
text: "Another table",
heading: HeadingLevel.HEADING_2,
}),
table2,
new Paragraph({
text: "Another table",
heading: HeadingLevel.HEADING_2,
}),
table3,
new Paragraph("hi"),
table4,
],
});
const packer = new Packer(); const packer = new Packer();

View File

@ -5,15 +5,26 @@ import { Document, Packer, Paragraph, TextRun } from "../build";
const doc = new Document(); const doc = new Document();
const paragraph = new Paragraph("Hello World 1->").addSequentialIdentifier("Caption").addRun(new TextRun(" text after sequencial caption 2->")).addSequentialIdentifier("Caption"); doc.addSection({
const paragraph2 = new Paragraph("Hello World 1->").addSequentialIdentifier("Label").addRun(new TextRun(" text after sequencial caption 2->")).addSequentialIdentifier("Label"); children: [
const paragraph3 = new Paragraph("Hello World 1->").addSequentialIdentifier("Another").addRun(new TextRun(" text after sequencial caption 3->")).addSequentialIdentifier("Label"); new Paragraph("Hello World 1->")
const paragraph4 = new Paragraph("Hello World 2->").addSequentialIdentifier("Another").addRun(new TextRun(" text after sequencial caption 4->")).addSequentialIdentifier("Label"); .addSequentialIdentifier("Caption")
.addRun(new TextRun(" text after sequencial caption 2->"))
doc.add(paragraph); .addSequentialIdentifier("Caption"),
doc.add(paragraph2); new Paragraph("Hello World 1->")
doc.add(paragraph3); .addSequentialIdentifier("Label")
doc.add(paragraph4); .addRun(new TextRun(" text after sequencial caption 2->"))
.addSequentialIdentifier("Label"),
new Paragraph("Hello World 1->")
.addSequentialIdentifier("Another")
.addRun(new TextRun(" text after sequencial caption 3->"))
.addSequentialIdentifier("Label"),
new Paragraph("Hello World 2->")
.addSequentialIdentifier("Another")
.addRun(new TextRun(" text after sequencial caption 4->"))
.addSequentialIdentifier("Label"),
],
});
const packer = new Packer(); const packer = new Packer();

View File

@ -29,11 +29,13 @@ const table = new Table({
layout: TableLayoutType.FIXED, layout: TableLayoutType.FIXED,
}); });
doc.add(table);
table.getCell(0, 0).add(new Paragraph("Hello")); table.getCell(0, 0).add(new Paragraph("Hello"));
table.getRow(0).mergeCells(0, 1); table.getRow(0).mergeCells(0, 1);
doc.addSection({
children: [table],
});
const packer = new Packer(); const packer = new Packer();
packer.toBuffer(doc).then((buffer) => { packer.toBuffer(doc).then((buffer) => {

View File

@ -8,7 +8,9 @@ const paragraph = new Paragraph({});
const link = doc.createHyperlink("http://www.example.com", "Hyperlink"); const link = doc.createHyperlink("http://www.example.com", "Hyperlink");
paragraph.addHyperLink(link); paragraph.addHyperLink(link);
doc.add(paragraph); doc.addSection({
children: [paragraph],
});
const packer = new Packer(); const packer = new Packer();

View File

@ -1,7 +1,7 @@
// Add image to table cell // Add image to table cell
// Import from 'docx' rather than '../build' if you install from npm // Import from 'docx' rather than '../build' if you install from npm
import * as fs from "fs"; import * as fs from "fs";
import { Document, Media, Packer, Paragraph, Table } from "../build"; import { Document, Header, Media, Packer, Paragraph, Table } from "../build";
const doc = new Document(); const doc = new Document();
const image = Media.addImage(doc, fs.readFileSync("./demo/images/image1.jpeg")); const image = Media.addImage(doc, fs.readFileSync("./demo/images/image1.jpeg"));
@ -12,11 +12,15 @@ const table = new Table({
}); });
table.getCell(1, 1).add(new Paragraph(image)); table.getCell(1, 1).add(new Paragraph(image));
doc.add(table); // Adding same table in the body and in the header
doc.addSection({
// doc.Header.createImage(fs.readFileSync("./demo/images/pizza.gif")); headers: {
doc.Header.add(table); default: new Header({
// doc.Footer.createImage(fs.readFileSync("./demo/images/pizza.gif")); children: [table],
}),
},
children: [table],
});
const packer = new Packer(); const packer = new Packer();

View File

@ -1,15 +1,21 @@
// Add images to header and footer // Add images to header and footer
// Import from 'docx' rather than '../build' if you install from npm // Import from 'docx' rather than '../build' if you install from npm
import * as fs from "fs"; import * as fs from "fs";
import { Document, Media, Packer, Paragraph } from "../build"; import { Document, Header, Media, Packer, Paragraph } from "../build";
const doc = new Document(); const doc = new Document();
const image = Media.addImage(doc, fs.readFileSync("./demo/images/image1.jpeg")); const image = Media.addImage(doc, fs.readFileSync("./demo/images/image1.jpeg"));
doc.add(new Paragraph("Hello World")); const image1 = Media.addImage(doc, fs.readFileSync("./demo/images/pizza.gif"));
const image2 = Media.addImage(doc, fs.readFileSync("./demo/images/image1.jpeg"));
doc.Header.addImage(image); doc.addSection({
doc.Header.createImage(fs.readFileSync("./demo/images/pizza.gif")); headers: {
doc.Header.createImage(fs.readFileSync("./demo/images/image1.jpeg")); default: new Header({
children: [new Paragraph(image), new Paragraph(image1), new Paragraph(image2)],
}),
},
children: [new Paragraph("Hello World")],
});
const packer = new Packer(); const packer = new Packer();

View File

@ -2,23 +2,11 @@
// Import from 'docx' rather than '../build' if you install from npm // Import from 'docx' rather than '../build' if you install from npm
import * as fs from "fs"; import * as fs from "fs";
// import { Document, Packer, Paragraph } from "../build"; // import { Document, Packer, Paragraph } from "../build";
import { Document, Packer, Paragraph, TextWrappingSide, TextWrappingType } from "../build"; import { Document, Media, Packer, Paragraph, TextWrappingSide, TextWrappingType } from "../build";
const doc = new Document(); const doc = new Document();
doc.add(new Paragraph( const image = Media.addImage(doc, fs.readFileSync("./demo/images/pizza.gif"), 200, 200, {
"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.",
));
doc.add(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.",
));
doc.add(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.",
));
doc.createImage(fs.readFileSync("./demo/images/pizza.gif"), 200, 200, {
floating: { floating: {
horizontalPosition: { horizontalPosition: {
offset: 2014400, offset: 2014400,
@ -37,6 +25,21 @@ doc.createImage(fs.readFileSync("./demo/images/pizza.gif"), 200, 200, {
}, },
}); });
doc.addSection({
children: [
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.",
),
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.",
),
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.",
),
new Paragraph(image),
],
});
const packer = new Packer(); const packer = new Packer();
packer.toBuffer(doc).then((buffer) => { packer.toBuffer(doc).then((buffer) => {

View File

@ -1,34 +1,44 @@
// Example how to display page numbers // Example how to display page numbers
// Import from 'docx' rather than '../build' if you install from npm // Import from 'docx' rather than '../build' if you install from npm
import * as fs from "fs"; import * as fs from "fs";
import { AlignmentType, Document, Packer, PageNumberFormat, Paragraph, TextRun } from "../build"; import { AlignmentType, Document, Footer, Header, Packer, PageNumberFormat, Paragraph, TextRun } from "../build";
const doc = new Document( const doc = new Document({});
{},
{ doc.addSection({
headers: {
default: new Header({
children: [
new Paragraph("Foo Bar corp. ")
.addRun(new TextRun("Page Number ").pageNumber())
.addRun(new TextRun(" to ").numberOfTotalPages()),
],
}),
},
footers: {
default: new Footer({
children: [
new Paragraph({
text: "Foo Bar corp. ",
alignment: AlignmentType.CENTER,
})
.addRun(new TextRun("Page Number: ").pageNumber())
.addRun(new TextRun(" to ").numberOfTotalPages()),
],
}),
},
properties: {
pageNumberStart: 1, pageNumberStart: 1,
pageNumberFormatType: PageNumberFormat.DECIMAL, pageNumberFormatType: PageNumberFormat.DECIMAL,
}, },
); children: [
new Paragraph("Hello World 1").pageBreak(),
doc.Header.add( new Paragraph("Hello World 2").pageBreak(),
new Paragraph("Foo Bar corp. ").addRun(new TextRun("Page Number ").pageNumber()).addRun(new TextRun(" to ").numberOfTotalPages()), new Paragraph("Hello World 3").pageBreak(),
); new Paragraph("Hello World 4").pageBreak(),
new Paragraph("Hello World 5").pageBreak(),
doc.Footer.add( ],
new Paragraph({ });
text: "Foo Bar corp. ",
alignment: AlignmentType.CENTER,
})
.addRun(new TextRun("Page Number: ").pageNumber())
.addRun(new TextRun(" to ").numberOfTotalPages()),
);
doc.add(new Paragraph("Hello World 1").pageBreak());
doc.add(new Paragraph("Hello World 2").pageBreak());
doc.add(new Paragraph("Hello World 3").pageBreak());
doc.add(new Paragraph("Hello World 4").pageBreak());
doc.add(new Paragraph("Hello World 5").pageBreak());
const packer = new Packer(); const packer = new Packer();

View File

@ -10,10 +10,12 @@ const table = new Table({
columns: 4, columns: 4,
}); });
doc.add(table);
table.getCell(2, 2).add(new Paragraph("Hello")); table.getCell(2, 2).add(new Paragraph("Hello"));
doc.addSection({
children: [table],
});
const packer = new Packer(); const packer = new Packer();
packer.toBuffer(doc).then((buffer) => { packer.toBuffer(doc).then((buffer) => {

View File

@ -3,30 +3,26 @@
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();
{},
{ doc.addSection({
properties: {
lineNumberCountBy: 1, lineNumberCountBy: 1,
lineNumberRestart: LineNumberRestartFormat.CONTINUOUS, lineNumberRestart: LineNumberRestartFormat.CONTINUOUS,
}, },
); children: [
new Paragraph({
doc.add( text: "Hello",
new Paragraph({ heading: HeadingLevel.HEADING_1,
text: "Hello", }),
heading: HeadingLevel.HEADING_1, 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.",
); ),
doc.add( new Paragraph(
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.",
"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.", ),
), ],
); });
doc.add(
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.",
),
);
const packer = new Packer(); const packer = new Packer();

View File

@ -10,8 +10,6 @@ const table = new Table({
columns: 6, columns: 6,
}); });
doc.add(table);
let row = 0; let row = 0;
table.getCell(row, 0).add(new Paragraph("0,0")); table.getCell(row, 0).add(new Paragraph("0,0"));
table.getCell(row, 1).add(new Paragraph("0,1")); table.getCell(row, 1).add(new Paragraph("0,1"));
@ -47,6 +45,10 @@ table.getCell(row, 0).add(new Paragraph("4,0"));
table.getCell(row, 5).add(new Paragraph("4,5")); table.getCell(row, 5).add(new Paragraph("4,5"));
table.getRow(row).mergeCells(0, 4); table.getRow(row).mergeCells(0, 4);
doc.addSection({
children: [table],
});
const packer = new Packer(); const packer = new Packer();
packer.toBuffer(doc).then((buffer) => { packer.toBuffer(doc).then((buffer) => {

View File

@ -10,11 +10,12 @@ const table = new Table({
columns: 4, columns: 4,
}); });
doc.add(table);
table.getCell(2, 2).add(new Paragraph("Hello")); table.getCell(2, 2).add(new Paragraph("Hello"));
table.getColumn(3).mergeCells(1, 2); table.getColumn(3).mergeCells(1, 2);
// table.getCell(3, 2).add(new Paragraph("Hello"));
doc.addSection({
children: [table],
});
const packer = new Packer(); const packer = new Packer();

View File

@ -1,34 +1,40 @@
// Sections with multiple columns // Sections with multiple columns
// Import from 'docx' rather than '../build' if you install from npm // Import from 'docx' rather than '../build' if you install from npm
import * as fs from "fs"; import * as fs from "fs";
import { Document, Packer } from "../build"; import { Document, Packer, Paragraph } from "../build";
const doc = new Document(); const doc = new Document();
doc.addSection({ doc.addSection({
column: { properties: {
width: 708, column: {
count: 2, width: 708,
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.",
),
],
}); });
doc.createParagraph("This text will be split into 2 columns on a page.");
doc.createParagraph(
"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.",
);
doc.addSection({ doc.addSection({
column: { properties: {
width: 708, column: {
count: 2, width: 708,
count: 3,
},
}, },
children: [
new Paragraph("This text will be split into 3 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.",
),
],
}); });
doc.createParagraph("This text will be split into 3 columns on a page.");
doc.createParagraph(
"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.",
);
const packer = new Packer(); const packer = new Packer();
packer.toBuffer(doc).then((buffer) => { packer.toBuffer(doc).then((buffer) => {

View File

@ -2,19 +2,25 @@
// Import from 'docx' rather than '../build' if you install from npm // Import from 'docx' rather than '../build' if you install from npm
import * as fs from "fs"; import * as fs from "fs";
// import { Document, Packer, Paragraph } from "../build"; // import { Document, Packer, Paragraph } from "../build";
import { Document, HorizontalPositionAlign, HorizontalPositionRelativeFrom, Packer, Paragraph, VerticalPositionAlign, VerticalPositionRelativeFrom} from "../build"; import {
Document,
HorizontalPositionAlign,
HorizontalPositionRelativeFrom,
Media,
Packer,
Paragraph,
VerticalPositionAlign,
VerticalPositionRelativeFrom,
} from "../build";
const doc = new Document(); const doc = new Document();
const paragraph = new Paragraph("Hello World"); const image1 = Media.addImage(doc, fs.readFileSync("./demo/images/image1.jpeg"));
doc.add(paragraph); const image2 = Media.addImage(doc, fs.readFileSync("./demo/images/dog.png").toString("base64"));
const image3 = Media.addImage(doc, fs.readFileSync("./demo/images/cat.jpg"));
doc.createImage(fs.readFileSync("./demo/images/image1.jpeg")); const image4 = Media.addImage(doc, fs.readFileSync("./demo/images/parrots.bmp"));
doc.createImage(fs.readFileSync("./demo/images/dog.png").toString("base64")); const image5 = Media.addImage(doc, fs.readFileSync("./demo/images/pizza.gif"));
doc.createImage(fs.readFileSync("./demo/images/cat.jpg")); const image6 = Media.addImage(doc, fs.readFileSync("./demo/images/pizza.gif"), 200, 200, {
doc.createImage(fs.readFileSync("./demo/images/parrots.bmp"));
doc.createImage(fs.readFileSync("./demo/images/pizza.gif"));
doc.createImage(fs.readFileSync("./demo/images/pizza.gif"), 200, 200, {
floating: { floating: {
horizontalPosition: { horizontalPosition: {
offset: 1014400, offset: 1014400,
@ -25,7 +31,7 @@ doc.createImage(fs.readFileSync("./demo/images/pizza.gif"), 200, 200, {
}, },
}); });
doc.createImage(fs.readFileSync("./demo/images/cat.jpg"), 200, 200, { const image7 = Media.addImage(doc, fs.readFileSync("./demo/images/cat.jpg"), 200, 200, {
floating: { floating: {
horizontalPosition: { horizontalPosition: {
relative: HorizontalPositionRelativeFrom.PAGE, relative: HorizontalPositionRelativeFrom.PAGE,
@ -38,6 +44,19 @@ doc.createImage(fs.readFileSync("./demo/images/cat.jpg"), 200, 200, {
}, },
}); });
doc.addSection({
children: [
new Paragraph("Hello World"),
new Paragraph(image1),
new Paragraph(image2),
new Paragraph(image3),
new Paragraph(image4),
new Paragraph(image5),
new Paragraph(image6),
new Paragraph(image7),
],
});
const packer = new Packer(); const packer = new Packer();
packer.toBuffer(doc).then((buffer) => { packer.toBuffer(doc).then((buffer) => {

View File

@ -3,34 +3,38 @@
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(undefined, { const doc = new Document();
top: 0,
right: 0, doc.addSection({
bottom: 0, margins: {
left: 0, top: 0,
right: 0,
bottom: 0,
left: 0,
},
children: [
new Paragraph({
children: [
new TextRun("Hello World"),
new TextRun({
text: "Foo bar",
bold: true,
}),
new TextRun({
text: "Github is the best",
bold: true,
}).tab(),
],
}),
new Paragraph({
text: "Hello World",
heading: HeadingLevel.HEADING_1,
}),
new Paragraph("Foo bar"),
new Paragraph("Github is the best"),
],
}); });
const paragraph = new Paragraph("Hello World");
const institutionText = new TextRun({
text: "Foo bar",
bold: true,
});
const dateText = new TextRun({
text: "Github is the best",
bold: true,
}).tab();
paragraph.addRun(institutionText);
paragraph.addRun(dateText);
doc.add(paragraph);
doc.add(new Paragraph({
text: "Hello World",
heading: HeadingLevel.HEADING_1,
}));
doc.add(new Paragraph("Foo bar"));
doc.add(new Paragraph("Github is the best"));
const packer = new Packer(); const packer = new Packer();
packer.toBuffer(doc).then((buffer) => { packer.toBuffer(doc).then((buffer) => {

View File

@ -3,14 +3,15 @@
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(undefined, { const doc = new Document();
orientation: PageOrientation.LANDSCAPE,
doc.addSection({
size: {
orientation: PageOrientation.LANDSCAPE,
},
children: [new Paragraph("Hello World")],
}); });
const paragraph = new Paragraph("Hello World");
doc.add(paragraph);
const packer = new Packer(); const packer = new Packer();
packer.toBuffer(doc).then((buffer) => { packer.toBuffer(doc).then((buffer) => {

View File

@ -1,14 +1,23 @@
// Add text to header and footer // Add text to header and footer
// Import from 'docx' rather than '../build' if you install from npm // Import from 'docx' rather than '../build' if you install from npm
import * as fs from "fs"; import * as fs from "fs";
import { Document, Packer, Paragraph } from "../build"; import { Document, Footer, Header, Packer, Paragraph } from "../build";
const doc = new Document(); const doc = new Document();
doc.add(new Paragraph("Hello World")); doc.addSection({
headers: {
doc.Header.add(new Paragraph("Header text")); default: new Header({
doc.Footer.add(new Paragraph("Footer text")); children: [new Paragraph("Header text")],
}),
},
footers: {
default: new Footer({
children: [new Paragraph("Footer text")],
}),
},
children: [new Paragraph("Hello World")],
});
const packer = new Packer(); const packer = new Packer();

View File

@ -1,14 +1,34 @@
// Add images to header and footer // Add images to header and footer
// Import from 'docx' rather than '../build' if you install from npm // Import from 'docx' rather than '../build' if you install from npm
import * as fs from "fs"; import * as fs from "fs";
import { Document, Packer, Paragraph } from "../build"; import { Document, Footer, Header, Media, Packer, Paragraph } from "../build";
const doc = new Document(); const doc = new Document();
doc.add(new Paragraph("Hello World")); const image1 = Media.addImage(doc, fs.readFileSync("./demo/images/pizza.gif"));
const image2 = Media.addImage(doc, fs.readFileSync("./demo/images/pizza.gif"));
doc.Header.createImage(fs.readFileSync("./demo/images/pizza.gif")); doc.addSection({
doc.Footer.createImage(fs.readFileSync("./demo/images/pizza.gif")); headers: {
default: new Header({
children: [
new Paragraph({
children: [image1],
}),
],
}),
},
footers: {
default: new Footer({
children: [
new Paragraph({
children: [image2],
}),
],
}),
},
children: [new Paragraph("Hello World")],
});
const packer = new Packer(); const packer = new Packer();

View File

@ -1,7 +1,7 @@
/* tslint:disable:typedef space-before-function-paren */ /* tslint:disable:typedef space-before-function-paren */
import { expect } from "chai"; import { expect } from "chai";
import { File } from "file"; import { File, Header, Footer } from "file";
import { Compiler } from "./next-compiler"; import { Compiler } from "./next-compiler";
@ -21,28 +21,39 @@ describe("Compiler", () => {
const fileNames = Object.keys(zipFile.files).map((f) => zipFile.files[f].name); const fileNames = Object.keys(zipFile.files).map((f) => zipFile.files[f].name);
expect(fileNames).is.an.instanceof(Array); expect(fileNames).is.an.instanceof(Array);
expect(fileNames).has.length(18); expect(fileNames).has.length(14);
expect(fileNames).to.include("word/document.xml"); expect(fileNames).to.include("word/document.xml");
expect(fileNames).to.include("word/styles.xml"); expect(fileNames).to.include("word/styles.xml");
expect(fileNames).to.include("docProps/core.xml"); expect(fileNames).to.include("docProps/core.xml");
expect(fileNames).to.include("docProps/app.xml"); expect(fileNames).to.include("docProps/app.xml");
expect(fileNames).to.include("word/numbering.xml"); expect(fileNames).to.include("word/numbering.xml");
expect(fileNames).to.include("word/header1.xml");
expect(fileNames).to.include("word/_rels/header1.xml.rels");
expect(fileNames).to.include("word/footer1.xml");
expect(fileNames).to.include("word/footnotes.xml"); expect(fileNames).to.include("word/footnotes.xml");
expect(fileNames).to.include("word/settings.xml"); expect(fileNames).to.include("word/settings.xml");
expect(fileNames).to.include("word/_rels/footer1.xml.rels");
expect(fileNames).to.include("word/_rels/document.xml.rels"); expect(fileNames).to.include("word/_rels/document.xml.rels");
expect(fileNames).to.include("[Content_Types].xml"); expect(fileNames).to.include("[Content_Types].xml");
expect(fileNames).to.include("_rels/.rels"); expect(fileNames).to.include("_rels/.rels");
}); });
it("should pack all additional headers and footers", async function() { it("should pack all additional headers and footers", async function() {
file.createFooter(); file.addSection({
file.createFooter(); headers: {
file.createHeader(); default: new Header(),
file.createHeader(); },
footers: {
default: new Footer(),
},
children: [],
});
file.addSection({
headers: {
default: new Header(),
},
footers: {
default: new Footer(),
},
children: [],
});
this.timeout(99999999); this.timeout(99999999);
@ -50,20 +61,16 @@ describe("Compiler", () => {
const fileNames = Object.keys(zipFile.files).map((f) => zipFile.files[f].name); const fileNames = Object.keys(zipFile.files).map((f) => zipFile.files[f].name);
expect(fileNames).is.an.instanceof(Array); expect(fileNames).is.an.instanceof(Array);
expect(fileNames).has.length(26); expect(fileNames).has.length(22);
expect(fileNames).to.include("word/header1.xml"); expect(fileNames).to.include("word/header1.xml");
expect(fileNames).to.include("word/_rels/header1.xml.rels"); expect(fileNames).to.include("word/_rels/header1.xml.rels");
expect(fileNames).to.include("word/header2.xml"); expect(fileNames).to.include("word/header2.xml");
expect(fileNames).to.include("word/_rels/header2.xml.rels"); expect(fileNames).to.include("word/_rels/header2.xml.rels");
expect(fileNames).to.include("word/header3.xml");
expect(fileNames).to.include("word/_rels/header3.xml.rels");
expect(fileNames).to.include("word/footer1.xml"); expect(fileNames).to.include("word/footer1.xml");
expect(fileNames).to.include("word/_rels/footer1.xml.rels"); expect(fileNames).to.include("word/_rels/footer1.xml.rels");
expect(fileNames).to.include("word/footer2.xml"); expect(fileNames).to.include("word/footer2.xml");
expect(fileNames).to.include("word/_rels/footer2.xml.rels"); expect(fileNames).to.include("word/_rels/footer2.xml.rels");
expect(fileNames).to.include("word/footer3.xml");
expect(fileNames).to.include("word/_rels/footer3.xml.rels");
}); });
}); });
}); });

View File

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

View File

@ -11,35 +11,7 @@ describe("Body", () => {
body = new Body(); body = new Body();
}); });
describe("#constructor()", () => {
it("should create default section", () => {
const formatted = new Formatter().format(body)["w:body"][0];
expect(formatted)
.to.have.property("w:sectPr")
.and.to.be.an.instanceof(Array);
expect(formatted["w:sectPr"]).to.have.length(4);
});
});
describe("#addSection", () => { describe("#addSection", () => {
it("should add section with options", () => {
body.addSection({
width: 10000,
height: 10000,
});
const formatted = new Formatter().format(body)["w:body"];
expect(formatted).to.be.an.instanceof(Array);
const defaultSectionPr = formatted[0]["w:p"][0]["w:pPr"][0]["w:sectPr"];
// check that this is the default section and added first in paragraph
expect(defaultSectionPr[0]).to.deep.equal({ "w:pgSz": { _attr: { "w:h": 16838, "w:w": 11906, "w:orient": "portrait" } } });
// check for new section (since it's the last one, it's direct child of body)
const newSection = formatted[1]["w:sectPr"];
expect(newSection[0]).to.deep.equal({ "w:pgSz": { _attr: { "w:h": 10000, "w:w": 10000, "w:orient": "portrait" } } });
});
it("should add section with default parameters", () => { it("should add section with default parameters", () => {
body.addSection({ body.addSection({
width: 10000, width: 10000,
@ -51,33 +23,7 @@ describe("Body", () => {
expect(tree).to.deep.equal({ expect(tree).to.deep.equal({
"w:body": [ "w:body": [
{ {
"w:p": [ "w:p": {},
{
"w:pPr": [
{
"w:sectPr": [
{ "w:pgSz": { _attr: { "w:w": 11906, "w:h": 16838, "w:orient": "portrait" } } },
{
"w:pgMar": {
_attr: {
"w:top": 1440,
"w:right": 1440,
"w:bottom": 1440,
"w:left": 1440,
"w:header": 708,
"w:footer": 708,
"w:gutter": 0,
"w:mirrorMargins": false,
},
},
},
{ "w:cols": { _attr: { "w:space": 708, "w:num": 1 } } },
{ "w:docGrid": { _attr: { "w:linePitch": 360 } } },
],
},
],
},
],
}, },
{ {
"w:sectPr": [ "w:sectPr": [
@ -104,21 +50,4 @@ describe("Body", () => {
}); });
}); });
}); });
describe("#getParagraphs", () => {
it("should get no paragraphs", () => {
const paragraphs = body.getParagraphs();
expect(paragraphs).to.be.an.instanceof(Array);
});
});
describe("#DefaultSection", () => {
it("should get section", () => {
const section = body.DefaultSection;
const tree = new Formatter().format(section);
expect(tree["w:sectPr"]).to.be.an.instanceof(Array);
});
});
}); });

View File

@ -3,15 +3,10 @@ import { Paragraph, ParagraphProperties, TableOfContents } from "../..";
import { SectionProperties, SectionPropertiesOptions } from "./section-properties/section-properties"; import { SectionProperties, SectionPropertiesOptions } from "./section-properties/section-properties";
export class Body extends XmlComponent { export class Body extends XmlComponent {
private readonly defaultSection: SectionProperties;
private readonly sections: SectionProperties[] = []; private readonly sections: SectionProperties[] = [];
constructor(sectionPropertiesOptions?: SectionPropertiesOptions) { constructor() {
super("w:body"); super("w:body");
this.defaultSection = new SectionProperties(sectionPropertiesOptions);
this.sections.push(this.defaultSection);
} }
/** /**
@ -20,21 +15,15 @@ export class Body extends XmlComponent {
* The spec says: * The spec says:
* - section element should be in the last paragraph of the section * - section element should be in the last paragraph of the section
* - last section should be direct child of body * - last section should be direct child of body
* @param section new section * @param options new section options
*/ */
public addSection(section: SectionPropertiesOptions | SectionProperties): void { public addSection(options: SectionPropertiesOptions): 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));
if (section instanceof SectionProperties) {
this.sections.push(section); this.sections.push(new SectionProperties(options));
} else {
const params = {
...this.defaultSection.Options,
...section,
};
this.sections.push(new SectionProperties(params));
}
} }
public prepForXml(): IXmlableObject | undefined { public prepForXml(): IXmlableObject | undefined {
if (this.sections.length === 1) { if (this.sections.length === 1) {
this.root.push(this.sections.pop() as SectionProperties); this.root.push(this.sections.pop() as SectionProperties);
@ -47,18 +36,10 @@ export class Body extends XmlComponent {
this.root.push(component); this.root.push(component);
} }
public get DefaultSection(): SectionProperties {
return this.defaultSection;
}
public getTablesOfContents(): TableOfContents[] { public getTablesOfContents(): TableOfContents[] {
return this.root.filter((child) => child instanceof TableOfContents) as TableOfContents[]; return this.root.filter((child) => child instanceof TableOfContents) as TableOfContents[];
} }
public getParagraphs(): Paragraph[] {
return this.root.filter((child) => child instanceof Paragraph) as Paragraph[];
}
private createSectionParagraph(section: SectionProperties): Paragraph { private createSectionParagraph(section: SectionProperties): Paragraph {
const paragraph = new Paragraph({}); const paragraph = new Paragraph({});
const properties = new ParagraphProperties({}); const properties = new ParagraphProperties({});

View File

@ -1,13 +1,13 @@
import { XmlComponent } from "file/xml-components"; import { XmlComponent } from "file/xml-components";
import { HeaderReferenceAttributes, HeaderReferenceType } from "./header-reference-attributes"; import { HeaderReferenceAttributes, HeaderReferenceType } from "./header-reference-attributes";
export interface IHeaderOptions { export interface IHeaderReferenceOptions {
readonly headerType?: HeaderReferenceType; readonly headerType?: HeaderReferenceType;
readonly headerId?: number; readonly headerId?: number;
} }
export class HeaderReference extends XmlComponent { export class HeaderReference extends XmlComponent {
constructor(options: IHeaderOptions) { constructor(options: IHeaderReferenceOptions) {
super("w:headerReference"); super("w:headerReference");
this.root.push( this.root.push(
new HeaderReferenceAttributes({ new HeaderReferenceAttributes({

View File

@ -1,4 +1,4 @@
import { assert, expect } from "chai"; import { expect } from "chai";
import { Formatter } from "export/formatter"; import { Formatter } from "export/formatter";
@ -13,19 +13,34 @@ describe("Document", () => {
describe("#constructor()", () => { describe("#constructor()", () => {
it("should create valid JSON", () => { it("should create valid JSON", () => {
const stringifiedJson = JSON.stringify(document); const tree = new Formatter().format(document);
try { expect(tree).to.deep.equal({
JSON.parse(stringifiedJson); "w:document": [
} catch (e) { {
assert.isTrue(false); _attr: {
} "xmlns:wpc": "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas",
assert.isTrue(true); "xmlns:mc": "http://schemas.openxmlformats.org/markup-compatibility/2006",
}); "xmlns:o": "urn:schemas-microsoft-com:office:office",
"xmlns:r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
it("should create default section", () => { "xmlns:m": "http://schemas.openxmlformats.org/officeDocument/2006/math",
const body = new Formatter().format(document)["w:document"][1]["w:body"]; "xmlns:v": "urn:schemas-microsoft-com:vml",
expect(body[0]).to.have.property("w:sectPr"); "xmlns:wp14": "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing",
"xmlns:wp": "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",
"xmlns:w10": "urn:schemas-microsoft-com:office:word",
"xmlns:w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
"xmlns:w14": "http://schemas.microsoft.com/office/word/2010/wordml",
"xmlns:w15": "http://schemas.microsoft.com/office/word/2012/wordml",
"xmlns:wpg": "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup",
"xmlns:wpi": "http://schemas.microsoft.com/office/word/2010/wordprocessingInk",
"xmlns:wne": "http://schemas.microsoft.com/office/word/2006/wordml",
"xmlns:wps": "http://schemas.microsoft.com/office/word/2010/wordprocessingShape",
"mc:Ignorable": "w14 w15 wp14",
},
},
{ "w:body": {} },
],
});
}); });
}); });
}); });

View File

@ -4,13 +4,12 @@ import { Paragraph } from "../paragraph";
import { Table } from "../table"; import { Table } from "../table";
import { TableOfContents } from "../table-of-contents"; import { TableOfContents } from "../table-of-contents";
import { Body } from "./body"; import { Body } from "./body";
import { SectionPropertiesOptions } from "./body/section-properties";
import { DocumentAttributes } from "./document-attributes"; import { DocumentAttributes } from "./document-attributes";
export class Document extends XmlComponent { export class Document extends XmlComponent {
private readonly body: Body; private readonly body: Body;
constructor(sectionPropertiesOptions?: SectionPropertiesOptions) { constructor() {
super("w:document"); super("w:document");
this.root.push( this.root.push(
new DocumentAttributes({ new DocumentAttributes({
@ -33,17 +32,12 @@ export class Document extends XmlComponent {
Ignorable: "w14 w15 wp14", Ignorable: "w14 w15 wp14",
}), }),
); );
this.body = new Body(sectionPropertiesOptions); this.body = new Body();
this.root.push(this.body); this.root.push(this.body);
} }
public add(paragraph: Paragraph | Table): Document { public add(item: Paragraph | Table | TableOfContents): Document {
this.body.push(paragraph); this.body.push(item);
return this;
}
public addTableOfContents(toc: TableOfContents): Document {
this.body.push(toc);
return this; return this;
} }
@ -54,8 +48,4 @@ export class Document extends XmlComponent {
public getTablesOfContents(): TableOfContents[] { public getTablesOfContents(): TableOfContents[] {
return this.body.getTablesOfContents(); return this.body.getTablesOfContents();
} }
public getParagraphs(): Paragraph[] {
return this.body.getParagraphs();
}
} }

View File

@ -4,24 +4,37 @@ 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 { Paragraph } from "./paragraph"; import { Paragraph } from "./paragraph";
import { Table } from "./table"; import { Table } from "./table";
import { TableOfContents } from "./table-of-contents"; 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.Body);
expect(tree["w:body"][1]["w:sectPr"][4]["w:headerReference"]._attr["w:type"]).to.equal("default");
expect(tree["w:body"][1]["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();
const header = doc.createHeader();
const footer = doc.createFooter();
doc.addSectionOld({ doc.addSection({
headers: { headers: {
default: header, default: new Header(),
}, },
footers: { footers: {
default: footer, default: new Footer(),
}, },
children: [],
}); });
const tree = new Formatter().format(doc.Document.Body); const tree = new Formatter().format(doc.Document.Body);
@ -32,40 +45,40 @@ 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();
const header = doc.createHeader();
const footer = doc.createFooter();
doc.addSectionOld({ doc.addSection({
headers: { headers: {
first: header, first: new Header(),
}, },
footers: { footers: {
first: footer, first: new Footer(),
}, },
children: [],
}); });
const tree = new Formatter().format(doc.Document.Body); const tree = new Formatter().format(doc.Document.Body);
expect(tree["w:body"][1]["w:sectPr"][4]["w:headerReference"]._attr["w:type"]).to.equal("first"); console.log(JSON.stringify(tree, null, 2));
expect(tree["w:body"][1]["w:sectPr"][5]["w:footerReference"]._attr["w:type"]).to.equal("first");
expect(tree["w:body"][1]["w:sectPr"][5]["w:headerReference"]._attr["w:type"]).to.equal("first");
expect(tree["w:body"][1]["w:sectPr"][7]["w:footerReference"]._attr["w:type"]).to.equal("first");
}); });
it("should create with correct headers", () => { it("should create with correct headers", () => {
const doc = new File(); const doc = new File();
const header = doc.createHeader();
const footer = doc.createFooter();
doc.addSectionOld({ doc.addSection({
headers: { headers: {
default: header, default: new Header(),
first: header, first: new Header(),
even: header, even: new Header(),
}, },
footers: { footers: {
default: footer, default: new Footer(),
first: footer, first: new Footer(),
even: footer, even: new Footer(),
}, },
children: [],
}); });
const tree = new Formatter().format(doc.Document.Body); const tree = new Formatter().format(doc.Document.Body);
@ -80,60 +93,56 @@ describe("File", () => {
}); });
}); });
describe("#add", () => { describe("#addSection", () => {
it("should call the underlying document's add a Paragraph", () => { it("should call the underlying document's add a Paragraph", () => {
const file = new File(); const file = new File();
const spy = sinon.spy(file.Document, "add"); const spy = sinon.spy(file.Document, "add");
file.add(new Paragraph({})); file.addSection({
children: [new Paragraph({})],
});
expect(spy.called).to.equal(true); expect(spy.called).to.equal(true);
}); });
it("should call the underlying document's add when adding a Table", () => { it("should call the underlying document's add when adding a Table", () => {
const wrapper = new File(); const file = new File();
const spy = sinon.spy(wrapper.Document, "add"); const spy = sinon.spy(file.Document, "add");
wrapper.add( file.addSection({
new Table({ children: [
rows: 1, new Table({
columns: 1, rows: 1,
}), columns: 1,
); }),
],
});
expect(spy.called).to.equal(true); expect(spy.called).to.equal(true);
}); });
it("should call the underlying document's add when adding an Image (paragraph)", () => { it("should call the underlying document's add when adding an Image (paragraph)", () => {
const wrapper = new File(); const file = new File();
const spy = sinon.spy(wrapper.Document, "add"); const spy = sinon.spy(file.Document, "add");
// tslint:disable-next-line:no-any // tslint:disable-next-line:no-any
wrapper.add(new Paragraph("")); file.addSection({
children: [new Paragraph("")],
});
expect(spy.called).to.equal(true); expect(spy.called).to.equal(true);
}); });
}); });
describe("#add", () => { describe("#addSection", () => {
it("should call the underlying document's addTableOfContents", () => { it("should call the underlying document's add", () => {
const wrapper = new File(); const file = new File();
const spy = sinon.spy(wrapper.Document, "addTableOfContents"); const spy = sinon.spy(file.Document, "add");
wrapper.add(new TableOfContents()); file.addSection({
children: [new TableOfContents()],
});
expect(spy.called).to.equal(true); expect(spy.called).to.equal(true);
}); });
}); });
describe("#createImage", () => {
it("should call the underlying document's createImage", () => {
const wrapper = new File();
const spy = sinon.spy(wrapper.Media, "addMedia");
const wrapperSpy = sinon.spy(wrapper.Document, "add");
wrapper.createImage("");
expect(spy.called).to.equal(true);
expect(wrapperSpy.called).to.equal(true);
});
});
describe("#createFootnote", () => { describe("#createFootnote", () => {
it("should call the underlying document's createFootnote", () => { it("should call the underlying document's createFootnote", () => {
const wrapper = new File(); const wrapper = new File();

View File

@ -3,17 +3,16 @@ import { ContentTypes } from "./content-types/content-types";
import { CoreProperties, IPropertiesOptions } from "./core-properties"; import { CoreProperties, IPropertiesOptions } from "./core-properties";
import { Document } from "./document"; import { Document } from "./document";
import { import {
FooterReference,
FooterReferenceType, FooterReferenceType,
HeaderReference,
HeaderReferenceType, HeaderReferenceType,
IHeaderFooterGroup, IPageSizeAttributes,
SectionPropertiesOptions, SectionPropertiesOptions,
} from "./document/body/section-properties"; } from "./document/body/section-properties";
import { IDrawingOptions } from "./drawing"; 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 { FootNotes } from "./footnotes"; import { FootNotes } from "./footnotes";
import { Footer, Header } from "./header";
import { HeaderWrapper, IDocumentHeader } from "./header-wrapper"; import { HeaderWrapper, IDocumentHeader } from "./header-wrapper";
import { Media } from "./media"; import { Media } from "./media";
import { Numbering } from "./numbering"; import { Numbering } from "./numbering";
@ -28,7 +27,19 @@ import { Table } from "./table";
import { TableOfContents } from "./table-of-contents"; import { TableOfContents } from "./table-of-contents";
export interface ISectionOptions { export interface ISectionOptions {
readonly properties: SectionPropertiesOptions; readonly headers?: {
readonly default?: Header;
readonly first?: Header;
readonly even?: Header;
};
readonly footers?: {
readonly default?: Footer;
readonly first?: Footer;
readonly even?: Footer;
};
readonly size?: IPageSizeAttributes;
readonly margins?: IPageMarginAttributes;
readonly properties?: SectionPropertiesOptions;
readonly children: Array<Paragraph | Table | TableOfContents>; readonly children: Array<Paragraph | Table | TableOfContents>;
} }
@ -57,7 +68,6 @@ export class File {
revision: "1", revision: "1",
lastModifiedBy: "Un-named", lastModifiedBy: "Un-named",
}, },
sectionPropertiesOptions: SectionPropertiesOptions = {},
fileProperties: IFileProperties = {}, fileProperties: IFileProperties = {},
sections: ISectionOptions[] = [], sections: ISectionOptions[] = [],
) { ) {
@ -68,6 +78,8 @@ export class File {
this.appProperties = new AppProperties(); this.appProperties = new AppProperties();
this.footNotes = new FootNotes(); this.footNotes = new FootNotes();
this.contentTypes = new ContentTypes(); this.contentTypes = new ContentTypes();
this.document = new Document();
this.settings = new Settings();
this.media = fileProperties.template && fileProperties.template.media ? fileProperties.template.media : new Media(); this.media = fileProperties.template && fileProperties.template.media ? fileProperties.template.media : new Media();
@ -96,65 +108,23 @@ export class File {
for (const templateHeader of fileProperties.template.headers) { for (const templateHeader of fileProperties.template.headers) {
this.addHeaderToDocument(templateHeader.header, templateHeader.type); this.addHeaderToDocument(templateHeader.header, templateHeader.type);
} }
} else {
this.createHeader();
} }
if (fileProperties.template && fileProperties.template.footers) { if (fileProperties.template && fileProperties.template.footers) {
for (const templateFooter of fileProperties.template.footers) { for (const templateFooter of fileProperties.template.footers) {
this.addFooterToDocument(templateFooter.footer, templateFooter.type); this.addFooterToDocument(templateFooter.footer, templateFooter.type);
} }
} else {
this.createFooter();
} }
const newSectionPropertiesOptions = {
...sectionPropertiesOptions,
headers: this.groupHeaders(this.headers, sectionPropertiesOptions.headers),
footers: this.groupFooters(this.footers, sectionPropertiesOptions.footers),
};
this.document = new Document(newSectionPropertiesOptions);
this.settings = new Settings();
for (const section of sections) { for (const section of sections) {
this.document.Body.addSection(section.properties); this.document.Body.addSection(section.properties ? section.properties : {});
for (const child of section.children) { for (const child of section.children) {
this.add(child); this.document.add(child);
} }
} }
} }
public add(item: Paragraph | Table | TableOfContents): File {
if (item instanceof Paragraph) {
this.document.add(item);
}
if (item instanceof Table) {
this.document.add(item);
}
if (item instanceof TableOfContents) {
this.document.addTableOfContents(item);
}
return this;
}
public createImage(
buffer: Buffer | string | Uint8Array | ArrayBuffer,
width?: number,
height?: number,
drawingOptions?: IDrawingOptions,
): Paragraph {
const image = Media.addImage(this, buffer, width, height, drawingOptions);
const paragraph = new Paragraph(image);
this.document.add(paragraph);
return paragraph;
}
public createHyperlink(link: string, text?: string): Hyperlink { public createHyperlink(link: string, text?: string): Hyperlink {
const newText = text === undefined ? link : text; const newText = text === undefined ? link : text;
const hyperlink = new Hyperlink(newText, this.docRelationships.RelationshipCount); const hyperlink = new Hyperlink(newText, this.docRelationships.RelationshipCount);
@ -175,21 +145,36 @@ export class File {
return hyperlink; return hyperlink;
} }
public createBookmark(name: string, text?: string): Bookmark { public createBookmark(name: string, text: string = name): Bookmark {
const newText = text === undefined ? name : text; return new Bookmark(name, text, this.docRelationships.RelationshipCount);
const bookmark = new Bookmark(name, newText, this.docRelationships.RelationshipCount);
return bookmark;
} }
public addSectionOld(sectionPropertiesOptions: SectionPropertiesOptions): void { public addSection({
this.document.Body.addSection(sectionPropertiesOptions); headers = { default: new Header() },
} footers = { default: new Header() },
margins = {},
size = {},
properties,
children,
}: ISectionOptions): void {
this.document.Body.addSection({
...properties,
headers: {
default: headers.default ? this.createHeader(headers.default) : this.createHeader(new Header()),
first: headers.first ? this.createHeader(headers.first) : undefined,
even: headers.even ? this.createHeader(headers.even) : undefined,
},
footers: {
default: footers.default ? this.createFooter(footers.default) : this.createFooter(new Footer()),
first: footers.first ? this.createFooter(footers.first) : undefined,
even: footers.even ? this.createFooter(footers.even) : undefined,
},
...margins,
...size,
});
public addSection(section: ISectionOptions): void { for (const child of children) {
this.document.Body.addSection(section.properties); this.document.add(child);
for (const child of section.children) {
this.add(child);
} }
} }
@ -197,92 +182,34 @@ export class File {
this.footNotes.createFootNote(paragraph); this.footNotes.createFootNote(paragraph);
} }
public createHeader(): HeaderWrapper {
const header = new HeaderWrapper(this.media, this.currentRelationshipId++);
this.addHeaderToDocument(header);
return header;
}
public createFooter(): FooterWrapper {
const footer = new FooterWrapper(this.media, this.currentRelationshipId++);
this.addFooterToDocument(footer);
return footer;
}
public createFirstPageHeader(): HeaderWrapper {
const headerWrapper = this.createHeader();
this.document.Body.DefaultSection.addChildElement(
new HeaderReference({
headerType: HeaderReferenceType.FIRST,
headerId: headerWrapper.Header.ReferenceId,
}),
);
return headerWrapper;
}
public createEvenPageHeader(): HeaderWrapper {
const headerWrapper = this.createHeader();
this.document.Body.DefaultSection.addChildElement(
new HeaderReference({
headerType: HeaderReferenceType.EVEN,
headerId: headerWrapper.Header.ReferenceId,
}),
);
return headerWrapper;
}
public createFirstPageFooter(): FooterWrapper {
const footerWrapper = this.createFooter();
this.document.Body.DefaultSection.addChildElement(
new FooterReference({
footerType: FooterReferenceType.FIRST,
footerId: footerWrapper.Footer.ReferenceId,
}),
);
return footerWrapper;
}
public createEvenPageFooter(): FooterWrapper {
const footerWrapper = this.createFooter();
this.document.Body.DefaultSection.addChildElement(
new FooterReference({
footerType: FooterReferenceType.EVEN,
footerId: footerWrapper.Footer.ReferenceId,
}),
);
return footerWrapper;
}
public getFooterByReferenceNumber(refId: number): FooterWrapper {
const entry = this.footers.map((item) => item.footer).find((h) => h.Footer.ReferenceId === refId);
if (entry) {
return entry;
}
throw new Error(`There is no footer with given reference id ${refId}`);
}
public getHeaderByReferenceNumber(refId: number): HeaderWrapper {
const entry = this.headers.map((item) => item.header).find((h) => h.Header.ReferenceId === refId);
if (entry) {
return entry;
}
throw new Error(`There is no header with given reference id ${refId}`);
}
public verifyUpdateFields(): void { public verifyUpdateFields(): void {
if (this.document.getTablesOfContents().length) { if (this.document.getTablesOfContents().length) {
this.settings.addUpdateFields(); this.settings.addUpdateFields();
} }
} }
private createHeader(header: Header): HeaderWrapper {
const wrapper = new HeaderWrapper(this.media, this.currentRelationshipId++);
for (const child of header.options.children) {
wrapper.add(child);
}
this.addHeaderToDocument(wrapper);
return wrapper;
}
private createFooter(footer: Footer): FooterWrapper {
const wrapper = new FooterWrapper(this.media, this.currentRelationshipId++);
for (const child of footer.options.children) {
wrapper.add(child);
}
this.addFooterToDocument(wrapper);
return wrapper;
}
private addHeaderToDocument(header: HeaderWrapper, type: HeaderReferenceType = HeaderReferenceType.DEFAULT): void { private addHeaderToDocument(header: HeaderWrapper, type: HeaderReferenceType = HeaderReferenceType.DEFAULT): void {
this.headers.push({ header, type }); this.headers.push({ header, type });
this.docRelationships.createRelationship( this.docRelationships.createRelationship(
@ -342,66 +269,6 @@ export class File {
); );
} }
private groupHeaders(headers: IDocumentHeader[], group: IHeaderFooterGroup<HeaderWrapper> = {}): IHeaderFooterGroup<HeaderWrapper> {
let newGroup = group;
for (const header of headers) {
switch (header.type) {
case HeaderReferenceType.FIRST:
newGroup = {
...newGroup,
first: header.header,
};
break;
case HeaderReferenceType.EVEN:
newGroup = {
...newGroup,
even: header.header,
};
break;
case HeaderReferenceType.DEFAULT:
default:
newGroup = {
...newGroup,
default: header.header,
};
break;
}
}
return newGroup;
}
private groupFooters(footers: IDocumentFooter[], group: IHeaderFooterGroup<FooterWrapper> = {}): IHeaderFooterGroup<FooterWrapper> {
let newGroup = group;
for (const footer of footers) {
switch (footer.type) {
case FooterReferenceType.FIRST:
newGroup = {
...newGroup,
first: footer.footer,
};
break;
case FooterReferenceType.EVEN:
newGroup = {
...newGroup,
even: footer.footer,
};
break;
case FooterReferenceType.DEFAULT:
default:
newGroup = {
...newGroup,
default: footer.footer,
};
break;
}
}
return newGroup;
}
public get Document(): Document { public get Document(): Document {
return this.document; return this.document;
} }
@ -434,18 +301,10 @@ export class File {
return this.fileRelationships; return this.fileRelationships;
} }
public get Header(): HeaderWrapper {
return this.headers[0].header;
}
public get Headers(): HeaderWrapper[] { public get Headers(): HeaderWrapper[] {
return this.headers.map((item) => item.header); return this.headers.map((item) => item.header);
} }
public get Footer(): FooterWrapper {
return this.footers[0].footer;
}
public get Footers(): FooterWrapper[] { public get Footers(): FooterWrapper[] {
return this.footers.map((item) => item.footer); return this.footers.map((item) => item.footer);
} }

View File

@ -39,17 +39,6 @@ describe("FooterWrapper", () => {
}); });
}); });
describe("#createImage", () => {
it("should call the underlying footer's createImage", () => {
const file = new FooterWrapper(new Media(), 1);
const spy = sinon.spy(Media, "addImage");
file.createImage("");
expect(spy.called).to.equal(true);
spy.restore();
});
});
describe("#addChildElement", () => { describe("#addChildElement", () => {
it("should call the underlying footer's addChildElement", () => { it("should call the underlying footer's addChildElement", () => {
const file = new FooterWrapper(new Media(), 1); const file = new FooterWrapper(new Media(), 1);

View File

@ -1,7 +1,6 @@
import { XmlComponent } from "file/xml-components"; import { XmlComponent } from "file/xml-components";
import { FooterReferenceType } from "./document"; import { FooterReferenceType } from "./document";
import { IDrawingOptions } from "./drawing";
import { Footer } from "./footer/footer"; import { Footer } from "./footer/footer";
import { Image, Media } from "./media"; import { Image, Media } from "./media";
import { Paragraph } from "./paragraph"; import { Paragraph } from "./paragraph";
@ -35,19 +34,6 @@ export class FooterWrapper {
this.footer.addChildElement(childElement); this.footer.addChildElement(childElement);
} }
public createImage(
buffer: Buffer | string | Uint8Array | ArrayBuffer,
width?: number,
height?: number,
drawingOptions?: IDrawingOptions,
): Paragraph {
const image = Media.addImage(this, buffer, width, height, drawingOptions);
const paragraph = new Paragraph(image);
this.add(paragraph);
return paragraph;
}
public get Footer(): Footer { public get Footer(): Footer {
return this.footer; return this.footer;
} }

View File

@ -41,17 +41,6 @@ describe("HeaderWrapper", () => {
}); });
}); });
describe("#createImage", () => {
it("should call the underlying header's createImage", () => {
const file = new HeaderWrapper(new Media(), 1);
const spy = sinon.spy(Media, "addImage");
file.createImage("");
expect(spy.called).to.equal(true);
spy.restore();
});
});
describe("#addChildElement", () => { describe("#addChildElement", () => {
it("should call the underlying header's addChildElement", () => { it("should call the underlying header's addChildElement", () => {
const file = new HeaderWrapper(new Media(), 1); const file = new HeaderWrapper(new Media(), 1);

View File

@ -1,7 +1,6 @@
import { XmlComponent } from "file/xml-components"; import { XmlComponent } from "file/xml-components";
import { HeaderReferenceType } from "./document"; import { HeaderReferenceType } from "./document";
import { IDrawingOptions } from "./drawing";
import { Header } from "./header/header"; import { Header } from "./header/header";
import { Image, Media } from "./media"; import { Image, Media } from "./media";
import { Paragraph } from "./paragraph"; import { Paragraph } from "./paragraph";
@ -37,19 +36,6 @@ export class HeaderWrapper {
this.header.addChildElement(childElement); this.header.addChildElement(childElement);
} }
public createImage(
buffer: Buffer | string | Uint8Array | ArrayBuffer,
width?: number,
height?: number,
drawingOptions?: IDrawingOptions,
): Paragraph {
const image = Media.addImage(this, buffer, width, height, drawingOptions);
const paragraph = new Paragraph(image);
this.add(paragraph);
return paragraph;
}
public get Header(): Header { public get Header(): Header {
return this.header; return this.header;
} }

14
src/file/header.ts Normal file
View File

@ -0,0 +1,14 @@
import { Paragraph } from "./paragraph";
import { Table } from "./table";
export interface IHeaderOptions {
readonly children: Array<Paragraph | Table>;
}
export class Header {
constructor(public readonly options: IHeaderOptions = { children: [] }) {}
}
export class Footer {
constructor(public readonly options: IHeaderOptions = { children: [] }) {}
}

View File

@ -11,3 +11,4 @@ export * from "./table-of-contents";
export * from "./xml-components"; export * from "./xml-components";
export * from "./header-wrapper"; export * from "./header-wrapper";
export * from "./footer-wrapper"; export * from "./footer-wrapper";
export * from "./header";

View File

@ -10,8 +10,4 @@ export class Image {
public get Run(): PictureRun { public get Run(): PictureRun {
return this.paragraph.Run; return this.paragraph.Run;
} }
public scale(factorX: number, factorY?: number): void {
this.paragraph.Run.scale(factorX, factorY);
}
} }

View File

@ -2,6 +2,7 @@ import { Attributes, XmlAttributeComponent, XmlComponent } from "file/xml-compon
import { import {
Alignment, Alignment,
AlignmentType, AlignmentType,
IIndentAttributesProperties,
Indent, Indent,
ISpacingProperties, ISpacingProperties,
KeepLines, KeepLines,
@ -235,7 +236,7 @@ export class LevelBase extends XmlComponent {
return this; return this;
} }
public indent(attrs: object): Level { public indent(attrs: IIndentAttributesProperties): Level {
this.addParagraphProperty(new Indent(attrs)); this.addParagraphProperty(new Indent(attrs));
return this; return this;
} }

View File

@ -1,12 +1,8 @@
// tslint:disable:object-literal-key-quotes // tslint:disable:object-literal-key-quotes
import { assert, expect } from "chai"; import { assert } from "chai";
import { Formatter } from "export/formatter";
import { ImageParagraph } from "./image"; import { ImageParagraph } from "./image";
import { EMPTY_OBJECT } from "file/xml-components";
describe("Image", () => { describe("Image", () => {
let image: ImageParagraph; let image: ImageParagraph;
@ -40,190 +36,4 @@ describe("Image", () => {
assert.isTrue(true); assert.isTrue(true);
}); });
}); });
describe("#scale()", () => {
it("should set the scale of the object properly", () => {
image.scale(2);
const tree = new Formatter().format(image);
expect(tree).to.deep.equal({
"w:p": [
{
"w:r": [
{
"w:drawing": [
{
"wp:inline": [
{
_attr: {
distB: 0,
distL: 0,
distR: 0,
distT: 0,
},
},
{
"wp:extent": {
_attr: {
cx: 20,
cy: 20,
},
},
},
{
"wp:effectExtent": {
_attr: {
b: 0,
l: 0,
r: 0,
t: 0,
},
},
},
{
"wp:docPr": {
_attr: {
descr: "",
id: 0,
name: "",
},
},
},
{
"wp:cNvGraphicFramePr": [
{
"a:graphicFrameLocks": {
_attr: {
noChangeAspect: 1,
"xmlns:a": "http://schemas.openxmlformats.org/drawingml/2006/main",
},
},
},
],
},
{
"a:graphic": [
{
_attr: {
"xmlns:a": "http://schemas.openxmlformats.org/drawingml/2006/main",
},
},
{
"a:graphicData": [
{
_attr: {
uri: "http://schemas.openxmlformats.org/drawingml/2006/picture",
},
},
{
"pic:pic": [
{
_attr: {
"xmlns:pic":
"http://schemas.openxmlformats.org/drawingml/2006/picture",
},
},
{
"pic:nvPicPr": [
{
"pic:cNvPr": {
_attr: {
desc: "",
id: 0,
name: "",
},
},
},
{
"pic:cNvPicPr": [
{
"a:picLocks": {
_attr: {
noChangeArrowheads: 1,
noChangeAspect: 1,
},
},
},
],
},
],
},
{
"pic:blipFill": [
{
"a:blip": {
_attr: {
cstate: "none",
"r:embed": "rId{test.png}",
},
},
},
{
"a:srcRect": EMPTY_OBJECT,
},
{
"a:stretch": [
{
"a:fillRect": EMPTY_OBJECT,
},
],
},
],
},
{
"pic:spPr": [
{
_attr: {
bwMode: "auto",
},
},
{
"a:xfrm": [
{
"a:ext": {
_attr: {
cx: 10,
cy: 10,
},
},
},
{
"a:off": {
_attr: {
x: 0,
y: 0,
},
},
},
],
},
{
"a:prstGeom": [
{
_attr: {
prst: "rect",
},
},
{
"a:avLst": EMPTY_OBJECT,
},
],
},
],
},
],
},
],
},
],
},
],
},
],
},
],
},
],
});
});
});
}); });

View File

@ -12,10 +12,6 @@ export class ImageParagraph extends Paragraph {
this.root.push(this.pictureRun); this.root.push(this.pictureRun);
} }
public scale(factorX: number, factorY?: number): void {
this.pictureRun.scale(factorX, factorY);
}
public get Run(): PictureRun { public get Run(): PictureRun {
return this.pictureRun; return this.pictureRun;
} }

View File

@ -4,8 +4,6 @@ import { IMediaData } from "../../media/data";
import { Run } from "../run"; import { Run } from "../run";
export class PictureRun extends Run { export class PictureRun extends Run {
private readonly drawing: Drawing;
constructor(imageData: IMediaData, drawingOptions?: IDrawingOptions) { constructor(imageData: IMediaData, drawingOptions?: IDrawingOptions) {
super({}); super({});
@ -13,12 +11,8 @@ export class PictureRun extends Run {
throw new Error("imageData cannot be undefined"); throw new Error("imageData cannot be undefined");
} }
this.drawing = new Drawing(imageData, drawingOptions); const drawing = new Drawing(imageData, drawingOptions);
this.root.push(this.drawing); this.root.push(drawing);
}
public scale(factorX: number = 1, factorY: number = factorX): void {
this.drawing.scale(factorX, factorY);
} }
} }