openui5 icon indicating copy to clipboard operation
openui5 copied to clipboard

sap.ui.core.File.save with backend generated PDF (pdfmake 0.1.68)

Open MedusaLuchs85 opened this issue 6 years ago • 9 comments

OpenUI5 version: 1.82.1

Browser/version (+device/version): Chrome 86.0.4240.75 - Desktop PC on Windows 10

Any other tested browsers/devices(OK/FAIL): On every tested browser it looks the same.

Steps to reproduce the problem: on a promise based function I will generate the PDF return new Promise((resolve, reject) => { var fonts = { Roboto: { normal: 'public/fonts/Roboto-Regular.ttf', bold: 'public/fonts/Roboto-Medium.ttf', italics: 'public/fonts/Roboto-Italic.ttf', bolditalics: 'public/fonts/Roboto-MediumItalic.ttf' } };

var printer = new PdfPrinter(fonts);
let pdfDoc = printer.createPdfKitDocument(docDef);
pdfDoc.end();

let pdfData;
let buffers = [];

try {
  pdfDoc.on('data', function(buffer) {
      buffers.push(buffer);
  });
  pdfDoc.on('end', function () {
    pdfData = Buffer.concat(buffers);
    resolve(pdfData);
  })

}
catch(pdfError) {
  reject(pdfError);
}

});

docDef will be something like this: let tableBody = { layout: 'noBorders', table: { headerRows: 0, widths: [ 100, '*'], body: [] }};

    docDefinition.header.columns[0].text = TermId;

    tableBody.table.body.push( [ { text: 'SapId', bold: true, margin: [0, 0, 0, 10]}, { text: device.TermId } ] );
    tableBody.table.body.push( [ { text: 'Desc', bold: true, margin: [0, 0, 0, 10]}, { text: device.Desc } ] );
    tableBody.table.body.push( [ { text: 'Ident', bold: true, margin: [0, 0, 0, 10] }, { text: device.Ident } ] );

    docDefinition.content.push(tableBody);

The Promise will return the result to the client from node.js Express: res.writeHead(200, { "Content-Type": "application/pdf", "content-Disposition": 'attachment; filename="' + oParams.TermId + '.pdf"' }); res.end(pdf);

If I use this code everything will work. The PDF will be saved and can be viewed without any problems. window.location.href = 'http://localhost:9001/api/pdf/device?TermId=' + sId;

