├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── android-pdf-viewer ├── build.gradle ├── publish-mavencentral.gradle └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── github │ │ └── barteksc │ │ └── pdfviewer │ │ ├── AnimationManager.java │ │ ├── CacheManager.java │ │ ├── DecodingAsyncTask.java │ │ ├── DragPinchManager.java │ │ ├── PDFView.java │ │ ├── PagesLoader.java │ │ ├── PdfFile.java │ │ ├── RenderingHandler.java │ │ ├── exception │ │ ├── FileNotFoundException.java │ │ └── PageRenderingException.java │ │ ├── link │ │ ├── DefaultLinkHandler.java │ │ └── LinkHandler.java │ │ ├── listener │ │ ├── Callbacks.java │ │ ├── OnDrawListener.java │ │ ├── OnErrorListener.java │ │ ├── OnLoadCompleteListener.java │ │ ├── OnLongPressListener.java │ │ ├── OnPageChangeListener.java │ │ ├── OnPageErrorListener.java │ │ ├── OnPageScrollListener.java │ │ ├── OnRenderListener.java │ │ └── OnTapListener.java │ │ ├── model │ │ ├── LinkTapEvent.java │ │ └── PagePart.java │ │ ├── scroll │ │ ├── DefaultScrollHandle.java │ │ └── ScrollHandle.java │ │ ├── source │ │ ├── AssetSource.java │ │ ├── ByteArraySource.java │ │ ├── DocumentSource.java │ │ ├── FileSource.java │ │ ├── InputStreamSource.java │ │ └── UriSource.java │ │ └── util │ │ ├── ArrayUtils.java │ │ ├── Constants.java │ │ ├── FileUtils.java │ │ ├── FitPolicy.java │ │ ├── MathUtils.java │ │ ├── PageSizeCalculator.java │ │ ├── SnapEdge.java │ │ └── Util.java │ └── res │ ├── drawable │ ├── default_scroll_handle_bottom.xml │ ├── default_scroll_handle_left.xml │ ├── default_scroll_handle_right.xml │ └── default_scroll_handle_top.xml │ └── values │ └── attrs.xml ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── sample ├── build.gradle └── src │ └── main │ ├── AndroidManifest.xml │ ├── assets │ └── sample.pdf │ ├── java │ └── com │ │ └── github │ │ └── barteksc │ │ └── sample │ │ └── PDFViewActivity.java │ └── res │ ├── drawable-hdpi │ └── ic_open_in_browser_grey_700_48dp.png │ ├── drawable-mdpi │ └── ic_open_in_browser_grey_700_48dp.png │ ├── drawable-xhdpi │ └── ic_open_in_browser_grey_700_48dp.png │ ├── drawable-xxhdpi │ └── ic_open_in_browser_grey_700_48dp.png │ ├── drawable-xxxhdpi │ └── ic_open_in_browser_grey_700_48dp.png │ ├── drawable │ └── ic_launcher.png │ ├── layout │ └── activity_main.xml │ ├── menu │ └── options.xml │ └── values │ ├── strings.xml │ └── styles.xml └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | build/ 3 | lint.xml 4 | bin/ 5 | gen/ 6 | .settings 7 | .project 8 | .classpath 9 | out 10 | gen-external-apklibs/ 11 | classes/ 12 | 13 | # Local configuration file (sdk path, etc) 14 | local.properties 15 | 16 | # Android Studio 17 | .idea/ 18 | */out 19 | !*/build/apk/ 20 | */production/ 21 | *.iws 22 | *.ipr 23 | *.iml 24 | *~ 25 | *.swp 26 | 27 | # gradle 28 | .gradle 29 | 30 | .DS_Store -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 3.2.0-beta.3 (2022-05-22) 2 | * Change minimum SDK version to 19 3 | * Drop MIPS support 4 | * Update to Androidx 5 | * Switch pdfium-android to a [fork](https://github.com/mhiew/PdfiumAndroid) so we can disable jetifier 6 | 7 | ## 3.2.0-beta.2 (2021-12-27) 8 | * Fix a potential NPE due to out of sync render thread management [Pull Request](https://github.com/barteksc/AndroidPdfViewer/pull/824) 9 | * Update the sample app configuration so that it can compile [Pull Request](https://github.com/mhiew/AndroidPdfViewer/pull/2) 10 | 11 | ## 3.2.0-beta.1 (2019-08-18) 12 | * Merge PR #714 with optimized page load 13 | * Merge PR #776 with fix for max & min zoom level 14 | * Merge PR #722 with fix for showing right position when view size changed 15 | * Merge PR #703 with fix for too many threads 16 | * Merge PR #702 with fix for memory leak 17 | * Merge PR #689 with possibility to disable long click 18 | * Merge PR #628 with fix for hiding scroll handle 19 | * Merge PR #627 with `fitEachPage` option 20 | * Merge PR #638 and #406 with fixed NPE 21 | * Merge PR #780 with README fix 22 | * Update compile SDK and support library to 28 23 | * Update Gradle and Gradle Plugin 24 | 25 | ## 3.1.0-beta.1 (2018-06-29) 26 | * Merge pull request #557 for snapping pages (scrolling page by page) 27 | * merge pull request #618 for night mode 28 | * Merge pull request #566 for `OnLongTapListener` 29 | * Update PdfiumAndroid to 1.9.0, which uses `c++_shared` instead of `gnustl_static` 30 | * Update Gradle Plugin 31 | * Update compile SDK and support library to 26 32 | * Change minimum SDK to 14 33 | 34 | ## 3.0.0-beta.5 (2018-01-06) 35 | * Fix issue with `Configurator#pages()` from #486 36 | * Fix `IllegalStateException` from #464 37 | * Fix not detecting links reported in #447 38 | 39 | ## 3.0.0-beta.4 (2017-12-15) 40 | * Fix not loaded pages when using animated `PDFView#jumpTo()` 41 | * Fix NPE in `canScrollVertically()` and `canScrollHorizontally()` 42 | 43 | ## 3.0.0-beta.3 (2017-11-18) 44 | * Fix bug preventing `OnErrorListener` from being called 45 | 46 | ## 3.0.0-beta.2 (2017-11-15) 47 | * Fix rendering with maximum zoom 48 | * Improve fit policies 49 | * Update PdfiumAndroid to 1.8.1 50 | 51 | ## 3.0.0-beta.1 (2017-11-12) 52 | * Add support for documents with different page sizes 53 | * Add support for links 54 | * Add support for defining page fit policy (fit width, height or both) 55 | * Update sample.pdf to contain different page sizes 56 | 57 | ## 2.8.1 (2017-11-11) 58 | * Fix bug with rendering `PDFView` in Android Studio Layout Editor 59 | 60 | ## 2.8.0 (2017-10-31) 61 | * Add handling of invalid pages, inspired by pull request #433. Exception on page opening crashed application until now, 62 | currently `OnPageErrorListener` set with `.onPageError()` is called. Invalid page color can be set using `.invalidPageColor()` 63 | * Implement `canScrollVertically()` and `canScrollHorizontally()` methods to work e.g. with `SwipeRefreshLayout` 64 | * Fix bug when `Configurator#load()` method was called before view has been measured, which resulted in empty canvas 65 | 66 | ## 2.7.0 (2017-08-30) 67 | * Merge pull request by [owurman](https://github.com/owurman) with added OnTapListener 68 | * Merge bugfix by [lzwandnju](https://github.com/lzwandnju) to prevent `ArithmeticException: divide by zero` 69 | 70 | ## 2.7.0-beta.1 (2017-07-05) 71 | * Updates PdfiumAndroid to 1.7.0 which reduces memory usage about twice and improves performance by using RGB 565 format (when not using `pdfView.useBestQuality(true)`) 72 | 73 | ## 2.7.0-beta (2017-06-16) 74 | * Update PdfiumAndroid to 1.6.1, which fixed font rendering (issue #253) 75 | * Add `.spacing(int)` method to add spacing (in dp) between document pages 76 | * Fix drawing with `.onDraw(onDrawListener)` 77 | * Add `.onDrawAll(onDrawListener)` method to draw on all pages 78 | * Add small rendering improvements 79 | * Fix rendering when duplicated pages are passed to `.pages(..)` 80 | 81 | ## 2.6.1 (2017-06-08) 82 | * Fix disappearing scroll handle 83 | 84 | ## 2.6.0 (2017-06-04) 85 | * Fix fling on single-page documents 86 | * Greatly improve overall fling experience 87 | 88 | ## 2.5.1 (2017-04-08) 89 | * Temporarily downgrade PdfiumAndroid until #253 will be fixed 90 | 91 | ## 2.5.0 (2017-03-23) 92 | * Update PdfiumAndroid to 1.6.0, which is based on newest Pdfium from Android 7.1.1. It should fix many rendering and fonts problems 93 | * Add method `pdfView.fitToWidth()`, which called in `OnRenderListener.onInitiallyRendered()` will fit document to width of the screen (inspired by [1stmetro](https://github.com/1stmetro)) 94 | * Add change from pull request by [isanwenyu](https://github.com/isanwenyu) to get rid of rare IllegalArgumentException while rendering 95 | * Add `OnRenderListener`, that will be called once, right before document is drawn on the screen 96 | * Add `Configurator.enableAntialiasing()` to improve rendering on low-res screen a little bit (as suggested by [majkimester](majkimester)) 97 | * Modify engine to not block UI when big documents are loaded 98 | * Change `Constants` interface and inner interfaces to static public classes, to allow modifying core config values 99 | 100 | ## 2.4.0 (2016-12-30) 101 | * Merge pull request by [hansinator85](https://github.com/hansinator85) which allows to enable/disable rendering during scale 102 | * Make rendering during scale disabled by default (looks better) 103 | * Merge pull request by [cesquivias](https://github.com/cesquivias) which replaces RenderingAsyncTask with Handler to simply code and work with testing frameworks 104 | 105 | ## 2.3.0 (2016-11-19) 106 | * Add mechanism for providing documents from different sources - more info in README 107 | * Update PdfiumAndroid to 1.5.0 108 | * Thanks to document sources and PdfiumAndroid update, in-memory documents are supported 109 | * Fix not working OnClickListener on PDFView 110 | * **com.github.barteksc.exception.FileNotFoundException** is deprecated and all usages was removed. 111 | All exceptions are delivered to old Configurator#onError() listener. 112 | 113 | ## 2.2.0 (2016-11-15) 114 | * Merge pull request by [skarempudi](https://github.com/skarempudi) which fixes SDK 23 permission problems in sample app 115 | * Merge pull request by skarempudi for showing info on phones without file manager 116 | * Add feature from 1.x - canvas is set to drawable from View#getBackground() 117 | 118 | ## 2.1.0 (2016-09-16) 119 | * fixed loading document from subfolder in assets directory 120 | * fixed scroll handle NPE after document loading error (improvement of 2.0.3 fix) 121 | * fixed incorrect scroll handle position with additional views in RelativeLayout 122 | * improved cache usage and fixed bug with rendering when zooming 123 | * if you are using custom scroll handle: scroll handle implementation changed a little bit, check DefaultScrollHandle source for details 124 | 125 | ## 2.0.3 (2016-08-30) 126 | * Fix scroll handle NPE after document loading error 127 | 128 | ## 2.0.2 (2016-08-27) 129 | * Fix exceptions caused by improperly finishing rendering task 130 | 131 | ## 2.0.1 (2016-08-16) 132 | * Fix NPE when onDetachFromWindow is called 133 | 134 | ## 2.0.0 (2016-08-14) 135 | * few API changes 136 | * improved rendering speed and accuracy 137 | * added continuous scroll - now it behaves like Adobe Reader and others 138 | * added `fling` scroll gesture for velocity based scrolling 139 | * added scroll handle as a replacement for scrollbar 140 | 141 | ### Changes in 2.0 API 142 | * `Configurator#defaultPage(int)` and `PDFView#jumpTo(int)` now require page index (i.e. starting from 0) 143 | * `OnPageChangeListener#onPageChanged(int, int)` is called with page index (i.e. starting from 0) 144 | * removed scrollbar 145 | * added scroll handle as a replacement for scrollbar, use with `Configurator#scrollHandle()` 146 | * added `OnPageScrollListener` listener due to continuous scroll, register with `Configurator#onPageScroll()` 147 | * default scroll direction is vertical, so `Configurator#swipeVertical()` was changed to `Configurator#swipeHorizontal()` 148 | * removed minimap and mask configuration 149 | 150 | ## 1.4.0 (2016-07-25) 151 | * Fix NPE and IndexOutOfBound bugs when rendering parts 152 | * Merge pull request by [paulo-sato-daitan](https://github.com/paulo-sato-daitan) for disabling page change animation 153 | * Merge pull request by [Miha-x64](https://github.com/Miha-x64) for drawing background if set on `PDFView` 154 | 155 | ## 1.3.0 (2016-07-13) 156 | * update PdfiumAndroid to 1.4.0 with support for rendering annotations 157 | * merge pull request by [usef](https://github.com/usef) for rendering annotations 158 | 159 | ## 1.2.0 (2016-07-11) 160 | * update PdfiumAndroid to 1.3.1 with support for bookmarks, Table Of Contents and documents with password: 161 | * added method `PDFView#getDocumentMeta()`, which returns document metadata 162 | * added method `PDFView#getTableOfContents()`, which returns whole tree of bookmarks in PDF document 163 | * added method `Configurator#password(String)` 164 | * added horizontal mode to **ScrollBar** - use `ScrollBar#setHorizontal(true)` or `app:sb_horizontal="true"` in XML 165 | * block interaction with `PDFView` when document is not loaded - prevent some exceptions 166 | * fix `PDFView` exceptions in layout preview (edit mode) 167 | 168 | ## 1.1.2 (2016-06-27) 169 | * update PdfiumAndroid to 1.1.0, which fixes displaying multiple `PDFView`s at the same time and few errors with loading PDF documents. 170 | 171 | ## 1.1.1 (2016-06-17) 172 | * fixes bug with strange behavior when indices passed to `.pages()` don't start with `0`. 173 | 174 | ## 1.1.0 (2016-06-16) 175 | * added method `pdfView.fromUri(Uri)` for opening files from content providers 176 | * updated PdfiumAndroid to 1.0.3, which should fix bug with exception 177 | * updated sample with demonstration of `fromUri()` method 178 | * some minor fixes 179 | 180 | ## 1.0.0 (2016-06-06) 181 | * Initial release 182 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | #### This is a fork of the [AndroidPdfViewer](https://github.com/barteksc/AndroidPdfViewer) 3 | switch back to the mainline repo when it gets migrated off JCenter 4 | 5 | 6 | # Android PdfViewer 7 | 8 | __AndroidPdfViewer 1.x is available on [AndroidPdfViewerV1](https://github.com/barteksc/AndroidPdfViewerV1) 9 | repo, where can be developed independently. Version 1.x uses different engine for drawing document on canvas, 10 | so if you don't like 2.x version, try 1.x.__ 11 | 12 | Library for displaying PDF documents on Android, with `animations`, `gestures`, `zoom` and `double tap` support. 13 | It is based on [PdfiumAndroid](https://github.com/barteksc/PdfiumAndroid) for decoding PDF files. Works on API 11 (Android 3.0) and higher. 14 | Licensed under Apache License 2.0. 15 | 16 | ## 3.2.0-beta.3 17 | * Change minimum SDK version to 19 18 | * Drop MIPS support 19 | * Update to Androidx 20 | * Switch pdfium-android to a [fork](https://github.com/mhiew/PdfiumAndroid) so we can disable jetifier 21 | 22 | ## 3.2.0-beta.2 23 | * Fix a potential NPE due to out of sync render thread management [Pull Request](https://github.com/barteksc/AndroidPdfViewer/pull/824) 24 | * Update the sample app configuration so that it can compile [Pull Request](https://github.com/mhiew/AndroidPdfViewer/pull/2) 25 | 26 | ## What's new in 3.2.0-beta.1? 27 | * Merge PR #714 with optimized page load 28 | * Merge PR #776 with fix for max & min zoom level 29 | * Merge PR #722 with fix for showing right position when view size changed 30 | * Merge PR #703 with fix for too many threads 31 | * Merge PR #702 with fix for memory leak 32 | * Merge PR #689 with possibility to disable long click 33 | * Merge PR #628 with fix for hiding scroll handle 34 | * Merge PR #627 with `fitEachPage` option 35 | * Merge PR #638 and #406 with fixed NPE 36 | * Merge PR #780 with README fix 37 | * Update compile SDK and support library to 28 38 | * Update Gradle and Gradle Plugin 39 | 40 | ## Changes in 3.0 API 41 | * Replaced `Contants.PRELOAD_COUNT` with `PRELOAD_OFFSET` 42 | * Removed `PDFView#fitToWidth()` (variant without arguments) 43 | * Removed `Configurator#invalidPageColor(int)` method as invalid pages are not rendered 44 | * Removed page size parameters from `OnRenderListener#onInitiallyRendered(int)` method, as document may have different page sizes 45 | * Removed `PDFView#setSwipeVertical()` method 46 | 47 | ## Installation 48 | 49 | Add to _build.gradle_: 50 | 51 | ```groovy 52 | allprojects { 53 | repositories { 54 | ... 55 | mavenCentral() 56 | ... 57 | } 58 | } 59 | ``` 60 | 61 | `implementation 'com.github.mhiew:android-pdf-viewer:3.2.0-beta.3'` 62 | 63 | ## ProGuard 64 | If you are using ProGuard, add following rule to proguard config file: 65 | 66 | ```proguard 67 | -keep class com.shockwave.** 68 | ``` 69 | 70 | ## Include PDFView in your layout 71 | 72 | ``` xml 73 | 77 | ``` 78 | 79 | ## Load a PDF file 80 | 81 | All available options with default values: 82 | ``` java 83 | pdfView.fromUri(Uri) 84 | or 85 | pdfView.fromFile(File) 86 | or 87 | pdfView.fromBytes(byte[]) 88 | or 89 | pdfView.fromStream(InputStream) // stream is written to bytearray - native code cannot use Java Streams 90 | or 91 | pdfView.fromSource(DocumentSource) 92 | or 93 | pdfView.fromAsset(String) 94 | .pages(0, 2, 1, 3, 3, 3) // all pages are displayed by default 95 | .enableSwipe(true) // allows to block changing pages using swipe 96 | .swipeHorizontal(false) 97 | .enableDoubletap(true) 98 | .defaultPage(0) 99 | // allows to draw something on the current page, usually visible in the middle of the screen 100 | .onDraw(onDrawListener) 101 | // allows to draw something on all pages, separately for every page. Called only for visible pages 102 | .onDrawAll(onDrawListener) 103 | .onLoad(onLoadCompleteListener) // called after document is loaded and starts to be rendered 104 | .onPageChange(onPageChangeListener) 105 | .onPageScroll(onPageScrollListener) 106 | .onError(onErrorListener) 107 | .onPageError(onPageErrorListener) 108 | .onRender(onRenderListener) // called after document is rendered for the first time 109 | // called on single tap, return true if handled, false to toggle scroll handle visibility 110 | .onTap(onTapListener) 111 | .onLongPress(onLongPressListener) 112 | .enableAnnotationRendering(false) // render annotations (such as comments, colors or forms) 113 | .password(null) 114 | .scrollHandle(null) 115 | .enableAntialiasing(true) // improve rendering a little bit on low-res screens 116 | // spacing between pages in dp. To define spacing color, set view background 117 | .spacing(0) 118 | .autoSpacing(false) // add dynamic spacing to fit each page on its own on the screen 119 | .linkHandler(DefaultLinkHandler) 120 | .pageFitPolicy(FitPolicy.WIDTH) // mode to fit pages in the view 121 | .fitEachPage(false) // fit each page to the view, else smaller pages are scaled relative to largest page. 122 | .pageSnap(false) // snap pages to screen boundaries 123 | .pageFling(false) // make a fling change only a single page like ViewPager 124 | .nightMode(false) // toggle night mode 125 | .load(); 126 | ``` 127 | 128 | * `pages` is optional, it allows you to filter and order the pages of the PDF as you need 129 | 130 | ## Scroll handle 131 | 132 | Scroll handle is replacement for **ScrollBar** from 1.x branch. 133 | 134 | From version 2.1.0 putting **PDFView** in **RelativeLayout** to use **ScrollHandle** is not required, you can use any layout. 135 | 136 | To use scroll handle just register it using method `Configurator#scrollHandle()`. 137 | This method accepts implementations of **ScrollHandle** interface. 138 | 139 | There is default implementation shipped with AndroidPdfViewer, and you can use it with 140 | `.scrollHandle(new DefaultScrollHandle(this))`. 141 | **DefaultScrollHandle** is placed on the right (when scrolling vertically) or on the bottom (when scrolling horizontally). 142 | By using constructor with second argument (`new DefaultScrollHandle(this, true)`), handle can be placed left or top. 143 | 144 | You can also create custom scroll handles, just implement **ScrollHandle** interface. 145 | All methods are documented as Javadoc comments on interface [source](https://github.com/barteksc/AndroidPdfViewer/tree/master/android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/scroll/ScrollHandle.java). 146 | 147 | ## Document sources 148 | Version 2.3.0 introduced _document sources_, which are just providers for PDF documents. 149 | Every provider implements **DocumentSource** interface. 150 | Predefined providers are available in **com.github.barteksc.pdfviewer.source** package and can be used as 151 | samples for creating custom ones. 152 | 153 | Predefined providers can be used with shorthand methods: 154 | ``` 155 | pdfView.fromUri(Uri) 156 | pdfView.fromFile(File) 157 | pdfView.fromBytes(byte[]) 158 | pdfView.fromStream(InputStream) 159 | pdfView.fromAsset(String) 160 | ``` 161 | Custom providers may be used with `pdfView.fromSource(DocumentSource)` method. 162 | 163 | ## Links 164 | Version 3.0.0 introduced support for links in PDF documents. By default, **DefaultLinkHandler** 165 | is used and clicking on link that references page in same document causes jump to destination page 166 | and clicking on link that targets some URI causes opening it in default application. 167 | 168 | You can also create custom link handlers, just implement **LinkHandler** interface and set it using 169 | `Configurator#linkHandler(LinkHandler)` method. Take a look at [DefaultLinkHandler](https://github.com/barteksc/AndroidPdfViewer/tree/master/android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/link/DefaultLinkHandler.java) 170 | source to implement custom behavior. 171 | 172 | ## Pages fit policy 173 | Since version 3.0.0, library supports fitting pages into the screen in 3 modes: 174 | * WIDTH - width of widest page is equal to screen width 175 | * HEIGHT - height of highest page is equal to screen height 176 | * BOTH - based on widest and highest pages, every page is scaled to be fully visible on screen 177 | 178 | Apart from selected policy, every page is scaled to have size relative to other pages. 179 | 180 | Fit policy can be set using `Configurator#pageFitPolicy(FitPolicy)`. Default policy is **WIDTH**. 181 | 182 | ## Additional options 183 | 184 | ### Bitmap quality 185 | By default, generated bitmaps are _compressed_ with `RGB_565` format to reduce memory consumption. 186 | Rendering with `ARGB_8888` can be forced by using `pdfView.useBestQuality(true)` method. 187 | 188 | ### Double tap zooming 189 | There are three zoom levels: min (default 1), mid (default 1.75) and max (default 3). On first double tap, 190 | view is zoomed to mid level, on second to max level, and on third returns to min level. 191 | If you are between mid and max levels, double tapping causes zooming to max and so on. 192 | 193 | Zoom levels can be changed using following methods: 194 | 195 | ``` java 196 | void setMinZoom(float zoom); 197 | void setMidZoom(float zoom); 198 | void setMaxZoom(float zoom); 199 | ``` 200 | 201 | ## Possible questions 202 | ### Why resulting apk is so big? 203 | Android PdfViewer depends on PdfiumAndroid, which is set of native libraries (almost 16 MB) for many architectures. 204 | Apk must contain all this libraries to run on every device available on market. 205 | Fortunately, Google Play allows us to upload multiple apks, e.g. one per every architecture. 206 | There is good article on automatically splitting your application into multiple apks, 207 | available [here](http://ph0b.com/android-studio-gradle-and-ndk-integration/). 208 | Most important section is _Improving multiple APKs creation and versionCode handling with APK Splits_, but whole article is worth reading. 209 | You only need to do this in your application, no need for forking PdfiumAndroid or so. 210 | 211 | ### Why I cannot open PDF from URL? 212 | Downloading files is long running process which must be aware of Activity lifecycle, must support some configuration, 213 | data cleanup and caching, so creating such module will probably end up as new library. 214 | 215 | ### How can I show last opened page after configuration change? 216 | You have to store current page number and then set it with `pdfView.defaultPage(page)`, refer to sample app 217 | 218 | ### How can I fit document to screen width (eg. on orientation change)? 219 | Use `FitPolicy.WIDTH` policy or add following snippet when you want to fit desired page in document with different page sizes: 220 | ``` java 221 | Configurator.onRender(new OnRenderListener() { 222 | @Override 223 | public void onInitiallyRendered(int pages, float pageWidth, float pageHeight) { 224 | pdfView.fitToWidth(pageIndex); 225 | } 226 | }); 227 | ``` 228 | 229 | ### How can I scroll through single pages like a ViewPager? 230 | You can use a combination of the following settings to get scroll and fling behaviour similar to a ViewPager: 231 | ``` java 232 | .swipeHorizontal(true) 233 | .pageSnap(true) 234 | .autoSpacing(true) 235 | .pageFling(true) 236 | ``` 237 | 238 | ## One more thing 239 | If you have any suggestions on making this lib better, write me, create issue or write some code and send pull request. 240 | 241 | ## License 242 | 243 | Created with the help of android-pdfview by [Joan Zapata](http://joanzapata.com/) 244 | ``` 245 | Copyright 2017 Bartosz Schiller 246 | 247 | Licensed under the Apache License, Version 2.0 (the "License"); 248 | you may not use this file except in compliance with the License. 249 | You may obtain a copy of the License at 250 | 251 | http://www.apache.org/licenses/LICENSE-2.0 252 | 253 | Unless required by applicable law or agreed to in writing, software 254 | distributed under the License is distributed on an "AS IS" BASIS, 255 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 256 | See the License for the specific language governing permissions and 257 | limitations under the License. 258 | ``` 259 | -------------------------------------------------------------------------------- /android-pdf-viewer/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | compileSdkVersion rootProject.tools.compileSdk 5 | 6 | defaultConfig { 7 | minSdkVersion rootProject.tools.minSdk 8 | targetSdkVersion rootProject.tools.targetSdk 9 | versionCode 1 10 | versionName "${rootProject.tools.versionName}" 11 | } 12 | 13 | } 14 | 15 | dependencies { 16 | implementation 'androidx.core:core:1.7.0' 17 | api 'com.github.mhiew:pdfium-android:1.9.2' 18 | } 19 | 20 | // Maven Publishing 21 | ext { 22 | PUBLISH_GROUP_ID = 'com.github.mhiew' 23 | PUBLISH_VERSION = "${rootProject.tools.versionName}" 24 | PUBLISH_ARTIFACT_ID = 'android-pdf-viewer' 25 | } 26 | 27 | apply from: "${rootProject.projectDir}/android-pdf-viewer/publish-mavencentral.gradle" -------------------------------------------------------------------------------- /android-pdf-viewer/publish-mavencentral.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'maven-publish' 2 | apply plugin: 'signing' 3 | 4 | def isAndroid = plugins.hasPlugin('com.android.library') 5 | 6 | task sourcesJar(type: Jar) { 7 | archiveClassifier.set('sources') 8 | if (isAndroid) { 9 | from android.sourceSets.main.java.srcDirs 10 | } else { 11 | from sourceSets.main.allSource 12 | } 13 | } 14 | 15 | task javadoc(type: Javadoc) { 16 | source = android.sourceSets.main.java.srcDirs 17 | options.addStringOption('Xdoclint:none', '-quiet') 18 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) 19 | } 20 | 21 | afterEvaluate { 22 | javadoc.classpath += files(android.libraryVariants.collect { variant -> 23 | variant.javaCompileProvider.get().classpath.files 24 | }) 25 | } 26 | 27 | task javadocJar(type: Jar, dependsOn: javadoc) { 28 | archiveClassifier.set('javadoc') 29 | from javadoc.destinationDir 30 | } 31 | 32 | artifacts { 33 | archives sourcesJar 34 | archives javadocJar 35 | } 36 | 37 | group = PUBLISH_GROUP_ID 38 | version = PUBLISH_VERSION 39 | 40 | ext["signing.keyId"] = '' 41 | ext["signing.password"] = '' 42 | ext["signing.secretKeyRingFile"] = '' 43 | ext["ossrhUsername"] = '' 44 | ext["ossrhPassword"] = '' 45 | ext["sonatypeStagingProfileId"] = '' 46 | 47 | File secretPropsFile = project.rootProject.file('local.properties') 48 | if (secretPropsFile.exists()) { 49 | Properties p = new Properties() 50 | p.load(new FileInputStream(secretPropsFile)) 51 | p.each { name, value -> 52 | ext[name] = value 53 | } 54 | } else { 55 | ext["signing.keyId"] = System.getenv('SIGNING_KEY_ID') 56 | ext["signing.password"] = System.getenv('SIGNING_PASSWORD') 57 | ext["signing.secretKeyRingFile"] = System.getenv('SIGNING_SECRET_KEY_RING_FILE') 58 | ext["ossrhUsername"] = System.getenv('OSSRH_USERNAME') 59 | ext["ossrhPassword"] = System.getenv('OSSRH_PASSWORD') 60 | ext["sonatypeStagingProfileId"] = System.getenv('SONATYPE_STAGING_PROFILE_ID') 61 | } 62 | 63 | afterEvaluate { 64 | publishing { 65 | publications { 66 | release(MavenPublication) { 67 | if (isAndroid) { 68 | from components.release 69 | } else { 70 | from components.java 71 | } 72 | artifact sourcesJar 73 | artifact javadocJar 74 | 75 | // Set within Library Gradle 76 | groupId PUBLISH_GROUP_ID 77 | artifactId PUBLISH_ARTIFACT_ID 78 | version PUBLISH_VERSION 79 | 80 | pom { 81 | name = PUBLISH_ARTIFACT_ID 82 | description = 'Fork of Barteksc AndroidPdfViewer - Android view for displaying PDFs rendered with PdfiumAndroid' 83 | url = 'https://github.com/mhiew/AndroidPdfViewer' 84 | licenses { 85 | license { 86 | name = 'The Apache License, Version 2.0' 87 | url = 'http://www.apache.org/licenses/LICENSE-2.0.txt' 88 | } 89 | } 90 | developers { 91 | developer { 92 | id = 'min' 93 | name = 'Min Hiew' 94 | } 95 | } 96 | scm { 97 | connection = 'scm:git:https://github.com/mhiew/AndroidPdfViewer' 98 | developerConnection = 'scm:git:ssh:github.com:mhiew/AndroidPdfViewer.git' 99 | url = 'https://github.com/mhiew/AndroidPdfViewer' 100 | } 101 | } 102 | } 103 | } 104 | // The repository to publish to, Sonatype/MavenCentral 105 | repositories { 106 | maven { 107 | // This is an arbitrary name, you may also use "mavencentral" or 108 | // any other name that's descriptive for you 109 | name = "sonatype" 110 | url = "https://oss.sonatype.org/service/local/staging/deploy/maven2/" 111 | credentials { 112 | username ossrhUsername 113 | password ossrhPassword 114 | } 115 | } 116 | } 117 | } 118 | } 119 | 120 | signing { 121 | sign publishing.publications 122 | } -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/AnimationManager.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2016 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer; 17 | 18 | import android.animation.Animator; 19 | import android.animation.Animator.AnimatorListener; 20 | import android.animation.AnimatorListenerAdapter; 21 | import android.animation.ValueAnimator; 22 | import android.animation.ValueAnimator.AnimatorUpdateListener; 23 | import android.graphics.PointF; 24 | import android.view.animation.DecelerateInterpolator; 25 | import android.widget.OverScroller; 26 | 27 | 28 | /** 29 | * This manager is used by the PDFView to launch animations. 30 | * It uses the ValueAnimator appeared in API 11 to start 31 | * an animation, and call moveTo() on the PDFView as a result 32 | * of each animation update. 33 | */ 34 | class AnimationManager { 35 | 36 | private PDFView pdfView; 37 | 38 | private ValueAnimator animation; 39 | 40 | private OverScroller scroller; 41 | 42 | private boolean flinging = false; 43 | 44 | private boolean pageFlinging = false; 45 | 46 | public AnimationManager(PDFView pdfView) { 47 | this.pdfView = pdfView; 48 | scroller = new OverScroller(pdfView.getContext()); 49 | } 50 | 51 | public void startXAnimation(float xFrom, float xTo) { 52 | stopAll(); 53 | animation = ValueAnimator.ofFloat(xFrom, xTo); 54 | XAnimation xAnimation = new XAnimation(); 55 | animation.setInterpolator(new DecelerateInterpolator()); 56 | animation.addUpdateListener(xAnimation); 57 | animation.addListener(xAnimation); 58 | animation.setDuration(400); 59 | animation.start(); 60 | } 61 | 62 | public void startYAnimation(float yFrom, float yTo) { 63 | stopAll(); 64 | animation = ValueAnimator.ofFloat(yFrom, yTo); 65 | YAnimation yAnimation = new YAnimation(); 66 | animation.setInterpolator(new DecelerateInterpolator()); 67 | animation.addUpdateListener(yAnimation); 68 | animation.addListener(yAnimation); 69 | animation.setDuration(400); 70 | animation.start(); 71 | } 72 | 73 | public void startZoomAnimation(float centerX, float centerY, float zoomFrom, float zoomTo) { 74 | stopAll(); 75 | animation = ValueAnimator.ofFloat(zoomFrom, zoomTo); 76 | animation.setInterpolator(new DecelerateInterpolator()); 77 | ZoomAnimation zoomAnim = new ZoomAnimation(centerX, centerY); 78 | animation.addUpdateListener(zoomAnim); 79 | animation.addListener(zoomAnim); 80 | animation.setDuration(400); 81 | animation.start(); 82 | } 83 | 84 | public void startFlingAnimation(int startX, int startY, int velocityX, int velocityY, int minX, int maxX, int minY, int maxY) { 85 | stopAll(); 86 | flinging = true; 87 | scroller.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY); 88 | } 89 | 90 | public void startPageFlingAnimation(float targetOffset) { 91 | if (pdfView.isSwipeVertical()) { 92 | startYAnimation(pdfView.getCurrentYOffset(), targetOffset); 93 | } else { 94 | startXAnimation(pdfView.getCurrentXOffset(), targetOffset); 95 | } 96 | pageFlinging = true; 97 | } 98 | 99 | void computeFling() { 100 | if (scroller.computeScrollOffset()) { 101 | pdfView.moveTo(scroller.getCurrX(), scroller.getCurrY()); 102 | pdfView.loadPageByOffset(); 103 | } else if (flinging) { // fling finished 104 | flinging = false; 105 | pdfView.loadPages(); 106 | hideHandle(); 107 | pdfView.performPageSnap(); 108 | } 109 | } 110 | 111 | public void stopAll() { 112 | if (animation != null) { 113 | animation.cancel(); 114 | animation = null; 115 | } 116 | stopFling(); 117 | } 118 | 119 | public void stopFling() { 120 | flinging = false; 121 | scroller.forceFinished(true); 122 | } 123 | 124 | public boolean isFlinging() { 125 | return flinging || pageFlinging; 126 | } 127 | 128 | class XAnimation extends AnimatorListenerAdapter implements AnimatorUpdateListener { 129 | 130 | @Override 131 | public void onAnimationUpdate(ValueAnimator animation) { 132 | float offset = (Float) animation.getAnimatedValue(); 133 | pdfView.moveTo(offset, pdfView.getCurrentYOffset()); 134 | pdfView.loadPageByOffset(); 135 | } 136 | 137 | @Override 138 | public void onAnimationCancel(Animator animation) { 139 | pdfView.loadPages(); 140 | pageFlinging = false; 141 | hideHandle(); 142 | } 143 | 144 | @Override 145 | public void onAnimationEnd(Animator animation) { 146 | pdfView.loadPages(); 147 | pageFlinging = false; 148 | hideHandle(); 149 | } 150 | } 151 | 152 | class YAnimation extends AnimatorListenerAdapter implements AnimatorUpdateListener { 153 | 154 | @Override 155 | public void onAnimationUpdate(ValueAnimator animation) { 156 | float offset = (Float) animation.getAnimatedValue(); 157 | pdfView.moveTo(pdfView.getCurrentXOffset(), offset); 158 | pdfView.loadPageByOffset(); 159 | } 160 | 161 | @Override 162 | public void onAnimationCancel(Animator animation) { 163 | pdfView.loadPages(); 164 | pageFlinging = false; 165 | hideHandle(); 166 | } 167 | 168 | @Override 169 | public void onAnimationEnd(Animator animation) { 170 | pdfView.loadPages(); 171 | pageFlinging = false; 172 | hideHandle(); 173 | } 174 | } 175 | 176 | class ZoomAnimation implements AnimatorUpdateListener, AnimatorListener { 177 | 178 | private final float centerX; 179 | private final float centerY; 180 | 181 | public ZoomAnimation(float centerX, float centerY) { 182 | this.centerX = centerX; 183 | this.centerY = centerY; 184 | } 185 | 186 | @Override 187 | public void onAnimationUpdate(ValueAnimator animation) { 188 | float zoom = (Float) animation.getAnimatedValue(); 189 | pdfView.zoomCenteredTo(zoom, new PointF(centerX, centerY)); 190 | } 191 | 192 | @Override 193 | public void onAnimationCancel(Animator animation) { 194 | pdfView.loadPages(); 195 | hideHandle(); 196 | } 197 | 198 | @Override 199 | public void onAnimationEnd(Animator animation) { 200 | pdfView.loadPages(); 201 | pdfView.performPageSnap(); 202 | hideHandle(); 203 | } 204 | 205 | @Override 206 | public void onAnimationRepeat(Animator animation) { 207 | } 208 | 209 | @Override 210 | public void onAnimationStart(Animator animation) { 211 | } 212 | 213 | } 214 | 215 | private void hideHandle() { 216 | if (pdfView.getScrollHandle() != null) { 217 | pdfView.getScrollHandle().hideDelayed(); 218 | } 219 | } 220 | 221 | } 222 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/CacheManager.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2016 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer; 17 | 18 | import android.graphics.RectF; 19 | import androidx.annotation.Nullable; 20 | 21 | import com.github.barteksc.pdfviewer.model.PagePart; 22 | 23 | import java.util.ArrayList; 24 | import java.util.Collection; 25 | import java.util.Comparator; 26 | import java.util.List; 27 | import java.util.PriorityQueue; 28 | 29 | import static com.github.barteksc.pdfviewer.util.Constants.Cache.CACHE_SIZE; 30 | import static com.github.barteksc.pdfviewer.util.Constants.Cache.THUMBNAILS_CACHE_SIZE; 31 | 32 | class CacheManager { 33 | 34 | private final PriorityQueue passiveCache; 35 | 36 | private final PriorityQueue activeCache; 37 | 38 | private final List thumbnails; 39 | 40 | private final Object passiveActiveLock = new Object(); 41 | 42 | private final PagePartComparator orderComparator = new PagePartComparator(); 43 | 44 | public CacheManager() { 45 | activeCache = new PriorityQueue<>(CACHE_SIZE, orderComparator); 46 | passiveCache = new PriorityQueue<>(CACHE_SIZE, orderComparator); 47 | thumbnails = new ArrayList<>(); 48 | } 49 | 50 | public void cachePart(PagePart part) { 51 | synchronized (passiveActiveLock) { 52 | // If cache too big, remove and recycle 53 | makeAFreeSpace(); 54 | 55 | // Then add part 56 | activeCache.offer(part); 57 | } 58 | } 59 | 60 | public void makeANewSet() { 61 | synchronized (passiveActiveLock) { 62 | passiveCache.addAll(activeCache); 63 | activeCache.clear(); 64 | } 65 | } 66 | 67 | private void makeAFreeSpace() { 68 | synchronized (passiveActiveLock) { 69 | while ((activeCache.size() + passiveCache.size()) >= CACHE_SIZE && 70 | !passiveCache.isEmpty()) { 71 | PagePart part = passiveCache.poll(); 72 | part.getRenderedBitmap().recycle(); 73 | } 74 | 75 | while ((activeCache.size() + passiveCache.size()) >= CACHE_SIZE && 76 | !activeCache.isEmpty()) { 77 | activeCache.poll().getRenderedBitmap().recycle(); 78 | } 79 | } 80 | } 81 | 82 | public void cacheThumbnail(PagePart part) { 83 | synchronized (thumbnails) { 84 | // If cache too big, remove and recycle 85 | while (thumbnails.size() >= THUMBNAILS_CACHE_SIZE) { 86 | thumbnails.remove(0).getRenderedBitmap().recycle(); 87 | } 88 | 89 | // Then add thumbnail 90 | addWithoutDuplicates(thumbnails, part); 91 | } 92 | 93 | } 94 | 95 | public boolean upPartIfContained(int page, RectF pageRelativeBounds, int toOrder) { 96 | PagePart fakePart = new PagePart(page, null, pageRelativeBounds, false, 0); 97 | 98 | PagePart found; 99 | synchronized (passiveActiveLock) { 100 | if ((found = find(passiveCache, fakePart)) != null) { 101 | passiveCache.remove(found); 102 | found.setCacheOrder(toOrder); 103 | activeCache.offer(found); 104 | return true; 105 | } 106 | 107 | return find(activeCache, fakePart) != null; 108 | } 109 | } 110 | 111 | /** 112 | * Return true if already contains the described PagePart 113 | */ 114 | public boolean containsThumbnail(int page, RectF pageRelativeBounds) { 115 | PagePart fakePart = new PagePart(page, null, pageRelativeBounds, true, 0); 116 | synchronized (thumbnails) { 117 | for (PagePart part : thumbnails) { 118 | if (part.equals(fakePart)) { 119 | return true; 120 | } 121 | } 122 | return false; 123 | } 124 | } 125 | 126 | /** 127 | * Add part if it doesn't exist, recycle bitmap otherwise 128 | */ 129 | private void addWithoutDuplicates(Collection collection, PagePart newPart) { 130 | for (PagePart part : collection) { 131 | if (part.equals(newPart)) { 132 | newPart.getRenderedBitmap().recycle(); 133 | return; 134 | } 135 | } 136 | collection.add(newPart); 137 | } 138 | 139 | @Nullable 140 | private static PagePart find(PriorityQueue vector, PagePart fakePart) { 141 | for (PagePart part : vector) { 142 | if (part.equals(fakePart)) { 143 | return part; 144 | } 145 | } 146 | return null; 147 | } 148 | 149 | public List getPageParts() { 150 | synchronized (passiveActiveLock) { 151 | List parts = new ArrayList<>(passiveCache); 152 | parts.addAll(activeCache); 153 | return parts; 154 | } 155 | } 156 | 157 | public List getThumbnails() { 158 | synchronized (thumbnails) { 159 | return thumbnails; 160 | } 161 | } 162 | 163 | public void recycle() { 164 | synchronized (passiveActiveLock) { 165 | for (PagePart part : passiveCache) { 166 | part.getRenderedBitmap().recycle(); 167 | } 168 | passiveCache.clear(); 169 | for (PagePart part : activeCache) { 170 | part.getRenderedBitmap().recycle(); 171 | } 172 | activeCache.clear(); 173 | } 174 | synchronized (thumbnails) { 175 | for (PagePart part : thumbnails) { 176 | part.getRenderedBitmap().recycle(); 177 | } 178 | thumbnails.clear(); 179 | } 180 | } 181 | 182 | class PagePartComparator implements Comparator { 183 | @Override 184 | public int compare(PagePart part1, PagePart part2) { 185 | if (part1.getCacheOrder() == part2.getCacheOrder()) { 186 | return 0; 187 | } 188 | return part1.getCacheOrder() > part2.getCacheOrder() ? 1 : -1; 189 | } 190 | } 191 | 192 | } 193 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/DecodingAsyncTask.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2016 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer; 17 | 18 | import android.os.AsyncTask; 19 | 20 | import com.github.barteksc.pdfviewer.source.DocumentSource; 21 | import com.shockwave.pdfium.PdfDocument; 22 | import com.shockwave.pdfium.PdfiumCore; 23 | import com.shockwave.pdfium.util.Size; 24 | 25 | import java.lang.ref.WeakReference; 26 | 27 | class DecodingAsyncTask extends AsyncTask { 28 | 29 | private boolean cancelled; 30 | 31 | private WeakReference pdfViewReference; 32 | 33 | private PdfiumCore pdfiumCore; 34 | private String password; 35 | private DocumentSource docSource; 36 | private int[] userPages; 37 | private PdfFile pdfFile; 38 | 39 | DecodingAsyncTask(DocumentSource docSource, String password, int[] userPages, PDFView pdfView, PdfiumCore pdfiumCore) { 40 | this.docSource = docSource; 41 | this.userPages = userPages; 42 | this.cancelled = false; 43 | this.pdfViewReference = new WeakReference<>(pdfView); 44 | this.password = password; 45 | this.pdfiumCore = pdfiumCore; 46 | } 47 | 48 | @Override 49 | protected Throwable doInBackground(Void... params) { 50 | try { 51 | PDFView pdfView = pdfViewReference.get(); 52 | if (pdfView != null) { 53 | PdfDocument pdfDocument = docSource.createDocument(pdfView.getContext(), pdfiumCore, password); 54 | pdfFile = new PdfFile(pdfiumCore, pdfDocument, pdfView.getPageFitPolicy(), getViewSize(pdfView), 55 | userPages, pdfView.isSwipeVertical(), pdfView.getSpacingPx(), pdfView.isAutoSpacingEnabled(), 56 | pdfView.isFitEachPage()); 57 | return null; 58 | } else { 59 | return new NullPointerException("pdfView == null"); 60 | } 61 | 62 | } catch (Throwable t) { 63 | return t; 64 | } 65 | } 66 | 67 | private Size getViewSize(PDFView pdfView) { 68 | return new Size(pdfView.getWidth(), pdfView.getHeight()); 69 | } 70 | 71 | @Override 72 | protected void onPostExecute(Throwable t) { 73 | PDFView pdfView = pdfViewReference.get(); 74 | if (pdfView != null) { 75 | if (t != null) { 76 | pdfView.loadError(t); 77 | return; 78 | } 79 | if (!cancelled) { 80 | pdfView.loadComplete(pdfFile); 81 | } 82 | } 83 | } 84 | 85 | @Override 86 | protected void onCancelled() { 87 | cancelled = true; 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/DragPinchManager.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2016 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer; 17 | 18 | import android.graphics.PointF; 19 | import android.graphics.RectF; 20 | import android.view.GestureDetector; 21 | import android.view.MotionEvent; 22 | import android.view.ScaleGestureDetector; 23 | import android.view.View; 24 | 25 | import com.github.barteksc.pdfviewer.model.LinkTapEvent; 26 | import com.github.barteksc.pdfviewer.scroll.ScrollHandle; 27 | import com.github.barteksc.pdfviewer.util.SnapEdge; 28 | import com.shockwave.pdfium.PdfDocument; 29 | import com.shockwave.pdfium.util.SizeF; 30 | 31 | import static com.github.barteksc.pdfviewer.util.Constants.Pinch.MAXIMUM_ZOOM; 32 | import static com.github.barteksc.pdfviewer.util.Constants.Pinch.MINIMUM_ZOOM; 33 | 34 | /** 35 | * This Manager takes care of moving the PDFView, 36 | * set its zoom track user actions. 37 | */ 38 | class DragPinchManager implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener, ScaleGestureDetector.OnScaleGestureListener, View.OnTouchListener { 39 | 40 | private PDFView pdfView; 41 | private AnimationManager animationManager; 42 | 43 | private GestureDetector gestureDetector; 44 | private ScaleGestureDetector scaleGestureDetector; 45 | 46 | private boolean scrolling = false; 47 | private boolean scaling = false; 48 | private boolean enabled = false; 49 | 50 | DragPinchManager(PDFView pdfView, AnimationManager animationManager) { 51 | this.pdfView = pdfView; 52 | this.animationManager = animationManager; 53 | gestureDetector = new GestureDetector(pdfView.getContext(), this); 54 | scaleGestureDetector = new ScaleGestureDetector(pdfView.getContext(), this); 55 | pdfView.setOnTouchListener(this); 56 | } 57 | 58 | void enable() { 59 | enabled = true; 60 | } 61 | 62 | void disable() { 63 | enabled = false; 64 | } 65 | 66 | void disableLongpress(){ 67 | gestureDetector.setIsLongpressEnabled(false); 68 | } 69 | 70 | @Override 71 | public boolean onSingleTapConfirmed(MotionEvent e) { 72 | boolean onTapHandled = pdfView.callbacks.callOnTap(e); 73 | boolean linkTapped = checkLinkTapped(e.getX(), e.getY()); 74 | if (!onTapHandled && !linkTapped) { 75 | ScrollHandle ps = pdfView.getScrollHandle(); 76 | if (ps != null && !pdfView.documentFitsView()) { 77 | if (!ps.shown()) { 78 | ps.show(); 79 | } else { 80 | ps.hide(); 81 | } 82 | } 83 | } 84 | pdfView.performClick(); 85 | return true; 86 | } 87 | 88 | private boolean checkLinkTapped(float x, float y) { 89 | PdfFile pdfFile = pdfView.pdfFile; 90 | if (pdfFile == null) { 91 | return false; 92 | } 93 | float mappedX = -pdfView.getCurrentXOffset() + x; 94 | float mappedY = -pdfView.getCurrentYOffset() + y; 95 | int page = pdfFile.getPageAtOffset(pdfView.isSwipeVertical() ? mappedY : mappedX, pdfView.getZoom()); 96 | SizeF pageSize = pdfFile.getScaledPageSize(page, pdfView.getZoom()); 97 | int pageX, pageY; 98 | if (pdfView.isSwipeVertical()) { 99 | pageX = (int) pdfFile.getSecondaryPageOffset(page, pdfView.getZoom()); 100 | pageY = (int) pdfFile.getPageOffset(page, pdfView.getZoom()); 101 | } else { 102 | pageY = (int) pdfFile.getSecondaryPageOffset(page, pdfView.getZoom()); 103 | pageX = (int) pdfFile.getPageOffset(page, pdfView.getZoom()); 104 | } 105 | for (PdfDocument.Link link : pdfFile.getPageLinks(page)) { 106 | RectF mapped = pdfFile.mapRectToDevice(page, pageX, pageY, (int) pageSize.getWidth(), 107 | (int) pageSize.getHeight(), link.getBounds()); 108 | mapped.sort(); 109 | if (mapped.contains(mappedX, mappedY)) { 110 | pdfView.callbacks.callLinkHandler(new LinkTapEvent(x, y, mappedX, mappedY, mapped, link)); 111 | return true; 112 | } 113 | } 114 | return false; 115 | } 116 | 117 | private void startPageFling(MotionEvent downEvent, MotionEvent ev, float velocityX, float velocityY) { 118 | if (!checkDoPageFling(velocityX, velocityY)) { 119 | return; 120 | } 121 | 122 | int direction; 123 | if (pdfView.isSwipeVertical()) { 124 | direction = velocityY > 0 ? -1 : 1; 125 | } else { 126 | direction = velocityX > 0 ? -1 : 1; 127 | } 128 | // get the focused page during the down event to ensure only a single page is changed 129 | float delta = pdfView.isSwipeVertical() ? ev.getY() - downEvent.getY() : ev.getX() - downEvent.getX(); 130 | float offsetX = pdfView.getCurrentXOffset() - delta * pdfView.getZoom(); 131 | float offsetY = pdfView.getCurrentYOffset() - delta * pdfView.getZoom(); 132 | int startingPage = pdfView.findFocusPage(offsetX, offsetY); 133 | int targetPage = Math.max(0, Math.min(pdfView.getPageCount() - 1, startingPage + direction)); 134 | 135 | SnapEdge edge = pdfView.findSnapEdge(targetPage); 136 | float offset = pdfView.snapOffsetForPage(targetPage, edge); 137 | animationManager.startPageFlingAnimation(-offset); 138 | } 139 | 140 | @Override 141 | public boolean onDoubleTap(MotionEvent e) { 142 | if (!pdfView.isDoubletapEnabled()) { 143 | return false; 144 | } 145 | 146 | if (pdfView.getZoom() < pdfView.getMidZoom()) { 147 | pdfView.zoomWithAnimation(e.getX(), e.getY(), pdfView.getMidZoom()); 148 | } else if (pdfView.getZoom() < pdfView.getMaxZoom()) { 149 | pdfView.zoomWithAnimation(e.getX(), e.getY(), pdfView.getMaxZoom()); 150 | } else { 151 | pdfView.resetZoomWithAnimation(); 152 | } 153 | return true; 154 | } 155 | 156 | @Override 157 | public boolean onDoubleTapEvent(MotionEvent e) { 158 | return false; 159 | } 160 | 161 | @Override 162 | public boolean onDown(MotionEvent e) { 163 | animationManager.stopFling(); 164 | return true; 165 | } 166 | 167 | @Override 168 | public void onShowPress(MotionEvent e) { 169 | 170 | } 171 | 172 | @Override 173 | public boolean onSingleTapUp(MotionEvent e) { 174 | return false; 175 | } 176 | 177 | @Override 178 | public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { 179 | scrolling = true; 180 | if (pdfView.isZooming() || pdfView.isSwipeEnabled()) { 181 | pdfView.moveRelativeTo(-distanceX, -distanceY); 182 | } 183 | if (!scaling || pdfView.doRenderDuringScale()) { 184 | pdfView.loadPageByOffset(); 185 | } 186 | return true; 187 | } 188 | 189 | private void onScrollEnd(MotionEvent event) { 190 | pdfView.loadPages(); 191 | hideHandle(); 192 | if (!animationManager.isFlinging()) { 193 | pdfView.performPageSnap(); 194 | } 195 | } 196 | 197 | @Override 198 | public void onLongPress(MotionEvent e) { 199 | pdfView.callbacks.callOnLongPress(e); 200 | } 201 | 202 | @Override 203 | public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { 204 | if (!pdfView.isSwipeEnabled()) { 205 | return false; 206 | } 207 | if (pdfView.isPageFlingEnabled()) { 208 | if (pdfView.pageFillsScreen()) { 209 | onBoundedFling(velocityX, velocityY); 210 | } else { 211 | startPageFling(e1, e2, velocityX, velocityY); 212 | } 213 | return true; 214 | } 215 | 216 | int xOffset = (int) pdfView.getCurrentXOffset(); 217 | int yOffset = (int) pdfView.getCurrentYOffset(); 218 | 219 | float minX, minY; 220 | PdfFile pdfFile = pdfView.pdfFile; 221 | if (pdfView.isSwipeVertical()) { 222 | minX = -(pdfView.toCurrentScale(pdfFile.getMaxPageWidth()) - pdfView.getWidth()); 223 | minY = -(pdfFile.getDocLen(pdfView.getZoom()) - pdfView.getHeight()); 224 | } else { 225 | minX = -(pdfFile.getDocLen(pdfView.getZoom()) - pdfView.getWidth()); 226 | minY = -(pdfView.toCurrentScale(pdfFile.getMaxPageHeight()) - pdfView.getHeight()); 227 | } 228 | 229 | animationManager.startFlingAnimation(xOffset, yOffset, (int) (velocityX), (int) (velocityY), 230 | (int) minX, 0, (int) minY, 0); 231 | return true; 232 | } 233 | 234 | private void onBoundedFling(float velocityX, float velocityY) { 235 | int xOffset = (int) pdfView.getCurrentXOffset(); 236 | int yOffset = (int) pdfView.getCurrentYOffset(); 237 | 238 | PdfFile pdfFile = pdfView.pdfFile; 239 | 240 | float pageStart = -pdfFile.getPageOffset(pdfView.getCurrentPage(), pdfView.getZoom()); 241 | float pageEnd = pageStart - pdfFile.getPageLength(pdfView.getCurrentPage(), pdfView.getZoom()); 242 | float minX, minY, maxX, maxY; 243 | if (pdfView.isSwipeVertical()) { 244 | minX = -(pdfView.toCurrentScale(pdfFile.getMaxPageWidth()) - pdfView.getWidth()); 245 | minY = pageEnd + pdfView.getHeight(); 246 | maxX = 0; 247 | maxY = pageStart; 248 | } else { 249 | minX = pageEnd + pdfView.getWidth(); 250 | minY = -(pdfView.toCurrentScale(pdfFile.getMaxPageHeight()) - pdfView.getHeight()); 251 | maxX = pageStart; 252 | maxY = 0; 253 | } 254 | 255 | animationManager.startFlingAnimation(xOffset, yOffset, (int) (velocityX), (int) (velocityY), 256 | (int) minX, (int) maxX, (int) minY, (int) maxY); 257 | } 258 | 259 | @Override 260 | public boolean onScale(ScaleGestureDetector detector) { 261 | float dr = detector.getScaleFactor(); 262 | float wantedZoom = pdfView.getZoom() * dr; 263 | float minZoom = Math.min(MINIMUM_ZOOM, pdfView.getMinZoom()); 264 | float maxZoom = Math.min(MAXIMUM_ZOOM, pdfView.getMaxZoom()); 265 | if (wantedZoom < minZoom) { 266 | dr = minZoom / pdfView.getZoom(); 267 | } else if (wantedZoom > maxZoom) { 268 | dr = maxZoom / pdfView.getZoom(); 269 | } 270 | pdfView.zoomCenteredRelativeTo(dr, new PointF(detector.getFocusX(), detector.getFocusY())); 271 | return true; 272 | } 273 | 274 | @Override 275 | public boolean onScaleBegin(ScaleGestureDetector detector) { 276 | scaling = true; 277 | return true; 278 | } 279 | 280 | @Override 281 | public void onScaleEnd(ScaleGestureDetector detector) { 282 | pdfView.loadPages(); 283 | hideHandle(); 284 | scaling = false; 285 | } 286 | 287 | @Override 288 | public boolean onTouch(View v, MotionEvent event) { 289 | if (!enabled) { 290 | return false; 291 | } 292 | 293 | boolean retVal = scaleGestureDetector.onTouchEvent(event); 294 | retVal = gestureDetector.onTouchEvent(event) || retVal; 295 | 296 | if (event.getAction() == MotionEvent.ACTION_UP) { 297 | if (scrolling) { 298 | scrolling = false; 299 | onScrollEnd(event); 300 | } 301 | } 302 | return retVal; 303 | } 304 | 305 | private void hideHandle() { 306 | ScrollHandle scrollHandle = pdfView.getScrollHandle(); 307 | if (scrollHandle != null && scrollHandle.shown()) { 308 | scrollHandle.hideDelayed(); 309 | } 310 | } 311 | 312 | private boolean checkDoPageFling(float velocityX, float velocityY) { 313 | float absX = Math.abs(velocityX); 314 | float absY = Math.abs(velocityY); 315 | return pdfView.isSwipeVertical() ? absY > absX : absX > absY; 316 | } 317 | } 318 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/PagesLoader.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer; 17 | 18 | import android.graphics.RectF; 19 | 20 | import com.github.barteksc.pdfviewer.util.Constants; 21 | import com.github.barteksc.pdfviewer.util.MathUtils; 22 | import com.github.barteksc.pdfviewer.util.Util; 23 | import com.shockwave.pdfium.util.SizeF; 24 | 25 | import java.util.LinkedList; 26 | import java.util.List; 27 | 28 | import static com.github.barteksc.pdfviewer.util.Constants.Cache.CACHE_SIZE; 29 | import static com.github.barteksc.pdfviewer.util.Constants.PRELOAD_OFFSET; 30 | 31 | class PagesLoader { 32 | 33 | private PDFView pdfView; 34 | private int cacheOrder; 35 | private float xOffset; 36 | private float yOffset; 37 | private float pageRelativePartWidth; 38 | private float pageRelativePartHeight; 39 | private float partRenderWidth; 40 | private float partRenderHeight; 41 | private final RectF thumbnailRect = new RectF(0, 0, 1, 1); 42 | private final int preloadOffset; 43 | 44 | private class Holder { 45 | int row; 46 | int col; 47 | 48 | @Override 49 | public String toString() { 50 | return "Holder{" + 51 | "row=" + row + 52 | ", col=" + col + 53 | '}'; 54 | } 55 | } 56 | 57 | private class RenderRange { 58 | int page; 59 | GridSize gridSize; 60 | Holder leftTop; 61 | Holder rightBottom; 62 | 63 | RenderRange() { 64 | this.page = 0; 65 | this.gridSize = new GridSize(); 66 | this.leftTop = new Holder(); 67 | this.rightBottom = new Holder(); 68 | } 69 | 70 | @Override 71 | public String toString() { 72 | return "RenderRange{" + 73 | "page=" + page + 74 | ", gridSize=" + gridSize + 75 | ", leftTop=" + leftTop + 76 | ", rightBottom=" + rightBottom + 77 | '}'; 78 | } 79 | } 80 | 81 | private class GridSize { 82 | int rows; 83 | int cols; 84 | 85 | @Override 86 | public String toString() { 87 | return "GridSize{" + 88 | "rows=" + rows + 89 | ", cols=" + cols + 90 | '}'; 91 | } 92 | } 93 | 94 | PagesLoader(PDFView pdfView) { 95 | this.pdfView = pdfView; 96 | this.preloadOffset = Util.getDP(pdfView.getContext(), PRELOAD_OFFSET); 97 | } 98 | 99 | private void getPageColsRows(GridSize grid, int pageIndex) { 100 | SizeF size = pdfView.pdfFile.getPageSize(pageIndex); 101 | float ratioX = 1f / size.getWidth(); 102 | float ratioY = 1f / size.getHeight(); 103 | final float partHeight = (Constants.PART_SIZE * ratioY) / pdfView.getZoom(); 104 | final float partWidth = (Constants.PART_SIZE * ratioX) / pdfView.getZoom(); 105 | grid.rows = MathUtils.ceil(1f / partHeight); 106 | grid.cols = MathUtils.ceil(1f / partWidth); 107 | } 108 | 109 | private void calculatePartSize(GridSize grid) { 110 | pageRelativePartWidth = 1f / (float) grid.cols; 111 | pageRelativePartHeight = 1f / (float) grid.rows; 112 | partRenderWidth = Constants.PART_SIZE / pageRelativePartWidth; 113 | partRenderHeight = Constants.PART_SIZE / pageRelativePartHeight; 114 | } 115 | 116 | 117 | /** 118 | * calculate the render range of each page 119 | */ 120 | private List getRenderRangeList(float firstXOffset, float firstYOffset, float lastXOffset, float lastYOffset) { 121 | 122 | float fixedFirstXOffset = -MathUtils.max(firstXOffset, 0); 123 | float fixedFirstYOffset = -MathUtils.max(firstYOffset, 0); 124 | 125 | float fixedLastXOffset = -MathUtils.max(lastXOffset, 0); 126 | float fixedLastYOffset = -MathUtils.max(lastYOffset, 0); 127 | 128 | float offsetFirst = pdfView.isSwipeVertical() ? fixedFirstYOffset : fixedFirstXOffset; 129 | float offsetLast = pdfView.isSwipeVertical() ? fixedLastYOffset : fixedLastXOffset; 130 | 131 | int firstPage = pdfView.pdfFile.getPageAtOffset(offsetFirst, pdfView.getZoom()); 132 | int lastPage = pdfView.pdfFile.getPageAtOffset(offsetLast, pdfView.getZoom()); 133 | int pageCount = lastPage - firstPage + 1; 134 | 135 | List renderRanges = new LinkedList<>(); 136 | 137 | for (int page = firstPage; page <= lastPage; page++) { 138 | RenderRange range = new RenderRange(); 139 | range.page = page; 140 | 141 | float pageFirstXOffset, pageFirstYOffset, pageLastXOffset, pageLastYOffset; 142 | if (page == firstPage) { 143 | pageFirstXOffset = fixedFirstXOffset; 144 | pageFirstYOffset = fixedFirstYOffset; 145 | if (pageCount == 1) { 146 | pageLastXOffset = fixedLastXOffset; 147 | pageLastYOffset = fixedLastYOffset; 148 | } else { 149 | float pageOffset = pdfView.pdfFile.getPageOffset(page, pdfView.getZoom()); 150 | SizeF pageSize = pdfView.pdfFile.getScaledPageSize(page, pdfView.getZoom()); 151 | if (pdfView.isSwipeVertical()) { 152 | pageLastXOffset = fixedLastXOffset; 153 | pageLastYOffset = pageOffset + pageSize.getHeight(); 154 | } else { 155 | pageLastYOffset = fixedLastYOffset; 156 | pageLastXOffset = pageOffset + pageSize.getWidth(); 157 | } 158 | } 159 | } else if (page == lastPage) { 160 | float pageOffset = pdfView.pdfFile.getPageOffset(page, pdfView.getZoom()); 161 | 162 | if (pdfView.isSwipeVertical()) { 163 | pageFirstXOffset = fixedFirstXOffset; 164 | pageFirstYOffset = pageOffset; 165 | } else { 166 | pageFirstYOffset = fixedFirstYOffset; 167 | pageFirstXOffset = pageOffset; 168 | } 169 | 170 | pageLastXOffset = fixedLastXOffset; 171 | pageLastYOffset = fixedLastYOffset; 172 | 173 | } else { 174 | float pageOffset = pdfView.pdfFile.getPageOffset(page, pdfView.getZoom()); 175 | SizeF pageSize = pdfView.pdfFile.getScaledPageSize(page, pdfView.getZoom()); 176 | if (pdfView.isSwipeVertical()) { 177 | pageFirstXOffset = fixedFirstXOffset; 178 | pageFirstYOffset = pageOffset; 179 | 180 | pageLastXOffset = fixedLastXOffset; 181 | pageLastYOffset = pageOffset + pageSize.getHeight(); 182 | } else { 183 | pageFirstXOffset = pageOffset; 184 | pageFirstYOffset = fixedFirstYOffset; 185 | 186 | pageLastXOffset = pageOffset + pageSize.getWidth(); 187 | pageLastYOffset = fixedLastYOffset; 188 | } 189 | } 190 | 191 | getPageColsRows(range.gridSize, range.page); // get the page's grid size that rows and cols 192 | SizeF scaledPageSize = pdfView.pdfFile.getScaledPageSize(range.page, pdfView.getZoom()); 193 | float rowHeight = scaledPageSize.getHeight() / range.gridSize.rows; 194 | float colWidth = scaledPageSize.getWidth() / range.gridSize.cols; 195 | 196 | 197 | // get the page offset int the whole file 198 | // --------------------------------------- 199 | // | | | | 200 | // |<--offset-->| (page) |<--offset-->| 201 | // | | | | 202 | // | | | | 203 | // --------------------------------------- 204 | float secondaryOffset = pdfView.pdfFile.getSecondaryPageOffset(page, pdfView.getZoom()); 205 | 206 | // calculate the row,col of the point in the leftTop and rightBottom 207 | if (pdfView.isSwipeVertical()) { 208 | range.leftTop.row = MathUtils.floor(Math.abs(pageFirstYOffset - pdfView.pdfFile.getPageOffset(range.page, pdfView.getZoom())) / rowHeight); 209 | range.leftTop.col = MathUtils.floor(MathUtils.min(pageFirstXOffset - secondaryOffset, 0) / colWidth); 210 | 211 | range.rightBottom.row = MathUtils.ceil(Math.abs(pageLastYOffset - pdfView.pdfFile.getPageOffset(range.page, pdfView.getZoom())) / rowHeight); 212 | range.rightBottom.col = MathUtils.floor(MathUtils.min(pageLastXOffset - secondaryOffset, 0) / colWidth); 213 | } else { 214 | range.leftTop.col = MathUtils.floor(Math.abs(pageFirstXOffset - pdfView.pdfFile.getPageOffset(range.page, pdfView.getZoom())) / colWidth); 215 | range.leftTop.row = MathUtils.floor(MathUtils.min(pageFirstYOffset - secondaryOffset, 0) / rowHeight); 216 | 217 | range.rightBottom.col = MathUtils.floor(Math.abs(pageLastXOffset - pdfView.pdfFile.getPageOffset(range.page, pdfView.getZoom())) / colWidth); 218 | range.rightBottom.row = MathUtils.floor(MathUtils.min(pageLastYOffset - secondaryOffset, 0) / rowHeight); 219 | } 220 | 221 | renderRanges.add(range); 222 | } 223 | 224 | return renderRanges; 225 | } 226 | 227 | private void loadVisible() { 228 | int parts = 0; 229 | float scaledPreloadOffset = preloadOffset; 230 | float firstXOffset = -xOffset + scaledPreloadOffset; 231 | float lastXOffset = -xOffset - pdfView.getWidth() - scaledPreloadOffset; 232 | float firstYOffset = -yOffset + scaledPreloadOffset; 233 | float lastYOffset = -yOffset - pdfView.getHeight() - scaledPreloadOffset; 234 | 235 | List rangeList = getRenderRangeList(firstXOffset, firstYOffset, lastXOffset, lastYOffset); 236 | 237 | for (RenderRange range : rangeList) { 238 | loadThumbnail(range.page); 239 | } 240 | 241 | for (RenderRange range : rangeList) { 242 | calculatePartSize(range.gridSize); 243 | parts += loadPage(range.page, range.leftTop.row, range.rightBottom.row, range.leftTop.col, range.rightBottom.col, CACHE_SIZE - parts); 244 | if (parts >= CACHE_SIZE) { 245 | break; 246 | } 247 | } 248 | 249 | } 250 | 251 | private int loadPage(int page, int firstRow, int lastRow, int firstCol, int lastCol, 252 | int nbOfPartsLoadable) { 253 | int loaded = 0; 254 | for (int row = firstRow; row <= lastRow; row++) { 255 | for (int col = firstCol; col <= lastCol; col++) { 256 | if (loadCell(page, row, col, pageRelativePartWidth, pageRelativePartHeight)) { 257 | loaded++; 258 | } 259 | if (loaded >= nbOfPartsLoadable) { 260 | return loaded; 261 | } 262 | } 263 | } 264 | return loaded; 265 | } 266 | 267 | private boolean loadCell(int page, int row, int col, float pageRelativePartWidth, float pageRelativePartHeight) { 268 | 269 | float relX = pageRelativePartWidth * col; 270 | float relY = pageRelativePartHeight * row; 271 | float relWidth = pageRelativePartWidth; 272 | float relHeight = pageRelativePartHeight; 273 | 274 | float renderWidth = partRenderWidth; 275 | float renderHeight = partRenderHeight; 276 | if (relX + relWidth > 1) { 277 | relWidth = 1 - relX; 278 | } 279 | if (relY + relHeight > 1) { 280 | relHeight = 1 - relY; 281 | } 282 | renderWidth *= relWidth; 283 | renderHeight *= relHeight; 284 | RectF pageRelativeBounds = new RectF(relX, relY, relX + relWidth, relY + relHeight); 285 | 286 | if (renderWidth > 0 && renderHeight > 0) { 287 | if (!pdfView.cacheManager.upPartIfContained(page, pageRelativeBounds, cacheOrder)) { 288 | pdfView.renderingHandler.addRenderingTask(page, renderWidth, renderHeight, 289 | pageRelativeBounds, false, cacheOrder, pdfView.isBestQuality(), 290 | pdfView.isAnnotationRendering()); 291 | } 292 | 293 | cacheOrder++; 294 | return true; 295 | } 296 | return false; 297 | } 298 | 299 | private void loadThumbnail(int page) { 300 | SizeF pageSize = pdfView.pdfFile.getPageSize(page); 301 | float thumbnailWidth = pageSize.getWidth() * Constants.THUMBNAIL_RATIO; 302 | float thumbnailHeight = pageSize.getHeight() * Constants.THUMBNAIL_RATIO; 303 | if (!pdfView.cacheManager.containsThumbnail(page, thumbnailRect)) { 304 | pdfView.renderingHandler.addRenderingTask(page, 305 | thumbnailWidth, thumbnailHeight, thumbnailRect, 306 | true, 0, pdfView.isBestQuality(), pdfView.isAnnotationRendering()); 307 | } 308 | } 309 | 310 | void loadPages() { 311 | cacheOrder = 1; 312 | xOffset = -MathUtils.max(pdfView.getCurrentXOffset(), 0); 313 | yOffset = -MathUtils.max(pdfView.getCurrentYOffset(), 0); 314 | 315 | loadVisible(); 316 | } 317 | } 318 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/PdfFile.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer; 17 | 18 | import android.graphics.Bitmap; 19 | import android.graphics.Rect; 20 | import android.graphics.RectF; 21 | import android.util.SparseBooleanArray; 22 | 23 | import com.github.barteksc.pdfviewer.exception.PageRenderingException; 24 | import com.github.barteksc.pdfviewer.util.FitPolicy; 25 | import com.github.barteksc.pdfviewer.util.PageSizeCalculator; 26 | import com.shockwave.pdfium.PdfDocument; 27 | import com.shockwave.pdfium.PdfiumCore; 28 | import com.shockwave.pdfium.util.Size; 29 | import com.shockwave.pdfium.util.SizeF; 30 | 31 | import java.util.ArrayList; 32 | import java.util.List; 33 | 34 | class PdfFile { 35 | 36 | private static final Object lock = new Object(); 37 | private PdfDocument pdfDocument; 38 | private PdfiumCore pdfiumCore; 39 | private int pagesCount = 0; 40 | /** Original page sizes */ 41 | private List originalPageSizes = new ArrayList<>(); 42 | /** Scaled page sizes */ 43 | private List pageSizes = new ArrayList<>(); 44 | /** Opened pages with indicator whether opening was successful */ 45 | private SparseBooleanArray openedPages = new SparseBooleanArray(); 46 | /** Page with maximum width */ 47 | private Size originalMaxWidthPageSize = new Size(0, 0); 48 | /** Page with maximum height */ 49 | private Size originalMaxHeightPageSize = new Size(0, 0); 50 | /** Scaled page with maximum height */ 51 | private SizeF maxHeightPageSize = new SizeF(0, 0); 52 | /** Scaled page with maximum width */ 53 | private SizeF maxWidthPageSize = new SizeF(0, 0); 54 | /** True if scrolling is vertical, else it's horizontal */ 55 | private boolean isVertical; 56 | /** Fixed spacing between pages in pixels */ 57 | private int spacingPx; 58 | /** Calculate spacing automatically so each page fits on it's own in the center of the view */ 59 | private boolean autoSpacing; 60 | /** Calculated offsets for pages */ 61 | private List pageOffsets = new ArrayList<>(); 62 | /** Calculated auto spacing for pages */ 63 | private List pageSpacing = new ArrayList<>(); 64 | /** Calculated document length (width or height, depending on swipe mode) */ 65 | private float documentLength = 0; 66 | private final FitPolicy pageFitPolicy; 67 | /** 68 | * True if every page should fit separately according to the FitPolicy, 69 | * else the largest page fits and other pages scale relatively 70 | */ 71 | private final boolean fitEachPage; 72 | /** 73 | * The pages the user want to display in order 74 | * (ex: 0, 2, 2, 8, 8, 1, 1, 1) 75 | */ 76 | private int[] originalUserPages; 77 | 78 | PdfFile(PdfiumCore pdfiumCore, PdfDocument pdfDocument, FitPolicy pageFitPolicy, Size viewSize, int[] originalUserPages, 79 | boolean isVertical, int spacing, boolean autoSpacing, boolean fitEachPage) { 80 | this.pdfiumCore = pdfiumCore; 81 | this.pdfDocument = pdfDocument; 82 | this.pageFitPolicy = pageFitPolicy; 83 | this.originalUserPages = originalUserPages; 84 | this.isVertical = isVertical; 85 | this.spacingPx = spacing; 86 | this.autoSpacing = autoSpacing; 87 | this.fitEachPage = fitEachPage; 88 | setup(viewSize); 89 | } 90 | 91 | private void setup(Size viewSize) { 92 | if (originalUserPages != null) { 93 | pagesCount = originalUserPages.length; 94 | } else { 95 | pagesCount = pdfiumCore.getPageCount(pdfDocument); 96 | } 97 | 98 | for (int i = 0; i < pagesCount; i++) { 99 | Size pageSize = pdfiumCore.getPageSize(pdfDocument, documentPage(i)); 100 | if (pageSize.getWidth() > originalMaxWidthPageSize.getWidth()) { 101 | originalMaxWidthPageSize = pageSize; 102 | } 103 | if (pageSize.getHeight() > originalMaxHeightPageSize.getHeight()) { 104 | originalMaxHeightPageSize = pageSize; 105 | } 106 | originalPageSizes.add(pageSize); 107 | } 108 | 109 | recalculatePageSizes(viewSize); 110 | } 111 | 112 | /** 113 | * Call after view size change to recalculate page sizes, offsets and document length 114 | * 115 | * @param viewSize new size of changed view 116 | */ 117 | public void recalculatePageSizes(Size viewSize) { 118 | pageSizes.clear(); 119 | PageSizeCalculator calculator = new PageSizeCalculator(pageFitPolicy, originalMaxWidthPageSize, 120 | originalMaxHeightPageSize, viewSize, fitEachPage); 121 | maxWidthPageSize = calculator.getOptimalMaxWidthPageSize(); 122 | maxHeightPageSize = calculator.getOptimalMaxHeightPageSize(); 123 | 124 | for (Size size : originalPageSizes) { 125 | pageSizes.add(calculator.calculate(size)); 126 | } 127 | if (autoSpacing) { 128 | prepareAutoSpacing(viewSize); 129 | } 130 | prepareDocLen(); 131 | preparePagesOffset(); 132 | } 133 | 134 | public int getPagesCount() { 135 | return pagesCount; 136 | } 137 | 138 | public SizeF getPageSize(int pageIndex) { 139 | int docPage = documentPage(pageIndex); 140 | if (docPage < 0) { 141 | return new SizeF(0, 0); 142 | } 143 | return pageSizes.get(pageIndex); 144 | } 145 | 146 | public SizeF getScaledPageSize(int pageIndex, float zoom) { 147 | SizeF size = getPageSize(pageIndex); 148 | return new SizeF(size.getWidth() * zoom, size.getHeight() * zoom); 149 | } 150 | 151 | /** 152 | * get page size with biggest dimension (width in vertical mode and height in horizontal mode) 153 | * 154 | * @return size of page 155 | */ 156 | public SizeF getMaxPageSize() { 157 | return isVertical ? maxWidthPageSize : maxHeightPageSize; 158 | } 159 | 160 | public float getMaxPageWidth() { 161 | return getMaxPageSize().getWidth(); 162 | } 163 | 164 | public float getMaxPageHeight() { 165 | return getMaxPageSize().getHeight(); 166 | } 167 | 168 | private void prepareAutoSpacing(Size viewSize) { 169 | pageSpacing.clear(); 170 | for (int i = 0; i < getPagesCount(); i++) { 171 | SizeF pageSize = pageSizes.get(i); 172 | float spacing = Math.max(0, isVertical ? viewSize.getHeight() - pageSize.getHeight() : 173 | viewSize.getWidth() - pageSize.getWidth()); 174 | if (i < getPagesCount() - 1) { 175 | spacing += spacingPx; 176 | } 177 | pageSpacing.add(spacing); 178 | } 179 | } 180 | 181 | private void prepareDocLen() { 182 | float length = 0; 183 | for (int i = 0; i < getPagesCount(); i++) { 184 | SizeF pageSize = pageSizes.get(i); 185 | length += isVertical ? pageSize.getHeight() : pageSize.getWidth(); 186 | if (autoSpacing) { 187 | length += pageSpacing.get(i); 188 | } else if (i < getPagesCount() - 1) { 189 | length += spacingPx; 190 | } 191 | } 192 | documentLength = length; 193 | } 194 | 195 | private void preparePagesOffset() { 196 | pageOffsets.clear(); 197 | float offset = 0; 198 | for (int i = 0; i < getPagesCount(); i++) { 199 | SizeF pageSize = pageSizes.get(i); 200 | float size = isVertical ? pageSize.getHeight() : pageSize.getWidth(); 201 | if (autoSpacing) { 202 | offset += pageSpacing.get(i) / 2f; 203 | if (i == 0) { 204 | offset -= spacingPx / 2f; 205 | } else if (i == getPagesCount() - 1) { 206 | offset += spacingPx / 2f; 207 | } 208 | pageOffsets.add(offset); 209 | offset += size + pageSpacing.get(i) / 2f; 210 | } else { 211 | pageOffsets.add(offset); 212 | offset += size + spacingPx; 213 | } 214 | } 215 | } 216 | 217 | public float getDocLen(float zoom) { 218 | return documentLength * zoom; 219 | } 220 | 221 | /** 222 | * Get the page's height if swiping vertical, or width if swiping horizontal. 223 | */ 224 | public float getPageLength(int pageIndex, float zoom) { 225 | SizeF size = getPageSize(pageIndex); 226 | return (isVertical ? size.getHeight() : size.getWidth()) * zoom; 227 | } 228 | 229 | public float getPageSpacing(int pageIndex, float zoom) { 230 | float spacing = autoSpacing ? pageSpacing.get(pageIndex) : spacingPx; 231 | return spacing * zoom; 232 | } 233 | 234 | /** Get primary page offset, that is Y for vertical scroll and X for horizontal scroll */ 235 | public float getPageOffset(int pageIndex, float zoom) { 236 | int docPage = documentPage(pageIndex); 237 | if (docPage < 0) { 238 | return 0; 239 | } 240 | return pageOffsets.get(pageIndex) * zoom; 241 | } 242 | 243 | /** Get secondary page offset, that is X for vertical scroll and Y for horizontal scroll */ 244 | public float getSecondaryPageOffset(int pageIndex, float zoom) { 245 | SizeF pageSize = getPageSize(pageIndex); 246 | if (isVertical) { 247 | float maxWidth = getMaxPageWidth(); 248 | return zoom * (maxWidth - pageSize.getWidth()) / 2; //x 249 | } else { 250 | float maxHeight = getMaxPageHeight(); 251 | return zoom * (maxHeight - pageSize.getHeight()) / 2; //y 252 | } 253 | } 254 | 255 | public int getPageAtOffset(float offset, float zoom) { 256 | int currentPage = 0; 257 | for (int i = 0; i < getPagesCount(); i++) { 258 | float off = pageOffsets.get(i) * zoom - getPageSpacing(i, zoom) / 2f; 259 | if (off >= offset) { 260 | break; 261 | } 262 | currentPage++; 263 | } 264 | return --currentPage >= 0 ? currentPage : 0; 265 | } 266 | 267 | public boolean openPage(int pageIndex) throws PageRenderingException { 268 | int docPage = documentPage(pageIndex); 269 | if (docPage < 0) { 270 | return false; 271 | } 272 | 273 | synchronized (lock) { 274 | if (openedPages.indexOfKey(docPage) < 0) { 275 | try { 276 | pdfiumCore.openPage(pdfDocument, docPage); 277 | openedPages.put(docPage, true); 278 | return true; 279 | } catch (Exception e) { 280 | openedPages.put(docPage, false); 281 | throw new PageRenderingException(pageIndex, e); 282 | } 283 | } 284 | return false; 285 | } 286 | } 287 | 288 | public boolean pageHasError(int pageIndex) { 289 | int docPage = documentPage(pageIndex); 290 | return !openedPages.get(docPage, false); 291 | } 292 | 293 | public void renderPageBitmap(Bitmap bitmap, int pageIndex, Rect bounds, boolean annotationRendering) { 294 | int docPage = documentPage(pageIndex); 295 | pdfiumCore.renderPageBitmap(pdfDocument, bitmap, docPage, 296 | bounds.left, bounds.top, bounds.width(), bounds.height(), annotationRendering); 297 | } 298 | 299 | public PdfDocument.Meta getMetaData() { 300 | if (pdfDocument == null) { 301 | return null; 302 | } 303 | return pdfiumCore.getDocumentMeta(pdfDocument); 304 | } 305 | 306 | public List getBookmarks() { 307 | if (pdfDocument == null) { 308 | return new ArrayList<>(); 309 | } 310 | return pdfiumCore.getTableOfContents(pdfDocument); 311 | } 312 | 313 | public List getPageLinks(int pageIndex) { 314 | int docPage = documentPage(pageIndex); 315 | return pdfiumCore.getPageLinks(pdfDocument, docPage); 316 | } 317 | 318 | public RectF mapRectToDevice(int pageIndex, int startX, int startY, int sizeX, int sizeY, 319 | RectF rect) { 320 | int docPage = documentPage(pageIndex); 321 | return pdfiumCore.mapRectToDevice(pdfDocument, docPage, startX, startY, sizeX, sizeY, 0, rect); 322 | } 323 | 324 | public void dispose() { 325 | if (pdfiumCore != null && pdfDocument != null) { 326 | pdfiumCore.closeDocument(pdfDocument); 327 | } 328 | 329 | pdfDocument = null; 330 | originalUserPages = null; 331 | } 332 | 333 | /** 334 | * Given the UserPage number, this method restrict it 335 | * to be sure it's an existing page. It takes care of 336 | * using the user defined pages if any. 337 | * 338 | * @param userPage A page number. 339 | * @return A restricted valid page number (example : -2 => 0) 340 | */ 341 | public int determineValidPageNumberFrom(int userPage) { 342 | if (userPage <= 0) { 343 | return 0; 344 | } 345 | if (originalUserPages != null) { 346 | if (userPage >= originalUserPages.length) { 347 | return originalUserPages.length - 1; 348 | } 349 | } else { 350 | if (userPage >= getPagesCount()) { 351 | return getPagesCount() - 1; 352 | } 353 | } 354 | return userPage; 355 | } 356 | 357 | public int documentPage(int userPage) { 358 | int documentPage = userPage; 359 | if (originalUserPages != null) { 360 | if (userPage < 0 || userPage >= originalUserPages.length) { 361 | return -1; 362 | } else { 363 | documentPage = originalUserPages[userPage]; 364 | } 365 | } 366 | 367 | if (documentPage < 0 || userPage >= getPagesCount()) { 368 | return -1; 369 | } 370 | 371 | return documentPage; 372 | } 373 | } 374 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/RenderingHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2016 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer; 17 | 18 | import android.graphics.Bitmap; 19 | import android.graphics.Color; 20 | import android.graphics.Matrix; 21 | import android.graphics.Rect; 22 | import android.graphics.RectF; 23 | import android.os.Handler; 24 | import android.os.Looper; 25 | import android.os.Message; 26 | import android.util.Log; 27 | 28 | import com.github.barteksc.pdfviewer.exception.PageRenderingException; 29 | import com.github.barteksc.pdfviewer.model.PagePart; 30 | 31 | /** 32 | * A {@link Handler} that will process incoming {@link RenderingTask} messages 33 | * and alert {@link PDFView#onBitmapRendered(PagePart)} when the portion of the 34 | * PDF is ready to render. 35 | */ 36 | class RenderingHandler extends Handler { 37 | /** 38 | * {@link Message#what} kind of message this handler processes. 39 | */ 40 | static final int MSG_RENDER_TASK = 1; 41 | 42 | private static final String TAG = RenderingHandler.class.getName(); 43 | 44 | private PDFView pdfView; 45 | 46 | private RectF renderBounds = new RectF(); 47 | private Rect roundedRenderBounds = new Rect(); 48 | private Matrix renderMatrix = new Matrix(); 49 | private boolean running = false; 50 | 51 | RenderingHandler(Looper looper, PDFView pdfView) { 52 | super(looper); 53 | this.pdfView = pdfView; 54 | } 55 | 56 | void addRenderingTask(int page, float width, float height, RectF bounds, boolean thumbnail, int cacheOrder, boolean bestQuality, boolean annotationRendering) { 57 | RenderingTask task = new RenderingTask(width, height, bounds, page, thumbnail, cacheOrder, bestQuality, annotationRendering); 58 | Message msg = obtainMessage(MSG_RENDER_TASK, task); 59 | sendMessage(msg); 60 | } 61 | 62 | @Override 63 | public void handleMessage(Message message) { 64 | RenderingTask task = (RenderingTask) message.obj; 65 | try { 66 | final PagePart part = proceed(task); 67 | if (part != null) { 68 | if (running) { 69 | pdfView.post(new Runnable() { 70 | @Override 71 | public void run() { 72 | pdfView.onBitmapRendered(part); 73 | } 74 | }); 75 | } else { 76 | part.getRenderedBitmap().recycle(); 77 | } 78 | } 79 | } catch (final PageRenderingException ex) { 80 | pdfView.post(new Runnable() { 81 | @Override 82 | public void run() { 83 | pdfView.onPageError(ex); 84 | } 85 | }); 86 | } 87 | } 88 | 89 | private PagePart proceed(RenderingTask renderingTask) throws PageRenderingException { 90 | PdfFile pdfFile = pdfView.pdfFile; 91 | pdfFile.openPage(renderingTask.page); 92 | 93 | int w = Math.round(renderingTask.width); 94 | int h = Math.round(renderingTask.height); 95 | 96 | if (w == 0 || h == 0 || pdfFile.pageHasError(renderingTask.page)) { 97 | return null; 98 | } 99 | 100 | Bitmap render; 101 | try { 102 | render = Bitmap.createBitmap(w, h, renderingTask.bestQuality ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); 103 | } catch (IllegalArgumentException e) { 104 | Log.e(TAG, "Cannot create bitmap", e); 105 | return null; 106 | } 107 | calculateBounds(w, h, renderingTask.bounds); 108 | 109 | pdfFile.renderPageBitmap(render, renderingTask.page, roundedRenderBounds, renderingTask.annotationRendering); 110 | 111 | return new PagePart(renderingTask.page, render, 112 | renderingTask.bounds, renderingTask.thumbnail, 113 | renderingTask.cacheOrder); 114 | } 115 | 116 | private void calculateBounds(int width, int height, RectF pageSliceBounds) { 117 | renderMatrix.reset(); 118 | renderMatrix.postTranslate(-pageSliceBounds.left * width, -pageSliceBounds.top * height); 119 | renderMatrix.postScale(1 / pageSliceBounds.width(), 1 / pageSliceBounds.height()); 120 | 121 | renderBounds.set(0, 0, width, height); 122 | renderMatrix.mapRect(renderBounds); 123 | renderBounds.round(roundedRenderBounds); 124 | } 125 | 126 | void stop() { 127 | running = false; 128 | } 129 | 130 | void start() { 131 | running = true; 132 | } 133 | 134 | private class RenderingTask { 135 | 136 | float width, height; 137 | 138 | RectF bounds; 139 | 140 | int page; 141 | 142 | boolean thumbnail; 143 | 144 | int cacheOrder; 145 | 146 | boolean bestQuality; 147 | 148 | boolean annotationRendering; 149 | 150 | RenderingTask(float width, float height, RectF bounds, int page, boolean thumbnail, int cacheOrder, boolean bestQuality, boolean annotationRendering) { 151 | this.page = page; 152 | this.width = width; 153 | this.height = height; 154 | this.bounds = bounds; 155 | this.thumbnail = thumbnail; 156 | this.cacheOrder = cacheOrder; 157 | this.bestQuality = bestQuality; 158 | this.annotationRendering = annotationRendering; 159 | } 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/exception/FileNotFoundException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2016 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.exception; 17 | 18 | @Deprecated 19 | public class FileNotFoundException extends RuntimeException { 20 | 21 | public FileNotFoundException(String detailMessage) { 22 | super(detailMessage); 23 | } 24 | 25 | public FileNotFoundException(String detailMessage, Throwable throwable) { 26 | super(detailMessage, throwable); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/exception/PageRenderingException.java: -------------------------------------------------------------------------------- 1 | package com.github.barteksc.pdfviewer.exception; 2 | 3 | public class PageRenderingException extends Exception { 4 | private final int page; 5 | 6 | public PageRenderingException(int page, Throwable cause) { 7 | super(cause); 8 | this.page = page; 9 | } 10 | 11 | public int getPage() { 12 | return page; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/link/DefaultLinkHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.link; 17 | 18 | import android.content.Context; 19 | import android.content.Intent; 20 | import android.net.Uri; 21 | import android.util.Log; 22 | 23 | import com.github.barteksc.pdfviewer.PDFView; 24 | import com.github.barteksc.pdfviewer.model.LinkTapEvent; 25 | 26 | public class DefaultLinkHandler implements LinkHandler { 27 | 28 | private static final String TAG = DefaultLinkHandler.class.getSimpleName(); 29 | 30 | private PDFView pdfView; 31 | 32 | public DefaultLinkHandler(PDFView pdfView) { 33 | this.pdfView = pdfView; 34 | } 35 | 36 | @Override 37 | public void handleLinkEvent(LinkTapEvent event) { 38 | String uri = event.getLink().getUri(); 39 | Integer page = event.getLink().getDestPageIdx(); 40 | if (uri != null && !uri.isEmpty()) { 41 | handleUri(uri); 42 | } else if (page != null) { 43 | handlePage(page); 44 | } 45 | } 46 | 47 | private void handleUri(String uri) { 48 | Uri parsedUri = Uri.parse(uri); 49 | Intent intent = new Intent(Intent.ACTION_VIEW, parsedUri); 50 | Context context = pdfView.getContext(); 51 | if (intent.resolveActivity(context.getPackageManager()) != null) { 52 | context.startActivity(intent); 53 | } else { 54 | Log.w(TAG, "No activity found for URI: " + uri); 55 | } 56 | } 57 | 58 | private void handlePage(int page) { 59 | pdfView.jumpTo(page); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/link/LinkHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.link; 17 | 18 | import com.github.barteksc.pdfviewer.model.LinkTapEvent; 19 | 20 | public interface LinkHandler { 21 | 22 | /** 23 | * Called when link was tapped by user 24 | * 25 | * @param event current event 26 | */ 27 | void handleLinkEvent(LinkTapEvent event); 28 | } 29 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/listener/Callbacks.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.listener; 17 | 18 | import android.view.MotionEvent; 19 | 20 | import com.github.barteksc.pdfviewer.link.LinkHandler; 21 | import com.github.barteksc.pdfviewer.model.LinkTapEvent; 22 | 23 | public class Callbacks { 24 | 25 | /** 26 | * Call back object to call when the PDF is loaded 27 | */ 28 | private OnLoadCompleteListener onLoadCompleteListener; 29 | 30 | /** 31 | * Call back object to call when document loading error occurs 32 | */ 33 | private OnErrorListener onErrorListener; 34 | 35 | /** 36 | * Call back object to call when the page load error occurs 37 | */ 38 | private OnPageErrorListener onPageErrorListener; 39 | 40 | /** 41 | * Call back object to call when the document is initially rendered 42 | */ 43 | private OnRenderListener onRenderListener; 44 | 45 | /** 46 | * Call back object to call when the page has changed 47 | */ 48 | private OnPageChangeListener onPageChangeListener; 49 | 50 | /** 51 | * Call back object to call when the page is scrolled 52 | */ 53 | private OnPageScrollListener onPageScrollListener; 54 | 55 | /** 56 | * Call back object to call when the above layer is to drawn 57 | */ 58 | private OnDrawListener onDrawListener; 59 | 60 | private OnDrawListener onDrawAllListener; 61 | 62 | /** 63 | * Call back object to call when the user does a tap gesture 64 | */ 65 | private OnTapListener onTapListener; 66 | 67 | /** 68 | * Call back object to call when the user does a long tap gesture 69 | */ 70 | private OnLongPressListener onLongPressListener; 71 | 72 | /** 73 | * Call back object to call when clicking link 74 | */ 75 | private LinkHandler linkHandler; 76 | 77 | public void setOnLoadComplete(OnLoadCompleteListener onLoadCompleteListener) { 78 | this.onLoadCompleteListener = onLoadCompleteListener; 79 | } 80 | 81 | public void callOnLoadComplete(int pagesCount) { 82 | if (onLoadCompleteListener != null) { 83 | onLoadCompleteListener.loadComplete(pagesCount); 84 | } 85 | } 86 | 87 | public void setOnError(OnErrorListener onErrorListener) { 88 | this.onErrorListener = onErrorListener; 89 | } 90 | 91 | public OnErrorListener getOnError() { 92 | return onErrorListener; 93 | } 94 | 95 | public void setOnPageError(OnPageErrorListener onPageErrorListener) { 96 | this.onPageErrorListener = onPageErrorListener; 97 | } 98 | 99 | public boolean callOnPageError(int page, Throwable error) { 100 | if (onPageErrorListener != null) { 101 | onPageErrorListener.onPageError(page, error); 102 | return true; 103 | } 104 | return false; 105 | } 106 | 107 | public void setOnRender(OnRenderListener onRenderListener) { 108 | this.onRenderListener = onRenderListener; 109 | } 110 | 111 | public void callOnRender(int pagesCount) { 112 | if (onRenderListener != null) { 113 | onRenderListener.onInitiallyRendered(pagesCount); 114 | } 115 | } 116 | 117 | public void setOnPageChange(OnPageChangeListener onPageChangeListener) { 118 | this.onPageChangeListener = onPageChangeListener; 119 | } 120 | 121 | public void callOnPageChange(int page, int pagesCount) { 122 | if (onPageChangeListener != null) { 123 | onPageChangeListener.onPageChanged(page, pagesCount); 124 | } 125 | } 126 | 127 | public void setOnPageScroll(OnPageScrollListener onPageScrollListener) { 128 | this.onPageScrollListener = onPageScrollListener; 129 | } 130 | 131 | public void callOnPageScroll(int currentPage, float offset) { 132 | if (onPageScrollListener != null) { 133 | onPageScrollListener.onPageScrolled(currentPage, offset); 134 | } 135 | } 136 | 137 | public void setOnDraw(OnDrawListener onDrawListener) { 138 | this.onDrawListener = onDrawListener; 139 | } 140 | 141 | public OnDrawListener getOnDraw() { 142 | return onDrawListener; 143 | } 144 | 145 | public void setOnDrawAll(OnDrawListener onDrawAllListener) { 146 | this.onDrawAllListener = onDrawAllListener; 147 | } 148 | 149 | public OnDrawListener getOnDrawAll() { 150 | return onDrawAllListener; 151 | } 152 | 153 | public void setOnTap(OnTapListener onTapListener) { 154 | this.onTapListener = onTapListener; 155 | } 156 | 157 | public boolean callOnTap(MotionEvent event) { 158 | return onTapListener != null && onTapListener.onTap(event); 159 | } 160 | 161 | public void setOnLongPress(OnLongPressListener onLongPressListener) { 162 | this.onLongPressListener = onLongPressListener; 163 | } 164 | 165 | public void callOnLongPress(MotionEvent event) { 166 | if (onLongPressListener != null) { 167 | onLongPressListener.onLongPress(event); 168 | } 169 | } 170 | 171 | public void setLinkHandler(LinkHandler linkHandler) { 172 | this.linkHandler = linkHandler; 173 | } 174 | 175 | public void callLinkHandler(LinkTapEvent event) { 176 | if (linkHandler != null) { 177 | linkHandler.handleLinkEvent(event); 178 | } 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/listener/OnDrawListener.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2016 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.listener; 17 | 18 | import android.graphics.Canvas; 19 | 20 | /** 21 | * This interface allows an extern class to draw 22 | * something on the PDFView canvas, above all images. 23 | */ 24 | public interface OnDrawListener { 25 | 26 | /** 27 | * This method is called when the PDFView is 28 | * drawing its view. 29 | *

