Microsoft 365 OneDrive for Business: Create PDF

Overview

Microsoft 365 OneDrive for Business: Create PDF

Microsoft 365 OneDrive for Business: PDF作成

This process converts files on OneDrive to PDF for data item.

Auto Step icon
Configs for this Auto Step
conf_OAuth2
C1: OAuth2 Setting *
conf_Url
C2: URL of the file to be convert to PDF *
conf_FileName
C3: File name of the PDF file in data item *#{EL}
conf_FileData
C4: Data item to save the PDF file *
Script (click to open)

// OAuth2 config sample at [OAuth 2.0 Setting]
// - Authorization Endpoint URL: https://login.microsoftonline.com/common/oauth2/v2.0/authorize
// - Token Endpoint URL: https://login.microsoftonline.com/common/oauth2/v2.0/token
// - Scope: https://graph.microsoft.com/Files.ReadWrite.All offline_access
// - Consumer Key: (Get by Microsoft Azure Active Directory)
// - Consumer Secret: (Get by Microsoft Azure Active Directory)

// グローバル変数
const GRAPH_URI = "https://graph.microsoft.com/v1.0/";

/**
  * PDFファイルに変換してダウンロード
  *   参考)https://learn.microsoft.com/ja-jp/graph/api/driveitem-get-content-format?view=graph-rest-1.0
  */

main();
function main(){
  //// == 工程コンフィグの参照 / Config Retrieving ==
  const oauth2 = configs.getObject("conf_OAuth2");
  const fileUrl = retrieveFileUrl();
  const fileName = configs.get("conf_FileName");
  const fileDataDef = configs.getObject("conf_FileData");

  //// == ワークフローデータの参照 / Data Retrieving ==
  const files = engine.findData( configs.getObject("conf_Url") );
  if (files === null) {
    engine.setData(fileDataDef, [""]);
    return;
  }

  //// == 演算 / Calculating ==
  // ファイルURLよりファイル情報を取得 / Get file information from file URL
  const fileInfo = getFileInfoByUrl( fileUrl, oauth2 );

  // APIよりPDFファイルを取得 / Get PDF files from API
  const httpResponse = downloadPDFFileRequest(fileInfo, oauth2);

  // データ項目が空の場合、変数を初期化 / If data item is empty, initialize variable.
  let filesAttached = engine.findData( fileDataDef ); // java.util.ArrayList
  if( filesAttached === null ) {
    engine.log( "AutomatedTask FilesArray {C4} (empty)" );
    filesAttached = new java.util.ArrayList();
  }else{
    engine.log( "AutomatedTask FilesArray {C4}: " + filesAttached.size() + " files" );
  }

  // データ項目にレスポンスデータをセット / Set response data to data items
  const fileTmp = new com.questetra.bpms.core.event.scripttask.NewQfile(
                   fileName, httpResponse.getContentType(), httpResponse.getResponse()
                  );
  filesAttached.add( fileTmp );

  engine.setData( fileDataDef , filesAttached );
}

/**
  * configからファイルURLの値を読み出す
  * @return {String} configの値
  */
function retrieveFileUrl() {
  const fileUrlDef = configs.getObject( "conf_Url" );
  let fileUrl;
  if ( fileUrlDef === null ) {
    fileUrl = configs.get( "conf_Url" )
  }else{
    fileUrl = engine.findData( fileUrlDef );
  }
  if ( fileUrl === "" || fileUrl === null){
    throw "File URL is empty."
  }
  return fileUrl;
}

/**
  * フォルダの URL からファイル情報(ドライブ ID とファイル ID)を取得し、
  * オブジェクトで返す(URL が空の場合はエラーとする)
  * @param {String} fileUrl  フォルダの URL
  * @param {String} oauth2  OAuth2 設定
  * @return {Object} fileInfo  ファイル情報 {driveId, fileId}
  */
