uniquejava / blog

My notes regarding the vibrating frontend :boom and the plain old java :rofl.
Creative Commons Zero v1.0 Universal
11 stars 5 forks source link

Google Docs Viewer #110

Open uniquejava opened 7 years ago

uniquejava commented 7 years ago

想在html5中内置office文档(包括pdf, word,excel等), 解决方案

最终我选择的google docs viewer

see https://gist.github.com/izazueta/4961650

Google Docs Viewer

Only files under 25 MB can be previewed with the Google Drive viewer.

Google Drive viewer helps you preview over 16 different file types, listed below:

Google Docs Viewer (Apps)

https://docs.google.com/a/[DOMINIO]/viewer?url=[FILE_URL]

Google Docs Viewer

https://docs.google.com/a/[DOMINIO]/viewer?url=[FILE_URL]

Office Web Apps Viewer

('.ppt' '.pptx' '.doc', '.docx', '.xls', '.xlsx')

Pantalla completa

http://view.officeapps.live.com/op/view.aspx?src=[OFFICE_FILE_URL]

Incrustado dentro de un 'iframe'

<iframe src='https://view.officeapps.live.com/op/embed.aspx?src=[OFFICE_FILE_URL]' width='px' height='px' frameborder='0'>
</iframe>

Info: http://www.labnol.org/internet/google-docs-viewer-alternative/

uniquejava commented 7 years ago

cyper实战

function useGoogleDocsViewer(filepath) {
  var suffix = filepath.slice(filepath.lastIndexOf('.') + 1);
  if (_.contains(['doc', 'docx', 'xls', 'xlsx', 'pdf'], suffix)) {

    $('#pdfContainer').html('<iframe id="iframe" frameborder="0"></iframe>');
    var protocol = location.protocol;
    var hostname = location.hostname;
    var port = location.port;

    var prefix = protocol + "//" + hostname;
    if (port !== '') {
      prefix += (":" + port);
    }

    var fileurl = prefix + "/api/getFile?token=" + getCookie('token') + "&filepath=" + filepath;
    console.log(fileurl);
    if (hostname === 'localhost') {
      //fileurl = "http://www.research-advisors.com/documents/SampleSize-web.xls";
      // for local test only
      //fileurl = "http://www.redbooks.ibm.com/redbooks/pdfs/sg247877.pdf";
      fileurl = "http://www.careers.wa.gov/assets/documents/Cover%20Letter%20Examples.doc";
    }
    var googledocs_url = "https://docs.google.com/a/mybluemix/viewer?url=" + encodeURIComponent(fileurl) + "&embedded=true";
    console.log(googledocs_url);
    $('#iframe').attr("src", googledocs_url);
    $('#iframe').on('load', function () {
      console.log('loaded!');
      // hide loading indicator here
    });
  } else {
    console.log("Invalid filepath", filepath);
  }

}

给iframe设定的样式

iframe {
  width: 100%;
  height: 380px;
}

注意要加上embedded=true的参数, 不然会报跨域错误. 然后传过去的url要encodeURIComponent(url)不然url中的参数会被误判成google docs中的参数.

refused to display in a frame because it set 'X-Frame-Options' to 'sameorigin'.