30 | * The page is starting at (0,0) 31 | * 32 | * @param canvas The canvas on which to draw things. 33 | * @param pageWidth The width of the current page. 34 | * @param pageHeight The height of the current page. 35 | * @param displayedPage The current page index 36 | */ 37 | void onLayerDrawn(Canvas canvas, float pageWidth, float pageHeight, int displayedPage); 38 | } 39 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/listener/OnErrorListener.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2016 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.listener; 17 | 18 | public interface OnErrorListener { 19 | 20 | /** 21 | * Called if error occurred while opening PDF 22 | * @param t Throwable with error 23 | */ 24 | void onError(Throwable t); 25 | } 26 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/listener/OnLoadCompleteListener.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2016 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.listener; 17 | 18 | /** 19 | * Implement this interface to receive events from PDFView 20 | * when loading is complete. 21 | */ 22 | public interface OnLoadCompleteListener { 23 | 24 | /** 25 | * Called when the PDF is loaded 26 | * @param nbPages the number of pages in this PDF file 27 | */ 28 | void loadComplete(int nbPages); 29 | } 30 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/listener/OnLongPressListener.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.listener; 17 | 18 | import android.view.MotionEvent; 19 | 20 | /** 21 | * Implement this interface to receive events from PDFView 22 | * when view has been long pressed 23 | */ 24 | public interface OnLongPressListener { 25 | 26 | /** 27 | * Called when the user has a long tap gesture, before processing scroll handle toggling 28 | * 29 | * @param e MotionEvent that registered as a confirmed long press 30 | */ 31 | void onLongPress(MotionEvent e); 32 | } 33 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/listener/OnPageChangeListener.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2016 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.listener; 17 | 18 | /** 19 | * Implements this interface to receive events from PDFView 20 | * when a page has changed through swipe 21 | */ 22 | public interface OnPageChangeListener { 23 | 24 | /** 25 | * Called when the user use swipe to change page 26 | * 27 | * @param page the new page displayed, starting from 0 28 | * @param pageCount the total page count 29 | */ 30 | void onPageChanged(int page, int pageCount); 31 | 32 | } 33 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/listener/OnPageErrorListener.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.listener; 17 | 18 | public interface OnPageErrorListener { 19 | 20 | /** 21 | * Called if error occurred while loading PDF page 22 | * @param t Throwable with error 23 | */ 24 | void onPageError(int page, Throwable t); 25 | } 26 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/listener/OnPageScrollListener.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2016 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.listener; 17 | 18 | /** 19 | * Implements this interface to receive events from PDFView 20 | * when a page has been scrolled 21 | */ 22 | public interface OnPageScrollListener { 23 | 24 | /** 25 | * Called on every move while scrolling 26 | * 27 | * @param page current page index 28 | * @param positionOffset see {@link com.github.barteksc.pdfviewer.PDFView#getPositionOffset()} 29 | */ 30 | void onPageScrolled(int page, float positionOffset); 31 | } 32 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/listener/OnRenderListener.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.listener; 17 | 18 | public interface OnRenderListener { 19 | 20 | /** 21 | * Called only once, when document is rendered 22 | * @param nbPages number of pages 23 | */ 24 | void onInitiallyRendered(int nbPages); 25 | } 26 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/listener/OnTapListener.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.listener; 17 | 18 | import android.view.MotionEvent; 19 | 20 | /** 21 | * Implement this interface to receive events from PDFView 22 | * when view has been touched 23 | */ 24 | public interface OnTapListener { 25 | 26 | /** 27 | * Called when the user has a tap gesture, before processing scroll handle toggling 28 | * 29 | * @param e MotionEvent that registered as a confirmed single tap 30 | * @return true if the single tap was handled, false to toggle scroll handle 31 | */ 32 | boolean onTap(MotionEvent e); 33 | } 34 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/model/LinkTapEvent.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2016 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.model; 17 | 18 | import android.graphics.RectF; 19 | 20 | import com.shockwave.pdfium.PdfDocument; 21 | 22 | public class LinkTapEvent { 23 | private float originalX; 24 | private float originalY; 25 | private float documentX; 26 | private float documentY; 27 | private RectF mappedLinkRect; 28 | private PdfDocument.Link link; 29 | 30 | public LinkTapEvent(float originalX, float originalY, float documentX, float documentY, RectF mappedLinkRect, PdfDocument.Link link) { 31 | this.originalX = originalX; 32 | this.originalY = originalY; 33 | this.documentX = documentX; 34 | this.documentY = documentY; 35 | this.mappedLinkRect = mappedLinkRect; 36 | this.link = link; 37 | } 38 | 39 | public float getOriginalX() { 40 | return originalX; 41 | } 42 | 43 | public float getOriginalY() { 44 | return originalY; 45 | } 46 | 47 | public float getDocumentX() { 48 | return documentX; 49 | } 50 | 51 | public float getDocumentY() { 52 | return documentY; 53 | } 54 | 55 | public RectF getMappedLinkRect() { 56 | return mappedLinkRect; 57 | } 58 | 59 | public PdfDocument.Link getLink() { 60 | return link; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/model/PagePart.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2016 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.model; 17 | 18 | import android.graphics.Bitmap; 19 | import android.graphics.RectF; 20 | 21 | public class PagePart { 22 | 23 | private int page; 24 | 25 | private Bitmap renderedBitmap; 26 | 27 | private RectF pageRelativeBounds; 28 | 29 | private boolean thumbnail; 30 | 31 | private int cacheOrder; 32 | 33 | public PagePart(int page, Bitmap renderedBitmap, RectF pageRelativeBounds, boolean thumbnail, int cacheOrder) { 34 | super(); 35 | this.page = page; 36 | this.renderedBitmap = renderedBitmap; 37 | this.pageRelativeBounds = pageRelativeBounds; 38 | this.thumbnail = thumbnail; 39 | this.cacheOrder = cacheOrder; 40 | } 41 | 42 | public int getCacheOrder() { 43 | return cacheOrder; 44 | } 45 | 46 | public int getPage() { 47 | return page; 48 | } 49 | 50 | public Bitmap getRenderedBitmap() { 51 | return renderedBitmap; 52 | } 53 | 54 | public RectF getPageRelativeBounds() { 55 | return pageRelativeBounds; 56 | } 57 | 58 | public boolean isThumbnail() { 59 | return thumbnail; 60 | } 61 | 62 | public void setCacheOrder(int cacheOrder) { 63 | this.cacheOrder = cacheOrder; 64 | } 65 | 66 | @Override 67 | public boolean equals(Object obj) { 68 | if (!(obj instanceof PagePart)) { 69 | return false; 70 | } 71 | 72 | PagePart part = (PagePart) obj; 73 | return part.getPage() == page 74 | && part.getPageRelativeBounds().left == pageRelativeBounds.left 75 | && part.getPageRelativeBounds().right == pageRelativeBounds.right 76 | && part.getPageRelativeBounds().top == pageRelativeBounds.top 77 | && part.getPageRelativeBounds().bottom == pageRelativeBounds.bottom; 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/scroll/DefaultScrollHandle.java: -------------------------------------------------------------------------------- 1 | package com.github.barteksc.pdfviewer.scroll; 2 | 3 | import android.content.Context; 4 | import android.graphics.Color; 5 | import android.graphics.drawable.Drawable; 6 | import android.os.Handler; 7 | import androidx.core.content.ContextCompat; 8 | import android.util.TypedValue; 9 | import android.view.MotionEvent; 10 | import android.view.ViewGroup; 11 | import android.widget.RelativeLayout; 12 | import android.widget.TextView; 13 | 14 | import com.github.barteksc.pdfviewer.PDFView; 15 | import com.github.barteksc.pdfviewer.R; 16 | import com.github.barteksc.pdfviewer.util.Util; 17 | 18 | public class DefaultScrollHandle extends RelativeLayout implements ScrollHandle { 19 | 20 | private final static int HANDLE_LONG = 65; 21 | private final static int HANDLE_SHORT = 40; 22 | private final static int DEFAULT_TEXT_SIZE = 16; 23 | 24 | private float relativeHandlerMiddle = 0f; 25 | 26 | protected TextView textView; 27 | protected Context context; 28 | private boolean inverted; 29 | private PDFView pdfView; 30 | private float currentPos; 31 | 32 | private Handler handler = new Handler(); 33 | private Runnable hidePageScrollerRunnable = new Runnable() { 34 | @Override 35 | public void run() { 36 | hide(); 37 | } 38 | }; 39 | 40 | public DefaultScrollHandle(Context context) { 41 | this(context, false); 42 | } 43 | 44 | public DefaultScrollHandle(Context context, boolean inverted) { 45 | super(context); 46 | this.context = context; 47 | this.inverted = inverted; 48 | textView = new TextView(context); 49 | setVisibility(INVISIBLE); 50 | setTextColor(Color.BLACK); 51 | setTextSize(DEFAULT_TEXT_SIZE); 52 | } 53 | 54 | @Override 55 | public void setupLayout(PDFView pdfView) { 56 | int align, width, height; 57 | Drawable background; 58 | // determine handler position, default is right (when scrolling vertically) or bottom (when scrolling horizontally) 59 | if (pdfView.isSwipeVertical()) { 60 | width = HANDLE_LONG; 61 | height = HANDLE_SHORT; 62 | if (inverted) { // left 63 | align = ALIGN_PARENT_LEFT; 64 | background = ContextCompat.getDrawable(context, R.drawable.default_scroll_handle_left); 65 | } else { // right 66 | align = ALIGN_PARENT_RIGHT; 67 | background = ContextCompat.getDrawable(context, R.drawable.default_scroll_handle_right); 68 | } 69 | } else { 70 | width = HANDLE_SHORT; 71 | height = HANDLE_LONG; 72 | if (inverted) { // top 73 | align = ALIGN_PARENT_TOP; 74 | background = ContextCompat.getDrawable(context, R.drawable.default_scroll_handle_top); 75 | } else { // bottom 76 | align = ALIGN_PARENT_BOTTOM; 77 | background = ContextCompat.getDrawable(context, R.drawable.default_scroll_handle_bottom); 78 | } 79 | } 80 | 81 | if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) { 82 | setBackgroundDrawable(background); 83 | } else { 84 | setBackground(background); 85 | } 86 | 87 | LayoutParams lp = new LayoutParams(Util.getDP(context, width), Util.getDP(context, height)); 88 | lp.setMargins(0, 0, 0, 0); 89 | 90 | LayoutParams tvlp = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); 91 | tvlp.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); 92 | 93 | addView(textView, tvlp); 94 | 95 | lp.addRule(align); 96 | pdfView.addView(this, lp); 97 | 98 | this.pdfView = pdfView; 99 | } 100 | 101 | @Override 102 | public void destroyLayout() { 103 | pdfView.removeView(this); 104 | } 105 | 106 | @Override 107 | public void setScroll(float position) { 108 | if (!shown()) { 109 | show(); 110 | } else { 111 | handler.removeCallbacks(hidePageScrollerRunnable); 112 | } 113 | if (pdfView != null) { 114 | setPosition((pdfView.isSwipeVertical() ? pdfView.getHeight() : pdfView.getWidth()) * position); 115 | } 116 | } 117 | 118 | private void setPosition(float pos) { 119 | if (Float.isInfinite(pos) || Float.isNaN(pos)) { 120 | return; 121 | } 122 | float pdfViewSize; 123 | if (pdfView.isSwipeVertical()) { 124 | pdfViewSize = pdfView.getHeight(); 125 | } else { 126 | pdfViewSize = pdfView.getWidth(); 127 | } 128 | pos -= relativeHandlerMiddle; 129 | 130 | if (pos < 0) { 131 | pos = 0; 132 | } else if (pos > pdfViewSize - Util.getDP(context, HANDLE_SHORT)) { 133 | pos = pdfViewSize - Util.getDP(context, HANDLE_SHORT); 134 | } 135 | 136 | if (pdfView.isSwipeVertical()) { 137 | setY(pos); 138 | } else { 139 | setX(pos); 140 | } 141 | 142 | calculateMiddle(); 143 | invalidate(); 144 | } 145 | 146 | private void calculateMiddle() { 147 | float pos, viewSize, pdfViewSize; 148 | if (pdfView.isSwipeVertical()) { 149 | pos = getY(); 150 | viewSize = getHeight(); 151 | pdfViewSize = pdfView.getHeight(); 152 | } else { 153 | pos = getX(); 154 | viewSize = getWidth(); 155 | pdfViewSize = pdfView.getWidth(); 156 | } 157 | relativeHandlerMiddle = ((pos + relativeHandlerMiddle) / pdfViewSize) * viewSize; 158 | } 159 | 160 | @Override 161 | public void hideDelayed() { 162 | handler.postDelayed(hidePageScrollerRunnable, 1000); 163 | } 164 | 165 | @Override 166 | public void setPageNum(int pageNum) { 167 | String text = String.valueOf(pageNum); 168 | if (!textView.getText().equals(text)) { 169 | textView.setText(text); 170 | } 171 | } 172 | 173 | @Override 174 | public boolean shown() { 175 | return getVisibility() == VISIBLE; 176 | } 177 | 178 | @Override 179 | public void show() { 180 | setVisibility(VISIBLE); 181 | } 182 | 183 | @Override 184 | public void hide() { 185 | setVisibility(INVISIBLE); 186 | } 187 | 188 | public void setTextColor(int color) { 189 | textView.setTextColor(color); 190 | } 191 | 192 | /** 193 | * @param size text size in dp 194 | */ 195 | public void setTextSize(int size) { 196 | textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, size); 197 | } 198 | 199 | private boolean isPDFViewReady() { 200 | return pdfView != null && pdfView.getPageCount() > 0 && !pdfView.documentFitsView(); 201 | } 202 | 203 | @Override 204 | public boolean onTouchEvent(MotionEvent event) { 205 | 206 | if (!isPDFViewReady()) { 207 | return super.onTouchEvent(event); 208 | } 209 | 210 | switch (event.getAction()) { 211 | case MotionEvent.ACTION_DOWN: 212 | case MotionEvent.ACTION_POINTER_DOWN: 213 | pdfView.stopFling(); 214 | handler.removeCallbacks(hidePageScrollerRunnable); 215 | if (pdfView.isSwipeVertical()) { 216 | currentPos = event.getRawY() - getY(); 217 | } else { 218 | currentPos = event.getRawX() - getX(); 219 | } 220 | case MotionEvent.ACTION_MOVE: 221 | if (pdfView.isSwipeVertical()) { 222 | setPosition(event.getRawY() - currentPos + relativeHandlerMiddle); 223 | pdfView.setPositionOffset(relativeHandlerMiddle / (float) getHeight(), false); 224 | } else { 225 | setPosition(event.getRawX() - currentPos + relativeHandlerMiddle); 226 | pdfView.setPositionOffset(relativeHandlerMiddle / (float) getWidth(), false); 227 | } 228 | return true; 229 | case MotionEvent.ACTION_CANCEL: 230 | case MotionEvent.ACTION_UP: 231 | case MotionEvent.ACTION_POINTER_UP: 232 | hideDelayed(); 233 | pdfView.performPageSnap(); 234 | return true; 235 | } 236 | 237 | return super.onTouchEvent(event); 238 | } 239 | } 240 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/scroll/ScrollHandle.java: -------------------------------------------------------------------------------- 1 | package com.github.barteksc.pdfviewer.scroll; 2 | 3 | import com.github.barteksc.pdfviewer.PDFView; 4 | 5 | public interface ScrollHandle { 6 | 7 | /** 8 | * Used to move the handle, called internally by PDFView 9 | * 10 | * @param position current scroll ratio between 0 and 1 11 | */ 12 | void setScroll(float position); 13 | 14 | /** 15 | * Method called by PDFView after setting scroll handle. 16 | * Do not call this method manually. 17 | * For usage sample see {@link DefaultScrollHandle} 18 | * 19 | * @param pdfView PDFView instance 20 | */ 21 | void setupLayout(PDFView pdfView); 22 | 23 | /** 24 | * Method called by PDFView when handle should be removed from layout 25 | * Do not call this method manually. 26 | */ 27 | void destroyLayout(); 28 | 29 | /** 30 | * Set page number displayed on handle 31 | * 32 | * @param pageNum page number 33 | */ 34 | void setPageNum(int pageNum); 35 | 36 | /** 37 | * Get handle visibility 38 | * 39 | * @return true if handle is visible, false otherwise 40 | */ 41 | boolean shown(); 42 | 43 | /** 44 | * Show handle 45 | */ 46 | void show(); 47 | 48 | /** 49 | * Hide handle immediately 50 | */ 51 | void hide(); 52 | 53 | /** 54 | * Hide handle after some time (defined by implementation) 55 | */ 56 | void hideDelayed(); 57 | } 58 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/source/AssetSource.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Bartosz Schiller. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.source; 17 | 18 | 19 | import android.content.Context; 20 | import android.os.ParcelFileDescriptor; 21 | 22 | import com.github.barteksc.pdfviewer.util.FileUtils; 23 | import com.shockwave.pdfium.PdfDocument; 24 | import com.shockwave.pdfium.PdfiumCore; 25 | 26 | import java.io.File; 27 | import java.io.IOException; 28 | 29 | public class AssetSource implements DocumentSource { 30 | 31 | private final String assetName; 32 | 33 | public AssetSource(String assetName) { 34 | this.assetName = assetName; 35 | } 36 | 37 | @Override 38 | public PdfDocument createDocument(Context context, PdfiumCore core, String password) throws IOException { 39 | File f = FileUtils.fileFromAsset(context, assetName); 40 | ParcelFileDescriptor pfd = ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY); 41 | return core.newDocument(pfd, password); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/source/ByteArraySource.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Bartosz Schiller. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.source; 17 | 18 | import android.content.Context; 19 | 20 | import com.shockwave.pdfium.PdfDocument; 21 | import com.shockwave.pdfium.PdfiumCore; 22 | 23 | import java.io.IOException; 24 | 25 | public class ByteArraySource implements DocumentSource { 26 | 27 | private byte[] data; 28 | 29 | public ByteArraySource(byte[] data) { 30 | this.data = data; 31 | } 32 | 33 | @Override 34 | public PdfDocument createDocument(Context context, PdfiumCore core, String password) throws IOException { 35 | return core.newDocument(data, password); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/source/DocumentSource.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Bartosz Schiller. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.source; 17 | 18 | import android.content.Context; 19 | 20 | import com.shockwave.pdfium.PdfDocument; 21 | import com.shockwave.pdfium.PdfiumCore; 22 | 23 | import java.io.IOException; 24 | 25 | public interface DocumentSource { 26 | PdfDocument createDocument(Context context, PdfiumCore core, String password) throws IOException; 27 | } 28 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/source/FileSource.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Bartosz Schiller. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.source; 17 | 18 | import android.content.Context; 19 | import android.os.ParcelFileDescriptor; 20 | 21 | import com.shockwave.pdfium.PdfDocument; 22 | import com.shockwave.pdfium.PdfiumCore; 23 | 24 | import java.io.File; 25 | import java.io.IOException; 26 | 27 | public class FileSource implements DocumentSource { 28 | 29 | private File file; 30 | 31 | public FileSource(File file) { 32 | this.file = file; 33 | } 34 | 35 | @Override 36 | public PdfDocument createDocument(Context context, PdfiumCore core, String password) throws IOException { 37 | ParcelFileDescriptor pfd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); 38 | return core.newDocument(pfd, password); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/source/InputStreamSource.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Bartosz Schiller. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.source; 17 | 18 | import android.content.Context; 19 | 20 | import com.github.barteksc.pdfviewer.util.Util; 21 | import com.shockwave.pdfium.PdfDocument; 22 | import com.shockwave.pdfium.PdfiumCore; 23 | 24 | import java.io.IOException; 25 | import java.io.InputStream; 26 | 27 | public class InputStreamSource implements DocumentSource { 28 | 29 | private InputStream inputStream; 30 | 31 | public InputStreamSource(InputStream inputStream) { 32 | this.inputStream = inputStream; 33 | } 34 | 35 | @Override 36 | public PdfDocument createDocument(Context context, PdfiumCore core, String password) throws IOException { 37 | return core.newDocument(Util.toByteArray(inputStream), password); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/source/UriSource.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Bartosz Schiller. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.source; 17 | 18 | import android.content.Context; 19 | import android.net.Uri; 20 | import android.os.ParcelFileDescriptor; 21 | 22 | import com.shockwave.pdfium.PdfDocument; 23 | import com.shockwave.pdfium.PdfiumCore; 24 | 25 | import java.io.IOException; 26 | 27 | public class UriSource implements DocumentSource { 28 | 29 | private Uri uri; 30 | 31 | public UriSource(Uri uri) { 32 | this.uri = uri; 33 | } 34 | 35 | @Override 36 | public PdfDocument createDocument(Context context, PdfiumCore core, String password) throws IOException { 37 | ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r"); 38 | return core.newDocument(pfd, password); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/ArrayUtils.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2016 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.util; 17 | 18 | import java.util.ArrayList; 19 | import java.util.List; 20 | 21 | public class ArrayUtils { 22 | 23 | private ArrayUtils() { 24 | // Prevents instantiation 25 | } 26 | 27 | /** Transforms (0,1,2,2,3) to (0,1,2,3) */ 28 | public static int[] deleteDuplicatedPages(int[] pages) { 29 | List result = new ArrayList<>(); 30 | int lastInt = -1; 31 | for (Integer currentInt : pages) { 32 | if (lastInt != currentInt) { 33 | result.add(currentInt); 34 | } 35 | lastInt = currentInt; 36 | } 37 | int[] arrayResult = new int[result.size()]; 38 | for (int i = 0; i < result.size(); i++) { 39 | arrayResult[i] = result.get(i); 40 | } 41 | return arrayResult; 42 | } 43 | 44 | /** Transforms (0, 4, 4, 6, 6, 6, 3) into (0, 1, 1, 2, 2, 2, 3) */ 45 | public static int[] calculateIndexesInDuplicateArray(int[] originalUserPages) { 46 | int[] result = new int[originalUserPages.length]; 47 | if (originalUserPages.length == 0) { 48 | return result; 49 | } 50 | 51 | int index = 0; 52 | result[0] = index; 53 | for (int i = 1; i < originalUserPages.length; i++) { 54 | if (originalUserPages[i] != originalUserPages[i - 1]) { 55 | index++; 56 | } 57 | result[i] = index; 58 | } 59 | 60 | return result; 61 | } 62 | 63 | public static String arrayToString(int[] array) { 64 | StringBuilder builder = new StringBuilder("["); 65 | for (int i = 0; i < array.length; i++) { 66 | builder.append(array[i]); 67 | if (i != array.length - 1) { 68 | builder.append(","); 69 | } 70 | } 71 | builder.append("]"); 72 | return builder.toString(); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Constants.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2016 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.util; 17 | 18 | public class Constants { 19 | 20 | public static boolean DEBUG_MODE = false; 21 | 22 | /** Between 0 and 1, the thumbnails quality (default 0.3). Increasing this value may cause performance decrease */ 23 | public static float THUMBNAIL_RATIO = 0.3f; 24 | 25 | /** 26 | * The size of the rendered parts (default 256) 27 | * Tinier : a little bit slower to have the whole page rendered but more reactive. 28 | * Bigger : user will have to wait longer to have the first visual results 29 | */ 30 | public static float PART_SIZE = 256; 31 | 32 | /** Part of document above and below screen that should be preloaded, in dp */ 33 | public static int PRELOAD_OFFSET = 20; 34 | 35 | public static class Cache { 36 | 37 | /** The size of the cache (number of bitmaps kept) */ 38 | public static int CACHE_SIZE = 120; 39 | 40 | public static int THUMBNAILS_CACHE_SIZE = 8; 41 | } 42 | 43 | public static class Pinch { 44 | 45 | public static float MAXIMUM_ZOOM = 10; 46 | 47 | public static float MINIMUM_ZOOM = 1; 48 | 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/FileUtils.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2016 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.util; 17 | 18 | import android.content.Context; 19 | 20 | import java.io.File; 21 | import java.io.FileOutputStream; 22 | import java.io.IOException; 23 | import java.io.InputStream; 24 | import java.io.OutputStream; 25 | 26 | public class FileUtils { 27 | 28 | private FileUtils() { 29 | // Prevents instantiation 30 | } 31 | 32 | public static File fileFromAsset(Context context, String assetName) throws IOException { 33 | File outFile = new File(context.getCacheDir(), assetName + "-pdfview.pdf"); 34 | if (assetName.contains("/")) { 35 | outFile.getParentFile().mkdirs(); 36 | } 37 | copy(context.getAssets().open(assetName), outFile); 38 | return outFile; 39 | } 40 | 41 | public static void copy(InputStream inputStream, File output) throws IOException { 42 | OutputStream outputStream = null; 43 | try { 44 | outputStream = new FileOutputStream(output); 45 | int read = 0; 46 | byte[] bytes = new byte[1024]; 47 | while ((read = inputStream.read(bytes)) != -1) { 48 | outputStream.write(bytes, 0, read); 49 | } 50 | } finally { 51 | try { 52 | if (inputStream != null) { 53 | inputStream.close(); 54 | } 55 | } finally { 56 | if (outputStream != null) { 57 | outputStream.close(); 58 | } 59 | } 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/FitPolicy.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.util; 17 | 18 | public enum FitPolicy { 19 | WIDTH, HEIGHT, BOTH 20 | } 21 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/MathUtils.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2016 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.util; 17 | 18 | public class MathUtils { 19 | 20 | static private final int BIG_ENOUGH_INT = 16 * 1024; 21 | static private final double BIG_ENOUGH_FLOOR = BIG_ENOUGH_INT; 22 | static private final double BIG_ENOUGH_CEIL = 16384.999999999996; 23 | 24 | private MathUtils() { 25 | // Prevents instantiation 26 | } 27 | 28 | /** 29 | * Limits the given number between the other values 30 | * @param number The number to limit. 31 | * @param between The smallest value the number can take. 32 | * @param and The biggest value the number can take. 33 | * @return The limited number. 34 | */ 35 | public static int limit(int number, int between, int and) { 36 | if (number <= between) { 37 | return between; 38 | } 39 | if (number >= and) { 40 | return and; 41 | } 42 | return number; 43 | } 44 | 45 | /** 46 | * Limits the given number between the other values 47 | * @param number The number to limit. 48 | * @param between The smallest value the number can take. 49 | * @param and The biggest value the number can take. 50 | * @return The limited number. 51 | */ 52 | public static float limit(float number, float between, float and) { 53 | if (number <= between) { 54 | return between; 55 | } 56 | if (number >= and) { 57 | return and; 58 | } 59 | return number; 60 | } 61 | 62 | public static float max(float number, float max) { 63 | if (number > max) { 64 | return max; 65 | } 66 | return number; 67 | } 68 | 69 | public static float min(float number, float min) { 70 | if (number < min) { 71 | return min; 72 | } 73 | return number; 74 | } 75 | 76 | public static int max(int number, int max) { 77 | if (number > max) { 78 | return max; 79 | } 80 | return number; 81 | } 82 | 83 | public static int min(int number, int min) { 84 | if (number < min) { 85 | return min; 86 | } 87 | return number; 88 | } 89 | 90 | /** 91 | * Methods from libGDX - https://github.com/libgdx/libgdx 92 | */ 93 | 94 | /** Returns the largest integer less than or equal to the specified float. This method will only properly floor floats from 95 | * -(2^14) to (Float.MAX_VALUE - 2^14). */ 96 | static public int floor(float value) { 97 | return (int) (value + BIG_ENOUGH_FLOOR) - BIG_ENOUGH_INT; 98 | } 99 | 100 | /** Returns the smallest integer greater than or equal to the specified float. This method will only properly ceil floats from 101 | * -(2^14) to (Float.MAX_VALUE - 2^14). */ 102 | static public int ceil(float value) { 103 | return (int) (value + BIG_ENOUGH_CEIL) - BIG_ENOUGH_INT; 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/PageSizeCalculator.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.util; 17 | 18 | import com.shockwave.pdfium.util.Size; 19 | import com.shockwave.pdfium.util.SizeF; 20 | 21 | public class PageSizeCalculator { 22 | 23 | private FitPolicy fitPolicy; 24 | private final Size originalMaxWidthPageSize; 25 | private final Size originalMaxHeightPageSize; 26 | private final Size viewSize; 27 | private SizeF optimalMaxWidthPageSize; 28 | private SizeF optimalMaxHeightPageSize; 29 | private float widthRatio; 30 | private float heightRatio; 31 | private boolean fitEachPage; 32 | 33 | public PageSizeCalculator(FitPolicy fitPolicy, Size originalMaxWidthPageSize, Size originalMaxHeightPageSize, 34 | Size viewSize, boolean fitEachPage) { 35 | this.fitPolicy = fitPolicy; 36 | this.originalMaxWidthPageSize = originalMaxWidthPageSize; 37 | this.originalMaxHeightPageSize = originalMaxHeightPageSize; 38 | this.viewSize = viewSize; 39 | this.fitEachPage = fitEachPage; 40 | calculateMaxPages(); 41 | } 42 | 43 | public SizeF calculate(Size pageSize) { 44 | if (pageSize.getWidth() <= 0 || pageSize.getHeight() <= 0) { 45 | return new SizeF(0, 0); 46 | } 47 | float maxWidth = fitEachPage ? viewSize.getWidth() : pageSize.getWidth() * widthRatio; 48 | float maxHeight = fitEachPage ? viewSize.getHeight() : pageSize.getHeight() * heightRatio; 49 | switch (fitPolicy) { 50 | case HEIGHT: 51 | return fitHeight(pageSize, maxHeight); 52 | case BOTH: 53 | return fitBoth(pageSize, maxWidth, maxHeight); 54 | default: 55 | return fitWidth(pageSize, maxWidth); 56 | } 57 | } 58 | 59 | public SizeF getOptimalMaxWidthPageSize() { 60 | return optimalMaxWidthPageSize; 61 | } 62 | 63 | public SizeF getOptimalMaxHeightPageSize() { 64 | return optimalMaxHeightPageSize; 65 | } 66 | 67 | private void calculateMaxPages() { 68 | switch (fitPolicy) { 69 | case HEIGHT: 70 | optimalMaxHeightPageSize = fitHeight(originalMaxHeightPageSize, viewSize.getHeight()); 71 | heightRatio = optimalMaxHeightPageSize.getHeight() / originalMaxHeightPageSize.getHeight(); 72 | optimalMaxWidthPageSize = fitHeight(originalMaxWidthPageSize, originalMaxWidthPageSize.getHeight() * heightRatio); 73 | break; 74 | case BOTH: 75 | SizeF localOptimalMaxWidth = fitBoth(originalMaxWidthPageSize, viewSize.getWidth(), viewSize.getHeight()); 76 | float localWidthRatio = localOptimalMaxWidth.getWidth() / originalMaxWidthPageSize.getWidth(); 77 | this.optimalMaxHeightPageSize = fitBoth(originalMaxHeightPageSize, originalMaxHeightPageSize.getWidth() * localWidthRatio, 78 | viewSize.getHeight()); 79 | heightRatio = optimalMaxHeightPageSize.getHeight() / originalMaxHeightPageSize.getHeight(); 80 | optimalMaxWidthPageSize = fitBoth(originalMaxWidthPageSize, viewSize.getWidth(), originalMaxWidthPageSize.getHeight() * heightRatio); 81 | widthRatio = optimalMaxWidthPageSize.getWidth() / originalMaxWidthPageSize.getWidth(); 82 | break; 83 | default: 84 | optimalMaxWidthPageSize = fitWidth(originalMaxWidthPageSize, viewSize.getWidth()); 85 | widthRatio = optimalMaxWidthPageSize.getWidth() / originalMaxWidthPageSize.getWidth(); 86 | optimalMaxHeightPageSize = fitWidth(originalMaxHeightPageSize, originalMaxHeightPageSize.getWidth() * widthRatio); 87 | break; 88 | } 89 | } 90 | 91 | private SizeF fitWidth(Size pageSize, float maxWidth) { 92 | float w = pageSize.getWidth(), h = pageSize.getHeight(); 93 | float ratio = w / h; 94 | w = maxWidth; 95 | h = (float) Math.floor(maxWidth / ratio); 96 | return new SizeF(w, h); 97 | } 98 | 99 | private SizeF fitHeight(Size pageSize, float maxHeight) { 100 | float w = pageSize.getWidth(), h = pageSize.getHeight(); 101 | float ratio = h / w; 102 | h = maxHeight; 103 | w = (float) Math.floor(maxHeight / ratio); 104 | return new SizeF(w, h); 105 | } 106 | 107 | private SizeF fitBoth(Size pageSize, float maxWidth, float maxHeight) { 108 | float w = pageSize.getWidth(), h = pageSize.getHeight(); 109 | float ratio = w / h; 110 | w = maxWidth; 111 | h = (float) Math.floor(maxWidth / ratio); 112 | if (h > maxHeight) { 113 | h = maxHeight; 114 | w = (float) Math.floor(maxHeight * ratio); 115 | } 116 | return new SizeF(w, h); 117 | } 118 | 119 | } 120 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/SnapEdge.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.util; 17 | 18 | public enum SnapEdge { 19 | START, CENTER, END, NONE 20 | } 21 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/github/barteksc/pdfviewer/util/Util.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2016 Bartosz Schiller. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.pdfviewer.util; 17 | 18 | import android.content.Context; 19 | import android.util.TypedValue; 20 | 21 | import java.io.ByteArrayOutputStream; 22 | import java.io.IOException; 23 | import java.io.InputStream; 24 | 25 | public class Util { 26 | private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; 27 | 28 | public static int getDP(Context context, int dp) { 29 | return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics()); 30 | } 31 | 32 | public static byte[] toByteArray(InputStream inputStream) throws IOException { 33 | ByteArrayOutputStream os = new ByteArrayOutputStream(); 34 | byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; 35 | int n; 36 | while (-1 != (n = inputStream.read(buffer))) { 37 | os.write(buffer, 0, n); 38 | } 39 | return os.toByteArray(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/res/drawable/default_scroll_handle_bottom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 11 | 12 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/res/drawable/default_scroll_handle_left.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/res/drawable/default_scroll_handle_right.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 11 | 12 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/res/drawable/default_scroll_handle_top.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/res/values/attrs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | 2 | buildscript { 3 | repositories { 4 | google() 5 | mavenCentral() 6 | } 7 | dependencies { 8 | classpath 'com.android.tools.build:gradle:7.2.0' 9 | } 10 | } 11 | 12 | allprojects { 13 | repositories { 14 | google() 15 | mavenCentral() 16 | } 17 | } 18 | 19 | ext { 20 | tools = [ 21 | minSdk : 19, 22 | targetSdk : 31, 23 | compileSdk : 31, 24 | versionName: '3.2.0-beta.3' 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | android.enableJetifier=false 2 | android.useAndroidX=true -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhiew/AndroidPdfViewer/45ef4a2e65a084906af98bcb0b2cae5d16592509/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sun May 22 12:13:43 EDT 2022 2 | distributionBase=GRADLE_USER_HOME 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip 4 | distributionPath=wrapper/dists 5 | zipStorePath=wrapper/dists 6 | zipStoreBase=GRADLE_USER_HOME 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @REM 2 | @REM Copyright 2014 Joan Zapata 3 | @REM 4 | @REM This file is part of Android-pdfview. 5 | @REM 6 | @REM Android-pdfview is free software: you can redistribute it and/or modify 7 | @REM it under the terms of the GNU General Public License as published by 8 | @REM the Free Software Foundation, either version 3 of the License, or 9 | @REM (at your option) any later version. 10 | @REM 11 | @REM Android-pdfview is distributed in the hope that it will be useful, 12 | @REM but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | @REM MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | @REM GNU General Public License for more details. 15 | @REM 16 | @REM You should have received a copy of the GNU General Public License 17 | @REM along with Android-pdfview. If not, see . 18 | @REM 19 | 20 | @if "%DEBUG%" == "" @echo off 21 | @rem ########################################################################## 22 | @rem 23 | @rem Gradle startup script for Windows 24 | @rem 25 | @rem ########################################################################## 26 | 27 | @rem Set local scope for the variables with windows NT shell 28 | if "%OS%"=="Windows_NT" setlocal 29 | 30 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | set DEFAULT_JVM_OPTS= 32 | 33 | set DIRNAME=%~dp0 34 | if "%DIRNAME%" == "" set DIRNAME=. 35 | set APP_BASE_NAME=%~n0 36 | set APP_HOME=%DIRNAME% 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto init 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto init 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :init 68 | @rem Get command-line arguments, handling Windowz variants 69 | 70 | if not "%OS%" == "Windows_NT" goto win9xME_args 71 | if "%@eval[2+2]" == "4" goto 4NT_args 72 | 73 | :win9xME_args 74 | @rem Slurp the command line arguments. 75 | set CMD_LINE_ARGS= 76 | set _SKIP=2 77 | 78 | :win9xME_args_slurp 79 | if "x%~1" == "x" goto execute 80 | 81 | set CMD_LINE_ARGS=%* 82 | goto execute 83 | 84 | :4NT_args 85 | @rem Get arguments from the 4NT Shell from JP Software 86 | set CMD_LINE_ARGS=%$ 87 | 88 | :execute 89 | @rem Setup the command line 90 | 91 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 92 | 93 | @rem Execute Gradle 94 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 95 | 96 | :end 97 | @rem End local scope for the variables with windows NT shell 98 | if "%ERRORLEVEL%"=="0" goto mainEnd 99 | 100 | :fail 101 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 102 | rem the _cmd.exe /c_ return code! 103 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 104 | exit /b 1 105 | 106 | :mainEnd 107 | if "%OS%"=="Windows_NT" endlocal 108 | 109 | :omega 110 | -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | google() 4 | mavenCentral() 5 | } 6 | } 7 | 8 | repositories { 9 | google() 10 | mavenCentral() 11 | } 12 | 13 | apply plugin: 'com.android.application' 14 | 15 | android { 16 | compileSdkVersion rootProject.tools.compileSdk 17 | 18 | defaultConfig { 19 | minSdkVersion rootProject.tools.minSdk 20 | targetSdkVersion rootProject.tools.targetSdk 21 | versionCode 3 22 | versionName "${rootProject.tools.versionName}" 23 | 24 | javaCompileOptions { 25 | annotationProcessorOptions { 26 | arguments = ["androidManifestFile": "$projectDir/src/main/AndroidManifest.xml".toString()] 27 | } 28 | } 29 | } 30 | } 31 | 32 | dependencies { 33 | implementation project(':android-pdf-viewer') 34 | implementation 'androidx.appcompat:appcompat:1.4.1' 35 | implementation 'org.androidannotations:androidannotations-api:4.6.0' 36 | annotationProcessor "org.androidannotations:androidannotations:4.6.0" 37 | } 38 | -------------------------------------------------------------------------------- /sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 10 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /sample/src/main/assets/sample.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhiew/AndroidPdfViewer/45ef4a2e65a084906af98bcb0b2cae5d16592509/sample/src/main/assets/sample.pdf -------------------------------------------------------------------------------- /sample/src/main/java/com/github/barteksc/sample/PDFViewActivity.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2016 Bartosz Schiller 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.github.barteksc.sample; 17 | 18 | import android.content.ActivityNotFoundException; 19 | import android.content.Intent; 20 | import android.content.pm.PackageManager; 21 | import android.database.Cursor; 22 | import android.graphics.Color; 23 | import android.net.Uri; 24 | import android.provider.OpenableColumns; 25 | import androidx.annotation.NonNull; 26 | import androidx.core.app.ActivityCompat; 27 | import androidx.core.content.ContextCompat; 28 | import androidx.appcompat.app.AppCompatActivity; 29 | import android.util.Log; 30 | import android.widget.Toast; 31 | 32 | import com.github.barteksc.pdfviewer.PDFView; 33 | import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener; 34 | import com.github.barteksc.pdfviewer.listener.OnPageChangeListener; 35 | import com.github.barteksc.pdfviewer.listener.OnPageErrorListener; 36 | import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle; 37 | import com.github.barteksc.pdfviewer.util.FitPolicy; 38 | import com.shockwave.pdfium.PdfDocument; 39 | 40 | import org.androidannotations.annotations.AfterViews; 41 | import org.androidannotations.annotations.EActivity; 42 | import org.androidannotations.annotations.NonConfigurationInstance; 43 | import org.androidannotations.annotations.OnActivityResult; 44 | import org.androidannotations.annotations.OptionsItem; 45 | import org.androidannotations.annotations.OptionsMenu; 46 | import org.androidannotations.annotations.ViewById; 47 | 48 | import java.util.List; 49 | 50 | @EActivity(R.layout.activity_main) 51 | @OptionsMenu(R.menu.options) 52 | public class PDFViewActivity extends AppCompatActivity implements OnPageChangeListener, OnLoadCompleteListener, 53 | OnPageErrorListener { 54 | 55 | private static final String TAG = PDFViewActivity.class.getSimpleName(); 56 | 57 | private final static int REQUEST_CODE = 42; 58 | public static final int PERMISSION_CODE = 42042; 59 | 60 | public static final String SAMPLE_FILE = "sample.pdf"; 61 | public static final String READ_EXTERNAL_STORAGE = "android.permission.READ_EXTERNAL_STORAGE"; 62 | 63 | @ViewById 64 | PDFView pdfView; 65 | 66 | @NonConfigurationInstance 67 | Uri uri; 68 | 69 | @NonConfigurationInstance 70 | Integer pageNumber = 0; 71 | 72 | String pdfFileName; 73 | 74 | @OptionsItem(R.id.pickFile) 75 | void pickFile() { 76 | int permissionCheck = ContextCompat.checkSelfPermission(this, 77 | READ_EXTERNAL_STORAGE); 78 | 79 | if (permissionCheck != PackageManager.PERMISSION_GRANTED) { 80 | ActivityCompat.requestPermissions( 81 | this, 82 | new String[]{READ_EXTERNAL_STORAGE}, 83 | PERMISSION_CODE 84 | ); 85 | 86 | return; 87 | } 88 | 89 | launchPicker(); 90 | } 91 | 92 | void launchPicker() { 93 | Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 94 | intent.setType("application/pdf"); 95 | try { 96 | startActivityForResult(intent, REQUEST_CODE); 97 | } catch (ActivityNotFoundException e) { 98 | //alert user that file manager not working 99 | Toast.makeText(this, R.string.toast_pick_file_error, Toast.LENGTH_SHORT).show(); 100 | } 101 | } 102 | 103 | @AfterViews 104 | void afterViews() { 105 | pdfView.setBackgroundColor(Color.LTGRAY); 106 | if (uri != null) { 107 | displayFromUri(uri); 108 | } else { 109 | displayFromAsset(SAMPLE_FILE); 110 | } 111 | setTitle(pdfFileName); 112 | } 113 | 114 | private void displayFromAsset(String assetFileName) { 115 | pdfFileName = assetFileName; 116 | 117 | pdfView.fromAsset(SAMPLE_FILE) 118 | .defaultPage(pageNumber) 119 | .onPageChange(this) 120 | .enableAnnotationRendering(true) 121 | .onLoad(this) 122 | .scrollHandle(new DefaultScrollHandle(this)) 123 | .spacing(10) // in dp 124 | .onPageError(this) 125 | .pageFitPolicy(FitPolicy.BOTH) 126 | .load(); 127 | } 128 | 129 | private void displayFromUri(Uri uri) { 130 | pdfFileName = getFileName(uri); 131 | 132 | pdfView.fromUri(uri) 133 | .defaultPage(pageNumber) 134 | .onPageChange(this) 135 | .enableAnnotationRendering(true) 136 | .onLoad(this) 137 | .scrollHandle(new DefaultScrollHandle(this)) 138 | .spacing(10) // in dp 139 | .onPageError(this) 140 | .load(); 141 | } 142 | 143 | @OnActivityResult(REQUEST_CODE) 144 | public void onResult(int resultCode, Intent intent) { 145 | if (resultCode == RESULT_OK) { 146 | uri = intent.getData(); 147 | displayFromUri(uri); 148 | } 149 | } 150 | 151 | @Override 152 | public void onPageChanged(int page, int pageCount) { 153 | pageNumber = page; 154 | setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount)); 155 | } 156 | 157 | public String getFileName(Uri uri) { 158 | String result = null; 159 | if (uri.getScheme().equals("content")) { 160 | Cursor cursor = getContentResolver().query(uri, null, null, null, null); 161 | try { 162 | if (cursor != null && cursor.moveToFirst()) { 163 | result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)); 164 | } 165 | } finally { 166 | if (cursor != null) { 167 | cursor.close(); 168 | } 169 | } 170 | } 171 | if (result == null) { 172 | result = uri.getLastPathSegment(); 173 | } 174 | return result; 175 | } 176 | 177 | @Override 178 | public void loadComplete(int nbPages) { 179 | PdfDocument.Meta meta = pdfView.getDocumentMeta(); 180 | Log.e(TAG, "title = " + meta.getTitle()); 181 | Log.e(TAG, "author = " + meta.getAuthor()); 182 | Log.e(TAG, "subject = " + meta.getSubject()); 183 | Log.e(TAG, "keywords = " + meta.getKeywords()); 184 | Log.e(TAG, "creator = " + meta.getCreator()); 185 | Log.e(TAG, "producer = " + meta.getProducer()); 186 | Log.e(TAG, "creationDate = " + meta.getCreationDate()); 187 | Log.e(TAG, "modDate = " + meta.getModDate()); 188 | 189 | printBookmarksTree(pdfView.getTableOfContents(), "-"); 190 | 191 | } 192 | 193 | public void printBookmarksTree(List tree, String sep) { 194 | for (PdfDocument.Bookmark b : tree) { 195 | 196 | Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx())); 197 | 198 | if (b.hasChildren()) { 199 | printBookmarksTree(b.getChildren(), sep + "-"); 200 | } 201 | } 202 | } 203 | 204 | /** 205 | * Listener for response to user permission request 206 | * 207 | * @param requestCode Check that permission request code matches 208 | * @param permissions Permissions that requested 209 | * @param grantResults Whether permissions granted 210 | */ 211 | @Override 212 | public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], 213 | @NonNull int[] grantResults) { 214 | if (requestCode == PERMISSION_CODE) { 215 | if (grantResults.length > 0 216 | && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 217 | launchPicker(); 218 | } 219 | } 220 | } 221 | 222 | @Override 223 | public void onPageError(int page, Throwable t) { 224 | Log.e(TAG, "Cannot load page " + page); 225 | } 226 | } 227 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable-hdpi/ic_open_in_browser_grey_700_48dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhiew/AndroidPdfViewer/45ef4a2e65a084906af98bcb0b2cae5d16592509/sample/src/main/res/drawable-hdpi/ic_open_in_browser_grey_700_48dp.png -------------------------------------------------------------------------------- /sample/src/main/res/drawable-mdpi/ic_open_in_browser_grey_700_48dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhiew/AndroidPdfViewer/45ef4a2e65a084906af98bcb0b2cae5d16592509/sample/src/main/res/drawable-mdpi/ic_open_in_browser_grey_700_48dp.png -------------------------------------------------------------------------------- /sample/src/main/res/drawable-xhdpi/ic_open_in_browser_grey_700_48dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhiew/AndroidPdfViewer/45ef4a2e65a084906af98bcb0b2cae5d16592509/sample/src/main/res/drawable-xhdpi/ic_open_in_browser_grey_700_48dp.png -------------------------------------------------------------------------------- /sample/src/main/res/drawable-xxhdpi/ic_open_in_browser_grey_700_48dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhiew/AndroidPdfViewer/45ef4a2e65a084906af98bcb0b2cae5d16592509/sample/src/main/res/drawable-xxhdpi/ic_open_in_browser_grey_700_48dp.png -------------------------------------------------------------------------------- /sample/src/main/res/drawable-xxxhdpi/ic_open_in_browser_grey_700_48dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhiew/AndroidPdfViewer/45ef4a2e65a084906af98bcb0b2cae5d16592509/sample/src/main/res/drawable-xxxhdpi/ic_open_in_browser_grey_700_48dp.png -------------------------------------------------------------------------------- /sample/src/main/res/drawable/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mhiew/AndroidPdfViewer/45ef4a2e65a084906af98bcb0b2cae5d16592509/sample/src/main/res/drawable/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 10 | 11 | -------------------------------------------------------------------------------- /sample/src/main/res/menu/options.xml: -------------------------------------------------------------------------------- 1 | 2 |

4 | 9 | -------------------------------------------------------------------------------- /sample/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | AndroidPdfViewer demo 3 | Pick file 4 | Unable to pick file. Check status of file manager. 5 | -------------------------------------------------------------------------------- /sample/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':android-pdf-viewer' 2 | include ':sample' --------------------------------------------------------------------------------