Convert Figma logo to code with AI

afreakyelf logoPdf-Viewer

A Lightweight PDF Viewer Android library which only occupies around 80kb while most of the Pdf viewer occupies up to 16MB space.

1,049
217
1,049
27

Top Related Projects

Android view for displaying PDFs rendered with PdfiumAndroid

iText for Java represents the next level of SDKs for developers that want to take advantage of the benefits PDF can bring. Equipped with a better document engine, high and low-level programming capabilities and the ability to create, edit and enhance PDF documents, iText can be a boon to nearly every workflow.

[DEPRECATED] A fast PDF reader component for Android development

Create Toast like tooltips, but targets can be specified, plus custom properties and features

Quick Overview

Pdf-Viewer is an Android library that provides a simple and customizable PDF viewer for Android applications. It allows developers to easily integrate PDF viewing capabilities into their apps, offering features like zooming, page navigation, and night mode.

Pros

  • Easy integration with minimal setup required
  • Customizable UI elements and themes
  • Supports both local and remote PDF files
  • Includes night mode for better reading experience in low-light conditions

Cons

  • Limited to Android platform only
  • May have performance issues with very large PDF files
  • Lacks advanced features like text selection or annotation

Code Examples

  1. Basic PDF viewer implementation:
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val pdfView: PDFView = findViewById(R.id.pdfView)
        pdfView.fromAsset("sample.pdf").load()
    }
}
  1. Loading a PDF from a URL:
pdfView.fromUrl("https://example.com/sample.pdf")
    .defaultPage(0)
    .enableSwipe(true)
    .swipeHorizontal(false)
    .enableDoubletap(true)
    .onLoad { nbPages -> /* PDF loaded */ }
    .load()
  1. Customizing the viewer appearance:
pdfView.fromAsset("sample.pdf")
    .pages(0, 2, 4) // Show only pages 0, 2, and 4
    .enableAnnotationRendering(true)
    .enableAntialiasing(true)
    .spacing(10) // Add spacing between pages
    .nightMode(true) // Enable night mode
    .load()

Getting Started

To use Pdf-Viewer in your Android project, follow these steps:

  1. Add the JitPack repository to your project's build.gradle file:
allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}
  1. Add the dependency to your app's build.gradle file:
dependencies {
    implementation 'com.github.afreakyelf:Pdf-Viewer:Tag'
}
  1. Add the PDFView to your layout XML:
<com.github.afreakyelf.pdfviewer.PDFView
    android:id="@+id/pdfView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
  1. Load a PDF file in your activity or fragment:
val pdfView: PDFView = findViewById(R.id.pdfView)
pdfView.fromAsset("sample.pdf").load()

Competitor Comparisons

Android view for displaying PDFs rendered with PdfiumAndroid

Pros of AndroidPdfViewer

  • More mature and established project with a larger user base
  • Supports a wider range of PDF features and rendering options
  • Better performance for large PDF files

Cons of AndroidPdfViewer

  • Less actively maintained, with fewer recent updates
  • More complex implementation, requiring more setup and configuration
  • Larger library size, potentially increasing app size

Code Comparison

AndroidPdfViewer:

PDFView pdfView = findViewById(R.id.pdfView);
pdfView.fromAsset("sample.pdf")
    .pages(0, 2, 1, 3, 3, 3)
    .defaultPage(1)
    .showMinimap(false)
    .enableSwipe(true)
    .load();

Pdf-Viewer:

val pdfView = findViewById<PDFView>(R.id.pdfView)
pdfView.fromAsset("sample.pdf")
    .defaultPage(0)
    .enableSwipe(true)
    .swipeHorizontal(false)
    .load()

Both libraries offer similar basic functionality for displaying PDF files in Android applications. AndroidPdfViewer provides more advanced features and customization options, while Pdf-Viewer focuses on simplicity and ease of use. The choice between the two depends on the specific requirements of your project, such as the need for advanced PDF handling or a lightweight implementation.

iText for Java represents the next level of SDKs for developers that want to take advantage of the benefits PDF can bring. Equipped with a better document engine, high and low-level programming capabilities and the ability to create, edit and enhance PDF documents, iText can be a boon to nearly every workflow.

Pros of itext-java

  • Comprehensive PDF manipulation library with extensive features
  • Well-established project with long-term support and documentation
  • Supports both creation and modification of PDF documents

Cons of itext-java

  • Larger library size, potentially increasing app footprint
  • Steeper learning curve due to more complex API
  • Commercial licensing required for some use cases

