This is a fork of the AndroidPdfViewer
switch back to the mainline repo when it gets migrated off JCenter
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.
Link to the Changelog
Add to build.gradle:
allprojects {
repositories {
...
maven { url 'https://maven.infomaniak.app/releases' }
mavenCentral()
...
}
}or build.gradle.kts:
dependencyResolutionManagement {
repositories {
...
maven(url = "https://maven.infomaniak.app/releases")
mavenCentral()
...
}
}implementation("com.infomaniak.pdfview:android-pdfview:3.2.18")
If you are using ProGuard, add following rule to proguard config file:
-keep class com.shockwave.**
<com.infomaniak.lib.pdfview.PDFView
android:id="@+id/pdfView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>All available options with default values:
pdfView.fromUri(Uri)
or
pdfView.fromFile(File)
or
pdfView.fromBytes(byte[])
or
pdfView.fromStream(InputStream) // stream is written to bytearray - native code cannot use Java Streams
or
pdfView.fromSource(DocumentSource)
or
pdfView.fromAsset(String)
.pages(0, 2, 1, 3, 3, 3) // all pages are displayed by default
.enableSwipe(true) // allows to block changing pages using swipe
.swipeHorizontal(false)
.enableDoubletap(true)
.defaultPage(0) // allows to draw something on the current page, usually visible in the middle of the screen
.onDraw(onDrawListener) // allows to draw something on all pages, separately for every page. Called only for visible pages
.onDrawAll(onDrawListener) // called after document is loaded and starts to be rendered
.onLoad(onLoadCompleteListener)
.onPageChange(onPageChangeListener)
.onPageScroll(onPageScrollListener)
.onError(onErrorListener)
.onPageError(onPageErrorListener) // called after document is rendered for the first time
.onRender(onRenderListener) // called on single tap, return true if handled, false to toggle scroll handle visibility
.onTap(onTapListener)
.onLongPress(onLongPressListener)
.enableAnnotationRendering(false) // render annotations (such as comments, colors or forms)
.password(null)
.scrollHandle(null) // improve rendering a little bit on low-res screens
.enableAntialiasing(true) // spacing between pages in dp. To define spacing color, set view background
.pageSeparatorSpacing(PDF_VIEW_HANDLE_TEXT_INDICATOR_SIZE_DP)
.autoSpacing(false) // add dynamic spacing to fit each page on its own on the screen
.linkHandler(DefaultLinkHandler)
.pageFitPolicy(FitPolicy.WIDTH) // mode to fit pages in the view
.fitEachPage(false) // fit each page to the view, else smaller pages are scaled relative to largest page.
.pageSnap(false) // snap pages to screen boundaries
.pageFling(false) // make a fling change only a single page like ViewPager
.nightMode(false) // toggle night mode
.enableTextSelection(false) // long press + drag to select text on a single page
.onSelectionAction(onSelectionActionListener) // called when the selection action popup is tapped (or copySelection() is called)
.onSelectionChange(onSelectionChangeListener) // called when selection becomes active or is cleared
.selectionPopupEnabled(true) // set to false to use your own copy UI (default: true)
.selectionHandleColor(Color) // color of the selection handles (default: #2196F3)
.selectionHighlightColor(Color) // color of the text highlight overlay (default: semi-transparent blue)
.selectionPopupBackgroundColor(Color) // background color of the action popup (default: #323232)
.selectionPopupTextColor(Color) // text color of the action popup (default: white)
.selectionPopupText(CharSequence) // label of the action popup (default: locale "Copy")
.searchHighlightColor(Color) // color of the matches of a text search, see PDFView#search() (default: semi-transparent yellow)
.searchCurrentHighlightColor(Color) // color of the current match of a text search (default: semi-transparent orange)
.onSearchResult(onSearchResultListener) // called when the result of a text search changes
.load();pagesis optional, it allows you to filter and order the pages of the PDF as you need
If you're using PDFView inside a ViewPager, make sure to enable touchPriority(true) when initializing PDFView.
This ensures that PDFView has touch priority, allowing users to zoom and navigate within the document. However, if the user
swipes and reaches the edge of the PDFView, the touch control is returned to the ViewPager, enabling seamless page
transitions.
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.infomaniak.lib.pdfview.source package and can be used as samples for creating custom ones.
Predefined providers can be used with shorthand methods:
pdfView.fromUri(Uri)
pdfView.fromFile(File)
pdfView.fromBytes(byte[])
pdfView.fromStream(InputStream)
pdfView.fromAsset(String)
Custom providers may be used with pdfView.fromSource(DocumentSource) method.
Version 3.0.0 introduced support for links in PDF documents. By default, DefaultLinkHandler is used and clicking on link that references page in same document causes jump to destination page and clicking on link that targets some URI causes opening it in default application.
You can also create custom link handlers, just implement LinkHandler interface and set it using
Configurator#linkHandler(LinkHandler) method. Take a look at DefaultLinkHandler
source to implement custom behavior.
Text selection can be enabled with Configurator#enableTextSelection(true).
- Long press on text to start selection
- Drag your finger to extend/reduce the selection
- Draggable handles are displayed at the start and end of the selection to resize it
- A popup is displayed above the selection with a configurable action label (defaults to the locale-appropriate word for "Copy")
- Receive the selected text when that action is tapped with
Configurator#onSelectionAction(...) - Read selected text with
PDFView#getSelectedText() - Clear current selection with
PDFView#clearTextSelection()
All visual aspects of text selection can be configured via the Configurator:
pdfView.fromUri(uri)
.enableTextSelection(true)
.onSelectionAction { selectedText -> /* handle selected text */ }
.onSelectionChange { hasSelection -> /* show/hide your own copy button */ }
.selectionPopupEnabled(true) // set to false to disable the built-in popup (default: true)
.selectionHandleColor(Color.BLUE) // color of the draggable handles (default: #2196F3)
.selectionHighlightColor(0x6633B5E5) // color of the text highlight overlay (default: semi-transparent blue)
.selectionPopupBackgroundColor(Color.DKGRAY) // background color of the action popup (default: #323232)
.selectionPopupTextColor(Color.WHITE) // text color of the action popup (default: white)
.selectionPopupText("Copy") // label shown in the popup (default: locale string "Copy"/"Copier"/…)
.load()If you provide your own copy button (e.g. in a TopAppBar), disable the built-in popup and use
pdfView.copySelection() to programmatically trigger the action:
pdfView.fromUri(uri)
.enableTextSelection(true)
.selectionPopupEnabled(false)
.onSelectionChange { hasSelection -> myToolbar.copyButton.isVisible = hasSelection }
.onSelectionAction { selectedText -> clipboard.setPrimaryClip(...) }
.load()
// In your button click handler:
binding.copyButton.setOnClickListener { pdfView.copySelection() }PDFView searches a text in the document and highlights the matches, there is nothing else to set up:
pdfView.search("invoice") // ignores the case, matches parts of words
pdfView.search("invoice", true, false) // matchCase, matchWholeWord
pdfView.goToNextSearchMatch()
pdfView.goToPreviousSearchMatch()
pdfView.clearSearch()search(...)looks for the text in the pages displayed by the view, in the background. It highlights every match and makes the first one from the current page the current match: it's highlighted with its own color, and the view scrolls to it- A new search cancels the running one, so it can be called each time the user types a letter. A blank text is the same as
clearSearch() goToNextSearchMatch()andgoToPreviousSearchMatch()change the current match, and go around the document- The search is cleared when another document is loaded
- Nothing is searched as long as the document isn't loaded, call it from
onLoador later
The result is given by Configurator#onSearchResult(...), to show something like "3 / 12":
pdfView.fromUri(uri)
.onSearchResult { matchCount, currentMatchIndex ->
// matchCount is 0 if nothing was found, and currentMatchIndex is -1 then
status.text = if (matchCount > 0) "${currentMatchIndex + 1} / $matchCount" else "No results"
}
.load()The sample has a complete example, with a search field in its toolbar.
Known limitations, which come from the search of PDFium:
- Only the text of the pages is searched, a scanned page without text has no result
- Accents are not ignored:
elevedoesn't matchélève - A word hyphenated at the end of a line is not matched as a whole
The colors can be configured via the Configurator (or later with PDFView#setSearchHighlightColor(Int) and
PDFView#setSearchCurrentHighlightColor(Int)):
pdfView.fromUri(uri)
.searchHighlightColor(Color.argb(100, 255, 235, 59)) // color of the matches (default: semi-transparent yellow)
.searchCurrentHighlightColor(Color.argb(180, 255, 152, 0)) // color of the current match (default: semi-transparent orange)
.load()Since version 3.0.0, library supports fitting pages into the screen in 3 modes:
- WIDTH - width of widest page is equal to screen width
- HEIGHT - height of highest page is equal to screen height
- BOTH - based on widest and highest pages, every page is scaled to be fully visible on screen
Apart from selected policy, every page is scaled to have size relative to other pages.
Fit policy can be set using Configurator#pageFitPolicy(FitPolicy). Default policy is WIDTH.
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.
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:
void setMinZoom(float zoom);
void setMidZoom(float zoom);
void setMaxZoom(float zoom);Pinch zoom is constrained to the 0.3f–100f range. Requested minimum and maximum values are
clamped to that range while processing a pinch gesture. If the resulting maximum is below the
resulting minimum, the effective maximum is raised to the effective minimum, so the pinch range
remains valid. The same behavior applies to Configurator#zoom(float, float, float).
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.
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.
You have to store current page number and then set it with pdfView.defaultPage(page), refer to sample app
Use FitPolicy.WIDTH policy or add following snippet when you want to fit desired page in document with different page sizes:
Configurator.onRender(new OnRenderListener() {
@Override
public void onInitiallyRendered(int pages, float pageWidth, float pageHeight) {
pdfView.fitToWidth(pageIndex);
}
});You can use a combination of the following settings to get scroll and fling behaviour similar to a ViewPager:
.swipeHorizontal(true)
.pageSnap(true)
.autoSpacing(true)
.pageFling(true)If you have any suggestions on making this lib better, write me, create issue or write some code and send pull request.
You can find a sample project in the sample folder.
Infomaniak kDrive allows you to manage your Infomaniak files in a completely secure environment.
Created with the help of android-pdfview by Joan Zapata
Copyright 2017 Bartosz Schiller
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.