But I want to have a short generation animation on that. Therefor I want to use this:

  this.showBusyIndicator();
  this.pdfDevice(sId)
    .then(function(pdf) {

// sap.ui.core.File.save // File.save(pdf, 'device', 'pdf', 'application/pdf', 'utf-8', false); oThat.hideBusyIndicator(); }) .catch(function (error) { console.log(error.message); oThat.hideBusyIndicator(); })

What happens instead? When I use window.location.href:

image The result ist ok.

When I use File.save from the UI framework: image The page is completly empty.

In both cases the result from the backend are the same: image

For me it looks like that there is a problem with the encoding from the server to the client. But I tried a lot, but nothing seems to work.

window.location.href is working fine, but the File.save from the UI framework doesn't. Maybe someone has an idea or faced the some problem in the past.

Sorry, but there is no example published. But I hope that my description wil be enough. Maybe I missed something but I don't see it by now.

Thank all of you who will support me on this issue.

MedusaLuchs85 avatar Oct 19 '20 14:10 MedusaLuchs85

Hello @MedusaLuchs85 , Thank you for sharing this finding. I've created an internal incident 2070425506. The status of the issue will be updated here in GitHub. Best Regards, Florian

flovogt avatar Oct 22 '20 08:10 flovogt

Hello @MedusaLuchs85 ,

may I ask why you set the UTF-8 flag? This will prefix the binary data with a byte order mark (BOM). Any PDF viewer expects a particular PDF signature in the file header, which gets corrupted by the BOM. Please try the File.save without UTF-8 flag.

Regards Sebastian

HerzogIgzorn avatar Oct 22 '20 10:10 HerzogIgzorn

Hello @MedusaLuchs85 ,

may I ask why you set the UTF-8 flag? This will prefix the binary data with a byte order mark (BOM). Any PDF viewer expects a particular PDF signature in the file header, which gets corrupted by the BOM. Please try the File.save without UTF-8 flag.

Regards Sebastian

For sure. I've tried different things, also only data (PDF), filename and extension w/o UTF-8 flag. But the effect at the end was the same. On window.location.href the PDF are ok, with sap.ui.core.file.save not. The backend generates the same data for both requests, but the result on the client is different. And by now I don't know why or find a solution to get sap.ui.core.file.save working correctly.

Regards Sascha

MedusaLuchs85 avatar Oct 22 '20 10:10 MedusaLuchs85

Basically the sap.ui.core.File.save should be replaced in the future by the mechanism that is currently used by the sap.ui.export library in SAPUI5. But as long as this is not available in OpenUI5, we have to investigate this issue. Is it possible to make a publicly available sample so that I can debug this issue?

At least make the content of the PDF available so that I can see if the encoding seems to be an issue or if it simply caused by the behavior of the File.save function.

Regards Sebastian

HerzogIgzorn avatar Oct 22 '20 10:10 HerzogIgzorn

There is no public example. Because the PDF will be generated at the backend. It's an express nodejs app with an endpoint for gereneration the PDF.

This are the function at the backend:

function getDevice(TermId) {
  return new Promise((resolve, reject) => {
    var docDefinition = {
      pageMargins: [60, 60, 60, 60],
      pageSize: "A4",
      // margin: [left, top, right, bottom]
      header: {
        columns: [
          {text: "Device", fontSize: 15, color: "green", alignment: "left", margin: [40, 20, 0, 0] },
          {text: fnGlobals.getDateAsString(), fontSize: 8, color: "green", alignment: "right", margin: [0, 20, 40, 0] }
        ]
      },
      footer: function (currentPage, pageCount) {
        return { text: "Page " + currentPage.toString() + " of " + pageCount.toString(),
          alignment: "right",
          margin: [0, 20, 40, 0],
          fontSize: 8,
          color: "navy"
        }
      },
      content: []
    };

    fnDevice.getDevice(TermId)
      .then(function (device) {

        let tableBody = { layout: "noBorders", table: {
            headerRows: 0,
            widths: [ 100, "*"],
            body: []
          }};

        docDefinition.header.columns[0].text = TermId;

        tableBody.table.body.push( [ { text: "Id", bold: true, margin: [0, 0, 0, 10]}, { text: device.TermId } ] );
        tableBody.table.body.push( [ { text: "Desc", bold: true, margin: [0, 0, 0, 10]}, { text: device.Desc } ] );

		/* more lines ... */

        docDefinition.content.push(tableBody);
        return generatePdf(docDefinition, device.Desc);
      })
      .then(function(pdf) {
        resolve(pdf);
      })
      .catch(function (error) {
        reject(error);
      })

  })
}

function generatePdf(docDef, docTitle) {
  return new Promise((resolve, reject) => {
    var fonts = {
      Roboto: {
        normal: "public/fonts/Roboto-Regular.ttf",
        bold: "public/fonts/Roboto-Medium.ttf",
        italics: "public/fonts/Roboto-Italic.ttf",
        bolditalics: "public/fonts/Roboto-MediumItalic.ttf"
      }
    };

    var printer = new PdfPrinter(fonts);
    let pdfDoc = printer.createPdfKitDocument(docDef);
    pdfDoc.end();

    let pdfData = {};
    let buffers = [];

    try {
      pdfDoc.on("data", function(buffer) {
          buffers.push(buffer);
      });
      pdfDoc.on("end", function () {

        pdfData.Document = Buffer.concat(buffers);
        pdfData.Name = docTitle;
        resolve(pdfData);
      })

    }
    catch(pdfError) {
      reject(pdfError);
    }

  });
}

This is the REST endpoint for generation the PDF content:

router.get("/device", function (req, res) {
  const oParams = req.query;
  if (oParams) {
    fnPdf.getDevice(oParams.TermId)
      .then(function (pdf) {
        res.type("pdf");
        res.set({
          "Content-Length": pdf.Document.length,
          "Content-Disposition": `attachment; filename="${pdf.Name}.pdf"`
        });
        res.status(200).send(pdf.Document);

      })
      .catch(function (error) {
        res.status(500).send(error.message);
      })
  }
});

Client - Side:

This if the function for accessing the REST endpoint at the server:

    pdfDevice: function (id) {
      var oThat = this;
      return new Promise(function (resolve, reject) {
        jQuery.ajax('/api/pdf/device', {
          contentType: 'application/pdf',
          data: { TermId: id },
          method: 'GET'
        }).done(function (pdf) {
          resolve(pdf);
        }).fail(function (error) {
          reject(error);
        });
      });
    }

The function itself will be called when a button was pressed.

    onDevicePrint: function () {
      var oThat = this;
      var sId = this.byId('printDevice').data('Id');

      window.open('api/pdf/device?TermId=' + sId, true);  // will work by now

      // !!! The code below don't work !!!

      // this.showBusyIndicator();
      // this.pdfDevice(sId)
      //   .then(function(pdfBuffer) {
      //     File.save(pdfBuffer, 'device', 'pdf', 'application/pdf');
      //     oThat.hideBusyIndicator();
      //   })
      //   .catch(function (error) {
      //     oThat.hideBusyIndicator();
      //   })
    },

I don't know what you are mean when you say you need the PDF content. The content is dynamically created. See a screentshot from my first posting.

This is the file with window.loaction.href / window.open

test.pdf

This is the file with sap.ui.core.file.save

test (1).pdf

The filesize of the PDF in both methods are different.

This is the PDF Buffer at the backend as small screenshot.

image

This the the PDF Buffer at the client as small screenshot.

image

So at the end the only difference is between window.location.href and sap.ui.core.file.save.

I hope this will help.

Regards Sascha

MedusaLuchs85 avatar Oct 22 '20 12:10 MedusaLuchs85

Hello Sascha,

I tried to reproduce the issue locally by creating an TypedArray out of your generated PDF. Unfortunately it works in Google Chrome. Can you please check what type is passed to File.save as parameter?

Although the File.save API expects a String, you can also pass an ArrayBuffer, as long as you are not using a byte order mark. The encoding can be ignored in that case.

I assume that you pass a string that has a different encoding in JavaScript (Strings are by default UTF-16 and which results in a different byte length when creating a Blob/ObjectURL).

I attached a sample that covers a basic download scenario and also a simplified version of File.save. Please understand that I removed unnecessary lines of code from the sample.

sample.zip

HerzogIgzorn avatar Nov 02 '20 10:11 HerzogIgzorn

Sorry for my late reply. Your code works, but I have the problem in combination with the "pdfmake" module. If I save the result of the pdfmake module directly as a variable in the UI5 page, then I can successfully save the PDF using the sap.ui method.

But if I send the result of the "pdfmake" module via express to the client (UI5-View), I can only successfully save the PDF using "window.open()". If I use "sap.ui.core.util.file.save", it does not work.

So my question is, why does window.open work and the sapui5 method does not? The passed "data" is identical in both cases.

MedusaLuchs85 avatar Nov 18 '20 14:11 MedusaLuchs85

Hello MedusaLuchs85,

This is most likely due to HTTP response character encoding. The HTTP request and response define an HTTP header Content-Type that defines how the data has to be interpreted. I'm not sure if express is able to provide all content types correctly. Even though the data represents an PDF file, the response is used as binary data, therefore I'd recommend using the Content-Type=application/octet-stream

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type https://www.iana.org/assignments/media-types/application/octet-stream

You can also take a look at the Accept-Charset request header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Charset

Beside that you will have to analyze the content of the HTTP response with the predefined value that is already stored as a variable in the UI5 page. Once you identified the difference, you can adjust your coding accordingly.

Please understand that sap.ui.core.util.File.save is intended to save files that have been created locally in the browser. If the backend service is already able to provide the file, there is no need to use the File.save function.

HerzogIgzorn avatar Nov 23 '20 08:11 HerzogIgzorn

Since there is no response from the author for more than 4 weeks I'm closing the ticket.

Martotko avatar Dec 21 '20 13:12 Martotko