Adobe PDF Services #ASSET: Download

Adobe PDF Services #ASSET: Download

translate Adobe PDF Services #ASSET: ダウンロード

Downloads ASSET file stored in the internal storage for PDF Services. It is also possible to get the file size and Content-Type. The default file name is the process ID and the extension is automatically added.

Auto Step icon
Configs for this Auto Step
AuthzConfU1
U1: Select Authz for PDF-SERVICES-API Client ID (Fixed Value) *
AuthzConfU2
U2: Select Authz for PDF-SERVICES-API Client Secret (FixedValue) *
StrConfA1
A1: Set AssetID *#{EL}
SelectConfB1
B1: Select FILE that stores Asset File (update) *
SelectConfB2
B2: Select NUMERIC that stores Size of Asset in Byte (update)
SelectConfB3
B3: Select STRING that stores Content-Type of Asset (update)
StrConfU3
U3: Set {regionCode} to process in a specified region (“ew1”)#{EL}
SelectConfB1b
B1b: Select FILE that stores Asset File (append)
StrConfC1
C1: To save-as, Set new File Name#{EL}
Script (click to open)
// GraalJS standard mode Script Script (engine type: 3)
// cf. 'engine type: 2': "GraalJS Nashorn compatible mode" (renamed from "GraalJS" at 20230526)

//////// START "main()" /////////////////////////////////////////////////////////////////

