Munish
Munish

Reputation: 196

Preview a remote URL (PDF, doc, img) file

I am facing issue while previewing remote URL inside my react-native application. It can be PDF, DOC, IMG etc. Some suggestions are to use react-native-fs to download and then see how to preview it. Sorry could not come up with any code as I am new to react-native. There are libraries like documentpicker where I can pick the file from mobile and preview it. But I am looking for a generic viewer specially for remote URL which can display the common formats like PDF, doc, docx, img etc. I could not find anything like such.

Upvotes: 5

Views: 18045

Answers (4)

Md. Robi Ullah
Md. Robi Ullah

Reputation: 2162

You can simply do it using WebView

<WebView
    source={{uri: remoteFileUrl}}
/>

Example

<WebView
    source={{uri: 'https://www.africau.edu/images/default/sample.pdf'}}
/>

Output:

enter image description here

Upvotes: -1

Ouneeb Ur Rehman
Ouneeb Ur Rehman

Reputation: 694

Instead of Downloading through rn-fetch-blob and then preview it through native app i cover it through view it in webview directly through google docs viewer and microsoft app preview Here is my Implementation

let fileFormate = url.split(".").pop();
    fileFormate = fileFormate.toLowerCase();
if (Platform.OS == "android") {
      if (
        fileExtension == "txt" ||
        fileExtension == "mp4" ||
        fileExtension == "webm" ||
        fileExtension == "webp" ||
        fileExtension == "mp3" ||
        fileExtension == "wav" ||
        fileExtension == "png" ||
        fileExtension == "jpeg" ||
        fileExtension == "jpg" ||
        fileExtension == "wav" ||
        fileExtension == "pdf"
      ) {
        var fileViewURI = Url;
        return fileViewURI;
      } else if (
        fileExtension == "odt" ||
        fileExtension == "ods" ||
        fileExtension == "odp" ||
        fileExtension == "rtf" ||
        fileExtension == "docx" ||
        fileExtension == "doc" ||
        fileExtension == "ppt" ||
        fileExtension == "pptx" ||
        fileExtension == "xls" ||
        fileExtension == "xlsx"
      )
        return `https://view.officeapps.live.com/op/view.aspx?src=${Url}`;
      else {
        var fileViewURI = `http://docs.google.com/gview?embedded=true&url=${Url}`;
        return fileViewURI;
      }
    } 
// for ios  
else {if (fileFormate == "docx")
      return `http://view.officeapps.live.com/op/view.aspx?src=${url}`;
    else if (fileFormate == "html")
      return `https://drive.google.com/viewerng/viewer?embedded=true&url=${url}`;
    else if (
      fileFormate == "odt" ||
      fileFormate == "ods" ||
      fileFormate == "odp"
    )
      return `http://view.officeapps.live.com/op/view.aspx?src=${url}`;
    return url;
  }```

Upvotes: 7

Akshay I
Akshay I

Reputation: 4175

I've do that by using react-native-file-viewer and rn-fetch-blob.

react-native-file-viewer

rn-fetch-blob

Here is my implementation :

import RNFetchBlob from 'rn-fetch-blob'
import FileViewer from 'react-native-file-viewer'


export function showFile (fileUrl) {
  const ext = fileUrl.split(/[#?]/)[0].split('.').pop().trim()
  return new Promise((resolve, reject) => {
    RNFetchBlob.config({
      fileCache: true,
      appendExt: ext
    })
      .fetch('GET', fileUrl)
      .then(res => {
        console.log('The file saved to ', res.path())
        const downloadFile =
          Platform.OS === 'android' ? 'file://' + res.path() : '' + res.path()
        setTimeout(() => {
          FileViewer.open(downloadFile, { showOpenWithDialog: true, onDismiss: () => RNFetchBlob.fs.unlink(res.path()) })
        }, 350)
        resolve(true)
      })
      .catch(err => {
        console.log(err)
        reject(err)
      })
  })
}

Upvotes: 4

Hamas Hassan
Hamas Hassan

Reputation: 941

We can preview URL files like this using these two libraries.

  1. react-native-file-viewer
  2. react-native-fs

Here is the complete code.

import React, { Component } from "react";
import { View, Text, TouchableOpacity } from "react-native";
import FileViewer from "react-native-file-viewer";
import RNFS from "react-native-fs";

export default class FileViewerSample extends Component {
  onPress = async () => {
    // These all formats are acceptable.

    // 'www.adobe.com/content/dam/Adobe/en/devnet/pdf/pdfs/PDF32000_2008.pdf';
    // 'https://file-examples-com.github.io/uploads/2017/02/file-sample_100kB.doc';
    // 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf';
    //  'https://scholar.harvard.edu/files/torman_personal/files/samplepptx.pptx';
    // 'https://file-examples-com.github.io/uploads/2017/02/file_example_XLS_10.xls';

    // Put your url here -----
    const url =
      "https://file-examples-com.github.io/uploads/2017/02/file-sample_100kB.doc";
    // -----

    // this will split the whole url.
    const f2 = url.split("/");

    // then get the file name with extention.
    const fileName = f2[f2.length - 1];
    // const fileExtention = url.split(".")[3];

    // create a local file path from url
    const localFile = `${RNFS.DocumentDirectoryPath}/${fileName}`;
    const options = {
      fromUrl: url,
      toFile: localFile,
    };

    // last step it will download open it with fileviewer.
    RNFS.downloadFile(options)
      .promise.then(() => FileViewer.open(localFile))
      .then(() => {
        // success
        // Here you can perform any of your completion tasks
      })
      .catch((error) => {
        // error
      });
  };

  render() {
    return (
      <View
        style={{
          alignItems: "center",
          justifyContent: "center",
          // backgroundColor: 'red',
          flex: 1,
        }}>
        <TouchableOpacity
          onPress={this.onPress}
          style={{ backgroundColor: "gray", padding: 20 }}>
          <Text style={{ fontSize: 25 }}> App </Text>
        </TouchableOpacity>
      </View>
    );
  }
}

Hope this will help you out. you can modify it more according to your preference.

Upvotes: 6

Related Questions