├── changelog.md ├── sample-local ├── src │ ├── main │ │ ├── res │ │ │ ├── values │ │ │ │ ├── strings.xml │ │ │ │ ├── colors.xml │ │ │ │ └── styles.xml │ │ │ ├── mipmap-hdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-mdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-xxxhdpi │ │ │ │ ├── ic_launcher.png │ │ │ │ └── ic_launcher_round.png │ │ │ ├── mipmap-anydpi-v26 │ │ │ │ ├── ic_launcher.xml │ │ │ │ └── ic_launcher_round.xml │ │ │ ├── layout │ │ │ │ └── activity_main.xml │ │ │ ├── drawable-v24 │ │ │ │ └── ic_launcher_foreground.xml │ │ │ └── drawable │ │ │ │ └── ic_launcher_background.xml │ │ ├── assets │ │ │ ├── paper.pdf │ │ │ └── great-expectations.pdf │ │ ├── AndroidManifest.xml │ │ └── java │ │ │ └── com │ │ │ └── pdfview_sample │ │ │ └── pdfview │ │ │ └── MainActivity.kt │ ├── test │ │ └── java │ │ │ └── com │ │ │ └── pdfview_sample │ │ │ └── pdfview │ │ │ └── ExampleUnitTest.kt │ └── androidTest │ │ └── java │ │ └── com │ │ └── pdfview_sample │ │ └── pdfview │ │ └── ExampleInstrumentedTest.kt ├── proguard-rules.pro └── build.gradle ├── sample-network ├── src │ └── main │ │ ├── res │ │ ├── values │ │ │ ├── strings.xml │ │ │ ├── colors.xml │ │ │ └── styles.xml │ │ ├── mipmap-hdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ │ ├── ic_launcher.png │ │ │ └── ic_launcher_round.png │ │ ├── mipmap-anydpi-v26 │ │ │ ├── ic_launcher.xml │ │ │ └── ic_launcher_round.xml │ │ ├── layout │ │ │ └── activity_main.xml │ │ ├── drawable-v24 │ │ │ └── ic_launcher_foreground.xml │ │ └── drawable │ │ │ └── ic_launcher_background.xml │ │ ├── java │ │ └── com │ │ │ └── pdfview_network_sample │ │ │ └── pdfview │ │ │ ├── MainActivity.kt │ │ │ └── PdfViewModel.kt │ │ └── AndroidManifest.xml ├── proguard-rules.pro └── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── settings.gradle ├── gifs └── fast_scrolling_on_weak_device.gif ├── pdfview-android ├── src │ └── main │ │ ├── AndroidManifest.xml │ │ ├── res │ │ └── values │ │ │ └── attrs.xml │ │ └── java │ │ └── com │ │ └── pdfview │ │ ├── FileUtils.kt │ │ ├── subsamplincscaleimageview │ │ ├── decoder │ │ │ ├── DecoderFactory.java │ │ │ ├── ImageDecoder.java │ │ │ ├── CompatDecoderFactory.java │ │ │ ├── ImageRegionDecoder.java │ │ │ ├── SkiaImageDecoder.java │ │ │ ├── SkiaImageRegionDecoder.java │ │ │ └── SkiaPooledImageRegionDecoder.java │ │ ├── ImageViewState.java │ │ └── ImageSource.java │ │ ├── PDFView.kt │ │ └── PDFRegionDecoder.kt └── build.gradle ├── gradle.properties ├── maven-scripts ├── publish-root.gradle ├── info.gradle └── publish-module.gradle ├── .gitignore ├── README.md ├── gradlew.bat ├── gradlew └── LICENSE /changelog.md: -------------------------------------------------------------------------------- 1 | 2 | 1.1.0 - republished to mavencentral 3 | 4 | 1.0.0 - initial stable release to jcenter 5 | 6 | -------------------------------------------------------------------------------- /sample-local/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | pdfview 3 | 4 | -------------------------------------------------------------------------------- /sample-network/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | pdfview 3 | 4 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dmitry-Borodin/pdfview-android/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'pdfview-root' 2 | 3 | include ':pdfview-android', 4 | ':sample-local', 5 | ':sample-network' 6 | -------------------------------------------------------------------------------- /gifs/fast_scrolling_on_weak_device.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dmitry-Borodin/pdfview-android/HEAD/gifs/fast_scrolling_on_weak_device.gif -------------------------------------------------------------------------------- /sample-local/src/main/assets/paper.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dmitry-Borodin/pdfview-android/HEAD/sample-local/src/main/assets/paper.pdf -------------------------------------------------------------------------------- /pdfview-android/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /sample-local/src/main/assets/great-expectations.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dmitry-Borodin/pdfview-android/HEAD/sample-local/src/main/assets/great-expectations.pdf -------------------------------------------------------------------------------- /sample-local/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dmitry-Borodin/pdfview-android/HEAD/sample-local/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample-local/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dmitry-Borodin/pdfview-android/HEAD/sample-local/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample-local/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dmitry-Borodin/pdfview-android/HEAD/sample-local/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample-local/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dmitry-Borodin/pdfview-android/HEAD/sample-local/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample-local/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dmitry-Borodin/pdfview-android/HEAD/sample-local/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample-network/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dmitry-Borodin/pdfview-android/HEAD/sample-network/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample-network/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dmitry-Borodin/pdfview-android/HEAD/sample-network/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample-network/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dmitry-Borodin/pdfview-android/HEAD/sample-network/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample-network/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dmitry-Borodin/pdfview-android/HEAD/sample-network/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample-network/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dmitry-Borodin/pdfview-android/HEAD/sample-network/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample-local/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dmitry-Borodin/pdfview-android/HEAD/sample-local/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample-local/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dmitry-Borodin/pdfview-android/HEAD/sample-local/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample-local/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dmitry-Borodin/pdfview-android/HEAD/sample-local/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample-local/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dmitry-Borodin/pdfview-android/HEAD/sample-local/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample-network/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dmitry-Borodin/pdfview-android/HEAD/sample-network/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample-network/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dmitry-Borodin/pdfview-android/HEAD/sample-network/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample-local/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dmitry-Borodin/pdfview-android/HEAD/sample-local/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample-network/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dmitry-Borodin/pdfview-android/HEAD/sample-network/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample-network/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dmitry-Borodin/pdfview-android/HEAD/sample-network/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample-network/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Dmitry-Borodin/pdfview-android/HEAD/sample-network/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /sample-local/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #008577 4 | #00574B 5 | #D81B60 6 | 7 | -------------------------------------------------------------------------------- /sample-network/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #008577 4 | #00574B 5 | #D81B60 6 | 7 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sat Mar 05 09:56:26 IST 2022 2 | distributionBase=GRADLE_USER_HOME 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip 4 | distributionPath=wrapper/dists 5 | zipStorePath=wrapper/dists 6 | zipStoreBase=GRADLE_USER_HOME 7 | -------------------------------------------------------------------------------- /sample-local/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /sample-local/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /sample-network/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /sample-network/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /sample-local/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /sample-network/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /sample-local/src/test/java/com/pdfview_sample/pdfview/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package com.pdfview_sample.pdfview 2 | 3 | import org.junit.Test 4 | 5 | import org.junit.Assert.* 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * See [testing documentation](http://d.android.com/tools/testing). 11 | */ 12 | class ExampleUnitTest { 13 | @Test 14 | fun addition_isCorrect() { 15 | assertEquals(4, 2 + 2) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /pdfview-android/src/main/res/values/attrs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /sample-local/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 12 | 13 | -------------------------------------------------------------------------------- /sample-network/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 12 | 13 | -------------------------------------------------------------------------------- /pdfview-android/src/main/java/com/pdfview/FileUtils.kt: -------------------------------------------------------------------------------- 1 | package com.pdfview 2 | 3 | import android.content.Context 4 | import java.io.File 5 | import java.io.IOException 6 | 7 | internal object FileUtils { 8 | 9 | @Throws(IOException::class) 10 | fun fileFromAsset(context: Context, assetFileName: String): File { 11 | val outFile = File(context.cacheDir, "$assetFileName-pdfview.pdf") 12 | if (assetFileName.contains("/")) { 13 | outFile.parentFile.mkdirs() 14 | } 15 | context.assets.open(assetFileName).copyTo(outFile.outputStream()) 16 | return outFile 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /sample-network/src/main/java/com/pdfview_network_sample/pdfview/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.pdfview_network_sample.pdfview 2 | 3 | import android.os.Bundle 4 | import androidx.activity.viewModels 5 | import androidx.appcompat.app.AppCompatActivity 6 | import androidx.core.net.toFile 7 | import androidx.lifecycle.observe 8 | import com.pdfview.PDFView 9 | 10 | class MainActivity : AppCompatActivity() { 11 | 12 | private val pdfViewModel: PdfViewModel by viewModels { PdfViewModelFactory(applicationContext) } 13 | 14 | override fun onCreate(savedInstanceState: Bundle?) { 15 | super.onCreate(savedInstanceState) 16 | setContentView(R.layout.activity_main) 17 | pdfViewModel.getLoadedFile().observe(this) { uri -> 18 | findViewById(R.id.activity_main_pdf_view).fromFile(uri.toFile()).show() 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx1536m 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | android.useAndroidX=true 15 | android.enableJetifier=true 16 | 17 | -------------------------------------------------------------------------------- /sample-local/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /sample-network/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /sample-local/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 12 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /maven-scripts/publish-root.gradle: -------------------------------------------------------------------------------- 1 | 2 | 3 | // Set up Sonatype repository 4 | nexusPublishing { 5 | repositories { 6 | sonatype { 7 | stagingProfileId = SONATYPE_STAGING_PROFILE_ID 8 | username = OSSRH_USERNAME 9 | password = OSSRH_PASSWORD 10 | } 11 | } 12 | } 13 | 14 | 15 | //version = libraryVersion 16 | 17 | //if (project.hasProperty("android")) { 18 | // task sourcesJar(type: Jar) { 19 | // classifier = 'sources' 20 | // from android.sourceSets.main.java.srcDirs 21 | // } 22 | //} else { 23 | // task sourcesJar(type: Jar, dependsOn: classes) { 24 | // classifier = 'sources' 25 | // from sourceSets.main.allSource 26 | // } 27 | //} 28 | 29 | //bintrayUpload.dependsOn install 30 | //bintrayUpload.dependsOn sourcesJar 31 | 32 | //artifacts { 33 | // archives sourcesJar 34 | //} 35 | 36 | -------------------------------------------------------------------------------- /pdfview-android/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'kotlin-android' 3 | apply from: "$rootDir/maven-scripts/info.gradle" 4 | 5 | // to upload to bintray use ./gradlew build bintrayUpload 6 | android { 7 | compileSdkVersion versions.compileSdk 8 | 9 | defaultConfig { 10 | minSdkVersion versions.minSdk 11 | targetSdkVersion versions.targetSdk 12 | } 13 | 14 | compileOptions { 15 | sourceCompatibility JavaVersion.VERSION_11 16 | targetCompatibility JavaVersion.VERSION_11 17 | } 18 | 19 | kotlinOptions { 20 | jvmTarget = "11" 21 | } 22 | 23 | } 24 | 25 | dependencies { 26 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:${versions.kotlin}" 27 | implementation 'androidx.annotation:annotation:1.3.0' 28 | } 29 | 30 | apply from: "$rootDir/maven-scripts/publish-module.gradle" 31 | -------------------------------------------------------------------------------- /sample-local/src/androidTest/java/com/pdfview_sample/pdfview/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package com.pdfview_sample.pdfview 2 | 3 | import androidx.test.ext.junit.runners.AndroidJUnit4 4 | import androidx.test.platform.app.InstrumentationRegistry 5 | import org.junit.Assert.assertEquals 6 | import org.junit.Test 7 | import org.junit.runner.RunWith 8 | 9 | import org.junit.Assert.* 10 | 11 | /** 12 | * Instrumented test, which will execute on an Android device. 13 | * 14 | * See [testing documentation](http://d.android.com/tools/testing). 15 | */ 16 | @RunWith(AndroidJUnit4::class) 17 | class ExampleInstrumentedTest { 18 | @Test 19 | fun useAppContext() { 20 | // Context of the app under test. 21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext 22 | assertEquals("com.pdfview_sample.pdfview", appContext.packageName) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /sample-network/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 14 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /pdfview-android/src/main/java/com/pdfview/subsamplincscaleimageview/decoder/DecoderFactory.java: -------------------------------------------------------------------------------- 1 | package com.pdfview.subsamplincscaleimageview.decoder; 2 | 3 | import androidx.annotation.NonNull; 4 | 5 | import java.lang.reflect.InvocationTargetException; 6 | 7 | /** 8 | * Interface for {@link ImageDecoder} and {@link ImageRegionDecoder} factories. 9 | * @param the class of decoder that will be produced. 10 | */ 11 | public interface DecoderFactory { 12 | 13 | /** 14 | * Produce a new instance of a decoder with type {@link T}. 15 | * @return a new instance of your decoder. 16 | * @throws IllegalAccessException if the factory class cannot be instantiated. 17 | * @throws InstantiationException if the factory class cannot be instantiated. 18 | * @throws NoSuchMethodException if the factory class cannot be instantiated. 19 | * @throws InvocationTargetException if the factory class cannot be instantiated. 20 | */ 21 | @NonNull T make() throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException; 22 | 23 | } 24 | -------------------------------------------------------------------------------- /pdfview-android/src/main/java/com/pdfview/subsamplincscaleimageview/decoder/ImageDecoder.java: -------------------------------------------------------------------------------- 1 | package com.pdfview.subsamplincscaleimageview.decoder; 2 | 3 | import android.content.Context; 4 | import android.graphics.Bitmap; 5 | import android.net.Uri; 6 | import androidx.annotation.NonNull; 7 | 8 | /** 9 | * Interface for image decoding classes, allowing the default {@link android.graphics.BitmapFactory} 10 | * based on the Skia library to be replaced with a custom class. 11 | */ 12 | public interface ImageDecoder { 13 | 14 | /** 15 | * Decode an image. The URI can be in one of the following formats: 16 | *
17 | * File: file:///scard/picture.jpg 18 | *
19 | * Asset: file:///android_asset/picture.png 20 | *
21 | * Resource: android.resource://com.example.app/drawable/picture 22 | * 23 | * @param context Application context 24 | * @param uri URI of the image 25 | * @return the decoded bitmap 26 | * @throws Exception if decoding fails. 27 | */ 28 | @NonNull Bitmap decode(Context context, @NonNull Uri uri) throws Exception; 29 | 30 | } 31 | -------------------------------------------------------------------------------- /pdfview-android/src/main/java/com/pdfview/subsamplincscaleimageview/ImageViewState.java: -------------------------------------------------------------------------------- 1 | package com.pdfview.subsamplincscaleimageview; 2 | 3 | import android.graphics.PointF; 4 | import androidx.annotation.NonNull; 5 | 6 | import java.io.Serializable; 7 | 8 | /** 9 | * Wraps the scale, center and orientation of a displayed image for easy restoration on screen rotate. 10 | */ 11 | @SuppressWarnings("WeakerAccess") 12 | public class ImageViewState implements Serializable { 13 | 14 | private final float scale; 15 | 16 | private final float centerX; 17 | 18 | private final float centerY; 19 | 20 | private final int orientation; 21 | 22 | public ImageViewState(float scale, @NonNull PointF center, int orientation) { 23 | this.scale = scale; 24 | this.centerX = center.x; 25 | this.centerY = center.y; 26 | this.orientation = orientation; 27 | } 28 | 29 | public float getScale() { 30 | return scale; 31 | } 32 | 33 | @NonNull public PointF getCenter() { 34 | return new PointF(centerX, centerY); 35 | } 36 | 37 | public int getOrientation() { 38 | return orientation; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /sample-local/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: 'kotlin-android' 3 | 4 | android { 5 | compileSdkVersion 32 6 | defaultConfig { 7 | applicationId "com.pdfview_sample.sample" 8 | minSdkVersion 21 9 | targetSdkVersion 32 10 | versionCode 1 11 | versionName "1.0" 12 | testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' 13 | } 14 | 15 | compileOptions { 16 | sourceCompatibility JavaVersion.VERSION_11 17 | targetCompatibility JavaVersion.VERSION_11 18 | } 19 | 20 | kotlinOptions { 21 | jvmTarget = "11" 22 | } 23 | 24 | buildTypes { 25 | release { 26 | minifyEnabled false 27 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 28 | } 29 | } 30 | } 31 | 32 | dependencies { 33 | implementation 'com.dmitryborodin:pdfview-android:1.1.0' 34 | // implementation project(':pdfview-android') 35 | implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk8:$versions.kotlin" 36 | implementation 'androidx.appcompat:appcompat:1.4.1' 37 | implementation 'androidx.constraintlayout:constraintlayout:2.1.3' 38 | testImplementation 'junit:junit:4.13.2' 39 | androidTestImplementation 'androidx.test.ext:junit:1.1.3' 40 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' 41 | } 42 | -------------------------------------------------------------------------------- /pdfview-android/src/main/java/com/pdfview/PDFView.kt: -------------------------------------------------------------------------------- 1 | package com.pdfview 2 | 3 | import android.content.Context 4 | import android.util.AttributeSet 5 | import com.pdfview.subsamplincscaleimageview.ImageSource 6 | import com.pdfview.subsamplincscaleimageview.SubsamplingScaleImageView 7 | import java.io.File 8 | 9 | class PDFView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : SubsamplingScaleImageView(context, attrs) { 10 | 11 | private var mfile: File? = null 12 | private var mScale: Float = 8f 13 | 14 | init { 15 | setMinimumTileDpi(120) 16 | setMinimumScaleType(SubsamplingScaleImageView.SCALE_TYPE_START) 17 | } 18 | 19 | fun fromAsset(assetFileName: String): PDFView { 20 | mfile = FileUtils.fileFromAsset(context, assetFileName) 21 | return this 22 | } 23 | 24 | fun fromFile(file: File): PDFView { 25 | mfile = file 26 | return this 27 | } 28 | 29 | fun fromFile(filePath: String): PDFView { 30 | mfile = File(filePath) 31 | return this 32 | } 33 | 34 | fun scale(scale: Float): PDFView { 35 | mScale = scale 36 | return this 37 | } 38 | 39 | fun show() { 40 | val source = ImageSource.uri(mfile!!.path) 41 | setRegionDecoderFactory { PDFRegionDecoder(view = this, file = mfile!!, scale = mScale) } 42 | setImage(source) 43 | } 44 | 45 | override fun onDetachedFromWindow() { 46 | super.onDetachedFromWindow() 47 | this.recycle() 48 | } 49 | } -------------------------------------------------------------------------------- /sample-network/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: 'kotlin-android' 3 | 4 | android { 5 | compileSdkVersion 32 6 | defaultConfig { 7 | applicationId "com.pdfview_sample.sample" 8 | minSdkVersion 21 9 | targetSdkVersion 32 10 | versionCode 1 11 | versionName "1.0" 12 | testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' 13 | } 14 | 15 | compileOptions { 16 | sourceCompatibility JavaVersion.VERSION_11 17 | targetCompatibility JavaVersion.VERSION_11 18 | } 19 | 20 | kotlinOptions { 21 | jvmTarget = "11" 22 | } 23 | 24 | buildTypes { 25 | release { 26 | minifyEnabled false 27 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 28 | } 29 | } 30 | } 31 | 32 | dependencies { 33 | // implementation 'com.pdfview:pdfview-android:1.0.0' 34 | implementation project(':pdfview-android') 35 | implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk8:$versions.kotlin" 36 | implementation 'androidx.appcompat:appcompat:1.4.1' 37 | //this provides toUri(), by viewModel and other extensions 38 | implementation "androidx.fragment:fragment-ktx:1.4.1" 39 | 40 | implementation 'com.squareup.okhttp3:okhttp:4.7.2' 41 | 42 | testImplementation 'junit:junit:4.13.2' 43 | androidTestImplementation 'androidx.test.ext:junit:1.1.3' 44 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' 45 | } 46 | -------------------------------------------------------------------------------- /maven-scripts/info.gradle: -------------------------------------------------------------------------------- 1 | ext { 2 | libraryVersion = '1.1.0' 3 | 4 | libraryName = 'pdfview-android' 5 | publishedGroupId = 'com.dmitryborodin' 6 | artifactId = 'pdfview-android' 7 | 8 | libraryDescription = 'Small library to show PDF files in your native android application' 9 | 10 | siteUrl = 'https://github.com/Dmitry-Borodin/pdfview' 11 | gitUrl = 'https://github.com/Dmitry-Borodin/pdfview' 12 | gitConnection = 'scm:git:github.com/Dmitry-Borodin/pdfview.git' 13 | gitDeveloperConnection = 'scm:git:ssh://github.com/Dmitry-Borodin/pdfview.git' 14 | 15 | developerId = 'Dmitry-Borodin' 16 | developerName = 'Dmitry Borodin' 17 | developerEmail = 'pdfview@DmitryBorodin.com' 18 | 19 | licenseName = 'Apache-2.0' 20 | licenseUrl = 'https://www.apache.org/licenses/LICENSE-2.0.html' 21 | allLicenses = ["Apache-2.0"] 22 | 23 | File secretPropsFile = project.rootProject.file('local.properties') 24 | if (secretPropsFile.exists()) { 25 | // Read local.properties file first if it exists 26 | Properties p = new Properties() 27 | new FileInputStream(secretPropsFile).withCloseable { is -> p.load(is) } 28 | p.each { name, value -> ext[name] = value } 29 | } else { 30 | // Use system environment variables 31 | OSSRH_USERNAME = System.getenv('OSSRH_USERNAME') 32 | OSSRH_PASSWORD = System.getenv('OSSRH_PASSWORD') 33 | SONATYPE_STAGING_PROFILE_ID = System.getenv('SONATYPE_STAGING_PROFILE_ID') 34 | SIGNING_KEY_ID = System.getenv('SIGNING_KEY_ID') 35 | SIGNING_PASSWORD = System.getenv('SIGNING_PASSWORD') 36 | SIGNING_KEY = System.getenv('SIGNING_KEY') 37 | } 38 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ### Android ### 2 | # from Stackoverflow 3 | # Built application files 4 | *.apk 5 | *.ap_ 6 | 7 | # Files for the Dalvik VM 8 | *.dex 9 | 10 | # Java class files 11 | *.class 12 | 13 | # Generated files 14 | bin/ 15 | gen/ 16 | 17 | # Gradle files 18 | .gradle/ 19 | build/ 20 | 21 | # Local configuration file (sdk path, etc) 22 | local.properties 23 | 24 | # Proguard folder generated by Eclipse 25 | proguard/ 26 | 27 | # Log Files 28 | *.log 29 | 30 | # Android Studio Navigation editor temp files 31 | .navigation/ 32 | 33 | ### Android Patch ### 34 | gen-external-apklibs 35 | 36 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 37 | hs_err_pid* 38 | 39 | ### Intellij ### 40 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio 41 | 42 | *.iml 43 | 44 | ## Directory-based project format: 45 | .idea/ 46 | # if you remove the above rule, at least ignore the following: 47 | 48 | # User-specific stuff: 49 | # .idea/workspace.xml 50 | # .idea/tasks.xml 51 | # .idea/dictionaries 52 | 53 | # Sensitive or high-churn files: 54 | # .idea/dataSources.ids 55 | # .idea/dataSources.xml 56 | # .idea/sqlDataSources.xml 57 | # .idea/dynamic.xml 58 | # .idea/uiDesigner.xml 59 | 60 | # Gradle: 61 | # .idea/gradle.xml 62 | # .idea/libraries 63 | 64 | # Mongo Explorer plugin: 65 | # .idea/mongoSettings.xml 66 | 67 | ## File-based project format: 68 | *.ipr 69 | *.iws 70 | 71 | ## Plugin-specific files: 72 | 73 | # IntelliJ 74 | /out/ 75 | /captures 76 | 77 | # mpeltonen/sbt-idea plugin 78 | .idea_modules/ 79 | 80 | # JIRA plugin 81 | atlassian-ide-plugin.xml 82 | 83 | # Crashlytics plugin (for Android Studio and IntelliJ) 84 | com_crashlytics_export_strings.xml 85 | crashlytics.properties 86 | crashlytics-build.properties -------------------------------------------------------------------------------- /pdfview-android/src/main/java/com/pdfview/subsamplincscaleimageview/decoder/CompatDecoderFactory.java: -------------------------------------------------------------------------------- 1 | package com.pdfview.subsamplincscaleimageview.decoder; 2 | 3 | import android.graphics.Bitmap; 4 | import androidx.annotation.NonNull; 5 | 6 | import java.lang.reflect.Constructor; 7 | import java.lang.reflect.InvocationTargetException; 8 | 9 | /** 10 | * Compatibility factory to instantiate decoders with empty public constructors. 11 | * @param The base type of the decoder this factory will produce. 12 | */ 13 | @SuppressWarnings("WeakerAccess") 14 | public class CompatDecoderFactory implements DecoderFactory { 15 | 16 | private final Class clazz; 17 | private final Bitmap.Config bitmapConfig; 18 | 19 | /** 20 | * Construct a factory for the given class. This must have a default constructor. 21 | * @param clazz a class that implements {@link ImageDecoder} or {@link ImageRegionDecoder}. 22 | */ 23 | public CompatDecoderFactory(@NonNull Class clazz) { 24 | this(clazz, null); 25 | } 26 | 27 | /** 28 | * Construct a factory for the given class. This must have a constructor that accepts a {@link Bitmap.Config} instance. 29 | * @param clazz a class that implements {@link ImageDecoder} or {@link ImageRegionDecoder}. 30 | * @param bitmapConfig bitmap configuration to be used when loading images. 31 | */ 32 | public CompatDecoderFactory(@NonNull Class clazz, Bitmap.Config bitmapConfig) { 33 | this.clazz = clazz; 34 | this.bitmapConfig = bitmapConfig; 35 | } 36 | 37 | @Override 38 | @NonNull 39 | public T make() throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { 40 | if (bitmapConfig == null) { 41 | return clazz.newInstance(); 42 | } else { 43 | Constructor ctor = clazz.getConstructor(Bitmap.Config.class); 44 | return ctor.newInstance(bitmapConfig); 45 | } 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /sample-local/src/main/java/com/pdfview_sample/pdfview/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.pdfview_sample.pdfview 2 | 3 | import android.content.DialogInterface 4 | import android.os.Bundle 5 | import androidx.appcompat.app.AlertDialog 6 | import androidx.appcompat.app.AppCompatActivity 7 | import com.pdfview.PDFView 8 | import com.pdfview.subsamplincscaleimageview.SubsamplingScaleImageView 9 | import java.io.File 10 | 11 | class MainActivity : AppCompatActivity() { 12 | 13 | override fun onCreate(savedInstanceState: Bundle?) { 14 | super.onCreate(savedInstanceState) 15 | setContentView(R.layout.activity_main) 16 | 17 | val view = findViewById(R.id.activity_main_pdf_view) 18 | view.setPanLimit(SubsamplingScaleImageView.PAN_LIMIT_OUTSIDE) 19 | //view.setDebug(true) 20 | 21 | // Place some pdf files to /storage/emulated/0/Android/data/com.pdfview_sample.sample/files 22 | // to try them all. A dialog with the list of files will be displayed. 23 | // Otherwise an internal file will be displayed 24 | 25 | getExternalFilesDir(null)?.mkdirs() // create a folder for the first run 26 | val pdfs: Array = getExternalFilesDir(null)?.listFiles { _: File?, name: String -> name.endsWith(".pdf") } 27 | ?: emptyArray() 28 | 29 | val list = mutableListOf() 30 | pdfs.forEach { list.add(it.name) } 31 | 32 | if (list.size > 0) { 33 | AlertDialog.Builder(this) 34 | .setTitle("List of files") 35 | .setItems(list.toTypedArray()) { _: DialogInterface?, item: Int -> 36 | view.fromFile(File(getExternalFilesDir(null), list[item])) 37 | view.show() 38 | } 39 | .show() 40 | } else { 41 | view.fromAsset("great-expectations.pdf") 42 | view.show() 43 | } 44 | 45 | // findViewById(R.id.activity_main_pdf_view).fromAsset("paper.pdf").show() 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /sample-local/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /sample-network/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pdfview 2 | 3 | [![Build Status](https://app.bitrise.io/app/40d453ac50882d9c/status.svg?token=BfV89EoWjOEfvATradLDOw&branch=dev)](https://app.bitrise.io/app/40d453ac50882d9c) 4 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.dmitryborodin/pdfview-android/badge.svg?style=plastic)](https://maven-badges.herokuapp.com/maven-central/com.dmitryborodin/pdfview-android) 5 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 6 | [![Android Arsenal]( https://img.shields.io/badge/Android%20Arsenal-PdfView--Android-green.svg?style=flat )]( https://android-arsenal.com/details/1/7820 ) 7 | 8 | Android PDF view - small (73kB .aar file, ~400 methods before minification) and efficient PDF viewer embedded in your native app 9 | 10 | It is based on ImageView and can handle big files with reasonable scrolling and zooming performance. 11 | 12 | This is how fast scrolling of 680 page document looks like on low-end device: 13 | 14 | ![Example1](gifs/fast_scrolling_on_weak_device.gif) 15 | 16 | ## Usage: 17 | 18 | To show pdf you just need a file on the device. 19 | 20 | ``` 21 | findViewById(R.id.activityMainPdfView).fromAsset("paper.pdf").show() 22 | ``` 23 | See [sources](/pdfview-android/src/main/java/com/pdfview/PDFView.kt) for other methods to provide a file. 24 | 25 | If pdf is on remote host - use your network client to download it to the cache folder, then show it. This library provides view, it doesn't do network requests. 26 | 27 | There is a [sample](/sample-network) of how to do it. 28 | 29 | ## Add to your project: 30 | 31 | The library is hosted in the central repository. 32 | ``` 33 | repositories { 34 | <...> 35 | mavenCentral() 36 | } 37 | ``` 38 | 39 | Add gradle dependency: 40 | ``` 41 | implementation "com.dmitryborodin:pdfview-android:1.1.0" 42 | ``` 43 | 44 | ## Wiki 45 | Please take a look into [the wiki](/../../wiki) to find out the technical details. 46 | 47 | ## Contrubitions 48 | 49 | Contributions are welcome. 50 | Just open PR to dev branch. 51 | 52 | Feel free to open issue with any questions. 53 | 54 | ## Credits 55 | Thanks to [Manuel Lilienberg](https://github.com/mlilienberg) for initial implementation of this library and [subsampling-scale library](https://github.com/davemorrissey/subsampling-scale-image-view) for influence. 56 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /maven-scripts/publish-module.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'maven-publish' 2 | apply plugin: 'signing' 3 | apply plugin: 'org.jetbrains.dokka' 4 | 5 | task androidSourcesJar(type: Jar) { 6 | archiveClassifier.set('sources') 7 | if (project.plugins.findPlugin("com.android.library")) { 8 | from android.sourceSets.main.java.srcDirs 9 | from android.sourceSets.main.kotlin.srcDirs 10 | } else { 11 | from sourceSets.main.java.srcDirs 12 | from sourceSets.main.kotlin.srcDirs 13 | } 14 | } 15 | 16 | tasks.withType(dokkaHtmlPartial.getClass()).configureEach { 17 | pluginsMapConfiguration.set( 18 | ["org.jetbrains.dokka.base.DokkaBase": """{ "separateInheritedMembers": true}"""] 19 | ) 20 | } 21 | 22 | task javadocJar(type: Jar, dependsOn: dokkaJavadoc) { 23 | archiveClassifier.set('javadoc') 24 | from dokkaJavadoc.outputDirectory 25 | } 26 | 27 | artifacts { 28 | archives androidSourcesJar 29 | archives javadocJar 30 | } 31 | 32 | group = publishedGroupId 33 | version = libraryVersion 34 | 35 | afterEvaluate { 36 | publishing { 37 | publications { 38 | release(MavenPublication) { 39 | groupId publishedGroupId 40 | artifactId artifactId 41 | version libraryVersion 42 | if (project.plugins.findPlugin("com.android.library")) { 43 | from components.release 44 | } else { 45 | from components.java 46 | } 47 | 48 | artifact androidSourcesJar 49 | artifact javadocJar 50 | 51 | pom { 52 | name = artifactId 53 | description = libraryDescription 54 | url = siteUrl 55 | licenses { 56 | license { 57 | name = licenseName 58 | url = licenseUrl 59 | } 60 | } 61 | developers { 62 | developer { 63 | id = developerId 64 | name = developerName 65 | email = developerEmail 66 | } 67 | } 68 | scm { 69 | connection = gitConnection 70 | developerConnection = gitDeveloperConnection 71 | url = gitConnection 72 | } 73 | } 74 | } 75 | } 76 | } 77 | } 78 | 79 | signing { 80 | useInMemoryPgpKeys( 81 | SIGNING_KEY_ID, 82 | SIGNING_KEY, 83 | SIGNING_PASSWORD, 84 | ) 85 | sign publishing.publications 86 | } 87 | -------------------------------------------------------------------------------- /pdfview-android/src/main/java/com/pdfview/subsamplincscaleimageview/decoder/ImageRegionDecoder.java: -------------------------------------------------------------------------------- 1 | package com.pdfview.subsamplincscaleimageview.decoder; 2 | 3 | import android.content.Context; 4 | import android.graphics.Bitmap; 5 | import android.graphics.Point; 6 | import android.graphics.Rect; 7 | import android.net.Uri; 8 | import androidx.annotation.NonNull; 9 | 10 | /** 11 | * Interface for image decoding classes, allowing the default {@link android.graphics.BitmapRegionDecoder} 12 | * based on the Skia library to be replaced with a custom class. 13 | */ 14 | public interface ImageRegionDecoder { 15 | 16 | /** 17 | * Initialise the decoder. When possible, perform initial setup work once in this method. The 18 | * dimensions of the image must be returned. The URI can be in one of the following formats: 19 | *
20 | * File: file:///scard/picture.jpg 21 | *
22 | * Asset: file:///android_asset/picture.png 23 | *
24 | * Resource: android.resource://com.example.app/drawable/picture 25 | * @param context Application context. A reference may be held, but must be cleared on recycle. 26 | * @param uri URI of the image. 27 | * @return Dimensions of the image. 28 | * @throws Exception if initialisation fails. 29 | */ 30 | @NonNull Point init(Context context, @NonNull Uri uri) throws Exception; 31 | 32 | /** 33 | *