main();
function main(){ 

////// == Config Retrieving / 工程コンフィグの参照 ==
const strAuthzId          = configs.get( "AuthzConfU1" );       /// REQUIRED
  engine.log( " AutomatedTask Config: Authz ID: " + strAuthzId );
  const strClientId       = httpClient.getOAuth2Token( strAuthzId );
  if (  strClientId     === "" ){
    throw new Error( "\n AutomatedTask ConfigError:" +
                     " Config {U1: ClientId} is empty \n" );
  }
const strAuthzSecret      = configs.get( "AuthzConfU2" );       /// REQUIRED
  engine.log( " AutomatedTask Config: Authz SECRET: " + strAuthzSecret );
  const strClientSecret   = httpClient.getOAuth2Token( strAuthzSecret );
  if (  strClientSecret === "" ){
    throw new Error( "\n AutomatedTask ConfigError:" +
                     " Config {U2: ClientSecret} is empty \n" );
  }
const strRegionCode       = configs.get( "StrConfU3" );         // Not Required
  let strRegionPostfix    = strRegionCode !== "" ? ("-" + strRegionCode) : "";
  engine.log( " AutomatedTask Config: strRegionPostfix: " + strRegionPostfix );
  // https://developer.adobe.com/document-services/docs/overview/pdf-services-api/howtos/service-region-configuration-for-apis/
const strAssetId          = configs.get( "StrConfA1" );         /// REQUIRED

const filesPocketUpdate = configs.getObject( "SelectConfB1" ); // NotRequired
  let filesUpdate       = new java.util.ArrayList();
const filesPocketAppend = configs.getObject( "SelectConfB1b" ); // NotRequired
  let filesAppend       = new java.util.ArrayList();
  if ( filesPocketAppend !== null ) {
    if ( engine.findData( filesPocketAppend ) !== null ) {
      filesAppend       = engine.findData( filesPocketAppend ); // java.util.ArrayList
      engine.log( " AutomatedTask FilesArray {B1b}: " +
                  filesAppend.size() + " files" );
    }
  }
const numPocketSize        = configs.getObject( "SelectConfB2" );  // Not Required
const strPocketContentType = configs.getObject( "SelectConfB3" );  // Not Required
let   strSaveAs            = configs.get( "StrConfC1" );           // NotRequired
if ( strSaveAs === "" ) {
  strSaveAs = processInstance.getProcessInstanceId().toString();
}


////// == Data Retrieving / ワークフローデータの参照 ==
// (Nothing. Retrieved via Expression Language in Config Retrieving)



////// == Calculating / 演算 ==

//// Adobe Developer > PDF Services API > Generate Token
//// Generate access token to perform PDF Services operations
//// https://developer.adobe.com/document-services/docs/apis/#tag/Generate-Token

/// prepare request1
let request1Uri = "https://pdf-services" + strRegionPostfix + ".adobe.io/token";
let request1 = httpClient.begin(); // HttpRequestWrapper
/// prepare application/x-www-form-urlencoded
    request1 = request1.formParam ( "client_id",     strClientId );
    request1 = request1.formParam ( "client_secret", strClientSecret );

/// try request1
const response1     = request1.post( request1Uri ); // HttpResponseWrapper
engine.log( " AutomatedTask ApiRequest1 Start: " + request1Uri );
const response1Code = response1.getStatusCode() + ""; // JavaNum to string
const response1Body = response1.getResponseAsString();
engine.log( " AutomatedTask ApiResponse1 Status: " + response1Code );
if( response1Code !== "200"){
  throw new Error( "\n AutomatedTask UnexpectedResponseError: " +
                    response1Code + "\n" + response1Body + "\n" );
}
/* engine.log( response1Body ); // debug
{
  "access_token":"xxxxxxxxxx975yyyyyyyyyy",
  "token_type":"bearer",
  "expires_in":86399
}
*/

/// parse response1 (OAuth Server-to-Server)
const response1Obj = JSON.parse( response1Body );
const strAccessToken = response1Obj.access_token;


//// Adobe Developer > PDF Services API > Assets
//// Get download pre-signed URI.
//// https://developer.adobe.com/document-services/docs/apis/#tag/Assets/operation/asset.get

/// prepare request2
let request2Uri = "https://pdf-services" + strRegionPostfix + ".adobe.io/assets/" +
                   strAssetId;
let request2 = httpClient.begin(); // HttpRequestWrapper
/// prepare header parameters
    request2 = request2.bearer ( strAccessToken );
    request2 = request2.header ( "x-api-key", strClientId );

/// try request2
const response2     = request2.get ( request2Uri ); // HttpResponseWrapper
engine.log( " AutomatedTask ApiRequest2 Start: " + request2Uri );
const response2Code = response2.getStatusCode() + ""; // JavaNum to string
const response2Body = response2.getResponseAsString();
engine.log( " AutomatedTask ApiResponse2 Status: " + response2Code );
if( response2Code !== "200"){
  throw new Error( "\n AutomatedTask UnexpectedResponseError: " +
                    response2Code + "\n" + response2Body + "\n" );
}
/* engine.log( response2Body ); // debug
{
  "type":"image/jpeg",
  "size":257519,
  "downloadUri":"https://dcplatformstorageservice-prod-us-east-1.s3-accelerate.amazonaws.com/xxxxx850yyyyy"
  // X-Amz-Security-Token=... X-Amz-Algorithm=... X-Amz-Date=... X-Amz-SignedHeaders=host
  // X-Amz-Expires=3600 X-Amz-Credential=... X-Amz-Signature=... 
}
*/

/// parse response2
const response2Obj   = JSON.parse( response2Body );
const strDownloadUri = response2Obj.downloadUri;
const numSize        = response2Obj.size;
const strContentType = response2Obj.type;


//// SET File Name
strSaveAs = user_correctFileExtension ( strSaveAs, strContentType );


//// GET API call
// Downloading the asset
// https://developer.adobe.com/document-services/docs/overview/pdf-services-api/gettingstarted/#step-5--downloading-the-asset

/// prepare request3
let request3Uri = strDownloadUri;
let request3 = httpClient.begin(); // HttpRequestWrapper

/// try request3
const response3     = request3.get ( request3Uri ); // HttpResponseWrapper
engine.log( " AutomatedTask ApiRequest3 Start: " + request3Uri );
const response3Code = response3.getStatusCode() + ""; // JavaNum to string
engine.log( " AutomatedTask ApiResponse3 Status: " + response3Code );
if( response3Code !== "200"){
  throw new Error( "\n AutomatedTask UnexpectedResponseError: " +
                    response3Code + "\n" + response3.getResponseAsString() + "\n" );
}

/* 
// debug
let jarrHeaders = response3.getHeaderNames();
for ( let j = 0; j < jarrHeaders.size() - 0 ; j++ ) {
  engine.log( " " + jarrHeaders.get(j) + ": " +
              response3.getHeaderValues(jarrHeaders.get(j)).get(0) );
}
 Content-Type: image/jpeg
 Content-Length: 257519
 Connection: keep-alive
 x-amz-id-2: /WmNxZ6bT8oI6llv+sL4CLw3sSG28E8fGP82o3teUUPmNnD8/3XZJqcfNT3YcsJlB7n9BXEM3dM=
 x-amz-request-id: 8N4EKAQ20WE38E55
 Date: Mon, 03 Jul 2023 06:31:19 GMT
 Last-Modified: Mon, 03 Jul 2023 05:52:49 GMT
 x-amz-expiration: expiry-date="Wed, 05 Jul 2023 00:00:00 GMT", rule-id="YTNmNmJlMTktM2U4YS00NDhhLTkyNzEtNjk1NTc3NGZlMDBj"
 ETag: "ded1380f5a6b28ad2234df5a32fb7008"
 x-amz-server-side-encryption: aws:kms
 x-amz-server-side-encryption-aws-kms-key-id: arn:aws:kms:us-east-1:420533445982:key/d51f5664-5955-44c4-abef-d01808a6c45e
 x-amz-server-side-encryption-bucket-key-enabled: true
 x-amz-version-id: sOXA53Uzkbr0nifTnmrLskShMJHlZBJ6
 Accept-Ranges: bytes
 Server: AmazonS3
 X-Cache: Miss from cloudfront
 Via: 1.1 eddf9e6940bd96929e1096ef63815d52.cloudfront.net (CloudFront)
 X-Amz-Cf-Pop: NRT57-P3
 X-Amz-Cf-Id: 3bXlBBE-SxtaSRuh3dppQLcpuWZtMZdN4Aid4zbmzaJI1QepO6gxqQ==

 Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document
 Content-Length: 14604
 Connection: keep-alive
 x-amz-id-2: icaAogX0Dr+E3zFMkew0PxoZ6sHptQCEg8VYo+MSIkBjXk9v3WglwE/gwJrxwoQy2XVrjn22rYQ=
 x-amz-request-id: A9X9TKH8V2GSQV6V
 Date: Fri, 30 Jun 2023 06:10:00 GMT
 Last-Modified: Thu, 29 Jun 2023 05:20:41 GMT
 x-amz-expiration: expiry-date="Sat, 01 Jul 2023 00:00:00 GMT", rule-id="YTNmNmJlMTktM2U4YS00NDhhLTkyNzEtNjk1NTc3NGZlMDBj"
 ETag: "120d041498437619f2a201fddbe41083"
 x-amz-server-side-encryption: aws:kms
 x-amz-server-side-encryption-aws-kms-key-id: arn:aws:kms:us-east-1:420533445982:key/d51f5664-5955-44c4-abef-d01808a6c45e
 x-amz-server-side-encryption-bucket-key-enabled: true
 x-amz-version-id: UZFC9SQ605UZwc.A_LIXqN1liO3MW3PH
 Accept-Ranges: bytes
 Server: AmazonS3
 X-Cache: Miss from cloudfront
 Via: 1.1 14dae839e44c027b553fbd7cea9e1334.cloudfront.net (CloudFront)
 X-Amz-Cf-Pop: NRT57-P1
 X-Amz-Cf-Id: IyXlGjzW_YAnNpinmT7Q4L6gUcWAQa3HZ_6EGTffUXwj7kvxJjhMig==
*/

const qfileTmp = new com.questetra.bpms.core.event.scripttask.NewQfile(
    strSaveAs, response3.getContentType(), response3.getResponse()
  );
filesUpdate.add( qfileTmp );
filesAppend.add( qfileTmp );


////// == Data Updating / ワークフローデータへの代入 ==

if( filesPocketUpdate !== null ){
  engine.setData( filesPocketUpdate, filesUpdate );
}
if( filesPocketAppend !== null ){
  engine.setData( filesPocketAppend, filesAppend );
}
if( numPocketSize !== null ){
  engine.setData( numPocketSize, new java.math.BigDecimal( numSize ) );
}
if( strPocketContentType !== null ){
  engine.setData( strPocketContentType, strContentType );
}

} //////// END "main()" /////////////////////////////////////////////////////////////////


