diff --git a/demo/text/fit-text.ts b/demo/text/fit-text.ts new file mode 100644 index 0000000000..43dcdf68f6 --- /dev/null +++ b/demo/text/fit-text.ts @@ -0,0 +1,44 @@ +// Fit text, which squeezes or spreads a run's text so that it takes up the width given for it + +import * as fs from "fs"; +import { Document, Packer, Paragraph, TextRun } from "docx"; + +const doc = new Document({ + styles: { + default: { + document: { + run: { + font: { ascii: "Calibri", eastAsia: "MS Mincho" }, + size: 22, + }, + }, + }, + }, + sections: [ + { + children: [ + new Paragraph({ children: [new TextRun({ text: "Name", fitText: { width: 1440 } }), new TextRun(": Jane Smith")] }), + new Paragraph({ children: [new TextRun({ text: "Address", fitText: { width: 1440 } }), new TextRun(": 1 Harbour Road")] }), + new Paragraph({ + children: [new TextRun({ text: "Telephone number", fitText: { width: 1440 } }), new TextRun(": 01234 567890")], + }), + new Paragraph({ + children: [ + new TextRun({ text: "Date of ", fitText: { width: 1440, group: 1 } }), + new TextRun({ text: "birth", bold: true, fitText: { width: 1440, group: 1 } }), + new TextRun(": 1 April 1990"), + ], + }), + new Paragraph(""), + // Four characters of 11 points wide + new Paragraph({ children: [new TextRun({ text: "氏名", fitText: { width: "44pt" } }), new TextRun(":山田太郎")] }), + new Paragraph({ children: [new TextRun({ text: "住所", fitText: { width: "44pt" } }), new TextRun(":東京都千代田区")] }), + new Paragraph({ children: [new TextRun({ text: "電話番号", fitText: { width: "44pt" } }), new TextRun(":03-1234-5678")] }), + ], + }, + ], +}); + +Packer.toBuffer(doc).then((buffer) => { + fs.writeFileSync("My Document.docx", buffer); +}); diff --git a/docs/usage/layout.md b/docs/usage/layout.md index e9aee9f020..eda89d9ebd 100644 --- a/docs/usage/layout.md +++ b/docs/usage/layout.md @@ -206,7 +206,7 @@ The pages are laid out with the widths and heights of the characters of the font - keeping a paragraph with the next, keeping its lines together, widow and orphan control, and page breaks - numbered and bulleted lists, including those a paragraph's style numbers it in, counted as Word counts them: lists made from the same definition count on from one another, and a list's own first number for a level, which `docx` writes for each `instance` of a list, starts that level there at the list's first paragraph of that level. A level starts again after any level above it, or only after the level it gives, or never (`w:lvlRestart`), and a legal level (`isLegalNumberingStyle`) writes every level's number in decimal. A number is in its paragraph mark's formatting (`run` on a `Paragraph`), but for what its level gives it (`style.run`), and makes its line taller only above the baseline, with multiple line spacing a share of its text's line more, as Word lays it out. Its emphasis marks, and a number raised or lowered, take room as text's do. A line with nothing but a number is as tall as its paragraph's mark, or as the number above the baseline where that is taller. A number aligned to the right (`AlignmentType.END` or `RIGHT`) ends at the start of its paragraph's first line, and a centred one, with the space after it, is centred there, so a wide number can go into the margin, as Word puts it, and the text after it goes on from its end, at the hanging indent or the next tab stop after it. Word lines up a number aligned distribute or with a low kashida to the left, one aligned `numTab` to the right, and one aligned for Thai in the centre, and so does the layout. A number in a border (`style.run.border`) is in a box with the tab or space after it: the text after it starts at the tab's stop, or right after the border's room from the number where that is further, and the line is taller by the room above. A word that doesn't fit after a number's tab stays on the number's line, broken after the last character that fits, as a word after a tab that starts its line does. Bullets that are pictures Word draws nothing for, so the text is at the tab's stop and the line as tall as its text. A level numbered as Word 6 numbered lists (`w:legacy`) puts the text at the level's indent from the number, or after its space from the number's end where that is further. After a number aligned to the right, the tab goes to the next stop past its end, or, without a first line or hanging indent, to the left indent, where the number ends. Word measures the space after a number (`LevelSuffix.SPACE`) in Arial, and so does the layout. Word writes Thai and Hindi words (`thaiCounting`, `hindiCounting`) from 1 to 5. A level whose text shows a level its list doesn't have, or aligned as justified text is (`w:lvlJc` both), Word leaves out, as though it weren't there: its paragraphs have no number, nor the level's indent, another level's number shows nothing for it, and a paragraph at it starts the levels below it again, as a paragraph at any level does, while the list's other levels are numbered as usual. Word puts its automatic spacing between the paragraphs of two lists made from the same definition (`instance`), as between lists of other definitions, and so does the layout - footnotes, which take room at the bottom of the page their reference is on, and endnotes, which follow the text. A footnote that doesn't fit below its reference continues at the bottom of the next page, as Word continues it: it breaks between its paragraphs and table rows, and inside a paragraph keeping to its widow and orphan control, and its reference's line moves to the next page with it when too little of it would stay. A first paragraph kept together, or kept with the next, stays with its reference whole, with the first lines of what it is kept with. A footnote breaks before a later paragraph kept together, and before paragraphs kept with the next with what they are kept with, as the text does, unless they start its part on the page, which would leave none of it, where it breaks as without them, as the text does at the top of a page. It breaks before a table row whose lines widow control keeps together, and in a row whose lines could go on both pages, between its cells' lines, as a row of the text breaks, with the rest of the row at the top of the next page's footnotes, as Word breaks it. A footnote or endnote that ends with a table has a line below it for the empty paragraph Word puts after the table. A table's header rows aren't repeated above the rest of a footnote on the next page, nor left alone at the bottom of a page, as the table goes on the next page then. The footnote of a line kept with a longer paragraph goes below the first lines of it that the line is kept with, and of one kept with a table, below its first row, and the rest goes on the next page. One longer than a page fills the pages after it, and the text goes on above its end. Before the next section, whether it starts on a new page or not, and before a paragraph with a page break before it, the rest of a footnote goes on pages of its own, which belong to the section its reference is in, and the new section or paragraph starts after them. Before a continuous section, those pages show that section's header and footer, as Word shows them, and in columns, the rest is evened out in the columns of its last page. After a footnote that continues from the page before, the text after a page break at the start of a paragraph goes on the page the footnote ends on, as Word puts it. Before a continuous section numbered afresh, Word numbers each of those pages with the section's first number, and so does `docx/layout`. Before a continuous section, the number of pages of the section the footnote is in isn't worked out, as Word counts it its own way, and the next section's is its own pages, as Word counts them. A line whose footnote can't go on a page with it, such as one that starts with a paragraph kept together that is taller than a page, goes at the top of a page, with the text after it, from the top of a later column too, and the footnote starts on the next page, with those referred to after it after it, the last of those going on to the next page as far as it doesn't fit below its end. So does the last of a line's footnotes that doesn't fit below the others, and the footnote of a table row at the top of a page that fits there, but not with it. In columns, a line referring to a footnote below one that continues on the next page goes on the next page with it. A table row refers to footnotes as a line does: it moves to the next page with a footnote that doesn't fit below it, and one that breaks across pages has each line's footnote on the page the line is on, and breaks after a line whose footnote continues. A table row in a footnote breaks across as many pages as it takes, as Word breaks it, and moves to the next page whole where a cell of it would have none of its lines on the page. Where its footnotes fit whole below fewer of its lines, with the lines that refer to them, it breaks there instead, as Word breaks a row with a table in a cell beside a line whose footnote would otherwise continue. In columns, the footnotes of a page are laid out in the columns too, as Word lays them out: one after the other from the first column, evened out, each part broken at the width of the column it is in, and every column ends above them. Footnotes from another section on the page go on in the columns of its first footnote's. A line or table row in columns whose footnotes don't fit below it moves to the next column, or the next page, with all of them, as Word moves it, and the page is left as it was when a reference moves on as its columns are laid out again for its footnote. At the top of the page's columns, or of the column a section starts in after the section before's, a line stays, and its footnote goes on the page as far as it fits below the lines of every column, with the text going on above it, and continues at the foot of the next page's columns. At the top of a later column, the columns before it are laid out again above as much of the footnote as leaves the line on the page, as Word lays them out: a footnote of 120 lines referred to from line 11 of the first of 2 columns takes 44 lines of each, the columns above it 6, and its reference goes on in the second. The separator above the endnotes goes on the page of their first line, and on each page after the first they are on, the continuation separator is above them, as Word puts them. Each is a line of its paragraph style's text tall, at single spacing, whatever its own spacing, line spacing, size, text and paragraphs, as Word lays them out. A footnote's paragraph borders take room as in the text. Below the continuation separator, as many lines of endnotes go on the page as fit on it without it, so the last can go past the bottom margin by as much as the separator takes, as Word puts them. Footnotes and endnotes are numbered as Word numbers them, 1, 2, 3 and i, ii, iii, or in the format and from the number a document or its sections give, afresh in each section when they say so, and footnotes afresh on each page. A section's own start number adds to the number of notes before it, as Word adds it: after 27 footnotes, a section numbered from 5 numbers its first 32. A footnote or endnote with a mark of its own in place of its number isn't counted, footnotes numbered afresh on each page are numbered on from those of the page numbered so in another section, and a section's footnotes can go just below the text of their page, rather than at its bottom, below the space after a section's last paragraph and the rest of one continued from the page before too, or in columns of their own, evened out, as Word puts them. Word puts the endnotes of a section that says they go at the end of it at the end of the document, unless the document's settings say so too, when each section's go after it, after a separator of their own, but for a section that suppresses its own, whose go after the next's, and so does `docx/layout`. After text in columns, the text is evened out above the endnotes, which are laid out in the columns below their separator, in the first column, the continuation separator at the top of the first column only on the next page, and evened out in the columns they end in, as Word lays them out -- run formatting that changes how much room text takes, as Word lays it out. Superscript and subscript (`superScript`, `subScript`) are drawn at 65% of the text's size, to the nearest half-point and down from a quarter, so 7 points at 11 and 9.5 at 15, and small capitals (`smallCaps`) at 80%, so 9 points at 11; both take up the line of their run's own size, so they never make a line taller. Raised and lowered text (`position`) raises the line's top or lowers its bottom by as much as it goes past the rest of the line: a word raised 6 points makes a line of Calibri 11 120 twips taller, and a smaller word raised a little none. Emphasis marks (`emphasisMark`) take a quarter of their line, over it, or under it for dots below, and both on a line with marks over and under it, with a picture in the line counted in it; line spacing that gives a line less room than a quarter of it adds it below the marks' room, and spacing that gives it at least that, such as 1.25 lines, holds the marks, and spacing of less than a line makes the line and the marks' room that share of themselves. A border around text (`border` on a `TextRun`) takes its space and its width on each side of the text, and above and below it, as wide as a paragraph's border of its style, an art border its size in points, and a space past 31 points only what is left over 32: two runs next to each other with the same border are in one box, a box that goes on to the next line starts again there, also in a word broken across lines, and a line keeps room for its box to end after its last word. A shadow doubles a border's width as Word draws it, whatever its style, and one drawn as a frame takes the room it takes without (`w:shadow`, `w:frame`, in documents Word made), and a picture in the line in a run with a border has its border's room around it, beside it and above and below it, in one box with text in the same border either side of it, and multiple line spacing adds its share of the run's line with the border's room above and below. Text fitted to a width (`w:fitText`, in documents Word made) is one box of that width, which goes on to the next line whole when it doesn't fit, or takes a line of its own and goes past its end when it is wider than the line, and runs one after the other fitted with the same id are one box, as tall as the tallest of their lines. Text with a phonetic guide over it (`w:ruby`, in documents Word made) is one box as wide as the wider of the guide and its base, and its line is as tall as the base makes it and as the guide raised over the base's baseline by its raise (`w:hpsRaise`), as text raised that far. Two lines in one (`eastAsianLayout: { twoLinesInOne: true }`) of text that isn't Chinese, Japanese or Korean is drawn at half its size on one row, as Word draws it +- run formatting that changes how much room text takes, as Word lays it out. Superscript and subscript (`superScript`, `subScript`) are drawn at 65% of the text's size, to the nearest half-point and down from a quarter, so 7 points at 11 and 9.5 at 15, and small capitals (`smallCaps`) at 80%, so 9 points at 11; both take up the line of their run's own size, so they never make a line taller. Raised and lowered text (`position`) raises the line's top or lowers its bottom by as much as it goes past the rest of the line: a word raised 6 points makes a line of Calibri 11 120 twips taller, and a smaller word raised a little none. Emphasis marks (`emphasisMark`) take a quarter of their line, over it, or under it for dots below, and both on a line with marks over and under it, with a picture in the line counted in it; line spacing that gives a line less room than a quarter of it adds it below the marks' room, and spacing that gives it at least that, such as 1.25 lines, holds the marks, and spacing of less than a line makes the line and the marks' room that share of themselves. A border around text (`border` on a `TextRun`) takes its space and its width on each side of the text, and above and below it, as wide as a paragraph's border of its style, an art border its size in points, and a space past 31 points only what is left over 32: two runs next to each other with the same border are in one box, a box that goes on to the next line starts again there, also in a word broken across lines, and a line keeps room for its box to end after its last word. A shadow doubles a border's width as Word draws it, whatever its style, and one drawn as a frame takes the room it takes without (`w:shadow`, `w:frame`, in documents Word made), and a picture in the line in a run with a border has its border's room around it, beside it and above and below it, in one box with text in the same border either side of it, and multiple line spacing adds its share of the run's line with the border's room above and below. Text fitted to a width (`fitText`) is one box of that width, which goes on to the next line whole when it doesn't fit, or takes a line of its own and goes past its end when it is wider than the line, and runs one after the other fitted with the same `group`, or the same id in documents Word made, are one box of the first one's width, as tall as the tallest of their lines. Text with a phonetic guide over it (`w:ruby`, in documents Word made) is one box as wide as the wider of the guide and its base, and its line is as tall as the base makes it and as the guide raised over the base's baseline by its raise (`w:hpsRaise`), as text raised that far. Two lines in one (`eastAsianLayout: { twoLinesInOne: true }`) of text that isn't Chinese, Japanese or Korean is drawn at half its size on one row, as Word draws it - pictures in the line, which stand on the baseline, so a line with text in it is as tall as the picture and the text below the baseline, as Word makes it. A line with a picture is at least as tall as a line of the picture's run's font, and its multiple line spacing adds a share of that, as Word's does. A line of only a picture isn't as tall as a larger paragraph mark, at single spacing - pictures, shapes and charts that text wraps around (`floating` with a `wrap`), as Word lays the text out around them. A line beside a drawing has the room beside it, with the drawing's distances from the text (`margins`) and the room its effects take, such as a shape's line or shadow, and a line with no room beside it goes below it. Square, tight and through wrapping put the text beside the drawing's box, on the side or sides its wrapping's `side` says, the left first, and Word puts as many words in the room on a side as fit there, and none when the next word doesn't fit, nor in a room narrower than 18 points, so a line with no wider room goes below the drawing. Top and bottom wrapping puts the lines below the drawing. Drawings that overlap keep the text out of all their room. A drawing in a margin, where there is no text, leaves the lines as they are. A line beside a drawing starts at the drawing's edge or the paragraph's left indent, whichever is further in, and its first line is indented from there. A drawing is placed against the page, its margins, the column, or the paragraph or line it is anchored in, as its `horizontalPosition` and `verticalPosition` say: at an offset, which places the drawing without its effects, lined up with them, with its effects, or at a percentage of them, as `docx/shapes` places shapes, and its percentage sizes are a share of the page or its margins: the inside and outside margins are those it is placed against on its page. Lined up inside or outside against the margins, it is lined up with them, and against the page, down it, it is at the top of the page, inside on odd pages and outside on even ones, half the header's distance from the page's top below it, and at the bottom otherwise, half the footer's distance above it. One placed by its simple position is placed from the page's top left corner by that. Placed against its paragraph, it is at the top of the paragraph, below the space after the paragraph before, which is that paragraph's, and above its own space before, and no higher than the top of the page's text. Where it would go past the bottom of the page's text, the paragraph moves to the next column or page with it, above footnotes too, and a paragraph whose first line goes below a drawing with top and bottom wrapping keeps its own space before above that line. Placed against its line, it is at the line its anchor is on before the text goes round it, though the text going round it can move the anchor on to the next line. One anchored in a line that goes on to the next page goes there with it, against the top of the paragraph's part on that page. The text before a drawing's paragraph on its page goes round it too, as Word lays the page out again with it, and the drawing stays where it was first placed, though its paragraph moves down: with top and bottom wrapping, the lines before it that its distance above it reaches go below it. Where that moves the paragraph on to the next page, it starts there with the drawing, and the page is laid out again without it. Of two drawings that may not overlap (`allowOverlap: false`), the later is moved out of the way across the page, at the height it was placed at: to the right of the other, their boxes side by side, or to the left of it when it is lined up at the right. A table that fits beside a drawing at its indent goes beside it, as does one that fits past a drawing on its left, with its indent from there, and one that doesn't fit goes below it; one sized to its text goes beside it as wide as it is in the column. Paragraphs kept with the next are kept with as many of the next paragraph's lines beside a drawing as they would be without it, and move to the next page with a paragraph that moves there with its drawing. Those with drawings of their own move to the next page with the next, and their drawings with them, and those kept with a table stay where they are when the next starts on their page. Columns are evened out with the drawings in them. A turned picture wraps the text around its box as it is before it is turned. A drawing that text wraps around in a header or footer, placed against the page or its margins, is on each page that shows the header or footer, and the body's text goes round it as round its own, as Word lays it out. So is one in the first line of a header's first paragraph placed against its paragraph or line, which is the top of the header, and one placed against a column of a section of several by a distance from its left, which is the left margin, and the header's lines go round its drawings, as the body's do. Drawings behind or in front of the text don't move the body's lines. A drawing beside the page's footnotes leaves their lines as they are - tables that text wraps around (a table's `float`), as Word lays the text out around them: the text after the table goes beside it, as beside a picture with square wrapping, kept from it by its distances from the text (`leftFromText`, `rightFromText`, `topFromText` and `bottomFromText`), and at least half a point from it across the page, as Word keeps it: half a point with none given, or with a smaller one. A table is placed across against the page, its margins or the column (`horizontalAnchor`), and down against the page, its margins or the top of the paragraph after it (`verticalAnchor`), at a distance (`absoluteHorizontalPosition`, `absoluteVerticalPosition`) or lined up with them (`relativeHorizontalPosition`, `relativeVerticalPosition`). Without `horizontalAnchor` it is placed against the column, and without `verticalAnchor` against the margins, and lined up inline against the text (`RelativeVerticalPosition.INLINE`), it is at the top of the paragraph after it. Its room is as wide as its rows with the halves of its borders left and right, on one side or both, or 0.75 points wider than its rows without any borders, which borders between its rows alone count as, and as tall as its rows, and its indent doesn't move it. It is below the space after the paragraph before, and the paragraph after it has all of its space before below that, as after a table. It is placed against the top of what comes after it: a paragraph, the empty paragraph that ends its section, which takes a line after it then, and whose next section on the page goes round it too, a table, or the empty paragraph Word adds after it at the end of the document. Tables one after the other before a paragraph each go round it, and the paragraphs after it go round it too while they are beside it. Its footnotes are on its page. Of two that may not overlap (`overlap: OverlapType.NEVER`), the later moves to the right until the room it keeps the text out of is beside the other's, or to the left of the other when it has no room on the right, or is lined up at the right. One that goes past the bottom of the page is broken between its rows: those that fit stay where it was placed, the rest go at the top of the next pages, below its header rows, which go there again, and the paragraph after it starts beside its last rows. One in a footnote or an endnote is laid out in the note's text, as a table that doesn't float. One before a table that moves on to the next page stays where it was placed, as does one anchored in a paragraph kept with the next that moves on to the next page with the next diff --git a/docs/usage/text.md b/docs/usage/text.md index a8d2c64657..c69bb24218 100644 --- a/docs/usage/text.md +++ b/docs/usage/text.md @@ -223,6 +223,37 @@ const doc = new Document({ }); ``` +### Fit Text + +`fitText` squeezes or spreads a run's text so that it takes up the `width` given, in twips (1440 is an inch) or as a measure such as `"1in"`, as Word's Fit Text does (`w:fitText`). Labels fitted to one width line up what comes after them. Runs next to each other with the same `group` are fitted together, as one piece of text, to the first one's width, so it can be formatted differently. A run without a `group` is fitted on its own. + +```ts live +import { Document, Paragraph, TextRun } from "docx"; + +const doc = new Document({ + sections: [ + { + children: [ + new Paragraph({ children: [new TextRun({ text: "Name", fitText: { width: 1440 } }), new TextRun(": Jane Smith")] }), + new Paragraph({ children: [new TextRun({ text: "Address", fitText: { width: 1440 } }), new TextRun(": 1 Harbour Road")] }), + new Paragraph({ + children: [new TextRun({ text: "Telephone number", fitText: { width: 1440 } }), new TextRun(": 01234 567890")], + }), + new Paragraph({ + children: [ + new TextRun({ text: "Date of ", fitText: { width: 1440, group: 1 } }), + new TextRun({ text: "birth", bold: true, fitText: { width: 1440, group: 1 } }), + new TextRun(": 1 April 1990"), + ], + }), + ], + }, + ], +}); +``` + +Word fits the text as it lays the page out. LibreOffice ignores `fitText`, and shows the text at its own width. + ### Shading and Highlighting ```ts live diff --git a/src/file/paragraph/run/fit-text.spec.ts b/src/file/paragraph/run/fit-text.spec.ts new file mode 100644 index 0000000000..069913be30 --- /dev/null +++ b/src/file/paragraph/run/fit-text.spec.ts @@ -0,0 +1,61 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { Formatter } from "@export/formatter"; +import * as convenienceFunctions from "@util/convenience-functions"; + +import { createFitText } from "./fit-text"; + +describe("createFitText", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("should write the width in twips as w:val, and the group as w:id", () => { + const tree = new Formatter().format(createFitText({ width: 1440, group: 1 })); + expect(tree).to.deep.equal({ + "w:fitText": { _attr: { "w:val": 1440, "w:id": 1 } }, + }); + }); + + it("should write a width given as a measure in whole twips, as Office's schemas allow only those", () => { + const valOf = (width: `${number}${"in" | "pt" | "cm" | "mm"}`): unknown => + new Formatter().format(createFitText({ width, group: 1 }))["w:fitText"]._attr["w:val"]; + expect(valOf("1in")).to.equal(1440); + expect(valOf("44pt")).to.equal(880); + expect(valOf("2.54cm")).to.equal(1440); + expect(valOf("10mm")).to.equal(567); + }); + + it("should write a group of 0", () => { + const tree = new Formatter().format(createFitText({ width: 1440, group: 0 })); + expect(tree).to.deep.equal({ + "w:fitText": { _attr: { "w:val": 1440, "w:id": 0 } }, + }); + }); + + it("should give text fitted without a group an ID of its own, as Word fits runs without one unreliably", () => { + vi.spyOn(convenienceFunctions, "fitTextUniqueNumericId").mockReturnValue(-7); + const tree = new Formatter().format(createFitText({ width: 1440 })); + expect(tree).to.deep.equal({ + "w:fitText": { _attr: { "w:val": 1440, "w:id": -7 } }, + }); + }); + + it("should give each piece of text fitted without a group a different negative ID, apart from the groups people give", () => { + const idOf = (): number => new Formatter().format(createFitText({ width: 1440 }))["w:fitText"]._attr["w:id"]; + const [first, second] = [idOf(), idOf()]; + expect(first).to.be.below(0); + expect(second).to.be.below(0); + expect(second).to.not.equal(first); + }); + + it("should throw for a negative width, rather than write it as w:val", () => { + expect(() => createFitText({ width: -1440 })).to.throw(); + expect(() => createFitText({ width: "-1in" as `${number}in` })).to.throw(); + }); + + it("should throw for a group that isn't a number, rather than write it as w:id", () => { + expect(() => createFitText({ width: 1440, group: NaN })).to.throw(); + expect(() => createFitText({ width: 1440, group: Infinity })).to.throw(); + }); +}); diff --git a/src/file/paragraph/run/fit-text.ts b/src/file/paragraph/run/fit-text.ts new file mode 100644 index 0000000000..a53a237c4f --- /dev/null +++ b/src/file/paragraph/run/fit-text.ts @@ -0,0 +1,64 @@ +/** + * Fit text module for WordprocessingML run properties. + * + * This module provides Word's Fit Text, which squeezes or spreads a run's text so that it takes up a width given for it. + * + * Reference: ISO/IEC 29500-1, 17.3.2.14 fitText + * + * @module + */ +import { BuilderElement, type XmlComponent } from "@file/xml-components"; +import { fitTextUniqueNumericId } from "@util/convenience-functions"; +import { type PositiveUniversalMeasure, decimalNumber, twipsMeasureValue, universalMeasureToTwips } from "@util/values"; + +/** + * Options for fitting a run's text to a width. + * + * @publicApi + */ +export type IFitTextOptions = { + /** The width the text is squeezed or spread to fill, in twips (1440 is an inch) or as a measure such as `"1in"` (`w:val`) */ + readonly width: number | PositiveUniversalMeasure; + /** + * Runs next to each other with the same group are fitted to the width together, as one piece of text, so it can be + * made of runs formatted differently (`w:id`). Word fits them to the first one's width. Without a group, the run is + * fitted to its width on its own. + */ + readonly group?: number; +}; + +type IFitTextAttributes = { + readonly val: number; + readonly id: number; +}; + +/** + * Creates the fitting of a run's text to a width (`w:fitText`). + * + * Word writes an ID for each piece of fitted text, and fits runs without one unreliably: two of them next to each other + * together, and some not at all. So a run without a group is given an ID of its own. + * + * A width given as a measure is written in twips, as Office's schemas allow only a whole number of them, though the + * standard's allow a measure. + * + * ## XSD Schema + * ```xml + * + * + * + * + * ``` + * + * @example + * ```typescript + * createFitText({ width: 1440, group: 1 }); + * ``` + */ +export const createFitText = ({ width, group }: IFitTextOptions): XmlComponent => + new BuilderElement({ + name: "w:fitText", + attributes: { + val: { key: "w:val", value: Math.round(universalMeasureToTwips(twipsMeasureValue(width))) }, + id: { key: "w:id", value: group === undefined ? fitTextUniqueNumericId() : decimalNumber(group) }, + }, + }); diff --git a/src/file/paragraph/run/index.ts b/src/file/paragraph/run/index.ts index 6fbbd34571..307e8f9e72 100644 --- a/src/file/paragraph/run/index.ts +++ b/src/file/paragraph/run/index.ts @@ -15,6 +15,7 @@ export * from "./sequential-identifier"; export * from "./underline"; export * from "./emphasis-mark"; export * from "./east-asian-layout"; +export * from "./fit-text"; export * from "./simple-field"; export * from "./comment-run"; export * from "./comments-extended"; diff --git a/src/file/paragraph/run/properties.ts b/src/file/paragraph/run/properties.ts index c189bd792e..96057ce44b 100644 --- a/src/file/paragraph/run/properties.ts +++ b/src/file/paragraph/run/properties.ts @@ -27,6 +27,7 @@ import type { PositiveUniversalMeasure, UniversalMeasure } from "@util/values"; import { type IEastAsianLayoutOptions, createEastAsianLayout } from "./east-asian-layout"; import { type EmphasisMarkType, createEmphasisMark } from "./emphasis-mark"; +import { type IFitTextOptions, createFitText } from "./fit-text"; import { CharacterSpacing, Color, Highlight } from "./formatting"; import { type ILanguageOptions, createLanguageComponent } from "./language"; import { type IFontAttributesProperties, type IThemeFontReference, createRunFonts } from "./run-fonts"; @@ -197,6 +198,11 @@ export type IRunStylePropertiesOptions = { readonly highlightComplexScript?: boolean | string; readonly characterSpacing?: number; readonly shading?: IShadingAttributesProperties; + /** + * Squeezes or spreads the run's text so that it takes up the width given, as Word's Fit Text does. Runs next to each + * other with the same `group` are fitted to it together. + */ + readonly fitText?: IFitTextOptions; readonly emboss?: boolean; readonly imprint?: boolean; readonly revision?: IRunPropertiesChangeOptions; @@ -389,6 +395,10 @@ export class RunProperties extends IgnoreIfEmptyXmlComponent { this.push(createShading(options.shading)); } + if (options.fitText) { + this.push(createFitText(options.fitText)); + } + if (options.subScript) { this.push(createSubScript()); } diff --git a/src/file/paragraph/run/run.spec.ts b/src/file/paragraph/run/run.spec.ts index 76335b09a0..bc5c7cac6f 100644 --- a/src/file/paragraph/run/run.spec.ts +++ b/src/file/paragraph/run/run.spec.ts @@ -284,6 +284,28 @@ describe("Run", () => { }); }); + describe("#fitText()", () => { + it("should write w:fitText after w:shd and before w:vertAlign, as Word orders them", () => { + const run = new Run({ + superScript: true, + fitText: { width: 2880, group: 4 }, + shading: { type: ShadingType.CLEAR, fill: "FFFF00" }, + }); + const tree = new Formatter().format(run); + expect(tree).to.deep.equal({ + "w:r": [ + { + "w:rPr": [ + { "w:shd": { _attr: { "w:val": "clear", "w:fill": "FFFF00" } } }, + { "w:fitText": { _attr: { "w:val": 2880, "w:id": 4 } } }, + { "w:vertAlign": { _attr: { "w:val": "superscript" } } }, + ], + }, + ], + }); + }); + }); + describe("#break()", () => { it("it should add break to the run", () => { const run = new Run({ diff --git a/src/layout/layout-document.spec.ts b/src/layout/layout-document.spec.ts index 11435175f0..59b1521f0a 100644 --- a/src/layout/layout-document.spec.ts +++ b/src/layout/layout-document.spec.ts @@ -371,6 +371,23 @@ describe("layoutDocument", () => { ); }); + it("should fit each run fitted to a width without a group on its own, and the runs of a group to the first one's width, as Word does", () => { + // Word for Mac 16.114 drew "Name" fitted to 1440 twips 72 points wide, "Bold " and "plain" fitted to 1440 each + // without a group 144, the two in one group of 2880 144, and in one group of 1440 and then 2880 72 + const widthOf = (...children: readonly TextRun[]): number => { + const { pages, stoppedAt } = layoutDocument(new Document({ sections: [{ children: [new Paragraph({ children })] }] })); + expect(stoppedAt).to.equal(undefined); + return linesOf(pages[0].body)[0].textWidth; + }; + const fitted = (text: string, width: number, group?: number): TextRun => + new TextRun({ text, fitText: { width, ...(group === undefined ? {} : { group }) } }); + // An inch is 1440 twips, and 96 pixels + expect(widthOf(fitted("Name", 1440))).to.be.closeTo(96, 0.001); + expect(widthOf(fitted("Bold ", 1440), fitted("plain", 1440))).to.be.closeTo(192, 0.001); + expect(widthOf(fitted("Bold ", 2880, 1), fitted("plain", 2880, 1))).to.be.closeTo(192, 0.001); + expect(widthOf(fitted("Bold ", 1440, 1), fitted("plain", 2880, 1))).to.be.closeTo(96, 0.001); + }); + it("should leave the document as it is written", () => { const options = (): IPropertiesOptions => ({ footnotes: { 1: { children: [new Paragraph("A footnote.")] } }, diff --git a/src/util/convenience-functions.spec.ts b/src/util/convenience-functions.spec.ts index f32ccb9e5b..c43e1404c9 100644 --- a/src/util/convenience-functions.spec.ts +++ b/src/util/convenience-functions.spec.ts @@ -12,6 +12,7 @@ import { docPropertiesUniqueNumericId, docPropertiesUniqueNumericIdGen, encodeUtf8, + fitTextUniqueNumericId, hashedId, uniqueId, uniqueNumericIdCreator, @@ -86,6 +87,14 @@ describe("Utility", () => { }); }); + describe("#fitTextUniqueNumericId", () => { + it("should keep counting down below 0 across calls instead of restarting", () => { + const first = fitTextUniqueNumericId(); + expect(first).to.be.below(0); + expect(fitTextUniqueNumericId()).to.equal(first - 1); + }); + }); + describe("#uniqueId", () => { it("should generate a unique pseudorandom ID", () => { expect(uniqueId()).to.not.be.empty; diff --git a/src/util/convenience-functions.ts b/src/util/convenience-functions.ts index bfc0faa0db..82e09ab668 100644 --- a/src/util/convenience-functions.ts +++ b/src/util/convenience-functions.ts @@ -166,6 +166,25 @@ export const bookmarkUniqueNumericIdGen = (): UniqueNumericIdCreator => uniqueNu */ export const bookmarkUniqueNumericId: UniqueNumericIdCreator = bookmarkUniqueNumericIdGen(); +const fitTextUniqueNumericIdGen = uniqueNumericIdCreator(); + +/** + * Returns the next ID for text fitted to a width on its own (`w:fitText`), from a single counter shared by every run. + * + * Word fits runs one after the other with the same ID together, and runs without one unreliably, so a run fitted + * without a group is given an ID no other run has. The IDs count down from -1, as Word's own are negative, so they + * don't meet the groups people give, which count up. + * + * @returns A negative number no earlier call has returned + * + * @example + * ```typescript + * const first = fitTextUniqueNumericId(); // -1 + * const second = fitTextUniqueNumericId(); // -2 + * ``` + */ +export const fitTextUniqueNumericId: UniqueNumericIdCreator = (): number => -fitTextUniqueNumericIdGen(); + /** * Generates a unique lowercase alphanumeric ID using nanoid. *