question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Webview error on render PDF

See original GitHub issue

Within a webview in react-native application, the following error occurred, and I don’t know how to solve:

Captura de Tela 2021-03-24 às 19 12 18

Same problem with the older version on ES5: Captura de Tela 2021-03-24 às 20 35 06

This code is working in desktop application, but not in webview, display console.log() fail to render:

Captura de Tela 2021-03-24 às 19 54 42

Information of chrome version: Version 89.0.4389.90 (x86_64)

The pdf is formatted in base64. But problem is in webview render only.

My Code into webview Angularjs :

$scope.loadingPDF = (pdf) => {

    var DEFAULT_URL = pdf;

    $scope.hasPDF = false;

  
    var vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0)
    var vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0)

    var scale = setMagazineScale(vw, vh);
                            
    var MIN_SCALE = 0.25;
    var MAX_SCALE = 10.1;
    var DEFAULT_SCALE_VALUE = "auto";
    var DEFAULT_SCALE_DELTA = scale ;
    $scope.scalePDF = DEFAULT_SCALE_DELTA || DEFAULT_SCALE_VALUE;

    var pdfjsLib = window['pdfjs-dist/build/pdf'];

    pdfjsLib.GlobalWorkerOptions.workerSrc = '/js/pdf.worker.js';

    var pdfDoc = null,
        pageNum = 1,
        pageNumPending = null,
        canvas = document.getElementById('pdf_canvas'),
        ctx = canvas.getContext('2d'),
        url = DEFAULT_URL,
        ticks = 0;
     
        $scope.pageRendering = false;
    /**
     * Get page info from document, resize canvas accordingly, and render page.
     * @param num Page number.
     */
    function renderPage(num, isZoom) {
    $scope.pageRendering = true;
    // Using promise to fetch the page
    pdfDoc.getPage(num)
    .then(function(page) {

        if(vw < 768) {
            //default width / height canvas
          canvas.height = Math.ceil((window.innerWidth / 2) + (window.innerWidth / 1.2));
          canvas.width = (window.innerWidth - 10);
        }

       
        $scope.hasPDF = true;

        var viewport = page.getViewport({scale: $scope.scalePDF});

            canvas.height = viewport.height;
            canvas.width = viewport.width;

            var size_margin = sizeMargin();
                var size =  (vw - (canvas.offsetWidth + size_margin )) / 2;
              
                canvas.style.position = 'absolute';
                canvas.style.left = size+'px';
                canvas.style.top = 0;
                canvas.style.zIndex = 'auto';

        // Render PDF page into canvas context
        var renderContext = {
        canvasContext: ctx,
        viewport: viewport
        };
        var renderTask = page.render(renderContext);

        // Wait for rendering to finish
        renderTask.promise.then(function() {
        $scope.pageRendering = false;
        if (pageNumPending !== null) {
            // New page rendering is pending
            renderPage(pageNumPending, isZoom);
            pageNumPending = null;
        }
        });
    });

    // Update page counters
    //document.getElementById('page_num').textContent = num;
    }

  
    /**
     * If another page rendering in progress, waits until the rendering is
     * finised. Otherwise, executes rendering immediately.
     */
    function queueRenderPage(num, isZoom) {


        if ($scope.pageRendering) {
            pageNumPending = num;
        } else {
            renderPage(num, isZoom);
        }
    }


    function showHideNavigator(num) {
        if (num > 1) {
            $scope.mag_prev = true;
            $scope.mag_next = true;
        }

        if (pdfDoc.numPages == num) {
            $scope.mag_prev = true;
            $scope.mag_next = false;
        }
    }

    /**
     * Displays previous page.
     */
    function onPrevPage() {
        $scope.mag_prev = true;
        if (pageNum <= 1) {
          
            $scope.mag_next = true;
            return;
        }
       
        pageNum--;
        showHideNavigator(pageNum);
        queueRenderPage(pageNum, false);
    }
    document.getElementById('prev').addEventListener('click', onPrevPage);

    /**
     * Displays next page.
     */
    function onNextPage() {
        $scope.mag_next = true;
        if (pageNum >= pdfDoc.numPages) {
            $scope.mag_next = false;
            $scope.mag_prev = true;
            return;
        } 
        if (pageNum > 1) {
            $scope.mag_prev = true;
        }
       
        pageNum++;
        showHideNavigator(pageNum);
        queueRenderPage(pageNum, false);
    }
    document.getElementById('next').addEventListener('click', onNextPage);


    function zoomIn() {

        var newScale = $scope.scalePDF;
        newScale += 0.5; 
      
        if (window.innerWidth > 767) {
            newScale = newScale.toFixed(2);
            newScale = Math.ceil(newScale * 10) / 10;
         }
        newScale = Math.min(MAX_SCALE, newScale);
            if(newScale < MAX_SCALE) {
               $scope.scalePDF = newScale; 
            }
            queueRenderPage(pageNum, true);   

        
    }
    document.getElementById("zoomIn").addEventListener("click", zoomIn);

 
    function zoomOut() {
       

        var newScale = $scope.scalePDF;
        newScale -= 0.5; 
        newScale = Math.max(MIN_SCALE, newScale);
       
        if(window.innerWidth > 767) {
           newScale = newScale.toFixed(2);
           newScale = Math.ceil(newScale * 10) / 10;
        }
        if (newScale > MIN_SCALE) {
           $scope.scalePDF = newScale;
        }
      
        queueRenderPage(pageNum, true);
     
        
    }
    document.getElementById("zoomOut").addEventListener("click", zoomOut);

    //TODO: scrolling page
    var canvas = document.getElementById("pdf_canvas"), num = 0, defaultScrollTop=0;
    function scrollingPage(scrollPos) {
        var distance = window.innerHeight / 10;
        var up = (scrollPos < 0);
        var down = !up;
        var max_down = Math.floor((canvas.height) - distance) - 120;
        var max_up = 0;
        var current_distance =  Math.abs(canvas.offsetTop + distance);

        if (down) {
            if (current_distance <= max_down) {
               num-=distance;
            }
        } else {
            if (canvas.offsetTop <= max_up) {
                num+=distance;
            }
        } 
        canvas.style.top = num+'px';   
      
    }
    
    document.addEventListener('wheel', function(e) {
        if(e) {
          scrollingPage(e.deltaY);
        }
    });
    /**
     * Asynchronously downloads PDF.
     */

    var ext = url.substring(url.lastIndexOf(".")).toLowerCase();
    if(ext == '.pdf') {
        $scope.isBase64PDF = false;
    } else {
        pdfData = atob(url);
        url = {data: pdfData}
        $scope.isBase64PDF = true;
    }
    pdfjsLib.getDocument(url)
    .promise.then(function(pdfDoc_) {
    pdfDoc = pdfDoc_;
   // document.getElementById('page_count').textContent = pdfDoc.numPages;

    // Initial/first page rendering
    renderPage(pageNum, false);
    }, (e) => {
        console.log(e);
    });

}

