【GAS】Google Apps Script 活用事例 Spreadsheetを手早くPDFに変換してくれるスクリプト
先日、Twitterで、このブログを読んで(難しかったけれど.....)役に立ったというメッセージを頂き、かなり嬉しかったです。
ライブラリでPDFを生成出来るようにしました
function generatePDF(){
//フォルダの保存先、 印刷したい範囲、 作成したいスプレッドシートのURLを指定
const folderUrl = 'https://drive.google.com/drive/folders/************';
const sheetUrl = 'https://docs.google.com/spreadsheets/d/************';
nepia_infinity.convertSheetToPdf(sheetUrl, 'A1:I19', folderUrl);
}
スクリプトID
18rg2maFYXNmPmB2R-8s3UuFG850j5OLw4WBvcOrghzRMlfVbQWDgOVvZ
ライブラリの + ボタンを押す
上記のスクリプトIDをペーストして検索を押す
追加を押す
Twitter経由で頂いたリクエスト、GASでスプレッドシートをPDF化したい。
function getFolderId_() {
const ui = SpreadsheetApp.getUi();
const response = ui.prompt(
'フォルダのURLを入力してください。',
'(例)https://drive.google.com/drive/folders/************',
ui.ButtonSet.OK
);
const folderId = response.getResponseText().replace(/.*\//, '');
console.log(`folderId: ${folderId}`);
return folderId;
}
function exportAsPDF() {
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
const ssId = spreadsheet.getId();
const sheetId = spreadsheet.getSheetByName('シート名').getSheetId();
const date = new Date();
const today = Utilities.formatDate(date, 'JST', 'yyyy/MM/dd');
const fileName = today + ' test';
const folderId = getFolderId_();
const folder = DriveApp.getFolderById(folderId);
const url = 'https://docs.google.com/spreadsheets/d/'+ ssId +'/export?';
const opts = {
format: 'pdf', // ファイル形式の指定 pdf / csv / xls / xlsx
size: 'A4', // 用紙サイズの指定 legal / letter / A4
portrait: 'true', // true → 縦向き、false → 横向き
fitw: 'true', // 幅を用紙に合わせるか
sheetnames: 'false', // シート名を PDF 上部に表示するか
printtitle: 'false', // スプレッドシート名を PDF 上部に表示するか
pagenumbers: 'false', // ページ番号の有無
gridlines: 'false', // グリッドラインの表示有無
fzr: 'false', // 固定行の表示有無
range : 'A1%3AE30', // 対象範囲「%3A」 = : (コロン)
gid: sheetId // シート ID を指定 (省略する場合、すべてのシートをダウンロード)
};
const urlExt = [];
for(optName in opts){
urlExt.push(optName + '=' + opts[optName]);
}
const options = urlExt.join('&');
const token = ScriptApp.getOAuthToken();
const response = UrlFetchApp.fetch(url + options, {
headers: {
'Authorization': 'Bearer ' + token
}
});
const blob = response.getBlob().setName(fileName + '.pdf');
folder.createFile(blob); // PDFを指定したフォルダに保存
}
こちらはGAS本の著者、高橋さんが運営しているノンプロ研のノンプロ研スニペットから拝借し、一部改変して使っています。
複数枚、一気にPDF出力したい場合は、こちら
Google ドキュメントをPDF化する方法
こちらのページが自分よりさらに丁寧に解説されていました。分かりやすい