├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md └── workflows │ ├── android.yml │ ├── auto-author-assign.yml │ └── dependent-issues.yml ├── .gitignore ├── .idea └── codeStyles │ ├── Project.xml │ └── codeStyleConfig.xml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── android-pdf-viewer ├── build.gradle.kts ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── infomaniak │ │ └── lib │ │ └── pdfview │ │ ├── AnimationManager.java │ │ ├── CacheManager.java │ │ ├── DecodingAsyncTask.java │ │ ├── DisplayOptions.kt │ │ ├── DragPinchManager.java │ │ ├── PDFSpacing.kt │ │ ├── PDFView.java │ │ ├── PagesLoader.java │ │ ├── PdfFile.java │ │ ├── RenderingHandler.kt │ │ ├── exception │ │ ├── FileNotFoundException.java │ │ └── PageRenderingException.java │ │ ├── link │ │ ├── DefaultLinkHandler.java │ │ └── LinkHandler.java │ │ ├── listener │ │ ├── Callbacks.java │ │ ├── OnAttachCompleteListener.java │ │ ├── OnDetachCompleteListener.java │ │ ├── OnDrawListener.java │ │ ├── OnErrorListener.java │ │ ├── OnLoadCompleteListener.java │ │ ├── OnLongPressListener.java │ │ ├── OnPageChangeListener.java │ │ ├── OnPageErrorListener.java │ │ ├── OnPageScrollListener.java │ │ ├── OnReadyForPrintingListener.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.kt │ │ ├── FileUtils.java │ │ ├── FitPolicy.java │ │ ├── MathUtils.java │ │ ├── PageSizeCalculator.java │ │ ├── SnapEdge.java │ │ ├── TouchUtils.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 │ ├── layout │ └── default_handle.xml │ └── values │ └── attrs.xml ├── build.gradle.kts ├── gradle.properties ├── gradle ├── libs.versions.toml └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── jitpack.yml ├── sample ├── build.gradle.kts └── src │ └── main │ ├── AndroidManifest.xml │ ├── assets │ └── sample.pdf │ ├── java │ └── com │ │ └── infomaniak │ │ └── lib │ │ └── pdfpreview │ │ └── sample │ │ ├── PDFViewActivity.kt │ │ ├── PDFViewViewModel.kt │ │ └── PasswordDialog.kt │ └── 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 │ ├── dialog_password.xml │ └── handle_background.xml │ ├── menu │ └── options.xml │ └── values │ ├── colors.xml │ ├── strings.xml │ └── styles.xml └── settings.gradle.kts /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @Infomaniak/android -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | *Note: Please write your issue only in english* 11 | 12 | **Description** 13 | A clear and concise description of what the bug is. 14 | 15 | **Steps to reproduce** 16 | Steps to reproduce the behavior: 17 | 1. Go to '...' 18 | 2. Click on '....' 19 | 3. Scroll down to '....' 20 | 4. See error 21 | 22 | **Expected behavior** 23 | A clear and concise description of what you expected to happen. 24 | 25 | **Screenshots** 26 | If applicable, add screenshots to help explain your problem. 27 | 28 | **Smartphone (please complete the following information):** 29 | - Device: [e.g. Samsung S20 Ultra 5G] 30 | - Android version: [e.g. Android 11] 31 | - App version: [e.g. 4.0.1] 32 | 33 | **Additional context** 34 | Add any other context about the problem here. 35 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | *Note: Please write your issue only in english* 11 | 12 | **Is your feature request related to a problem? Please describe.** 13 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 14 | 15 | **Describe the solution you'd like** 16 | A clear and concise description of what you want to happen. 17 | 18 | **Describe alternatives you've considered** 19 | A clear and concise description of any alternative solutions or features you've considered. 20 | 21 | **Additional context** 22 | Add any other context or screenshots about the feature request here. 23 | -------------------------------------------------------------------------------- /.github/workflows/android.yml: -------------------------------------------------------------------------------- 1 | name: Android CI 2 | 3 | on: 4 | pull_request: 5 | branches: [ master ] 6 | types: [ synchronize, opened, reopened, ready_for_review ] 7 | 8 | concurrency: 9 | group: ${{ github.head_ref }} 10 | cancel-in-progress: true 11 | 12 | jobs: 13 | 14 | instrumentation-tests: 15 | if: github.event.pull_request.draft == false 16 | runs-on: [ self-hosted, Android ] 17 | strategy: 18 | matrix: 19 | api-level: [ 34 ] 20 | target: [ google_apis ] 21 | 22 | steps: 23 | - name: Cancel Previous Runs 24 | uses: styfle/cancel-workflow-action@0.12.1 25 | with: 26 | access_token: ${{ github.token }} 27 | 28 | - name: Checkout the code 29 | uses: actions/checkout@v4.1.1 30 | with: 31 | token: ${{ github.token }} 32 | submodules: recursive 33 | 34 | # Setup Gradle and run Build 35 | - name: Grant execute permission for gradlew 36 | run: chmod +x gradlew 37 | - name: Build with Gradle 38 | run: ./gradlew build 39 | 40 | # Run tests 41 | - name: Run Unit tests 42 | run: ./gradlew testDebugUnitTest --stacktrace 43 | -------------------------------------------------------------------------------- /.github/workflows/auto-author-assign.yml: -------------------------------------------------------------------------------- 1 | name: Auto Author Assign 2 | 3 | on: 4 | pull_request_target: 5 | types: [ opened, reopened ] 6 | 7 | permissions: 8 | pull-requests: write 9 | 10 | jobs: 11 | assign-author: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: toshimaru/auto-author-assign@v2.1.0 15 | -------------------------------------------------------------------------------- /.github/workflows/dependent-issues.yml: -------------------------------------------------------------------------------- 1 | name: Dependent Issues 2 | 3 | on: 4 | issues: 5 | types: 6 | - opened 7 | - edited 8 | - closed 9 | - reopened 10 | pull_request_target: 11 | types: 12 | - opened 13 | - edited 14 | - closed 15 | - reopened 16 | # Makes sure we always add status check for PRs. Useful only if 17 | # this action is required to pass before merging. Otherwise, it 18 | # can be removed. 19 | - synchronize 20 | 21 | jobs: 22 | check: 23 | runs-on: ubuntu-latest 24 | steps: 25 | - uses: z0al/dependent-issues@v1.5.2 26 | env: 27 | # (Required) The token to use to make API calls to GitHub. 28 | GITHUB_TOKEN: ${{ github.token }} 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea 5 | .DS_Store 6 | build/ 7 | /captures 8 | .externalNativeBuild 9 | .cxx 10 | local.properties 11 | *.apk 12 | *.aab 13 | -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 140 | -------------------------------------------------------------------------------- /.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 3.2.11 (2025-03-11) 2 | * Fix issues when swiping PDfs in a ViewPager 3 | * Convert build.gradle to kts and use version catalog 4 | * Update libs 5 | 6 | ## 3.2.10 (2024-06-28) 7 | * Add setThumbnailRatio to change the render quality of thumbnails 8 | * Update kotlin version to 2.0.0 9 | * Update gradle to 8.8 10 | * Upgrade AGP to 8.5.0 11 | 12 | ## 3.2.9 (2024-05-14) 13 | * Add loadPagesForPrinting method on PDFView to start generating bitmaps for printing 14 | * Add OnReadyForPrintingListener listener to know when bitmaps are ready 15 | 16 | ## 3.2.8 (2024-01-09) 17 | * Add the possibility to have space above the first page and below the last page of the PDF 18 | * Change the default min, mid, max zoom value 19 | * Change the initial position in the PDF in order to take into account that first space 20 | * Change the length of the document to take into account the first and last spacer if any 21 | 22 | ## 3.2.7 (2024-01-02) 23 | * Change the way we declare the dependency in order to be able to use the exception created in 24 | application that uses this library 25 | 26 | ## 3.2.6 (2024-01-02) 27 | * Add onAttach and onDetach listeners 28 | 29 | ## 3.2.4 (2023-12-26) 30 | * Add a minimum value before triggering the touch priority 31 | * Fix some warnings 32 | 33 | ## 3.2.3 (2023-12-07) 34 | * Add the possibility to customize the page handle 35 | -------------------------------------------------------------------------------- /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/mhiew/AndroidPdfViewer) 3 | switch back to the mainline repo when it gets migrated off JCenter 4 | 5 | # Android PdfViewer 6 | 7 | __AndroidPdfViewer 1.x is available on [AndroidPdfViewerV1](https://github.com/barteksc/AndroidPdfViewerV1) 8 | repo, where can be developed independently. Version 1.x uses different engine for drawing document on canvas, 9 | so if you don't like 2.x version, try 1.x.__ 10 | 11 | Library for displaying PDF documents on Android, with `animations`, `gestures`, `zoom` and `double tap` support. 12 | It is based on [PdfiumAndroid](https://github.com/infomaniak/PdfiumAndroid) for decoding PDF files. Works on API 11 (Android 3.0) and higher. 13 | Licensed under Apache License 2.0. 14 | 15 | Link to the [Changelog](https://github.com/Infomaniak/android-pdfview/blob/master/CHANGELOG.md) 16 | 17 | ## Installation 18 | 19 | Add to _build.gradle_: 20 | 21 | ```groovy 22 | allprojects { 23 | repositories { 24 | ... 25 | mavenCentral() 26 | ... 27 | } 28 | } 29 | ``` 30 | 31 | `implementation 'com.github.Infomaniak:android-pdfview:3.2.11` 32 | 33 | ## ProGuard 34 | If you are using ProGuard, add following rule to proguard config file: 35 | 36 | ```proguard 37 | -keep class com.shockwave.** 38 | ``` 39 | 40 | ## Include PDFView in your layout 41 | 42 | ``` xml 43 | 47 | ``` 48 | 49 | ## Load a PDF file 50 | 51 | All available options with default values: 52 | ``` java 53 | pdfView.fromUri(Uri) 54 | or 55 | pdfView.fromFile(File) 56 | or 57 | pdfView.fromBytes(byte[]) 58 | or 59 | pdfView.fromStream(InputStream) // stream is written to bytearray - native code cannot use Java Streams 60 | or 61 | pdfView.fromSource(DocumentSource) 62 | or 63 | pdfView.fromAsset(String) 64 | .pages(0, 2, 1, 3, 3, 3) // all pages are displayed by default 65 | .enableSwipe(true) // allows to block changing pages using swipe 66 | .swipeHorizontal(false) 67 | .enableDoubletap(true) 68 | .defaultPage(0) // allows to draw something on the current page, usually visible in the middle of the screen 69 | .onDraw(onDrawListener) // allows to draw something on all pages, separately for every page. Called only for visible pages 70 | .onDrawAll(onDrawListener) // called after document is loaded and starts to be rendered 71 | .onLoad(onLoadCompleteListener) 72 | .onPageChange(onPageChangeListener) 73 | .onPageScroll(onPageScrollListener) 74 | .onError(onErrorListener) 75 | .onPageError(onPageErrorListener) // called after document is rendered for the first time 76 | .onRender(onRenderListener) // called on single tap, return true if handled, false to toggle scroll handle visibility 77 | .onTap(onTapListener) 78 | .onLongPress(onLongPressListener) 79 | .enableAnnotationRendering(false) // render annotations (such as comments, colors or forms) 80 | .password(null) 81 | .scrollHandle(null) // improve rendering a little bit on low-res screens 82 | .enableAntialiasing(true) // spacing between pages in dp. To define spacing color, set view background 83 | .pageSeparatorSpacing(PDF_VIEW_HANDLE_TEXT_INDICATOR_SIZE_DP) 84 | .autoSpacing(false) // add dynamic spacing to fit each page on its own on the screen 85 | .linkHandler(DefaultLinkHandler) 86 | .pageFitPolicy(FitPolicy.WIDTH) // mode to fit pages in the view 87 | .fitEachPage(false) // fit each page to the view, else smaller pages are scaled relative to largest page. 88 | .pageSnap(false) // snap pages to screen boundaries 89 | .pageFling(false) // make a fling change only a single page like ViewPager 90 | .nightMode(false) // toggle night mode 91 | .load(); 92 | ``` 93 | 94 | * `pages` is optional, it allows you to filter and order the pages of the PDF as you need 95 | 96 | ## Touch conflicts 97 | 98 | If you're using `PDFView` inside a `ViewPager`, make sure to enable `touchPriority(true)` when initializing PDFView. 99 | This ensures that `PDFView` has touch priority, allowing users to zoom and navigate within the document. However, if the user 100 | swipes and reaches the edge of the `PDFView`, the touch control is returned to the `ViewPager`, enabling seamless page 101 | transitions. 102 | 103 | ## Scroll handle 104 | 105 | Scroll handle is replacement for **ScrollBar** from 1.x branch. 106 | 107 | From version 2.1.0 putting **PDFView** in **RelativeLayout** to use **ScrollHandle** is not required, you can use any layout. 108 | 109 | To use scroll handle just register it using method `Configurator#scrollHandle()`. 110 | This method accepts implementations of **ScrollHandle** interface. 111 | 112 | There is default implementation shipped with AndroidPdfViewer, and you can use it with 113 | `.scrollHandle(new DefaultScrollHandle(this))`. 114 | **DefaultScrollHandle** is placed on the right (when scrolling vertically) or on the bottom (when scrolling horizontally). 115 | By using constructor with second argument (`new DefaultScrollHandle(this, true)`), handle can be placed left or top. 116 | 117 | You can also create custom scroll handles, just implement **ScrollHandle** interface. 118 | 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). 119 | 120 | ## Document sources 121 | Version 2.3.0 introduced _document sources_, which are just providers for PDF documents. 122 | Every provider implements **DocumentSource** interface. 123 | Predefined providers are available in **com.infomaniak.lib.pdfview.source** package and can be used as 124 | samples for creating custom ones. 125 | 126 | Predefined providers can be used with shorthand methods: 127 | ``` 128 | pdfView.fromUri(Uri) 129 | pdfView.fromFile(File) 130 | pdfView.fromBytes(byte[]) 131 | pdfView.fromStream(InputStream) 132 | pdfView.fromAsset(String) 133 | ``` 134 | Custom providers may be used with `pdfView.fromSource(DocumentSource)` method. 135 | 136 | ## Links 137 | Version 3.0.0 introduced support for links in PDF documents. By default, **DefaultLinkHandler** 138 | is used and clicking on link that references page in same document causes jump to destination page 139 | and clicking on link that targets some URI causes opening it in default application. 140 | 141 | You can also create custom link handlers, just implement **LinkHandler** interface and set it using 142 | `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) 143 | source to implement custom behavior. 144 | 145 | ## Pages fit policy 146 | Since version 3.0.0, library supports fitting pages into the screen in 3 modes: 147 | * WIDTH - width of widest page is equal to screen width 148 | * HEIGHT - height of highest page is equal to screen height 149 | * BOTH - based on widest and highest pages, every page is scaled to be fully visible on screen 150 | 151 | Apart from selected policy, every page is scaled to have size relative to other pages. 152 | 153 | Fit policy can be set using `Configurator#pageFitPolicy(FitPolicy)`. Default policy is **WIDTH**. 154 | 155 | ## Additional options 156 | 157 | ### Bitmap quality 158 | By default, generated bitmaps are _compressed_ with `RGB_565` format to reduce memory consumption. 159 | Rendering with `ARGB_8888` can be forced by using `pdfView.useBestQuality(true)` method. 160 | 161 | ### Double tap zooming 162 | There are three zoom levels: min (default 1), mid (default 1.75) and max (default 3). On first double tap, 163 | view is zoomed to mid level, on second to max level, and on third returns to min level. 164 | If you are between mid and max levels, double tapping causes zooming to max and so on. 165 | 166 | Zoom levels can be changed using following methods: 167 | 168 | ``` java 169 | void setMinZoom(float zoom); 170 | void setMidZoom(float zoom); 171 | void setMaxZoom(float zoom); 172 | ``` 173 | 174 | ## Possible questions 175 | ### Why resulting apk is so big? 176 | Android PdfViewer depends on PdfiumAndroid, which is set of native libraries (almost 16 MB) for many architectures. 177 | Apk must contain all this libraries to run on every device available on market. 178 | Fortunately, Google Play allows us to upload multiple apks, e.g. one per every architecture. 179 | There is good article on automatically splitting your application into multiple apks, 180 | available [here](http://ph0b.com/android-studio-gradle-and-ndk-integration/). 181 | Most important section is _Improving multiple APKs creation and versionCode handling with APK Splits_, but whole article is worth reading. 182 | You only need to do this in your application, no need for forking PdfiumAndroid or so. 183 | 184 | ### Why I cannot open PDF from URL? 185 | Downloading files is long running process which must be aware of Activity lifecycle, must support some configuration, 186 | data cleanup and caching, so creating such module will probably end up as new library. 187 | 188 | ### How can I show last opened page after configuration change? 189 | You have to store current page number and then set it with `pdfView.defaultPage(page)`, refer to sample app 190 | 191 | ### How can I fit document to screen width (eg. on orientation change)? 192 | Use `FitPolicy.WIDTH` policy or add following snippet when you want to fit desired page in document with different page sizes: 193 | ``` java 194 | Configurator.onRender(new OnRenderListener() { 195 | @Override 196 | public void onInitiallyRendered(int pages, float pageWidth, float pageHeight) { 197 | pdfView.fitToWidth(pageIndex); 198 | } 199 | }); 200 | ``` 201 | 202 | ### How can I scroll through single pages like a ViewPager? 203 | You can use a combination of the following settings to get scroll and fling behaviour similar to a ViewPager: 204 | ``` java 205 | .swipeHorizontal(true) 206 | .pageSnap(true) 207 | .autoSpacing(true) 208 | .pageFling(true) 209 | ``` 210 | 211 | ## One more thing 212 | If you have any suggestions on making this lib better, write me, create issue or write some code and send pull request. 213 | 214 | ## License 215 | 216 | Created with the help of android-pdfview by [Joan Zapata](http://joanzapata.com/) 217 | ``` 218 | Copyright 2017 Bartosz Schiller 219 | 220 | Licensed under the Apache License, Version 2.0 (the "License"); 221 | you may not use this file except in compliance with the License. 222 | You may obtain a copy of the License at 223 | 224 | http://www.apache.org/licenses/LICENSE-2.0 225 | 226 | Unless required by applicable law or agreed to in writing, software 227 | distributed under the License is distributed on an "AS IS" BASIS, 228 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 229 | See the License for the specific language governing permissions and 230 | limitations under the License. 231 | ``` 232 | -------------------------------------------------------------------------------- /android-pdf-viewer/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | id("com.android.library") 3 | id("maven-publish") 4 | alias(libs.plugins.kotlinAndroid) 5 | alias(libs.plugins.kapt) 6 | } 7 | 8 | val libMinSdk: Int by rootProject.extra 9 | val libCompileSdk: Int by rootProject.extra 10 | val libTargetSdk: Int by rootProject.extra 11 | val javaVersion: JavaVersion by rootProject.extra 12 | val libVersionName: String by rootProject.extra 13 | 14 | android { 15 | namespace = "com.infomaniak.lib.pdfview" 16 | 17 | defaultConfig { 18 | minSdk = libMinSdk 19 | compileSdk = libCompileSdk 20 | targetSdk = libTargetSdk 21 | } 22 | 23 | publishing { 24 | singleVariant("release") { 25 | withSourcesJar() 26 | } 27 | } 28 | 29 | compileOptions { 30 | sourceCompatibility = javaVersion 31 | targetCompatibility = javaVersion 32 | } 33 | 34 | kotlinOptions { 35 | jvmTarget = javaVersion.toString() 36 | } 37 | } 38 | 39 | dependencies { 40 | implementation(libs.core.ktx) 41 | implementation(libs.recyclerview) 42 | implementation(libs.viewpager2) 43 | 44 | api(libs.pdfium) 45 | } 46 | 47 | afterEvaluate { 48 | publishing { 49 | publications { 50 | create("release") { 51 | from(components.findByName("release")!!) 52 | groupId = "com.github.Infomaniak" 53 | artifactId = "android-pdfview" 54 | version = libVersionName 55 | } 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /android-pdf-viewer/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/mac/android-sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | 19 | -keep class com.shockwave.** -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview; 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 | * This manager is used by the PDFView to launch animations. 29 | * It uses the ValueAnimator appeared in API 11 to start 30 | * an animation, and call moveTo() on the PDFView as a result 31 | * of each animation update. 32 | */ 33 | class AnimationManager { 34 | 35 | private PDFView pdfView; 36 | 37 | private ValueAnimator animation; 38 | 39 | private OverScroller scroller; 40 | 41 | private boolean flinging = false; 42 | 43 | private boolean pageFlinging = false; 44 | 45 | public AnimationManager(PDFView pdfView) { 46 | this.pdfView = pdfView; 47 | scroller = new OverScroller(pdfView.getContext()); 48 | } 49 | 50 | public void startXAnimation(float xFrom, float xTo) { 51 | stopAll(); 52 | animation = ValueAnimator.ofFloat(xFrom, xTo); 53 | XAnimation xAnimation = new XAnimation(); 54 | animation.setInterpolator(new DecelerateInterpolator()); 55 | animation.addUpdateListener(xAnimation); 56 | animation.addListener(xAnimation); 57 | animation.setDuration(400); 58 | animation.start(); 59 | } 60 | 61 | public void startYAnimation(float yFrom, float yTo) { 62 | stopAll(); 63 | animation = ValueAnimator.ofFloat(yFrom, yTo); 64 | YAnimation yAnimation = new YAnimation(); 65 | animation.setInterpolator(new DecelerateInterpolator()); 66 | animation.addUpdateListener(yAnimation); 67 | animation.addListener(yAnimation); 68 | animation.setDuration(400); 69 | animation.start(); 70 | } 71 | 72 | public void startZoomAnimation(float centerX, float centerY, float zoomFrom, float zoomTo) { 73 | stopAll(); 74 | animation = ValueAnimator.ofFloat(zoomFrom, zoomTo); 75 | animation.setInterpolator(new DecelerateInterpolator()); 76 | ZoomAnimation zoomAnim = new ZoomAnimation(centerX, centerY); 77 | animation.addUpdateListener(zoomAnim); 78 | animation.addListener(zoomAnim); 79 | animation.setDuration(400); 80 | animation.start(); 81 | } 82 | 83 | public void startFlingAnimation( 84 | int startX, 85 | int startY, 86 | int velocityX, 87 | int velocityY, 88 | int minX, 89 | int maxX, 90 | int minY, 91 | int maxY 92 | ) { 93 | stopAll(); 94 | flinging = true; 95 | scroller.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY); 96 | } 97 | 98 | public void startPageFlingAnimation(float targetOffset) { 99 | if (pdfView.isSwipeVertical()) { 100 | startYAnimation(pdfView.getCurrentYOffset(), targetOffset); 101 | } else { 102 | startXAnimation(pdfView.getCurrentXOffset(), targetOffset); 103 | } 104 | pageFlinging = true; 105 | } 106 | 107 | void computeFling() { 108 | if (scroller.computeScrollOffset()) { 109 | if (shouldHandleScrollerValue()) { 110 | pdfView.moveTo(scroller.getCurrX(), scroller.getCurrY()); 111 | pdfView.loadPageByOffset(); 112 | } 113 | } else if (flinging) { // fling finished 114 | flinging = false; 115 | pdfView.loadPages(); 116 | hideHandle(); 117 | pdfView.performPageSnap(); 118 | } 119 | } 120 | 121 | private boolean shouldHandleScrollerValue() { 122 | // Sometimes, when we reach the end of the PDF and we perform a scroll, the scroller sometimes return 0 when we 123 | // release the touch. 124 | if (pdfView.isSwipeVertical()) { 125 | return scroller.getCurrY() != 0 && scroller.getCurrY() != pdfView.getDocumentLength(); 126 | } else { 127 | return scroller.getCurrX() != 0 && scroller.getCurrX() != pdfView.getDocumentLength(); 128 | } 129 | } 130 | 131 | public void stopAll() { 132 | if (animation != null) { 133 | animation.cancel(); 134 | animation = null; 135 | } 136 | stopFling(); 137 | } 138 | 139 | public void stopFling() { 140 | flinging = false; 141 | scroller.forceFinished(true); 142 | } 143 | 144 | public boolean isFlinging() { 145 | return flinging || pageFlinging; 146 | } 147 | 148 | private void hideHandle() { 149 | if (pdfView.getScrollHandle() != null) { 150 | pdfView.getScrollHandle().hideDelayed(); 151 | } 152 | } 153 | 154 | class XAnimation extends AnimatorListenerAdapter implements AnimatorUpdateListener { 155 | 156 | @Override 157 | public void onAnimationUpdate(ValueAnimator animation) { 158 | float offset = (Float) animation.getAnimatedValue(); 159 | pdfView.moveTo(offset, pdfView.getCurrentYOffset()); 160 | pdfView.loadPageByOffset(); 161 | } 162 | 163 | @Override 164 | public void onAnimationCancel(Animator animation) { 165 | pdfView.loadPages(); 166 | pageFlinging = false; 167 | hideHandle(); 168 | } 169 | 170 | @Override 171 | public void onAnimationEnd(Animator animation) { 172 | pdfView.loadPages(); 173 | pageFlinging = false; 174 | hideHandle(); 175 | } 176 | } 177 | 178 | class YAnimation extends AnimatorListenerAdapter implements AnimatorUpdateListener { 179 | 180 | @Override 181 | public void onAnimationUpdate(ValueAnimator animation) { 182 | float offset = (Float) animation.getAnimatedValue(); 183 | pdfView.moveTo(pdfView.getCurrentXOffset(), offset); 184 | pdfView.loadPageByOffset(); 185 | } 186 | 187 | @Override 188 | public void onAnimationCancel(Animator animation) { 189 | pdfView.loadPages(); 190 | pageFlinging = false; 191 | hideHandle(); 192 | } 193 | 194 | @Override 195 | public void onAnimationEnd(Animator animation) { 196 | pdfView.loadPages(); 197 | pageFlinging = false; 198 | hideHandle(); 199 | } 200 | } 201 | 202 | class ZoomAnimation implements AnimatorUpdateListener, AnimatorListener { 203 | 204 | private final float centerX; 205 | private final float centerY; 206 | 207 | public ZoomAnimation(float centerX, float centerY) { 208 | this.centerX = centerX; 209 | this.centerY = centerY; 210 | } 211 | 212 | @Override 213 | public void onAnimationUpdate(ValueAnimator animation) { 214 | float zoom = (Float) animation.getAnimatedValue(); 215 | pdfView.zoomCenteredTo(zoom, new PointF(centerX, centerY)); 216 | } 217 | 218 | @Override 219 | public void onAnimationCancel(Animator animation) { 220 | pdfView.loadPages(); 221 | hideHandle(); 222 | } 223 | 224 | @Override 225 | public void onAnimationEnd(Animator animation) { 226 | pdfView.loadPages(); 227 | pdfView.performPageSnap(); 228 | hideHandle(); 229 | } 230 | 231 | @Override 232 | public void onAnimationRepeat(Animator animation) { 233 | } 234 | 235 | @Override 236 | public void onAnimationStart(Animator animation) { 237 | } 238 | } 239 | } 240 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/CacheManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Infomaniak android-pdf-viewer 3 | * Copyright (C) 2024 Infomaniak Network SA 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.infomaniak.lib.pdfview; 19 | 20 | import static com.infomaniak.lib.pdfview.util.Constants.Cache.CACHE_SIZE; 21 | import static com.infomaniak.lib.pdfview.util.Constants.Cache.THUMBNAILS_CACHE_SIZE; 22 | 23 | import android.graphics.RectF; 24 | 25 | import androidx.annotation.Nullable; 26 | 27 | import com.infomaniak.lib.pdfview.model.PagePart; 28 | 29 | import java.util.ArrayList; 30 | import java.util.Collection; 31 | import java.util.Comparator; 32 | import java.util.List; 33 | import java.util.PriorityQueue; 34 | 35 | class CacheManager { 36 | 37 | private final PriorityQueue passiveCache; 38 | 39 | private final PriorityQueue activeCache; 40 | 41 | private final List thumbnails; 42 | 43 | private final Object passiveActiveLock = new Object(); 44 | 45 | private final PagePartComparator orderComparator = new PagePartComparator(); 46 | 47 | public CacheManager() { 48 | activeCache = new PriorityQueue<>(CACHE_SIZE, orderComparator); 49 | passiveCache = new PriorityQueue<>(CACHE_SIZE, orderComparator); 50 | thumbnails = new ArrayList<>(); 51 | } 52 | 53 | @Nullable 54 | private static PagePart find(PriorityQueue vector, PagePart fakePart) { 55 | for (PagePart part : vector) { 56 | if (part.equals(fakePart)) { 57 | return part; 58 | } 59 | } 60 | return null; 61 | } 62 | 63 | public void cachePart(PagePart part) { 64 | synchronized (passiveActiveLock) { 65 | // If cache too big, remove and recycle 66 | makeAFreeSpace(); 67 | 68 | // Then add part 69 | activeCache.offer(part); 70 | } 71 | } 72 | 73 | public void makeANewSet() { 74 | synchronized (passiveActiveLock) { 75 | passiveCache.addAll(activeCache); 76 | activeCache.clear(); 77 | } 78 | } 79 | 80 | private void makeAFreeSpace() { 81 | synchronized (passiveActiveLock) { 82 | while ((activeCache.size() + passiveCache.size()) >= CACHE_SIZE && !passiveCache.isEmpty()) { 83 | recycleBitmapsFromPart(passiveCache); 84 | } 85 | 86 | while ((activeCache.size() + passiveCache.size()) >= CACHE_SIZE && !activeCache.isEmpty()) { 87 | recycleBitmapsFromPart(activeCache); 88 | } 89 | } 90 | } 91 | 92 | public void cacheThumbnail(PagePart part, boolean isForPrinting) { 93 | synchronized (thumbnails) { 94 | // If cache too big, remove and recycle. But if we're printing, we don't want any limit. 95 | while (!isForPrinting && thumbnails.size() >= THUMBNAILS_CACHE_SIZE) { 96 | thumbnails.remove(0).getRenderedBitmap().recycle(); 97 | } 98 | 99 | // Then add thumbnail 100 | addWithoutDuplicates(thumbnails, part); 101 | } 102 | } 103 | 104 | public boolean upPartIfContained(int page, RectF pageRelativeBounds, int toOrder) { 105 | PagePart fakePart = new PagePart(page, null, pageRelativeBounds, false, 0); 106 | 107 | PagePart found; 108 | synchronized (passiveActiveLock) { 109 | if ((found = find(passiveCache, fakePart)) != null) { 110 | passiveCache.remove(found); 111 | found.setCacheOrder(toOrder); 112 | activeCache.offer(found); 113 | return true; 114 | } 115 | 116 | return find(activeCache, fakePart) != null; 117 | } 118 | } 119 | 120 | /** 121 | * Return true if already contains the described PagePart 122 | */ 123 | public boolean containsThumbnail(int page, RectF pageRelativeBounds) { 124 | PagePart fakePart = new PagePart(page, null, pageRelativeBounds, true, 0); 125 | synchronized (thumbnails) { 126 | for (PagePart part : thumbnails) { 127 | if (part.equals(fakePart)) { 128 | return true; 129 | } 130 | } 131 | return false; 132 | } 133 | } 134 | 135 | private void recycleBitmapsFromPart(PriorityQueue cache) { 136 | PagePart part = cache.poll(); 137 | if (part != null) { 138 | part.getRenderedBitmap().recycle(); 139 | } 140 | } 141 | 142 | /** 143 | * Add part if it doesn't exist, recycle bitmap otherwise 144 | */ 145 | private void addWithoutDuplicates(Collection collection, PagePart newPart) { 146 | for (PagePart part : collection) { 147 | if (part.equals(newPart)) { 148 | newPart.getRenderedBitmap().recycle(); 149 | return; 150 | } 151 | } 152 | collection.add(newPart); 153 | } 154 | 155 | public List getPageParts() { 156 | synchronized (passiveActiveLock) { 157 | List parts = new ArrayList<>(passiveCache); 158 | parts.addAll(activeCache); 159 | return parts; 160 | } 161 | } 162 | 163 | public List getThumbnails() { 164 | synchronized (thumbnails) { 165 | return thumbnails; 166 | } 167 | } 168 | 169 | public void recycle() { 170 | synchronized (passiveActiveLock) { 171 | for (PagePart part : passiveCache) { 172 | part.getRenderedBitmap().recycle(); 173 | } 174 | passiveCache.clear(); 175 | for (PagePart part : activeCache) { 176 | part.getRenderedBitmap().recycle(); 177 | } 178 | activeCache.clear(); 179 | } 180 | synchronized (thumbnails) { 181 | for (PagePart part : thumbnails) { 182 | part.getRenderedBitmap().recycle(); 183 | } 184 | thumbnails.clear(); 185 | } 186 | } 187 | 188 | class PagePartComparator implements Comparator { 189 | @Override 190 | public int compare(PagePart part1, PagePart part2) { 191 | if (part1.getCacheOrder() == part2.getCacheOrder()) { 192 | return 0; 193 | } 194 | return part1.getCacheOrder() > part2.getCacheOrder() ? 1 : -1; 195 | } 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview; 17 | 18 | import android.os.AsyncTask; 19 | 20 | import com.infomaniak.lib.pdfview.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 | PDFSpacing pdfSpacing = new PDFSpacing( 55 | pdfView.getPageSeparatorSpacing(), 56 | pdfView.getStartSpacing(), 57 | pdfView.getEndSpacing(), 58 | pdfView.isAutoSpacingEnabled() 59 | ); 60 | DisplayOptions displayOptions = new DisplayOptions( 61 | pdfView.isSwipeVertical(), 62 | pdfSpacing, 63 | pdfView.isFitEachPage(), 64 | getViewSize(pdfView), 65 | pdfView.getPageFitPolicy()); 66 | pdfFile = new PdfFile( 67 | pdfiumCore, 68 | pdfDocument, 69 | userPages, 70 | displayOptions); 71 | return null; 72 | } else { 73 | return new NullPointerException("pdfView == null"); 74 | } 75 | 76 | } catch (Throwable t) { 77 | return t; 78 | } 79 | } 80 | 81 | private Size getViewSize(PDFView pdfView) { 82 | return new Size(pdfView.getWidth(), pdfView.getHeight()); 83 | } 84 | 85 | @Override 86 | protected void onPostExecute(Throwable t) { 87 | PDFView pdfView = pdfViewReference.get(); 88 | if (pdfView != null) { 89 | if (t != null) { 90 | pdfView.loadError(t); 91 | return; 92 | } 93 | if (!cancelled) { 94 | pdfView.loadComplete(pdfFile); 95 | } 96 | } 97 | } 98 | 99 | @Override 100 | protected void onCancelled() { 101 | cancelled = true; 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/DisplayOptions.kt: -------------------------------------------------------------------------------- 1 | package com.infomaniak.lib.pdfview 2 | 3 | import com.infomaniak.lib.pdfview.util.FitPolicy 4 | import com.shockwave.pdfium.util.Size 5 | 6 | data class DisplayOptions( 7 | /** True if scrolling is vertical, else it's horizontal */ 8 | val isVertical: Boolean, 9 | val pdfSpacing: PDFSpacing, 10 | /** 11 | * True if every page should fit separately according to the FitPolicy, 12 | * else the largest page fits and other pages scale relatively 13 | */ 14 | val fitEachPage: Boolean, 15 | val viewSize: Size, 16 | val pageFitPolicy: FitPolicy 17 | ) 18 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/PDFSpacing.kt: -------------------------------------------------------------------------------- 1 | package com.infomaniak.lib.pdfview 2 | 3 | data class PDFSpacing( 4 | /** Fixed spacing between pages in pixels */ 5 | val pageSeparatorSpacing: Int = 0, 6 | /** Fixed spacing between pages in pixels */ 7 | val startSpacing: Int = 0, 8 | /** Fixed spacing between pages in pixels */ 9 | val endSpacing: Int = 0, 10 | /** Calculate spacing automatically so each page fits on it's own in the center of the view */ 11 | val autoSpacing: Boolean = false 12 | ) 13 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/PagesLoader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Infomaniak android-pdf-viewer 3 | * Copyright (C) 2024 Infomaniak Network SA 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.infomaniak.lib.pdfview; 19 | 20 | import static com.infomaniak.lib.pdfview.util.Constants.Cache.CACHE_SIZE; 21 | import static com.infomaniak.lib.pdfview.util.Constants.PRELOAD_OFFSET; 22 | 23 | import android.graphics.RectF; 24 | 25 | import com.infomaniak.lib.pdfview.RenderingHandler.RenderingSize; 26 | import com.infomaniak.lib.pdfview.util.Constants; 27 | import com.infomaniak.lib.pdfview.util.MathUtils; 28 | import com.infomaniak.lib.pdfview.util.Util; 29 | import com.shockwave.pdfium.util.SizeF; 30 | 31 | import java.util.LinkedList; 32 | import java.util.List; 33 | 34 | class PagesLoader { 35 | 36 | private PDFView pdfView; 37 | private int cacheOrder; 38 | private float xOffset; 39 | private float yOffset; 40 | private float pageRelativePartWidth; 41 | private float pageRelativePartHeight; 42 | private float partRenderWidth; 43 | private float partRenderHeight; 44 | private final RectF thumbnailRect = new RectF(0, 0, 1, 1); 45 | private final int preloadOffset; 46 | 47 | private class Holder { 48 | int row; 49 | int col; 50 | 51 | @Override 52 | public String toString() { 53 | return "Holder{row=" + row + ", col=" + col + '}'; 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{rows=" + rows + ", cols=" + cols + '}'; 88 | } 89 | } 90 | 91 | PagesLoader(PDFView pdfView) { 92 | this.pdfView = pdfView; 93 | this.preloadOffset = Util.getDP(pdfView.getContext(), PRELOAD_OFFSET); 94 | } 95 | 96 | void loadPagesForPrinting(int pagesCount) { 97 | loadAllForPrinting(pagesCount); 98 | } 99 | 100 | private void getPageColsRows(GridSize grid, int pageIndex) { 101 | SizeF size = pdfView.pdfFile.getPageSize(pageIndex); 102 | float ratioX = 1f / size.getWidth(); 103 | float ratioY = 1f / size.getHeight(); 104 | final float partHeight = (Constants.PART_SIZE * ratioY) / pdfView.getZoom(); 105 | final float partWidth = (Constants.PART_SIZE * ratioX) / pdfView.getZoom(); 106 | grid.rows = MathUtils.ceil(1f / partHeight); 107 | grid.cols = MathUtils.ceil(1f / partWidth); 108 | } 109 | 110 | private void calculatePartSize(GridSize grid) { 111 | pageRelativePartWidth = 1f / (float) grid.cols; 112 | pageRelativePartHeight = 1f / (float) grid.rows; 113 | partRenderWidth = Constants.PART_SIZE / pageRelativePartWidth; 114 | partRenderHeight = Constants.PART_SIZE / pageRelativePartHeight; 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 | // Get the page offset int the whole file 197 | // --------------------------------------- 198 | // | | | | 199 | // |<--offset-->| (page) |<--offset-->| 200 | // | | | | 201 | // | | | | 202 | // --------------------------------------- 203 | float secondaryOffset = pdfView.pdfFile.getSecondaryPageOffset(page, pdfView.getZoom()); 204 | 205 | // calculate the row,col of the point in the leftTop and rightBottom 206 | if (pdfView.isSwipeVertical()) { 207 | range.leftTop.row = MathUtils.floor( 208 | Math.abs(pageFirstYOffset - pdfView.pdfFile.getPageOffset(range.page, pdfView.getZoom())) / rowHeight 209 | ); 210 | range.leftTop.col = MathUtils.floor(MathUtils.min(pageFirstXOffset - secondaryOffset, 0) / colWidth); 211 | 212 | range.rightBottom.row = MathUtils.ceil( 213 | Math.abs(pageLastYOffset - pdfView.pdfFile.getPageOffset(range.page, pdfView.getZoom())) / rowHeight 214 | ); 215 | range.rightBottom.col = MathUtils.floor( 216 | MathUtils.min(pageLastXOffset - secondaryOffset, 0) / colWidth 217 | ); 218 | } else { 219 | range.leftTop.col = MathUtils.floor( 220 | Math.abs(pageFirstXOffset - pdfView.pdfFile.getPageOffset(range.page, pdfView.getZoom())) / colWidth 221 | ); 222 | range.leftTop.row = MathUtils.floor( 223 | MathUtils.min(pageFirstYOffset - secondaryOffset, 0) / rowHeight 224 | ); 225 | 226 | range.rightBottom.col = MathUtils.floor( 227 | Math.abs(pageLastXOffset - pdfView.pdfFile.getPageOffset(range.page, pdfView.getZoom())) / colWidth 228 | ); 229 | range.rightBottom.row = MathUtils.floor( 230 | MathUtils.min(pageLastYOffset - secondaryOffset, 0) / rowHeight 231 | ); 232 | } 233 | 234 | renderRanges.add(range); 235 | } 236 | 237 | return renderRanges; 238 | } 239 | 240 | private void loadAllForPrinting(int pagesCount) { 241 | for (int i = 0; i < pagesCount; i++) { 242 | loadThumbnail(i, true); 243 | } 244 | } 245 | 246 | private void loadVisible() { 247 | int parts = 0; 248 | float scaledPreloadOffset = preloadOffset; 249 | float firstXOffset = -xOffset + scaledPreloadOffset; 250 | float lastXOffset = -xOffset - pdfView.getWidth() - scaledPreloadOffset; 251 | float firstYOffset = -yOffset + scaledPreloadOffset; 252 | float lastYOffset = -yOffset - pdfView.getHeight() - scaledPreloadOffset; 253 | 254 | List rangeList = getRenderRangeList(firstXOffset, firstYOffset, lastXOffset, lastYOffset); 255 | 256 | for (RenderRange range : rangeList) { 257 | loadThumbnail(range.page, false); 258 | } 259 | 260 | for (RenderRange range : rangeList) { 261 | calculatePartSize(range.gridSize); 262 | parts += loadPage( 263 | range.page, 264 | range.leftTop.row, 265 | range.rightBottom.row, 266 | range.leftTop.col, 267 | range.rightBottom.col, 268 | CACHE_SIZE - parts 269 | ); 270 | if (parts >= CACHE_SIZE) { 271 | break; 272 | } 273 | } 274 | } 275 | 276 | private int loadPage(int page, int firstRow, int lastRow, int firstCol, int lastCol, int nbOfPartsLoadable) { 277 | int loaded = 0; 278 | for (int row = firstRow; row <= lastRow; row++) { 279 | for (int col = firstCol; col <= lastCol; col++) { 280 | if (loadCell(page, row, col, pageRelativePartWidth, pageRelativePartHeight)) { 281 | loaded++; 282 | } 283 | if (loaded >= nbOfPartsLoadable) { 284 | return loaded; 285 | } 286 | } 287 | } 288 | return loaded; 289 | } 290 | 291 | private boolean loadCell(int page, int row, int col, float pageRelativePartWidth, float pageRelativePartHeight) { 292 | 293 | float relX = pageRelativePartWidth * col; 294 | float relY = pageRelativePartHeight * row; 295 | float relWidth = pageRelativePartWidth; 296 | float relHeight = pageRelativePartHeight; 297 | 298 | float renderWidth = partRenderWidth; 299 | float renderHeight = partRenderHeight; 300 | if (relX + relWidth > 1) { 301 | relWidth = 1 - relX; 302 | } 303 | if (relY + relHeight > 1) { 304 | relHeight = 1 - relY; 305 | } 306 | renderWidth *= relWidth; 307 | renderHeight *= relHeight; 308 | RectF pageRelativeBounds = new RectF(relX, relY, relX + relWidth, relY + relHeight); 309 | 310 | if (renderWidth > 0 && renderHeight > 0) { 311 | if (!pdfView.cacheManager.upPartIfContained(page, pageRelativeBounds, cacheOrder)) { 312 | pdfView.renderingHandler.addRenderingTask( 313 | page, 314 | new RenderingSize(renderWidth, renderHeight, pageRelativeBounds), 315 | false, 316 | cacheOrder, 317 | pdfView.isBestQuality(), 318 | pdfView.isAnnotationRendering(), 319 | false 320 | ); 321 | } 322 | 323 | cacheOrder++; 324 | return true; 325 | } 326 | return false; 327 | } 328 | 329 | private void loadThumbnail(int page, boolean isForPrinting) { 330 | SizeF pageSize = pdfView.pdfFile.getPageSize(page); 331 | float thumbnailRatio = isForPrinting ? Constants.THUMBNAIL_RATIO_PRINTING : pdfView.getThumbnailRatio(); 332 | float thumbnailWidth = pageSize.getWidth() * thumbnailRatio; 333 | float thumbnailHeight = pageSize.getHeight() * thumbnailRatio; 334 | if (!pdfView.cacheManager.containsThumbnail(page, thumbnailRect)) { 335 | pdfView.renderingHandler.addRenderingTask( 336 | page, 337 | new RenderingSize(thumbnailWidth, thumbnailHeight, thumbnailRect), 338 | true, 339 | 0, 340 | pdfView.isBestQuality(), 341 | pdfView.isAnnotationRendering(), 342 | isForPrinting 343 | ); 344 | } else if (page == pdfView.getPageCount() - 1 && isForPrinting) { 345 | pdfView.callbacks.callsOnReadyForPrinting(pdfView.getPagesAsBitmaps()); 346 | } 347 | } 348 | 349 | void loadPages() { 350 | cacheOrder = 1; 351 | xOffset = -MathUtils.max(pdfView.getCurrentXOffset(), 0); 352 | yOffset = -MathUtils.max(pdfView.getCurrentYOffset(), 0); 353 | 354 | loadVisible(); 355 | } 356 | } 357 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview; 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.infomaniak.lib.pdfview.exception.PageRenderingException; 24 | import com.infomaniak.lib.pdfview.util.PageSizeCalculator; 25 | import com.shockwave.pdfium.PdfDocument; 26 | import com.shockwave.pdfium.PdfiumCore; 27 | import com.shockwave.pdfium.util.Size; 28 | import com.shockwave.pdfium.util.SizeF; 29 | 30 | import java.util.ArrayList; 31 | import java.util.List; 32 | 33 | class PdfFile { 34 | 35 | private static final Object lock = new Object(); 36 | 37 | private PdfDocument pdfDocument; 38 | private PdfiumCore pdfiumCore; 39 | private int pagesCount = 0; 40 | /** 41 | * Original page sizes 42 | */ 43 | private List originalPageSizes = new ArrayList<>(); 44 | /** 45 | * Scaled page sizes 46 | */ 47 | private List pageSizes = new ArrayList<>(); 48 | /** 49 | * Opened pages with indicator whether opening was successful 50 | */ 51 | private SparseBooleanArray openedPages = new SparseBooleanArray(); 52 | /** 53 | * Page with maximum width 54 | */ 55 | private Size originalMaxWidthPageSize = new Size(0, 0); 56 | /** 57 | * Page with maximum height 58 | */ 59 | private Size originalMaxHeightPageSize = new Size(0, 0); 60 | /** 61 | * Scaled page with maximum height 62 | */ 63 | private SizeF maxHeightPageSize = new SizeF(0, 0); 64 | /** 65 | * Scaled page with maximum width 66 | */ 67 | private SizeF maxWidthPageSize = new SizeF(0, 0); 68 | /** 69 | * Calculated offsets for pages 70 | */ 71 | private List pageOffsets = new ArrayList<>(); 72 | /** 73 | * Calculated auto spacing for pages 74 | */ 75 | private List pageSpacing = new ArrayList<>(); 76 | /** 77 | * Calculated document length (width or height, depending on swipe mode) 78 | */ 79 | private float documentLength = 0; 80 | 81 | /** 82 | * The pages the user want to display in order 83 | * (ex: 0, 2, 2, 8, 8, 1, 1, 1) 84 | */ 85 | private int[] originalUserPages; 86 | private DisplayOptions displayOptions; 87 | 88 | PdfFile( 89 | PdfiumCore pdfiumCore, 90 | PdfDocument pdfDocument, 91 | int[] originalUserPages, 92 | DisplayOptions displayOptions 93 | ) { 94 | this.pdfiumCore = pdfiumCore; 95 | this.pdfDocument = pdfDocument; 96 | this.originalUserPages = originalUserPages; 97 | this.displayOptions = displayOptions; 98 | setup(this.displayOptions.getViewSize()); 99 | } 100 | 101 | private void setup(Size viewSize) { 102 | if (originalUserPages != null) { 103 | pagesCount = originalUserPages.length; 104 | } else { 105 | pagesCount = pdfiumCore.getPageCount(pdfDocument); 106 | } 107 | 108 | for (int i = 0; i < pagesCount; i++) { 109 | Size pageSize = pdfiumCore.getPageSize(pdfDocument, documentPage(i)); 110 | if (pageSize.getWidth() > originalMaxWidthPageSize.getWidth()) { 111 | originalMaxWidthPageSize = pageSize; 112 | } 113 | if (pageSize.getHeight() > originalMaxHeightPageSize.getHeight()) { 114 | originalMaxHeightPageSize = pageSize; 115 | } 116 | originalPageSizes.add(pageSize); 117 | } 118 | 119 | recalculatePageSizes(viewSize); 120 | } 121 | 122 | /** 123 | * Call after view size change to recalculate page sizes, offsets and document length 124 | * 125 | * @param viewSize new size of changed view 126 | */ 127 | public void recalculatePageSizes(Size viewSize) { 128 | pageSizes.clear(); 129 | PageSizeCalculator calculator = new PageSizeCalculator( 130 | displayOptions.getPageFitPolicy(), 131 | originalMaxWidthPageSize, 132 | originalMaxHeightPageSize, 133 | viewSize, 134 | displayOptions.getFitEachPage() 135 | ); 136 | maxWidthPageSize = calculator.getOptimalMaxWidthPageSize(); 137 | maxHeightPageSize = calculator.getOptimalMaxHeightPageSize(); 138 | 139 | for (Size size : originalPageSizes) { 140 | pageSizes.add(calculator.calculate(size)); 141 | } 142 | if (displayOptions.getPdfSpacing().getAutoSpacing()) { 143 | prepareAutoSpacing(viewSize); 144 | } 145 | prepareDocLen(); 146 | preparePagesOffset(); 147 | } 148 | 149 | public int getPagesCount() { 150 | return pagesCount; 151 | } 152 | 153 | public SizeF getPageSize(int pageIndex) { 154 | int docPage = documentPage(pageIndex); 155 | if (docPage < 0) { 156 | return new SizeF(0, 0); 157 | } 158 | return pageSizes.get(pageIndex); 159 | } 160 | 161 | public SizeF getScaledPageSize(int pageIndex, float zoom) { 162 | SizeF size = getPageSize(pageIndex); 163 | return new SizeF(size.getWidth() * zoom, size.getHeight() * zoom); 164 | } 165 | 166 | /** 167 | * get page size with biggest dimension (width in vertical mode and height in horizontal mode) 168 | * 169 | * @return size of page 170 | */ 171 | public SizeF getMaxPageSize() { 172 | return displayOptions.isVertical() ? maxWidthPageSize : maxHeightPageSize; 173 | } 174 | 175 | public float getMaxPageWidth() { 176 | return getMaxPageSize().getWidth(); 177 | } 178 | 179 | public float getMaxPageHeight() { 180 | return getMaxPageSize().getHeight(); 181 | } 182 | 183 | private void prepareAutoSpacing(Size viewSize) { 184 | pageSpacing.clear(); 185 | for (int i = 0; i < getPagesCount(); i++) { 186 | SizeF pageSize = pageSizes.get(i); 187 | float spacing = Math.max(0, displayOptions.isVertical() ? viewSize.getHeight() - pageSize.getHeight() : 188 | viewSize.getWidth() - pageSize.getWidth()); 189 | if (i < getPagesCount() - 1) { 190 | spacing += displayOptions.getPdfSpacing().getPageSeparatorSpacing(); 191 | } 192 | pageSpacing.add(spacing); 193 | } 194 | } 195 | 196 | private void prepareDocLen() { 197 | float length = 0; 198 | for (int i = 0; i < getPagesCount(); i++) { 199 | SizeF pageSize = pageSizes.get(i); 200 | length += displayOptions.isVertical() ? pageSize.getHeight() : pageSize.getWidth(); 201 | if (displayOptions.getPdfSpacing().getAutoSpacing()) { 202 | length += pageSpacing.get(i); 203 | } else if (i < getPagesCount() - 1) { 204 | length += displayOptions.getPdfSpacing().getPageSeparatorSpacing(); 205 | } 206 | } 207 | documentLength = 208 | length + displayOptions.getPdfSpacing().getStartSpacing() + displayOptions.getPdfSpacing().getEndSpacing(); 209 | } 210 | 211 | private void preparePagesOffset() { 212 | pageOffsets.clear(); 213 | float offset = 0; 214 | for (int i = 0; i < getPagesCount(); i++) { 215 | SizeF pageSize = pageSizes.get(i); 216 | float size = displayOptions.isVertical() ? pageSize.getHeight() : pageSize.getWidth(); 217 | if (displayOptions.getPdfSpacing().getAutoSpacing()) { 218 | offset += pageSpacing.get(i) / 2f; 219 | if (i == 0) { 220 | offset -= displayOptions.getPdfSpacing().getPageSeparatorSpacing() / 2f; 221 | } else if (i == getPagesCount() - 1) { 222 | offset += displayOptions.getPdfSpacing().getPageSeparatorSpacing() / 2f; 223 | } 224 | pageOffsets.add(offset); 225 | offset += size + pageSpacing.get(i) / 2f; 226 | } else { 227 | // Adding a space at the beginning to be able to zoom out with a space between the top of the screen 228 | // and the first page of the PDF 229 | if (i == 0) { 230 | offset += displayOptions.getPdfSpacing().getStartSpacing(); 231 | } 232 | pageOffsets.add(offset); 233 | offset += size + displayOptions.getPdfSpacing().getPageSeparatorSpacing(); 234 | } 235 | } 236 | } 237 | 238 | public float getDocLen(float zoom) { 239 | return documentLength * zoom; 240 | } 241 | 242 | /** 243 | * Get the page's height if swiping vertical, or width if swiping horizontal. 244 | */ 245 | public float getPageLength(int pageIndex, float zoom) { 246 | SizeF size = getPageSize(pageIndex); 247 | return (displayOptions.isVertical() ? size.getHeight() : size.getWidth()) * zoom; 248 | } 249 | 250 | public float getPageSpacing(int pageIndex, float zoom) { 251 | float spacing; 252 | if (displayOptions.getPdfSpacing().getAutoSpacing()) { 253 | spacing = pageSpacing.get(pageIndex); 254 | } else { 255 | spacing = displayOptions.getPdfSpacing().getPageSeparatorSpacing(); 256 | } 257 | return spacing * zoom; 258 | } 259 | 260 | /** 261 | * Get primary page offset, that is Y for vertical scroll and X for horizontal scroll 262 | */ 263 | public float getPageOffset(int pageIndex, float zoom) { 264 | int docPage = documentPage(pageIndex); 265 | if (docPage < 0) { 266 | return 0; 267 | } 268 | return pageOffsets.get(pageIndex) * zoom; 269 | } 270 | 271 | /** 272 | * Get secondary page offset, that is X for vertical scroll and Y for horizontal scroll 273 | */ 274 | public float getSecondaryPageOffset(int pageIndex, float zoom) { 275 | SizeF pageSize = getPageSize(pageIndex); 276 | if (displayOptions.isVertical()) { 277 | float maxWidth = getMaxPageWidth(); 278 | return zoom * (maxWidth - pageSize.getWidth()) / 2; //x 279 | } else { 280 | float maxHeight = getMaxPageHeight(); 281 | return zoom * (maxHeight - pageSize.getHeight()) / 2; //y 282 | } 283 | } 284 | 285 | public int getPageAtOffset(float offset, float zoom) { 286 | int currentPage = 0; 287 | for (int i = 0; i < getPagesCount(); i++) { 288 | float off = pageOffsets.get(i) * zoom - getPageSpacing(i, zoom) / 2f; 289 | if (off >= offset) { 290 | break; 291 | } 292 | currentPage++; 293 | } 294 | return --currentPage >= 0 ? currentPage : 0; 295 | } 296 | 297 | public boolean openPage(int pageIndex) throws PageRenderingException { 298 | int docPage = documentPage(pageIndex); 299 | if (docPage < 0) { 300 | return false; 301 | } 302 | 303 | synchronized (lock) { 304 | if (openedPages.indexOfKey(docPage) < 0) { 305 | try { 306 | pdfiumCore.openPage(pdfDocument, docPage); 307 | openedPages.put(docPage, true); 308 | return true; 309 | } catch (Exception e) { 310 | openedPages.put(docPage, false); 311 | throw new PageRenderingException(pageIndex, e); 312 | } 313 | } 314 | return false; 315 | } 316 | } 317 | 318 | public boolean pageHasError(int pageIndex) { 319 | int docPage = documentPage(pageIndex); 320 | return !openedPages.get(docPage, false); 321 | } 322 | 323 | public void renderPageBitmap(Bitmap bitmap, int pageIndex, Rect bounds, boolean annotationRendering) { 324 | int docPage = documentPage(pageIndex); 325 | pdfiumCore.renderPageBitmap(pdfDocument, bitmap, docPage, 326 | bounds.left, bounds.top, bounds.width(), bounds.height(), annotationRendering); 327 | } 328 | 329 | public PdfDocument.Meta getMetaData() { 330 | if (pdfDocument == null) { 331 | return null; 332 | } 333 | return pdfiumCore.getDocumentMeta(pdfDocument); 334 | } 335 | 336 | public List getBookmarks() { 337 | if (pdfDocument == null) { 338 | return new ArrayList<>(); 339 | } 340 | return pdfiumCore.getTableOfContents(pdfDocument); 341 | } 342 | 343 | public List getPageLinks(int pageIndex) { 344 | int docPage = documentPage(pageIndex); 345 | return pdfiumCore.getPageLinks(pdfDocument, docPage); 346 | } 347 | 348 | public RectF mapRectToDevice(int pageIndex, int startX, int startY, int sizeX, int sizeY, 349 | RectF rect) { 350 | int docPage = documentPage(pageIndex); 351 | return pdfiumCore.mapRectToDevice(pdfDocument, docPage, startX, startY, sizeX, sizeY, 0, rect); 352 | } 353 | 354 | public void dispose() { 355 | if (pdfiumCore != null && pdfDocument != null) { 356 | pdfiumCore.closeDocument(pdfDocument); 357 | } 358 | 359 | pdfDocument = null; 360 | originalUserPages = null; 361 | } 362 | 363 | /** 364 | * Given the UserPage number, this method restrict it 365 | * to be sure it's an existing page. It takes care of 366 | * using the user defined pages if any. 367 | * 368 | * @param userPage A page number. 369 | * @return A restricted valid page number (example : -2 => 0) 370 | */ 371 | public int determineValidPageNumberFrom(int userPage) { 372 | if (userPage <= 0) { 373 | return 0; 374 | } 375 | if (originalUserPages != null) { 376 | if (userPage >= originalUserPages.length) { 377 | return originalUserPages.length - 1; 378 | } 379 | } else { 380 | if (userPage >= getPagesCount()) { 381 | return getPagesCount() - 1; 382 | } 383 | } 384 | return userPage; 385 | } 386 | 387 | public int documentPage(int userPage) { 388 | int documentPage = userPage; 389 | if (originalUserPages != null) { 390 | if (userPage < 0 || userPage >= originalUserPages.length) { 391 | return -1; 392 | } else { 393 | documentPage = originalUserPages[userPage]; 394 | } 395 | } 396 | 397 | if (documentPage < 0 || userPage >= getPagesCount()) { 398 | return -1; 399 | } 400 | 401 | return documentPage; 402 | } 403 | } 404 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/RenderingHandler.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Infomaniak android-pdf-viewer 3 | * Copyright (C) 2024 Infomaniak Network SA 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | package com.infomaniak.lib.pdfview 20 | 21 | import android.graphics.Bitmap 22 | import android.graphics.Matrix 23 | import android.graphics.Rect 24 | import android.graphics.RectF 25 | import android.os.Handler 26 | import android.os.Looper 27 | import android.os.Message 28 | import android.util.Log 29 | import com.infomaniak.lib.pdfview.RenderingHandler.RenderingTask 30 | import com.infomaniak.lib.pdfview.exception.PageRenderingException 31 | import com.infomaniak.lib.pdfview.model.PagePart 32 | 33 | /** 34 | * A [Handler] that will process incoming [RenderingTask] messages 35 | * and alert [PDFView.onBitmapRendered] when the portion of the 36 | * PDF is ready to render. 37 | */ 38 | internal class RenderingHandler( 39 | looper: Looper?, 40 | private val pdfView: PDFView, 41 | ) : Handler(looper!!) { 42 | private val renderBounds = RectF() 43 | private val roundedRenderBounds = Rect() 44 | private val renderMatrix = Matrix() 45 | private var running = false 46 | 47 | fun addRenderingTask( 48 | page: Int, 49 | renderingSize: RenderingSize, 50 | thumbnail: Boolean, 51 | cacheOrder: Int, 52 | bestQuality: Boolean, 53 | annotationRendering: Boolean, 54 | isForPrinting: Boolean, 55 | ) { 56 | val task = RenderingTask( 57 | renderingSize, 58 | page, 59 | thumbnail, 60 | cacheOrder, 61 | bestQuality, 62 | annotationRendering, 63 | isForPrinting, 64 | ) 65 | val msg = obtainMessage(MSG_RENDER_TASK, task) 66 | sendMessage(msg) 67 | } 68 | 69 | fun stop() { 70 | running = false 71 | } 72 | 73 | fun start() { 74 | running = true 75 | } 76 | 77 | override fun handleMessage(message: Message): Unit = with(pdfView) { 78 | val task = message.obj as RenderingTask 79 | runCatching { 80 | proceed(task)?.let { pagePart -> 81 | if (running) { 82 | post { onBitmapRendered(pagePart, task.isForPrinting) } 83 | } else { 84 | pagePart.renderedBitmap.recycle() 85 | } 86 | } 87 | }.onFailure { exception -> 88 | if (exception is PageRenderingException) post { onPageError(exception) } 89 | } 90 | } 91 | 92 | @Throws(PageRenderingException::class) 93 | private fun proceed(renderingTask: RenderingTask): PagePart? { 94 | val pdfFile = pdfView.pdfFile 95 | pdfFile.openPage(renderingTask.page) 96 | 97 | val w = Math.round(renderingTask.renderingSize.width) 98 | val h = Math.round(renderingTask.renderingSize.height) 99 | 100 | if (w == 0 || h == 0 || pdfFile.pageHasError(renderingTask.page)) { 101 | return null 102 | } 103 | 104 | var render: Bitmap? = null 105 | runCatching { 106 | Bitmap.createBitmap( 107 | w, h, if (renderingTask.bestQuality) Bitmap.Config.ARGB_8888 else Bitmap.Config.RGB_565 108 | ) 109 | }.onSuccess { renderedBitmap -> 110 | render = renderedBitmap 111 | }.onFailure { 112 | Log.e(TAG, "Cannot create bitmap", it) 113 | render = null 114 | } 115 | 116 | calculateBounds(w, h, renderingTask.renderingSize.bounds) 117 | 118 | pdfFile.renderPageBitmap( 119 | render, renderingTask.page, roundedRenderBounds, renderingTask.annotationRendering 120 | ) 121 | 122 | return PagePart( 123 | renderingTask.page, 124 | render, 125 | renderingTask.renderingSize.bounds, 126 | renderingTask.thumbnail, 127 | renderingTask.cacheOrder 128 | ) 129 | } 130 | 131 | private fun calculateBounds(width: Int, height: Int, pageSliceBounds: RectF) { 132 | renderMatrix.reset() 133 | renderMatrix.postTranslate(-pageSliceBounds.left * width, -pageSliceBounds.top * height) 134 | renderMatrix.postScale(1 / pageSliceBounds.width(), 1 / pageSliceBounds.height()) 135 | 136 | renderBounds[0f, 0f, width.toFloat()] = height.toFloat() 137 | renderMatrix.mapRect(renderBounds) 138 | renderBounds.round(roundedRenderBounds) 139 | } 140 | 141 | data class RenderingSize( 142 | var width: Float, 143 | var height: Float, 144 | var bounds: RectF, 145 | ) 146 | 147 | private data class RenderingTask( 148 | var renderingSize: RenderingSize, 149 | var page: Int, 150 | var thumbnail: Boolean, 151 | var cacheOrder: Int, 152 | var bestQuality: Boolean, 153 | var annotationRendering: Boolean, 154 | var isForPrinting: Boolean, 155 | ) 156 | 157 | companion object { 158 | /** 159 | * [Message.what] kind of message this handler processes. 160 | */ 161 | const val MSG_RENDER_TASK: Int = 1 162 | 163 | private val TAG: String = RenderingHandler::class.java.name 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.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/infomaniak/lib/pdfview/exception/PageRenderingException.java: -------------------------------------------------------------------------------- 1 | package com.infomaniak.lib.pdfview.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/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.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.infomaniak.lib.pdfview.PDFView; 24 | import com.infomaniak.lib.pdfview.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/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.link; 17 | 18 | import com.infomaniak.lib.pdfview.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/infomaniak/lib/pdfview/listener/Callbacks.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * Infomaniak android-pdf-viewer 4 | * Copyright (C) 2024 Infomaniak Network SA 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | 20 | package com.infomaniak.lib.pdfview.listener; 21 | 22 | import android.graphics.Bitmap; 23 | import android.view.MotionEvent; 24 | 25 | import com.infomaniak.lib.pdfview.link.LinkHandler; 26 | import com.infomaniak.lib.pdfview.model.LinkTapEvent; 27 | 28 | import java.util.List; 29 | 30 | public class Callbacks { 31 | 32 | private OnReadyForPrintingListener onReadyForPrintingListener; 33 | 34 | /** 35 | * Call back object to call when the PDF is loaded 36 | */ 37 | private OnLoadCompleteListener onLoadCompleteListener; 38 | private OnAttachCompleteListener onAttachCompleteListener; 39 | private OnDetachCompleteListener onDetachCompleteListener; 40 | 41 | /** 42 | * Call back object to call when document loading error occurs 43 | */ 44 | private OnErrorListener onErrorListener; 45 | 46 | /** 47 | * Call back object to call when the page load error occurs 48 | */ 49 | private OnPageErrorListener onPageErrorListener; 50 | 51 | /** 52 | * Call back object to call when the document is initially rendered 53 | */ 54 | private OnRenderListener onRenderListener; 55 | 56 | /** 57 | * Call back object to call when the page has changed 58 | */ 59 | private OnPageChangeListener onPageChangeListener; 60 | 61 | /** 62 | * Call back object to call when the page is scrolled 63 | */ 64 | private OnPageScrollListener onPageScrollListener; 65 | 66 | /** 67 | * Call back object to call when the above layer is to drawn 68 | */ 69 | private OnDrawListener onDrawListener; 70 | 71 | private OnDrawListener onDrawAllListener; 72 | 73 | /** 74 | * Call back object to call when the user does a tap gesture 75 | */ 76 | private OnTapListener onTapListener; 77 | 78 | /** 79 | * Call back object to call when the user does a long tap gesture 80 | */ 81 | private OnLongPressListener onLongPressListener; 82 | 83 | /** 84 | * Call back object to call when clicking link 85 | */ 86 | private LinkHandler linkHandler; 87 | 88 | public void setOnReadyForPrinting(OnReadyForPrintingListener onReadyForPrintingListener) { 89 | this.onReadyForPrintingListener = onReadyForPrintingListener; 90 | } 91 | 92 | public void callsOnReadyForPrinting(List pagesAsBitmaps) { 93 | if (onReadyForPrintingListener != null) { 94 | onReadyForPrintingListener.bitmapsReady(pagesAsBitmaps); 95 | } 96 | } 97 | 98 | public void setOnLoadComplete(OnLoadCompleteListener onLoadCompleteListener) { 99 | this.onLoadCompleteListener = onLoadCompleteListener; 100 | } 101 | 102 | public void callOnLoadComplete(int pagesCount) { 103 | if (onLoadCompleteListener != null) { 104 | onLoadCompleteListener.loadComplete(pagesCount); 105 | } 106 | } 107 | 108 | public void setOnAttachCompleteListener(OnAttachCompleteListener onAttachCompleteListener) { 109 | this.onAttachCompleteListener = onAttachCompleteListener; 110 | } 111 | 112 | public void setOnDetachCompleteListener(OnDetachCompleteListener onDetachCompleteListener) { 113 | this.onDetachCompleteListener = onDetachCompleteListener; 114 | } 115 | 116 | public void callOnAttachComplete() { 117 | if (onAttachCompleteListener != null) { 118 | onAttachCompleteListener.onAttachComplete(); 119 | } 120 | } 121 | 122 | public void callOnDetachComplete() { 123 | if (onDetachCompleteListener != null) { 124 | onDetachCompleteListener.onDetachComplete(); 125 | } 126 | } 127 | 128 | public OnErrorListener getOnError() { 129 | return onErrorListener; 130 | } 131 | 132 | public void setOnError(OnErrorListener onErrorListener) { 133 | this.onErrorListener = onErrorListener; 134 | } 135 | 136 | public void setOnPageError(OnPageErrorListener onPageErrorListener) { 137 | this.onPageErrorListener = onPageErrorListener; 138 | } 139 | 140 | public boolean callOnPageError(int page, Throwable error) { 141 | if (onPageErrorListener != null) { 142 | onPageErrorListener.onPageError(page, error); 143 | return true; 144 | } 145 | return false; 146 | } 147 | 148 | public void setOnRender(OnRenderListener onRenderListener) { 149 | this.onRenderListener = onRenderListener; 150 | } 151 | 152 | public void callOnRender(int pagesCount) { 153 | if (onRenderListener != null) { 154 | onRenderListener.onInitiallyRendered(pagesCount); 155 | } 156 | } 157 | 158 | public void setOnPageChange(OnPageChangeListener onPageChangeListener) { 159 | this.onPageChangeListener = onPageChangeListener; 160 | } 161 | 162 | public void callOnPageChange(int page, int pagesCount) { 163 | if (onPageChangeListener != null) { 164 | onPageChangeListener.onPageChanged(page, pagesCount); 165 | } 166 | } 167 | 168 | public void setOnPageScroll(OnPageScrollListener onPageScrollListener) { 169 | this.onPageScrollListener = onPageScrollListener; 170 | } 171 | 172 | public void callOnPageScroll(int currentPage, float offset) { 173 | if (onPageScrollListener != null) { 174 | onPageScrollListener.onPageScrolled(currentPage, offset); 175 | } 176 | } 177 | 178 | public OnDrawListener getOnDraw() { 179 | return onDrawListener; 180 | } 181 | 182 | public void setOnDraw(OnDrawListener onDrawListener) { 183 | this.onDrawListener = onDrawListener; 184 | } 185 | 186 | public OnDrawListener getOnDrawAll() { 187 | return onDrawAllListener; 188 | } 189 | 190 | public void setOnDrawAll(OnDrawListener onDrawAllListener) { 191 | this.onDrawAllListener = onDrawAllListener; 192 | } 193 | 194 | public void setOnTap(OnTapListener onTapListener) { 195 | this.onTapListener = onTapListener; 196 | } 197 | 198 | public boolean callOnTap(MotionEvent event) { 199 | return onTapListener != null && onTapListener.onTap(event); 200 | } 201 | 202 | public void setOnLongPress(OnLongPressListener onLongPressListener) { 203 | this.onLongPressListener = onLongPressListener; 204 | } 205 | 206 | public void callOnLongPress(MotionEvent event) { 207 | if (onLongPressListener != null) { 208 | onLongPressListener.onLongPress(event); 209 | } 210 | } 211 | 212 | public void setLinkHandler(LinkHandler linkHandler) { 213 | this.linkHandler = linkHandler; 214 | } 215 | 216 | public void callLinkHandler(LinkTapEvent event) { 217 | if (linkHandler != null) { 218 | linkHandler.handleLinkEvent(event); 219 | } 220 | } 221 | 222 | public void clear() { 223 | // Not clearing onAttach and onDetach listeners because those are called before view initialization 224 | onLoadCompleteListener = null; 225 | onErrorListener = null; 226 | onPageErrorListener = null; 227 | onRenderListener = null; 228 | onPageChangeListener = null; 229 | onPageScrollListener = null; 230 | onDrawListener = null; 231 | onDrawAllListener = null; 232 | onTapListener = null; 233 | onLongPressListener = null; 234 | linkHandler = null; 235 | } 236 | } 237 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/listener/OnAttachCompleteListener.java: -------------------------------------------------------------------------------- 1 | package com.infomaniak.lib.pdfview.listener; 2 | 3 | public interface OnAttachCompleteListener { 4 | 5 | void onAttachComplete(); 6 | } 7 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/listener/OnDetachCompleteListener.java: -------------------------------------------------------------------------------- 1 | package com.infomaniak.lib.pdfview.listener; 2 | 3 | public interface OnDetachCompleteListener { 4 | 5 | void onDetachComplete(); 6 | } 7 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.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/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.listener; 17 | 18 | public interface OnErrorListener { 19 | 20 | /** 21 | * Called if error occurred while opening PDF 22 | * 23 | * @param t Throwable with error 24 | */ 25 | void onError(Throwable t); 26 | } 27 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.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 | * 27 | * @param nbPages the number of pages in this PDF file 28 | */ 29 | void loadComplete(int nbPages); 30 | } 31 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.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/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.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/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.listener; 17 | 18 | public interface OnPageErrorListener { 19 | 20 | /** 21 | * Called if error occurred while loading PDF page 22 | * 23 | * @param t Throwable with error 24 | */ 25 | void onPageError(int page, Throwable t); 26 | } 27 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.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.infomaniak.lib.pdfview.PDFView#getPositionOffset()} 29 | */ 30 | void onPageScrolled(int page, float positionOffset); 31 | } 32 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/listener/OnReadyForPrintingListener.java: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | * Infomaniak android-pdf-viewer 4 | * Copyright (C) 2024 Infomaniak Network SA 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | */ 19 | 20 | package com.infomaniak.lib.pdfview.listener; 21 | 22 | import android.graphics.Bitmap; 23 | 24 | import java.util.List; 25 | 26 | /** 27 | * Implement this interface to receive events from PDFView 28 | * when bitmaps has been generated. Used to print password protected PDF. 29 | */ 30 | public interface OnReadyForPrintingListener { 31 | 32 | /** 33 | * Called when bitmaps has been generated 34 | * 35 | * @param bitmaps pages of the PDF as bitmaps 36 | */ 37 | void bitmapsReady(List bitmaps); 38 | } 39 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.listener; 17 | 18 | public interface OnRenderListener { 19 | 20 | /** 21 | * Called only once, when document is rendered 22 | * 23 | * @param nbPages number of pages 24 | */ 25 | void onInitiallyRendered(int nbPages); 26 | } 27 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.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/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.model; 17 | 18 | import android.graphics.RectF; 19 | 20 | import com.shockwave.pdfium.PdfDocument; 21 | 22 | public class LinkTapEvent { 23 | 24 | private float originalX; 25 | private float originalY; 26 | private float documentX; 27 | private float documentY; 28 | private RectF mappedLinkRect; 29 | private PdfDocument.Link link; 30 | 31 | public LinkTapEvent( 32 | float originalX, 33 | float originalY, 34 | float documentX, 35 | float documentY, 36 | RectF mappedLinkRect, 37 | PdfDocument.Link link 38 | ) { 39 | this.originalX = originalX; 40 | this.originalY = originalY; 41 | this.documentX = documentX; 42 | this.documentY = documentY; 43 | this.mappedLinkRect = mappedLinkRect; 44 | this.link = link; 45 | } 46 | 47 | public float getOriginalX() { 48 | return originalX; 49 | } 50 | 51 | public float getOriginalY() { 52 | return originalY; 53 | } 54 | 55 | public float getDocumentX() { 56 | return documentX; 57 | } 58 | 59 | public float getDocumentY() { 60 | return documentY; 61 | } 62 | 63 | public RectF getMappedLinkRect() { 64 | return mappedLinkRect; 65 | } 66 | 67 | public PdfDocument.Link getLink() { 68 | return link; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.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 void setCacheOrder(int cacheOrder) { 47 | this.cacheOrder = cacheOrder; 48 | } 49 | 50 | public int getPage() { 51 | return page; 52 | } 53 | 54 | public Bitmap getRenderedBitmap() { 55 | return renderedBitmap; 56 | } 57 | 58 | public RectF getPageRelativeBounds() { 59 | return pageRelativeBounds; 60 | } 61 | 62 | public boolean isThumbnail() { 63 | return thumbnail; 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/infomaniak/lib/pdfview/scroll/DefaultScrollHandle.java: -------------------------------------------------------------------------------- 1 | package com.infomaniak.lib.pdfview.scroll; 2 | 3 | import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; 4 | 5 | import android.content.Context; 6 | import android.graphics.drawable.Drawable; 7 | import android.os.Handler; 8 | import android.os.Looper; 9 | import android.util.TypedValue; 10 | import android.view.LayoutInflater; 11 | import android.view.MotionEvent; 12 | import android.view.View; 13 | import android.widget.RelativeLayout; 14 | import android.widget.TextView; 15 | 16 | import androidx.core.content.ContextCompat; 17 | 18 | import com.infomaniak.lib.pdfview.PDFView; 19 | import com.infomaniak.lib.pdfview.R; 20 | import com.infomaniak.lib.pdfview.util.TouchUtils; 21 | import com.infomaniak.lib.pdfview.util.Util; 22 | 23 | public class DefaultScrollHandle extends RelativeLayout implements ScrollHandle { 24 | 25 | private static final int HANDLE_WIDTH = 65; 26 | private static final int HANDLE_HEIGHT = 40; 27 | private static final int NO_ALIGN = -1; 28 | private static final int TOUCH_POINTER_COUNT = 1; 29 | 30 | private final Handler handler = new Handler(Looper.getMainLooper()); 31 | private final boolean inverted; 32 | private final Runnable hidePageScrollerRunnable = this::hide; 33 | protected TextView pageIndicator; 34 | protected Context context; 35 | private float relativeHandlerMiddle = 0f; 36 | private PDFView pdfView; 37 | private float currentPos; 38 | private Drawable handleBackgroundDrawable; 39 | private View handleView; 40 | private int handleAlign; 41 | private int handleWidth = HANDLE_WIDTH; 42 | private int handleHeight = HANDLE_HEIGHT; 43 | private int handlePaddingLeft = 0; 44 | private int handlePaddingTop = 0; 45 | private int handlePaddingRight = 0; 46 | private int handlePaddingBottom = 0; 47 | 48 | private int hideHandleDelayMillis = 1000; 49 | 50 | private boolean hasStartedDragging = false; 51 | private int textColorResId = -1; 52 | private int textSize = -1; 53 | 54 | public DefaultScrollHandle(Context context) { 55 | this(context, false); 56 | } 57 | 58 | public DefaultScrollHandle(Context context, boolean inverted) { 59 | super(context); 60 | this.context = context; 61 | this.inverted = inverted; 62 | } 63 | 64 | @Override 65 | public void setupLayout(PDFView pdfView) { 66 | setHandleRelativePosition(pdfView); 67 | setHandleView(); 68 | pdfView.addView(this); 69 | this.pdfView = pdfView; 70 | } 71 | 72 | private void setHandleRelativePosition(PDFView pdfView) { 73 | // determine handler position, default is right (when scrolling vertically) or bottom (when scrolling horizontally) 74 | if (pdfView.isSwipeVertical()) { 75 | handleAlign = inverted ? ALIGN_PARENT_LEFT : ALIGN_PARENT_RIGHT; 76 | } else { 77 | int tempWidth = handleWidth; 78 | handleWidth = handleHeight; 79 | handleHeight = tempWidth; 80 | handleAlign = inverted ? ALIGN_PARENT_TOP : ALIGN_PARENT_BOTTOM; 81 | } 82 | } 83 | 84 | private void setHandleView() { 85 | if (handleView != null) { 86 | initViewWithCustomView(); 87 | } else { 88 | initDefaultView(handleBackgroundDrawable); 89 | } 90 | 91 | setVisibility(INVISIBLE); 92 | if (pageIndicator != null) { 93 | if (textColorResId != -1) pageIndicator.setTextColor(textColorResId); 94 | if (textSize != -1) pageIndicator.setTextSize(TypedValue.COMPLEX_UNIT_DIP, textSize); 95 | } 96 | } 97 | 98 | private void initDefaultView(Drawable drawable) { 99 | LayoutInflater layoutInflater = LayoutInflater.from(context); 100 | View view = layoutInflater.inflate(R.layout.default_handle, null); 101 | pageIndicator = view.findViewById(R.id.pageIndicator); 102 | pageIndicator.setBackground(drawable != null ? drawable : getDefaultHandleBackgroundDrawable()); 103 | addView(view, getCustomViewLayoutParams()); 104 | setRootLayoutParams(); 105 | } 106 | 107 | private LayoutParams getCustomViewLayoutParams() { 108 | return getLayoutParams( 109 | Util.getDP(context, handleWidth), 110 | Util.getDP(context, handleHeight), 111 | NO_ALIGN, 112 | true 113 | ); 114 | } 115 | 116 | private void initViewWithCustomView() { 117 | if (handleView.getParent() != null) { 118 | removeView(handleView); 119 | } 120 | addView(handleView, getCustomViewLayoutParams()); 121 | setRootLayoutParams(); 122 | } 123 | 124 | private Drawable getDefaultHandleBackgroundDrawable() { 125 | int drawableResId = switch (handleAlign) { 126 | case ALIGN_PARENT_LEFT -> R.drawable.default_scroll_handle_left; 127 | case ALIGN_PARENT_RIGHT -> R.drawable.default_scroll_handle_right; 128 | case ALIGN_PARENT_TOP -> R.drawable.default_scroll_handle_top; 129 | default -> R.drawable.default_scroll_handle_bottom; 130 | }; 131 | return getDrawable(drawableResId); 132 | } 133 | 134 | private LayoutParams getLayoutParams(int width, int height, int align, boolean withPadding) { 135 | LayoutParams layoutParams = new LayoutParams(width, height); 136 | if (align != NO_ALIGN) layoutParams.addRule(align); 137 | 138 | if (withPadding) { 139 | layoutParams.setMargins( 140 | Util.getDP(context, handlePaddingLeft), 141 | Util.getDP(context, handlePaddingTop), 142 | Util.getDP(context, handlePaddingRight), 143 | Util.getDP(context, handlePaddingBottom) 144 | ); 145 | } 146 | 147 | return layoutParams; 148 | } 149 | 150 | private void setRootLayoutParams() { 151 | setLayoutParams(getLayoutParams(WRAP_CONTENT, WRAP_CONTENT, handleAlign, false)); 152 | } 153 | 154 | private Drawable getDrawable(int resDrawable) { 155 | return ContextCompat.getDrawable(context, resDrawable); 156 | } 157 | 158 | @Override 159 | public void destroyLayout() { 160 | pdfView.removeView(this); 161 | } 162 | 163 | @Override 164 | public void setScroll(float position) { 165 | if (!shown()) { 166 | show(); 167 | } else { 168 | handler.removeCallbacks(hidePageScrollerRunnable); 169 | } 170 | if (pdfView != null) { 171 | setPosition((pdfView.isSwipeVertical() ? pdfView.getHeight() : pdfView.getWidth()) * position); 172 | } 173 | } 174 | 175 | private void setPosition(float pos) { 176 | if (Float.isInfinite(pos) || Float.isNaN(pos)) { 177 | return; 178 | } 179 | float pdfViewSize; 180 | int handleSize; 181 | if (pdfView.isSwipeVertical()) { 182 | pdfViewSize = pdfView.getHeight(); 183 | handleSize = handleHeight; 184 | } else { 185 | pdfViewSize = pdfView.getWidth(); 186 | handleSize = handleWidth; 187 | } 188 | pos -= relativeHandlerMiddle; 189 | 190 | float maxBound = pdfViewSize - Util.getDP(context, handleSize) - getPaddings(); 191 | if (pos < 0) { 192 | pos = 0; 193 | } else if (pos > maxBound) { 194 | pos = maxBound; 195 | } 196 | 197 | if (pdfView.isSwipeVertical()) { 198 | setY(pos); 199 | } else { 200 | setX(pos); 201 | } 202 | 203 | calculateMiddle(); 204 | invalidate(); 205 | } 206 | 207 | private int getPaddings() { 208 | int paddings = switch (handleAlign) { 209 | case ALIGN_PARENT_LEFT, ALIGN_PARENT_RIGHT -> handlePaddingTop + handlePaddingBottom; 210 | case ALIGN_PARENT_TOP, ALIGN_PARENT_BOTTOM -> handlePaddingLeft + handlePaddingRight; 211 | default -> 0; 212 | }; 213 | return Util.getDP(context, paddings); 214 | } 215 | 216 | private void calculateMiddle() { 217 | float pos; 218 | float viewSize; 219 | float pdfViewSize; 220 | if (pdfView.isSwipeVertical()) { 221 | pos = getY(); 222 | viewSize = getHeight(); 223 | pdfViewSize = pdfView.getHeight(); 224 | } else { 225 | pos = getX(); 226 | viewSize = getWidth(); 227 | pdfViewSize = pdfView.getWidth(); 228 | } 229 | relativeHandlerMiddle = ((pos + relativeHandlerMiddle) / pdfViewSize) * viewSize; 230 | } 231 | 232 | @Override 233 | public void hideDelayed() { 234 | handler.postDelayed(hidePageScrollerRunnable, hideHandleDelayMillis); 235 | } 236 | 237 | @Override 238 | public void setPageNum(int pageNum) { 239 | String text = String.valueOf(pageNum); 240 | if (pageIndicator != null && !pageIndicator.getText().equals(text)) { 241 | pageIndicator.setText(text); 242 | } 243 | } 244 | 245 | @Override 246 | public boolean shown() { 247 | return getVisibility() == VISIBLE; 248 | } 249 | 250 | @Override 251 | public void show() { 252 | setVisibility(VISIBLE); 253 | } 254 | 255 | @Override 256 | public void hide() { 257 | setVisibility(INVISIBLE); 258 | } 259 | 260 | /** 261 | * @param color color of the text handle 262 | */ 263 | public void setTextColor(int color) { 264 | textColorResId = color; 265 | } 266 | 267 | /** 268 | * @param size text size in dp 269 | */ 270 | public void setTextSize(int size) { 271 | textSize = size; 272 | } 273 | 274 | /** 275 | * @param handleBackgroundDrawable drawable to set as a background 276 | */ 277 | public void setPageHandleBackground(Drawable handleBackgroundDrawable) { 278 | this.handleBackgroundDrawable = handleBackgroundDrawable; 279 | } 280 | 281 | /** 282 | * Use a custom view as the handle. if you want to have the page indicator, 283 | * provide the pageIndicator parameter. 284 | * 285 | * @param handleView view to set as the handle 286 | * @param pageIndicator TextView to use as the page indicator 287 | */ 288 | public void setPageHandleView(View handleView, TextView pageIndicator) { 289 | this.handleView = handleView; 290 | this.pageIndicator = pageIndicator; 291 | } 292 | 293 | /** 294 | * @param handleWidth width of the handle 295 | * @param handleHeight width of the handle 296 | */ 297 | public void setHandleSize(int handleWidth, int handleHeight) { 298 | this.handleWidth = handleWidth; 299 | this.handleHeight = handleHeight; 300 | } 301 | 302 | /** 303 | * @param paddingLeft left padding of the handle 304 | * @param paddingTop top padding of the handle 305 | * @param paddingRight right padding of the handle 306 | * @param paddingBottom bottom padding of the handle 307 | */ 308 | public void setHandlePaddings(int paddingLeft, int paddingTop, int paddingRight, int paddingBottom) { 309 | handlePaddingLeft = paddingLeft; 310 | handlePaddingTop = paddingTop; 311 | handlePaddingRight = paddingRight; 312 | handlePaddingBottom = paddingBottom; 313 | } 314 | 315 | /** 316 | * @param hideHandleDelayMillis delay in milliseconds to hide the handle after scrolling the PDF 317 | */ 318 | public void setHideHandleDelay(int hideHandleDelayMillis) { 319 | this.hideHandleDelayMillis = hideHandleDelayMillis; 320 | } 321 | 322 | private boolean isPDFViewReady() { 323 | return pdfView != null && pdfView.getPageCount() > 0 && !pdfView.documentFitsView(); 324 | } 325 | 326 | private View getTouchedView(MotionEvent event) { 327 | int x = Math.round(event.getX()); 328 | int y = Math.round(event.getY()); 329 | for (int i = 0; i < getChildCount(); i++) { 330 | View child = getChildAt(i); 331 | if (x > child.getLeft() && x < child.getRight() && y > child.getTop() && y < child.getBottom()) { 332 | return child; 333 | } 334 | } 335 | return null; 336 | } 337 | 338 | private boolean shouldIgnoreTouch(MotionEvent event) { 339 | View touchedView = getTouchedView(event); 340 | if (hasStartedDragging) { 341 | return false; 342 | } else if (touchedView != null) { 343 | Object tag = touchedView.getTag(); 344 | return tag != null && !tag.toString().equals("rootHandle"); 345 | } 346 | return true; 347 | } 348 | 349 | @Override 350 | public boolean onTouchEvent(MotionEvent event) { 351 | if (!isPDFViewReady() || shouldIgnoreTouch(event)) { 352 | return super.onTouchEvent(event); 353 | } 354 | 355 | hasStartedDragging = true; 356 | 357 | TouchUtils.handleTouchPriority(event, this, TOUCH_POINTER_COUNT, false, pdfView.isZooming()); 358 | switch (event.getAction()) { 359 | case MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> { 360 | pdfView.stopFling(); 361 | handler.removeCallbacks(hidePageScrollerRunnable); 362 | if (pdfView.isSwipeVertical()) { 363 | currentPos = event.getRawY() - getY(); 364 | } else { 365 | currentPos = event.getRawX() - getX(); 366 | } 367 | return true; 368 | } 369 | case MotionEvent.ACTION_MOVE -> { 370 | if (pdfView.isSwipeVertical()) { 371 | setPosition(event.getRawY() - currentPos + relativeHandlerMiddle); 372 | pdfView.setPositionOffset(relativeHandlerMiddle / getHeight(), false); 373 | } else { 374 | setPosition(event.getRawX() - currentPos + relativeHandlerMiddle); 375 | pdfView.setPositionOffset(relativeHandlerMiddle / getWidth(), false); 376 | } 377 | return true; 378 | } 379 | case MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> { 380 | hideDelayed(); 381 | pdfView.performPageSnap(); 382 | hasStartedDragging = false; 383 | return true; 384 | } 385 | default -> { 386 | return super.onTouchEvent(event); 387 | } 388 | } 389 | } 390 | } 391 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/scroll/ScrollHandle.java: -------------------------------------------------------------------------------- 1 | package com.infomaniak.lib.pdfview.scroll; 2 | 3 | import com.infomaniak.lib.pdfview.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/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.source; 17 | 18 | import android.content.Context; 19 | import android.os.ParcelFileDescriptor; 20 | 21 | import com.infomaniak.lib.pdfview.util.FileUtils; 22 | import com.shockwave.pdfium.PdfDocument; 23 | import com.shockwave.pdfium.PdfiumCore; 24 | 25 | import java.io.File; 26 | import java.io.IOException; 27 | 28 | public class AssetSource implements DocumentSource { 29 | 30 | private final String assetName; 31 | 32 | public AssetSource(String assetName) { 33 | this.assetName = assetName; 34 | } 35 | 36 | @Override 37 | public PdfDocument createDocument(Context context, PdfiumCore core, String password) throws IOException { 38 | File f = FileUtils.fileFromAsset(context, assetName); 39 | ParcelFileDescriptor pfd = ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY); 40 | return core.newDocument(pfd, password); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.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/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.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/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.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/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.source; 17 | 18 | import android.content.Context; 19 | 20 | import com.infomaniak.lib.pdfview.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/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.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 | public Uri getUri() { 36 | return uri; 37 | } 38 | 39 | @Override 40 | public PdfDocument createDocument(Context context, PdfiumCore core, String password) throws IOException { 41 | ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r"); 42 | return core.newDocument(pfd, password); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.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 | /** 28 | * Transforms (0,1,2,2,3) to (0,1,2,3) 29 | */ 30 | public static int[] deleteDuplicatedPages(int[] pages) { 31 | List result = new ArrayList<>(); 32 | int lastInt = -1; 33 | for (Integer currentInt : pages) { 34 | if (lastInt != currentInt) { 35 | result.add(currentInt); 36 | } 37 | lastInt = currentInt; 38 | } 39 | int[] arrayResult = new int[result.size()]; 40 | for (int i = 0; i < result.size(); i++) { 41 | arrayResult[i] = result.get(i); 42 | } 43 | return arrayResult; 44 | } 45 | 46 | /** 47 | * Transforms (0, 4, 4, 6, 6, 6, 3) into (0, 1, 1, 2, 2, 2, 3) 48 | */ 49 | public static int[] calculateIndexesInDuplicateArray(int[] originalUserPages) { 50 | int[] result = new int[originalUserPages.length]; 51 | if (originalUserPages.length == 0) { 52 | return result; 53 | } 54 | 55 | int index = 0; 56 | result[0] = index; 57 | for (int i = 1; i < originalUserPages.length; i++) { 58 | if (originalUserPages[i] != originalUserPages[i - 1]) { 59 | index++; 60 | } 61 | result[i] = index; 62 | } 63 | 64 | return result; 65 | } 66 | 67 | public static String arrayToString(int[] array) { 68 | StringBuilder builder = new StringBuilder("["); 69 | for (int i = 0; i < array.length; i++) { 70 | builder.append(array[i]); 71 | if (i != array.length - 1) { 72 | builder.append(","); 73 | } 74 | } 75 | builder.append("]"); 76 | return builder.toString(); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/util/Constants.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Infomaniak android-pdf-viewer 3 | * Copyright (C) 2024 Infomaniak Network SA 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | package com.infomaniak.lib.pdfview.util 19 | 20 | object Constants { 21 | 22 | const val DEBUG_MODE = false 23 | 24 | /** 25 | * Between 0 and 1, the thumbnails quality (default 0.3). Increasing this value may cause performances decrease. 26 | */ 27 | const val THUMBNAIL_RATIO = 0.3f 28 | 29 | /** 30 | * Minimum quality for printing. 31 | */ 32 | const val THUMBNAIL_RATIO_PRINTING = 0.75f 33 | 34 | /** 35 | * The size of the rendered parts (default 256). 36 | * Tinier : a little bit slower to have the whole page rendered but more reactive. 37 | * Bigger : user will have to wait longer to have the first visual results. 38 | */ 39 | const val PART_SIZE = 256.0f 40 | 41 | /** 42 | * Part of document above and below screen that should be preloaded, in dp. 43 | */ 44 | const val PRELOAD_OFFSET = 20 45 | 46 | object Cache { 47 | /** 48 | * The size of the cache (number of bitmaps kept). 49 | */ 50 | const val CACHE_SIZE = 120 51 | const val THUMBNAILS_CACHE_SIZE = 8 52 | } 53 | 54 | object Pinch { 55 | const val MAXIMUM_ZOOM = 100.0f 56 | const val MINIMUM_ZOOM = 0.3f 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.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/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.util; 17 | 18 | public enum FitPolicy { 19 | WIDTH, HEIGHT, BOTH 20 | } 21 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.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 | * 31 | * @param number The number to limit. 32 | * @param between The smallest value the number can take. 33 | * @param and The biggest value the number can take. 34 | * @return The limited number. 35 | */ 36 | public static int limit(int number, int between, int and) { 37 | if (number <= between) { 38 | return between; 39 | } 40 | if (number >= and) { 41 | return and; 42 | } 43 | return number; 44 | } 45 | 46 | /** 47 | * Limits the given number between the other values 48 | * 49 | * @param number The number to limit. 50 | * @param between The smallest value the number can take. 51 | * @param and The biggest value the number can take. 52 | * @return The limited number. 53 | */ 54 | public static float limit(float number, float between, float and) { 55 | if (number <= between) { 56 | return between; 57 | } 58 | if (number >= and) { 59 | return and; 60 | } 61 | return number; 62 | } 63 | 64 | public static float max(float number, float max) { 65 | if (number > max) { 66 | return max; 67 | } 68 | return number; 69 | } 70 | 71 | public static float min(float number, float min) { 72 | if (number < min) { 73 | return min; 74 | } 75 | return number; 76 | } 77 | 78 | public static int max(int number, int max) { 79 | if (number > max) { 80 | return max; 81 | } 82 | return number; 83 | } 84 | 85 | public static int min(int number, int min) { 86 | if (number < min) { 87 | return min; 88 | } 89 | return number; 90 | } 91 | 92 | /** 93 | * Methods from libGDX - https://github.com/libgdx/libgdx 94 | */ 95 | 96 | /** 97 | * Returns the largest integer less than or equal to the specified float. This method will only properly floor floats from 98 | * -(2^14) to (Float.MAX_VALUE - 2^14). 99 | */ 100 | static public int floor(float value) { 101 | return (int) (value + BIG_ENOUGH_FLOOR) - BIG_ENOUGH_INT; 102 | } 103 | 104 | /** 105 | * Returns the smallest integer greater than or equal to the specified float. This method will only properly ceil floats from 106 | * -(2^14) to (Float.MAX_VALUE - 2^14). 107 | */ 108 | static public int ceil(float value) { 109 | return (int) (value + BIG_ENOUGH_CEIL) - BIG_ENOUGH_INT; 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.util; 17 | 18 | import com.shockwave.pdfium.util.Size; 19 | import com.shockwave.pdfium.util.SizeF; 20 | 21 | public class PageSizeCalculator { 22 | 23 | private final Size originalMaxWidthPageSize; 24 | private final Size originalMaxHeightPageSize; 25 | private final Size viewSize; 26 | private FitPolicy fitPolicy; 27 | private SizeF optimalMaxWidthPageSize; 28 | private SizeF optimalMaxHeightPageSize; 29 | private float widthRatio; 30 | private float heightRatio; 31 | private boolean fitEachPage; 32 | 33 | public PageSizeCalculator( 34 | FitPolicy fitPolicy, 35 | Size originalMaxWidthPageSize, 36 | Size originalMaxHeightPageSize, 37 | Size viewSize, 38 | boolean fitEachPage 39 | ) { 40 | this.fitPolicy = fitPolicy; 41 | this.originalMaxWidthPageSize = originalMaxWidthPageSize; 42 | this.originalMaxHeightPageSize = originalMaxHeightPageSize; 43 | this.viewSize = viewSize; 44 | this.fitEachPage = fitEachPage; 45 | calculateMaxPages(); 46 | } 47 | 48 | public SizeF calculate(Size pageSize) { 49 | if (pageSize.getWidth() <= 0 || pageSize.getHeight() <= 0) { 50 | return new SizeF(0, 0); 51 | } 52 | float maxWidth = fitEachPage ? viewSize.getWidth() : pageSize.getWidth() * widthRatio; 53 | float maxHeight = fitEachPage ? viewSize.getHeight() : pageSize.getHeight() * heightRatio; 54 | switch (fitPolicy) { 55 | case HEIGHT: 56 | return fitHeight(pageSize, maxHeight); 57 | case BOTH: 58 | return fitBoth(pageSize, maxWidth, maxHeight); 59 | default: 60 | return fitWidth(pageSize, maxWidth); 61 | } 62 | } 63 | 64 | public SizeF getOptimalMaxWidthPageSize() { 65 | return optimalMaxWidthPageSize; 66 | } 67 | 68 | public SizeF getOptimalMaxHeightPageSize() { 69 | return optimalMaxHeightPageSize; 70 | } 71 | 72 | private void calculateMaxPages() { 73 | switch (fitPolicy) { 74 | case HEIGHT: 75 | optimalMaxHeightPageSize = fitHeight(originalMaxHeightPageSize, viewSize.getHeight()); 76 | heightRatio = optimalMaxHeightPageSize.getHeight() / originalMaxHeightPageSize.getHeight(); 77 | optimalMaxWidthPageSize = fitHeight(originalMaxWidthPageSize, originalMaxWidthPageSize.getHeight() * heightRatio); 78 | break; 79 | case BOTH: 80 | SizeF localOptimalMaxWidth = fitBoth(originalMaxWidthPageSize, viewSize.getWidth(), viewSize.getHeight()); 81 | float localWidthRatio = localOptimalMaxWidth.getWidth() / originalMaxWidthPageSize.getWidth(); 82 | this.optimalMaxHeightPageSize = fitBoth(originalMaxHeightPageSize, 83 | originalMaxHeightPageSize.getWidth() * localWidthRatio, viewSize.getHeight()); 84 | heightRatio = optimalMaxHeightPageSize.getHeight() / originalMaxHeightPageSize.getHeight(); 85 | optimalMaxWidthPageSize = fitBoth(originalMaxWidthPageSize, viewSize.getWidth(), 86 | originalMaxWidthPageSize.getHeight() * heightRatio); 87 | widthRatio = optimalMaxWidthPageSize.getWidth() / originalMaxWidthPageSize.getWidth(); 88 | break; 89 | default: 90 | optimalMaxWidthPageSize = fitWidth(originalMaxWidthPageSize, viewSize.getWidth()); 91 | widthRatio = optimalMaxWidthPageSize.getWidth() / originalMaxWidthPageSize.getWidth(); 92 | optimalMaxHeightPageSize = fitWidth(originalMaxHeightPageSize, originalMaxHeightPageSize.getWidth() * widthRatio); 93 | break; 94 | } 95 | } 96 | 97 | private SizeF fitWidth(Size pageSize, float maxWidth) { 98 | float w = pageSize.getWidth(), h = pageSize.getHeight(); 99 | float ratio = w / h; 100 | w = maxWidth; 101 | h = (float) Math.floor(maxWidth / ratio); 102 | return new SizeF(w, h); 103 | } 104 | 105 | private SizeF fitHeight(Size pageSize, float maxHeight) { 106 | float w = pageSize.getWidth(), h = pageSize.getHeight(); 107 | float ratio = h / w; 108 | h = maxHeight; 109 | w = (float) Math.floor(maxHeight / ratio); 110 | return new SizeF(w, h); 111 | } 112 | 113 | private SizeF fitBoth(Size pageSize, float maxWidth, float maxHeight) { 114 | float w = pageSize.getWidth(), h = pageSize.getHeight(); 115 | float ratio = w / h; 116 | w = maxWidth; 117 | h = (float) Math.floor(maxWidth / ratio); 118 | if (h > maxHeight) { 119 | h = maxHeight; 120 | w = (float) Math.floor(maxHeight * ratio); 121 | } 122 | return new SizeF(w, h); 123 | } 124 | 125 | } 126 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.util; 17 | 18 | public enum SnapEdge { 19 | START, CENTER, END, NONE 20 | } 21 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/util/TouchUtils.java: -------------------------------------------------------------------------------- 1 | package com.infomaniak.lib.pdfview.util; 2 | 3 | import android.view.MotionEvent; 4 | import android.view.View; 5 | import android.view.ViewParent; 6 | 7 | import androidx.recyclerview.widget.RecyclerView; 8 | import androidx.viewpager2.widget.ViewPager2; 9 | 10 | import com.infomaniak.lib.pdfview.PDFView; 11 | 12 | public class TouchUtils { 13 | 14 | public static final int DIRECTION_SCROLLING_LEFT = -1; 15 | public static final int DIRECTION_SCROLLING_RIGHT = 1; 16 | static final int DIRECTION_SCROLLING_TOP = -1; 17 | static final int DIRECTION_SCROLLING_BOTTOM = 1; 18 | 19 | private TouchUtils() { 20 | throw new IllegalStateException("Utility class"); 21 | } 22 | 23 | public static void handleTouchPriority( 24 | MotionEvent event, 25 | View view, 26 | int pointerCount, 27 | boolean shouldOverrideTouchPriority, 28 | boolean isZooming 29 | ) { 30 | ViewParent viewToDisableTouch = getViewToDisableTouch(view); 31 | 32 | if (viewToDisableTouch == null) { 33 | return; 34 | } 35 | 36 | boolean canScrollHorizontally = 37 | view.canScrollHorizontally(DIRECTION_SCROLLING_RIGHT) && view.canScrollHorizontally(DIRECTION_SCROLLING_LEFT); 38 | boolean canScrollVertically = 39 | view.canScrollVertically(DIRECTION_SCROLLING_TOP) && view.canScrollVertically(DIRECTION_SCROLLING_BOTTOM); 40 | if (shouldOverrideTouchPriority) { 41 | viewToDisableTouch.requestDisallowInterceptTouchEvent(false); 42 | 43 | ViewParent viewPager = getViewPager(view); 44 | if (viewPager != null) { 45 | viewPager.requestDisallowInterceptTouchEvent(true); 46 | } 47 | } else if (event.getPointerCount() >= pointerCount || canScrollHorizontally || canScrollVertically) { 48 | int action = event.getAction(); 49 | 50 | if (action == MotionEvent.ACTION_UP) { 51 | viewToDisableTouch.requestDisallowInterceptTouchEvent(false); 52 | } else if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_MOVE || isZooming) { 53 | viewToDisableTouch.requestDisallowInterceptTouchEvent(true); 54 | } 55 | } 56 | } 57 | 58 | private static ViewParent getViewToDisableTouch(View startingView) { 59 | ViewParent parentView = startingView.getParent(); 60 | 61 | while (parentView != null && !(parentView instanceof RecyclerView)) { 62 | parentView = parentView.getParent(); 63 | } 64 | 65 | return parentView; 66 | } 67 | 68 | private static ViewParent getViewPager(View startingView) { 69 | ViewParent parentView = startingView.getParent(); 70 | 71 | while (parentView != null && !(parentView instanceof ViewPager2)) { 72 | parentView = parentView.getParent(); 73 | } 74 | 75 | return parentView; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/java/com/infomaniak/lib/pdfview/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.infomaniak.lib.pdfview.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 | 4 | 7 | 10 | 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 | 4 | 7 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/res/drawable/default_scroll_handle_top.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/res/layout/default_handle.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /android-pdf-viewer/src/main/res/values/attrs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | buildscript { 2 | 3 | extra.apply { 4 | set("libMinSdk", 21) 5 | set("libCompileSdk", 34) 6 | set("libTargetSdk", 34) 7 | set("libVersionName", "3.2.11") 8 | set("javaVersion", JavaVersion.VERSION_17) 9 | set("kotlinVersion", "2.0.21") 10 | } 11 | 12 | repositories { 13 | google() 14 | mavenCentral() 15 | } 16 | 17 | dependencies { 18 | classpath(libs.gradle) 19 | } 20 | } 21 | 22 | apply(plugin = "maven-publish") 23 | 24 | allprojects { 25 | repositories { 26 | google() 27 | //mavenLocal() 28 | mavenCentral() 29 | maven("https://jitpack.io") 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | android.enableJetifier=false 2 | android.useAndroidX=true -------------------------------------------------------------------------------- /gradle/libs.versions.toml: -------------------------------------------------------------------------------- 1 | [versions] 2 | activityKtx = "1.9.3" 3 | androidannotations = "4.8.0" 4 | appcompat = "1.7.0" 5 | coreKtx = "1.13.1" 6 | gradle = "8.9.0" 7 | kotlinAndroid = "2.0.21" 8 | material = "1.12.0" 9 | pdfium = "1.9.6" 10 | recyclerView = "1.3.2" 11 | viewpager2 = "1.1.0" 12 | 13 | [libraries] 14 | activity-ktx = { module = "androidx.activity:activity-ktx", version.ref = "activityKtx" } 15 | androidannotations = { module = "org.androidannotations:androidannotations", version.ref = "androidannotations" } 16 | appcompat = { module = "androidx.appcompat:appcompat", version.ref = "appcompat" } 17 | core-ktx = { module = "androidx.core:core-ktx", version.ref = "coreKtx" } 18 | gradle = { module = "com.android.tools.build:gradle", version.ref = "gradle" } 19 | material = { module = "com.google.android.material:material", version.ref = "material" } 20 | pdfium = { module = "com.github.infomaniak:pdfiumandroid", version.ref = "pdfium" } 21 | recyclerview = { module = "androidx.recyclerview:recyclerview", version.ref = "recyclerView" } 22 | viewpager2 = { module = "androidx.viewpager2:viewpager2", version.ref = "viewpager2" } 23 | 24 | [plugins] 25 | kapt = { id = "org.jetbrains.kotlin.kapt", version.ref = "kotlinAndroid" } 26 | kotlinAndroid = { id = "org.jetbrains.kotlin.android", version.ref = "kotlinAndroid" } 27 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Infomaniak/android-pdfview/eefa67e6143401562b95e123ef17f7fc32a0c054/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 | distributionPath=wrapper/dists 4 | zipStorePath=wrapper/dists 5 | zipStoreBase=GRADLE_USER_HOME 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip 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 | -------------------------------------------------------------------------------- /jitpack.yml: -------------------------------------------------------------------------------- 1 | jdk: 2 | - openjdk17 3 | -------------------------------------------------------------------------------- /sample/build.gradle.kts: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | google() 4 | mavenCentral() 5 | } 6 | } 7 | 8 | repositories { 9 | google() 10 | //mavenLocal() 11 | mavenCentral() 12 | } 13 | 14 | plugins { 15 | id("com.android.application") 16 | 17 | alias(libs.plugins.kotlinAndroid) 18 | alias(libs.plugins.kapt) 19 | } 20 | 21 | val libMinSdk: Int by rootProject.extra 22 | val libCompileSdk: Int by rootProject.extra 23 | val libTargetSdk: Int by rootProject.extra 24 | val javaVersion: JavaVersion by rootProject.extra 25 | val versionName: String by rootProject.extra 26 | 27 | android { 28 | namespace = "com.infomaniak.lib.pdfview.sample" 29 | 30 | defaultConfig { 31 | minSdk = libMinSdk 32 | compileSdk = libCompileSdk 33 | targetSdk = libTargetSdk 34 | versionCode = 3 35 | versionName = versionName 36 | } 37 | buildFeatures { viewBinding = true } 38 | 39 | compileOptions { 40 | sourceCompatibility = javaVersion 41 | targetCompatibility = javaVersion 42 | } 43 | 44 | kotlinOptions { jvmTarget = javaVersion.toString() } 45 | } 46 | 47 | dependencies { 48 | implementation(project(":android-pdf-viewer")) 49 | 50 | implementation(libs.activity.ktx) 51 | implementation(libs.appcompat) 52 | implementation(libs.material) 53 | implementation(libs.pdfium) 54 | 55 | annotationProcessor(libs.androidannotations) 56 | } 57 | -------------------------------------------------------------------------------- /sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 7 | 11 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /sample/src/main/assets/sample.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Infomaniak/android-pdfview/eefa67e6143401562b95e123ef17f7fc32a0c054/sample/src/main/assets/sample.pdf -------------------------------------------------------------------------------- /sample/src/main/java/com/infomaniak/lib/pdfpreview/sample/PDFViewActivity.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Infomaniak android-pdf-viewer 3 | * Copyright (C) 2024 Infomaniak Network SA 4 | * 5 | * This program is free software: you can redistribute it and/or modify 6 | * it under the terms of the GNU General Public License as published by 7 | * the Free Software Foundation, either version 3 of the License, or 8 | * (at your option) any later version. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | package com.infomaniak.lib.pdfpreview.sample 20 | 21 | import android.annotation.SuppressLint 22 | import android.content.ActivityNotFoundException 23 | import android.content.Intent 24 | import android.content.pm.PackageManager 25 | import android.graphics.Color 26 | import android.net.Uri 27 | import android.os.Build 28 | import android.os.Bundle 29 | import android.util.Log 30 | import android.widget.Toast 31 | import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult 32 | import androidx.activity.viewModels 33 | import androidx.appcompat.app.AppCompatActivity 34 | import androidx.core.app.ActivityCompat 35 | import androidx.core.content.ContextCompat 36 | import androidx.core.content.res.ResourcesCompat 37 | import com.infomaniak.lib.pdfview.PDFView.Configurator 38 | import com.infomaniak.lib.pdfview.listener.OnErrorListener 39 | import com.infomaniak.lib.pdfview.listener.OnLoadCompleteListener 40 | import com.infomaniak.lib.pdfview.listener.OnPageChangeListener 41 | import com.infomaniak.lib.pdfview.listener.OnPageErrorListener 42 | import com.infomaniak.lib.pdfview.sample.R 43 | import com.infomaniak.lib.pdfview.sample.databinding.ActivityMainBinding 44 | import com.infomaniak.lib.pdfview.scroll.DefaultScrollHandle 45 | import com.infomaniak.lib.pdfview.scroll.ScrollHandle 46 | import com.infomaniak.lib.pdfview.util.FitPolicy 47 | import com.shockwave.pdfium.PdfDocument 48 | import com.shockwave.pdfium.PdfPasswordException 49 | 50 | class PDFViewActivity : AppCompatActivity(), OnPageChangeListener, OnLoadCompleteListener, OnPageErrorListener, OnErrorListener { 51 | 52 | private var uri: Uri? = null 53 | private var pageNumber = 0 54 | private var pdfFileName: String? = null 55 | 56 | private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) } 57 | private val viewModel: PDFViewViewModel by viewModels() 58 | 59 | private val pdfScrollHandle by lazy { getScrollHandle() } 60 | 61 | private val selectFileResult = registerForActivityResult(StartActivityForResult()) { activityResult -> 62 | if (activityResult.resultCode == RESULT_OK) { 63 | activityResult.data?.let { intent -> 64 | uri = intent.data 65 | displayFromUri(uri) 66 | } 67 | } 68 | } 69 | 70 | override fun onCreate(savedInstanceState: Bundle?) { 71 | super.onCreate(savedInstanceState) 72 | setContentView(binding.root) 73 | initializePDFView() 74 | binding.selectFile.setOnClickListener { pickFile() } 75 | } 76 | 77 | private fun pickFile() { 78 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { 79 | val permissionCheck = ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) 80 | if (permissionCheck != PackageManager.PERMISSION_GRANTED) { 81 | ActivityCompat.requestPermissions(this, arrayOf(READ_EXTERNAL_STORAGE), PERMISSION_CODE) 82 | return 83 | } 84 | } 85 | launchPicker() 86 | } 87 | 88 | private fun launchPicker() { 89 | val intent = Intent(Intent.ACTION_GET_CONTENT) 90 | intent.type = "application/pdf" 91 | runCatching { 92 | selectFileResult.launch(intent) 93 | }.onFailure { exception -> 94 | if (exception is ActivityNotFoundException) { 95 | Toast.makeText(this, R.string.toast_pick_file_error, Toast.LENGTH_SHORT).show() 96 | } 97 | } 98 | } 99 | 100 | private fun initializePDFView() { 101 | binding.pdfView.setBackgroundColor(Color.LTGRAY) 102 | if (uri != null) { 103 | displayFromUri(uri) 104 | } else { 105 | displayFromAsset() 106 | } 107 | title = pdfFileName 108 | } 109 | 110 | @SuppressLint("InflateParams") 111 | private fun getScrollHandle(): ScrollHandle = DefaultScrollHandle(this).apply { 112 | val view = layoutInflater.inflate(R.layout.handle_background, null); 113 | setPageHandleView(view, view.findViewById(R.id.pageIndicator)) 114 | setTextColor(ResourcesCompat.getColor(resources, android.R.color.white, null)) 115 | setTextSize(DEFAULT_TEXT_SIZE_DP) 116 | setHandleSize(HANDLE_WIDTH_DP, HANDLE_HEIGHT_DP) 117 | setHandlePaddings(0, HANDLE_PADDING_TOP_DP, 0, HANDLE_PADDING_BOTTOM_DP) 118 | } 119 | 120 | private fun displayFromAsset(password: String? = null) { 121 | pdfFileName = SAMPLE_FILE 122 | loadPDF(binding.pdfView.fromAsset(SAMPLE_FILE), password) 123 | } 124 | 125 | private fun displayFromUri(uri: Uri?, password: String? = null) { 126 | pdfFileName = viewModel.getFileName(contentResolver, uri) 127 | loadPDF(binding.pdfView.fromUri(uri), password) 128 | } 129 | 130 | private fun loadPDF(pdfConfigurator: Configurator, password: String? = null) { 131 | pdfConfigurator.defaultPage(pageNumber) 132 | .onPageChange(this) 133 | .enableAnnotationRendering(true) 134 | .onLoad(this) 135 | .scrollHandle(pdfScrollHandle) 136 | .pageSeparatorSpacing(PDF_PAGE_SPACING_DP) 137 | .startEndSpacing(START_END_SPACING_DP, START_END_SPACING_DP) 138 | .zoom(MIN_ZOOM, MID_ZOOM, MAX_ZOOM) 139 | .onPageError(this) 140 | .pageFitPolicy(FitPolicy.BOTH) 141 | .password(password) 142 | .load() 143 | } 144 | 145 | private fun openPasswordDialog() { 146 | PasswordDialog( 147 | onPasswordEntered = { password -> displayFromUri(uri, password) }, 148 | ).also { it.show(supportFragmentManager, "TAG") } 149 | } 150 | 151 | private fun printBookmarksTree(bookmarks: List, sep: String) { 152 | for (bookmark in bookmarks) { 153 | Log.e(TAG, String.format("%s %s, p %d", sep, bookmark.title, bookmark.pageIdx)) 154 | if (bookmark.hasChildren()) printBookmarksTree(bookmark.children, "$sep-") 155 | } 156 | } 157 | 158 | override fun loadComplete(nbPages: Int) { 159 | val meta = binding.pdfView.documentMeta 160 | Log.e(TAG, "title = " + meta.title) 161 | Log.e(TAG, "author = " + meta.author) 162 | Log.e(TAG, "subject = " + meta.subject) 163 | Log.e(TAG, "keywords = " + meta.keywords) 164 | Log.e(TAG, "creator = " + meta.creator) 165 | Log.e(TAG, "producer = " + meta.producer) 166 | Log.e(TAG, "creationDate = " + meta.creationDate) 167 | Log.e(TAG, "modDate = " + meta.modDate) 168 | printBookmarksTree(binding.pdfView.tableOfContents, "-") 169 | } 170 | 171 | override fun onPageChanged(page: Int, pageCount: Int) { 172 | pageNumber = page 173 | title = String.format("%s %s / %s", pdfFileName, page + 1, pageCount) 174 | } 175 | 176 | /** 177 | * Listener for response to user permission request 178 | * 179 | * @param requestCode Check that permission request code matches 180 | * @param permissions Permissions that requested 181 | * @param grantResults Whether permissions granted 182 | */ 183 | override fun onRequestPermissionsResult( 184 | requestCode: Int, 185 | permissions: Array, 186 | grantResults: IntArray, 187 | ) { 188 | super.onRequestPermissionsResult(requestCode, permissions, grantResults) 189 | if (requestCode == PERMISSION_CODE && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 190 | launchPicker() 191 | } 192 | } 193 | 194 | override fun onPageError(page: Int, t: Throwable) { 195 | Log.e(TAG, "Cannot load page $page") 196 | } 197 | 198 | override fun onError(throwable: Throwable?) { 199 | when (throwable) { 200 | is PdfPasswordException -> openPasswordDialog() 201 | } 202 | } 203 | 204 | companion object { 205 | private val TAG: String = PDFViewActivity::class.java.simpleName 206 | private const val PERMISSION_CODE = 42042 207 | private const val SAMPLE_FILE = "sample.pdf" 208 | private const val READ_EXTERNAL_STORAGE = "android.permission.READ_EXTERNAL_STORAGE" 209 | private const val HANDLE_WIDTH_DP = 65 210 | private const val HANDLE_HEIGHT_DP = 40 211 | private const val HANDLE_PADDING_TOP_DP = 40 212 | private const val HANDLE_PADDING_BOTTOM_DP = 40 213 | private const val PDF_PAGE_SPACING_DP = 10 214 | private const val DEFAULT_TEXT_SIZE_DP = 16 215 | private const val START_END_SPACING_DP = 10 216 | private const val MIN_ZOOM = 0.93f 217 | private const val MID_ZOOM = 3.0f 218 | private const val MAX_ZOOM = 6.0f 219 | } 220 | } 221 | -------------------------------------------------------------------------------- /sample/src/main/java/com/infomaniak/lib/pdfpreview/sample/PDFViewViewModel.kt: -------------------------------------------------------------------------------- 1 | package com.infomaniak.lib.pdfpreview.sample 2 | 3 | import android.app.Application 4 | import android.content.ContentResolver 5 | import android.net.Uri 6 | import android.provider.OpenableColumns 7 | import androidx.lifecycle.AndroidViewModel 8 | 9 | class PDFViewViewModel(appContext: Application) : AndroidViewModel(appContext) { 10 | 11 | fun getFileName(contentResolver: ContentResolver, uri: Uri?): String? { 12 | return uri?.let { fileUri -> 13 | var result: String? = null 14 | if (fileUri.scheme == "content") { 15 | val cursor = contentResolver.query(fileUri, null, null, null, null) 16 | cursor?.use { fileCursor -> 17 | if (fileCursor.moveToFirst()) { 18 | val columnIndex = fileCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME) 19 | result = fileCursor.getString(columnIndex) 20 | } 21 | } 22 | } 23 | if (result == null) { 24 | result = fileUri.lastPathSegment 25 | } 26 | result 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /sample/src/main/java/com/infomaniak/lib/pdfpreview/sample/PasswordDialog.kt: -------------------------------------------------------------------------------- 1 | package com.infomaniak.lib.pdfpreview.sample 2 | 3 | import android.app.Dialog 4 | import android.os.Bundle 5 | import android.view.LayoutInflater 6 | import androidx.fragment.app.DialogFragment 7 | import com.google.android.material.dialog.MaterialAlertDialogBuilder 8 | import com.infomaniak.lib.pdfview.sample.databinding.DialogPasswordBinding 9 | 10 | class PasswordDialog(private val onPasswordEntered: (String) -> Unit) : DialogFragment() { 11 | private val binding by lazy { 12 | DialogPasswordBinding.inflate(LayoutInflater.from(context)) 13 | } 14 | 15 | override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { 16 | binding.validate.setOnClickListener { 17 | onPasswordEntered.invoke(binding.passwordInputField.text.toString()) 18 | dismiss() 19 | } 20 | return MaterialAlertDialogBuilder(requireContext()).setView(binding.root).create() 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable-hdpi/ic_open_in_browser_grey_700_48dp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Infomaniak/android-pdfview/eefa67e6143401562b95e123ef17f7fc32a0c054/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/Infomaniak/android-pdfview/eefa67e6143401562b95e123ef17f7fc32a0c054/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/Infomaniak/android-pdfview/eefa67e6143401562b95e123ef17f7fc32a0c054/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/Infomaniak/android-pdfview/eefa67e6143401562b95e123ef17f7fc32a0c054/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/Infomaniak/android-pdfview/eefa67e6143401562b95e123ef17f7fc32a0c054/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/Infomaniak/android-pdfview/eefa67e6143401562b95e123ef17f7fc32a0c054/sample/src/main/res/drawable/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 15 | 16 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/dialog_password.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 10 | 11 | 20 | 21 | 27 | 28 | 29 | 30 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/handle_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /sample/src/main/res/menu/options.xml: -------------------------------------------------------------------------------- 1 | 2 |

4 | 9 | -------------------------------------------------------------------------------- /sample/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #0098FF 4 | #0079CC 5 | @color/infomaniak 6 | @color/infomaniak 7 | @color/infomaniakDark 8 | -------------------------------------------------------------------------------- /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 | 10 | 11 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | include(":android-pdf-viewer") 2 | include(":sample") 3 | --------------------------------------------------------------------------------