UI5 | SmartChart를 PDF로 인쇄
Analytical List Page에 "차트를 PDF로 인쇄" 버튼 추가: SmartChart SVG를 캡처해 canvas로 그리고 jsPDF로 내보내기.
9분 분량ui5 · fiori-elements · sap
Analytical List Page(Fiori Elements)를 만들고 확장해, UI5와 가벼운 클라이언트 라이브러리로 "차트를 PDF로 인쇄" 기능을 추가합니다.
참고 저장소 (전체 코드): https://github.com/GonzaloMB/smartchart_pdf_print_ui5.git
요구사항
- 온프레미스 시스템의 ABAP CDS (
@OData.publish: true로 게시한 OData V2). - FE 개발용 SAP BAS 또는 VS Code.
- SAP Logon / Eclipse (해당한다면 ABAP CDS 작성용).
백엔드 (ABAP CDS)
- 기본 뷰: 온프레미스의
sflight테이블을 사용합니다.
@AbapCatalog.sqlViewName: 'ZISFLIGHTDEMOCDS'
@AbapCatalog.compiler.compareFilter: true
@AbapCatalog.preserveKey: true
@AccessControl.authorizationCheck: #NOT_REQUIRED
@VDM.viewType: #BASIC
@EndUserText.label: 'Basic CDS to capability demo'
define view ZI_SFLIGHT_DEMO_CDS
as select from sflight
{
key carrid as Carrid,
key connid as Connid,
key fldate as Fldate,
price as Price,
currency as Currency,
planetype as Planetype,
seatsmax as Seatsmax,
seatsocc as Seatsocc,
paymentsum as Paymentsum,
seatsmax_b as SeatsmaxB,
seatsocc_b as SeatsoccB,
seatsmax_f as SeatsmaxF,
seatsocc_f as SeatsoccF
}- 소비 뷰: OData V2를 게시합니다.
@AbapCatalog.sqlViewName: 'ZCSFLIGHTCAP'
@AbapCatalog.compiler.compareFilter: true
@AbapCatalog.preserveKey: true
@AccessControl.authorizationCheck: #NOT_REQUIRED
@VDM.viewType: #CONSUMPTION
@Metadata.allowExtensions: true
@OData.publish: true
@EndUserText.label: 'Consumption CDS to capability demo'
define view ZC_SFLIGHT_CAPABILITY_CDS
as select from ZI_SFLIGHT_DEMO_CDS
{
key Carrid,
key Connid,
key Fldate,
Price,
Currency,
Planetype,
Seatsmax,
Seatsocc,
Paymentsum,
SeatsmaxB,
SeatsoccB,
SeatsmaxF,
SeatsoccF
}- 메타데이터 확장: 어노테이션을 비즈니스 로직과 분리합니다.
@Metadata.layer: #(sflight)
@UI.chart: [
{
chartType: #COLUMN,
dimensions: [ 'Planetype' ],
measures: [ 'Seatsmax' ]
}
]
@UI: {
headerInfo: {
typeName: 'Flight',
typeNamePlural: 'Flights',
title: { type: #STANDARD, value: 'Carrid' },
description: { value: 'Planetype' }
}
}
annotate entity ZC_SFLIGHT_CAPABILITY_CDS with
{
@UI.facet: [
{ id: 'Fldateheaderid', purpose: #HEADER, type: #DATAPOINT_REFERENCE, position: 10, targetQualifier: 'Fldateheader' },
{ id: 'Currencyheaderid', purpose: #HEADER, type: #DATAPOINT_REFERENCE, position: 20, targetQualifier: 'Priceheader' },
{ label: 'General Information', id: 'GeneralInfo', type: #COLLECTION, position: 10 },
{ id: 'Price', purpose: #STANDARD, type: #IDENTIFICATION_REFERENCE, parentId: 'GeneralInfo', label: 'Price', position: 10 }
]
@UI.lineItem: [{position: 10 }]
@UI.selectionField: [{position: 10 }]
Carrid;
@UI.lineItem: [{position: 20 }]
@UI.selectionField: [{position: 20 }]
Connid;
@UI.lineItem: [{position: 30 }]
@UI.selectionField: [{position: 30 }]
@UI.dataPoint: { qualifier: 'Fldateheader', title: 'Flight Date'}
Fldate;
@UI.dataPoint: { qualifier: 'Priceheader', title: 'Airfare'}
@UI.lineItem: [{position: 40 }]
@UI.identification: [{ position: 10 }]
Price;
@UI.dataPoint: { qualifier: 'Currencyheader', title: 'Airline Currency'}
@UI.lineItem: [{position: 50 }]
@UI.identification: [{ position: 20 }]
Currency;
@UI.lineItem: [{position: 60 }]
Planetype;
@UI.lineItem: [{position: 70 }]
Seatsmax;
@UI.lineItem: [{position: 80 }]
Seatsocc;
@UI.lineItem: [{position: 90 }]
Paymentsum;
@UI.lineItem: [{position: 100 }]
SeatsmaxB;
@UI.lineItem: [{position: 110 }]
SeatsoccB;
@UI.lineItem: [{position: 120 }]
SeatsmaxF;
@UI.lineItem: [{position: 130 }]
SeatsoccF;
}프론트엔드 (Fiori Elements · Analytical List Page)
-
ALP 앱을 생성합니다 (템플릿: Analytical List Page). 프로젝트 정보와 기본 OData 서비스를 입력합니다.
-
manifest.json의 데이터 소스를 확인합니다.
"dataSources": {
"mainService": {
"uri": "/sap/opu/odata/sap/ZC_SFLIGHT_CAPABILITY_CDS_CDS/",
"type": "OData",
"settings": {
"annotations": ["ZC_SFLIGHT_CAPABILITY_CDS_CD_VAN", "annotation"],
"localUri": "localService/metadata.xml",
"odataVersion": "2.0"
}
},
"ZC_SFLIGHT_CAPABILITY_CDS_CD_VAN": {
"uri": "/sap/opu/odata/IWFND/CATALOGSERVICE;v=2/Annotations(TechnicalName='ZC_SFLIGHT_CAPABILITY_CDS_CD_VAN',Version='0001')/$value/",
"type": "ODataAnnotation",
"settings": { "localUri": "localService/ZC_SFLIGHT_CAPABILITY_CDS_CD_VAN.xml" }
},
"annotation": {
"type": "ODataAnnotation",
"uri": "annotations/annotation.xml",
"settings": { "localUri": "annotations/annotation.xml" }
}
}- 컨트롤러 확장:
webapp/ext/controller/AnalyticalListPageExt.controller.js를 만들고manifest.json에서 참조합니다.
"extends": {
"extensions": {
"sap.ui.controllerExtensions": {
"sap.suite.ui.generic.template.AnalyticalListPage.view.AnalyticalListPage": {
"controllerName": "pdfprintui5.ext.controller.AnalyticalListPageExt"
}
}
}
}- 컨트롤러 메서드에 연결된 사용자 정의 액션(버튼):
"extends": {
"extensions": {
"sap.ui.controllerExtensions": {
"sap.suite.ui.generic.template.AnalyticalListPage.view.AnalyticalListPage": {
"controllerName": "pdfprintui5.ext.controller.AnalyticalListPageExt",
"sap.ui.generic.app": {
"ZC_SFLIGHT_CAPABILITY_CDS": {
"EntitySet": "ZC_SFLIGHT_CAPABILITY_CDS",
"Actions": {
"btnPrintChart": {
"id": "btnPrintChart",
"text": "Print Chart to PDF",
"press": "onPrintChart"
}
}
}
}
}
}
}
}manifest.json의 서드파티 라이브러리와 선택적 CSS (webapp/libs와webapp/css에 배치):
"resources": {
"css": [ { "uri": "css/style.css" } ],
"js": [
{ "uri": "libs/rgbcolor.js" },
{ "uri": "libs/StackBlur.js" },
{ "uri": "libs/canvg.js" },
{ "uri": "libs/jspdf.js" }
]
}- 컨트롤러 로직: SmartChart SVG를 캡처해 canvas에 그리고, jsPDF로 PDF를 만든 뒤
sap.m.PDFViewer로 보여 줍니다.
sap.ui.define(
["sap/ui/core/BusyIndicator", "sap/m/PDFViewer"],
function (BusyIndicator, PDFViewer) {
"use strict";
return sap.ui.controller(
"pdfprintui5.ext.controller.AnalyticalListPageExt",
{
onPrintChart: function () {
BusyIndicator.show(0);
this.smartChartId =
"pdfprintui5::sap.suite.ui.generic.template.AnalyticalListPage.view.AnalyticalListPage::ZC_SFLIGHT_CAPABILITY_CDS--chart";
this.chart = this.getView()
.byId(this.smartChartId)
.getItems()[2]
.getAggregation("_vizFrame");
this.chart.setWidth("1100px");
this.chart.setHeight("700px");
setTimeout(
function () {
this.processChartPDF();
}.bind(this),
100
);
},
processChartPDF: function () {
var svg = this.chart.getDomRef().getElementsByTagName("svg")[0];
var canvas = document.createElement("canvas");
var bBox = svg.getBBox();
canvas.width = bBox.width;
canvas.height = bBox.height;
var context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.src =
"data:image/svg+xml," +
jQuery.sap.encodeURL(
svg.outerHTML.replace(
/^<svg/,
'<svg xmlns="http://www.w3.org/2000/svg" version="1.1"'
)
);
imageObj.onload = function () {
context.drawImage(imageObj, 0, 0, canvas.width, canvas.height);
var dataURL = canvas.toDataURL("base64");
const doc = new jsPDF("l", "px", "a4");
doc.addImage(dataURL, "jpg", 10, 20);
this.chart.setWidth("100%");
this.chart.setHeight("100%");
var blob = doc.output("blob", "chart_in_pdf.pdf");
var _pdfurl = URL.createObjectURL(blob);
this._pdfViewer = new PDFViewer();
this.getView().addDependent(this._pdfViewer);
this._PDFViewer = new sap.m.PDFViewer({
width: "auto",
source: _pdfurl,
showDownloadButton: true,
});
jQuery.sap.addUrlWhitelist("blob");
this._PDFViewer.open();
}.bind(this);
setTimeout(function () {
BusyIndicator.hide();
}, 100);
},
}
);
}
);문제 해결
- Blob URL 차단:
PDFViewer를 열기 전에jQuery.sap.addUrlWhitelist("blob")를 추가하세요. - 차트를 찾지 못함: SmartChart 컨트롤 id와 사용 중인 ALP 버전에서 내부
_vizFrame까지의getItems()[2]경로를 확인하세요. - 빈 PDF: 캡처 전에 SVG가 완전히 렌더링되었는지 확인하고(지연), SVG 안에 다른 출처의 이미지를 쓰지 마세요 (
toDataURL이 깨집니다). - 라이브러리 누락:
rgbcolor.js,StackBlur.js,canvg.js,jspdf.js가webapp/libs에서 로드되는지 확인하세요.
사용 기술
- ABAP CDS
- JavaScript / UI5
- Fiori Elements