Search code examples
androidandroid-webview

Show blank page in showing pdf via Googler drive in Android webview


I show my pdfs via https://docs.google.com/viewer?embedded=true&url={my pdf link} in WebView. Sometimes my WebView shows a blank page without any error in "onReceivedError" method. Why this blank page show?


Solution

  • Take this as an example.

    class PdfViewActivity : AppCompatActivity() {
        private lateinit var activityPdfViewBinding: ActivityPdfViewBinding
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            activityPdfViewBinding = DataBindingUtil.setContentView(this, R.layout.activity_pdf_view)
            val path =  "https://github.github.com/training-kit/downloads/github-git-cheat-sheet.pdf" // Add Your URL here
            loadPdfFromURL(path)
        }
    
        @SuppressLint("SetJavaScriptEnabled")
        private fun loadPdfFromURL(path: String?) {
            activityPdfViewBinding.webview.settings.loadWithOverviewMode = true
            activityPdfViewBinding.webview.settings.javaScriptEnabled = true
            val url = "https://docs.google.com/gview?embedded=true&url=$path"
            activityPdfViewBinding.webview.loadUrl(url)
        }
    }
    

    also, add these lines into onPageFinished method

    if (view.getTitle().equals("")) { 
       view.reload();
    }