diff --git a/demo/browser-demo.html b/demo/browser-demo.html index 535b55beea..a199c1b4e8 100644 --- a/demo/browser-demo.html +++ b/demo/browser-demo.html @@ -1,39 +1,45 @@ + + + + - - - - + +

DOCX browser Word document generation

- + -

DOCX browser Word document generation

+ - - + const packer = new Packer(); + packer.toBlob(doc).then((blob) => { + console.log(blob); + saveAs(blob, "example.docx"); + console.log("Document created successfully"); + }); + } + + diff --git a/demo/demo1.ts b/demo/demo1.ts index c8ed2e4781..2787c869d7 100644 --- a/demo/demo1.ts +++ b/demo/demo1.ts @@ -5,19 +5,24 @@ import { Document, Packer, Paragraph, TextRun } from "../build"; const doc = new Document(); -const paragraph = new Paragraph("Hello World"); -const institutionText = new TextRun({ - text: "Foo Bar", - bold: true, +doc.addSection({ + properties: {}, + 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(), + ], + }), + ], }); -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(); diff --git a/demo/demo10.ts b/demo/demo10.ts index 62077cf4c4..f7a89a0512 100644 --- a/demo/demo10.ts +++ b/demo/demo10.ts @@ -127,97 +127,86 @@ const achievements = [ ]; class DocumentCreator { - public create(data: object[]): Document { - // tslint:disable-next-line:no-any - 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[]; + // tslint:disable-next-line: typedef + public create([experiences, educations, skills, achivements]): 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.add(this.createHeading("Education")); + document.addSection({ + 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) { - document.add( - this.createInstitutionHeader(education.schoolName, `${education.startDate.year} - ${education.endDate.year}`), - ); - document.add(this.createRoleText(`${education.fieldOfStudy} - ${education.degree}`)); + const bulletPoints = this.splitParagraphIntoBullets(education.notes); + bulletPoints.forEach((bulletPoint) => { + arr.push(this.createBullet(bulletPoint)); + }); - const bulletPoints = this.splitParagraphIntoBullets(education.notes); - bulletPoints.forEach((bulletPoint) => { - document.add(this.createBullet(bulletPoint)); - }); - } + return arr; + }) + .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) { - document.add( - this.createInstitutionHeader( - position.company.name, - this.createPositionDateText(position.startDate, position.endDate, position.isCurrent), + const bulletPoints = this.splitParagraphIntoBullets(position.summary); + + bulletPoints.forEach((bulletPoint) => { + arr.push(this.createBullet(bulletPoint)); + }); + + 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", ), - ); - document.add(this.createRoleText(position.title)); + new Paragraph("More references upon request"), + 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; } public createContactInfo(phoneNumber: string, profileUrl: string, email: string): Paragraph { - const paragraph = new Paragraph({ + return new Paragraph({ 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 { @@ -236,36 +225,32 @@ class DocumentCreator { } public createInstitutionHeader(institutionName: string, dateText: string): Paragraph { - const paragraph = new Paragraph({ + return new Paragraph({ tabStop: { 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 { - const paragraph = new Paragraph({}); - const role = new TextRun({ - text: roleText, - italics: true, + return new Paragraph({ + children: [ + new TextRun({ + text: roleText, + italics: true, + }), + ], }); - - paragraph.addRun(role); - - return paragraph; } public createBullet(text: string): Paragraph { @@ -279,36 +264,28 @@ class DocumentCreator { // tslint:disable-next-line:no-any public createSkillList(skills: any[]): Paragraph { - const paragraph = new Paragraph({}); - const skillConcat = skills.map((skill) => skill.name).join(", ") + "."; - - paragraph.addRun(new TextRun(skillConcat)); - - return paragraph; + return new Paragraph({ + children: [new TextRun(skills.map((skill) => skill.name).join(", ") + ".")], + }); } // tslint:disable-next-line:no-any public createAchivementsList(achivements: any[]): Paragraph[] { - const arr: Paragraph[] = []; - - for (const achievement of achivements) { - const paragraph = new Paragraph({ - text: achievement.name, - bullet: { - level: 0, - }, - }); - arr.push(paragraph); - } - - return arr; + return achivements.map( + (achievement) => + new Paragraph({ + text: achievement.name, + bullet: { + level: 0, + }, + }), + ); } public createInterests(interests: string): Paragraph { - const paragraph = new Paragraph({}); - - paragraph.addRun(new TextRun(interests)); - return paragraph; + return new Paragraph({ + children: [new TextRun(interests)], + }); } public splitParagraphIntoBullets(text: string): string[] { diff --git a/demo/demo11.ts b/demo/demo11.ts index 3861447df9..e286ed7556 100644 --- a/demo/demo11.ts +++ b/demo/demo11.ts @@ -1,14 +1,9 @@ // Setting styles with JavaScript configuration // Import from 'docx' rather than '../build' if you install from npm 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, { - top: 700, - right: 700, - bottom: 700, - left: 700, -}); +const doc = new Document(); doc.Styles.createParagraphStyle("Heading1", "Heading 1") .basedOn("Normal") @@ -83,76 +78,7 @@ doc.Styles.createParagraphStyle("ListParagraph", "List Paragraph") .quickFormat() .basedOn("Normal"); -doc.createImage(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 image = Media.addImage(doc, fs.readFileSync("./demo/images/pizza.gif")); const table = new Table({ rows: 4, @@ -163,27 +89,78 @@ table .getCell(0) .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 = [ - { - image: "./demo/images/pizza.gif", - comment: "Test", +doc.addSection({ + properties: { + top: 700, + right: 700, + bottom: 700, + left: 700, }, - { - image: "./demo/images/pizza.gif", - comment: "Test 2", + footers: { + default: new Footer({ + children: [ + new Paragraph({ + text: "1", + style: "normalPara", + alignment: AlignmentType.RIGHT, + }), + ], + }), }, -]; - -arrboth.forEach((item) => { - doc.createImage(fs.readFileSync(item.image)); - doc.add( + children: [ + new Paragraph(image), 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", }), - ); + new Paragraph(image2), + new Paragraph({ + text: "Test 2", + style: "normalPara2", + }), + ], }); const packer = new Packer(); diff --git a/demo/demo12.ts b/demo/demo12.ts index f27aee4968..2de556a262 100644 --- a/demo/demo12.ts +++ b/demo/demo12.ts @@ -1,22 +1,18 @@ // Scaling images // Import from 'docx' rather than '../build' if you install from npm import * as fs from "fs"; -import { Document, Packer, Paragraph } from "../build"; +import { Document, Media, Packer, Paragraph } from "../build"; const doc = new Document(); -const paragraph = new Paragraph("Hello World"); -doc.add(paragraph); +const image = Media.addImage(doc, fs.readFileSync("./demo/images/pizza.gif"), 50, 50); +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")); -const image2 = doc.createImage(fs.readFileSync("./demo/images/pizza.gif")); -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); +doc.addSection({ + children: [new Paragraph("Hello World"), new Paragraph(image), new Paragraph(image2), new Paragraph(image3), new Paragraph(image4)], +}); const packer = new Packer(); diff --git a/demo/demo13.ts b/demo/demo13.ts index 53287c2e1a..9d84777f68 100644 --- a/demo/demo13.ts +++ b/demo/demo13.ts @@ -9,25 +9,23 @@ const doc = new Document({ externalStyles: styles, }); -doc.add(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"', - style: "MyFancyStyle", +doc.addSection({ + children: [ + new Paragraph({ + text: "Cool Heading Text", + heading: HeadingLevel.HEADING_1, + }), + new Paragraph({ + 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(); diff --git a/demo/demo14.ts b/demo/demo14.ts index 310f854301..f8e024547c 100644 --- a/demo/demo14.ts +++ b/demo/demo14.ts @@ -1,36 +1,37 @@ // Page numbers // Import from 'docx' rather than '../build' if you install from npm 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(); -doc.add( - new Paragraph({ - text: "First Page", - }).pageBreak(), -); -doc.add(new Paragraph("Second Page")); - -const pageNumber = new TextRun("Page ").pageNumber(); - -const pageoneheader = new Paragraph({ - text: "First Page Header ", - alignment: AlignmentType.RIGHT, +doc.addSection({ + headers: { + default: new Header({ + children: [ + new Paragraph({ + alignment: AlignmentType.RIGHT, + children: [new TextRun("My Title "), new TextRun("Page ").pageNumber()], + }), + ], + }), + first: new Header({ + 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(); packer.toBuffer(doc).then((buffer) => { diff --git a/demo/demo15.ts b/demo/demo15.ts index f25639bf2f..73ab48680e 100644 --- a/demo/demo15.ts +++ b/demo/demo15.ts @@ -5,15 +5,16 @@ import { Document, Packer, Paragraph } from "../build"; const doc = new Document(); -const paragraph = new Paragraph("Hello World"); -const paragraph2 = new Paragraph({ - text: "Hello World on another page", - pageBreakBefore: true, +doc.addSection({ + children: [ + new Paragraph("Hello World"), + new Paragraph({ + text: "Hello World on another page", + pageBreakBefore: true, + }), + ], }); -doc.add(paragraph); -doc.add(paragraph2); - const packer = new Packer(); packer.toBuffer(doc).then((buffer) => { diff --git a/demo/demo16.ts b/demo/demo16.ts index ee77ce7ebb..ede5e4058e 100644 --- a/demo/demo16.ts +++ b/demo/demo16.ts @@ -1,27 +1,26 @@ // Multiple sections and headers // Import from 'docx' rather than '../build' if you install from npm 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 paragraph = 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({ + children: [new Paragraph("Hello World").pageBreak()], +}); 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: { - headers: { - default: header, - }, - footers: { - default: footer, - }, pageNumberStart: 1, pageNumberFormatType: PageNumberFormat.DECIMAL, }, @@ -29,39 +28,53 @@ 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: { - headers: { - default: header, - }, - footers: { - default: footer, - }, pageNumberStart: 1, pageNumberFormatType: PageNumberFormat.DECIMAL, - orientation: PageOrientation.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({ - properties: { - headers: { - default: header2, - }, + headers: { + default: new Header({ + children: [ + new Paragraph({ + children: [new TextRun("Page number: ").pageNumber()], + }), + ], + }), + }, + size: { orientation: PageOrientation.PORTRAIT, }, children: [new Paragraph("Page number in the header must be 2, because it continues from the previous section.")], }); doc.addSection({ + headers: { + default: new Header({ + children: [ + new Paragraph({ + children: [new TextRun("Page number: ").pageNumber()], + }), + ], + }), + }, properties: { - headers: { - default: header2, - }, pageNumberFormatType: PageNumberFormat.UPPER_ROMAN, orientation: PageOrientation.PORTRAIT, }, @@ -73,13 +86,21 @@ doc.addSection({ }); doc.addSection({ + headers: { + default: new Header({ + children: [ + new Paragraph({ + children: [new TextRun("Page number: ").pageNumber()], + }), + ], + }), + }, + size: { + orientation: PageOrientation.PORTRAIT, + }, properties: { - headers: { - default: header2, - }, pageNumberFormatType: PageNumberFormat.DECIMAL, pageNumberStart: 25, - orientation: PageOrientation.PORTRAIT, }, 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."), diff --git a/demo/demo17.ts b/demo/demo17.ts index 1d928b60b5..e316ea4edb 100644 --- a/demo/demo17.ts +++ b/demo/demo17.ts @@ -5,11 +5,9 @@ import { Document, Packer, Paragraph } from "../build"; const doc = new Document(); -const paragraph = new Paragraph("Hello World").referenceFootnote(1); -const paragraph2 = new Paragraph("Hello World").referenceFootnote(2); - -doc.add(paragraph); -doc.add(paragraph2); +doc.addSection({ + children: [new Paragraph("Hello World").referenceFootnote(1), new Paragraph("Hello World").referenceFootnote(2)], +}); doc.createFootnote(new Paragraph("Test")); doc.createFootnote(new Paragraph("My amazing reference")); diff --git a/demo/demo18.ts b/demo/demo18.ts index 4a61488c1f..7eefdc4328 100644 --- a/demo/demo18.ts +++ b/demo/demo18.ts @@ -1,14 +1,21 @@ // Insert image from a buffer // Import from 'docx' rather than '../build' if you install from npm import * as fs from "fs"; -import { Document, Packer } from "../build"; +import { Document, Media, Packer, Paragraph } from "../build"; const doc = new Document(); const imageBase64Data = `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`; -// doc.createImage(Buffer.from(imageBase64Data, 'base64')); -doc.createImage(Buffer.from(imageBase64Data, "base64"), 100, 100); +const image = Media.addImage(doc, Buffer.from(imageBase64Data, "base64"), 100, 100); + +doc.addSection({ + children: [ + new Paragraph({ + children: [image], + }), + ], +}); const packer = new Packer(); diff --git a/demo/demo19.ts b/demo/demo19.ts index f8930db836..84991cc929 100644 --- a/demo/demo19.ts +++ b/demo/demo19.ts @@ -5,19 +5,23 @@ import { Document, Packer, Paragraph, TextRun } from "../build"; const doc = new Document(); -const paragraph = new Paragraph("Hello World"); -const institutionText = new TextRun({ - text: "Foo", - bold: true, +doc.addSection({ + children: [ + new Paragraph({ + 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(); diff --git a/demo/demo2.ts b/demo/demo2.ts index 5764f40f91..3397f41ee8 100644 --- a/demo/demo2.ts +++ b/demo/demo2.ts @@ -46,96 +46,76 @@ doc.Styles.createParagraphStyle("ListParagraph", "List Paragraph") const numberedAbstract = doc.Numbering.createAbstractNumbering(); 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 letterNumbering5 = doc.Numbering.createConcreteNumbering(numberedAbstract); letterNumbering5.overrideLevel(0, 5); -doc.add( - new Paragraph({ - text: "Option1", - numbering: { - num: letterNumbering, - level: 0, - }, - }), -); -doc.add( - new Paragraph({ - text: "Option5 -- override 2 to 5", - numbering: { - 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", +doc.addSection({ + children: [ + new Paragraph({ + text: "Test heading1, bold and italicized", + heading: HeadingLevel.HEADING_1, + }), + new Paragraph("Some simple content"), + new Paragraph({ + text: "Test heading2 with double red underline", + heading: HeadingLevel.HEADING_2, + }), + new Paragraph({ + text: "Option1", + numbering: { + num: letterNumbering, + level: 0, }, }), - ), -); - -doc.add( - new Paragraph({ - text: "An aside, in light gray italics and indented", - style: "aside", - }), -); -doc.add( - new Paragraph({ - text: "This is normal, but well-spaced text", - style: "wellSpaced", - }), -); -const para = new Paragraph({}); -doc.add(para); -// Showing the different ways to create a TextRun -para.addRun( - new TextRun({ - text: "This is a bold run,", - bold: true, - }), -); -para.addRun(new TextRun(" switching to normal ")); -para.addRun( - new TextRun({ - text: "and then underlined ", - underline: {}, - }), -); -para.addRun( - new TextRun({ - text: "and back to normal.", - }), -); + new Paragraph({ + text: "Option5 -- override 2 to 5", + numbering: { + num: letterNumbering, + level: 0, + }, + }), + new Paragraph({ + text: "Option3", + numbering: { + num: letterNumbering, + level: 0, + }, + }), + new Paragraph({}).addRun( + new TextRun({ + text: "Some monospaced content", + font: { + name: "Monospace", + }, + }), + ), + new Paragraph({ + text: "An aside, in light gray italics and indented", + style: "aside", + }), + new Paragraph({ + text: "This is normal, but well-spaced text", + style: "wellSpaced", + }), + new Paragraph({ + children: [ + new TextRun({ + text: "This is a bold run,", + bold: true, + }), + new TextRun(" switching to normal "), + new TextRun({ + text: "and then underlined ", + underline: {}, + }), + new TextRun({ + text: "and back to normal.", + }), + ], + }), + ], +}); const packer = new Packer(); diff --git a/demo/demo20.ts b/demo/demo20.ts index b861a10cfa..ee2b7918e2 100644 --- a/demo/demo20.ts +++ b/demo/demo20.ts @@ -10,7 +10,7 @@ const table = new Table({ columns: 4, }); -doc.add(table); +doc.addSection({ children: [table] }); table .getCell(2, 2) .add(new Paragraph("Hello")) diff --git a/demo/demo21.ts b/demo/demo21.ts index 5ce3bc2930..1193ee01c0 100644 --- a/demo/demo21.ts +++ b/demo/demo21.ts @@ -3,7 +3,7 @@ import * as fs from "fs"; 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."; const doc = new Document({ @@ -16,21 +16,19 @@ const anchorId = "anchorID"; // First create the bookmark 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!`); -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(); diff --git a/demo/demo22.ts b/demo/demo22.ts index c92406071e..3a70c01d21 100644 --- a/demo/demo22.ts +++ b/demo/demo22.ts @@ -5,37 +5,39 @@ import { Document, Packer, Paragraph, TextRun } from "../build"; const doc = new Document(); -const paragraph1 = new Paragraph({ - bidirectional: true, +doc.addSection({ + 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(); diff --git a/demo/demo23.ts b/demo/demo23.ts index 8cbdac292c..5333d91e9b 100644 --- a/demo/demo23.ts +++ b/demo/demo23.ts @@ -1,13 +1,10 @@ // 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 * as fs from "fs"; -import { Document, Media, Packer, Paragraph } from "../build"; +import { Document, Media, Packer, Paragraph, TextRun } from "../build"; 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 image2 = Media.addImage(doc, fs.readFileSync("./demo/images/dog.png")); 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 = `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`; 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 -paragraph.addImage(image5); - -doc.add(image); -doc.add(image2); -doc.add(image3); -doc.add(image4); -doc.add(image5); -doc.add(image6); +doc.addSection({ + children: [ + new Paragraph({ + children: [new TextRun("Hello World"), image5], + }), + new Paragraph(image), + new Paragraph(image2), + new Paragraph(image3), + new Paragraph(image4), + new Paragraph(image6), + ], +}); const packer = new Packer(); diff --git a/demo/demo24.ts b/demo/demo24.ts index fc940eed1d..2ea6f664c3 100644 --- a/demo/demo24.ts +++ b/demo/demo24.ts @@ -10,7 +10,9 @@ const table = new Table({ columns: 4, }); -doc.add(table); +doc.addSection({ + children: [table], +}); table.getCell(2, 2).add(new Paragraph("Hello")); diff --git a/demo/demo26.ts b/demo/demo26.ts index ef914e9465..421d8477e5 100644 --- a/demo/demo26.ts +++ b/demo/demo26.ts @@ -5,30 +5,29 @@ import { Document, Packer, Paragraph } from "../build"; const doc = new Document(); -const paragraph = new Paragraph("No border!"); - -doc.add(paragraph); - -const borderParagraph = new Paragraph({ - text: "I have borders on my top and bottom sides!", - border: { - top: { - color: "auto", - space: 1, - value: "single", - size: 6, - }, - bottom: { - color: "auto", - space: 1, - value: "single", - size: 6, - }, - }, +doc.addSection({ + children: [ + new Paragraph("No border!"), + new Paragraph({ + text: "I have borders on my top and bottom sides!", + border: { + top: { + color: "auto", + space: 1, + value: "single", + size: 6, + }, + bottom: { + color: "auto", + space: 1, + value: "single", + size: 6, + }, + }, + }), + ], }); -doc.add(borderParagraph); - const packer = new Packer(); packer.toBuffer(doc).then((buffer) => { diff --git a/demo/demo27.ts b/demo/demo27.ts index 28d2ba5d09..a31ce0b44b 100644 --- a/demo/demo27.ts +++ b/demo/demo27.ts @@ -4,12 +4,10 @@ import * as fs from "fs"; import { Document, HeadingLevel, Packer, Paragraph } from "../build"; const doc = new Document(); -const myStyles = doc.Styles; // 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 -myStyles - .createParagraphStyle("myWonkyStyle", "My Wonky Style") +doc.Styles.createParagraphStyle("myWonkyStyle", "My Wonky Style") .basedOn("Normal") .next("Normal") .color("990000") @@ -17,8 +15,7 @@ myStyles .indent({ left: 720 }) // 720 TWIP === 720 / 20 pt === .5 in .spacing({ line: 276 }); // 276 / 240 = 1.15x line spacing -myStyles - .createParagraphStyle("Heading2", "Heading 2") +doc.Styles.createParagraphStyle("Heading2", "Heading 2") .basedOn("Normal") .next("Normal") .quickFormat() @@ -27,18 +24,18 @@ myStyles .underline("double", "FF0000") .spacing({ before: 240, after: 120 }); // TWIP for both -doc.add( - new Paragraph({ - text: "Hello", - style: "myWonkyStyle", - }), -); -doc.add( - new Paragraph({ - text: "World", - heading: HeadingLevel.HEADING_2, - }), -); // Uses the Heading2 style +doc.addSection({ + children: [ + new Paragraph({ + text: "Hello", + style: "myWonkyStyle", + }), + new Paragraph({ + text: "World", + heading: HeadingLevel.HEADING_2, + }), + ], +}); const packer = new Packer(); diff --git a/demo/demo28.ts b/demo/demo28.ts index 0bef4470bc..414c2ad97d 100644 --- a/demo/demo28.ts +++ b/demo/demo28.ts @@ -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, // making the entries be hyperlinks for the paragraph -const toc = new TableOfContents("Summary", { - hyperlink: true, - headingStyleRange: "1-5", - stylesWithLevels: [new StyleLevel("MySpectacularStyle", 1)], + +doc.addSection({ + children: [ + 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(); packer.toBuffer(doc).then((buffer) => { diff --git a/demo/demo29.ts b/demo/demo29.ts index f8982e425d..31dcd6d28f 100644 --- a/demo/demo29.ts +++ b/demo/demo29.ts @@ -1,66 +1,65 @@ // Numbered lists // Import from 'docx' rather than '../build' if you install from npm 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 numbering = new Numbering(); 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 item1 = new Paragraph({ - text: "line with contextual spacing", - numbering: { - num: concrete, - level: 0, - }, - contextualSpacing: true, - spacing: { - before: 200, - }, +doc.addSection({ + children: [ + new Paragraph({ + text: "line with contextual spacing", + numbering: { + num: concrete, + level: 0, + }, + 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(); diff --git a/demo/demo3.ts b/demo/demo3.ts index e901049ec9..79545c75ec 100644 --- a/demo/demo3.ts +++ b/demo/demo3.ts @@ -1,82 +1,75 @@ // Numbering and bullet points example // Import from 'docx' rather than '../build' if you install from npm 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 numbering = new Numbering(); const abstractNum = numbering.createAbstractNumbering(); -abstractNum.createLevel(0, "upperRoman", "%1", "start").addProperty(new Indent({ left: 720, hanging: 260 })); -abstractNum.createLevel(1, "decimal", "%2.", "start").addProperty(new Indent({ left: 1440, hanging: 980 })); -abstractNum.createLevel(2, "lowerLetter", "%3)", "start").addProperty(new Indent({ left: 14402160, hanging: 1700 })); +abstractNum.createLevel(0, "upperRoman", "%1", "start").indent({ left: 720, hanging: 260 }); +abstractNum.createLevel(1, "decimal", "%2.", "start").indent({ left: 1440, hanging: 980 }); +abstractNum.createLevel(2, "lowerLetter", "%3)", "start").indent({ left: 14402160, hanging: 1700 }); const concrete = numbering.createConcreteNumbering(abstractNum); -const topLevelP = new Paragraph({ - text: "Hey you", - numbering: { - num: concrete, - level: 0, - }, +doc.addSection({ + children: [ + new Paragraph({ + text: "Hey you", + 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(); diff --git a/demo/demo30.ts b/demo/demo30.ts index 92b929bd30..e9ebfd5c2b 100644 --- a/demo/demo30.ts +++ b/demo/demo30.ts @@ -12,16 +12,16 @@ fs.readFile(filePath, (err, data) => { } importDotx.extract(data).then((templateDocument) => { - // This any needs fixing - const sectionProps = { - titlePage: templateDocument.titlePageIsDefined, - } as any; - - const doc = new Document(undefined, sectionProps, { + const doc = new Document(undefined, { 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(); packer.toBuffer(doc).then((buffer) => { diff --git a/demo/demo31.ts b/demo/demo31.ts index 32c8cd755a..d3e4cd3a8a 100644 --- a/demo/demo31.ts +++ b/demo/demo31.ts @@ -1,7 +1,7 @@ // 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 * 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(); @@ -10,8 +10,6 @@ const table = new Table({ columns: 2, }); -doc.add(table); - table .getCell(1, 1) .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(); packer.toBuffer(doc).then((buffer) => { diff --git a/demo/demo32.ts b/demo/demo32.ts index c2fd76ebf6..8526dc4916 100644 --- a/demo/demo32.ts +++ b/demo/demo32.ts @@ -5,24 +5,15 @@ import { Document, HeadingLevel, Packer, Paragraph, ShadingType, Table, WidthTyp const doc = new Document(); -let table = new Table({ +const table = new Table({ rows: 2, columns: 2, }); -doc.add(table); - table.getCell(0, 0).add(new Paragraph("Hello")); table.getRow(0).mergeCells(0, 1); -doc.add( - new Paragraph({ - text: "Another table", - heading: HeadingLevel.HEADING_2, - }), -); - -table = new Table({ +const table2 = new Table({ rows: 2, columns: 3, width: 100, @@ -30,9 +21,7 @@ table = new Table({ columnWidths: [1000, 1000, 1000], }); -doc.add(table); - -table +table2 .getCell(0, 0) .add(new Paragraph("World")) .setMargins({ @@ -43,14 +32,7 @@ table }); table.getRow(0).mergeCells(0, 2); -doc.add( - new Paragraph({ - text: "Another table", - heading: HeadingLevel.HEADING_2, - }), -); - -table = new Table({ +const table3 = new Table({ rows: 2, columns: 4, 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")); -table.getCell(0, 1).add(new Paragraph("v")); - -table +table3 .getCell(1, 0) .add(new Paragraph("Bar1")) .setShading({ @@ -76,7 +56,7 @@ table val: ShadingType.REVERSE_DIAGONAL_STRIPE, color: "auto", }); -table +table3 .getCell(1, 1) .add(new Paragraph("Bar2")) .setShading({ @@ -84,7 +64,7 @@ table val: ShadingType.PERCENT_95, color: "auto", }); -table +table3 .getCell(1, 2) .add(new Paragraph("Bar3")) .setShading({ @@ -92,7 +72,7 @@ table val: ShadingType.PERCENT_10, color: "e2df0b", }); -table +table3 .getCell(1, 3) .add(new Paragraph("Bar4")) .setShading({ @@ -101,18 +81,32 @@ table color: "auto", }); -table.getRow(0).mergeCells(0, 3); +table3.getRow(0).mergeCells(0, 3); -doc.add(new Paragraph("hi")); - -table = new Table({ +const table4 = new Table({ rows: 2, columns: 2, width: 100, 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(); diff --git a/demo/demo33.ts b/demo/demo33.ts index b4831d849b..bf0913d6f1 100644 --- a/demo/demo33.ts +++ b/demo/demo33.ts @@ -5,15 +5,26 @@ import { Document, Packer, Paragraph, TextRun } from "../build"; const doc = new Document(); -const paragraph = new Paragraph("Hello World 1->").addSequentialIdentifier("Caption").addRun(new TextRun(" text after sequencial caption 2->")).addSequentialIdentifier("Caption"); -const paragraph2 = new Paragraph("Hello World 1->").addSequentialIdentifier("Label").addRun(new TextRun(" text after sequencial caption 2->")).addSequentialIdentifier("Label"); -const paragraph3 = new Paragraph("Hello World 1->").addSequentialIdentifier("Another").addRun(new TextRun(" text after sequencial caption 3->")).addSequentialIdentifier("Label"); -const paragraph4 = new Paragraph("Hello World 2->").addSequentialIdentifier("Another").addRun(new TextRun(" text after sequencial caption 4->")).addSequentialIdentifier("Label"); - -doc.add(paragraph); -doc.add(paragraph2); -doc.add(paragraph3); -doc.add(paragraph4); +doc.addSection({ + children: [ + new Paragraph("Hello World 1->") + .addSequentialIdentifier("Caption") + .addRun(new TextRun(" text after sequencial caption 2->")) + .addSequentialIdentifier("Caption"), + new Paragraph("Hello World 1->") + .addSequentialIdentifier("Label") + .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(); diff --git a/demo/demo34.ts b/demo/demo34.ts index 007be8efdb..c24246b709 100644 --- a/demo/demo34.ts +++ b/demo/demo34.ts @@ -29,11 +29,13 @@ const table = new Table({ layout: TableLayoutType.FIXED, }); -doc.add(table); - table.getCell(0, 0).add(new Paragraph("Hello")); table.getRow(0).mergeCells(0, 1); +doc.addSection({ + children: [table], +}); + const packer = new Packer(); packer.toBuffer(doc).then((buffer) => { diff --git a/demo/demo35.ts b/demo/demo35.ts index a2927a6957..41117a6a51 100644 --- a/demo/demo35.ts +++ b/demo/demo35.ts @@ -8,7 +8,9 @@ const paragraph = new Paragraph({}); const link = doc.createHyperlink("http://www.example.com", "Hyperlink"); paragraph.addHyperLink(link); -doc.add(paragraph); +doc.addSection({ + children: [paragraph], +}); const packer = new Packer(); diff --git a/demo/demo36.ts b/demo/demo36.ts index 1faf0c3e94..689a07a997 100644 --- a/demo/demo36.ts +++ b/demo/demo36.ts @@ -1,7 +1,7 @@ // Add image to table cell // Import from 'docx' rather than '../build' if you install from npm 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 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)); -doc.add(table); - -// doc.Header.createImage(fs.readFileSync("./demo/images/pizza.gif")); -doc.Header.add(table); -// doc.Footer.createImage(fs.readFileSync("./demo/images/pizza.gif")); +// Adding same table in the body and in the header +doc.addSection({ + headers: { + default: new Header({ + children: [table], + }), + }, + children: [table], +}); const packer = new Packer(); diff --git a/demo/demo37.ts b/demo/demo37.ts index 6f599cd15a..08c4e547f5 100644 --- a/demo/demo37.ts +++ b/demo/demo37.ts @@ -1,15 +1,21 @@ // Add images to header and footer // Import from 'docx' rather than '../build' if you install from npm 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 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.Header.createImage(fs.readFileSync("./demo/images/pizza.gif")); -doc.Header.createImage(fs.readFileSync("./demo/images/image1.jpeg")); +doc.addSection({ + headers: { + default: new Header({ + children: [new Paragraph(image), new Paragraph(image1), new Paragraph(image2)], + }), + }, + children: [new Paragraph("Hello World")], +}); const packer = new Packer(); diff --git a/demo/demo38.ts b/demo/demo38.ts index eca2c82ef4..84eb162fa5 100644 --- a/demo/demo38.ts +++ b/demo/demo38.ts @@ -2,23 +2,11 @@ // Import from 'docx' rather than '../build' if you install from npm import * as fs from "fs"; // 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(); -doc.add(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.", -)); - -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, { +const image = Media.addImage(doc, fs.readFileSync("./demo/images/pizza.gif"), 200, 200, { floating: { horizontalPosition: { 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(); packer.toBuffer(doc).then((buffer) => { diff --git a/demo/demo39.ts b/demo/demo39.ts index 0c4cf86ca8..811115b876 100644 --- a/demo/demo39.ts +++ b/demo/demo39.ts @@ -1,34 +1,44 @@ // Example how to display page numbers // Import from 'docx' rather than '../build' if you install from npm 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, pageNumberFormatType: PageNumberFormat.DECIMAL, }, -); - -doc.Header.add( - new Paragraph("Foo Bar corp. ").addRun(new TextRun("Page Number ").pageNumber()).addRun(new TextRun(" to ").numberOfTotalPages()), -); - -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()); + children: [ + new Paragraph("Hello World 1").pageBreak(), + new Paragraph("Hello World 2").pageBreak(), + new Paragraph("Hello World 3").pageBreak(), + new Paragraph("Hello World 4").pageBreak(), + new Paragraph("Hello World 5").pageBreak(), + ], +}); const packer = new Packer(); diff --git a/demo/demo4.ts b/demo/demo4.ts index 5e528ac2db..48bcca1c0a 100644 --- a/demo/demo4.ts +++ b/demo/demo4.ts @@ -10,10 +10,12 @@ const table = new Table({ columns: 4, }); -doc.add(table); - table.getCell(2, 2).add(new Paragraph("Hello")); +doc.addSection({ + children: [table], +}); + const packer = new Packer(); packer.toBuffer(doc).then((buffer) => { diff --git a/demo/demo40.ts b/demo/demo40.ts index 6db6e7ba1e..f3bef349ec 100644 --- a/demo/demo40.ts +++ b/demo/demo40.ts @@ -3,30 +3,26 @@ import * as fs from "fs"; import { Document, HeadingLevel, LineNumberRestartFormat, Packer, Paragraph } from "../build"; -const doc = new Document( - {}, - { +const doc = new Document(); + +doc.addSection({ + properties: { lineNumberCountBy: 1, lineNumberRestart: LineNumberRestartFormat.CONTINUOUS, }, -); - -doc.add( - new Paragraph({ - text: "Hello", - heading: HeadingLevel.HEADING_1, - }), -); -doc.add( - 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( - "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.", - ), -); + children: [ + new Paragraph({ + 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.", + ), + 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(); diff --git a/demo/demo41.ts b/demo/demo41.ts index 977d99abb5..2d3609fe5d 100644 --- a/demo/demo41.ts +++ b/demo/demo41.ts @@ -10,8 +10,6 @@ const table = new Table({ columns: 6, }); -doc.add(table); - let row = 0; table.getCell(row, 0).add(new Paragraph("0,0")); 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.getRow(row).mergeCells(0, 4); +doc.addSection({ + children: [table], +}); + const packer = new Packer(); packer.toBuffer(doc).then((buffer) => { diff --git a/demo/demo43.ts b/demo/demo43.ts index 451d21a0fd..06806d5780 100644 --- a/demo/demo43.ts +++ b/demo/demo43.ts @@ -10,11 +10,12 @@ const table = new Table({ columns: 4, }); -doc.add(table); - table.getCell(2, 2).add(new Paragraph("Hello")); table.getColumn(3).mergeCells(1, 2); -// table.getCell(3, 2).add(new Paragraph("Hello")); + +doc.addSection({ + children: [table], +}); const packer = new Packer(); diff --git a/demo/demo44.ts b/demo/demo44.ts index a64062222b..83fbcf9efe 100644 --- a/demo/demo44.ts +++ b/demo/demo44.ts @@ -1,34 +1,40 @@ // Sections with multiple columns // Import from 'docx' rather than '../build' if you install from npm import * as fs from "fs"; -import { Document, Packer } from "../build"; +import { Document, Packer, Paragraph } from "../build"; const doc = new Document(); doc.addSection({ - column: { - width: 708, - count: 2, + properties: { + column: { + 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({ - column: { - width: 708, - count: 2, + properties: { + column: { + 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(); packer.toBuffer(doc).then((buffer) => { diff --git a/demo/demo5.ts b/demo/demo5.ts index be340a3530..0102998570 100644 --- a/demo/demo5.ts +++ b/demo/demo5.ts @@ -2,19 +2,25 @@ // Import from 'docx' rather than '../build' if you install from npm import * as fs from "fs"; // 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 paragraph = new Paragraph("Hello World"); -doc.add(paragraph); - -doc.createImage(fs.readFileSync("./demo/images/image1.jpeg")); -doc.createImage(fs.readFileSync("./demo/images/dog.png").toString("base64")); -doc.createImage(fs.readFileSync("./demo/images/cat.jpg")); -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, { +const image1 = Media.addImage(doc, fs.readFileSync("./demo/images/image1.jpeg")); +const image2 = Media.addImage(doc, fs.readFileSync("./demo/images/dog.png").toString("base64")); +const image3 = Media.addImage(doc, fs.readFileSync("./demo/images/cat.jpg")); +const image4 = Media.addImage(doc, fs.readFileSync("./demo/images/parrots.bmp")); +const image5 = Media.addImage(doc, fs.readFileSync("./demo/images/pizza.gif")); +const image6 = Media.addImage(doc, fs.readFileSync("./demo/images/pizza.gif"), 200, 200, { floating: { horizontalPosition: { 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: { horizontalPosition: { 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(); packer.toBuffer(doc).then((buffer) => { diff --git a/demo/demo6.ts b/demo/demo6.ts index 2629c1b96d..47cca9c5f6 100644 --- a/demo/demo6.ts +++ b/demo/demo6.ts @@ -3,34 +3,38 @@ import * as fs from "fs"; import { Document, HeadingLevel, Packer, Paragraph, TextRun } from "../build"; -const doc = new Document(undefined, { - top: 0, - right: 0, - bottom: 0, - left: 0, +const doc = new Document(); + +doc.addSection({ + margins: { + 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(); packer.toBuffer(doc).then((buffer) => { diff --git a/demo/demo7.ts b/demo/demo7.ts index db528cb157..2b171dea2f 100644 --- a/demo/demo7.ts +++ b/demo/demo7.ts @@ -3,14 +3,15 @@ import * as fs from "fs"; import { Document, Packer, PageOrientation, Paragraph } from "../build"; -const doc = new Document(undefined, { - orientation: PageOrientation.LANDSCAPE, +const doc = new Document(); + +doc.addSection({ + size: { + orientation: PageOrientation.LANDSCAPE, + }, + children: [new Paragraph("Hello World")], }); -const paragraph = new Paragraph("Hello World"); - -doc.add(paragraph); - const packer = new Packer(); packer.toBuffer(doc).then((buffer) => { diff --git a/demo/demo8.ts b/demo/demo8.ts index 1e3dfbaada..012a4a7bf5 100644 --- a/demo/demo8.ts +++ b/demo/demo8.ts @@ -1,14 +1,23 @@ // Add text to header and footer // Import from 'docx' rather than '../build' if you install from npm import * as fs from "fs"; -import { Document, Packer, Paragraph } from "../build"; +import { Document, Footer, Header, Packer, Paragraph } from "../build"; const doc = new Document(); -doc.add(new Paragraph("Hello World")); - -doc.Header.add(new Paragraph("Header text")); -doc.Footer.add(new Paragraph("Footer text")); +doc.addSection({ + headers: { + default: new Header({ + children: [new Paragraph("Header text")], + }), + }, + footers: { + default: new Footer({ + children: [new Paragraph("Footer text")], + }), + }, + children: [new Paragraph("Hello World")], +}); const packer = new Packer(); diff --git a/demo/demo9.ts b/demo/demo9.ts index 8787d43b24..eb81879223 100644 --- a/demo/demo9.ts +++ b/demo/demo9.ts @@ -1,14 +1,34 @@ // Add images to header and footer // Import from 'docx' rather than '../build' if you install from npm import * as fs from "fs"; -import { Document, Packer, Paragraph } from "../build"; +import { Document, Footer, Header, Media, Packer, Paragraph } from "../build"; 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.Footer.createImage(fs.readFileSync("./demo/images/pizza.gif")); +doc.addSection({ + 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(); diff --git a/src/export/packer/next-compiler.spec.ts b/src/export/packer/next-compiler.spec.ts index dec853ba68..43bd4814f1 100644 --- a/src/export/packer/next-compiler.spec.ts +++ b/src/export/packer/next-compiler.spec.ts @@ -1,7 +1,7 @@ /* tslint:disable:typedef space-before-function-paren */ import { expect } from "chai"; -import { File } from "file"; +import { File, Header, Footer } from "file"; import { Compiler } from "./next-compiler"; @@ -21,28 +21,39 @@ describe("Compiler", () => { const fileNames = Object.keys(zipFile.files).map((f) => zipFile.files[f].name); 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/styles.xml"); expect(fileNames).to.include("docProps/core.xml"); expect(fileNames).to.include("docProps/app.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/settings.xml"); - expect(fileNames).to.include("word/_rels/footer1.xml.rels"); expect(fileNames).to.include("word/_rels/document.xml.rels"); expect(fileNames).to.include("[Content_Types].xml"); expect(fileNames).to.include("_rels/.rels"); }); it("should pack all additional headers and footers", async function() { - file.createFooter(); - file.createFooter(); - file.createHeader(); - file.createHeader(); + file.addSection({ + headers: { + default: new Header(), + }, + footers: { + default: new Footer(), + }, + children: [], + }); + + file.addSection({ + headers: { + default: new Header(), + }, + footers: { + default: new Footer(), + }, + children: [], + }); this.timeout(99999999); @@ -50,20 +61,16 @@ describe("Compiler", () => { const fileNames = Object.keys(zipFile.files).map((f) => zipFile.files[f].name); 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/_rels/header1.xml.rels"); expect(fileNames).to.include("word/header2.xml"); 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/_rels/footer1.xml.rels"); expect(fileNames).to.include("word/footer2.xml"); 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"); }); }); }); diff --git a/src/export/packer/packer.spec.ts b/src/export/packer/packer.spec.ts index 201f5eb38d..e2be5aca44 100644 --- a/src/export/packer/packer.spec.ts +++ b/src/export/packer/packer.spec.ts @@ -16,26 +16,24 @@ describe("Packer", () => { revision: "1", lastModifiedBy: "Dolan Miu", }); - const paragraph = new Paragraph("test text"); - const heading = new Paragraph({ - text: "Hello world", - heading: HeadingLevel.HEADING_1, - }); - file.add( - new Paragraph({ - text: "title", - heading: HeadingLevel.TITLE, - }), - ); - file.add(heading); - file.add( - new Paragraph({ - text: "heading 2", - heading: HeadingLevel.HEADING_2, - }), - ); - file.add(paragraph); + file.addSection({ + children: [ + new Paragraph({ + text: "title", + heading: HeadingLevel.TITLE, + }), + new Paragraph({ + text: "Hello world", + heading: HeadingLevel.HEADING_1, + }), + new Paragraph({ + text: "heading 2", + heading: HeadingLevel.HEADING_2, + }), + new Paragraph("test text"), + ], + }); packer = new Packer(); }); diff --git a/src/file/document/body/body.spec.ts b/src/file/document/body/body.spec.ts index 6eb8cdddad..a5bc222fb4 100644 --- a/src/file/document/body/body.spec.ts +++ b/src/file/document/body/body.spec.ts @@ -11,35 +11,7 @@ describe("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", () => { - 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", () => { body.addSection({ width: 10000, @@ -51,33 +23,7 @@ describe("Body", () => { expect(tree).to.deep.equal({ "w:body": [ { - "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:p": {}, }, { "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); - }); - }); }); diff --git a/src/file/document/body/body.ts b/src/file/document/body/body.ts index 54d08ef9c5..e91b72d59a 100644 --- a/src/file/document/body/body.ts +++ b/src/file/document/body/body.ts @@ -3,15 +3,10 @@ import { Paragraph, ParagraphProperties, TableOfContents } from "../.."; import { SectionProperties, SectionPropertiesOptions } from "./section-properties/section-properties"; export class Body extends XmlComponent { - private readonly defaultSection: SectionProperties; - private readonly sections: SectionProperties[] = []; - constructor(sectionPropertiesOptions?: SectionPropertiesOptions) { + constructor() { 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: * - section element should be in the last paragraph of the section * - 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; this.root.push(this.createSectionParagraph(currentSection)); - if (section instanceof SectionProperties) { - this.sections.push(section); - } else { - const params = { - ...this.defaultSection.Options, - ...section, - }; - this.sections.push(new SectionProperties(params)); - } + + this.sections.push(new SectionProperties(options)); } + public prepForXml(): IXmlableObject | undefined { if (this.sections.length === 1) { this.root.push(this.sections.pop() as SectionProperties); @@ -47,18 +36,10 @@ export class Body extends XmlComponent { this.root.push(component); } - public get DefaultSection(): SectionProperties { - return this.defaultSection; - } - public getTablesOfContents(): 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 { const paragraph = new Paragraph({}); const properties = new ParagraphProperties({}); diff --git a/src/file/document/body/section-properties/header-reference/header-reference.ts b/src/file/document/body/section-properties/header-reference/header-reference.ts index 8f89ea09b3..b1bc4ef4f4 100644 --- a/src/file/document/body/section-properties/header-reference/header-reference.ts +++ b/src/file/document/body/section-properties/header-reference/header-reference.ts @@ -1,13 +1,13 @@ import { XmlComponent } from "file/xml-components"; import { HeaderReferenceAttributes, HeaderReferenceType } from "./header-reference-attributes"; -export interface IHeaderOptions { +export interface IHeaderReferenceOptions { readonly headerType?: HeaderReferenceType; readonly headerId?: number; } export class HeaderReference extends XmlComponent { - constructor(options: IHeaderOptions) { + constructor(options: IHeaderReferenceOptions) { super("w:headerReference"); this.root.push( new HeaderReferenceAttributes({ diff --git a/src/file/document/document.spec.ts b/src/file/document/document.spec.ts index 780dca0f27..dba489601e 100644 --- a/src/file/document/document.spec.ts +++ b/src/file/document/document.spec.ts @@ -1,4 +1,4 @@ -import { assert, expect } from "chai"; +import { expect } from "chai"; import { Formatter } from "export/formatter"; @@ -13,19 +13,34 @@ describe("Document", () => { describe("#constructor()", () => { it("should create valid JSON", () => { - const stringifiedJson = JSON.stringify(document); + const tree = new Formatter().format(document); - try { - JSON.parse(stringifiedJson); - } catch (e) { - assert.isTrue(false); - } - assert.isTrue(true); - }); - - it("should create default section", () => { - const body = new Formatter().format(document)["w:document"][1]["w:body"]; - expect(body[0]).to.have.property("w:sectPr"); + expect(tree).to.deep.equal({ + "w:document": [ + { + _attr: { + "xmlns:wpc": "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas", + "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", + "xmlns:m": "http://schemas.openxmlformats.org/officeDocument/2006/math", + "xmlns:v": "urn:schemas-microsoft-com:vml", + "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": {} }, + ], + }); }); }); }); diff --git a/src/file/document/document.ts b/src/file/document/document.ts index b716c1367b..d8c0c55131 100644 --- a/src/file/document/document.ts +++ b/src/file/document/document.ts @@ -4,13 +4,12 @@ import { Paragraph } from "../paragraph"; import { Table } from "../table"; import { TableOfContents } from "../table-of-contents"; import { Body } from "./body"; -import { SectionPropertiesOptions } from "./body/section-properties"; import { DocumentAttributes } from "./document-attributes"; export class Document extends XmlComponent { private readonly body: Body; - constructor(sectionPropertiesOptions?: SectionPropertiesOptions) { + constructor() { super("w:document"); this.root.push( new DocumentAttributes({ @@ -33,17 +32,12 @@ export class Document extends XmlComponent { Ignorable: "w14 w15 wp14", }), ); - this.body = new Body(sectionPropertiesOptions); + this.body = new Body(); this.root.push(this.body); } - public add(paragraph: Paragraph | Table): Document { - this.body.push(paragraph); - return this; - } - - public addTableOfContents(toc: TableOfContents): Document { - this.body.push(toc); + public add(item: Paragraph | Table | TableOfContents): Document { + this.body.push(item); return this; } @@ -54,8 +48,4 @@ export class Document extends XmlComponent { public getTablesOfContents(): TableOfContents[] { return this.body.getTablesOfContents(); } - - public getParagraphs(): Paragraph[] { - return this.body.getParagraphs(); - } } diff --git a/src/file/file.spec.ts b/src/file/file.spec.ts index 00e0b7d02b..6c4532a889 100644 --- a/src/file/file.spec.ts +++ b/src/file/file.spec.ts @@ -4,24 +4,37 @@ import * as sinon from "sinon"; import { Formatter } from "export/formatter"; import { File } from "./file"; +import { Footer, Header } from "./header"; import { Paragraph } from "./paragraph"; import { Table } from "./table"; import { TableOfContents } from "./table-of-contents"; describe("File", () => { 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", () => { const doc = new File(); - const header = doc.createHeader(); - const footer = doc.createFooter(); - doc.addSectionOld({ + doc.addSection({ headers: { - default: header, + default: new Header(), }, footers: { - default: footer, + default: new Footer(), }, + children: [], }); const tree = new Formatter().format(doc.Document.Body); @@ -32,40 +45,40 @@ describe("File", () => { it("should create with first headers and footers", () => { const doc = new File(); - const header = doc.createHeader(); - const footer = doc.createFooter(); - doc.addSectionOld({ + doc.addSection({ headers: { - first: header, + first: new Header(), }, footers: { - first: footer, + first: new Footer(), }, + children: [], }); const tree = new Formatter().format(doc.Document.Body); - expect(tree["w:body"][1]["w:sectPr"][4]["w:headerReference"]._attr["w:type"]).to.equal("first"); - expect(tree["w:body"][1]["w:sectPr"][5]["w:footerReference"]._attr["w:type"]).to.equal("first"); + console.log(JSON.stringify(tree, null, 2)); + + 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", () => { const doc = new File(); - const header = doc.createHeader(); - const footer = doc.createFooter(); - doc.addSectionOld({ + doc.addSection({ headers: { - default: header, - first: header, - even: header, + default: new Header(), + first: new Header(), + even: new Header(), }, footers: { - default: footer, - first: footer, - even: footer, + default: new Footer(), + first: new Footer(), + even: new Footer(), }, + children: [], }); 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", () => { const file = new File(); const spy = sinon.spy(file.Document, "add"); - file.add(new Paragraph({})); + file.addSection({ + children: [new Paragraph({})], + }); expect(spy.called).to.equal(true); }); it("should call the underlying document's add when adding a Table", () => { - const wrapper = new File(); - const spy = sinon.spy(wrapper.Document, "add"); - wrapper.add( - new Table({ - rows: 1, - columns: 1, - }), - ); + const file = new File(); + const spy = sinon.spy(file.Document, "add"); + file.addSection({ + children: [ + new Table({ + rows: 1, + columns: 1, + }), + ], + }); expect(spy.called).to.equal(true); }); it("should call the underlying document's add when adding an Image (paragraph)", () => { - const wrapper = new File(); - const spy = sinon.spy(wrapper.Document, "add"); + const file = new File(); + const spy = sinon.spy(file.Document, "add"); // tslint:disable-next-line:no-any - wrapper.add(new Paragraph("")); + file.addSection({ + children: [new Paragraph("")], + }); expect(spy.called).to.equal(true); }); }); - describe("#add", () => { - it("should call the underlying document's addTableOfContents", () => { - const wrapper = new File(); - const spy = sinon.spy(wrapper.Document, "addTableOfContents"); - wrapper.add(new TableOfContents()); + describe("#addSection", () => { + it("should call the underlying document's add", () => { + const file = new File(); + const spy = sinon.spy(file.Document, "add"); + file.addSection({ + children: [new TableOfContents()], + }); 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", () => { it("should call the underlying document's createFootnote", () => { const wrapper = new File(); diff --git a/src/file/file.ts b/src/file/file.ts index a78acd86e6..c0adf21e30 100644 --- a/src/file/file.ts +++ b/src/file/file.ts @@ -3,17 +3,16 @@ import { ContentTypes } from "./content-types/content-types"; import { CoreProperties, IPropertiesOptions } from "./core-properties"; import { Document } from "./document"; import { - FooterReference, FooterReferenceType, - HeaderReference, HeaderReferenceType, - IHeaderFooterGroup, + IPageSizeAttributes, SectionPropertiesOptions, } 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 { FooterWrapper, IDocumentFooter } from "./footer-wrapper"; import { FootNotes } from "./footnotes"; +import { Footer, Header } from "./header"; import { HeaderWrapper, IDocumentHeader } from "./header-wrapper"; import { Media } from "./media"; import { Numbering } from "./numbering"; @@ -28,7 +27,19 @@ import { Table } from "./table"; import { TableOfContents } from "./table-of-contents"; 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; } @@ -57,7 +68,6 @@ export class File { revision: "1", lastModifiedBy: "Un-named", }, - sectionPropertiesOptions: SectionPropertiesOptions = {}, fileProperties: IFileProperties = {}, sections: ISectionOptions[] = [], ) { @@ -68,6 +78,8 @@ export class File { this.appProperties = new AppProperties(); this.footNotes = new FootNotes(); this.contentTypes = new ContentTypes(); + this.document = new Document(); + this.settings = new Settings(); 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) { this.addHeaderToDocument(templateHeader.header, templateHeader.type); } - } else { - this.createHeader(); } if (fileProperties.template && fileProperties.template.footers) { for (const templateFooter of fileProperties.template.footers) { 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) { - this.document.Body.addSection(section.properties); + this.document.Body.addSection(section.properties ? section.properties : {}); 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 { const newText = text === undefined ? link : text; const hyperlink = new Hyperlink(newText, this.docRelationships.RelationshipCount); @@ -175,21 +145,36 @@ export class File { return hyperlink; } - public createBookmark(name: string, text?: string): Bookmark { - const newText = text === undefined ? name : text; - const bookmark = new Bookmark(name, newText, this.docRelationships.RelationshipCount); - return bookmark; + public createBookmark(name: string, text: string = name): Bookmark { + return new Bookmark(name, text, this.docRelationships.RelationshipCount); } - public addSectionOld(sectionPropertiesOptions: SectionPropertiesOptions): void { - this.document.Body.addSection(sectionPropertiesOptions); - } + public addSection({ + 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 { - this.document.Body.addSection(section.properties); - - for (const child of section.children) { - this.add(child); + for (const child of children) { + this.document.add(child); } } @@ -197,92 +182,34 @@ export class File { 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 { if (this.document.getTablesOfContents().length) { 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 { this.headers.push({ header, type }); this.docRelationships.createRelationship( @@ -342,66 +269,6 @@ export class File { ); } - private groupHeaders(headers: IDocumentHeader[], group: IHeaderFooterGroup = {}): IHeaderFooterGroup { - 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 = {}): IHeaderFooterGroup { - 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 { return this.document; } @@ -434,18 +301,10 @@ export class File { return this.fileRelationships; } - public get Header(): HeaderWrapper { - return this.headers[0].header; - } - public get Headers(): HeaderWrapper[] { return this.headers.map((item) => item.header); } - public get Footer(): FooterWrapper { - return this.footers[0].footer; - } - public get Footers(): FooterWrapper[] { return this.footers.map((item) => item.footer); } diff --git a/src/file/footer-wrapper.spec.ts b/src/file/footer-wrapper.spec.ts index 882e47fadf..3f6fb01b82 100644 --- a/src/file/footer-wrapper.spec.ts +++ b/src/file/footer-wrapper.spec.ts @@ -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", () => { it("should call the underlying footer's addChildElement", () => { const file = new FooterWrapper(new Media(), 1); diff --git a/src/file/footer-wrapper.ts b/src/file/footer-wrapper.ts index ebd0610a23..01087e9861 100644 --- a/src/file/footer-wrapper.ts +++ b/src/file/footer-wrapper.ts @@ -1,7 +1,6 @@ import { XmlComponent } from "file/xml-components"; import { FooterReferenceType } from "./document"; -import { IDrawingOptions } from "./drawing"; import { Footer } from "./footer/footer"; import { Image, Media } from "./media"; import { Paragraph } from "./paragraph"; @@ -35,19 +34,6 @@ export class FooterWrapper { 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 { return this.footer; } diff --git a/src/file/header-wrapper.spec.ts b/src/file/header-wrapper.spec.ts index 0d10b5818a..d07473f03a 100644 --- a/src/file/header-wrapper.spec.ts +++ b/src/file/header-wrapper.spec.ts @@ -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", () => { it("should call the underlying header's addChildElement", () => { const file = new HeaderWrapper(new Media(), 1); diff --git a/src/file/header-wrapper.ts b/src/file/header-wrapper.ts index 58826ec03b..d698505e4a 100644 --- a/src/file/header-wrapper.ts +++ b/src/file/header-wrapper.ts @@ -1,7 +1,6 @@ import { XmlComponent } from "file/xml-components"; import { HeaderReferenceType } from "./document"; -import { IDrawingOptions } from "./drawing"; import { Header } from "./header/header"; import { Image, Media } from "./media"; import { Paragraph } from "./paragraph"; @@ -37,19 +36,6 @@ export class HeaderWrapper { 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 { return this.header; } diff --git a/src/file/header.ts b/src/file/header.ts new file mode 100644 index 0000000000..05e227d9f8 --- /dev/null +++ b/src/file/header.ts @@ -0,0 +1,14 @@ +import { Paragraph } from "./paragraph"; +import { Table } from "./table"; + +export interface IHeaderOptions { + readonly children: Array; +} + +export class Header { + constructor(public readonly options: IHeaderOptions = { children: [] }) {} +} + +export class Footer { + constructor(public readonly options: IHeaderOptions = { children: [] }) {} +} diff --git a/src/file/index.ts b/src/file/index.ts index 199679bee3..d14d4d9b1a 100644 --- a/src/file/index.ts +++ b/src/file/index.ts @@ -11,3 +11,4 @@ export * from "./table-of-contents"; export * from "./xml-components"; export * from "./header-wrapper"; export * from "./footer-wrapper"; +export * from "./header"; diff --git a/src/file/media/image.ts b/src/file/media/image.ts index b596f77d9d..8255fe7398 100644 --- a/src/file/media/image.ts +++ b/src/file/media/image.ts @@ -10,8 +10,4 @@ export class Image { public get Run(): PictureRun { return this.paragraph.Run; } - - public scale(factorX: number, factorY?: number): void { - this.paragraph.Run.scale(factorX, factorY); - } } diff --git a/src/file/numbering/level.ts b/src/file/numbering/level.ts index bd213cfa6c..d8c3d07b0f 100644 --- a/src/file/numbering/level.ts +++ b/src/file/numbering/level.ts @@ -2,6 +2,7 @@ import { Attributes, XmlAttributeComponent, XmlComponent } from "file/xml-compon import { Alignment, AlignmentType, + IIndentAttributesProperties, Indent, ISpacingProperties, KeepLines, @@ -235,7 +236,7 @@ export class LevelBase extends XmlComponent { return this; } - public indent(attrs: object): Level { + public indent(attrs: IIndentAttributesProperties): Level { this.addParagraphProperty(new Indent(attrs)); return this; } diff --git a/src/file/paragraph/image.spec.ts b/src/file/paragraph/image.spec.ts index 6fb07e5294..715c1c93ab 100644 --- a/src/file/paragraph/image.spec.ts +++ b/src/file/paragraph/image.spec.ts @@ -1,12 +1,8 @@ // tslint:disable:object-literal-key-quotes -import { assert, expect } from "chai"; - -import { Formatter } from "export/formatter"; +import { assert } from "chai"; import { ImageParagraph } from "./image"; -import { EMPTY_OBJECT } from "file/xml-components"; - describe("Image", () => { let image: ImageParagraph; @@ -40,190 +36,4 @@ describe("Image", () => { 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, - }, - ], - }, - ], - }, - ], - }, - ], - }, - ], - }, - ], - }, - ], - }, - ], - }, - ], - }); - }); - }); }); diff --git a/src/file/paragraph/image.ts b/src/file/paragraph/image.ts index f4adffbdd4..4fa3d97b9f 100644 --- a/src/file/paragraph/image.ts +++ b/src/file/paragraph/image.ts @@ -12,10 +12,6 @@ export class ImageParagraph extends Paragraph { this.root.push(this.pictureRun); } - public scale(factorX: number, factorY?: number): void { - this.pictureRun.scale(factorX, factorY); - } - public get Run(): PictureRun { return this.pictureRun; } diff --git a/src/file/paragraph/run/picture-run.ts b/src/file/paragraph/run/picture-run.ts index 9f8cd7393c..c796beebfc 100644 --- a/src/file/paragraph/run/picture-run.ts +++ b/src/file/paragraph/run/picture-run.ts @@ -4,8 +4,6 @@ import { IMediaData } from "../../media/data"; import { Run } from "../run"; export class PictureRun extends Run { - private readonly drawing: Drawing; - constructor(imageData: IMediaData, drawingOptions?: IDrawingOptions) { super({}); @@ -13,12 +11,8 @@ export class PictureRun extends Run { throw new Error("imageData cannot be undefined"); } - this.drawing = new Drawing(imageData, drawingOptions); + const drawing = new Drawing(imageData, drawingOptions); - this.root.push(this.drawing); - } - - public scale(factorX: number = 1, factorY: number = factorX): void { - this.drawing.scale(factorX, factorY); + this.root.push(drawing); } }