无法在谷歌文档查看器中嵌入 .doc、docx 文件

Nja*_*iyo 5 php jquery google-docs-api

我有将文件嵌入页面并在 Google Docs Viewer 中打开的代码。但到目前为止,当我想打开 .doc 或 docx 文件时,我得到“无预览可用”,但在打开 PDF 文件时可以正确打开。再次提示我不是在 Google Docs 中打开文件而是下载文件而不是在浏览器上查看它。

这是我的代码:

<a href="sample.doc"  class="embed"><h2>sample.doc</h2><button >view document</button></a>
<script>
    $(document).ready(function() {
      $('a.embed').gdocsViewer({width:740,height:742});
      $('#embedURL').gdocsViewer();
    });
</script>
Run Code Online (Sandbox Code Playgroud)

这是我的 jQuery 插件:

(function($){
    $.fn.gdocsViewer = function(options) {

        var settings = {
            width  : '600',
            height : '700'
        };

        if (options) { 
            $.extend(settings, options);
        }

        return this.each(function() {
            var file = $(this).attr('href');
            var ext = file.substring(file.lastIndexOf('.') + 1);

            if (/^(tiff|doc|ppt|pps|pdf|docx)$/.test(ext)) {
                $(this).after(function () {
                    var id = $(this).attr('id');
                    var gdvId = (typeof id !== 'undefined' && id !== false) ? id + '-gdocsviewer' : '';
                    return '<div id="' + gdvId + '" class="gdocsviewer"><iframe src="http://docs.google.com/viewer?embedded=true&url=' + encodeURIComponent(file) + '" width="' + settings.width + '" height="' + settings.height + '" style="border: none;margin : 0 auto; display : block;"></iframe></div>';
                })
            }
        });
    };})( jQuery );
Run Code Online (Sandbox Code Playgroud)

jos*_*mmo 8

注意:请阅读完整的答案,包括下面的编辑

Google Docs Viewer 似乎工作得很好。出于测试目的,我使用了此文档:http : //homepages.inf.ed.ac.uk/neilb/TestWordDoc.doc

直接从新选项卡访问https://docs.google.com/viewer?embedded=true&url=http%3A%2F%2Fhomepages.inf.ed.ac.uk%2Fneilb%2FTestWordDoc.doc 会导致标准的 Google 文档查看器没有问题。

从 iframe 内部测试它的工作方式相同:

<iframe src="https://docs.google.com/viewer?embedded=true&url=http%3A%2F%2Fhomepages.inf.ed.ac.uk%2Fneilb%2FTestWordDoc.doc" frameborder="no" style="width:100%;height:160px"></iframe>
Run Code Online (Sandbox Code Playgroud)

综上所述,

Google 在 Docs Viewer 中没有任何改变。我的猜测是您没有在 href 标签中使用绝对 URL。因此,在您的代码中,将第一行更改为如下所示:

<a href="http://www.yourwebsite.com/directory/sample.doc" class="embed"><h2>sample.doc</h2><button >view document</button></a>ç
Run Code Online (Sandbox Code Playgroud)

编辑

如果之前的代码对您不起作用,请尝试使用更新的 Google Drive 查看器,将 iframe 代码替换为:

<iframe src="https://docs.google.com/viewerng/viewer?url=YOUR_DOCUMENT_URL"></iframe>
Run Code Online (Sandbox Code Playgroud)

编辑 2 (2019)

Google Docs Viewer 似乎有一半的时间加载文档,在这些情况下必须重新加载 iframe,直到它正确显示。因此,最好使用 Office Web Apps Viewer 作为替代方案:

<a href="http://www.yourwebsite.com/directory/sample.doc" class="embed"><h2>sample.doc</h2><button >view document</button></a>ç
Run Code Online (Sandbox Code Playgroud)


Rey*_*cia 1

Google 文档查看器似乎不再工作了。Google 现在使用Drive Rest API,文档需要转换为 google 格式。

如果你想嵌入谷歌文档文件。转到“文件”->“发布到 Web”并选择“嵌入”选项。它将生成嵌入片段代码。