Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Use Custom Chrome Tabs in Android?
Next article icon

How to Load PDF from URL in Android?

Last Updated : 01 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Most of the apps require to include support to display PDF files in their app. So if we have to use multiple PDF files in our app it is practically not possible to add each PDF file inside our app because this approach may lead to an increase in the size of the app and no user would like to download the app with such a huge size. So to tackle this issue related to the size we will load PDF files from the server directly inside our app without actually saving that files inside our app. Loading PDF files from the server will help us to manage the increase in the size of our app. So in this article, we will take a look at How to Load PDF files from URLs inside our Android App. 

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.

Step 2: Add dependency to build.gradle(Module:app)

Navigate to the Gradle Scripts > build.gradle.kts (Module:app) and add the below dependency in the dependencies section. 

dependencies {
...
implementation ("com.github.mhiew:android-pdf-viewer:3.2.0-beta.3")
}

Refer to this github repo for the documentation

Now sync option will appear at the top right corner click on the sync now option.  

Step 3: Add permission to the internet in your AndroidManifest.xml file

Add below two lines inside your AndroidManifest.xml file.

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

Step 4: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

activity_main.xml:

XML
<?xml version="1.0" encoding="utf-8"?> <LinearLayout     xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:id="@+id/main"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".MainActivity">      <!--PDF Viewer to display our PDF-->     <com.github.barteksc.pdfviewer.PDFView         android:id="@+id/pdfView"         android:layout_width="match_parent"         android:layout_height="match_parent" />  </LinearLayout> 


Step 5: Working with the MainActivity file

Navigate to the app > java > your apps package name > MainActivity.java file. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. 

