Google Apps Script:如何添加查看已存云端硬盘的表格PDF功能?
Hey there, I’ve dealt with this exact issue before when trying to add PDF previews to Google Sheet scripts—those generic online solutions often miss key details like permission handling or proper Drive preview endpoints. Let’s walk through a reliable, working implementation:
Core Idea
Google Apps Script can’t render PDFs natively, but we can leverage Google Drive’s built-in preview functionality. The trick is to generate a valid preview URL for your saved PDF and either open it in a new tab or embed it directly in a custom sidebar/modal dialog.
Approach 1: Open PDF Preview in a New Browser Tab
This is the simplest method and works for most use cases. Here’s how to modify your existing save function:
function saveSheetAsPDFAndView() { // --- Your existing code to save Sheet as PDF to Drive --- const activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet(); const targetSheet = activeSpreadsheet.getActiveSheet(); // Generate PDF from the sheet const pdfBlob = targetSheet.getAs('application/pdf'); // Save to Drive (adjust folder ID if you want to save to a specific folder) const pdfFile = DriveApp.createFile(pdfBlob); pdfFile.setName(`${targetSheet.getName()}_${new Date().toLocaleDateString()}.pdf`); // --- Add PDF viewing functionality --- const fileId = pdfFile.getId(); // Official Drive preview URL (works for any accessible file) const previewUrl = `https://drive.google.com/file/d/${fileId}/preview`; // Use a tiny modal dialog to trigger opening the preview in a new tab const triggerHtml = HtmlService.createHtmlOutput(` <script> // Open preview in new tab window.open('${previewUrl}', '_blank'); // Close the tiny dialog immediately google.script.host.close(); </script> `).setWidth(100).setHeight(100); SpreadsheetApp.getUi().showModalDialog(triggerHtml, 'Opening PDF...'); }
Approach 2: Embed PDF Preview in a Modal Dialog
If you want users to view the PDF without leaving the Sheet interface, embed it in a modal dialog:
function showPDFPreview(fileId) { const previewUrl = `https://drive.google.com/file/d/${fileId}/preview`; const dialogHtml = HtmlService.createHtmlOutput(` <style> body { margin: 0; padding: 15px; } .pdf-container { width: 100%; height: 80vh; } .close-btn { margin-top: 10px; padding: 8px 16px; cursor: pointer; } </style> <iframe class="pdf-container" src="${previewUrl}" frameborder="0"></iframe> <button class="close-btn" onclick="google.script.host.close()">Close Preview</button> `).setWidth(900).setHeight(650); SpreadsheetApp.getUi().showModalDialog(dialogHtml, 'PDF Preview'); } // Call this from your save function: // showPDFPreview(pdfFile.getId());
Key Notes to Avoid Common Pitfalls
- Permission Checks: Ensure the user running the script has view access to the saved PDF (since it’s created by their account, this is usually automatic, but if saving to a shared folder, double-check permissions).
- Folder Targeting: If you’re saving PDFs to a specific Drive folder instead of the root, use
DriveApp.getFolderById('YOUR_FOLDER_ID').createFile(pdfBlob)instead ofDriveApp.createFile(). - Custom Menu (Optional): Add a menu item to make this function easily accessible:
function onOpen() { const ui = SpreadsheetApp.getUi(); ui.createMenu('PDF Tools') .addItem('Save & View PDF', 'saveSheetAsPDFAndView') .addToUi(); }
Why Generic Online Solutions Fail
Most online snippets either use outdated Drive API endpoints, don’t handle the cross-origin restrictions for embeds, or skip the tiny dialog trigger (browsers block direct window.open() from Apps Script unless it’s initiated by user interaction). The methods above bypass these issues by using Google’s official preview URL and a user-triggered dialog to open the link.
内容的提问来源于stack exchange,提问作者Eric K.

