【问题标题】:How to change font in docx generated by JavaScript function如何更改由 JavaScript 函数生成的 docx 中的字体
【发布时间】:2020-06-24 13:13:27
【问题描述】:

我是一名学生,也是一名学习者。我第一次尝试使用 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 页面格式的样式吗?

【问题讨论】:

    标签: javascript html css xml word


    【解决方案1】:

    我遇到了同样的问题。

    From documentation改变字体的标签不是fontFamily,而是font

    运行格式化

    • bolditalicssmallCapsallCapsstrikedoubleStrikesubScriptsuperScript:将格式设置属性设置为 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,我就可以更改字体。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-16
      • 2015-03-07
      • 2018-08-16
      • 1970-01-01
      • 1970-01-01
      • 2015-02-26
      相关资源
      最近更新 更多