34 | * Decode a region of the image with the given sample size. This method is called off the UI 35 | * thread so it can safely load the image on the current thread. It is called from 36 | * {@link android.os.AsyncTask}s running in an executor that may have multiple threads, so 37 | * implementations must be thread safe. Adding synchronized to the method signature 38 | * is the simplest way to achieve this, but bear in mind the {@link #recycle()} method can be 39 | * called concurrently. 40 | *

41 | * See {@link SkiaImageRegionDecoder} and {@link SkiaPooledImageRegionDecoder} for examples of 42 | * internal locking and synchronization. 43 | *

44 | * @param sRect Source image rectangle to decode. 45 | * @param sampleSize Sample size. 46 | * @return The decoded region. It is safe to return null if decoding fails. 47 | */ 48 | @NonNull Bitmap decodeRegion(@NonNull Rect sRect, int sampleSize); 49 | 50 | /** 51 | * Status check. Should return false before initialisation and after recycle. 52 | * @return true if the decoder is ready to be used. 53 | */ 54 | boolean isReady(); 55 | 56 | /** 57 | * This method will be called when the decoder is no longer required. It should clean up any resources still in use. 58 | */ 59 | void recycle(); 60 | 61 | } 62 | -------------------------------------------------------------------------------- /pdfview-android/src/main/java/com/pdfview/PDFRegionDecoder.kt: -------------------------------------------------------------------------------- 1 | package com.pdfview 2 | 3 | import android.content.Context 4 | import android.graphics.* 5 | import android.graphics.pdf.PdfRenderer 6 | import android.net.Uri 7 | import android.os.ParcelFileDescriptor 8 | import androidx.annotation.ColorInt 9 | import com.pdfview.subsamplincscaleimageview.SubsamplingScaleImageView.SCALE_TYPE_CENTER_INSIDE 10 | import com.pdfview.subsamplincscaleimageview.decoder.ImageRegionDecoder 11 | import java.io.File 12 | 13 | internal class PDFRegionDecoder(private val view: PDFView, 14 | private val file: File, 15 | private val scale: Float, 16 | @param:ColorInt private val backgroundColorPdf: Int = Color.WHITE) : ImageRegionDecoder { 17 | 18 | private lateinit var descriptor: ParcelFileDescriptor 19 | private lateinit var renderer: PdfRenderer 20 | private var pageWidth = 0 21 | private var pageHeight = 0 22 | 23 | @Throws(Exception::class) 24 | override fun init(context: Context, uri: Uri): Point { 25 | descriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY) 26 | renderer = PdfRenderer(descriptor) 27 | val page = renderer.openPage(0) 28 | pageWidth = (page.width * scale).toInt() 29 | pageHeight = (page.height * scale).toInt() 30 | if (renderer.pageCount > 15) { 31 | view.setHasBaseLayerTiles(false) 32 | } else if (renderer.pageCount == 1) { 33 | view.setMinimumScaleType(SCALE_TYPE_CENTER_INSIDE) 34 | } 35 | page.close() 36 | return Point(pageWidth,pageHeight * renderer.pageCount) 37 | } 38 | 39 | override fun decodeRegion(rect: Rect, sampleSize: Int): Bitmap { 40 | val numPageAtStart = Math.floor(rect.top.toDouble() / pageHeight).toInt() 41 | val numPageAtEnd = Math.ceil(rect.bottom.toDouble() / pageHeight).toInt() - 1 42 | val bitmap = Bitmap.createBitmap(rect.width() / sampleSize, rect.height() / sampleSize, Bitmap.Config.ARGB_8888) 43 | val canvas = Canvas(bitmap) 44 | canvas.drawColor(backgroundColorPdf) 45 | canvas.drawBitmap(bitmap, 0f, 0f, null) 46 | for ((iteration, pageIndex) in (numPageAtStart..numPageAtEnd).withIndex()) { 47 | synchronized(renderer) { 48 | val page = renderer.openPage(pageIndex) 49 | val matrix = Matrix() 50 | matrix.setScale(scale / sampleSize, scale / sampleSize) 51 | matrix.postTranslate( 52 | (-rect.left / sampleSize).toFloat(), -((rect.top - pageHeight * numPageAtStart) / sampleSize).toFloat() + (pageHeight.toFloat() / sampleSize) * iteration) 53 | page.render(bitmap,null, matrix, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY) 54 | page.close() 55 | } 56 | } 57 | return bitmap 58 | } 59 | 60 | override fun isReady(): Boolean { 61 | return pageWidth > 0 && pageHeight > 0 62 | } 63 | 64 | override fun recycle() { 65 | renderer.close() 66 | descriptor.close() 67 | pageWidth = 0 68 | pageHeight = 0 69 | } 70 | } -------------------------------------------------------------------------------- /sample-network/src/main/java/com/pdfview_network_sample/pdfview/PdfViewModel.kt: -------------------------------------------------------------------------------- 1 | package com.pdfview_network_sample.pdfview 2 | 3 | import android.content.Context 4 | import android.net.Uri 5 | import android.os.Handler 6 | import android.os.Looper 7 | import androidx.annotation.MainThread 8 | import androidx.core.net.toUri 9 | import androidx.lifecycle.LiveData 10 | import androidx.lifecycle.MutableLiveData 11 | import androidx.lifecycle.ViewModel 12 | import androidx.lifecycle.ViewModelProvider 13 | import okhttp3.Call 14 | import okhttp3.Callback 15 | import okhttp3.OkHttpClient 16 | import okhttp3.Request 17 | import okhttp3.Response 18 | import java.io.BufferedInputStream 19 | import java.io.File 20 | import java.io.FileOutputStream 21 | import java.io.IOException 22 | import java.io.OutputStream 23 | 24 | /** 25 | * Provides path to a file when it's downloading and surviving view lifecycle 26 | * 27 | * @author Dmitry Borodin on 7/17/20. 28 | */ 29 | 30 | const val REMOTE_PDF_URL = "https://github.com/Dmitry-Borodin/pdfview-android/raw/dev/sample-local/src/main/assets/great-expectations.pdf" 31 | const val PDF_CACHED_FILE_NAME = "mypdf.pdf" 32 | 33 | class PdfViewModel(private val cacheDir: File) : ViewModel() { 34 | 35 | /** 36 | * Used to avoid starting another download while first one is in progress. It shouldn't happen anyway, 37 | * but I would like to be sure, even after modification. 38 | * 39 | * If downloading with coroutines we can just keep reference to Job and check if it's active, then we won't need to set it to false. 40 | */ 41 | private var inProgress = false //should be used from main thread only 42 | 43 | private val pdfPath: MutableLiveData = MutableLiveData() 44 | 45 | init { 46 | loadPdf() 47 | } 48 | 49 | fun getLoadedFile(): LiveData { 50 | return pdfPath 51 | } 52 | 53 | /** 54 | * No synchronization is used for local variables since we call it only from main thread anyway 55 | */ 56 | @MainThread 57 | private fun loadPdf() { 58 | 59 | //if currently saving file to disk - Livedata will be updated later, just wait 60 | if (inProgress) return 61 | inProgress = true 62 | 63 | val pdf = File(cacheDir, PDF_CACHED_FILE_NAME) 64 | if (pdf.exists() && pdf.canRead()) { 65 | //file already in a cache - just show it 66 | pdfPath.value = pdf.toUri() 67 | inProgress = false 68 | return 69 | } 70 | 71 | // If your pdf may be changed and backend controling it - http mechanics are recommeneded for caching 72 | // This will cause additional network traffic and additional alignment with backend reqired to make sure proper http headers setup on a backend for OkHTTP cache to work properly 73 | // Then always get response from OkHttp after initialization 74 | // 10Mb - make sure PDf will fit 75 | // val cacheSize = 10L * 1024 * 1024 76 | // probably don't use default cache folder to not mix this cache with your usual REST responses cache - this file may not be requestet often, but it's big 77 | // val cacheDirectory = File(cacheDir.toURI()) 78 | // val cache = Cache(cacheDirectory, cacheSize) 79 | // val client = OkHttpClient.Builder() 80 | // .cache(cache) 81 | // .build() 82 | 83 | val client = OkHttpClient.Builder().build() 84 | val request = Request.Builder().url(REMOTE_PDF_URL).build() 85 | client.newCall(request).enqueue(object : Callback { 86 | override fun onFailure(call: Call, e: IOException) { 87 | //show error state and send analytics report? 88 | Handler(Looper.getMainLooper()).post { 89 | inProgress = false 90 | } 91 | 92 | } 93 | 94 | override fun onResponse(call: Call, response: Response) { 95 | if (!response.isSuccessful) { 96 | //show error state and send analytics report? 97 | Handler(Looper.getMainLooper()).post { 98 | inProgress = false 99 | } 100 | return 101 | } 102 | val result = File(cacheDir, PDF_CACHED_FILE_NAME) 103 | val body = response.body!! 104 | val inputStream = body.byteStream() 105 | val input = BufferedInputStream(inputStream) 106 | val output: OutputStream = FileOutputStream(result) 107 | input.copyTo(output) 108 | output.flush(); 109 | output.close(); 110 | input.close(); //will closing just body is enough?? 111 | body.close(); 112 | 113 | //Update 114 | Handler(Looper.getMainLooper()).post { 115 | pdfPath.value = result.toUri() 116 | inProgress = false 117 | } 118 | } 119 | }) 120 | } 121 | } 122 | 123 | class PdfViewModelFactory(private val appContext: Context) : ViewModelProvider.NewInstanceFactory() { 124 | override fun create(modelClass: Class): T = PdfViewModel(appContext.cacheDir) as T 125 | } -------------------------------------------------------------------------------- /pdfview-android/src/main/java/com/pdfview/subsamplincscaleimageview/decoder/SkiaImageDecoder.java: -------------------------------------------------------------------------------- 1 | package com.pdfview.subsamplincscaleimageview.decoder; 2 | 3 | import android.content.ContentResolver; 4 | import android.content.Context; 5 | import android.content.pm.PackageManager; 6 | import android.content.res.Resources; 7 | import android.graphics.Bitmap; 8 | import android.graphics.BitmapFactory; 9 | import android.net.Uri; 10 | import androidx.annotation.Keep; 11 | import androidx.annotation.NonNull; 12 | import androidx.annotation.Nullable; 13 | import android.text.TextUtils; 14 | 15 | 16 | import com.pdfview.subsamplincscaleimageview.SubsamplingScaleImageView; 17 | 18 | import java.io.InputStream; 19 | import java.util.List; 20 | 21 | /** 22 | * Default implementation of {@link ImageDecoder} 23 | * using Android's {@link BitmapFactory}, based on the Skia library. This 24 | * works well in most circumstances and has reasonable performance, however it has some problems 25 | * with grayscale, indexed and CMYK images. 26 | */ 27 | public class SkiaImageDecoder implements ImageDecoder { 28 | 29 | private static final String FILE_PREFIX = "file://"; 30 | private static final String ASSET_PREFIX = FILE_PREFIX + "/android_asset/"; 31 | private static final String RESOURCE_PREFIX = ContentResolver.SCHEME_ANDROID_RESOURCE + "://"; 32 | 33 | private final Bitmap.Config bitmapConfig; 34 | 35 | @Keep 36 | @SuppressWarnings("unused") 37 | public SkiaImageDecoder() { 38 | this(null); 39 | } 40 | 41 | @SuppressWarnings({"WeakerAccess", "SameParameterValue"}) 42 | public SkiaImageDecoder(@Nullable Bitmap.Config bitmapConfig) { 43 | Bitmap.Config globalBitmapConfig = SubsamplingScaleImageView.getPreferredBitmapConfig(); 44 | if (bitmapConfig != null) { 45 | this.bitmapConfig = bitmapConfig; 46 | } else if (globalBitmapConfig != null) { 47 | this.bitmapConfig = globalBitmapConfig; 48 | } else { 49 | this.bitmapConfig = Bitmap.Config.RGB_565; 50 | } 51 | } 52 | 53 | @Override 54 | @NonNull 55 | public Bitmap decode(Context context, @NonNull Uri uri) throws Exception { 56 | String uriString = uri.toString(); 57 | BitmapFactory.Options options = new BitmapFactory.Options(); 58 | Bitmap bitmap; 59 | options.inPreferredConfig = bitmapConfig; 60 | if (uriString.startsWith(RESOURCE_PREFIX)) { 61 | Resources res; 62 | String packageName = uri.getAuthority(); 63 | if (context.getPackageName().equals(packageName)) { 64 | res = context.getResources(); 65 | } else { 66 | PackageManager pm = context.getPackageManager(); 67 | res = pm.getResourcesForApplication(packageName); 68 | } 69 | 70 | int id = 0; 71 | List segments = uri.getPathSegments(); 72 | int size = segments.size(); 73 | if (size == 2 && segments.get(0).equals("drawable")) { 74 | String resName = segments.get(1); 75 | id = res.getIdentifier(resName, "drawable", packageName); 76 | } else if (size == 1 && TextUtils.isDigitsOnly(segments.get(0))) { 77 | try { 78 | id = Integer.parseInt(segments.get(0)); 79 | } catch (NumberFormatException ignored) { 80 | } 81 | } 82 | 83 | bitmap = BitmapFactory.decodeResource(context.getResources(), id, options); 84 | } else if (uriString.startsWith(ASSET_PREFIX)) { 85 | String assetName = uriString.substring(ASSET_PREFIX.length()); 86 | bitmap = BitmapFactory.decodeStream(context.getAssets().open(assetName), null, options); 87 | } else if (uriString.startsWith(FILE_PREFIX)) { 88 | bitmap = BitmapFactory.decodeFile(uriString.substring(FILE_PREFIX.length()), options); 89 | } else { 90 | InputStream inputStream = null; 91 | try { 92 | ContentResolver contentResolver = context.getContentResolver(); 93 | inputStream = contentResolver.openInputStream(uri); 94 | bitmap = BitmapFactory.decodeStream(inputStream, null, options); 95 | } finally { 96 | if (inputStream != null) { 97 | try { inputStream.close(); } catch (Exception e) { /* Ignore */ } 98 | } 99 | } 100 | } 101 | if (bitmap == null) { 102 | throw new RuntimeException("Skia image region decoder returned null bitmap - image format may not be supported"); 103 | } 104 | return bitmap; 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 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 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /sample-local/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /sample-network/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /pdfview-android/src/main/java/com/pdfview/subsamplincscaleimageview/decoder/SkiaImageRegionDecoder.java: -------------------------------------------------------------------------------- 1 | package com.pdfview.subsamplincscaleimageview.decoder; 2 | 3 | import android.content.ContentResolver; 4 | import android.content.Context; 5 | import android.content.pm.PackageManager; 6 | import android.content.res.AssetManager; 7 | import android.content.res.Resources; 8 | import android.graphics.Bitmap; 9 | import android.graphics.BitmapFactory; 10 | import android.graphics.BitmapRegionDecoder; 11 | import android.graphics.Point; 12 | import android.graphics.Rect; 13 | import android.net.Uri; 14 | import android.os.Build; 15 | import androidx.annotation.Keep; 16 | import androidx.annotation.NonNull; 17 | import androidx.annotation.Nullable; 18 | import android.text.TextUtils; 19 | 20 | 21 | import com.pdfview.subsamplincscaleimageview.SubsamplingScaleImageView; 22 | 23 | import java.io.InputStream; 24 | import java.util.List; 25 | import java.util.concurrent.locks.Lock; 26 | import java.util.concurrent.locks.ReadWriteLock; 27 | import java.util.concurrent.locks.ReentrantReadWriteLock; 28 | 29 | /** 30 | * Default implementation of {@link ImageRegionDecoder} 31 | * using Android's {@link BitmapRegionDecoder}, based on the Skia library. This 32 | * works well in most circumstances and has reasonable performance due to the cached decoder instance, 33 | * however it has some problems with grayscale, indexed and CMYK images. 34 | * 35 | * A {@link ReadWriteLock} is used to delegate responsibility for multi threading behaviour to the 36 | * {@link BitmapRegionDecoder} instance on SDK >= 21, whilst allowing this class to block until no 37 | * tiles are being loaded before recycling the decoder. In practice, {@link BitmapRegionDecoder} is 38 | * synchronized internally so this has no real impact on performance. 39 | */ 40 | public class SkiaImageRegionDecoder implements ImageRegionDecoder { 41 | 42 | private BitmapRegionDecoder decoder; 43 | private final ReadWriteLock decoderLock = new ReentrantReadWriteLock(true); 44 | 45 | private static final String FILE_PREFIX = "file://"; 46 | private static final String ASSET_PREFIX = FILE_PREFIX + "/android_asset/"; 47 | private static final String RESOURCE_PREFIX = ContentResolver.SCHEME_ANDROID_RESOURCE + "://"; 48 | 49 | private final Bitmap.Config bitmapConfig; 50 | 51 | @Keep 52 | @SuppressWarnings("unused") 53 | public SkiaImageRegionDecoder() { 54 | this(null); 55 | } 56 | 57 | @SuppressWarnings({"WeakerAccess", "SameParameterValue"}) 58 | public SkiaImageRegionDecoder(@Nullable Bitmap.Config bitmapConfig) { 59 | Bitmap.Config globalBitmapConfig = SubsamplingScaleImageView.getPreferredBitmapConfig(); 60 | if (bitmapConfig != null) { 61 | this.bitmapConfig = bitmapConfig; 62 | } else if (globalBitmapConfig != null) { 63 | this.bitmapConfig = globalBitmapConfig; 64 | } else { 65 | this.bitmapConfig = Bitmap.Config.RGB_565; 66 | } 67 | } 68 | 69 | @Override 70 | @NonNull 71 | public Point init(Context context, @NonNull Uri uri) throws Exception { 72 | String uriString = uri.toString(); 73 | if (uriString.startsWith(RESOURCE_PREFIX)) { 74 | Resources res; 75 | String packageName = uri.getAuthority(); 76 | if (context.getPackageName().equals(packageName)) { 77 | res = context.getResources(); 78 | } else { 79 | PackageManager pm = context.getPackageManager(); 80 | res = pm.getResourcesForApplication(packageName); 81 | } 82 | 83 | int id = 0; 84 | List segments = uri.getPathSegments(); 85 | int size = segments.size(); 86 | if (size == 2 && segments.get(0).equals("drawable")) { 87 | String resName = segments.get(1); 88 | id = res.getIdentifier(resName, "drawable", packageName); 89 | } else if (size == 1 && TextUtils.isDigitsOnly(segments.get(0))) { 90 | try { 91 | id = Integer.parseInt(segments.get(0)); 92 | } catch (NumberFormatException ignored) { 93 | } 94 | } 95 | 96 | decoder = BitmapRegionDecoder.newInstance(context.getResources().openRawResource(id), false); 97 | } else if (uriString.startsWith(ASSET_PREFIX)) { 98 | String assetName = uriString.substring(ASSET_PREFIX.length()); 99 | decoder = BitmapRegionDecoder.newInstance(context.getAssets().open(assetName, AssetManager.ACCESS_RANDOM), false); 100 | } else if (uriString.startsWith(FILE_PREFIX)) { 101 | decoder = BitmapRegionDecoder.newInstance(uriString.substring(FILE_PREFIX.length()), false); 102 | } else { 103 | InputStream inputStream = null; 104 | try { 105 | ContentResolver contentResolver = context.getContentResolver(); 106 | inputStream = contentResolver.openInputStream(uri); 107 | decoder = BitmapRegionDecoder.newInstance(inputStream, false); 108 | } finally { 109 | if (inputStream != null) { 110 | try { inputStream.close(); } catch (Exception e) { /* Ignore */ } 111 | } 112 | } 113 | } 114 | return new Point(decoder.getWidth(), decoder.getHeight()); 115 | } 116 | 117 | @Override 118 | @NonNull 119 | public Bitmap decodeRegion(@NonNull Rect sRect, int sampleSize) { 120 | getDecodeLock().lock(); 121 | try { 122 | if (decoder != null && !decoder.isRecycled()) { 123 | BitmapFactory.Options options = new BitmapFactory.Options(); 124 | options.inSampleSize = sampleSize; 125 | options.inPreferredConfig = bitmapConfig; 126 | Bitmap bitmap = decoder.decodeRegion(sRect, options); 127 | if (bitmap == null) { 128 | throw new RuntimeException("Skia image decoder returned null bitmap - image format may not be supported"); 129 | } 130 | return bitmap; 131 | } else { 132 | throw new IllegalStateException("Cannot decode region after decoder has been recycled"); 133 | } 134 | } finally { 135 | getDecodeLock().unlock(); 136 | } 137 | } 138 | 139 | @Override 140 | public synchronized boolean isReady() { 141 | return decoder != null && !decoder.isRecycled(); 142 | } 143 | 144 | @Override 145 | public synchronized void recycle() { 146 | decoderLock.writeLock().lock(); 147 | try { 148 | decoder.recycle(); 149 | decoder = null; 150 | } finally { 151 | decoderLock.writeLock().unlock(); 152 | } 153 | } 154 | 155 | /** 156 | * Before SDK 21, BitmapRegionDecoder was not synchronized internally. Any attempt to decode 157 | * regions from multiple threads with one decoder instance causes a segfault. For old versions 158 | * use the write lock to enforce single threaded decoding. 159 | */ 160 | private Lock getDecodeLock() { 161 | if (Build.VERSION.SDK_INT < 21) { 162 | return decoderLock.writeLock(); 163 | } else { 164 | return decoderLock.readLock(); 165 | } 166 | } 167 | } 168 | -------------------------------------------------------------------------------- /pdfview-android/src/main/java/com/pdfview/subsamplincscaleimageview/ImageSource.java: -------------------------------------------------------------------------------- 1 | package com.pdfview.subsamplincscaleimageview; 2 | 3 | import android.graphics.Bitmap; 4 | import android.graphics.Rect; 5 | import android.net.Uri; 6 | import androidx.annotation.NonNull; 7 | 8 | import java.io.File; 9 | import java.io.UnsupportedEncodingException; 10 | import java.net.URLDecoder; 11 | 12 | /** 13 | * Helper class used to set the source and additional attributes from a variety of sources. Supports 14 | * use of a bitmap, asset, resource, external file or any other URI. 15 | * 16 | * When you are using a preview image, you must set the dimensions of the full size image on the 17 | * ImageSource object for the full size image using the {@link #dimensions(int, int)} method. 18 | */ 19 | @SuppressWarnings({"unused", "WeakerAccess"}) 20 | public final class ImageSource { 21 | 22 | static final String FILE_SCHEME = "file:///"; 23 | static final String ASSET_SCHEME = "file:///android_asset/"; 24 | 25 | private final Uri uri; 26 | private final Bitmap bitmap; 27 | private final Integer resource; 28 | private boolean tile; 29 | private int sWidth; 30 | private int sHeight; 31 | private Rect sRegion; 32 | private boolean cached; 33 | 34 | private ImageSource(Bitmap bitmap, boolean cached) { 35 | this.bitmap = bitmap; 36 | this.uri = null; 37 | this.resource = null; 38 | this.tile = false; 39 | this.sWidth = bitmap.getWidth(); 40 | this.sHeight = bitmap.getHeight(); 41 | this.cached = cached; 42 | } 43 | 44 | private ImageSource(@NonNull Uri uri) { 45 | // #114 If file doesn't exist, attempt to url decode the URI and try again 46 | String uriString = uri.toString(); 47 | if (uriString.startsWith(FILE_SCHEME)) { 48 | File uriFile = new File(uriString.substring(FILE_SCHEME.length() - 1)); 49 | if (!uriFile.exists()) { 50 | try { 51 | uri = Uri.parse(URLDecoder.decode(uriString, "UTF-8")); 52 | } catch (UnsupportedEncodingException e) { 53 | // Fallback to encoded URI. This exception is not expected. 54 | } 55 | } 56 | } 57 | this.bitmap = null; 58 | this.uri = uri; 59 | this.resource = null; 60 | this.tile = true; 61 | } 62 | 63 | private ImageSource(int resource) { 64 | this.bitmap = null; 65 | this.uri = null; 66 | this.resource = resource; 67 | this.tile = true; 68 | } 69 | 70 | /** 71 | * Create an instance from a resource. The correct resource for the device screen resolution will be used. 72 | * @param resId resource ID. 73 | * @return an {@link ImageSource} instance. 74 | */ 75 | @NonNull 76 | public static ImageSource resource(int resId) { 77 | return new ImageSource(resId); 78 | } 79 | 80 | /** 81 | * Create an instance from an asset name. 82 | * @param assetName asset name. 83 | * @return an {@link ImageSource} instance. 84 | */ 85 | @NonNull 86 | public static ImageSource asset(@NonNull String assetName) { 87 | //noinspection ConstantConditions 88 | if (assetName == null) { 89 | throw new NullPointerException("Asset name must not be null"); 90 | } 91 | return uri(ASSET_SCHEME + assetName); 92 | } 93 | 94 | /** 95 | * Create an instance from a URI. If the URI does not start with a scheme, it's assumed to be the URI 96 | * of a file. 97 | * @param uri image URI. 98 | * @return an {@link ImageSource} instance. 99 | */ 100 | @NonNull 101 | public static ImageSource uri(@NonNull String uri) { 102 | //noinspection ConstantConditions 103 | if (uri == null) { 104 | throw new NullPointerException("Uri must not be null"); 105 | } 106 | if (!uri.contains("://")) { 107 | if (uri.startsWith("/")) { 108 | uri = uri.substring(1); 109 | } 110 | uri = FILE_SCHEME + uri; 111 | } 112 | return new ImageSource(Uri.parse(uri)); 113 | } 114 | 115 | /** 116 | * Create an instance from a URI. 117 | * @param uri image URI. 118 | * @return an {@link ImageSource} instance. 119 | */ 120 | @NonNull 121 | public static ImageSource uri(@NonNull Uri uri) { 122 | //noinspection ConstantConditions 123 | if (uri == null) { 124 | throw new NullPointerException("Uri must not be null"); 125 | } 126 | return new ImageSource(uri); 127 | } 128 | 129 | /** 130 | * Provide a loaded bitmap for display. 131 | * @param bitmap bitmap to be displayed. 132 | * @return an {@link ImageSource} instance. 133 | */ 134 | @NonNull 135 | public static ImageSource bitmap(@NonNull Bitmap bitmap) { 136 | //noinspection ConstantConditions 137 | if (bitmap == null) { 138 | throw new NullPointerException("Bitmap must not be null"); 139 | } 140 | return new ImageSource(bitmap, false); 141 | } 142 | 143 | /** 144 | * Provide a loaded and cached bitmap for display. This bitmap will not be recycled when it is no 145 | * longer needed. Use this method if you loaded the bitmap with an image loader such as Picasso 146 | * or Volley. 147 | * @param bitmap bitmap to be displayed. 148 | * @return an {@link ImageSource} instance. 149 | */ 150 | @NonNull 151 | public static ImageSource cachedBitmap(@NonNull Bitmap bitmap) { 152 | //noinspection ConstantConditions 153 | if (bitmap == null) { 154 | throw new NullPointerException("Bitmap must not be null"); 155 | } 156 | return new ImageSource(bitmap, true); 157 | } 158 | 159 | /** 160 | * Enable tiling of the image. This does not apply to preview images which are always loaded as a single bitmap., 161 | * and tiling cannot be disabled when displaying a region of the source image. 162 | * @return this instance for chaining. 163 | */ 164 | @NonNull 165 | public ImageSource tilingEnabled() { 166 | return tiling(true); 167 | } 168 | 169 | /** 170 | * Disable tiling of the image. This does not apply to preview images which are always loaded as a single bitmap, 171 | * and tiling cannot be disabled when displaying a region of the source image. 172 | * @return this instance for chaining. 173 | */ 174 | @NonNull 175 | public ImageSource tilingDisabled() { 176 | return tiling(false); 177 | } 178 | 179 | /** 180 | * Enable or disable tiling of the image. This does not apply to preview images which are always loaded as a single bitmap, 181 | * and tiling cannot be disabled when displaying a region of the source image. 182 | * @param tile whether tiling should be enabled. 183 | * @return this instance for chaining. 184 | */ 185 | @NonNull 186 | public ImageSource tiling(boolean tile) { 187 | this.tile = tile; 188 | return this; 189 | } 190 | 191 | /** 192 | * Use a region of the source image. Region must be set independently for the full size image and the preview if 193 | * you are using one. 194 | * @param sRegion the region of the source image to be displayed. 195 | * @return this instance for chaining. 196 | */ 197 | @NonNull 198 | public ImageSource region(Rect sRegion) { 199 | this.sRegion = sRegion; 200 | setInvariants(); 201 | return this; 202 | } 203 | 204 | /** 205 | * Declare the dimensions of the image. This is only required for a full size image, when you are specifying a URI 206 | * and also a preview image. When displaying a bitmap object, or not using a preview, you do not need to declare 207 | * the image dimensions. Note if the declared dimensions are found to be incorrect, the view will reset. 208 | * @param sWidth width of the source image. 209 | * @param sHeight height of the source image. 210 | * @return this instance for chaining. 211 | */ 212 | @NonNull 213 | public ImageSource dimensions(int sWidth, int sHeight) { 214 | if (bitmap == null) { 215 | this.sWidth = sWidth; 216 | this.sHeight = sHeight; 217 | } 218 | setInvariants(); 219 | return this; 220 | } 221 | 222 | private void setInvariants() { 223 | if (this.sRegion != null) { 224 | this.tile = true; 225 | this.sWidth = this.sRegion.width(); 226 | this.sHeight = this.sRegion.height(); 227 | } 228 | } 229 | 230 | protected final Uri getUri() { 231 | return uri; 232 | } 233 | 234 | protected final Bitmap getBitmap() { 235 | return bitmap; 236 | } 237 | 238 | protected final Integer getResource() { 239 | return resource; 240 | } 241 | 242 | protected final boolean getTile() { 243 | return tile; 244 | } 245 | 246 | protected final int getSWidth() { 247 | return sWidth; 248 | } 249 | 250 | protected final int getSHeight() { 251 | return sHeight; 252 | } 253 | 254 | protected final Rect getSRegion() { 255 | return sRegion; 256 | } 257 | 258 | protected final boolean isCached() { 259 | return cached; 260 | } 261 | } 262 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /pdfview-android/src/main/java/com/pdfview/subsamplincscaleimageview/decoder/SkiaPooledImageRegionDecoder.java: -------------------------------------------------------------------------------- 1 | package com.pdfview.subsamplincscaleimageview.decoder; 2 | 3 | import android.app.ActivityManager; 4 | import android.content.ContentResolver; 5 | import android.content.Context; 6 | import android.content.pm.PackageManager; 7 | import android.content.res.AssetFileDescriptor; 8 | import android.content.res.AssetManager; 9 | import android.content.res.Resources; 10 | import android.graphics.Bitmap; 11 | import android.graphics.BitmapFactory; 12 | import android.graphics.BitmapRegionDecoder; 13 | import android.graphics.Point; 14 | import android.graphics.Rect; 15 | import android.net.Uri; 16 | import android.os.Build; 17 | import androidx.annotation.Keep; 18 | import androidx.annotation.NonNull; 19 | import androidx.annotation.Nullable; 20 | import android.text.TextUtils; 21 | import android.util.Log; 22 | 23 | 24 | import com.pdfview.subsamplincscaleimageview.SubsamplingScaleImageView; 25 | 26 | import java.io.File; 27 | import java.io.FileFilter; 28 | import java.io.InputStream; 29 | import java.util.List; 30 | import java.util.Map; 31 | import java.util.concurrent.ConcurrentHashMap; 32 | import java.util.concurrent.Executor; 33 | import java.util.concurrent.Semaphore; 34 | import java.util.concurrent.atomic.AtomicBoolean; 35 | import java.util.concurrent.locks.ReadWriteLock; 36 | import java.util.concurrent.locks.ReentrantReadWriteLock; 37 | import java.util.regex.Pattern; 38 | 39 | import static android.content.Context.ACTIVITY_SERVICE; 40 | 41 | /** 42 | *

43 | * An implementation of {@link ImageRegionDecoder} using a pool of {@link BitmapRegionDecoder}s, 44 | * to provide true parallel loading of tiles. This is only effective if parallel loading has been 45 | * enabled in the view by calling {@link SubsamplingScaleImageView#setExecutor(Executor)} 46 | * with a multi-threaded {@link Executor} instance. 47 | *

48 | * One decoder is initialised when the class is initialised. This is enough to decode base layer tiles. 49 | * Additional decoders are initialised when a subregion of the image is first requested, which indicates 50 | * interaction with the view. Creation of additional encoders stops when {@link #allowAdditionalDecoder(int, long)} 51 | * returns false. The default implementation takes into account the file size, number of CPU cores, 52 | * low memory status and a hard limit of 4. Extend this class to customise this. 53 | *

54 | * WARNING: This class is highly experimental and not proven to be stable on a wide range of 55 | * devices. You are advised to test it thoroughly on all available devices, and code your app to use 56 | * {@link SkiaImageRegionDecoder} on old or low powered devices you could not test. 57 | *

58 | */ 59 | public class SkiaPooledImageRegionDecoder implements ImageRegionDecoder { 60 | 61 | private static final String TAG = SkiaPooledImageRegionDecoder.class.getSimpleName(); 62 | 63 | private static boolean debug = false; 64 | 65 | private DecoderPool decoderPool = new DecoderPool(); 66 | private final ReadWriteLock decoderLock = new ReentrantReadWriteLock(true); 67 | 68 | private static final String FILE_PREFIX = "file://"; 69 | private static final String ASSET_PREFIX = FILE_PREFIX + "/android_asset/"; 70 | private static final String RESOURCE_PREFIX = ContentResolver.SCHEME_ANDROID_RESOURCE + "://"; 71 | 72 | private final Bitmap.Config bitmapConfig; 73 | 74 | private Context context; 75 | private Uri uri; 76 | 77 | private long fileLength = Long.MAX_VALUE; 78 | private final Point imageDimensions = new Point(0, 0); 79 | private final AtomicBoolean lazyInited = new AtomicBoolean(false); 80 | 81 | @Keep 82 | @SuppressWarnings("unused") 83 | public SkiaPooledImageRegionDecoder() { 84 | this(null); 85 | } 86 | 87 | @SuppressWarnings({"WeakerAccess", "SameParameterValue"}) 88 | public SkiaPooledImageRegionDecoder(@Nullable Bitmap.Config bitmapConfig) { 89 | Bitmap.Config globalBitmapConfig = SubsamplingScaleImageView.getPreferredBitmapConfig(); 90 | if (bitmapConfig != null) { 91 | this.bitmapConfig = bitmapConfig; 92 | } else if (globalBitmapConfig != null) { 93 | this.bitmapConfig = globalBitmapConfig; 94 | } else { 95 | this.bitmapConfig = Bitmap.Config.RGB_565; 96 | } 97 | } 98 | 99 | /** 100 | * Controls logging of debug messages. All instances are affected. 101 | * @param debug true to enable debug logging, false to disable. 102 | */ 103 | @Keep 104 | @SuppressWarnings("unused") 105 | public static void setDebug(boolean debug) { 106 | SkiaPooledImageRegionDecoder.debug = debug; 107 | } 108 | 109 | /** 110 | * Initialises the decoder pool. This method creates one decoder on the current thread and uses 111 | * it to decode the bounds, then spawns an independent thread to populate the pool with an 112 | * additional three decoders. The thread will abort if {@link #recycle()} is called. 113 | */ 114 | @Override 115 | @NonNull 116 | public Point init(final Context context, @NonNull final Uri uri) throws Exception { 117 | this.context = context; 118 | this.uri = uri; 119 | initialiseDecoder(); 120 | return this.imageDimensions; 121 | } 122 | 123 | /** 124 | * Initialises extra decoders for as long as {@link #allowAdditionalDecoder(int, long)} returns 125 | * true and the pool has not been recycled. 126 | */ 127 | private void lazyInit() { 128 | if (lazyInited.compareAndSet(false, true) && fileLength < Long.MAX_VALUE) { 129 | debug("Starting lazy init of additional decoders"); 130 | Thread thread = new Thread() { 131 | @Override 132 | public void run() { 133 | while (decoderPool != null && allowAdditionalDecoder(decoderPool.size(), fileLength)) { 134 | // New decoders can be created while reading tiles but this read lock prevents 135 | // them being initialised while the pool is being recycled. 136 | try { 137 | if (decoderPool != null) { 138 | long start = System.currentTimeMillis(); 139 | debug("Starting decoder"); 140 | initialiseDecoder(); 141 | long end = System.currentTimeMillis(); 142 | debug("Started decoder, took " + (end - start) + "ms"); 143 | } 144 | } catch (Exception e) { 145 | // A decoder has already been successfully created so we can ignore this 146 | debug("Failed to start decoder: " + e.getMessage()); 147 | } 148 | } 149 | } 150 | }; 151 | thread.start(); 152 | } 153 | } 154 | 155 | /** 156 | * Initialises a new {@link BitmapRegionDecoder} and adds it to the pool, unless the pool has 157 | * been recycled while it was created. 158 | */ 159 | private void initialiseDecoder() throws Exception { 160 | String uriString = uri.toString(); 161 | BitmapRegionDecoder decoder; 162 | long fileLength = Long.MAX_VALUE; 163 | if (uriString.startsWith(RESOURCE_PREFIX)) { 164 | Resources res; 165 | String packageName = uri.getAuthority(); 166 | if (context.getPackageName().equals(packageName)) { 167 | res = context.getResources(); 168 | } else { 169 | PackageManager pm = context.getPackageManager(); 170 | res = pm.getResourcesForApplication(packageName); 171 | } 172 | 173 | int id = 0; 174 | List segments = uri.getPathSegments(); 175 | int size = segments.size(); 176 | if (size == 2 && segments.get(0).equals("drawable")) { 177 | String resName = segments.get(1); 178 | id = res.getIdentifier(resName, "drawable", packageName); 179 | } else if (size == 1 && TextUtils.isDigitsOnly(segments.get(0))) { 180 | try { 181 | id = Integer.parseInt(segments.get(0)); 182 | } catch (NumberFormatException ignored) { 183 | } 184 | } 185 | try { 186 | AssetFileDescriptor descriptor = context.getResources().openRawResourceFd(id); 187 | fileLength = descriptor.getLength(); 188 | } catch (Exception e) { 189 | // Pooling disabled 190 | } 191 | decoder = BitmapRegionDecoder.newInstance(context.getResources().openRawResource(id), false); 192 | } else if (uriString.startsWith(ASSET_PREFIX)) { 193 | String assetName = uriString.substring(ASSET_PREFIX.length()); 194 | try { 195 | AssetFileDescriptor descriptor = context.getAssets().openFd(assetName); 196 | fileLength = descriptor.getLength(); 197 | } catch (Exception e) { 198 | // Pooling disabled 199 | } 200 | decoder = BitmapRegionDecoder.newInstance(context.getAssets().open(assetName, AssetManager.ACCESS_RANDOM), false); 201 | } else if (uriString.startsWith(FILE_PREFIX)) { 202 | decoder = BitmapRegionDecoder.newInstance(uriString.substring(FILE_PREFIX.length()), false); 203 | try { 204 | File file = new File(uriString); 205 | if (file.exists()) { 206 | fileLength = file.length(); 207 | } 208 | } catch (Exception e) { 209 | // Pooling disabled 210 | } 211 | } else { 212 | InputStream inputStream = null; 213 | try { 214 | ContentResolver contentResolver = context.getContentResolver(); 215 | inputStream = contentResolver.openInputStream(uri); 216 | decoder = BitmapRegionDecoder.newInstance(inputStream, false); 217 | try { 218 | AssetFileDescriptor descriptor = contentResolver.openAssetFileDescriptor(uri, "r"); 219 | if (descriptor != null) { 220 | fileLength = descriptor.getLength(); 221 | } 222 | } catch (Exception e) { 223 | // Stick with MAX_LENGTH 224 | } 225 | } finally { 226 | if (inputStream != null) { 227 | try { inputStream.close(); } catch (Exception e) { /* Ignore */ } 228 | } 229 | } 230 | } 231 | 232 | this.fileLength = fileLength; 233 | this.imageDimensions.set(decoder.getWidth(), decoder.getHeight()); 234 | decoderLock.writeLock().lock(); 235 | try { 236 | if (decoderPool != null) { 237 | decoderPool.add(decoder); 238 | } 239 | } finally { 240 | decoderLock.writeLock().unlock(); 241 | } 242 | } 243 | 244 | /** 245 | * Acquire a read lock to prevent decoding overlapping with recycling, then check the pool still 246 | * exists and acquire a decoder to load the requested region. There is no check whether the pool 247 | * currently has decoders, because it's guaranteed to have one decoder after {@link #init(Context, Uri)} 248 | * is called and be null once {@link #recycle()} is called. In practice the view can't call this 249 | * method until after {@link #init(Context, Uri)}, so there will be no blocking on an empty pool. 250 | */ 251 | @Override 252 | @NonNull 253 | public Bitmap decodeRegion(@NonNull Rect sRect, int sampleSize) { 254 | debug("Decode region " + sRect + " on thread " + Thread.currentThread().getName()); 255 | if (sRect.width() < imageDimensions.x || sRect.height() < imageDimensions.y) { 256 | lazyInit(); 257 | } 258 | decoderLock.readLock().lock(); 259 | try { 260 | if (decoderPool != null) { 261 | BitmapRegionDecoder decoder = decoderPool.acquire(); 262 | try { 263 | // Decoder can't be null or recycled in practice 264 | if (decoder != null && !decoder.isRecycled()) { 265 | BitmapFactory.Options options = new BitmapFactory.Options(); 266 | options.inSampleSize = sampleSize; 267 | options.inPreferredConfig = bitmapConfig; 268 | Bitmap bitmap = decoder.decodeRegion(sRect, options); 269 | if (bitmap == null) { 270 | throw new RuntimeException("Skia image decoder returned null bitmap - image format may not be supported"); 271 | } 272 | return bitmap; 273 | } 274 | } finally { 275 | if (decoder != null) { 276 | decoderPool.release(decoder); 277 | } 278 | } 279 | } 280 | throw new IllegalStateException("Cannot decode region after decoder has been recycled"); 281 | } finally { 282 | decoderLock.readLock().unlock(); 283 | } 284 | } 285 | 286 | /** 287 | * Holding a read lock to avoid returning true while the pool is being recycled, this returns 288 | * true if the pool has at least one decoder available. 289 | */ 290 | @Override 291 | public synchronized boolean isReady() { 292 | return decoderPool != null && !decoderPool.isEmpty(); 293 | } 294 | 295 | /** 296 | * Wait until all read locks held by {@link #decodeRegion(Rect, int)} are released, then recycle 297 | * and destroy the pool. Elsewhere, when a read lock is acquired, we must check the pool is not null. 298 | */ 299 | @Override 300 | public synchronized void recycle() { 301 | decoderLock.writeLock().lock(); 302 | try { 303 | if (decoderPool != null) { 304 | decoderPool.recycle(); 305 | decoderPool = null; 306 | context = null; 307 | uri = null; 308 | } 309 | } finally { 310 | decoderLock.writeLock().unlock(); 311 | } 312 | } 313 | 314 | /** 315 | * Called before creating a new decoder. Based on number of CPU cores, available memory, and the 316 | * size of the image file, determines whether another decoder can be created. Subclasses can 317 | * override and customise this. 318 | * @param numberOfDecoders the number of decoders that have been created so far 319 | * @param fileLength the size of the image file in bytes. Creating another decoder will use approximately this much native memory. 320 | * @return true if another decoder can be created. 321 | */ 322 | @SuppressWarnings("WeakerAccess") 323 | protected boolean allowAdditionalDecoder(int numberOfDecoders, long fileLength) { 324 | if (numberOfDecoders >= 4) { 325 | debug("No additional decoders allowed, reached hard limit (4)"); 326 | return false; 327 | } else if (numberOfDecoders * fileLength > 20 * 1024 * 1024) { 328 | debug("No additional encoders allowed, reached hard memory limit (20Mb)"); 329 | return false; 330 | } else if (numberOfDecoders >= getNumberOfCores()) { 331 | debug("No additional encoders allowed, limited by CPU cores (" + getNumberOfCores() + ")"); 332 | return false; 333 | } else if (isLowMemory()) { 334 | debug("No additional encoders allowed, memory is low"); 335 | return false; 336 | } 337 | debug("Additional decoder allowed, current count is " + numberOfDecoders + ", estimated native memory " + ((fileLength * numberOfDecoders)/(1024 * 1024)) + "Mb"); 338 | return true; 339 | } 340 | 341 | 342 | /** 343 | * A simple pool of {@link BitmapRegionDecoder} instances, all loading from the same source. 344 | */ 345 | private static class DecoderPool { 346 | private final Semaphore available = new Semaphore(0, true); 347 | private final Map decoders = new ConcurrentHashMap<>(); 348 | 349 | /** 350 | * Returns false if there is at least one decoder in the pool. 351 | */ 352 | private synchronized boolean isEmpty() { 353 | return decoders.isEmpty(); 354 | } 355 | 356 | /** 357 | * Returns number of encoders. 358 | */ 359 | private synchronized int size() { 360 | return decoders.size(); 361 | } 362 | 363 | /** 364 | * Acquire a decoder. Blocks until one is available. 365 | */ 366 | private BitmapRegionDecoder acquire() { 367 | available.acquireUninterruptibly(); 368 | return getNextAvailable(); 369 | } 370 | 371 | /** 372 | * Release a decoder back to the pool. 373 | */ 374 | private void release(BitmapRegionDecoder decoder) { 375 | if (markAsUnused(decoder)) { 376 | available.release(); 377 | } 378 | } 379 | 380 | /** 381 | * Adds a newly created decoder to the pool, releasing an additional permit. 382 | */ 383 | private synchronized void add(BitmapRegionDecoder decoder) { 384 | decoders.put(decoder, false); 385 | available.release(); 386 | } 387 | 388 | /** 389 | * While there are decoders in the map, wait until each is available before acquiring, 390 | * recycling and removing it. After this is called, any call to {@link #acquire()} will 391 | * block forever, so this call should happen within a write lock, and all calls to 392 | * {@link #acquire()} should be made within a read lock so they cannot end up blocking on 393 | * the semaphore when it has no permits. 394 | */ 395 | private synchronized void recycle() { 396 | while (!decoders.isEmpty()) { 397 | BitmapRegionDecoder decoder = acquire(); 398 | decoder.recycle(); 399 | decoders.remove(decoder); 400 | } 401 | } 402 | 403 | private synchronized BitmapRegionDecoder getNextAvailable() { 404 | for (Map.Entry entry : decoders.entrySet()) { 405 | if (!entry.getValue()) { 406 | entry.setValue(true); 407 | return entry.getKey(); 408 | } 409 | } 410 | return null; 411 | } 412 | 413 | private synchronized boolean markAsUnused(BitmapRegionDecoder decoder) { 414 | for (Map.Entry entry : decoders.entrySet()) { 415 | if (decoder == entry.getKey()) { 416 | if (entry.getValue()) { 417 | entry.setValue(false); 418 | return true; 419 | } else { 420 | return false; 421 | } 422 | } 423 | } 424 | return false; 425 | } 426 | 427 | } 428 | 429 | private int getNumberOfCores() { 430 | if (Build.VERSION.SDK_INT >= 17) { 431 | return Runtime.getRuntime().availableProcessors(); 432 | } else { 433 | return getNumCoresOldPhones(); 434 | } 435 | } 436 | 437 | /** 438 | * Gets the number of cores available in this device, across all processors. 439 | * Requires: Ability to peruse the filesystem at "/sys/devices/system/cpu" 440 | * @return The number of cores, or 1 if failed to get result 441 | */ 442 | private int getNumCoresOldPhones() { 443 | class CpuFilter implements FileFilter { 444 | @Override 445 | public boolean accept(File pathname) { 446 | return Pattern.matches("cpu[0-9]+", pathname.getName()); 447 | } 448 | } 449 | try { 450 | File dir = new File("/sys/devices/system/cpu/"); 451 | File[] files = dir.listFiles(new CpuFilter()); 452 | return files.length; 453 | } catch(Exception e) { 454 | return 1; 455 | } 456 | } 457 | 458 | private boolean isLowMemory() { 459 | ActivityManager activityManager = (ActivityManager)context.getSystemService(ACTIVITY_SERVICE); 460 | if (activityManager != null) { 461 | ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo(); 462 | activityManager.getMemoryInfo(memoryInfo); 463 | return memoryInfo.lowMemory; 464 | } else { 465 | return true; 466 | } 467 | } 468 | 469 | private void debug(String message) { 470 | if (debug) { 471 | Log.d(TAG, message); 472 | } 473 | } 474 | } 475 | --------------------------------------------------------------------------------