Giter VIP home page Giter VIP logo

create-react-app-hook-example's Introduction

Foxit PDF SDK for Web Example - React.js created by "create-react-app" (React hook)

This guide shows two examples. One introduces how to quickly run the out-of-the-box sample for react.js created by "create-react-app" in Foxit PDF SDK for Web package, and the other presents a way to integrate Foxit PDF SDK for Web into React app created by "create-react-app".

Quickly run the out-of-the-box sample for Create-react-app-hook-Example

Note:The root folder of Foxit PDF SDK for Web is referred as root in the following.

Foxit PDF SDK for Web provides a boilerplate project for React app which was created by "create-react-app".

Overview the project structure

├─public
│   └── index.html
├─src/
│  ├─components/
│  │  └─PDFViewer/
│  ├─App.css
│  ├─App.js
│  ├─index.css
│  ├─index.js
│  ├─license-key.js
│  └──preload.js
├─.eslintignore
├─config-overrides.js
├─package.json

Key directory and files descriptions

File/Folder Description
src/ Contains all JS and CSS files for the app.
src/components/PDFViewer/ Contains the initilization plugins for FoxitPDFSDK for Web.
src/preload.js This entry point used to preload SDK core assets.
src/license-key.js The license-key
src/App.js The entry point for application.
config-overrides.js Adjust the Webpack configuration
package.json Lists dependencies, version build information and ect.

Prerequisites

Getting started

Let's call the Foxit PDF SDK for Web as SDK.

  • Clone this repository to any location

    git clone https://github.com/foxitsoftware/Create-react-app-hook-Example.git
  • Place the license-key.js into ./src/, You can find the license information at SDK/examples/.

  • Navigate to ./Create-react-app-hook-Example folder, and execute:

    yarn 
    yarn start

Now everything is set up. Open your browser, navigate to http://localhost:3000/ to launch this application.

Reference the fonts

If some text in a PDF document requires a specified font to be rendered correctly, you need to specify a font loading path during initialization. In this example, you can refer to the fontPath configuration in src/preload.js. What we need to do is to copy the external folder in the SDK to the public folder so that the special font can be rendered normally.

Integrate Web SDK to react app created by "create-react-app"

Prerequisites

