0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

GASでスプレッドシートをPDFに変換する

Posted at

①スプレッドを開く
②コードを実行する
③ドライブにPDFが保存される

function savePdf() {
  //PDFの保存先
  //★★★フォルダーIDを入力してください★★★
  let folderId = "フォルダID";

  //アクティブなスプレッドシートを取得する
  let ss = SpreadsheetApp.getActiveSpreadsheet();

  //スプレッドシートIDを取得する
  let ssId = ss.getId();

  //シートIDを取得する
  let shId = ss.getActiveSheet().getSheetId();

  //★★★PDFのファイル名を入力してください★★★
  //※ポイント: ファイル名が重複しないようにしましょう
  let fileName = "pdfファイル名";

  //関数createPdfを実行し、PDFを作成して保存する
  createPdf(folderId, ssId, shId, fileName);
}

//PDFを作成し指定したフォルダーに保存する関数
//以下4つの引数を指定する必要がある
//1: フォルダーID (folderId)
//2: スプレッドシートID (ssId)
//3: シートID (shId)
//4: ファイル名 (fileName)
function createPdf(folderId, ssId, shId, fileName) {
  //PDFを作成するためのベースとなるURL
  let baseUrl = "https://docs.google.com/spreadsheets/d/"
    + ssId
    + "/export?gid="
    + shId;

  //★★★自由にカスタマイズしてください★★★
  //PDFのオプションを指定
  let pdfOptions = "&exportFormat=pdf&format=pdf"
    + "&size=A4" //用紙サイズ (A4)
    + "&portrait=false"  //用紙の向き true: 縦向き / false: 横向き
    + "&fitw=true"  //ページ幅を用紙にフィットさせるか true: フィットさせる / false: 原寸大
    + "&top_margin=0.50" //上の余白
    + "&right_margin=0.50" //右の余白
    + "&bottom_margin=0.50" //下の余白
    + "&left_margin=0.50" //左の余白
    + "&horizontal_alignment=CENTER" //水平方向の位置
    + "&vertical_alignment=TOP" //垂直方向の位置
    + "&printtitle=false" //スプレッドシート名の表示有無
    + "&sheetnames=false" //シート名の表示有無
    + "&gridlines=false" //グリッドラインの表示有無
    + "&fzr=false" //固定行の表示有無
    + "&fzc=false" //固定列の表示有無;

  //PDFを作成するためのURL
  let url = baseUrl + pdfOptions;

  //アクセストークンを取得する
  let token = ScriptApp.getOAuthToken();

  //headersにアクセストークンを格納する
  let options = {
    headers: {
      'Authorization': 'Bearer ' + token
    }
  };

  //PDFを作成する
  let blob = UrlFetchApp.fetch(url, options).getBlob().setName(fileName + '.pdf');

  //PDFの保存先フォルダー
  //フォルダーIDは引数のfolderIdを使用します
  let folder = DriveApp.getFolderById(folderId);

  //PDFを指定したフォルダに保存する
  folder.createFile(blob);

}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?