Skip to content

Instantly share code, notes, and snippets.

@draqoon
Last active November 9, 2020 05:35
Show Gist options
  • Save draqoon/9e5896f735be2cf9b3c17101ced8af8a to your computer and use it in GitHub Desktop.
Save draqoon/9e5896f735be2cf9b3c17101ced8af8a to your computer and use it in GitHub Desktop.
Export Google Spreadsheet to PDF for Google Apps Script
function onOpen() {
SpreadsheetApp.getUi()
.createMenu("マクロ")
.addItem("Export PDF", "exportPDF")
.addToUi();
}
function encodeDate(yy, mm, dd, hh, ii, ss) {
var days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (yy % 4 == 0 && (yy % 100 != 0 || yy % 400 == 0)) days[1] = 29;
for (var i = 0; i < mm; i++) dd += days[i];
yy--;
return (
((((yy * 365 +
(yy - (yy % 4)) / 4 -
(yy - (yy % 100)) / 100 +
(yy - (yy % 400)) / 400 +
dd -
693594) *
24 +
hh) *
60 +
ii) *
60 +
ss) /
86400.0
);
}
function exportPDF() {
const file = SpreadsheetApp.getActiveSpreadsheet();
const sheet = file.getSheets()[0];
const lastRow = sheet.getLastRow();
const lastCol = sheet.getLastColumn();
const exportSource = [
[
sheet.getSheetId().toString(), //シートID
0, // 範囲:開始行(0~)
lastRow, // 範囲:終了行
0, // 範囲:開始列(0~)
lastCol, // 範囲:終了列
],
];
const exportOptions = [
0, // 印刷形式:メモを表示 0:なし 1:あり
null, // (不明)
1, // 印刷形式:グリッド線を表示 0:あり 1:なし
0, // ヘッダーとフッター:ページ番号 0:なし 1:あり
0, // ヘッダーとフッター:ワークブックのタイトル 0:なし 1:あり
0, // ヘッダーとフッター:シート名 0:なし 1:あり
0, // ヘッダーとフッター:現在の日付 0:なし 1:あり
0, // ヘッダーとフッター:現在の時刻 0:なし 1:あり
1, // 行と列の見出し:固定行を繰り返す 0:なし 1:あり
1, // 行と列の見出し:固定列を繰り返す 0:なし 1:あり
2, // ページの印刷順序 1:上から下 2:左から右
1, // (不明)
null, // (不明)
null, // (不明)
1, // 配置:水平 1:左 2:中央 3:右
1, // 配置:垂直 1:上 2:中央 3:下
];
const exportFormat = [
"A4", // 用紙サイズ
0, // ページの向き 0:横向き 1:縦向き
2, // スケール 0:標準(100%) 1:幅に合わせる 2:高さに合わせる 3:ページに合わせる 4:カスタム
1, // スケールで4(カスタム)選択時のパーセント(0~1の範囲)
[
0.75, // 上部オフセット 0.75インチ
0.75, // 下部オフセット 0.75インチ
0.7, // 左オフセット 0.7インチ
0.7, // 右オフセット 0.7インチ
],
];
var today = new Date();
var d = encodeDate(
today.getFullYear(),
today.getMonth(),
today.getDate(),
today.getHours(),
today.getMinutes(),
today.getSeconds()
);
var pc = [
null,
null,
null,
null,
null,
null,
null,
null,
null,
0,
exportSource,
10000000,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
null,
d,
null,
null,
exportOptions,
exportFormat,
null,
0,
null,
0,
];
const ssID = file.getId();
const options = {
method: "post",
payload: "a=true&pc=" + JSON.stringify(pc) + "&gf=[]",
headers: { Authorization: "Bearer " + ScriptApp.getOAuthToken() },
muteHttpExceptions: true,
};
const res = UrlFetchApp.fetch(
"https://docs.google.com/spreadsheets/d/" + ssID + "/pdf?id=" + ssID,
options
);
const resCode = res.getResponseCode();
if (resCode !== 200) {
throw new Error(`(${resCode}) ${res.getContentText()}`);
}
const blob = res.getBlob();
const filename = file.getName() + " " + sheet.getName() + ".pdf"
DriveApp.createFile(blob).setName(filename);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment