Download a PDF (Parse JSON and Base64 decode)

I am trying to allow for PDF downloads via my API.

Is it possible to parse the JSON and then Base64 decode on the appgyver end?

1 Like

So would your API return the PDF data as a field in the API response JSON with Base64 encoded contents? A better way would be to just have the API serve a binary download and use the Download file flow function to get access to it.

Yes the API responds with this: (demo data)

The documentation says “The response will return the document in the _content section of the response body. This content is base64 encoded. After you get the response back with the content, you will need to parse the JSON and base64 decode the _content, then save it with the extension type. 5. The extension type will get returned after the _content. You could also parse the JSON and dynamically return the extension type (to dynamically handle multiple file format types)”

is that supported on appgyver?

On mobile, you should be able to use the Write file flow function (select base64 as the encoding) to write the file to disk and then use other flow functions to manipulate the file further.

On web, you can convert the base64 string to a downloadable file with the following code in JavaScript function box (by mapping the Get record output as the response input):

const { response } = inputs;
const { base64 } = response;
const bytes = atob(base64)
  .split('')
  .map(c => c.charCodeAt(0));
const blob = new Blob([ new Uint8Array(bytes) ], { type: 'application/pdf' });
const url = URL.createObjectURL(blob);
const filename = 'filename.pdf';
const a = self.document.createElement('a');
a.href = url;
a.setAttribute('download', filename);
a.click();
return {};

For mobile, would write file be used in combination with Download file?

I’m a bit new to this. For the Data To Write input (in the Write File flow function) I’m assuming it would be the value of the _content section, but I’m lost on the Target File Path Input. How does that work? All of our users are on IOS if that’s helpful.

Thank you for your guidance!

For the Data to write input – correct.

For the Target file path, you would get the base path from system variables then append the filename, e.g.

systemVars.fileSystem.directories.document + "/myFile.pdf"

You then have the file in your local filesystem and can use e.g. Preview PDF to view it.

1 Like

That worked thank you!

One last question. How can I customize the Preview PDF modal? I can’t exit it. Sometimes when I drag down it closes, but then pops back up a few seconds later.

EDIT: Continuing discussion here: View PDF modal issue

@Ryan_Nisbet we couldn’t repro the issue you mentioned. Could tell more about the logic / configuration you’ve used when you use Preview PDF Flow function? Is the page on root level or a modal? A screenshot of the logic could help. Also, are you still using just iOS or which platform has the issue?