我是学生,也是学习者。我第一次尝试使用 JavaScript 制作一个新的 Web 应用程序,但我无法在 JavaScript 生成的 Word 文档中添加字体或更改字体。这是我的代码:
doc.addSection({
properties: {},
children: [
new docx.Paragraph({
children: [
new docx.TextRun({
text: x,
bold: true,
**fontFamily: 'Myfont',**
这里 fontFamily 显示错误: }),
],
}),
],
});
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/docx@5.0.2/build/index.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.js"></script>
<link rel="stylesheet" type="text/css" href="">
<style type="text/css">
@font-face {
font-family: Myfont;
src: url('Myfont2-Regular.ttf');
}
h1 {
font-family: Myfont, sans-serif;
}
</style>
</head>
<body>
<h1>This is my first word document!</h1>
<input type="text" placeholder="Type something..." id="myInput">
<button type="button" onclick="generate()">Click to generate document</button>
<script>
function generate() {
const doc = new docx.Document();
var x = document.getElementById('myInput').value;
doc.addSection({
properties: {},
children: [
new docx.Paragraph({
children: [
new docx.TextRun({
text: x,
bold: true,
fontFamily: 'Myfont',
}),
],
}),
],
});
docx.Packer.toBlob(doc).then(blob => {
console.log(blob);
saveAs(blob, "mydocument.docx");
console.log("Document created successfully");
});
}
</script>
</body>
</html>
是否还有另一种语法,以便我可以设置我的 word 页面格式的样式?
最佳答案
我遇到过同样的问题。
From documentation更改字体的标签不是 fontFamily
但只是font
:
运行格式化
bold
, italics
, smallCaps
, allCaps
, strike
, doubleStrike
, subScript
, superScript
: 将格式属性设置为 true underline({type="single", color=null})
:设置下划线样式和颜色emphasisMark({type="dot"})
: 设置强调标记样式color(color)
: 设置文本颜色,RRGGBB 使用 6 个十六进制字符(无前导 #
)size(halfPts)
: 设置字体大小,以半磅为单位font(name)
或 font({ascii, cs, eastAsia, hAnsi, hint})
: 设置运行字体style(name)
: 应用命名运行样式 characterSpacing(value)
:设置字符间距调整(以TWIP为单位)这是一个代码示例:
new TextRun({
text: "Hello",
bold: true,
font: "Calibri"
})
还要确保使用最新版本的 docx。
我正在使用
docx@5.0.2
一旦我升级到 docx@5.4.1
我能够更改字体。
关于javascript - 如何更改由 JavaScript 函数生成的 docx 中的字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62555920/