cancel
Showing results for 
Search instead for 
Did you mean: 
Read only

How to set the file name in SAPUI5 PDFViewer for base64 encoded PDF

renejurmann
Participant
1,383

Hi experts,

we want to render a base64 encoded PDF in SAPUI5 PDFViewer. We implemented this based on the blog "How to view a base64 encoded pdf using PDFViewer".

Just for the download we have chosen a different approach. This is what we implemented:

const oModel = this.getOwnerComponent().getModel();
oModel.read("/MyEntity", {
	success: function (oData, oResponse) {
		const base64Str = oData.File;
		const sFileName = oData.fileName
		var decodedPdfContent = atob(base64Str);
		var byteArray = new Uint8Array(decodedPdfContent.length);
		for (var i = 0; i < decodedPdfContent.length; i++) {
			byteArray[i] = decodedPdfContent.charCodeAt(i);
		}
		var blob = new Blob([byteArray.buffer], { type: 'application/pdf' });
		var _pdfurl = URL.createObjectURL(blob);
		
		if(!this._PDFViewer){
			 this._PDFViewer = new sap.m.PDFViewer({
				 width:"auto",
				 source:_pdfurl // my blob url
			 });
			 jQuery.sap.addUrlWhitelist("blob"); // register blob url as whitelist
		}
		this._PDFViewer.downloadPDF = function(){
			var link = document.createElement('a');
			link.href = _pdfurl
			link.download =  sFileName
			link.style.display = 'none';
			document.body.appendChild(link);
			
			// Trigger a click event on the anchor element
			link.click();
			
			// Clean up
			document.body.removeChild(link);
		};
		this._PDFViewer.open();
	}.bind(this),
	error: function (oError) {
		console.error(oError)
	}
});

Pressing the download button rendered by the PDFViewer the custom file name as specified in the OData return is used to store the file on the desktop.

But when using the embedded download icon of the PDF preview a random HEX-value is used. In Chrome this random value is also shown in the PDF preview header. Is there any way to use the custom file name here as well?

I know that the random HEX value is generated by the code "URL.createObjectURL(blob);" But even here I have not yet figured out how to use a custom file name...

This is how the PDF looks like in Chrome:

renejurmann_1-1719998147066.png

 

Any ideas?

 

regards

René

 

 

Accepted Solutions (0)

Answers (0)