- Работа с PDF. Чтение PDF-файлов
- Шаг 1. Создание списка PDF-файлов
- Шаг 2. Создание активности для просмотра
- Заключение
- Работа с PDF. Чтение PDF-файлов : 2 комментария
- 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
- How to Load PDF from URL in Android?
- Implementation of PDFView
- Step by Step Implementation
- How to Build an Android PDF Viewer Using Java
- View a PDF using the Android SDK
- View a PDF using PDFTron
Работа с 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, я сделал так:
Отлично маштабируется и намного приятнее)
Но всё равно спасибо, статья неплохая.
Источник
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.
Источник
How to Load PDF from URL in Android?
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.
Implementation of PDFView
For adding this PDF View we are using a library that will help us to load PDF from URL. Note that we are going to implement this project using the Java language.
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. Note that select Java as the programming language.
Step 2: Add dependency to build.gradle(Module:app)
Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.
Now sync option will appear at the top right corner click on the sync now option.
Источник
How to Build an Android PDF Viewer Using Java
In order to let users view PDF documents in an Android app, it’s common practice to defer this functionality to a third-party app on the user’s device. By doing so, developers won’t have to build their own PDF viewer from scratch, however this isn’t always the best solution. What if you want to view PDF documents directly in your app? Luckily, the Android SDK provides classes to handle PDF documents in apps running Android 5.0 or higher.
In this blog post, we’ll use PdfRenderer from the android.graphics.pdf package to create a basic PDF viewer in your Android app. Then, we’ll see how easy it is to implement a document viewer using the PDFTron SDK. Here are a few steps to get you started.
For reference, the sample code for this post can be found at Github.
View a PDF using the Android SDK
To keep things simple, we’re going to view a PDF file stored in the raw resource folder (i.e. res/raw/sample.pdf ). Your app will also need to set the minimum API level to 21 (Android 5.0).
Add PdfRenderer and PdfRenderer.Page member variables to your activity so that we can clean them up later. You’ll also need to add an ImageView to your activity in order to display the PDF:
In order for PdfRenderer to handle PDFs from the res/raw folder, we’ll need to copy the file and cache it locally. Add this method to your activity:
Then you can display a page from your PDF by loading it to an ImageView as a bitmap:
The sample above will look something like this:
As you can see, using PdfRenderer is an easy way to create a simple single-page PDF viewer in your Android app. However if you need users to interact with a PDF document, then I’m afraid you’re out of luck. The Android SDK does not provide any basic UI controls for PDF viewing like page zooming and scrolling, and PdfRenderer only supports opening one page at a time — you’ll need to write your own UI to handle user interaction and multi-page documents.
Additionally, PdfRenderer does not support password-protected or encrypted files, and uses PDFium for rendering which only works well with simple documents. You could run in to some rendering inconsistencies or failures when working with more complex or unsupported PDF documents. For a more stable and interactive viewing experience you’ll have to look elsewhere for a solution.
Fortunately, PDFTron’s Android PDF SDK comes with a fully-featured document viewer that includes these basic controls in addition to features such as:
Also it’s easy as pie to integrate with your Android app, here’s how!
View a PDF using PDFTron
We’ll be using DocumentActivity as our PDF viewer. Set up this activity as described in this short guide .
From your main activity, open the PDF document in DocumentActivity by calling:
That’s it! You now have a fully-featured document viewer in your Android app.
Out of the box, PDFTron provides an interactive document viewer that can be easily integrated into existing Android apps with dozens of features , giving users a better document viewing experience. What’s even better is that it’s highly customizable, allowing for feature customization and UI theming to fit all use-cases.
To get started just download our [free trial>(/documentation/android/get-started/) and explore our guides & documentation for our Android PDF library .
If you have any questions about PDFTron’s Android PDF SDK, please feel free to get in touch !
You can find the source code for this blog post at Github.
Источник