Getting started

  1. Create the React app with "create-react-app":

    npx create-react-app app
  2. In app folder, Update package.json:

    "scripts": {
        "start": "react-app-rewired --max_old_space_size=8192 start",
        "build": "react-app-rewired --max_old_space_size=8192 build",
        "test": "react-app-rewired --max_old_space_size=8192 test --env=jsdom",
        "eject": "react-app-rewired --max_old_space_size=8192 eject"
    },
  3. In app folder, add config-overrides.js:

     const CopyWebpackPlugin = require("copy-webpack-plugin");
     const { override, addWebpackPlugin, addWebpackExternals} = require('customize-cra');
     const path = require("path")
     
     const libraryModulePath = path.resolve('node_modules/@foxitsoftware/foxit-pdf-sdk-for-web-library');
     const libPath = path.resolve(libraryModulePath, 'lib');
     
     module.exports = override(
         addWebpackPlugin(
             new CopyWebpackPlugin({
                 patterns: [{
                     from: libPath,
                     to: 'foxit-lib',
                     force: true
                 }]
             })
         ),
         addWebpackExternals(
             'UIExtension', 
             'PDFViewCtrl'
         )
     )
  4. In src folder, add license-key.js, copy the content below to that file and fill in the License's KEY and SN fields.

    export const licenseKey = '';
    export const licenseSN = '';
  5. In src folder, add preload.js:

     import preloadJrWorker from '@foxitsoftware/foxit-pdf-sdk-for-web-library/lib/preload-jr-worker';
     import { licenseKey, licenseSN } from './license-key';
     
     const libPath = "/foxit-lib/"
     
     window.readyWorker = preloadJrWorker({
         workerPath: libPath,
         enginePath: libPath+'/jr-engine/gsdk',
         fontPath: '/external/brotli',
         licenseSN,
         licenseKey,
     });
  6. Copy the external folder inside SDK to public folder.

  7. In src/index.js file, import preload.js:

     import './preload.js'
  8. In src folder, add components/PDFViewer/index.js:

     import React, { createRef, forwardRef, useImperativeHandle, useRef } from 'react';
     import * as UIExtension from '@foxitsoftware/foxit-pdf-sdk-for-web-library/lib/UIExtension.full.js';
     import "@foxitsoftware/foxit-pdf-sdk-for-web-library/lib/UIExtension.css";
     import * as Addons from '@foxitsoftware/foxit-pdf-sdk-for-web-library/lib/uix-addons/allInOne.js';
     import * as mobileAddons from '@foxitsoftware/foxit-pdf-sdk-for-web-library/lib/uix-addons/allInOne.mobile.js';
    
    
     function PDFViewer(props, ref) {
         const viewerContainerRef = useRef(null);
    
         const pdfuiInstanceRef = createRef();
    
         useImperativeHandle(ref,() => {
             if(window.pdfui){
                 pdfuiInstanceRef.current = window.pdfui
                 return pdfuiInstanceRef.current
             }
             const renderTo = viewerContainerRef.current;
             const libPath = "/foxit-lib/";
             const pdfui = new UIExtension.PDFUI({
                 viewerOptions: {
                     libPath,
                     jr: {
                         readyWorker: window.readyWorker
                     },
                     ...(props.viewerOptions || {})
                 },
                 renderTo: renderTo,
                 appearance: UIExtension.appearances.adaptive,
                 addons: UIExtension.PDFViewCtrl.DeviceInfo.isMobile? mobileAddons:Addons
             });
             window.pdfui = pdfuiInstanceRef.current = pdfui;
             return pdfui;
         });
         
         return <div className = "foxit-PDF" ref = { viewerContainerRef } />;
     }
     export default forwardRef(PDFViewer);
  9. Update App.js:

    import { useEffect, useRef } from 'react';
    import './App.css';
    import PDFViewer from './components/PDFViewer';
    
    function App() {
        const pdfuiRef = useRef(null);
        useEffect(() => {
            const pdfui = pdfuiRef.current;
            if(!pdfui) {
                return;
            }
            // Here, you can do anything with the pdfui instance.
            function handleWindowResize() {
                pdfui.redraw();
            }
            window.addEventListener('resize', handleWindowResize);
            return () => {
                // Here, you can perform any destruction actions.
                window.removeEventListener('resize', handleWindowResize);
            };
        }, [pdfuiRef]);
        const externalViewerOptions = {
            // more viewer options
        };
        return (
            <div className="App">
                <PDFViewer ref={pdfuiRef} viewerOptions={externalViewerOptions}></PDFViewer>
            </div>
        );
    }
    
    export default App;
  10. Update App.css

    #root,.App,.foxit-PDF{
        height: 100%;
    }
  11. Install dependencies and run:

    cd app
    yarn add @foxitsoftware/foxit-pdf-sdk-for-web-library 
    yarn add [email protected] [email protected] [email protected] -D
    yarn start

Now everything is set up. Open your browser, navigate to http://localhost:3000/ to launch your application.

create-react-app-hook-example's People

Contributors

linc0803 avatar y1j2x34 avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

Forkers

luonan-chen

create-react-app-hook-example's Issues

Integrating foxit-pdf-reader with single-spa-react throws the error died in status LOADING_SOURCE_CODE: Automatic publicPath is not supported in this browser

image

