Microsoft 365 OneDrive for Business: ファイルを PDF でダウンロード

Microsoft 365 OneDrive for Business: ファイルを PDF でダウンロード

Microsoft 365 OneDrive for Business: Download File as PDF

この工程は、OneDrive 内の指定ファイルを PDF 形式でダウンロードします。

Auto Step icon
Configs for this Auto Step
conf_OAuth2
C1: OAuth2 設定 *
conf_FileUrl
C2: ダウンロードするファイルの URL *
conf_SaveAs
C3: ファイル名(空白の場合、OneDrive でのファイル名を使用します)#{EL}
conf_Files
C4: ダウンロードファイルを追加保存するデータ項目 *
Script (click to open)

// OAuth2 config sample at [OAuth 2.0 Setting]
// - Authorization Endpoint URL: https://login.microsoftonline.com/{your-tenant-id}/oauth2/v2.0/authorize
// - Token Endpoint URL: https://login.microsoftonline.com/{your-tenant-id}/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/';

function main() {
    //// == 工程コンフィグの参照 / Config Retrieving ==
    const oauth2 = configs.getObject('conf_OAuth2');
    const fileUrl = retrieveFileUrl();
    let saveAs = configs.get('conf_SaveAs');
    const filesDef = configs.getObject('conf_Files');

    //// == 演算 / Calculating ==
    const {fileName, driveId, fileId} = getFileInfoByUrl(oauth2, fileUrl);
    const {contentType, content} = downloadPdf(oauth2, driveId, fileId);
    if (saveAs === '') {
        const nameWithoutExtension = fileName.slice(0, fileName.lastIndexOf('.')); // 拡張子を除いたファイル名
        saveAs = `${nameWithoutExtension}.pdf`;
    }

    //// == ワークフローデータへの代入 / Data Updating ==
    saveFile(filesDef, saveAs, contentType, content);
}

/**
  * config からファイル URL の値を読み出す
  * ファイル URL が設定されていない場合はエラー
  * @returns {String} fileUrl ファイル URL
  */
function retrieveFileUrl() {
    const fileUrlDef = configs.getObject('conf_FileUrl');
    let fileUrl = '';
    if (fileUrlDef === null) {
        fileUrl = configs.get('conf_FileUrl');
    } else {
        fileUrl = engine.findData(fileUrlDef);
    }
    if (fileUrl === null || fileUrl === '') {
        throw 'File URL is blank.';
    }
    return fileUrl;
}

/**
  * OneDrive のファイルのメタデータを取得し、JSONオブジェクトを返す
  * APIの仕様: https://docs.microsoft.com/ja-jp/onedrive/developer/rest-api/api/shares_get?view=odsp-graph-online
  * @param {AuthSettingWrapper} oauth2  OAuth2 設定情報
  * @param {String} sharingUrl  ファイルの共有 URL
  * @returns {Object} ファイル情報 {fileName, driveId, fileId}
  */
function getFileInfoByUrl(oauth2, sharingUrl) {
    // encoding sharing URL
    const encodedSharingUrl = encodeSharingUrl(sharingUrl);

    // preparing for API Request
    const response = httpClient.begin()
        .authSetting(oauth2)
        .queryParam('select', 'name,id,parentReference/driveId,file')
        .get(`${GRAPH_URI}shares/${encodedSharingUrl}/driveItem`);
    const status = response.getStatusCode();
    const responseStr = response.getResponseAsString();
    if (status !== 200) {
        engine.log(responseStr);
        throw `Failed to get drive item. status: ${status}`;
    }
    const json = JSON.parse(responseStr);
    if (json.file === undefined) { // フォルダ URL を指定した場合など
        throw 'The specified URL is not a file.';
    }
    const fileName = json.name;
    const driveId = json.parentReference.driveId;
    const fileId = json.id;
    return {fileName, driveId, fileId};
}

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

/**
  * OneDrive のファイルを PDF 形式でダウンロードする
  * APIの仕様: https://learn.microsoft.com/ja-jp/onedrive/developer/rest-api/api/driveitem_get_content_format?view=odsp-graph-online
  * @param {AuthSettingWrapper} oauth2  OAuth2 設定情報
  * @param {String} driveId  ドライブ ID
  * @param {String} fileId  ファイル ID
  * @returns {Object} response
  * @returns {String} response.contentType
  * @returns {ByteArrayWrapper} response.content
  */
function downloadPdf(oauth2, driveId, fileId) {
    const response = httpClient.begin()
        .authSetting(oauth2)
        .queryParam('format', 'pdf')
        .get(`${GRAPH_URI}drives/${driveId}/items/${fileId}/content`);
    const status = response.getStatusCode();
    if (status === 200) { // ドキュメントには記載がないが、直接 200 レスポンスが返ることがある
        return {
            contentType: response.getContentType(),
            content: response.getResponse()
        };
    }
    if (status === 302) { // ドキュメントの記載通り、ダウンロード URL が返る場合
        engine.log('302 Found');
        const downloadUrl = response.getHeaderValues('Location').get(0);
        return download(downloadUrl);
    }
    // 上記いずれのレスポンスステータスでもない場合、エラー
    engine.log(response.getResponseAsString());
    throw `Failed to download pdf format. status: ${status}`;
}

/**
  * ファイルをダウンロードする
  * @param {String} downloadUrl ダウンロード URL
  * @returns {Object} response
  * @returns {String} response.contentType
  * @returns {ByteArrayWrapper} response.content
  */
function download(downloadUrl) {
    const response = httpClient.begin().get(downloadUrl);
    const status = response.getStatusCode();
    if (status !== 200) {
        engine.log(response.getResponseAsString());
        throw `Failed to download. status: ${status}`;
    }
    return {
        contentType: response.getContentType(),
        content: response.getResponse()
    };
}

/**
  * ダウンロードしたファイルを保存する
  * @param {ProcessDataDefinitionView} filesDef  保存先データ項目
  * @param {String} fileName  保存する際のファイル名
  * @param {String} contentType
  * @param {ByteArrayWrapper} content
  */
function saveFile(filesDef, fileName, contentType, content){
    let files = engine.findData(filesDef);
    if (files === null) {
        files = new java.util.ArrayList();
    }
    const qfile = new com.questetra.bpms.core.event.scripttask.NewQfile(
        fileName, contentType, content
    );
    files.add(qfile);
    engine.setData(filesDef, files);
}

    

Download

warning 自由改変可能な JavaScript (ECMAScript) コードです。いかなる保証もありません。
(アドオン自動工程のインストールは Professional editionでのみ可能です)

Notes

  • Microsoft 365 の OneDrive for Business で使用できる自動工程です
    • 個人用の OneDrive では使用できません
  • ファイルやフォルダの URL は、OneDrive でファイルやフォルダの詳細ウィンドウ(右上の情報アイコン)から「その他の詳細」へ進み、「パス」の隣のアイコンから取得します

Capture

上部へスクロール

Questetra Supportをもっと見る

今すぐ購読し、続きを読んで、すべてのアーカイブにアクセスしましょう。

続きを読む