MainActivity.java
package org.geeksforgeeks.demo;  import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.Toast;  import androidx.activity.EdgeToEdge; import androidx.appcompat.app.AppCompatActivity; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat;  import com.github.barteksc.pdfviewer.PDFView;  import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL;  import javax.net.ssl.HttpsURLConnection;  public class MainActivity extends AppCompatActivity {      // Declare the PDFView variable to display the PDF file.     private PDFView pdfView;      // URL of the PDF file to be loaded.     private static final String PDF_URL = "https://icseindia.org/document/sample.pdf";      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         EdgeToEdge.enable(this);         setContentView(R.layout.activity_main);          ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {             WindowInsetsCompat systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());             v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);             return insets;         });          // Initialize the PDFView from the layout.         pdfView = findViewById(R.id.pdfView);          // Load the PDF from the specified URL.         new LoadPdfTask().execute(PDF_URL);     }      /**      * AsyncTask to load PDF in the background to prevent UI blocking.      */     private class LoadPdfTask extends AsyncTask<String, Void, InputStream> {          @Override         protected InputStream doInBackground(String... strings) {             return fetchPdfStream(strings[0]);         }          @Override         protected void onPostExecute(InputStream inputStream) {             if (inputStream != null) {                 pdfView.fromStream(inputStream).load();             } else {                 Toast.makeText(MainActivity.this, "Failed to load PDF. Check your internet connection.", Toast.LENGTH_SHORT).show();             }         }     }      /**      * Fetches the PDF InputStream from the given URL.      * Uses HTTPS connection to securely download the PDF file.      */     private InputStream fetchPdfStream(String urlString) {         try {             URL url = new URL(urlString);             HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();              // Check if the connection response is successful (HTTP 200 OK).             if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {                 return new BufferedInputStream(urlConnection.getInputStream());             } else {                 return null;             }         } catch (IOException e) {             e.printStackTrace();             return null;         }     } } 
MainActivity.kt
package org.geeksforgeeks.demo  import android.os.Bundle import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.github.barteksc.pdfviewer.PDFView import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.BufferedInputStream import java.io.IOException import java.io.InputStream import java.net.HttpURLConnection import java.net.URL import javax.net.ssl.HttpsURLConnection  class MainActivity : AppCompatActivity() {      // Declare the PDFView variable to display the PDF file.     private lateinit var pdfView: PDFView      // URL of the PDF file to be loaded.     private val pdfUrl = "https://icseindia.org/document/sample.pdf"      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         enableEdgeToEdge()         setContentView(R.layout.activity_main)         ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->             val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())             v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)             insets         }          // Initialize the PDFView from the layout.         pdfView = findViewById(R.id.pdfView)          // Load the PDF from the specified URL.         loadPdfFromUrl(pdfUrl)     }      // Loads the PDF file from the given URL using coroutines to prevent blocking the main thread.     private fun loadPdfFromUrl(url: String) {         CoroutineScope(Dispatchers.IO).launch {             // Fetch the InputStream of the PDF file.             val inputStream = fetchPdfStream(url)              // Switch back to the main thread to update UI.             withContext(Dispatchers.Main) {                 inputStream?.let {                     // Load the PDF into the PDFView.                     pdfView.fromStream(it).load()                 }             }         }     }      // Fetches the PDF InputStream from the given URL.     // Uses HTTPS connection to securely download the PDF file.     private fun fetchPdfStream(urlString: String): InputStream? {         return try {             val url = URL(urlString)             val urlConnection = url.openConnection() as HttpsURLConnection              // Check if the connection response is successful (HTTP 200 OK).             if (urlConnection.responseCode == HttpURLConnection.HTTP_OK) {                 BufferedInputStream(urlConnection.inputStream)             } else {                 null             }         } catch (e: IOException) {             // Print the error in case of a network failure.             e.printStackTrace()             null         }     } } 


Output: 


Next Article
How to Use Custom Chrome Tabs in Android?

C

chaitanyamunje
Improve
Article Tags :
  • Java
  • Technical Scripter
  • Android
  • Technical Scripter 2020
  • Android Projects
Practice Tags :
  • Java

Similar Reads

  • How to Play Video from URL in Android?
    In this article, you will see how to play a video from a URL on Android. For showing the video in our Android application we will use the VideoView widget. The VideoView widget is capable of playing media files, and the formats supported by the VideoView are 3gp and MP4. By using VideoView you can p
    3 min read
  • How to Play Audio from URL in Android?
    Many apps require the feature to add the audio feature in their application and there so many audio files that we have to play inside our application. If we will store so many audio files inside our application, then it will increase the size of the app and this may reduce the user base due to the h
    4 min read
  • How to Load SVG from URL in Android ImageView?
    It is seen that many Android apps require to use of high-quality images that will not get blur while zooming. So we have to use high-quality images. But if we are using PNG images then they will get blur after zooming because PNG images are made up of pixels and they will reduce their quality after
    4 min read
  • Load PDF From URL in Android with Kotlin
    PDF View is most of the applications to display the PDF files within the application to display the pdf within our own application rather than redirecting to another application. If we want to display multiple pdf files within our application we have to host these files and then access these files w
    4 min read
  • How to Use Custom Chrome Tabs in Android?
    Many apps have to display different types of web pages inside their application. For displaying webpages in Android there are so many features with which we can display webpages in our Android app. Developers generally prefer to use WebView or redirect users to any browser inside their application.
    3 min read
  • How to Read a Text File in Android?
    A text file is a type of file that can store a sequence of characters or text. These characters can be anything that is human-readable. Such kind of files does not have any formatting for the text like Bold, Italics, Underline, Font, Font Size, etc. A Text file in Android can be used for accessing o
    3 min read
  • How to Extract Data from PDF file in Android?
    PDF is a portable document format that is used to represent data such as images, tables, and many more. Nowadays the use of PDF is increased rapidly in different fields. Many apps have switched overusing PDF files to represent data. So some of the apps have a requirement to extract the data from the
    4 min read
  • How to Load Image From URL in Android using Jetpack Compose?
    Most of the applications in android use images for displaying some useful information within the applications. Images are considered as easy to convey information to the user. An android application uses more than 100 different types of images. So it is not practically possible to add all the images
    4 min read
  • How to Share Image From URL with Intent in Android?
    In this article, we will see how can we share images and text with Android Intent. In this activity URL of an image to be shared will be given with extra text and we will open the Dialog where the user chooses using which he wants to share this image as shown on the screen. A sample video is given b
    5 min read
  • How to Open PDF From URL in Android Without Any Third Party Libraries?
    There are lots of libraries that are available online but it takes lots of space and time to render you can see these articles if you want to load pdf using third-party libraries Load PDF from URL in Android. But today we are going to load PDFs without using any third-party libraries the main purpos
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences