星期五, 4月 10, 2026

[GAS] Google Doc 轉為 PDF

GAS 內可以透過 getAs() 把 Google Doc 轉換為 PDF

限制
gs code
/**
 * 將指定的 Google Doc 文件轉換為 PDF,並儲存到指定的 Google Drive 資料夾中
 *
 * @param {string} documentId - 欲轉換的 Google Doc 檔案 ID
 * @param {string} folderId - 儲存 PDF 的目標資料夾 ID
 * @returns {string} 新建立的 PDF 檔案 URL
 * @throws {Error} 當缺少必要參數、找不到檔案、權限不足或轉換失敗時拋出錯誤
 */
function convertDocToPdf(documentId, folderId) {

  if (!documentId || !folderId) {
    throw new Error("執行失敗:必須同時提供 documentId (文件 ID) 與 folderId (目標資料夾 ID)。");
  }

  try {
    // 1. 透過 ID 取得指定的 Google 文件
    const docFile = DriveApp.getFileById(documentId);

    // 2. 將檔案轉換為 PDF 格式的 Blob (二進位大型物件)
    const pdfBlob = docFile.getAs(MimeType.PDF);

    // 3. 設定產出的 PDF 檔名 (預設為原檔名加上 .pdf)
    const newFileName = `${docFile.getName()}.pdf`;
    pdfBlob.setName(newFileName);

    // 4. 取得目標資料夾實體,並在該資料夾內直接建立 PDF 檔案
    const folder = DriveApp.getFolderById(folderId);
    const newPdfFile = folder.createFile(pdfBlob);
    return newPdfFile.getUrl();

  } catch (error) {
    throw new Error(`PDF 轉換程序發生錯誤: ${error.message}`);
  }
}
執行
function testConvertDocToPdf() {
  const targetDocumentId = "1x17o_MEpEU-S2jKzFhdVqfQ3bswGVPKf2ottem8TSRE"; 
  const targetFolderId = "1Odq3pbNO63RxXmrxWNM9vSGWuGWyBmbZ";

  try {
    const pdfUrl = convertDocToPdf(targetDocumentId, targetFolderId);
    console.log(`轉換完成!PDF 檔案已儲存至指定資料夾,連結請見: ${pdfUrl}`);
  } catch (error) {
    console.error(error);
  }
}

沒有留言:

張貼留言