- Open a PDF in an Android App
- Displaying PDFs Using the Android SDK
- Displaying PDFs with MuPDF
- Rendering PDFs with the Android PdfViewer Library
- PSPDFKit for Android
- Conclusion
- Android developer pdf view
- Android developer pdf view
- About
- Работа с PDF. Чтение PDF-файлов
- Шаг 1. Создание списка PDF-файлов
- Шаг 2. Создание активности для просмотра
- Заключение
- Работа с PDF. Чтение PDF-файлов : 2 комментария
Open a PDF in an Android App
PDF documents are the de facto standard for archiving, transferring, and presenting documents online. Android developers frequently need to display PDF documents within their applications, so in this article, we’ll look at different solutions for doing exactly that.
We’ll begin with the basic PDF support provided by the Android SDK library, move on to MuPDF, and finally look at rendering PDFs with the Android PdfViewer library.
Displaying PDFs Using the Android SDK
The Android SDK has had basic support for PDF files since API level 21 (Android 5.0). This API resides in a package, android.graphics.pdf , and it supports basic low-level operations, such as creating PDF files and rendering pages to bitmaps. The Android SDK doesn’t provide a UI for interacting with PDF documents, so you’ll need to write your own UI to handle user interaction if you wish to use it as a basis for a PDF viewer in your app.
The main API entry point is PdfRenderer , which provides an easy way to render single pages into bitmaps:
You can now set these rendered bitmaps into an ImageView or build your own UI that handles multi-page documents, scrolling, and zooming.
Now, we’ll introduce two libraries that support basic, ready-to-use UIs for displaying documents.
Displaying PDFs with MuPDF
One of the most widely known PDF libraries is MuPDF. It’s available either as a commercial solution or under an open source (AGPL) license.
MuPDF provides a small and fast viewer with a basic UI. Embedding it in your app is simple:
You can now open the MuPDF viewer activity by launching an intent with a document URI:
Using DocumentActivity is enough for most basic use cases. MuPDF ships with its entire source code, so you can build any required functionality on top of it.
ℹ️ Note: MuPDF also supports other document formats on top of PDF, such as XPS, CBZ, EPUB, and FictionBook 2.
Rendering PDFs with the Android PdfViewer Library
Android PdfViewer is a library for displaying PDF documents. It has basic support for page layouts, zooming, and touch gestures. It’s available under the Apache License, Version 2.0 and, as such, is free to use, even in commercial apps.
Integration is simple. Start with adding a library dependency to your build.gradle file:
Then add the main PDFView to the layout where you wish to view the PDFs:
Now you can load the document in your activity:
PSPDFKit for Android
The above solutions are free or open source libraries with viewer capabilities. However, the PDF spec is fairly complex, and it defines many more features on top of the basic document viewing capabilities. We at PSPDFKit offer a comprehensive PDF solution for Android and other platforms, along with first-class support included with every plan. PSPDFKit comes with a fully featured document viewer with a modern customizable user interface and a range of additional features such as:
Interactive forms with JavaScript support
Document editing (both programmatically and through the UI)
If you’re interested in our solution, visit the Android product page to learn more and download a free trial.
Conclusion
In this post, we outlined some of the available free PDF viewer libraries for Android that can help you render PDFs. However, if you want to add more advanced features to your PDF viewer — such as PDF annotation support, interactive PDF forms, and digital signatures — you should consider looking into commercial alternatives.
At PSPDFKit, we offer a commercial, feature-rich, and completely customizable Android PDF library that’s easy to integrate and comes with well-documented APIs to handle complex use cases. Try our PDF library using our free trial and check out our demos to see what’s possible.
Источник
Android developer pdf view
Android PDF view — small (73kB .aar file,
400 methods before minification) and efficient PDF viewer embedded in your native app
It is based on ImageView and can handle big files with reasonable scrolling and zooming performance.
This is how fast scrolling of 680 page document looks like on low-end device:
To show pdf you just need a file on the device.
See sources for other methods to provide a file.
If pdf is on remote host — use your network client to download it to the cache folder, then show it. This library provides view, it doesn’t do network requests.
There is a sample of how to do it.
Add to your project:
The library is hosted in the central repository.
Add gradle dependency:
Please take a look into the wiki to find out the technical details.
Contributions are welcome. Just open PR to dev branch.
Feel free to open issue with any questions.
Thanks to Manuel Lilienberg for initial implementation of this library and subsampling-scale library for influence.
Источник
Android developer pdf view
AndroidPdfViewer 1.x is available on AndroidPdfViewerV1 repo, where can be developed independently. Version 1.x uses different engine for drawing document on canvas, so if you don’t like 2.x version, try 1.x.
Library for displaying PDF documents on Android, with animations , gestures , zoom and double tap support. It is based on PdfiumAndroid for decoding PDF files. Works on API 11 (Android 3.0) and higher. Licensed under Apache License 2.0.
What’s new in 2.8.0?
- Add handling of invalid pages, inspired by pull request #433. Exception on page opening crashed application until now, currently OnPageErrorListener set with Configurator#onPageError() is called. Invalid page color ( Color class) can be set using Configurator#invalidPageColor()
- Implement canScrollVertically() and canScrollHorizontally() methods to work e.g. with SwipeRefreshLayout
- Fix bug when Configurator#load() method was called before view has been measured, which resulted in empty canvas
2.8.1 fixes bug with rendering PDFView in Android Studio Layout Editor
2.8.2 fixes not loaded pages when using animated PDFView#jumpTo()
Changes in 2.0 API
- Configurator#defaultPage(int) and PDFView#jumpTo(int) now require page index (i.e. starting from 0)
- OnPageChangeListener#onPageChanged(int, int) is called with page index (i.e. starting from 0)
- removed scrollbar
- added scroll handle as a replacement for scrollbar, use with Configurator#scrollHandle()
- added OnPageScrollListener listener due to continuous scroll, register with Configurator#onPageScroll()
- default scroll direction is vertical, so Configurator#swipeVertical() was changed to Configurator#swipeHorizontal()
- removed minimap and mask configuration
Add to build.gradle:
Library is available in jcenter repository, probably it’ll be in Maven Central soon.
Include PDFView in your layout
Load a PDF file
All available options with default values:
- pages is optional, it allows you to filter and order the pages of the PDF as you need
Scroll handle is replacement for ScrollBar from 1.x branch.
From version 2.1.0 putting PDFView in RelativeLayout to use ScrollHandle is not required, you can use any layout.
To use scroll handle just register it using method Configurator#scrollHandle() . This method accepts implementations of ScrollHandle interface.
There is default implementation shipped with AndroidPdfViewer, and you can use it with .scrollHandle(new DefaultScrollHandle(this)) . DefaultScrollHandle is placed on the right (when scrolling vertically) or on the bottom (when scrolling horizontally). By using constructor with second argument ( new DefaultScrollHandle(this, true) ), handle can be placed left or top.
You can also create custom scroll handles, just implement ScrollHandle interface. All methods are documented as Javadoc comments on interface source.
Version 2.3.0 introduced document sources, which are just providers for PDF documents. Every provider implements DocumentSource interface. Predefined providers are available in com.github.barteksc.pdfviewer.source package and can be used as samples for creating custom ones.
Predefined providers can be used with shorthand methods:
Custom providers may be used with pdfView.fromSource(DocumentSource) method.
By default, generated bitmaps are compressed with RGB_565 format to reduce memory consumption. Rendering with ARGB_8888 can be forced by using pdfView.useBestQuality(true) method.
Double tap zooming
There are three zoom levels: min (default 1), mid (default 1.75) and max (default 3). On first double tap, view is zoomed to mid level, on second to max level, and on third returns to min level. If you are between mid and max levels, double tapping causes zooming to max and so on.
Zoom levels can be changed using following methods:
Why resulting apk is so big?
Android PdfViewer depends on PdfiumAndroid, which is set of native libraries (almost 16 MB) for many architectures. Apk must contain all this libraries to run on every device available on market. Fortunately, Google Play allows us to upload multiple apks, e.g. one per every architecture. There is good article on automatically splitting your application into multiple apks, available here. Most important section is Improving multiple APKs creation and versionCode handling with APK Splits, but whole article is worth reading. You only need to do this in your application, no need for forking PdfiumAndroid or so.
Why I cannot open PDF from URL?
Downloading files is long running process which must be aware of Activity lifecycle, must support some configuration, data cleanup and caching, so creating such module will probably end up as new library.
How can I show last opened page after configuration change?
You have to store current page number and then set it with pdfView.defaultPage(page) , refer to sample app
How can I fit document to screen width (eg. on orientation change)?
Use this code snippet:
If you have any suggestions on making this lib better, write me, create issue or write some code and send pull request.
Created with the help of android-pdfview by Joan Zapata
About
Android view for displaying PDFs rendered with PdfiumAndroid
Источник
Работа с PDF. Чтение PDF-файлов
Android не всегда умел работать с PDF-файлами. Вплоть до версии Android 4.4 KitKat (API 19) у нас не было возможности просматривать PDF-файлы, кроме как используя сторонние приложения, такие как Google Drive PDF Viewer или другой нативный ридер на устройстве.
Начиная с Android 5.0 Lolipop (API 21) появилось API под названием PDFRenderer, с помощью которого можно выводить содержимое PDF-файлов. В этой статье мы создадим приложение, которое открывает PDF-файлы на устройстве для чтения.
Создадим новый проект, указав для него минимальную версию SDK Android 5.0 Lolipop. Для навигации приложения и дальнейшей работы с ним выберем Navigation Drawer Activity.
Шаг 1. Создание списка PDF-файлов
Перед тем, как начать работу, нужно предоставить приложению разрешения. Для этого в AndoridManifest.xml добавим следующие разрешения на чтение и запись.
На MainActivity мы будем получать список PDF-файлов, которые находятся в хранилище устройства. Для этого на файле разметки content_main.xml добавим компонент ListView.
Также нужно создать разметку для элемента в списке. Создадим в res/layout файл разметки list_item.xml и добавим в него следующий код.
Найденные файлы нужно сохранять в модель, чтобы затем передать в список. Для этого создадим класс PdfFile, в котором будут определены 2 поля (имя файла и путь), а также сеттеры и геттеры для изменения полей.
После этого в коде активности перед началом работы нужно проверить версию Android. Если версия ниже Android 6.0 M — инициализируем создание списка, в противном случае нужно проверить разрешения.
Метод checkPermission() проверяет наличие разрешения на чтение внешнего хранилища. Если разрешения имеются, то инициализируем создание списка, иначе запрашиваем разрешения. Пользователю будет показан диалог, предлагающий предоставить приложению разрешение, результат этого вернётся в метод onRequestPermissionsResult() активности.
В методе initViews() нам нужно инициализировать список. Для этого вызываем внутри метод initList(), который будет рекурсивно вызываться до тех пор, пока не будет проверен каждый каталог. В результате выполнения initList() будет заполнен список найденными PDF-файлами, который затем будет передан в адаптер. В адаптере переопределяются методы в соответствии с тем, что нам нужно, в частности в методе getView() мы получаем созданную для элемента разметку и устанавливаем в поле имя файла.
Шаг 2. Создание активности для просмотра
Здесь мы создадим активность, в которой будет просматриваться выбранный PDF-файл. Отрендеренная страница PDF будет загружаться в компонент ImageView. Также здесь будут располагаться кнопки переключения страниц и увеличения/уменьшения масштаба страницы.
Добавим Empty Activity, назвав PdfActivity, и в коде разметки активности добавим следующий код.
При запуске активности в методе onCreate() получаем имя и путь файла из интента, а также определяем компоненты и устанавливает слушатели на кнопки.
Затем в методе onStart() вызывается метод openPdfRenderer(), в котором происходит получение дескриптора файла для поиска PDF и создание объекта PdfRenderer. После этого вызывается метод displayPage(), который рендерит выбранную страницу.
Что касается метода displayPage(), в нём для каждой страницы, которую нужно отрендерить, открываем эту страницу, рендерим её и закрываем страницу. В результате рендера страница сохраняется в Bitmap с заданными размерами и зумом, после чего загружается в ImageView.
Обработчики кнопок вынесены в onClick(), здесь ничего особенного нет: кнопки «Назад» и «Вперёд» изменяют текущий индекс страницы в нужную сторону и вызывают метод displayPage(), аналогично кнопки зума изменяют уровень зума и вызывают метод displayPage() с текущим индексом.
Для того, чтобы при перевороте экрана запомнить текущий индекс страницы, переопределён метод onSaveInstanceBundle(), в котором в бандл помещается индекс страницы. Затем этот индекс забирается в onCreate() активности, что было показано выше.
При завершении работы и закрытии активности нужно закрыть PdfRenderer, для этого в переопределённом методе onStop() вызывается метод closePdfRenderer(), в котором удаляются все данные рендера.
В результате получилось простое приложение, способное открывать и показывать PDF-файлы.
Заключение
В этой статье мы рассмотрели, как можно использовать PdfRenderer API для отображения PDF-файлов в приложении. В следующей статье мы рассмотрим, как создать свой PDF-файл.
Работа с PDF. Чтение PDF-файлов : 2 комментария
Доброго времени суток.
Всё круто, но)
Для рендеринга нужно что бы страница умещалась во вьюху
// определяем размеры Bitmap
int newWidth = (int) (getResources().getDisplayMetrics().widthPixels * curPage.getWidth() / 72
* currentZoomLevel / 40);//45
int newHeight = (int) (getResources().getDisplayMetrics().heightPixels * curPage.getHeight() / 72
* currentZoomLevel / 65);//90
Bitmap bitmap = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
Matrix matrix = new Matrix();
float dpiAdjustedZoomLevel = currentZoomLevel * DisplayMetrics.DENSITY_MEDIUM
/ getResources().getDisplayMetrics().densityDpi;
matrix.setScale(dpiAdjustedZoomLevel, dpiAdjustedZoomLevel);
curPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
Далее, вместо скролов и ImageView, я сделал так:
Отлично маштабируется и намного приятнее)
Но всё равно спасибо, статья неплохая.
Источник