Code Comparison

itext-java:

PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
Document document = new Document(pdf);
document.add(new Paragraph("Hello World!"));
document.close();

Pdf-Viewer:

PdfViewerFragment fragment = PdfViewerFragment.newInstance("sample.pdf");
getSupportFragmentManager().beginTransaction()
    .replace(R.id.container, fragment)
    .commit();

Summary

itext-java is a powerful PDF manipulation library offering extensive features for creating and modifying PDF documents. It provides robust functionality but comes with a steeper learning curve and potential licensing costs. Pdf-Viewer, on the other hand, focuses on PDF viewing capabilities, offering a simpler implementation for Android applications. While itext-java is more suitable for complex PDF operations, Pdf-Viewer excels in providing a straightforward solution for displaying PDF files in Android apps.

[DEPRECATED] A fast PDF reader component for Android development

Pros of android-pdfview

  • Lightweight and simple implementation
  • Supports zooming and panning of PDF documents
  • Renders PDF pages as images for smooth scrolling

Cons of android-pdfview

  • Limited features compared to more modern PDF viewers
  • Last updated in 2017, potentially outdated for current Android versions
  • Lacks advanced features like text selection or annotation support

Code Comparison

android-pdfview:

PDFView pdfView = (PDFView) findViewById(R.id.pdfview);
pdfView.fromAsset("example.pdf")
       .defaultPage(1)
       .showMinimap(false)
       .enableSwipe(true)
       .load();

Pdf-Viewer:

pdfView.fromAsset("sample.pdf")
    .password(null)
    .defaultPage(0)
    .onPageChange(this)
    .enableSwipe(true)
    .swipeHorizontal(false)
    .onLoad(this)
    .load()

The code comparison shows that both libraries have similar APIs for loading and displaying PDF files. However, Pdf-Viewer offers more configuration options and callback methods, indicating a more feature-rich implementation. android-pdfview has a simpler setup but fewer customization options.

Pdf-Viewer is a more recent project with active development, offering better compatibility with modern Android versions and additional features like password protection and page change callbacks. It also uses Kotlin, which may be preferred by developers working on newer Android projects.

Create Toast like tooltips, but targets can be specified, plus custom properties and features

Pros of android-target-tooltip

  • Specialized for creating tooltips and overlays in Android apps
  • Offers customizable tooltip appearance and positioning
  • Lightweight library focused on a single functionality

Cons of android-target-tooltip

  • Limited to tooltip functionality, not a comprehensive PDF viewer
  • May require additional libraries for more complex UI interactions
  • Less actively maintained compared to Pdf-Viewer

Code Comparison

android-target-tooltip:

val tooltip = Tooltip.Builder(context)
    .anchor(view, Tooltip.Gravity.BOTTOM)
    .text("This is a tooltip")
    .show()

Pdf-Viewer:

pdfView.fromAsset("sample.pdf")
    .defaultPage(0)
    .onPageChange { page, pageCount -> }
    .load()

The code snippets demonstrate the core functionality of each library. android-target-tooltip focuses on creating and displaying tooltips, while Pdf-Viewer is designed for loading and displaying PDF documents.

While both libraries serve different purposes, they can be complementary in an Android app that requires both PDF viewing capabilities and enhanced UI tooltips. Pdf-Viewer offers a more comprehensive solution for handling PDF documents, while android-target-tooltip provides a specialized tool for creating informative overlays and tooltips within the app's interface.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Pdf Viewer For Android

A Simple PDF Viewer library which only occupies around 80kb while most of the Pdf viewer occupies upto 16MB space.

Maven Central License Visitors CodeFactor Discord

[New] Join our Discord Community here!

✨ Major Enhancements in Our PDF Viewer Library ✨

