问题描述
我想以 pdf 格式下载在谷歌幻灯片中打开的当前页面。 Google 幻灯片允许在他们自己的用户界面中将整个演示文稿下载为 PDF,但我有兴趣一张一张地下载演示文稿中的幻灯片。
现在我可以选择当前页面,
export const getCurrentPage = () => {
return SlidesApp.getActivePresentation()
.getSelection()
.getCurrentPage();
};
此函数返回一个 Page Class。
问题是我不知道如何将这个“页面类”转换为 PDF 并下载它。我已经检查了可用的方法,但还没有找到任何有用的东西。有什么建议吗?
解决方法
@Luke 提到的
Save Google Slide as PDF using Google Apps Script 将整个幻灯片文件转换为 PDF 并将其保存到您的 Google Drive。如果您想在本地计算机上下载特定幻灯片,可以参考示例代码。
示例代码:
function onOpen() {
// get the UI for the Spreadsheet
const ui = SlidesApp.getUi();
// add the menu
const menu = ui.createMenu("Download")
.addItem("Download Current Slide",'downloadModal')
.addToUi();
}
function downloadModal() {
var pdfFile = convertToPdf();
//Get the pdf file's download url
var html = "<script>window.open('" + pdfFile.getDownloadUrl() + "');google.script.host.close();</script>";
var userInterface = HtmlService.createHtmlOutput(html)
.setHeight(10)
.setWidth(100);
SlidesApp.getUi().showModalDialog(userInterface,'Downloading PDF ... ');
//Delete pdf file in the drive
pdfFile.setTrashed(true);
}
function convertToPdf() {
//Get current slide
var presentation = SlidesApp.getActivePresentation();
var slide = presentation.getSelection().getCurrentPage().asSlide();
Logger.log(slide.getObjectId());
//Create temporary slide file
var tmpPresentation = SlidesApp.create("tmpFile");
//Delete default initial slide
tmpPresentation.getSlideById("p").remove();
//Add current slide to the temporary presentation
tmpPresentation.insertSlide(0,slide);
tmpPresentation.saveAndClose();
//Create a temporary pdf file from the temporary slide file
var tmpFile = DriveApp.getFileById(tmpPresentation.getId());
var pdfFile = DriveApp.createFile(tmpFile.getBlob().setName("slide.pdf"))
//delete temporary slide file
tmpFile.setTrashed(true);
return pdfFile;
}
它有什么作用?
将当前幻灯片转换为 PDF 文件:
- 使用 Page.asSlide() 获取当前幻灯片。
- 创建临时幻灯片文件。选择初始幻灯片并使用 Slide.remove() 将其删除。
注意:
文件中的第一张幻灯片有一个 object id = 'q'
,您可以在浏览器中查看幻灯片 url 中的对象 ID#slide=id.<object id>
- 使用 Presentation.insertSlide(insertionIndex,slide) 将步骤 1 中的当前幻灯片插入到我们的临时幻灯片文件中。保存并关闭
- 从我们的临时幻灯片文件创建一个 pdf 文件。使用 File 获取临时幻灯片的 DriveApp.getFileById(id) 对象,使用 File.getBlob() 获取其 blob。使用 Blob.setName(name) 将 blob 的名称设置为 pdf 文件。使用 DriveApp.createFile(blob) 从 blob 创建 pdf 文件
下载文件:
- 创建一个 custom menu,它会调用
downloadModal()
将当前幻灯片下载到本地计算机中 - 调用
convertToPdf()
以获取 pdf 文件的 File 对象。使用 File.getDownloadUrl() 获取下载网址
- 使用 custom dialog 显示 HTML service 将使用步骤 2 中获得的下载 url 下载文件。
- 使用 File.setTrashed(trashed) 删除 Google Drive 中的 pdf 文件