single-spa-layout.min.js:2 Uncaught Error: application '@textile/biz-components' died in status LOADING_SOURCE_CODE: Automatic publicPath is not supported in this browser
at UIExtension.full.js:111:169840
at UIExtension.full.js:111:170011
at UIExtension.full.js:111:171098
at UIExtension.full.js:1:65
at ./node_modules/@foxitsoftware/foxit-pdf-sdk-for-web-library/lib/UIExtension.full.js (UIExtension.full.js:1:203)
at webpack_require (bootstrap:19:1)
at ./src/components/foxit-web-pdf/FoxitWebPDFApp.tsx (format-manager-provider.component.tsx:21:8)
at webpack_require (bootstrap:19:1)
at ./src/screens/pdf-viewer-sample-screen.component.tsx (my-wizard-dialog.component.tsx:231:8)
at webpack_require (bootstrap:19:1)
(anonymous) @ UIExtension.full.js:111
(anonymous) @ UIExtension.full.js:111
(anonymous) @ UIExtension.full.js:111
(anonymous) @ UIExtension.full.js:1
./node_modules/@foxitsoftware/foxit-pdf-sdk-for-web-library/lib/UIExtension.full.js @ UIExtension.full.js:1
webpack_require @ bootstrap:19
./src/components/foxit-web-pdf/FoxitWebPDFApp.tsx @ format-manager-provider.component.tsx:21
webpack_require @ bootstrap:19
./src/screens/pdf-viewer-sample-screen.component.tsx @ my-wizard-dialog.component.tsx:231
webpack_require @ bootstrap:19
./src/routes.tsx @ root.component.tsx:22
webpack_require @ bootstrap:19
./src/root.component.tsx @ refresh-token.hook.tsx:9
webpack_require @ bootstrap:19
(anonymous) @ 1.js:3
(anonymous) @ textile-biz-components.local-dev.tsx:18
execute @ textile-biz-components.local-dev.tsx:18
i @ system-core.js:279
e @ system-core.js:275
(anonymous) @ system-core.js:232
setTimeout (async)
y @ single-spa-layout.min.js:2
(anonymous) @ app-errors.js:9
a @ app-errors.js:9
(anonymous) @ load.js:147
Promise.catch (async)
(anonymous) @ load.js:137
Promise.then (async)
X @ load.js:24
(anonymous) @ reroute.js:78
Promise.then (async)
d @ reroute.js:77
Rt @ reroute.js:69
Pt @ apps.js:133
_callee$ @ textile-runtime.ts:190
tryCatch @ runtime.js:63
invoke @ runtime.js:293
(anonymous) @ runtime.js:118
asyncGeneratorStep @ asyncToGenerator.js:3
_next @ asyncToGenerator.js:25
Promise.then (async)
asyncGeneratorStep @ asyncToGenerator.js:13
_next @ asyncToGenerator.js:25
Promise.then (async)
asyncGeneratorStep @ asyncToGenerator.js:13
_next @ asyncToGenerator.js:25
(anonymous) @ asyncToGenerator.js:32
(anonymous) @ asyncToGenerator.js:21
_initTextile @ textile-runtime.development.js:3085
initTextile @ textile-runtime.ts:60
(anonymous) @ ui/:93
Promise.then (async)
(anonymous) @ ui/:93
Show 15 more frames
Show less
UIExtension.full.js:111 Uncaught (in promise) Error: application '@textile/biz-components' died in status LOADING_SOURCE_CODE: Automatic publicPath is not supported in this browser
at UIExtension.full.js:111:169840
at UIExtension.full.js:111:170011
at UIExtension.full.js:111:171098
at UIExtension.full.js:1:65
at ./node_modules/@foxitsoftware/foxit-pdf-sdk-for-web-library/lib/UIExtension.full.js (UIExtension.full.js:1:203)
at webpack_require (bootstrap:19:1)
at ./src/components/foxit-web-pdf/FoxitWebPDFApp.tsx (format-manager-provider.component.tsx:21:8)
at webpack_require (bootstrap:19:1)
at ./src/screens/pdf-viewer-sample-screen.component.tsx (my-wizard-dialog.component.tsx:231:8)
at webpack_require (bootstrap:19:1)

Hi i am getting the above errors when integrating foxit-pdf-reader  i'm using a single-spa with react please find the 

webpack.config.js code below