Hello Developers! We're thrilled to share some significant enhancements we've made to our PDF viewer library. We've fine-tuned several aspects to enhance your experience and ensure top-notch performance and security. Here's what's new:

  • Jetpack Compose Ready 🚀

    Step into the future with Jetpack Compose compatibility. Integrating our PDF viewer in Compose projects is now effortless, thanks to the PdfRendererViewCompose composable function.
  • Turbocharged Performance 🏎️

    We've optimized performance to handle PDFs more efficiently, ensuring swift and smooth operations, even with large documents.
  • Local and on device files 📁

    We have made it better and smooth with how local files are handled now, with latest permission policies.
  • Seamless Orientation Adaptation 🔄

    Our library now smartly preserves your page position during orientation changes, ensuring uninterrupted reading sessions.
  • Enhanced File Path Security 🔐

    Security just got stronger. We've revamped our file path handling to provide robust protection against directory traversal attacks, keeping your data safer than ever.
  • Streamlined Caching System 💾

    Experience efficiency at its best! Our refined caching strategy smartly manages storage, retaining only the most recent PDF file to optimize performance and space usage.
  • Discreet Screenshot Prevention Feature 🚫📸

    Privacy matters. Our new screenshot-blocking feature enhances data confidentiality in your app, keeping sensitive information secure from prying eyes.
  • Flexible UI Customization ✨

    Your design, your rules. Enjoy complete freedom in customizing the PDF viewer's interface, ensuring a perfect match with your app's style and theme. Render the view directly in your screen now.
  • 'NoActionBar' Theme Compatibility 🎨

    Seamless aesthetics, no matter the theme. Our library now gracefully integrates with 'NoActionBar' themes, ensuring a cohesive and appealing user interface.

Stay tuned as we continue to innovate and improve. Happy coding, and let's keep creating amazing experiences together!

How to integrate into your app? ⚙️

We have migrated our library to Maven Central for easier integration and better reliability. To use the Pdf Viewer library in your project, add the following dependency to your build.gradle file:

Latest version: without 'v'

Groovy DSL

dependencies {
    // Replace 'latest-version' with the actual latest version number
    implementation 'io.github.afreakyelf:Pdf-Viewer:latest-version'
}

Kotlin DSL

dependencies {
    // Replace 'latest-version' with the actual latest version number
    implementation("io.github.afreakyelf:Pdf-Viewer:latest-version")
}

Requirements:

  • Minimum SDK version: 21
  • Compile & Target SDK version: 35 (updated since version 2.2.0)

How to use the library?

Now you have integrated the library in your project but how do you use it? Well it's really easy. Just launch the intent with in following way: (Refer to MainActivity.kt for more details.)

Prerequisites

Ensure the library is included in your project's dependencies.

Launching PDF Viewer

Opening PDF from a URL

To display a PDF from a URL, use the following code:

/* Parameters:
- context: The context of your activity.
- pdfUrl: URL of the PDF to be displayed.
- pdfTitle: Title of the PDF document.
- saveTo: Determines how to handle saving the PDF (e.g., ASK_EVERYTIME prompts the user each time).
- enableDownload: Enables downloading of the PDF. */

PdfViewerActivity.launchPdfFromUrl(
    context = this,
    pdfUrl = "your_pdf_url_here",
    pdfTitle = "PDF Title",
    saveTo = saveTo.ASK_EVERYTIME,
    enableDownload = true
)

Opening PDF from Local Storage

To open a PDF stored in local storage:

/* Parameters:
- path: File path or URI of the local PDF.
- fromAssets: Set to false when loading from local storage. // FALSE by default
*/

PdfViewerActivity.launchPdfFromPath(
    context = this,
    path = "your_file_path_or_uri_here",
    pdfTitle = "Title",
    saveTo = saveTo.ASK_EVERYTIME,
    fromAssets = false
)

Opening PDF from Assets

To open a PDF from the app's assets folder:

/* Parameters:
- path: File path or URI of the local PDF.
- fromAssets: Set to true when loading from assets.
*/

PdfViewerActivity.launchPdfFromPath(
  context = this,
  path = "file_name_in_assets",
  pdfTitle = "Title",
  saveTo = saveTo.ASK_EVERYTIME,
  fromAssets = true
)

Loading PDF in a View

Load a PDF directly into a view:

Add PDF render view in your layout file

<com.rajat.pdfviewer.PdfRendererView
    android:id="@+id/pdfView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:pdfView_divider="@drawable/pdf_viewer_divider"
    app:pdfView_showDivider="false" />

and in your kotlin file

binding.pdfView.initWithUrl(
  url = "your_pdf_url_here",
  lifecycleCoroutineScope = lifecycleScope,
  lifecycle = lifecycle
)

Using with Jetpack Compose

For Jetpack Compose, utilize PdfRendererViewCompose:

