9

I am developing a new project about publishing Personal CV.

I need to show users' CVs in the application.

My standard WebView code is below and working well on iOS.

import * as React from 'react';
import { WebView } from 'react-native';


export default class App extends React.Component {
  render() {
    return (
      <WebView
            style={{flex: 1, backgroundColor: 'white'}}
            source={{
              uri: 'http://www.africau.edu/images/default/sample.pdf',
            }}
            bounces={true}
            useWebKit={true}
            scrollEnabled={true}
          />
    );
  }
}

This code also needs to work on Android. When I try it on Android the page shows nothing.

You can try this on Expo Snack.

aytek
  • 1,842
  • 24
  • 32
Hasan Rıza Uzuner
  • 445
  • 1
  • 7
  • 21

4 Answers4

27

Android Webview cannot display PDF files. There is an issue related to this problem. You can view it from this link

There are multiple solutions to your problem, you can pick the most relevant one for yourself.

1) Use react-native-pdf-view

2) Use Google Docs as a viewer. Try to load this URL in your Webview http://docs.google.com/gview?embedded=true&url=http://www.africau.edu/images/default/sample.pdf

3) Use Chrome Custom Tabs.

aytek
  • 1,842
  • 24
  • 32
  • 2
    I use the second option as I want the pdf to open inApp. The problem is that sometimes I get white screen with no error log. Has anyone faced this issue? – itdoesntwork Sep 27 '21 at 10:16
  • 1
    @itdoesntwork Yes, I faced that problem. I think there is a [bug](https://stackoverflow.com/questions/62583248/google-viewer-is-opening-blank-page-frequently) in Google's doc viewer. – aytek Sep 27 '21 at 11:39
  • @aytek Is it possibe to hide open in browser icon on top right to block the pdf to download – Anuj Todankar Mar 21 '23 at 07:20
  • Google Docs viewer is available to show the PDF but if PDF is large in size, then it could not be able to display it and shows the error like "Couldn't preview file" – Sudhakar Jun 12 '23 at 11:54
4

I went with option 2 but faced a Google doc viewer error so I did this hacky thing to check if there is no content on load in order to refresh the webview.

const retries = 10

const PdfViewerScreen = ({ route, navigation }: Props) => {
  const { pdfUrl } = route.params || {}
  const webview = useRef(null)
  const [tries, setTries] = useState(1)
  const [reset, setReset] = useState(Date.now())

  const isAndroid = Platform.OS === 'android'
  const base = !isAndroid
    ? ''
    : 'https://docs.google.com/gview?embedded=true&url='

  // Use date as reset to be able to 
  // reload the webview
  const uri = `${base}${pdfUrl}?t=${reset}`

  // Js code to get baseURI when 
  // webview is loaded. docs.google.com has a bug
  // where no content is returned.
  const myInjectedJs = `    
    (function(){ 
      window.ReactNativeWebView.postMessage(window.document.baseURI);
    })();`

  const onMessage = (event: WebViewMessageEvent) => {
    // Issue does not occur in iOS
    if(!isAndroid) return

    const baseURI = event.nativeEvent.data
    if (tries === retries) navigation.goBack()

    if (baseURI !== uri) {
      setReset(Date.now())
      setTries(tries + 1)
    }
  }

  return (
    <>
      <WebView
        ref={webview}
        javaScriptEnabled={true}
        domStorageEnabled={true}
        startInLoadingState={true}
        style={tailwind(`flex-1`)}
        injectedJavaScript={myInjectedJs}
        source={{ uri }}
        onMessage={onMessage}
        renderLoading={() => (
          <View style={tailwind('w-full h-full')}>
            <Loading />
          </View>
        )}
      />
    </>
  )
}
itdoesntwork
  • 1,745
  • 16
  • 31
0

For Android : To view PDF files from URL then below solution worked for me.

Good thing is it comes up with default controls like Zoom, Next page etc

Import react-native-webview as

import { WebView } from 'react-native-webview';

<WebView style={{ height: 500, width: 350 }} nestedScrollEnabled={true} source={{ uri: 'https://drive.google.com/viewerng/viewer?embedded=true&url=http://www.africau.edu/images/default/sample.pdf' }} />

Note : Height and width is mandatory to add else it will be hiddenenter image description here

Rohit Parte
  • 3,365
  • 26
  • 26
-1

Use this link to show pdf/doc files in webview(for android).

https://drive.google.com/viewerng/viewer?embedded=true&url={your pdf url}’
  • 1
    A link to a solution is welcome, but please ensure your answer is useful without it: [add context around the link](//meta.stackexchange.com/a/8259) so your fellow users will have some idea what it is and why it is there, then quote the most relevant part of the page you are linking to in case the target page is unavailable. [Answers that are little more than a link may be deleted.](/help/deleted-answers) – Daniel Widdis Feb 14 '23 at 08:59
  • This worked properly, on EXPO react-native app. – Rohit Parte May 29 '23 at 08:09
  • It worked on my end. How does it work? Is it safe? – Riku Aug 17 '23 at 14:47