5

I have a React application which needs to support both WebViews and Browsers. I have a functionality where-in we have an API which returns base64String and we need to convert it to PDF and provide a link to user to download the PDF. Below is a sample code snippet.

Code Snippet:


const convertBase64StringToPDF = (data: string) => {
  const byteCharacters = atob(data);
  const byteNumbers = new Array(byteCharacters.length);
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
  }
  const byteArray = new Uint8Array(byteNumbers);
  return new Blob([byteArray], { type: 'application/pdf' });
};


getbase64StringData(baseUrl2)
  .then((response) => {
    const blob = convertBase64StringToPDF(response.foobar);
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = 'MyDoc' + new Date() + '.pdf';
    link.click();
  })

The problem I'm facing is when a user clicks on the link we create, the download isn't getting triggered only in WebViews. I searched for solutions but most of them suggest making changes in WebView code. Problem is I don't have control over the App code which has the WebView embedded in it. Is there a way I can solve this in React/JavaScript application? I don't care where the download happens, I just need it to get triggered and get stored in users device.

8
  • Added a bounty. To note something with the bounty, the solution does not have to directly be for PDF files or even a blob related solution -- this issue persists across many file types with webviews. So a solution in general that doesn't use device specific code is the desired endgame. Commented May 26, 2024 at 2:33
  • @Jesse have you checked this solution? Commented May 27, 2024 at 14:32
  • @BobSmith Which solution? That is a link to a similar question with only java answers. The bounty states: "The original question mentions not having access to the actual code of the application, so no swift or java code will be accepted." Commented May 27, 2024 at 16:38
  • 3
    Unfortunately it seems that you need to implement a DownloadListener and register it with WebView.setDownloadListener. Or create a custom WebView class which does this automatically. So I'd say, if you don't have access to the hosting application you are out of luck ... Commented May 29, 2024 at 17:11
  • 1
    : and /are not legal characters in a filename on most filesystems, and are part of the default string that Date creates. Doesn't really matter since the webview is not allowing download capability, but worth noting. Commented May 31, 2024 at 6:01

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.