如何在Google Apps Script Web应用中预览本地PDF文件?
解决Google Apps Script中本地PDF预览被Chrome阻止的问题
你的代码里有两个关键问题导致预览失败:
1. 重复Base64编码
reader.readAsDataURL(file)返回的结果已经是带data:application/pdf;base64,前缀的Base64编码字符串,但你把整个字符串传给loadPdfBytes后又用Utilities.base64Encode再次编码,导致最终生成的data URL完全无效,Chrome无法解析。
2. iframe的type属性拼写错误
你写的是type="appplication/pdf",多了一个字母p,正确写法是type="application/pdf"。
修复后的代码如下:
index.html
<!DOCTYPE html> <html> <head> <base target="_top"> <script> function showFile() { var file = document.getElementById("pick").files[0]; var reader = new FileReader(); reader.onload = function(e) { // 截取data URL中的Base64部分,去掉前缀后传给后端 var base64Content = reader.result.split(',')[1]; google.script.run.withSuccessHandler(showBytes).loadPdfBytes(base64Content); } reader.readAsDataURL(file); } function showBytes(bytes) { var data = "data:application/pdf;base64," + bytes; document.getElementById("preview").setAttribute("src", data); } </script> </head> <body> <input type="file" id="pick" onchange="showFile()"> <iframe type="application/pdf" id="preview" height="300" width="300"></iframe> </body> </html>
Code.gs
function doGet() { return HtmlService.createHtmlOutputFromFile("index").setSandboxMode( HtmlService.SandboxMode.IFRAME); } function loadPdfBytes(content) { // 无需再次编码,直接返回传入的Base64内容 return content; }
额外优化:无需后端直接前端预览
其实完全没必要把文件传到Google Apps Script后端,直接在前端处理就能完成预览,效率更高:
<!DOCTYPE html> <html> <head> <base target="_top"> <script> function showFile() { var file = document.getElementById("pick").files[0]; var reader = new FileReader(); reader.onload = function(e) { // 直接把readAsDataURL的结果赋值给iframe的src document.getElementById("preview").setAttribute("src", reader.result); } reader.readAsDataURL(file); } </script> </head> <body> <input type="file" id="pick" onchange="showFile()"> <iframe type="application/pdf" id="preview" height="300" width="300"></iframe> </body> </html>
内容的提问来源于stack exchange,提问作者Sam JB
相关产品推荐
相关产品推荐

