1. Project Overview
In modern applications, PDF format is widely used in e-books, reports, contracts, data reading and other scenarios due to its cross-platform, good stability, and consistent display content. On the Android platform, how to efficiently open local PDF files not only affects the user experience, but also directly affects the function richness of the application. In actual projects, there are two main ways to open local PDF files:
External call method
Use Intent to call the installed PDF reader program of the system and pass the local PDF file to the program for display. This method is low in development and simple in implementation. The disadvantage is that it requires relying on third-party PDF readers, and the user experience will vary from reader to reader.Embed display method
Integrate third-party PDF reading libraries (such as AndroidPdfViewer, PdfRenderer, MuPDF, etc.) to directly parse and display PDF files in your own applications. This method can provide users with a unified and customized reading experience, but it needs to consider issues such as library compatibility, performance, and memory usage.
This project aims to help developers fully master the key technologies of opening local PDF files on the Android platform by introducing the principles, advantages and disadvantages, implementation steps and specific code examples of the above two implementation methods. The content of the article is mainly divided into the following parts:
Project background and application scenarios
Related knowledge introduction
Comparison of implementation ideas and solutions
Code integration and detailed comments
Code interpretation and key technology analysis
Project summary and extended discussion
Practical suggestions and future prospects
Through the introduction of the overall architecture, key modules and detailed processing of the project, this article can not only help beginners quickly realize the function of opening local PDF files, but also provide reference for experienced developers, making it easier to carry out secondary development and technical expansion in actual projects.
2. Related knowledge
Before opening a local PDF file, you need to master the following related knowledge:
2.1 Basic Overview of PDF Files
Introduction to PDF format
PDF (Portable Document Format) is a portable document format launched by Adobe in 1993. Its features fixed document content and format and can be displayed correctly on different devices. It is often used in e-books, reports, instructions, contracts, invoices and other scenarios.PDF reading principle
The internal structure of PDF files includes text, images, vector graphics, forms, attachments, etc. parsing PDF files requires page rendering, text and image extraction, vector graphics drawing and other functions. On the Android platform, PDF Renderer (API21 and above) or third-party libraries included with the system can be used to implement PDF rendering.
2.2 Android file access and storage permissions
File Read PermissionsAccessing local PDF files usually requires reading external storage, so relevant permissions need to be declared in them, e.g.
<uses-permission android:name=".READ_EXTERNAL_STORAGE"/>
At the same time, under Android 6.0 (API 23) and above, you also need to apply for permission dynamically at runtime.
File path and FileProvider
In order to access files safely, especially in Android 7.0 (API 24) and later, in order to solve the problem of File URI exposure, FileProvider needs to be used to generate content:// URI, convert the path of the local PDF file into a URI that can be accessed by other applications.
2.3 Calling the system PDF reader
Intent calling mechanism
Android uses the Intent mechanism to allow communication between applications. When you need to open a PDF file, you can construct an Intent of type ACTION_VIEW, and pass the URI and MIME types of the file (usually "application/pdf") to the system. The system will automatically select an installed PDF reader to handle it.-
Frequently Asked Questions
What should be noted is:If the PDF reader is not installed in the system, the Intent call may fail. At this time, exception capture and prompt the user;
File URI needs to be passed through FileProvider, otherwise FileUriExposedException will occur in Android 7.0 or above.
2.4 Third-party PDF reading library
AndroidPdfViewer
Currently, an open source PDF reading library is a popular open source PDF rendering based on PdfiumAndroid, with good performance and interactive experience. The integration method is simple. You just need to add dependencies in Gradle and then refer to the PDFView control in the layout to render and page turn.PdfRenderer
The Android system provides the PdfRenderer class starting from API21, which can be directly used to render PDF pages, but the functions are relatively basic and support rotation, zoom and page switching, but the interactive experience needs to be expanded by the developers.Other open source libraries
In addition to the above two, there are MuPDF, PdfBox-Android and other libraries. Different libraries have their own emphasis on performance, volume, and function expansion. Developers can choose according to actual project needs.
2.5 Dynamic permissions and FileProvider configuration
Dynamic permissions
In Android 6.0 and above, reading external storage permissions is a dangerous permission, and users need to be requested for authorization when the application is running. You need to use the() method to request permissions and receive the user's authorization result in the onRequestPermissionsResult() method.FileProvider configuration
In order to use FileProvider, you need to declare FileProvider in it, and create the file_paths.xml file in the res/xml directory to configure the directory that is allowed to access, so as to safely share the file URI.
Ideas for project implementation
This project implements the implementation of opening local PDF files mainly provides two implementation solutions, the specific ideas are as follows:
3.1 External call method: use Intent to open PDF
Authorization application
Declare the READ_EXTERNAL_STORAGE permission in the Activity and dynamically request the permission in the activity.File access and URI conversion
Get the path to the local PDF file (can be saved in the SD card or internal storage) and use FileProvider to convert the File object to the content:// URI.Construct Intent
Create an Intent of type ACTION_VIEW, pass the generated URI and MIME type "application/pdf" to the Intent, and set the FLAG_GRANT_READ_URI_PERMISSION flag.Start Activity
Call startActivity (intent) to start the system PDF reader. If the PDF reader is not installed in the system, the ActivityNotFoundException is captured and the user is prompted to download and install the PDF reader.Exception handling
For situations such as non-existence of files, unauthorized permissions, and illegal URIs of files, users will be given corresponding prompts to ensure application stability.
3.2 Embedded display method: Use third-party PDF reading library
Integrated third-party library
Add such a AndroidPdfViewer dependency (such as ":android-pdf-viewer:3.2.0-beta.1") to Gradle to ensure that the version is compatible with the current project requirements.Design layout
Add PDFView control to the layout file to display PDF documents.Read PDF files
In Activity or Fragment, get the InputStream of a PDF file through the file path or FileProvider and pass it to the PDFView control for parsing and rendering.Interactive design
Third-party libraries generally have built-in gesture operations (page turn, zoom, drag, etc.). Developers can configure gesture control and display options according to their needs, such as whether to display directories, bookmarks, page numbers, etc.Error handling and performance optimization
Consider issues such as large file loading, page caching, memory overflow, etc., and optimize the settings according to the library's documents, and give the user an error prompt when an exception occurs.
3.3 Comparison and selection
External call method
Advantages: The implementation is simple, and there is no need to maintain PDF rendering logic in the APP, and it depends on the system or third-party readers; Disadvantages: The user experience is not unified and it depends on external applications.Embed display method
Advantages: It can customize a unified user interface and interactive experience, control of PDFs more flexible, and supports more custom functions; Disadvantages: The integration cost is high, and it is necessary to pay attention to performance, compatibility and library maintenance and updates.
In actual projects, you can choose a suitable solution based on project positioning and user needs; if it is only a temporary preview of PDF files, the Intent method can be given priority; if the application focuses on PDF reading experience, it is recommended to integrate a third-party PDF reading library.
4. Integrate code
The following are two complete sets of example codes, which correspond to external calling methods and embedded display methods, and are accompanied by detailed comments and instructions.
4.1 External call method
4.1.1 Configuration
Declare permissions in Manifest and configure FileProvider (note that file_paths.xml needs to be created at the same time).
<!-- --> <manifest xmlns:andro package=""> <!-- Apply for external storage permissions --> <uses-permission android:name=".READ_EXTERNAL_STORAGE"/> <application android:allowBackup="true" android:label="PDFOpener" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:theme="@style/AppTheme"> <!-- hostActivity --> <activity android:name=".MainActivity"> <intent-filter> <action android:name=""/> <category android:name=""/> </intent-filter> </activity> <!-- ConfigurationFileProvider --> <provider android:name="" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name=".FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"/> </provider> </application> </manifest>
4.1.2 file_paths.xml file (placed in the res/xml/ directory)
<!-- res/xml/file_paths.xml --> <paths xmlns:andro> <!-- Allow access to all files in the specified directory in the external storage --> <external-path name="external_files" path="."/> </paths>
4.1.3 (Calling external PDF reader)
package ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; /** * MainActivity * * This Activity shows how to use Intent to open PDF files locally, * Use FileProvider to get the content:// URI and call the system PDF reader. */ public class MainActivity extends AppCompatActivity { private static final int REQUEST_READ_STORAGE = 100; private Button btnOpenPDF; @Override protected void onCreate(Bundle savedInstanceState) { (savedInstanceState); setContentView(.activity_main_pdf); btnOpenPDF = findViewById(.btn_open_pdf); // Check READ_EXTERNAL_STORAGE permissions if ((this, .READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { (this, new String[]{.READ_EXTERNAL_STORAGE}, REQUEST_READ_STORAGE); } (v -> { // Here, assume that the PDF file is located in the Download directory of external storage and the file name is File pdfFile = new File(( Environment.DIRECTORY_DOWNLOADS), ""); if (!()) { (, "PDF file does not exist", Toast.LENGTH_SHORT).show(); return; } // Get content URI through FileProvider Uri pdfUri = (, getApplicationContext().getPackageName() + ".fileprovider", pdfFile); // Create an Intent, set the type to application/pdf Intent intent = new Intent(Intent.ACTION_VIEW); (pdfUri, "application/pdf"); // Authorize temporary read permissions (Intent.FLAG_GRANT_READ_URI_PERMISSION); try { startActivity(intent); } catch (ActivityNotFoundException e) { (, "No app found to open PDF, please install PDF reader", Toast.LENGTH_LONG).show(); } }); } /** * Dynamic request permission callback */ @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == REQUEST_READ_STORAGE) { if (!( > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)) { (this, "Storage read permissions are required", Toast.LENGTH_LONG).show(); } } (requestCode, permissions, grantResults); } }
4.1.4 activity_main_pdf.xml layout file
<!-- res/layout/activity_main_pdf.xml --> <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:andro android: android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center" android:padding="16dp"> <Button android: android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Open local PDF file" /> </LinearLayout>
4.2 Embedded display method: Integrate Android PdfViewer library
The following describes how to display PDF files in an embedded application and use the open source library AndroidPdfViewer to implement it. This library relies on PdfiumAndroid to achieve efficient PDF parsing and display.
4.2.1 Gradle dependency configuration
Add the following dependencies to the project's app module:
dependencies { // Other dependencies... implementation ':android-pdf-viewer:3.2.0-beta.1' }
At the same time, make sure to add the jitpack repository in the project root directory:
allprojects { repositories { google() jcenter() maven { url '' } } }
4.2.2 Layout file (activity_pdf_viewer.xml)
Add PDFView control to the layout:
<!-- res/layout/activity_pdf_viewer.xml --> <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:andro android: android:layout_width="match_parent" android:layout_height="match_parent"> < android: android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>
4.2.3
Create an Activity to load and display PDF files. This example loads a PDF file from local storage, similar to external calling methods, and can also be used in conjunction with FileProvider to read the file safely.
package ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; /** * PDFViewerActivity * * This Activity shows how to load and present local PDF files inside the app using the AndroidPdfViewer library. */ public class PDFViewerActivity extends AppCompatActivity { private static final int REQUEST_READ_STORAGE = 101; private PDFView pdfView; @Override protected void onCreate(Bundle savedInstanceState) { (savedInstanceState); setContentView(.activity_pdf_viewer); pdfView = findViewById(); if ((this, .READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { (this, new String[]{.READ_EXTERNAL_STORAGE}, REQUEST_READ_STORAGE); } else { loadPdf(); } } private void loadPdf() { // Suppose the PDF file is located in the Download directory and the file name is File pdfFile = new File(( Environment.DIRECTORY_DOWNLOADS), ""); if (!()) { (, "PDF file does not exist", Toast.LENGTH_SHORT).show(); return; } // Load PDF files using PDFView (pdfFile) .enableSwipe(true) // Support sliding page turn .swipeHorizontal(false) // false is vertical sliding .enableDoubletap(true) // Support double-click zoom .defaultPage(0) // Default first page .load(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == REQUEST_READ_STORAGE) { if ( > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { loadPdf(); } else { (this, "Requires read storage permission to open PDF files", Toast.LENGTH_LONG).show(); } } (requestCode, permissions, grantResults); } }
And add this button in the corresponding layout.
5. Code interpretation
The following is a detailed explanation of the core implementation logic and key points in the above code.
5.1 External call method
Authorization application
First check and dynamically apply for READ_EXTERNAL_STORAGE permission in MainActivity to ensure that external storage files can be accessed.FileProvider configuration
By configuring FileProvider in Manifest and defining permission access directories in res/xml/file_paths.xml, the local file path is guaranteed to convert the local file path into a secure content URI, thereby avoiding FileUriExposedException in Android 7.0 and above.Intent construction and startup
When constructing the Intent of ACTION_VIEW, set the URI and MIME types of the file to "application/pdf" by setDataAndType(), and set the FLAG_GRANT_READ_URI_PERMISSION flag to ensure that the target application has permission to read the file; call startActivity() to start the system PDF reader.Exception capture
If there is no application that can open PDF files in the system, the ActivityNotFoundException is captured and the user is prompted to download and install the PDF reader.
5.2 Embed display method
Third-party library integration
Use Gradle to introduce the Android PdfViewer library, and refer to its documents to load PDF files through PDFView control. Use the (file).load() method to implement file reading and page rendering.Interactive experience configuration
The PDFView control has a variety of built-in gesture operations, which supports page turn, zoom, double-click, etc. Developers can adjust the interaction effect by configuring enableSwipe(), swipeHorizontal(), enableDoubletap() and other methods to improve the user's reading experience.Error handling
It is also necessary to check whether the file exists. If it does not exist, the user will be prompted and dynamic permission applications will be processed to ensure that the application can run normally on all versions of the system.
5.3 Permissions and Compatibility
Dynamic permission processing
Combined with () to implement dynamic permission application, and give prompts for situations where they are not authorized.FileProvider usage
Prevent the use of file://URI directly causing exceptions in the new version of the system, and convert it to content://URI through FileProvider to ensure safe data transmission.
5.4 Pros and cons of the two solutions
External call method
Advantages: It implements simple and dependent system applications without introducing huge libraries; Disadvantages: The user experience is limited by other PDF readers, and the ability to customize interactions and interfaces is insufficient.Embed display method
Advantages: Customizable interfaces and operations, integrated within the application, and unified user experience; Disadvantages: It is necessary to integrate third-party libraries, which may introduce dependency and performance tuning issues.
6. Project Summary
This project introduces in detail two common methods and key technologies to open local PDF files on the Android platform:
External call method
Using Intent and FileProvider to call the installed PDF reader of the system to open local PDF files, the development process is simple and the implementation cost is low, but the user experience depends on third-party applications.Embed display method
Integrate third-party PDF reading libraries (such as AndroidPdfViewer) to directly display PDF files in the application, providing a customized reading experience, suitable for projects with high requirements for PDF reading.
Through the introduction of relevant knowledge (such as basic PDF concepts, file storage and permission management, Intent calling mechanism, FileProvider configuration, etc.), combined with detailed implementation ideas and step-by-step code analysis, this project provides developers with a complete set of implementation solutions. The code section is accompanied by detailed comments to help readers understand the functions and implementation details of each module line by line.
6.1 Technical Highlights
Dynamic permission application and FileProvider configuration ensure secure access to local files under the latest Android version.
Use the Intent mechanism to call system applications to show the easiest way to open files.
Integrate the Android PdfViewer library to implement embedded PDF reading, providing good user interaction and customized expansion capabilities.
6.2 Application scenarios
Applications that require the display of PDF files for internal document viewing tools, e-book readers, contract management systems, etc.
In scenarios where user reading experience needs to be unified and controlled, it is recommended to use embedded display.
When you have a simple preview or temporary file viewing, you can quickly call the system reader using the Intent method.
6.3 Development Suggestions
Before development, be sure to check the file path and permissions on the target device to avoid application crashes caused by permission issues.
Consider a variety of error handling situations and design friendly user prompt information, such as the file does not exist, the permissions are not authorized, or the PDF reader is not installed.
For embedded display mode, pay attention to the version update and compatibility test of third-party libraries to ensure that they can run smoothly on different Android versions and devices.
Choose the appropriate plan according to the actual needs of the project and make a balance between user experience and development costs.
7. Practical suggestions and future prospects
In future development, this function can be further expanded and optimized from the following aspects:
-
Advanced interactive features
Added functions such as directory navigation, bookmark management, and full-text search to improve the PDF reading experience.
Supports personalized functions such as night mode, font adjustment, page rotation, etc., making reading more convenient and comfortable.
-
Performance optimization
Optimize the loading speed and memory management of large files, and adopt paging loading or caching strategies.
Encapsulate system APIs such as PdfRenderer and adapt to devices lower than API21 to improve compatibility.
-
Data protection and security
Add encryption and decryption mechanism when reading sensitive documents to protect user privacy data from illegal disclosure.
Use custom FileProvider to configure more granular access control to ensure secure sharing of application files.
-
Integrate with online services
Supports obtaining PDF files from the server and cache them locally, and automatically detecting document updates.
Establish a cloud document management system to realize cross-device synchronization and online annotation functions.
-
Multi-platform expansion
Encapsulate some functional modules into independent libraries and implement similar functions in other platforms (such as desktop systems and iOS).
Explore the implementation of a declarative PDF reading interface using Jetpack Compose, combining the latest Android development trends.
8. Conclusion
This article introduces in detail two main methods to open local PDF files on the Android platform: one is to open PDF files through the Intent call system PDF reader, and the other is to integrate a third-party PDF reading library to display PDF documents inside the application. The full text provides a comprehensive and in-depth analysis of the entire implementation process from project overview, related theories, implementation ideas, to complete code, annotation and interpretation, practical suggestions and future prospects.
Whether you are a beginner or an experienced developer, through this article, you can systematically understand how to process file permissions in Android, use FileProvider, construct Intents, and integrate third-party libraries to realize the reading function of PDF files. I hope this article can provide sufficient reference and help for your blog writing and project development, and continuously optimize the user experience in actual work to achieve higher quality and professional applications.
The above is the detailed content of two ways to open local pdf files on Android. For more information about Android opening local pdf files, please follow my other related articles!