Reputation: 3784
I'm using React Native with Expo and I'm trying to open a pdf file. I already have the file in my assets folder. I prefer to not detach expo.
I tried to use react-native-pdf
like:
import React, { Component } from 'react';
import { StyleSheet, Dimensions, View } from 'react-native';
import Pdf from 'react-native-pdf';
export default class PDFExample extends Component {
render() {
const source = {uri:'bundle-assets://test.pdf'};
return (
<View style={styles.container}>
<Pdf
source={source}
style={styles.pdf} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'flex-start',
alignItems: 'center',
marginTop: 25,
},
pdf: {
flex:1,
width:Dimensions.get('window').width,
}
});
But no success. Many errors occur and I'm losing faith in this package. So I'm looking for a simpler solution.
The question:
How can I open a asset file in another app. Like, making ios or android choose which app will open the pdf file. Can I do that with only managed code in expo without detach?
Upvotes: 2
Views: 5690
Reputation: 33
A workaround I found is using Adobe PDF Embed API. Using it in the react-native-webview does the job.
What I did is that I create a new component and passed the pdf url as its props and then displaying it.
import React from 'react';
import { WebView } from 'react-native-webview';
function PdfViewScreen({route}) {
const pdfUrl = route.params;
const myHtml = `<html><body>
<div id="adobe-dc-view"></div>
<script src="https://documentcloud.adobe.com/view-sdk/main.js"></script>
<script type="text/javascript">
document.addEventListener("adobe_dc_view_sdk.ready", function(){
var adobeDCView = new AdobeDC.View({clientId: "<YOUR_CLIENT_ID>", divId: "adobe-dc-view"});
adobeDCView.previewFile({
content:{ location:
{ url: '${pdfUrl}'}},
metaData:{fileName: "Dummy name"}
},
{
embedMode: "SIZED_CONTAINER"
});
});
</script>
</body></html>`
return (
<WebView
originWhitelist={['*']}
source={{ html : myHtml}}
onMessage={(event) => {
alert(event.nativeEvent.data);
}}
/>
);
}
export default PdfViewScreen;
Upvotes: 1
Reputation: 31
Install the following libraries via yarn or npm:
yarn add react-native-webview expo-file-system expo-constants rn-pdf-reader-js
Then you can display a PDF like so:
import React from ‘react’
import { ScrollView, View, } from ‘react-native’
import PDFReader from ‘rn-pdf-reader-js’
export default class Publications extends React.Component {
render() {
return (
<PDFReader
source={{
uri: ‘http://www.africau.edu/images/default/sample.pdf’,
}}
/>
)
}
}
Upvotes: 3