PdfRendererViewCompose(
    source = PdfSource.Remote("your_pdf_url_here"),
    lifecycleOwner = LocalLifecycleOwner.current,
    modifier = Modifier,
    headers = HeaderData(mapOf("Authorization" to "123456789")),
    statusCallBack = object : PdfRendererView.StatusCallBack {
                // Override functions here
    },
    zoomListener = object : PdfRendererView.ZoomListener {
                // Override functions here
        override fun onZoomChanged(isZoomedIn: Boolean, scale: Float) {
                    TODO("Not yet implemented")
         }
     }
)

That's all you need to integrate PDF rendering in your Compose application.

Track PDF Load & Zoom Events

You can monitor download progress, rendering success, page changes, and zoom state using the following callbacks:

PDF Load Status

Use the statusListener to get callbacks on PDF lifecycle events:

binding.pdfView.statusListener = object : PdfRendererView.StatusCallBack {
    override fun onPdfLoadStart() {
        Log.i("PDF Status", "Loading started")
    }

    override fun onPdfLoadProgress(progress: Int, downloadedBytes: Long, totalBytes: Long?) {
        Log.i("PDF Status", "Download progress: $progress%")
    }

    override fun onPdfLoadSuccess(absolutePath: String) {
        Log.i("PDF Status", "Load successful: $absolutePath")
    }

    override fun onError(error: Throwable) {
        Log.e("PDF Status", "Error loading PDF: ${error.message}")
    }

    override fun onPageChanged(currentPage: Int, totalPage: Int) {
        Log.i("PDF Status", "Page changed: $currentPage / $totalPage")
    }
  
    override fun onPdfRenderStart() {
      Log.i("PDF Status", "Render started")
    }

    override fun onPdfRenderSuccess() {
      Log.i("PDF Status", "Render successful")
      binding.pdfView.jumpToPage($number)  // Recommend to use `jumpToPage` inside `onPdfRenderSuccess`
    }
}

Zoom Change Listener

You can also monitor when the user zooms in or out using zoomListener:

binding.pdfView.zoomListener = object : PdfRendererView.ZoomListener {
    override fun onZoomChanged(isZoomedIn: Boolean, scale: Float) {
        Log.i("PDF Zoom", "Zoomed in: $isZoomedIn, Scale: $scale")
    }
}

Ui Customizations

You need to add the custom theme to styles.xml/themes.xml file and override the required attribute values. Parent theme can be either Theme.PdfView.Light or Theme.PdfView.Dark or the one with no actionbar from the application. Note: If parent is not one of the themes from this library, all of the pdfView attributes should be added to that theme.

<style name="Theme.PdfView.SelectedTheme" parent="@style/Theme.PdfView.Light">
    <item name="pdfView_backIcon">@drawable/ic_arrow_back</item>
    <item name="pdfView_showToolbar">true</item>
    <item name="pdfView_disableScreenshots">true</item>
    ...
</style>

Ui Customizations - Page number

You need to add the custom layout to pdf_view_page_no.xml file and override the required attribute values.

<?xml version="1.0" encoding="utf-8"?>  
<TextView xmlns:android="http://schemas.android.com/apk/res/android"  
  android:id="@+id/pageNo"  
  android:layout_width="wrap_content"  
  android:layout_height="wrap_content"  
  android:layout_margin="18dp"  
  android:background="#9C27B0"  
  android:paddingStart="12dp"  
  android:paddingTop="4dp"  
  android:paddingEnd="12dp"  
  android:paddingBottom="4dp"  
  android:textColor="#ffffff"  
  android:textSize="16sp"  
  android:visibility="gone" />

Ui Page number

You need to add the custom string to strings.xml file and override the required strings.xml values.

Default:

<string name="pdfView_page_no">%1$s of %2$s</string>

Custom:

<string name="pdfView_page_no" >%1$s / %2$s</string>

Supported attributes

Attribute NameTypeExpected changes
pdfView_backIcondrawableNavigation icon
pdfView_downloadIcondrawableDownload icon
pdfView_downloadIconTintcolorDownload icon tint
pdfView_toolbarColorcolorActionbar background color
pdfView_titleTextStylestyleActionbar title text appearance
pdfView_progressBarstyleProgress bar style

Who's using Pdf-Viewer?

👉 Check out who's using Pdf-Viewer

Contributing

Any contributions you make are greatly appreciated.

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/NewFeature)
  3. Commit your Changes (git commit -m 'Add some NewFeature')
  4. Push to the Branch (git push origin feature/NewFeature)
  5. Open a Pull Request

Donations

If this library helps you save time during development, you can buy me a cup of coffee :)

paypal

Author

Maintained by Rajat Mittal