`const path = require("path");
const { merge } = require("webpack-merge");
const singleSpaDefaults = require("webpack-config-single-spa-react-ts");
const CopyPlugin = require("copy-webpack-plugin");

const libraryModulePath = path.resolve(
"node_modules/@foxitsoftware/foxit-pdf-sdk-for-web-library"
);
const libPath = path.resolve(libraryModulePath, "lib");

module.exports = (webpackConfigEnv, argv) => {
const defaultConfig = singleSpaDefaults({
orgName: "textile",
projectName: "biz-components",
webpackConfigEnv,
argv,
});

// Use the local development entrypoint for local builds builds.
if (webpackConfigEnv.local_dev === "true") {
const parsedPath = path.parse(defaultConfig.entry);
defaultConfig.entry = ${parsedPath.dir}${path.sep}${parsedPath.name}.local-dev${parsedPath.ext};
}

return merge(defaultConfig, {
output: {
filename: textile-biz-components.${argv.mode}${ argv.mode === "production" ? ".min" : "" }.js,
},
// entry: {
// preload: path.resolve("app/preload.js"),
// },
plugins: [
// Copy the default static files.
new CopyPlugin({
patterns: [
{
from: "static",
to: "",
},
],
}),
new CopyPlugin({
patterns: [
{
from: libPath,
to: "foxit-lib",
force: true,
},
],
}),
],
externals: [
/**
* Make shared modules external to prevent from packaging them up with this module's webpack.
* Use both exact match and regex to treat all submodules as external, thus forcing runtime errors
* when developers import from submodules.
*
* Incorrect:
* import Button from "@textile/mui/Button"
*
* Correct:
* import { Button } from "@textile/mui"
*
*/
"UIExtension",

  "PDFViewCtrl",

  "axios",
  new RegExp("^axios/.*$"),

  "react",

  "react-dom",
  new RegExp("^react-dom/.*$"),

  "history",
  new RegExp("^history/.*$"),

  "react-router",
  new RegExp("^react-router/.*$"),

  "react-router-dom",
  new RegExp("^react-router-dom/.*$"),

  "prop-types",

  "@textile/runtime",
  new RegExp("^@textile/runtime/.*$"),

  // Add textile material ui common utility module.
  // This module is supposed to be included in the Fabric stack by adding chart textile-common
  // to the application's Chart.yaml dependencies section.
  "@textile/common",
  new RegExp("^@textile/common/.*$"),

  "@textile/mui",
  new RegExp("^@textile/mui/.*$"),

  "@textile/ag-grid",
  new RegExp("^@textile/ag-grid/.*$"),

  /**
   * We still need to externalize @mui/material because we use @mui/icons-material through tree shaking
   * and the icons code explicitly refers to @mui/material/* packages. We want to make sure we won't end up
   * bundling @mui/material code which is already provided to us through @textile/mui.
   */
  "@mui/material",
  new RegExp("^@mui/material/.*$"),
],

});
};
`

PDFViewer only renders once

I have a React app that will only show the PDFViewer on certain pages. The Foxit UI will be displayed the first time it is loaded, but if you navigate away and come back, the screen is blank. Only a browser refresh will show the UI again.

You can reproduce the issue by modifying App.js to conditionally render the PDFViewer:

import {useEffect, useRef, useState} from 'react';
import './App.css';
import PDFViewer from './components/PDFViewer';

function App() {
    const pdfuiRef = useRef(null);
    const [show, setShow] = useState(true);

    useEffect(() => {
        const pdfui = pdfuiRef.current;
        if(!pdfui) {
            return;
        }
        // Here, you can do anything with the pdfui instance.
        function handleWindowResize() {
            pdfui.redraw();
        }
        window.addEventListener('resize', handleWindowResize);
        return () => {
            // Here, you can perform any destruction actions.
            window.removeEventListener('resize', handleWindowResize);
        };
    }, [pdfuiRef]);
    const externalViewerOptions = {
        // more viewer options
    };


    return (
        <div className="App">
            <button onClick={() => setShow(!show)}>Toggle PDFViewer</button>
            { show ?
                <PDFViewer ref={pdfuiRef} viewerOptions={externalViewerOptions}></PDFViewer> :
                <div>PDFViewer is not mounted.</div>
            }
        </div>
    );
}

export default App;

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.