mirror of
https://github.com/dolanmiu/docx.git
synced 2026-11-30 16:47:55 +01:00
@@ -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);
|
||||
});
|
||||
File diff suppressed because one or more lines are too long
@@ -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
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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
|
||||
* <xsd:complexType name="CT_FitText">
|
||||
* <xsd:attribute name="val" type="s:ST_TwipsMeasure" use="required"/>
|
||||
* <xsd:attribute name="id" type="ST_DecimalNumber" use="optional"/>
|
||||
* </xsd:complexType>
|
||||
* ```
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* createFitText({ width: 1440, group: 1 });
|
||||
* ```
|
||||
*/
|
||||
export const createFitText = ({ width, group }: IFitTextOptions): XmlComponent =>
|
||||
new BuilderElement<IFitTextAttributes>({
|
||||
name: "w:fitText",
|
||||
attributes: {
|
||||
val: { key: "w:val", value: Math.round(universalMeasureToTwips(twipsMeasureValue(width))) },
|
||||
id: { key: "w:id", value: group === undefined ? fitTextUniqueNumericId() : decimalNumber(group) },
|
||||
},
|
||||
});
|
||||
@@ -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";
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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.")] } },
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user