Category: UI5

  • Implementing Cookie Settings in SAP UI5

    Introduction

    With the constant evolution of the web and the various platforms that power it, ensuring a seamless user experience is crucial. In SAP UI5, a key component that aids in enhancing this experience is the use of cookies. Through this article, we’ll delve into the realm of cookies in SAP UI5, why they’re essential, and how to set them up for optimal use.

    What is a Cookie and why is it required in SAP UI5?

    A cookie is a small piece of data sent from a website and stored in a user’s web browser. They remember stateful information for the stateless HTTP protocol. In SAP UI5, cookies play an essential role in retaining user preferences, maintaining sessions, or even tracking user interactions, ensuring users don’t have to re-enter preferences every time they revisit an application.

    Client-side Cookies vs. server-side Cookies

    In the realm of web development, cookies can generally be categorized into two types:

    • Client-side Cookies: These are stored on the user’s browser and can be read using JavaScript when the user revisits the site. They are primarily used for local preferences, theme settings, or even short-term tracking.
    • Server-side Cookies: These are processed on the web server and can be read on subsequent HTTP requests made to the server for the same domain. They are mainly utilized for sessions, user authentication, and more persistent tracking.

    In SAP UI5, depending on your requirements, you might lean towards one type of cookie over the other, or even use a combination of both.

    Set cookie and get a cookie with JavaScript in SAP UI5

    Using JavaScript in SAP UI5 to set and retrieve cookies is straightforward.

    Setting a Cookie:

    function setCookie(name, value, days) {
        let expires = "";
        if (days) {
            const date = new Date();
            date.setTime(date.getTime() + (days*24*60*60*1000));
            expires = "; expires=" + date.toUTCString();
        }
        document.cookie = name + "=" + (value || "") + expires + "; path=/";
    }
    

    Usage:

    setCookie("userPreference", "darkTheme", 7);
    

    Getting a Cookie:

    function getCookie(name) {
        const nameEQ = name + "=";
        const cookiesArray = document.cookie.split(';');
        for(let i=0; i < cookiesArray.length; i++) {
            let cookie = cookiesArray[i];
            while (cookie.charAt(0) == ' ') cookie = cookie.substring(1, cookie.length);
            if (cookie.indexOf(nameEQ) == 0) return cookie.substring(nameEQ.length, cookie.length);
        }
        return null;
    }
    

    Usage:

    const userPreference = getCookie("userPreference");
    

     

    Adding Cookies to a Request

    When making AJAX calls in SAP UI5, you might need to send cookies along with your request. Here’s a simple way to do it:

    Using the jQuery ajax method:

    $.ajax({
        url: "https://yourapiendpoint.com/data",
        type: "GET",
        xhrFields: {
            withCredentials: true
        },
        success: function(data) {
            // Handle data here
        }
    });
    

    The withCredentials: true ensures that cookies are sent with the request. Remember that the server also needs to accept credentials from the origin by setting the appropriate CORS headers.

  • How to create introduction guides in SAP UI5

    Introduction

    In modern web applications, ensuring that users understand and navigate through the interface efficiently is paramount. This becomes especially vital in comprehensive platforms like SAP UI5, where complex functionalities and data-driven interfaces are the norms. “How to create introduction guides in SAP UI5” serves as a comprehensive guide to set up intuitive step-by-step onboarding instructions for your SAP UI5 application. From header bars, filters, tables, to footer buttons, this guide elucidates how to create a guided tour, ensuring that users have a clear understanding of each interface element. Dive in to provide your users with a smooth introduction to your UI5 application’s functionalities.

    How to create introduction guides in SAP UI5

    How to create introduction guides in SAP UI5

    To implement the introduction guide along with the described page, you can leverage the sap.m library of SAP UI5 and the sap.ui.core.delegate.ItemNavigation class for the guided introduction. Let’s go step-by-step:

    1. Initial Setup

    Include the required libraries in your XML view:

    xmlns:m="sap.m"
    xmlns:core="sap.ui.core"
    

    2. Setup View with hardcoded data

    <mvc:View controllerName="IntroductionGuides.IntroductionGuides.controller.View1" xmlns:mvc="sap.ui.core.mvc" displayBlock="true"
        xmlns="sap.m" xmlns:core="sap.ui.core">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page title="My Page">
                        <customHeader>
                            <Bar>
                                <contentRight>
                                    <Button text="Profile" id="profileBtn"/>
                                    <Button text="Logout" id="logoutBtn"/>
                                </contentRight>
                            </Bar>
                        </customHeader>
                        <content>
                            <VBox>
                                <!-- Filter Section -->
                                <HBox>
                                    <Input placeholder="Search..." id="searchFilter"/>
                                    <ComboBox>
                                        <core:Item key="1" text="Item 1"/>
                                        <core:Item key="2" text="Item 2"/>
                                    </ComboBox>
                                </HBox>
                                <!-- Table Section -->
                                <Table id="dataTable">
                                    <columns>
                                        <Column width="12em">
                                            <Text text="Product"/>
                                        </Column>
                                        <Column minScreenWidth="Tablet" demandPopin="true">
                                            <Text text="Supplier"/>
                                        </Column>
                                    </columns>
                                    <items>
                                        <ColumnListItem>
                                            <cells>
                                                <Text text="Product 1"/>
                                                <Text text="SupplierName 1"/>
                                            </cells>
                                        </ColumnListItem>
                                    </items>
                                </Table>
                            </VBox>
                        </content>
                        <footer>
                            <Bar id="footerBar">
                                <contentRight>
                                    <Button text="Button 1"/>
                                    <Button text="Button 2"/>
                                </contentRight>
                            </Bar>
                        </footer>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

    3. Build the Page Layout

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/m/Popover"
    ], function (Controller, Popover) {
        "use strict";
    
        return Controller.extend("IntroductionGuides.IntroductionGuides.controller.View1", {
    
            onAfterRendering: function () {
                this.getView().setModel(new sap.ui.model.json.JSONModel({
                    hardcodedData: [ /* your data here */ ],
                    hardcodedFilters: [ /* your filter data here */ ]
                }));
    
                // Start the introduction guide once the UI is rendered
                this.startIntroduction();
            },
    
            startIntroduction: function () {
                var aSteps = [{
                    id: "profileBtn",
                    text: "This is the profile button."
                }, {
                    id: "logoutBtn",
                    text: "Click here to log out."
                }, {
                    id: "searchFilter",
                    text: "Search using this filter."
                }, {
                    id: "comboFilter",
                    text: "Choose filters from this dropdown."
                }, {
                    id: "dataTable",
                    text: "This is your main data table."
                }, {
                    id: "footerBar",
                    text: "Footer contains various operations."
                }];
    
                var iCurrentStep = 0;
    
                var fnShowStep = function () {
                    if (iCurrentStep >= aSteps.length) {
                        // Completed the introduction
                        return;
                    }
    
                    var oControl = this.getView().byId(aSteps[iCurrentStep].id);
                    if (!oControl) {
                        iCurrentStep++;
                        fnShowStep.call(this);
                        return;
                    }
    
                    var oPopover = new Popover({
                        title: "Step " + (iCurrentStep + 1),
                        content: new sap.m.Text({
                            text: aSteps[iCurrentStep].text
                        }),
                        contentWidth: "350px", // set the desired width here
                        placement: sap.m.PlacementType.Bottom, // initially set to show below the control
                        footer: new sap.m.Toolbar({
                            content: [
                                new sap.m.ToolbarSpacer(),
                                new sap.m.Button({
                                    text: "Next",
                                    press: function () {
                                        oPopover.close();
                                        iCurrentStep++;
                                        fnShowStep.call(this);
                                    }.bind(this)
                                })
                            ]
                        })
                    });
    
                    var oControlPosition = oControl.getDomRef().getBoundingClientRect();
                    if (oControlPosition.top > window.innerHeight / 2) {
                        oPopover.setPlacement(sap.m.PlacementType.Top); // if control is in the bottom half of the screen, show popover above it
                    }
    
                    oPopover.openBy(oControl);
                };
    
                fnShowStep.call(this);
            }
    
        });
    });

    The startIntroduction method will contain the logic for showcasing different sections. This logic can use modals, popovers, or tooltips to display guidance text. For brevity, I’ve not implemented the detailed logic in the example, but you can use libraries like Intro.js or write custom logic to guide users through the different sections.

    The general idea is to highlight and provide information for each section, making the UI interactive and user-friendly for new users.

  • How to Display Disclaimer Page for GDPR in SAP UI5?

    Introduction

    Learn the straightforward approach to displaying a GDPR-compliant disclaimer page in SAP UI5. In this guide, we walk you through the steps to create a popup that appears as your application starts, ensuring users read and acknowledge the disclaimer before proceeding. This method, leveraging the sap.m.Dialog and sap.m.VBox controls, is crucial for applications needing to meet GDPR requirements. Follow along to integrate this solution into your SAP UI5 application.

    How to Display Disclaimer Page for GDPR in SAP UI5

    How to Display Disclaimer Page for GDPR in SAP UI5?

    To achieve this in SAP UI5, you can use a Dialog control with a CheckBox inside. Here’s a step-by-step guide to create this functionality:

    1. Add necessary libraries: Ensure you’ve added the following libraries to your SAP UI5 project’s index.html or as per your application structure:

    <script src="resources/sap/m/library.js" id="sap-ui-bootstrap"></script>
    <script src="resources/sap/ui/layout/library.js"></script>
    

     

    2. Create the Disclaimer Dialog: You can add this in your Component.js or App.controller.js‘s onInit function or any initial function that loads as soon as the app starts.

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/m/Dialog",
        "sap/m/Text",
        "sap/m/CheckBox",
        "sap/m/Button"
    ], function(Controller, Dialog, Text, CheckBox, Button) {
        "use strict";
    
        return Controller.extend("your.controller.path", {
            onInit: function() {
                this._showDisclaimer();
            },
    
            _showDisclaimer: function() {
        var oVBox = new sap.m.VBox({
            items: [
                new sap.m.Text({ 
                    text: 'Your GDPR compliance related content here. By continuing to use this application, you accept the data terms and conditions.' 
                }),
                new sap.m.CheckBox({ 
                    text: 'I have read and understood the disclaimer', 
                    selected: false 
                })
            ]
        });
    
        var oDisclaimerDialog = new sap.m.Dialog({
            title: 'Disclaimer',
            content: [oVBox],
            beginButton: new sap.m.Button({
                text: 'Continue',
                enabled: false,  // Disabled initially
                press: function() {
                    oDisclaimerDialog.close();
                    
                    // Logic to save acceptance in the database would be here.
                    
                    // Display the success message
                    sap.m.MessageToast.show("Your acceptance is saved in the database, you will not be asked again!");
                }
            }),
            afterClose: function() {
                oDisclaimerDialog.destroy();
            }
        });
    
        oDisclaimerDialog.open();
    
        // Enabling the continue button only when the checkbox is selected
        oVBox.getItems()[1].attachSelect(function(oEvent) {
            var bSelected = oEvent.getParameter("selected");
            oDisclaimerDialog.getBeginButton().setEnabled(bSelected);
        });
    }
    
        });
    });
    

    The above code snippet places the Text and CheckBox inside a VBox. This VBox is then set as the content of the Dialog. This arrangement ensures a neat vertical alignment of the disclaimer content and the checkbox.

    In the press event of the “Continue” button, right after closing the dialog, the sap.m.MessageToast is used to display a success message. Note that you will need to incorporate the logic to save this acceptance to the database where I have added the comment.

  • Print Full Screen in SAP UI5

    Introduction

    Learn how to print a full screen in SAP UI5 using this straightforward guide. Using HTML and JavaScript, we’ll walk you through the steps to integrate efficient printing capabilities in your SAP UI5 application. Whether it’s an entire page or specific sections, this tutorial ensures you capture the details you need. Enhance your SAP UI5 user experience by adding this practical feature. Thus, you will learn How to print UI5 page.

    Print in SAP UI5 using Windows Function

    To perform a print in SAP UI5 using HTML and JavaScript, you can utilize the `window.print()` method. This method prompts the user to print the current page. You can just use CTRL + P in your keyboard to trigger print in Windows laptops.

    Here’s a simple way to do it:

    1. Create a Button in your XML View:

    <Button text="Print" press="onPrint"/>
    

    2. Define the onPrint function in your Controller:

    onPrint: function() {
        window.print();
    }
    

    When the button is pressed, the `onPrint` function will be executed, and the user will be prompted to print the current page.

    Print in SAP UI5 after converting to Image

    HTML Code:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.3.3/html2canvas.min.js"></script>

    View Code:

    <Button text="Print after converting to Image" press="onPrinCapturet"/>

    Controller Code:

    onPrinCapturet: function () {
                var oPage = this.getView().byId("page"); // Assuming "page" is the id of your main Page or container in the XML view
    
                if (oPage && oPage.getDomRef()) {
                    var oDomElement = oPage.getDomRef();
    
                    html2canvas(oDomElement).then(canvas => {
                        var oImgData = canvas.toDataURL("image/png");
    
                        // Open a new window or iframe and load the image data to print
                        var oPrintWindow = window.open('', '_blank');
                        oPrintWindow.document.write('<img src="' + oImgData + '" onload="window.print();"/>');
                    });
                }
            },

    Print specific content in SAP UI5

    However, if you want to print specific content (not the entire page), you can utilize a hidden `iframe`:

    1. Create a Hidden iFrame in your HTML:

    <iframe id="printFrame" style="display:none;"></iframe>
    

    2. Add the Print Button in the View:

    Add id as “idFrame” to the view.

    <Button text="PrintFrame" press="onPrint"/>
    

    3. JavaScript to load content and print:

    onPrintFrame: function () {
        var oFrame = document.getElementById("printFrame");
        var oContentWindow = oFrame.contentWindow;
        var oDoc = oContentWindow.document;
        // var oViewContent = this.getView().getContent()[0]; // get content of the whole view
        var oViewContent = this.getView().byId("idFrame");  // get content of the vbox view
        var sHtml = oViewContent.getDomRef().outerHTML;
        oDoc.open();
        oDoc.write("<html><head><title>Print Content</title></head><body>");
        // oDoc.write("<h1>This is the content to print</h1>"); // Replace this with the content you want to print
        oDoc.write(sHtml);  // passing the content of the UI5 view
        oDoc.write("</body></html>");
        oDoc.close();
        oContentWindow.print();
    }

    In the example above, the content to print is loaded into the hidden iFrame and then printed. This way, only the specific content (and not the entire UI5 application) gets printed.

    Please note: Printing from a web application can vary based on the browser, so always test your printing function on different browsers to ensure compatibility.

     

    Full Code

    HTML

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>My Project Ideas</title>
            <link rel="icon" type="image/x-icon" href="https://myprojectideas.com/wp-content/uploads/2021/08/cropped-Screenshot-2021-07-26-at-1.39.04-PM.png"/>
            <script id="sap-ui-bootstrap"
                src="resources/sap-ui-core.js"
                data-sap-ui-theme="sap_fiori_3"
                data-sap-ui-resourceroots='{"PrintPage.PrintPage": "./"}'
                data-sap-ui-compatVersion="edge"
                data-sap-ui-oninit="module:sap/ui/core/ComponentSupport"
                data-sap-ui-async="true"
                data-sap-ui-frameOptions="trusted">
            </script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.3.3/html2canvas.min.js"></script>
        </head>
        <body class="sapUiBody">
            <iframe id="printFrame" style="display:none;"></iframe>
            <div data-sap-ui-component data-name="PrintPage.PrintPage" data-id="container" data-settings='{"id" : "PrintPage"}'></div>
        </body>
    </html>
    

     

    View

    <mvc:View controllerName="PrintPage.PrintPage.controller.View1" xmlns:core="sap.ui.core" xmlns:layout="sap.ui.layout"
        xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page">
                        <content>
                            <VBox id="idFrame" justifyContent="Center" alignItems="Center" class="sapUiMediumMargin">
                                <!-- Invoice Heading -->
                                <Title text="Invoice" level="H1" class="sapUiSmallMarginBottom"/>
                                <!-- Invoice Date -->
                                <HBox justifyContent="Center" class="sapUiSmallMarginBottom">
                                    <Label text="Invoice Date:" class="sapUiSmallMarginEnd"/>
                                    <Text text="20.09.2023"/>
                                </HBox>
                                <!-- Company Name -->
                                <HBox justifyContent="Center" class="sapUiSmallMarginBottom">
                                    <Label text="Company Name:" class="sapUiSmallMarginEnd"/>
                                    <Text text="RUDE LABS Pvt Ltd"/>
                                </HBox>
                                <!-- Address -->
                                <HBox justifyContent="Center" class="sapUiSmallMarginBottom">
                                    <Label text="Address:" class="sapUiSmallMarginEnd"/>
                                    <Text text="123, Web Street, Noida, 45678"/>
                                </HBox>
                                <!-- Service Details -->
                                <Title text="Service Details" level="H2" class="sapUiSmallMarginBottom"/>
                                <Table class="sapUiMediumMarginBottom">
                                    <columns>
                                        <Column><Text text="Service Name"/></Column>
                                        <Column><Text text="Description"/></Column>
                                        <Column><Text text="Amount"/></Column>
                                    </columns>
                                    <items>
                                        <ColumnListItem>
                                            <cells>
                                                <Text text="Website Development "/>
                                                <Text text="First Installment"/>
                                                <Text text="1000 USD"/>
                                            </cells>
                                        </ColumnListItem>
                                    </items>
                                </Table>
                                <!-- Total Amount -->
                                <HBox justifyContent="End" class="sapUiSmallMarginBottom">
                                    <Label text="Total Amount:" class="sapUiSmallMarginEnd"/>
                                    <Text text="1000 USD"/>
                                </HBox>
                                <!-- Footer Note -->
                                <Text text="Thank you for doing business with us!" class="sapUiSmallMarginTop"/>
                            </VBox>
                            <Button text="Default Print" press="onPressPrint"/>
                            <Button text="Print after converting to Image" press="onPrinCapturet"/>
                            <Button text="PrintFrame" press="onPrintFrame"/>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    Controller

    sap.ui.define([
        "sap/ui/core/mvc/Controller"
    ], function (Controller) {
        "use strict";
    
        return Controller.extend("PrintPage.PrintPage.controller.View1", {
            onInit: function () {
    
            },
    
            onPrinCapturet: function () {
                var oPage = this.getView().byId("page"); // Assuming "page" is the id of your main Page or container in the XML view
    
                if (oPage && oPage.getDomRef()) {
                    var oDomElement = oPage.getDomRef();
    
                    html2canvas(oDomElement).then(canvas => {
                        var oImgData = canvas.toDataURL("image/png");
    
                        // Open a new window or iframe and load the image data to print
                        var oPrintWindow = window.open('', '_blank');
                        oPrintWindow.document.write('<img src="' + oImgData + '" onload="window.print();"/>');
                    });
                }
            },
    
            onPressPrint: function (oEvent) {
                window.print();
            },
    
            onPrintFrame: function () {
                var oFrame = document.getElementById("printFrame");
                var oContentWindow = oFrame.contentWindow;
                var oDoc = oContentWindow.document;
                // var oViewContent = this.getView().getContent()[0]; // get content of the whole view
                var oViewContent = this.getView().byId("idFrame");  // get content of the vbox view
                // var sHtml = oViewContent.getDomRef().outerHTML;
                oDoc.open();
                oDoc.write("<html><head><title>Print Content</title></head><body>");
                // oDoc.write("<h1>This is the content to print</h1>"); // Replace this with the content you want to print
                oDoc.write(sHtml);  // passing the content of the UI5 view
                oDoc.write("</body></html>");
                oDoc.close();
                oContentWindow.print();
            }
    
        });
    });

     

  • Download excel in SAP UI5 using XLSX JS

    Introduction

    Discover the seamless integration of ‘Download Excel in SAP UI5 using XLSX JS.’ Dive into this comprehensive guide that unveils the step-by-step process to harness the power of XLSX JS, optimizing SAP UI5 applications. Ideal for developers and SAP enthusiasts, this tutorial not only simplifies data exportation into Excel format but also boosts the functionality of your UI5 projects. Stay ahead in the evolving landscape of SAP and enhance your skills with this essential technique.

    What is XLSX/Sheet.js?

    XLSX.js is a JavaScript library that facilitates reading and writing various spreadsheet file formats, including XLSX, which is the format used by modern versions of Microsoft Excel. In essence, it allows developers to handle Excel files (both reading and creating them) directly in JavaScript, making it easier to integrate spreadsheet functionalities in web applications.

    For instance, in the context of SAP UI5 or other web frameworks, XLSX.js can be used to provide users with the ability to download data from the application in Excel format or upload Excel files for processing in the application, all without requiring server-side processing or additional software installations.

    How to Download excel in SAP UI5 using XLSX JS?

    index.html

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>My Project Ideas</title>
            <link rel="icon" type="image/x-icon" href="https://myprojectideas.com/wp-content/uploads/2021/08/cropped-Screenshot-2021-07-26-at-1.39.04-PM.png"/>
            <script id="sap-ui-bootstrap"
                src="resources/sap-ui-core.js"
                data-sap-ui-theme="sap_fiori_3"
                data-sap-ui-resourceroots='{"excelProject.excelProject": "./"}'
                data-sap-ui-compatVersion="edge"
                data-sap-ui-oninit="module:sap/ui/core/ComponentSupport"
                data-sap-ui-async="true"
                data-sap-ui-frameOptions="trusted">
            </script>
            <script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
        </head>
        <body class="sapUiBody">
            <div data-sap-ui-component data-name="excelProject.excelProject" data-id="container" data-settings='{"id" : "excelProject"}'></div>
        </body>
    </html>

     

    View.XML

    <mvc:View controllerName="excelProject.excelProject.controller.Main" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="My Project Ideas: Download Table in Excel">
                        <content>
                        <Button text="Export to Excel" press="onExportToExcel"/>
            <Table id="idProducts">
            <columns>
                <Column
                    width="12em">
                    <Text text="Name" />
                </Column>
                <Column
                    minScreenWidth="Tablet"
                    demandPopin="true">
                    <Text text="City" />
                </Column>
            </columns>
            <items>
                <ColumnListItem vAlign="Middle">
                    <cells>
                        <Text	text="Rudra" />
                        <Text	text="Mughalsarai" />
                    </cells>
                </ColumnListItem>
                <ColumnListItem vAlign="Middle">
                    <cells>
                        <Text	text="Deepak" />
                        <Text	text="Kolkata" />
                    </cells>
                </ColumnListItem>
            </items>
                </Table>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    Controller.Js

    sap.ui.define([
        "sap/ui/core/mvc/Controller"
    ], function (Controller) {
        "use strict";
    
        return Controller.extend("excelProject.excelProject.controller.Main", {
            onInit: function () {
    
            },
    
            onExportToExcel: function () {
                // Get the JSON data
                var rows = [];
            var selection = this.getView().byId('idProducts').getSelectedItems();
            selection.forEach(val => {
            var data = val.getBindingContext().getObject();
            rows.push(data);
            });
    
                // Convert JSON to Excel workbook
                var workbook = XLSX.utils.book_new();
                var worksheet = XLSX.utils.json_to_sheet(rows);
                XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
    
                // Save the workbook as an Excel file
                XLSX.writeFile(workbook, "data.xlsx");
            }
    
        });
    });

     

    Output

    Download excel in SAP UI5 using XLSX JS

  • Planning Calendar in SAP UI5

    Introduction

    The SAP UI5 Planning Calendar is a powerful, feature-rich tool that aids in visualizing, scheduling, and managing appointments or tasks efficiently. Designed to be user-friendly and intuitive, the Planning Calendar offers an overview of appointments or tasks over various views, including hours, days, 1 week, 1 month, or even a custom-defined timeline.

    Key features of the Planning Calendar include the ability to display appointments over different intervals, support for both single and multiple row layouts, various appointment types, and built-in controls for navigating between different intervals. It is designed with flexibility in mind and can be adapted to handle a variety of use cases. Appointments can be selected, resized, or moved according to your needs, and the overall look and feel of the calendar can be customized as well.

    In addition to these, the Planning Calendar also offers built-in support for handling different time zones, special dates like holidays or non-working days, and it even supports screen readers for accessibility.

    Whether you’re developing an employee scheduling app, a project management tool, a room booking system, or any other application where time-bound events need to be visualized and managed, the SAP UI5 Planning Calendar can be a great asset. It simplifies complex scheduling tasks, improves productivity, and delivers a superior user experience, aligning perfectly with SAP’s philosophy of helping the world run better.

    In the next sections, we will delve deeper into how to use and customize the SAP UI5 Planning Calendar, enriching it with our application-specific data and functionality.

    Why we need Planning Calendar in SAP UI5

    In any organization or business application, managing time and events efficiently is crucial to achieving goals and maintaining order. This is where the SAP UI5 Planning Calendar comes into play. Here are a few reasons why it’s needed:

    1. Ease of use: With its user-friendly interface, the SAP UI5 Planning Calendar simplifies the task of creating, viewing, and managing appointments. It provides an intuitive visualization of events, which allows users to grasp their schedules quickly.

    2. Flexibility: The SAP UI5 Planning Calendar is flexible and can be adapted to a variety of use cases. Whether it’s managing employee schedules, tracking project timelines, or scheduling room bookings, the Planning Calendar can be customized to fit your needs.

    3. Rich Feature Set: The SAP UI5 Planning Calendar comes packed with features such as support for different intervals (hours, days, 1 week, 1 month), different appointment types, and multiple row layouts. This allows the calendar to cater to a wide range of scheduling requirements.

    4. Efficiency: It improves efficiency by reducing the time and effort needed to schedule and reschedule appointments or tasks. Users can easily select, resize, or move appointments according to their needs.

    5. Consistency: By using the Planning Calendar in SAP UI5, you maintain consistency with other SAP applications. This allows for a seamless user experience across all your business applications.

    6. Accessibility: The Planning Calendar in SAP UI5 is designed with accessibility in mind, with built-in support for screen readers. This ensures that the tool can be used by people with diverse abilities, adhering to inclusivity standards.

    7. Customization: The look and feel of the calendar can be tailored according to your needs, enabling you to maintain the branding and aesthetics of your application.

    8. Integration: It seamlessly integrates with other SAP UI5 controls and services, making it a robust choice for applications built on the SAP platform.

    In summary, the SAP UI5 Planning Calendar provides a robust, user-friendly, and efficient way to handle scheduling tasks in your applications.

    How to develop Planning Calendar in SAP UI5

    View

    <mvc:View controllerName="PlanningCalendar.PlanningCalendar.controller.Main" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m"
        xmlns:unified="sap.ui.unified">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="My Project Ideas: Planning Calendar in SAP UI5">
                        <content>
                            <Button text="Block for Next Meeting" press="onPressBlock"/>
                            <PlanningCalendar id="planningCalendar" startDate="{path: '/startDate'}" rows="{path: '/rows'}" appointmentsVisualization="Filled"
                                appointmentSelect="handleAppointmentSelect" showEmptyIntervalHeaders="false" showWeekNumbers="true">
                                <rows>
                                    <PlanningCalendarRow startDate="{startDate}" appointments="{appointments}">
                                        <appointments>
                                            <unified:CalendarAppointment resizable="true" startDate="{startDate}" endDate="{endDate}" title="{title}" text="{text}" type="{type}"
                                                resize="handleAppointmentResize"/>
                                        </appointments>
                                    </PlanningCalendarRow>
                                </rows>
                            </PlanningCalendar>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    Controller

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/ui/model/json/JSONModel",
        'sap/m/MessageBox',
        'sap/ui/core/date/UI5Date'
    ], function (Controller, JSONModel, MessageBox, UI5Date) {
        "use strict";
    
        return Controller.extend("PlanningCalendar.PlanningCalendar.controller.Main", {
            onInit: function () {
                var currentDate = new Date();
                var oData = {
                    startDate: new Date(),
                    rows: [{
                        startDate: new Date(),
                        appointments: [{
                            startDate: new Date(),
                            endDate: new Date(currentDate.getTime() + (3 * 60 * 60 * 1000)),
                            title: "Meeting with SAP",
                            text: "Discuss project status",
                            type: "Type01",
                            pic: "sap-icon://sap-ui5",
                        }]
                    }]
                };
    
                var oModel = new JSONModel(oData);
                this.getView().setModel(oModel);
            },
    
            handleAppointmentSelect: function (oEvent) {
                var oAppointment = oEvent.getParameter("appointment"),
                    sSelected;
                if (oAppointment) {
                    sSelected = oAppointment.getSelected() ? "selected" : "deselected";
                    MessageBox.show("'" + oAppointment.getTitle() + "' " + sSelected);
                } else {
                    var aAppointments = oEvent.getParameter("appointments");
                    var sValue = aAppointments.length + " Appointments selected";
                    MessageBox.show(sValue);
                }
            },
    
            onPressBlock: function (oEvent) {
                var currentDate = new Date();
                var oData = {
                    startDate: new Date(),
                    rows: [{
                        startDate: new Date(),
                        appointments: [{
                            startDate: new Date(),
                            endDate: new Date(currentDate.getTime() + (3 * 60 * 60 * 1000)),
                            title: "Meeting with SAP",
                            text: "Discuss project status",
                            type: "Type01",
                            pic: "sap-icon://sap-ui5",
                        }, {
                            startDate: new Date(currentDate.getTime() + (3 * 60 * 60 * 1000)),
                            endDate: new Date(currentDate.getTime() + (6 * 60 * 60 * 1000)),
                            title: "Next Meeting with SAP",
                            text: "Discuss Next Meeting",
                            type: "Type02",
                            pic: "sap-icon://sap-ui5",
                            tentative: false
                        }]
                    }]
                };
    
                var oModel = new JSONModel(oData);
                this.getView().setModel(oModel);
            }
        });
    });

     

    Output

    Planning Calendar in SAP UI5

  • Developing Analytic Map using SAP UI5

    Introduction

    Discover the world of data visualization in an engaging and interactive way with our comprehensive guide on “Developing Analytic Map using SAP UI5”. Explore how to harness the power of SAP UI5, a highly efficient JavaScript framework, to create visually striking and informative analytic maps that transform raw data into meaningful insights.

    In this article, we delve into the step-by-step process of creating analytic maps, providing clear instructions and expert tips to help you effectively illustrate complex data sets. Whether you’re monitoring logistics, tracking global sales, or studying demographic trends, analytic maps present data in a geographic context, allowing for a more intuitive understanding and smarter decision-making process.

    Unlock the potential of geo-spatial data visualization and learn how to create dynamic, interactive maps with SAP UI5. This guide is perfect for developers seeking to enhance their skills, as well as businesses striving for a data-driven approach to achieve their goals. Let’s chart your path to successful data visualization.

    What is an Analytic Map?

    An Analytic Map is a type of data visualization that combines geographical data with quantitative data to provide insights in a visually compelling way. The primary goal of analytic maps is to help interpret and analyze patterns, trends, and correlations in data that may otherwise go unnoticed in a standard table or chart.

    In an analytic map, data is typically represented through various colors, symbols, or sizes of specific regions or points on the map. For instance, in a global sales report, the sales volume for each country can be represented by different colors, with darker shades indicating higher sales.

    These maps can be interactive, allowing users to zoom in and out, hover over specific regions to get more details, and even click on parts of the map to navigate to other reports or sections of the data.

    Analytic maps are particularly useful in a wide range of fields including business intelligence, public health, environmental studies, transportation planning, and many more. They help in understanding spatial relationships and geographic patterns in data, thereby aiding in more informed decision-making.

    Uses of Analytic Map in SAP UI5

    Analytic Maps in SAP UI5 open up a whole world of possibilities when it comes to data visualization and analysis. They can be used in various ways to provide spatial context to data, and deliver insights in an engaging and interactive way. Here are some of the primary uses:

    1. **Geospatial Data Visualization**: With SAP UI5, you can present your data in a geographical context, such as sales performance across different regions or tracking shipments in real-time.

    2. **Business Intelligence**: Analytic maps are a powerful tool in business intelligence, allowing businesses to visually compare data across different locations, track changes over time, and identify patterns and trends.

    3. **Interactive User Experience**: SAP UI5 analytic maps are interactive, enabling users to zoom in and out, hover over regions to get more details, and click on map points to navigate to other reports or sections of the data. This enriches the user experience, making data exploration more intuitive and engaging.

    4. **Real-Time Tracking**: For industries that rely on real-time location data, such as logistics, transportation, and supply chain management, SAP UI5 analytic maps can provide live updates and visual tracking.

    5. **Customization**: SAP UI5 provides the flexibility to customize the appearance and functionality of your maps according to your specific requirements. You can alter colors, shapes, sizes, and labels to best represent your data.

    6. **Integration with SAP Systems**: Given that SAP UI5 is a part of the larger SAP ecosystem, analytic maps can easily be integrated with other SAP applications and tools, allowing for seamless data flow and advanced analytics.

    Remember, the key to successfully leveraging analytic maps lies in understanding your data and knowing what story you want to tell. With SAP UI5, you’re equipped with a powerful tool that can transform your data into meaningful, actionable insights.

    Developing Analytic Map using SAP UI5

    View

    <mvc:View controllerName="geoMap.geoMap.controller.Main" xmlns:mvc="sap.ui.core.mvc" xmlns:l="sap.ui.layout" displayBlock="true"
        xmlns="sap.m">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="{i18n>title}">
                        <content>
                            <l:VerticalLayout id="mapContainer" width="100%"/>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    Controller

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/ui/vbm/AnalyticMap",
        "sap/ui/vbm/Spot",
    ], function (Controller, AnalyticMap, Spot) {
        "use strict";
    
        return Controller.extend("geoMap.geoMap.controller.Main", {
            onInit: function () {
                var oMapView = new AnalyticMap({
                    width: "100%"
                });
                this.getView().byId("mapContainer").addContent(oMapView);
                var oSpot = new Spot({
                    "position": "77.1024902;28.7040592;0", // Replace with actual coordinates
                    "tooltip": "Delhi",
                    "type": "Success",
                    "text": "Delhi"
                });
    
                var oSpot2 = new Spot({
                    "position": "-74.013327;40.705395;0", // Replace with actual coordinates
                    "tooltip": "New York",
                    "type": "Inactive",
                    "text": "New York"
                });
    
                var oSpots = new sap.ui.vbm.Spots({
                    items: [oSpot, oSpot2]
                });
    
                oMapView.addVo(oSpots);
    
            }
        });
    });

     

    Output

    Developing Analytic Map using SAP UI5

  • VizFrame Chart in UI5 using local JSON or OData

    Introduction

    Introduction to VizFrame Chart in SAP UI5 using Local JSON or OData:

    VizFrame is a powerful data visualization control in SAP UI5 that empowers developers to create stunning charts and graphs for displaying data in a user-friendly and interactive manner. With VizFrame, you can visualize data from various sources, including local JSON and OData services. This introduction will explore how VizFrame can be leveraged to create dynamic and visually appealing charts using data from local JSON or OData services.

    1. Local JSON Data Source:
    Local JSON serves as an ideal data source for small to medium-sized datasets that are readily available within the application without the need for server-side communication. By utilizing the JSONModel in SAP UI5, developers can easily bind the local JSON data to the VizFrame control, allowing seamless data visualization directly within the application.

    2. OData Service Data Source:
    For larger datasets or real-time data, SAP UI5 offers integration with OData services. OData provides a standardized way to interact with remote data sources, enabling the VizFrame chart to visualize live data fetched from an external service. Leveraging the ODataModel, developers can efficiently connect the VizFrame chart to the OData service and automatically update the visualization as the data changes in the backend.

    Key Features of VizFrame Chart:
    – **Rich Chart Types:** VizFrame offers a wide range of chart types, including column charts, line charts, pie charts, bar charts, and more. You can select the most suitable chart type to present your data effectively.

    – **Interactive and Responsive:** VizFrame charts come with interactive features such as zooming, panning, and tooltips, providing users with a dynamic and engaging experience. The charts are responsive and adapt gracefully to various screen sizes and devices.

    – **Data Binding and Aggregation:** Whether using local JSON or OData services, VizFrame seamlessly binds data to the chart, allowing you to leverage data aggregation to summarize and group information for a clearer presentation.

    – **Customization and Theming:** Developers can easily customize the appearance of VizFrame charts by adjusting colors, labels, axis properties, and more. SAP UI5’s theming capabilities enable charts to harmonize with the overall application design.

    – **Integration with Other UI5 Controls:** VizFrame can be seamlessly integrated with other UI5 controls to build comprehensive and feature-rich analytical dashboards and applications.

    In conclusion, VizFrame in SAP UI5 is a versatile and user-friendly charting solution that enables developers to create visually compelling data visualizations using local JSON or OData services. By leveraging the power of VizFrame, developers can transform raw data into meaningful insights, empowering users to make informed decisions and gain valuable insights from their data.

    Important Terms to Understand

    In SAP UI5, the concept of Model, FlattenedDataset, and FeedItem is related to data visualization using VizFrame controls. VizFrame is a versatile UI5 control that allows you to create various types of charts and graphs for data representation.

    1. Model:
    A Model in SAP UI5 is an abstraction of data that allows you to access and manipulate data in a consistent way. It is a data binding concept that separates the control logic from the data. The Model provides a standard API to interact with the data, irrespective of the data source. There are various types of models, such as JSONModel, ODataModel, etc., which can be used based on the data source and requirements.

    2. FlattenedDataset:
    The FlattenedDataset is a specialized dataset used by VizFrame controls to represent data in a flattened format suitable for visualization. It takes tabular data and converts it into a format that can be easily understood by charts and graphs. The FlattenedDataset provides configuration options for defining dimensions (e.g., categories, groups) and measures (e.g., values, quantities) of the chart.

    3. FeedItem:
    The FeedItem is used in conjunction with the FlattenedDataset to define the mapping between the dimensions and measures of the FlattenedDataset and the corresponding axes of the chart. It defines which dimensions should be represented on which axis and which measures should be used for different aspects of the chart (e.g., axis values, colors, sizes).

    4. addFeed:
    In the context of VizFrame, addFeed is a method used to associate FeedItems with the FlattenedDataset. By adding FeedItems to the FlattenedDataset, you define how the data should be visualized in the chart. For example, you can specify that a particular dimension should be shown on the X-axis, or a certain measure should be used to determine the color of the chart elements.

    In summary, when using VizFrame for data visualization in SAP UI5, you create a FlattenedDataset to convert your tabular data into a suitable format for charting. You then use FeedItems to map dimensions and measures from the FlattenedDataset to specific aspects of the chart. Finally, you add these FeedItems to the FlattenedDataset using the addFeed method, allowing you to visualize the data in a meaningful and informative way.

    VizFrame Chart in UI5 using local JSON or OData

    View

    <mvc:View controllerName="vizChartJSON.vizChartJSON.controller.Main" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m"
        xmlns:viz="sap.viz.ui5.controls" xmlns:viz.feeds="sap.viz.ui5.controls.common.feeds">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="My Project Ideas: VizFrame Chart in UI5 using local JSON or OData">
                        <content>
                            <RadioButtonGroup id='datasetRadioGroup'>
                                <buttons>
                                    <RadioButton class='settingsRadio' text="Line" select="onDatasetSelectedLine"/>
                                    <RadioButton class='settingsRadio' text="Column" select="onDatasetSelecteColumn"/>
                                    <RadioButton class='settingsRadio' text="Bullet" select="onDatasetSelecteBullet"/>
                                    <RadioButton class='settingsRadio' text="Area" select="onDatasetSelecteArea"/>
                                </buttons>
                            </RadioButtonGroup>
                            <viz:VizFrame id="chartContainer" vizType="line" width="600px" height="400px"/>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    Controller

    sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/viz/ui5/data/FlattenedDataset",
        "sap/viz/ui5/controls/common/feeds/FeedItem"
    ], function (Controller, FlattenedDataset, FeedItem) {
        "use strict";
    
        return Controller.extend("vizChartJSON.vizChartJSON.controller.Main", {
            onInit: function () {
                var data = [{
                    "Category": "Category 1",
                    "Revenue": 100
                }, {
                    "Category": "Category 2",
                    "Revenue": 200
                }, {
                    "Category": "Category 3",
                    "Revenue": 300
                }, {
                    "Category": "Category 4",
                    "Revenue": 400
                }, {
                    "Category": "Category 5",
                    "Revenue": 500
                }];
                // Load local JSON data
                var oDataModel = new sap.ui.model.json.JSONModel(data);
                // Use this line in case you are loading from external OData url
                // oDataModel.loadData(data);
    
                // Get the VizFrame control
                var oChartContainer = this.getView().byId("chartContainer");
    
                // Set the data model to the VizFrame
                oChartContainer.setModel(oDataModel);
    
                // Create a FlattenedDataset
                var oDataset = new FlattenedDataset({
                    dimensions: [{
                        name: "Category",
                        value: "{Category}"
                    }],
                    measures: [{
                        name: "Revenue",
                        value: "{Revenue}"
                    }],
                    data: {
                        path: "/"
                    }
                });
    
                // Add the dataset to the VizFrame
                oChartContainer.setDataset(oDataset);
    
                // Create a FeedItem for Category dimension
                var oCategoryFeed = new FeedItem({
                    uid: "categoryAxis",
                    type: "Dimension",
                    values: ["Category"]
                });
    
                // Create a FeedItem for Revenue measure
                var oRevenueFeed = new FeedItem({
                    uid: "valueAxis",
                    type: "Measure",
                    values: ["Revenue"]
                });
    
                // Add the FeedItems to the VizFrame
                oChartContainer.addFeed(oCategoryFeed);
                oChartContainer.addFeed(oRevenueFeed);
            },
            
            onDatasetSelectedLine: function(oEvent){
                this.byId("chartContainer").setVizType('line');
            },
            
            onDatasetSelecteColumn: function(oEvent){
                this.byId("chartContainer").setVizType('column');
            },
            
            onDatasetSelecteBullet: function(oEvent){
                this.byId("chartContainer").setVizType('bullet');
            },
            
            onDatasetSelecteArea: function(oEvent){
                this.byId("chartContainer").setVizType('area');
            }
        });
    });

     

    Output

    VizFrame Chart in UI5 using local JSON or OData

  • Convert PDF to Text in SAP UI5 using PDF.js

    Introduction

    Discover the power of PDF.js in our comprehensive guide to transforming PDF files into readable text within the SAP UI5 framework. As digital data continues to proliferate, the need for seamless data conversion and extraction increases. Leveraging the power of PDF.js, we will unravel the process of converting complex PDF files into simple text directly in your SAP UI5 applications. This powerful JavaScript library brings PDF rendering capabilities to your browser, making it easier than ever to parse and extract data from PDF files.

    Whether you’re a seasoned SAP UI5 developer or just beginning your journey, this guide offers a practical, step-by-step process for implementing PDF.js in your applications. From installation to implementation, we’ve got you covered. Improve your SAP UI5 skill set, enhance your applications, and unlock new possibilities with PDF.js today. Let’s dive into the world of PDF to text conversion in SAP UI5 with PDF.js.

    What is PDF.js

    PDF.js is a robust, open-source JavaScript library developed by Mozilla. It is used to parse and render PDF files directly in a web browser. One of its primary features is its ability to maintain the high fidelity of the original PDF file, including its fonts, vector graphics, and images.

    CDN for PDF.js: cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.min.js

    The library offers a wide range of functionalities. For instance, it allows developers to highlight text within the PDF, search for specific text, and zoom in or out of the document. PDF.js can also be used to convert PDF files into other formats such as text or images, which is especially useful when you need to extract or manipulate the content of PDF files programmatically.

    By leveraging the power of modern web standards like HTML5 and JavaScript, PDF.js ensures a seamless, platform-independent solution that works across various devices and operating systems. As a result, it’s used in numerous applications and projects around the world, including the Firefox browser, where it’s used as the default PDF viewer.

    How to convert PDF to Text using PDF.js using JavaScript

    To convert PDF to Text using PDF.js with JavaScript, you can follow these steps:

    1. First, you need to include the PDF.js library in your project. You can download it from the official GitHub repository and include it in your HTML file.

    2. Load your PDF file using the ‘getDocument’ function. This function returns a promise that is resolved with a PDFDocumentProxy object.

    3. Once you have the PDFDocumentProxy object, you can call the ‘getPage’ function to get a particular page (let’s assume the first page). This function also returns a promise that is resolved with a PDFPageProxy object.

    4. Now, you can call the ‘getTextContent’ function on the PDFPageProxy object. This function returns a promise that is resolved with a TextContent object.

    5. The TextContent object has an array called ‘items’ which contains the individual text items of the page. You can loop through this array and concatenate all the strings to get the full text of the page.

    6. Repeat steps 3 to 5 for all pages in the PDF document.

    Please note that these are the general steps. Depending on your specific project and setup, there might be some variations in how you apply them. You will need to have a good understanding of JavaScript and Promises to work with PDF.js effectively.

    Also note that text extraction with PDF.js might not always be perfect. Due to the way PDF files are structured, sometimes the order of the text can get mixed up, or some characters might not get extracted correctly.

    Convert PDF to Text in SAP UI5 using PDF.js

    Index.html

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>My Project Ideas</title>
            <link rel="icon" type="image/x-icon" href="https://myprojectideas.com/wp-content/uploads/2021/08/cropped-Screenshot-2021-07-26-at-1.39.04-PM.png"/>
            <script id="sap-ui-bootstrap"
                src="resources/sap-ui-core.js"
                data-sap-ui-theme="sap_fiori_3"
                data-sap-ui-resourceroots='{"pdfUploader.pdfUploader": "./"}'
                data-sap-ui-compatVersion="edge"
                data-sap-ui-oninit="module:sap/ui/core/ComponentSupport"
                data-sap-ui-async="true"
                data-sap-ui-frameOptions="trusted">
            </script>
                <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.min.js"></script>
        </head>
        <body class="sapUiBody">
            <div data-sap-ui-component data-name="pdfUploader.pdfUploader" data-id="container" data-settings='{"id" : "pdfUploader"}'></div>
        </body>
    </html>

    View

    <mvc:View controllerName="pdfUploader.pdfUploader.controller.Main" xmlns:mvc="sap.ui.core.mvc" xmlns:u="sap.ui.unified" displayBlock="true"
        xmlns="sap.m">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="My Project Ideas: Convert PDF to Text in SAP UI5 using PDF.js">
                        <content>
                            <VBox alignItems="Center" justifyContent="Center">
                                <u:FileUploader name="pdfUploader" buttonText="Upload PDF" fileType="pdf" change="onFileUpload"/>
                                <TextArea id="textArea" rows="10" width="100%" editable="false"/>
                            </VBox>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    Controller

    sap.ui.define([
        "sap/ui/core/mvc/Controller"
    ], function (Controller) {
        "use strict";
    
        return Controller.extend("pdfUploader.pdfUploader.controller.Main", {
            onInit: function () {
    
            },
    
            onFileUpload: function (event) {
                var that = this;
                var file = event.getParameter("files")[0];
                var reader = new FileReader();
    
                reader.onload = function (event) {
                    var pdfData = new Uint8Array(event.target.result);
    
                    // Load the PDF data using PDF.js
                    pdfjsLib.getDocument(pdfData).promise.then(function (pdf) {
                        // Access the first page of the PDF
                        pdf.getPage(1).then(function (page) {
                            // Extract the text content from the page
                            page.getTextContent().then(function (textContent) {
                                var extractedText = "";
    
                                // Concatenate the text content from all items
                                textContent.items.forEach(function (item) {
                                    extractedText += item.str + " ";
                                });
    
                                // Bind the extracted text to the TextArea control
                                var textArea = that.getView().byId("textArea");
                                textArea.setValue(extractedText);
                            }.bind(this));
                        });
                    });
                }.bind(this);
    
                reader.readAsArrayBuffer(file);
            },
        });
    });

     

    Output

    Sample PDF:

    Sample PDF

    After Upload:

    Convert PDF to Text in SAP UI5 using PDF.js

     

  • Download PDF in SAP UI5

    Introduction

    Welcome to a comprehensive guide on “Downloading PDFs in SAP UI5”. If you’ve ever grappled with the task of managing PDF files within your SAP UI5 applications, you’re in the right place. This tutorial will break down the process, providing you with an easy-to-follow method to implement this feature. Learn how to facilitate seamless PDF downloads, enhancing the user experience and functionality of your SAP UI5 application. So, whether you’re a seasoned developer or just starting out, this guide will help you master the process of PDF downloads in SAP UI5.

    How to Download PDF using JavaScript

    If you want to download a PDF file using JavaScript, you can use the built-in fetch API to retrieve the file from the server and then create a Blob from the response. After that, you can create a link element and simulate a click on it to start the download. Here are the steps:

    1. Make an HTTP request for the file: You can use the fetch API, which returns a promise that resolves to the Response to that request, whether it is successful or not.

    2. Read the response as a Blob: The response object resulting from the fetch request contains several methods to read the body in various formats. You can use `response.blob()` to read the response as a Blob which represents the PDF file.

    3. Create an object URL representing the Blob: Once you have the Blob, you can create an object URL for it using `URL.createObjectURL(blob)`. This will return a URL representing the blob, which you can use to link to the file.

    4. Simulate a link click to download the file: Now you can create a new link element, set its `href` attribute to the object URL, and simulate a click on it. This will start the download of the file.

    5. Revoke the object URL: After starting the download, it’s a good practice to revoke the object URL with `URL.revokeObjectURL(objectUrl)` to free up memory.

    Please note, if you’re going to implement it on a webpage, make sure the server is configured to allow such downloads, the correct CORS headers are set, and the file is available to be fetched and downloaded. This method should work in most modern browsers.

    Download PDF in SAP UI5

    View

    <mvc:View controllerName="pdfDownload.pdfDownload.controller.Main" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m">
        <Shell id="shell">
            <App id="app">
                <pages>
                    <Page id="page" title="My Project Ideas: Download PDF in UI5">
                        <content>
                            <Link id="downloadLink" text="Download PDF" press="onDownloadPDF"/>
                            <PDFViewer id="pdfViewer" source="https://www.africau.edu/images/default/sample.pdf" width="100%" height="600px"/>
                        </content>
                    </Page>
                </pages>
            </App>
        </Shell>
    </mvc:View>

     

    Controller

    sap.ui.define([
        "sap/ui/core/mvc/Controller"
    ], function (Controller) {
        "use strict";
    
        return Controller.extend("pdfDownload.pdfDownload.controller.Main", {
            onInit: function () {
    
            },
    
            onDownloadPDF: function () {
                // Replace with the actual URL of the PDF file or get it from OData
                var pdfURL = "https://www.africau.edu/images/default/sample.pdf";
                var link = document.createElement("a");
                link.href = pdfURL;
                link.target = "_blank";
                link.download = "document.pdf";
                link.click();
            }
        });
    });

     

    Output

    Download PDF in SAP UI5