function getFileInfoByUrl( fileUrl, oauth2 ) {
  let fileInfo;
  if ( fileUrl !== "" && fileUrl !== null ) {
    // 分割代入
    const {
      id,
      parentReference: {
        driveId
      }
    } = getObjBySharingUrl( fileUrl, oauth2 );
    fileInfo = {driveId: `drives/${driveId}`, fileId: id};
  }
  return fileInfo;
}

/**
  * OneDrive のドライブアイテム(ファイル、フォルダ)のメタデータを取得し、JSON オブジェクトを返す
  * API の仕様:https://docs.microsoft.com/ja-jp/onedrive/developer/rest-api/api/shares_get?view=odsp-graph-online
  * @param {String} sharingUrl  ファイルの共有 URL
  * @param {String} oauth2  OAuth2 設定
  * @return {Object} responseObj  ドライブアイテムのメタデータの JSON オブジェクト
  */
function getObjBySharingUrl( sharingUrl, oauth2 ) {
  if (sharingUrl === "" || sharingUrl === null) {
    throw `Sharing URL is empty.`;
  }

  // encoding sharing URL
  const encodedSharingUrl = encodeSharingUrl(sharingUrl);

  // API Request
  const response = httpClient.begin()
    .authSetting( oauth2 )
    .get( `${GRAPH_URI}shares/${encodedSharingUrl}/driveItem` );

  const responseStr = logAndJudgeError(response, "GET");

  return JSON.parse( responseStr );
}

/**
  * 共有URLをunpadded base64url 形式にエンコードする
  * @param {String} sharingUrl  共有 URL
  * @return {String} encodedSharingUrl  エンコードされた共有 URL
  */
function encodeSharingUrl( sharingUrl ) {
  let encodedSharingUrl = base64.encodeToUrlSafeString( sharingUrl );
  while ( encodedSharingUrl.slice(-1) === '=' ) {
    encodedSharingUrl = encodedSharingUrl.slice(0,-1);
  }
  return `u!${encodedSharingUrl}`;
}

/**
  * FileInfoを元にPDFファイル形式で指定ファイルを取得する
  * @param {String} fileInfo  ダウンロード元アイテム情報 {driveId, id}
  * @param {String} oauth2  OAuth2 認証設定
  * @return {HttpResponseWrapper} response  レスポンス
  */
function downloadPDFFileRequest(fileInfo, oauth2) {
  // Request PATH
  const apiUri = `${GRAPH_URI}${fileInfo.driveId}/items/${fileInfo.fileId}/content?format=pdf`;

  // API Request
  const response = httpClient.begin() // HttpRequestWrapper
    .authSetting( oauth2 ) // Request HEADER (OAuth2 Token)
    .get( apiUri ); // HttpResponseWrapper
  const httpStatus = response.getStatusCode();
  if (httpStatus >= 300) {
    const accessLog = `---GET request--- ${httpStatus}\n${response.getResponseAsString()}\n${fileInfo.driveId}\n${fileInfo.fileId}\n${apiUri}`;
    engine.log(accessLog);
    throw `Failed to download for PDF File. status: ${httpStatus}`;
  }
  return response;
}

/**
  * ログの出力と、エラー発生時のスローを行う
  * @param {HttpResponseWrapper} response  リクエストの応答
  * @param {String} requestType リクエストをどの形式で行ったか("GET" or "POST" or "PATCH")
  * @return {String} responseStr レスポンスの文字列
  */
function logAndJudgeError(response, requestType){
  const responseStr = response.getResponseAsString();
  const status = response.getStatusCode();
  if(status >= 300){
    const accessLog = `---${requestType} request--- ${status}\n${responseStr}\n`;
    engine.log(accessLog);
    throw `Failed in ${requestType} request. status: ${status}`;
  }
  return responseStr;
}

Download

warning Freely modifiable JavaScript (ECMAScript) code. No warranty of any kind.
(Installing Addon Auto-Steps are available only on the Professional edition.)

Notes

Capture

See also

Discover more from Questetra Support

Subscribe now to keep reading and get access to the full archive.

Continue reading