-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathPdfViewerActivity.kt
More file actions
258 lines (229 loc) · 9.79 KB
/
PdfViewerActivity.kt
File metadata and controls
258 lines (229 loc) · 9.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
package com.bhuvaneshw.pdfviewerdemo
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.widget.Toast
import androidx.activity.addCallback
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.net.toUri
import androidx.core.view.GravityCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.bhuvaneshw.pdf.PdfEditor
import com.bhuvaneshw.pdf.PdfListener
import com.bhuvaneshw.pdf.PdfUnstableApi
import com.bhuvaneshw.pdf.addListener
import com.bhuvaneshw.pdf.callIfScrollSpeedLimitIsEnabled
import com.bhuvaneshw.pdf.callSafely
import com.bhuvaneshw.pdf.print.DefaultPdfPrintAdapter
import com.bhuvaneshw.pdf.setting.PdfSettingsManager
import com.bhuvaneshw.pdf.sharedPdfSettingsManager
import com.bhuvaneshw.pdfviewerdemo.databinding.ActivityPdfViewerBinding
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.jaredrummler.android.colorpicker.ColorPickerDialog
import com.jaredrummler.android.colorpicker.ColorPickerDialogListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
class PdfViewerActivity : AppCompatActivity() {
private lateinit var view: ActivityPdfViewerBinding
private var fullscreen = false
private lateinit var pdfSettingsManager: PdfSettingsManager
private var selectedColor = Color.WHITE
private val scope = CoroutineScope(Dispatchers.Default + SupervisorJob())
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
view = ActivityPdfViewerBinding.inflate(layoutInflater)
setContentView(view.root)
ViewCompat.setOnApplyWindowInsetsListener(view.container.mainView) { v, insets ->
val systemBars =
insets.getInsets(WindowInsetsCompat.Type.systemBars() + WindowInsetsCompat.Type.displayCutout())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
ViewCompat.setOnApplyWindowInsetsListener(view.pdfOutlineView) { v, insets ->
val systemBars =
insets.getInsets(WindowInsetsCompat.Type.systemBars() + WindowInsetsCompat.Type.displayCutout())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
pdfSettingsManager = sharedPdfSettingsManager("PdfSettings", MODE_PRIVATE)
.also { it.includeAll() }
val (filePath, fileName) = getDataFromIntent() ?: run {
toast("No source available!")
finish()
return
}
view.pdfViewer.onReady {
// minPageScale = PdfViewer.Zoom.PAGE_WIDTH.floatValue
// maxPageScale = 5f
// defaultPageScale = PdfViewer.Zoom.PAGE_WIDTH.floatValue
// editor.highlightColor = Color.BLUE
editor.applyHighlightColorOnTextSelection = true
pdfSettingsManager.restore(this)
load(filePath)
if (filePath.isNotBlank())
view.pdfToolBar.setFileName(fileName)
ariaLabel = fileName.split(".")[0]
ariaRoleDescription = "Pdf"
}
view.pdfToolBar.alertDialogBuilder = { MaterialAlertDialogBuilder(this) }
view.pdfToolBar.onBack = onBackPressedDispatcher::onBackPressed
view.pdfToolBar.pickColor = { onPickColor ->
ColorPickerDialog.newBuilder()
.setColor(selectedColor)
.create().apply {
setColorPickerDialogListener(object : ColorPickerDialogListener {
override fun onColorSelected(dialogId: Int, color: Int) {
selectedColor = color
onPickColor(color)
}
override fun onDialogDismissed(dialogId: Int) {}
})
show(supportFragmentManager, "color-picker-dialog")
}
}
view.container.alertDialogBuilder = view.pdfToolBar.alertDialogBuilder
view.pdfViewer.pdfPrintAdapter = DefaultPdfPrintAdapter(this).apply {
defaultFileName = fileName
}
view.pdfViewer.addListener(DownloadPdfListener(fileName))
view.pdfViewer.addListener(ImagePickerListener(this))
view.container.setAsLoadingIndicator(view.loader)
view.pdfOutlineView.onItemClick = {
scope.launch { view.pdfViewer.ui.performSidebarTreeItemClick(it.id) }
view.container.closeDrawer(GravityCompat.START)
}
onBackPressedDispatcher.addCallback(this) {
when {
view.pdfToolBar.handleBackPressed() -> {
// Handled by toolbar
}
view.container.handleBackPressed() -> {
// Handled by container
}
view.pdfViewer.editor.hasUnsavedChanges -> showSaveDialog()
else -> {
isEnabled = false
onBackPressedDispatcher.onBackPressed()
}
}
}
view.pdfViewer.run {
// highlightEditorColors = listOf("blue" to Color.BLUE, "black" to Color.BLACK)
addListener(
onPageLoadFailed = {
toast(it.formatToString())
finish()
},
onLinkClick = { link ->
startActivity(Intent(Intent.ACTION_VIEW, link.toUri()))
},
onProgressChange = { progress ->
view.progressBar.isIndeterminate = false
view.progressBar.progress = (progress * 100).toInt()
},
onAnnotationEditor = { type ->
when (type) {
is PdfEditor.AnnotationEventType.Saved -> {
view.pdfToolBar.setFileName(fileName)
}
is PdfEditor.AnnotationEventType.Unsaved -> {
view.pdfToolBar.setFileName("*$fileName")
}
else -> {}
}
},
onFindMatchComplete = { found ->
if (!found)
Toast.makeText(context, "No match found!", Toast.LENGTH_SHORT).show()
}
)
}
view.pdfViewer.addListener(object : PdfListener {
@OptIn(PdfUnstableApi::class)
override fun onSingleClick() {
view.pdfViewer.callSafely { // Helpful if you are using scrollSpeedLimit or skip if editing pdf
if (!view.pdfToolBar.isEditorBarVisible()) {
fullscreen = !fullscreen
setFullscreen(fullscreen)
view.container.animateToolBar(!fullscreen)
}
}
}
@OptIn(PdfUnstableApi::class)
override fun onDoubleClick() {
view.pdfViewer.run {
callSafely { // Helpful if you are using scrollSpeedLimit or skip if editing pdf
if (!view.pdfToolBar.isEditorBarVisible()) {
val originalCurrentPage = currentPage
if (!isZoomInMinScale()) zoomToMinimum()
else zoomToMaximum()
callIfScrollSpeedLimitIsEnabled {
goToPage(originalCurrentPage)
}
}
}
}
}
})
}
override fun onPause() {
pdfSettingsManager.save(view.pdfViewer)
super.onPause()
}
override fun onDestroy() {
pdfSettingsManager.save(view.pdfViewer)
super.onDestroy()
}
private fun showSaveDialog() {
MaterialAlertDialogBuilder(this)
.setTitle("Document modified!")
.setMessage("Do you want to save the document before exiting?")
.setPositiveButton("Save") { _, _ ->
view.pdfViewer.downloadFile()
}
.setNegativeButton("Exit") { _, _ ->
finish()
}
.show()
}
inner class DownloadPdfListener(private val pdfTitle: String) : PdfListener {
private var bytes: ByteArray? = null
private val saveFileLauncher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result ->
CoroutineScope(Dispatchers.IO + SupervisorJob()).launch {
bytes?.let { pdfAsBytes ->
if (result.resultCode == RESULT_OK) {
result.data?.data?.let { uri ->
try {
contentResolver.openOutputStream(uri)?.use { it.write(pdfAsBytes) }
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
}
}
override fun onDownload(
fileBytes: ByteArray,
fileName: String?,
mimeType: String?
) {
bytes = fileBytes
saveFileLauncher.launch(Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = mimeType ?: "application/pdf"
putExtra(
Intent.EXTRA_TITLE, if (mimeType == "application/pdf") pdfTitle else fileName
)
})
}
}
}