// Get the default extension for a content-type (PDF Services targetFormat)
/**
 * Corrects the file extension of the provided save-as name, returns a resultant save-as name with correct extension.
 * If the save-as name does not end with an extension, it appends the correct one according to the MIME type of the content.
 *
 * @param {string} strSaveAs - The name to save the file as. Can be with or without extension.
 * @param {string} strContentType - The MIME type of the content. For example, "application/pdf", "image/jpeg", etc.
 *
 * @returns {string} A corrected save-as name with the correct extension, if needed, according to the content type.
 *
 * @example
 * // returns 'document.pdf'
 * user_correctFileExtension('document', 'application/pdf')
 * 
 * @example
 * // returns 'image.jpg'
 * user_correctFileExtension('image', 'image/jpeg')
 * 
 * @example
 * // returns 'image.jpg' - although 'png' is provided, but jpg image type is given, so it corrects the extension
 * user_correctFileExtension('image.png', 'image/jpeg')
 */
function user_correctFileExtension ( strSaveAs, strContentType ){
  const objMime2Extension = {
    'application/pdf': '.pdf',
    'text/html': '.htm',
    'application/zip': '.zip',
    'image/bmp': '.bmp',
    'application/msword': '.doc',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document': '.docx',
    'image/gif': '.gif',
    'image/jpeg': '.jpg',
    'image/png': '.png',
    'application/vnd.ms-powerpoint': '.ppt',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation': '.pptx',
    'application/rtf': '.rtf',
    'image/tiff': '.tif',
    'text/plain': '.txt',
    'application/vnd.ms-excel': '.xls',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': '.xlsx'
  };

  let strExtension = objMime2Extension?.[ strContentType ] ?? "";
  if ( ! strSaveAs.endsWith( strExtension ) ){
    strSaveAs += strExtension;
  }
  return strSaveAs;
}


