我有将文件嵌入页面并在 Google 文档查看器中打开的代码。但到目前为止,当我想打开 .doc 或 docx 文件时,我收到“无预览可用”的消息,但当我打开 PDF 文件时却可以正确打开。 再次,我没有在 Google 文档中打开文件,而是被提示下载该文件,而不是在浏览器上查看它。
这是我的代码:
<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>
这是我的 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 );
注意:请阅读完整答案,包括下面的编辑
Google 文档查看器似乎工作得很好。出于测试目的,我使用了此文档: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>
Google 没有对文档查看器进行任何更改。我的猜测是您没有在 href 标记中使用 absolute URL。因此,在您的代码中,将第一行更改为如下所示:
<a href="http://www.yourwebsite.com/directory/sample.doc" class="embed"><h2>sample.doc</h2><button >view document</button></a>ç
如果之前的代码不适合您,请尝试使用较新的 Google Drive 查看器,将 iframe 代码替换为以下代码:
<iframe src="https://docs.google.com/viewerng/viewer?url=YOUR_DOCUMENT_URL"></iframe>
Google Docs Viewer 似乎有一半时间会加载文档,在这些情况下必须重新加载 iframe 直到它正确显示。因此,最好使用 Office Web Apps Viewer 作为替代方案:
<iframe src="https://view.officeapps.live.com/op/embed.aspx?src=http%3A%2F%2Fhomepages.inf.ed.ac.uk%2Fneilb%2FTestWordDoc.doc" frameborder="no" style="width:100%;height:500px"></iframe>
Google 文档查看器 似乎不再起作用。 Google 现在使用 Drive Rest API,文档需要转换为 google 格式。
如果您想嵌入谷歌文档文件。转到“文件”->“发布到 Web”并选择“嵌入”选项。它将生成一个嵌入片段代码。
我尝试过将 Google 文档“gview”与 .doc 和 .docx 文件一起使用。当文档在 iFrame 中呈现时,它就是页面 HTML。这是我的代码。
我的技术堆栈是带有 C# 的 ASP.NET Webforms。非常感谢任何帮助!
页面 iframe
<iframe id="DocXIFrame" runat="server"></iframe>
方法代码:
DocXIFrame.Attributes["src"] = "https://docs.google.com/gview?url=https://watersidepoolsportaldev.scm.azurewebsites.net/dev/wwwroot/Documents/Contract.docx&embedded=true";