将 Google 幻灯片导出为图像/PDF - Google Apps 脚本

问题描述 投票:0回答:1

我正在尝试将 google 幻灯片转换为 PDF 或 IMAGE 格式,但我在寻找不到 10 年且仍在工作的解决方案时遇到了很多麻烦。

所以,对于未来的我和其他人,我是这样做的:

image google-apps-script google-slides google-slides-api
1个回答
0
投票

这是我的做法:

无论你选择哪种方式,你都需要添加服务“Google Slides API”!! enter image description here

如果脚本链接到演示文稿,您可以使用以下内容:

PDF版

function toPDF() {
  const folderId = "1-rCYyDgTzOV0FKt2gdh8dtaB1hSi1JN-";
  const presentation = SlidesApp.getActivePresentation();
  const slides = presentation.getSlides();
  let temp = SlidesApp.create("Temporary");
  const id = temp.getId();
  const file = DriveApp.getFileById(id);
  const folder = DriveApp.getFolderById(folderId);
  slides.forEach((slide, i) => {
    temp.appendSlide(slide);
    temp.getSlides()[0].remove();
    temp.saveAndClose();
    folder.createFile(file.getBlob().setName(i + 1));
    temp = SlidesApp.openById(id);
  });
  file.setTrashed(true);
}

用于图像

 function toPNG() {
      const folderId = "1G6E_BZeilLJ1_f36xpwFqlthXblGOI3h";
      const presentation = SlidesApp.getActivePresentation();
      const id = presentation.getId();
      const slides = presentation.getSlides();
      const folder = DriveApp.getFolderById(folderId);
      const options =  {"thumbnailProperties.mimeType": "PNG" };
      slides.forEach((slide, i) => {
        const url = Slides.Presentations.Pages.getThumbnail(
          id, 
          slide.getObjectId(),
          options
         ).contentUrl;
        const blob = UrlFetchApp.fetch(url).getAs(MimeType.PNG);
        folder.createFile(blob.setName(i + 1));
      });
    }

如果您想使用更大脚本中的代码(链接到谷歌幻灯片文档的脚本之外),那么您可以使用以下代码:

对于图像

/**
 * Converts all slides of a Google Slides presentation (specified by its ID) to PNG images
 * and saves them to a specified folder.
 * 
 * @param {string} slideFileId - The ID of the Google Slides presentation to convert.
 * @param {string} folderId - The ID of the folder where the PNG images should be saved.
 */
function convertSlideToPNG(slideFileId, folderId) {
  // Get the specified presentation by its ID
  const presentation = SlidesApp.openById(slideFileId);
  
  // Get all slides in the presentation
  const slides = presentation.getSlides();
  
  // Get the target folder by its ID
  const folder = DriveApp.getFolderById(folderId);
  
  // Define the options to get the slide as PNG
  const options = { "thumbnailProperties.mimeType": "PNG" };

  // Loop through each slide and generate its thumbnail
  slides.forEach((slide, i) => {
    const url = Slides.Presentations.Pages.getThumbnail(
      slideFileId,
      slide.getObjectId(),
      options
    ).contentUrl; // Get the URL for the PNG thumbnail
    
    const blob = UrlFetchApp.fetch(url).getAs(MimeType.PNG); // Fetch the image as PNG
    folder.createFile(blob.setName('Slide_' + (i + 1) + '.png')); // Save the PNG in the folder with a slide-based name
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.