In React-native webview is:

return (
    <>
      <StatusBar backgroundColor={'#7fd233'} />
      <SafeAreaView style={{flex: 1, backgroundColor: 'white'}}>
        <WebView
          style={{flex: 1}}
          source={{uri: gutenURL}}
          onShouldStartLoadWithRequest={_onShouldStartLoadWithRequest}
          onNavigationStateChange={navState => {
            canGoBack.current = navState.canGoBack
          }}
          javaScriptEnabledAndroid
          ref={webViewRef}
          mixedContentMode={'compatibility'}
          allowsInlineMediaPlayback={true}
          allowsFullscreenVideo={true}
          javaScriptEnabled
          domStorageEnabled
          onMessage={_onMessage}
          injectedJavaScript={jsLib}
          onError={evt => {
            navigation.goBack()
            alert('Desculpe houve um erro ao carregar o conteúdo')
          }}
          onHttpError={evt => {
            navigation.goBack()
            alert('Desculpe houve um erro ao carregar o conteúdo')
          }}
          startInLoadingState
          renderLoading={() => {
            return (
              <View
                style={{
                  position: 'absolute',
                  width: '100%',
                  height: '100%',
                  justifyContent: 'center',
                  alignItems: 'center',
                }}>
                <ActivityIndicator size='large' color='#43d41f' />
              </View>
            )
          }}
          thirdPartyCookiesEnabled
          sharedCookiesEnabled
        />
      </SafeAreaView>
    </>
  )

AndroidManifest.XML:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="br.com.blablablabla">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme">
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize"
        android:launchMode="singleTask"
        >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
          <action android:name="android.intent.action.VIEW" />
          <category android:name="android.intent.category.DEFAULT" />
          <category android:name="android.intent.category.BROWSABLE" />
          <data
              android:pathPrefix="/blablabla/android/callback"
              android:scheme="blablabla" />
        </intent-filter>
        <intent-filter>
          <action android:name="android.intent.action.VIEW" />
          <category android:name="android.intent.category.DEFAULT" />
          <category android:name="android.intent.category.BROWSABLE" />
          <data android:scheme="blablabla"
                android:host="blablabla" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
    </application>

</manifest>



Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:6 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
timvandermeijcommented, Mar 26, 2021

The error message states that it doesn’t use the ES5-compatible build which is apparently necessary in your configuration, because if you were using it that error message cannot be shown at all. Moreover, it’s impossible for us to tell what goes wrong with only snippets instead of a runnable example. Finally, we’re not familiar with AngularJS and since this seems to be specific to that platform (given that it works outside of Angular), it’s probably best to ask at an AngularJS support forum instead.

1reaction
Snuffleupaguscommented, Mar 25, 2021

Same problem with the older version on ES5:

Huh; but this very clearly shows that you’re still not using the correct build type (as linked to above) since the error message simply cannot be printed if you’d actually use the ES5 version as you claim!

Please see https://github.com/mozilla/pdf.js/blob/master/.github/CONTRIBUTING.md (emphasis mine):

If you are developing a custom solution, first check the examples at https://github.com/mozilla/pdf.js#learning and search existing issues. If this does not help, please prepare a short well-documented example that demonstrates the problem and make it accessible online on your website, JS Bin, GitHub, etc. before opening a new issue or contacting us in the Matrix room – keep in mind that just code snippets won’t help us troubleshoot the problem.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Error- Loading PDF from URL inside android Webview
I am trying to load the PDF File from URL inside web-view without Downloading in android. Most of the time its loading perfectly...
Read more >
Error Opening PDF in Web View on Android - AppGyver forums
When my app starts I download several PDFs to the local file system using the cache file step. I am then displaying the...
Read more >
Fix PDF View Problems for Chrome and Edge Browsers
When you see the error after Microsoft Edge attempts to render the PDF file in the browser, click on the ( … )...
Read more >
Various ways to load PDF in Android webview - django-cas-ng
Android webview can not load PDF file by default. Luckily, there are various ways to how to load PDF file in Android webview,...
Read more >
How to view PDF in Kony Android WebView/Browser
A simpler solution, there is a component available in market place called PDF viewer, that can be used. Helpful ( ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found