In my blog Upload rendered PDF document into BTP document manangement service in SAPUI5 Application , the PDF document has been uploaded into  BTP Document Management Service(CMIS). If the user want to download and view the PDF document later, how to realize it in SAPUI5 application?  Today I will explain the precedure in detailed steps.

Prerequisite:

1, You have installed CF Client .

2, You have installed Nodejs .

3,  You have installed  Cloud MTA Build Tool .

4, You have finished  Initial Setup for Document Management Service, Integration Option.

5, You have finished Onboarding Repository.

6, Destination for CMIS service key has been created as step 1 in  blog .

7, You have installed VSCode (optional).

Steps :

Step 1:  Generate SAPUI5 project with easy-ui5 .

 

Step 2, Change the view MainView.view.xml as the following code:

<mvc:View controllerName="com.sap.sdishowpdf1.controller.MainView" 
xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" xmlns:core="sap.ui.core" displayBlock="true" >
    <Page id="page" title="{i18n>title}">
        <content>
          <VBox>
            <HBox>
              <Label id="l1" text="Document Id"/>
              <Select
              id="select"
              showSecondaryValues= "true"
              items="{ path: '/items' }">
              <core:ListItem text="{documentId}" additionalText="{documentName}"/>
            </Select>
            </HBox>
             <Button id="button1" press="pressButton" text="Display Document" />
             <ScrollContainer
             height="100%"
             width="100%"
             horizontal="true"
             vertical="true">
             <FlexBox direction="Column" renderType="Div" class="sapUiSmallMargin">
               <PDFViewer id="pdfview" source="{/Source}" title="{/Title}" height="{/Height}">
                 <layoutData>
                   <FlexItemData growFactor="1" />
                 </layoutData>
               </PDFViewer>
             </FlexBox>
           </ScrollContainer>
          </VBox>
        </content>
    </Page>
</mvc:View>

Step 3, Change the constroller MainView.Controller.js as the following code:

/* eslint-disable no-trailing-spaces */
/* eslint-disable @sap/ui5-jsdocs/no-jsdoc-param */
sap.ui.define(
  ["./BaseController", "sap/m/MessageBox", "sap/base/Log", "sap/ui/model/json/JSONModel", "sap/base/security/URLWhitelist"],
  /**
   * @param {typeof sap.ui.core.mvc.Controller} Controller
   */
  function (Controller, MessageBox, Log, JSONModel, URLWhitelist) {
    "use strict";

    return Controller.extend("com.sap.sdishowpdf1.controller.MainView", {
      onInit: function () {

        const request = new Request('/sdi/browser/f98b60e4-aed8-4e21-bd91-a64f0b3b4df8/root');
        request.headers.append("Content-Type", "application/json");
        fetch(request).then((res) => res.json()).then((data) => {
          const aItems = [];
          data.objects.forEach(objectI => {
            const properties = objectI.object.properties;
            const docuId = properties["cmis:objectId"].value;
            const docuName = properties["cmis:name"].value;
            let docuType = '';
            if (properties.hasOwnProperty('cmis:contentStreamMimeType')) { docuType = properties['cmis:contentStreamMimeType'].value; }

            if (docuType.length !== 0 && docuType === "application/pdf") {
              aItems.push({ "documentId": docuId, "documentName": docuName, "documentType": docuType });
            }
          });
          const oModel = new JSONModel({ items: aItems });
          this.getView().setModel(oModel);
        }).catch((err) => {
          Log.info("failed");
        });
      },
      pressButton: function () {
        const objId = this.byId('select').getSelectedItem().getText();
        const filename = this.byId('select').getSelectedItem().getAdditionalText();
        const urlO = new URL("http://www.sap.com");
        urlO.searchParams.append("cmisselector", "content");
        urlO.searchParams.append("download", "attachment");
        urlO.searchParams.append("filename", filename);
        urlO.searchParams.append("objectId", objId);
        const url = JSON.stringify(urlO).replace('http://www.sap.com', '/sdi/browser/f98b60e4-aed8-4e21-bd91-a64f0b3b4df8/root').replaceAll('"', '');
        const request = new Request(url);
        request.headers.append("Content-Type", "application/json");
        fetch(request).then((res) => res.arrayBuffer()).then((data) => {
          const blob = new Blob([data], { type: "application/pdf" });
          const docurl = URL.createObjectURL(blob);
          this._pdfModel = new JSONModel({
            Source: docurl,
            Title: filename,
            Height: "600px"
          });
          URLWhitelist.add("blob");
          this.byId("pdfview").setModel(this._pdfModel);

          // this.byId("pdf")
        }).catch(err => { console.log(err) });
      }
    });
  }
);

Step 4, Add the following route in the xs-app.json under folder approuter :

Step 5, Adjust nodejs version above 14 according to BTP Cloud Foundry runtime nodejs version .

Step 6, Build the project with following commands step by step:

mbt build

cf login

cf deploy mta_archivessdishowpdf1_0.0.1.mtar

Step 7, Test in BTP cockpit:

Sara Sampaio

Sara Sampaio

Author Since: March 10, 2022

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x