react-native-pdf

repository·master·Indexed 23 days ago

https://github.com/wonday/react-native-pdf

A cross-platform PDF viewing component for React Native supporting iOS, Android, and Windows. It enables reading PDFs from URLs, blobs, local files, and assets with features such as caching, zooming, page navigation via setPage(), and support for base64 strings. Requires react-native-blob-util for file system access.

Tokens
5.4K
Snippets
13
Records
22
Agent score
83%

What's inside react-native-pdf

  1. Reload the application

    master

    If you need to perform a full reload to reset the app state (instead of using Fast Refresh), use the following platform-specific commands:

    • Android: Press the <kbd>R</kbd> key twice, or access the Dev Menu via <kbd>Ctrl</kbd> + <kbd>M</kbd> (Windows/Linux) or <kbd>Cmd ⌘</kbd> + <kbd>M</kbd> (macOS) and select "Reload".
    • iOS: Press <kbd>R</kbd> in the iOS Simulator.
  2. Install react-native-pdf on Windows

    master

    To integrate react-native-pdf into a Windows React Native project, follow these steps in Visual Studio 2019:

    1. Add Projects to Solution:

      • Open your solution (e.g., windows\yourapp.sln).
      • Right-click the Solution icon in Solution Explorer and select Add > Existing Project....
      • For RNW 0.62, add these two projects:
        • node_modules\react-native-pdf\windows\RCTPdf\RCTPdf.vcxproj
        • node_modules\rn-fetch-blob\windows\RNFetchBlob\RNFetchBlob.vcxproj
    2. Add Project References:

      • Right-click your main application project and select Add > Reference....
      • For RNW 0.62, ensure you select both RCTPdf and RNFetchBlob.
    3. Configure Header Files:

      • In your app's pch.h file, add the following includes:
        • #include "winrt/RCTPdf.h"
        • For RNW 0.62, also add: #include "winrt/RNFetchBlob.h"
    4. Initialize Package Providers (RNW 0.62 only):

      • In your app's initialization code, add the following lines before InitializeComponent();:
        • PackageProviders().Append(winrt::RCTPdf::ReactPackageProvider());
        • PackageProviders().Append(winrt::RNFetchBlob::ReactPackageProvider());
    # No single runnable code block represents the full installation, but the header/initialization snippets are:
    
    ```cpp
    // pch.h
    #include "winrt/RCTPdf.h"
    #include "winrt/RNFetchBlob.h"
    
    // App initialization
    PackageProviders().Append(winrt::RCTPdf::ReactPackageProvider());
    PackageProviders().Append(winrt::RNFetchBlob::ReactPackageProvider());
    InitializeComponent();
  3. Build and run the iOS app

    master

    For iOS, you must first install CocoaPods dependencies. If this is your first time or you have updated native dependencies, run bundle install followed by bundle exec pod install. Then, run the iOS build command.

    Note: You can also build directly from Xcode.

    # Install CocoaPods dependencies
    bundle install
    bundle exec pod install
    
    # Run the app
    # Using npm
    npm run ios
    
    # OR using Yarn
    yarn ios
  4. Configure iOS installation

    master

    Linking requirements for iOS depend on your React Native version:

    • React Native 0.60 and above: Run pod install in the ios directory. Manual linking is not required.
    • React Native 0.59 and below: Run the following commands to link both dependencies:
    react-native link react-native-blob-util
    react-native link react-native-pdf
  5. Configure Android installation

    master

    Android installation requirements depend on your React Native version:

    • React Native 0.59.0 and above: You must add packagingOptions to your android/app/build.gradle file to avoid conflicts:
    android {
    
    +    packagingOptions {
    +       pickFirst 'lib/x86/libc++_shared.so'
    +       pickFirst 'lib/x86_64/libjsc.so'
    +       pickFirst 'lib/arm64-v8a/libjsc.so'
    +       pickFirst 'lib/arm64-v8a/libc++_shared.so'
    +       pickFirst 'lib/x86_64/libc++_shared.so'
    +       pickFirst 'lib/armeabi-v7a/libc++_shared.so'
    +     }
    
       }
    • React Native 0.59.0 and below: Run the following commands to link both dependencies:
    react-native link react-native-blob-util
    react-native link react-native-pdf
  6. Configure Windows installation

    master

    To install on Windows, follow these steps in Visual Studio 2019:

    1. Open your solution (e.g., windows\yourapp.sln).
    2. Right-click Solution in Solution Explorer > Add > Existing Project...
    3. If running RNW 0.62, add:
      • node_modules\react-native-pdf\windows\RCTPdf\RCTPdf.vcxproj
      • node_modules\react-native-blob-util\windows\ReactNativeBlobUtil\ReactNativeBlobUtil.vcxproj
    4. Right-click main application project > Add > Reference...
    5. Select progress-view and in Solution Projects:
      • If running 0.62, also select RCTPdf and ReactNativeBlobUtil.
    6. In app pch.h, add:
      • #include "winrt/RCTPdf.h"
      • If running 0.62, also select #include "winrt/ReactNativeBlobUtil.h"
    7. In App.cpp, add the following before InitializeComponent();:
      • PackageProviders().Append(winrt::progress_view::ReactPackageProvider());
      • If running 0.62, also add:
        • PackageProviders().Append(winrt::RCTPdf::ReactPackageProvider());
        • PackageProviders().Append(winrt::ReactNativeBlobUtil::ReactPackageProvider());

    Bundling PDFs with the app

    To include a PDF file (e.g., test.pdf) in your app, add this to your .vcxproj file before <None Include="packages.config" />:

    <None Include="..\..\test.pdf">
      <DeploymentContent>true</DeploymentContent>
    </None>
  7. Install react-native-pdf and react-native-blob-util

    master

    To use react-native-pdf, you must also install react-native-blob-util for file system access. Use npm or yarn to add both packages to your project.

    Installation Commands

    # Using npm
    npm install react-native-pdf react-native-blob-util --save
    
    # or using yarn:
    yarn add react-native-pdf react-native-blob-util
  8. Bundle PDF files with your Windows app

    master

    To include a PDF file (e.g., test.pdf) as part of your application deployment, you must modify your app's .vcxproj file. Add a <None> entry with DeploymentContent set to true before the packages.config inclusion.

    <None Include="..\..\test.pdf">
      <DeploymentContent>true</DeploymentContent>
    </None>
  9. Troubleshoot PDF loading issues

    master

    Common Issues

    PDF not visible after installation

    Ensure you have correctly run react-native link for both react-native-blob-util and react-native-pdf if you are on React Native 0.59 or below. If linking fails, you may need to add them manually.

    White/Gray screen or loading bar stuck (HTTP issues)

    If you are trying to load a PDF from an http (unsecured) URL, you must configure exceptions:

    iOS: Add an exception for the server in your info.plist using NSAppTransportSecurity:

    <key>NSAppTransportSecurity</key>
    <dict>
      <key>NSExceptionDomains</key>
      <dict>
        <key>yourserver.com</key>
        <dict>
          <key>NSIncludesSubdomains</key>
          <true/>
          <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
          <true/>
          <key>NSTemporaryExceptionMinimumTLSVersion</key>
          <string>TLSv1.1</string>
        </dict>
      </dict>
    </dict>

    Android: Refer to documentation regarding cleartext HTTP traffic.

    Expo Compatibility

    This package is not available in the Expo Go app because it relies on native modules. To use it with Expo, you must use Custom Dev Clients via an Expo Config Plugin.

  10. Use the Pdf component

    master

    The Pdf component is used to render PDF files from various sources including URLs, local files, base64 strings, and assets.

    Basic Usage Example

    import React from 'react';
    import { StyleSheet, Dimensions, View } from 'react-native';
    import Pdf from 'react-native-pdf';
    
    export default class PDFExample extends React.Component {
        render() {
            const source = { uri: 'http://samples.leanpub.com/thereactnativebook-sample.pdf', cache: true };
    
            return (
                <View style={styles.container}>
                    <Pdf
                        source={source}
                        onLoadComplete={(numberOfPages, filePath) => {
                            console.log(`Number of pages: ${numberOfPages}`);
                        }}
                        onPageChanged={(page, numberOfPages) => {
                            console.log(`Current page: ${page}`);
                        }}
                        onError={(error) => {
                            console.log(error);
                        }}
                        onPressLink={(uri) => {
                            console.log(`Link pressed: ${uri}`);
                        }}
                        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,
            height:Dimensions.get('window').height,
        }
    });