0

This is the response that I am getting from the api which is raw pdf data.

%PDF-1.4
%цдьЯ
1 0 obj
<<
/Type /Catalog
/Version /1.4
/Pages 2 0 R
/ViewerPreferences 3 0 R
>>

I tried to change it to a string and then encode as base64 which is giving an error, then tried to directly convert to base64 it is creating a pdf file but it's empty. I am not sure which library to use to download this content as pdf and then view it in expo application.

const Buffer = require('buffer').Buffer;

let encodedAuth = new Buffer(responseBlob).toString('base64'); //above raw pdf

I am trying to build an application which allow the user to download a pdf file, once the download is complete the user can view the pdf in the react native expo application

1
  • yes @KJ, but the base64 that I am getting after encoding with buffer is not correct, it returns an empty pdf. Commented Jun 21 at 12:54

1 Answer 1

0

One way to download and view a file (e.g pdf) is to use FileSystem.downloadAsync first to download content to a local file and then use Sharing to view it in any application capable of doing that (e.g. PDF reader).

import * as FileSystem from 'expo-file-system';
import * as Sharing from 'expo-sharing';

const result = await FileSystem.downloadAsync(
  'https://pdfobject.com/pdf/sample.pdf',
  FileSystem.documentDirectory + 'sample.pdf'
);

if (result.status == 200) {
  Sharing.shareAsync(result.uri);
}

Same fetching data first.

import * as FileSystem from 'expo-file-system';
import * as Sharing from 'expo-sharing';

const result = await fetch('https://pdfobject.com/pdf/sample.pdf');
if (result.status == 200) {
  const blob = await result.blob();
  const reader = new FileReader();
  reader.onload = async (e) => {
    const uri = FileSystem.documentDirectory + 'sample.pdf';
    await FileSystem.writeAsStringAsync(uri, e.target.result.split(',')[1], {
      encoding: FileSystem.EncodingType.Base64,
    });
    Sharing.shareAsync(uri);
  };
  reader.readAsDataURL(blob);
}
1
  • This is apt when you have the pdf url, I am actually getting the raw pdf content as response from the api. I am not sure how to convert that into base64 or which package to use for this. Commented Jun 24 at 5:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.