/*
Notes:
- If you place this "Automated Step" in the Workflow diagram, the request will be automatically sent every time the process token arrives.
    - A request is automatically sent to the Adobe PDF Services API server. (REST API)
    - The response from the Adobe PDF Services API server is automatically parsed.
- This "Automated Step" will automatically download the file (Asset) stored in Adobe's internal storage.
    - Default file name is process id.
        - Filename extensions (.pdf, etc.) are autocompleted.
    - In addition to ASSET files, the following metadata can also be acquired.
        - Size of the file (Asset) in Byte
        - Content-Type of the file (Asset)
- To activate a Workflow App that includes this Automated Step, "HTTP Authz Setting" is required
    - Set Credentials to "Token Fixed Value" in Workflow App.
    - Obtain Credentials ("Client ID" and "Client Secret") in advance.
        - https://acrobatservices.adobe.com/dc-integration-creation-app-cdn/main.html?api=pdf-services-api
    - Adobe Developer Console
        - https://developer.adobe.com/console/projects

APPENDIX
- PDF Services: 
    - Essential PDF tools to store and share files online, as well as create, combine, export, organize, and fill & sign documents.
    - https://helpx.adobe.com/enterprise/using/optional-services.html
- PDF Services API to automate for your document workflows
    - create a PDF from a dynamic HTML report
    - set a password to prevent unauthorized opening of the document
    - compress it for sharing as an attachment
    - extract text, tables, images and document structure to enable downstream solutions
    - https://developer.adobe.com/document-services/docs/overview/#pdf-services-api-to-automate-for-your-document-workflows
- Adobe PDF Services API Free Tier
    - 500 freeDocument Transactions per month. No credit card required. (asof 202306)
    - https://developer.adobe.com/document-services/docs/overview/limits/#usage-limits
- Internal storage retention period
    - Each ASSET is deleted after a certain period of time.
    - AutomatedTask UnexpectedResponseError: 404
    - `{"error":{"code":"Not Found","message":"The requested resource does not exist."}}`

Notes-ja:
- この[自動工程]をワークフロー図に配置すれば、案件が到達する度にリクエストが自動送信されます。
    - Adobe PDF Services API サーバに対してリクエストが自動送出されます。(REST API通信)
    - Adobe PDF Services API サーバからのレスポンスが自動保存解析されます。
- この[自動工程]は、Adobe 内部ストレージに保存されているファイル(Asset)を自動ダウンロードします。
    - Defaultファイル名はプロセスIDです。
        - ファイル名の拡張子(.pdf等)が自動補完されます。
    - ASSETファイル以外に以下のメタデータも取得可能です。
        - 素材ファイル(Asset)のサイズ(Byte)
        - 素材ファイル(Asset)の Content-Type
- この[アドオン自動工程]を含むワークフローアプリを運用するには[HTTP 認証設定]が必要です。
    - Credentials はワークフローアプリの[トークン直接指定]にセットします。
    - あらかじめ Credentials ("Client ID" および "Client Secret") を取得しておいてください。
        - https://acrobatservices.adobe.com/dc-integration-creation-app-cdn/main.html?api=pdf-services-api
    - Adobe Developer Console
        - https://developer.adobe.com/console/projects

APPENDIX-ja
- PDF Servicesとは
    - ファイルのオンラインでの保存、共有のほか、ドキュメントの作成、結合、書き出し、整理、入力と署名を行うための PDF 基本ツールです。
    - https://helpx.adobe.com/jp/enterprise/using/optional-services.html
- Document ワークフローを自動化する PDF Services API
    - 動的 HTML レポートから PDF を簡単に作成
    - ドキュメントが不正に開かれないようにパスワードを設定
    - 添付ファイルとして共有するために圧縮
    - テキスト、表、画像、ドキュメント構造を抽出してダウンストリーム ソリューションを実現
    - https://developer.adobe.com/document-services/docs/overview/#pdf-services-api-to-automate-for-your-document-workflows
- Adobe PDF Services API の無料利用枠
    - 毎月500件の無料ドキュメントトランザクション。クレジットカードは必要なし。(202306現在)
    - https://developer.adobe.com/document-services/docs/overview/limits/#usage-limits
- 内部ストレージの保存期間
    - 各ASSETは、一定時間経過で削除されます。
    - AutomatedTask UnexpectedResponseError: 404
    - `{"error":{"code":"Not Found","message":"The requested resource does not exist."}}`
*/

Download

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

Notes

  • If you place this “Automated Step” in the Workflow diagram, the request will be automatically sent every time the process token arrives.
    • A request is automatically sent to the Adobe PDF Services API server. (REST API)
    • The response from the Adobe PDF Services API server is automatically parsed.
  • This “Automated Step” will automatically download the file (Asset) stored in Adobe’s internal storage.
    • Default file name is process id.
      • Filename extensions (.pdf, etc.) are autocompleted.
    • In addition to ASSET files, the following metadata can also be acquired.
      • Size of the file (Asset) in Byte
      • Content-Type of the file (Asset)
  • To activate a Workflow App that includes this Automated Step, “HTTP Authz Setting” is required

Capture

Adobe PDF Services #ASSET: Download

Appendix

See Also

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: