2

Download And View PDF document From BTP Document Management Service In SAPUI5

 1 year ago
source link: https://blogs.sap.com/2022/12/08/download-and-view-pdf-document-from-btp-document-management-service/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
December 8, 2022 3 minute read

Download And View PDF document From BTP Document Management Service In SAPUI5

0 2 101

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 .

sdi11.png

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.text()).then((data) => {
          const aItems = [];
          const loopbody = JSON.parse(data);
          loopbody.objects.forEach(body => {
            const a = body.object.properties;
            const b = JSON.stringify(a).replaceAll("cmis:", "");
            const c = JSON.parse(b);
            const docuId = c.objectId.value;
            let docuType = '';
            if (c.hasOwnProperty('contentStreamMimeType')) { docuType = c.contentStreamMimeType.value; }

            const docuName = c.name.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 () {

        // this.getView().getModel()
        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 :

sdi12.png

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

sdi13.png

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

mbt build

cf login

cf deploy mta_archives\sdishowpdf1_0.0.1.mtar

Step 7, Test in BTP cockpit:

sdi14.png
sdi15.png
sdi16.png
sdi17.png

The Ends

Thank you for your time!

Best Regards!

Jacky Liu


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK