3

I'm working with an existing Electron project (convert web app to desktop app), which has a task that is to export content on screen to pdf/png/jpg.

Here is the situation:

  1. The desktop app is purely client-side code, it doesn't connect to any API or server (just in case you suggest a solution using Nodejs server-side code)
  2. I got the dataUrl from canvas object already (it's a base64 string of the file)

How can I save that dataUrl into a file (pdf/png/jpg)?

Here are some ways that I tried:

  1. The good old window.location = dataUrl (nothing happens)
  2. Create a form inside the div, action = dataUrl, then submit the form

Both ways are not working!

Thank you very much

0xh8h
  • 3,271
  • 4
  • 34
  • 55

1 Answers1

0

For the download to occur the MIME type of the data URI needs to be changed to "application/octet-stream"

var dataURL = "data:text/plain,123";
var form = document.createElement("form");
form.action = dataURL.replace(/:[\w-/]+(?=,)/, ":application/octet-stream");
form.method = "GET";
document.body.appendChild(form);
form.submit();

Using <a> element with download attribute

var dataURL = "data:text/plain,123";
var a = document.createElement("a");
a.download = "file";
a.href = dataURL;
document.body.appendChild(a);
a.click();

See also How to download a file without using <a> element with download attribute or a server??

guest271314
  • 1
  • 15
  • 104
  • 177
  • Thank you @guest271314. I tried both ways but it just doesn't work. No error in console log but file is not downloaded – 0xh8h Oct 23 '17 at 15:10
  • @HoangTrinh Have not tried electron. Is the environment a `window` and HTML `document`? – guest271314 Oct 23 '17 at 15:11
  • http://prntscr.com/h0z341 Yes, there is **window** and also **document**, but it just doesn't work in Electron, this environment is so weird – 0xh8h Oct 23 '17 at 15:14