docx
docx copied to clipboard
WidthType.PERCENTAGE doesn't work for tables in Google Docs or Apple Pages
When creating the following table using percent widths it works fine in Word but doesn't in Google Docs or Apple Pages:
const fs = require('fs');
const {execSync} = require('child_process');
const {
Document,
Packer,
Paragraph,
Table,
TableCell,
TableRow,
WidthType
} = require('docx');
const dxaWidthTable = new Table({
width: {
size: 100,
type: WidthType.PERCENTAGE,
},
columnWidths: [3505, 5505],
rows: [
new TableRow({
children: [
new TableCell({
width: {
size: 3505,
type: WidthType.DXA,
},
children: [new Paragraph('Hello')],
}),
new TableCell({
width: {
size: 5505,
type: WidthType.DXA,
},
children: [],
}),
],
}),
new TableRow({
children: [
new TableCell({
width: {
size: 3505,
type: WidthType.DXA,
},
children: [],
}),
new TableCell({
width: {
size: 5505,
type: WidthType.DXA,
},
children: [new Paragraph('World')],
}),
],
}),
],
});
const percentWidthTable = new Table({
width: {
size: 100,
type: WidthType.PERCENTAGE,
},
columnWidths: [90, 10],
rows: [
new TableRow({
children: [
new TableCell({
width: {
size: 90,
type: WidthType.PERCENTAGE,
},
children: [new Paragraph('Hello')],
}),
new TableCell({
width: {
size: 10,
type: WidthType.PERCENTAGE,
},
children: [],
}),
],
}),
new TableRow({
children: [
new TableCell({
width: {
size: 90,
type: WidthType.PERCENTAGE,
},
children: [],
}),
new TableCell({
width: {
size: 10,
type: WidthType.PERCENTAGE,
},
children: [new Paragraph('World')],
}),
],
}),
],
});
const doc = new Document({
sections: [
{
children: [
new Paragraph({ text: 'Table with DXA widths' }),
dxaWidthTable,
new Paragraph({ text: 'Table with percentage widths' }),
percentWidthTable,
],
},
],
});
const fileName = `/tmp/test-${(new Date().getTime()).toString(36)}.docx`;
(async () => {
const buffer = await Packer.toBuffer(doc);
fs.writeFileSync(fileName, buffer);
execSync(`open ${fileName}`);
execSync(`open -a /Applications/Pages.app ${fileName}`);
})();
The result looks like this:

Node.js: 14.17.5 docx: v 7.3.0
Bonjour :)
Very known issue. Best explanation is in here, I think: https://github.com/dolanmiu/docx/issues/349