【问题标题】:get docx file contents using javascript/jquery使用 javascript/jquery 获取 docx 文件内容
【发布时间】:2023-11-26 10:59:01
【问题描述】:

希望使用客户端技术 (HTML/JS) 打开/读取 docx 文件。

如果可能,请提供帮助。找到了一个名为 docx.js 的 Javascript 库,但个人似乎找不到任何文档。 (http://blog.innovatejs.com/?p=184)

目标是为 docx 文件和 txt 文件制作一个基于浏览器的搜索工具。

任何帮助表示赞赏。

【问题讨论】:

  • @KennyJohnson 在这里提供的演示似乎不起作用:pinzhang.github.io/docx.js-demo
  • 我很抱歉。我不记得我是否测试过演示。询问者说他找不到任何文件。我记得为文档发布了这个链接,但我现在在那个链接上找不到任何链接。 (这是近 2 年前发布的)。

标签: javascript jquery docx


【解决方案1】:

使用docxtemplater,您可以使用 doc.getFullText() 方法轻松获取单词的全文(仅适用于 docx)。

HTML 代码:

<body>
    <button onclick="gettext()">Get document text</button>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/docxtemplater/3.26.2/docxtemplater.js"></script>
<script src="https://unpkg.com/pizzip@3.1.1/dist/pizzip.js"></script>
<script src="https://unpkg.com/pizzip@3.1.1/dist/pizzip-utils.js"></script>
<script>
    function loadFile(url, callback) {
        PizZipUtils.getBinaryContent(url, callback);
    }
    function gettext() {
        loadFile(
            "https://docxtemplater.com/tag-example.docx",
            function (error, content) {
                if (error) {
                    throw error;
                }
                var zip = new PizZip(content);
                var doc = new window.docxtemplater(zip);
                var text = doc.getFullText();
                console.log(text);
                alert("Text is " + text);
            }
        );
    }
</script>

【讨论】:

  • 感谢您的回复。会调查的。虽然它似乎解决了这个问题。
  • 您的代码不适用于 jszip 版本 3.0.0。你能更新一下吗?
  • Docxtemplater 仍然依赖于 jszip@2.x ,您仍然可以安装它,所以它应该可以工作。在未来的版本中,docxtemplater 将与 JSZip 3.x 一起使用
  • 为什么那个 API 会压缩所有的换行符?
  • 它是这样工作的,只返回一个字符串,或者我们必须使用格式化(字符串数组或 HTML)
【解决方案2】:

我知道这是一篇旧帖子,但 doctemplater 已继续前进,接受的答案不再有效。这对我有用:

function loadDocx(filename) {
  // Read document.xml from docx document
  const AdmZip = require("adm-zip");
  const zip = new AdmZip(filename);
  const xml = zip.readAsText("word/document.xml");
  // Load xml DOM
  const cheerio = require('cheerio');
  $ = cheerio.load(xml, {
    normalizeWhitespace: true,
    xmlMode: true
  })
  // Extract text
  let out = new Array()
  $('w\\:t').each((i, el) => {
    out.push($(el).text())
  })
  return out
}

【讨论】:

  • 救命稻草,谢谢!
  • 这个节点是JS吗?什么是cheerio?
【解决方案3】:

如果您希望能够在 Web 浏览器中显示 docx 文件,您可能会对 Native Documents 最近发布的商业 Word 文件编辑器感兴趣;试试https://nativedocuments.com/test_drive.html

如果你这样做,你将获得更好的布局保真度,而不是尝试转换为 (X)HTML 并以这种方式查看。

它是专门为嵌入 web 应用而设计的,因此有一个用于加载文档的 API,它会很高兴地位于 web 应用的安全上下文中。

披露:我对 Native Documents 有商业利益

【讨论】: