In questo articolo vedremo come poter visualizzare un file PDF all'interno della propria applicazione.
Esistono varie librerie che possono essere utilizzate per visualizzare i file PDF nella nostra applicazione. In alcuni di questi esempi vedremo come utilizzare la libreria AndroidPdfViewer.
ESEMPIO 1:
In questo esempio vedremo come visualizzare un file PDF incorporato nell'applicazione.
Questa modalità aumenta le dimensioni del file APK (file di installazione dell'applicazione) in base alla dimensione del/dei file PDF inseriti nella cartella assets
Per prima cosa occorre aprire il file build.gradle ed inserire le seguenti righe
Ecco come si presenta il file activity_main.xml
Ora bisogna creare una funzione che permette di recuperare il file PDF dalla cartella assets
Poi occorre creare una funzione per la visualizzazione del file PDF
Ecco come si presenta il file MainActivity.kt
ESEMPIO 2:
In questo esempio vedremo come visualizzare un file PDF da un sito Web all'interno della WebView.
Questa modalità rispetto all'ESEMPIO 1, riduce notevolmente le dimensioni del file APK in quanto nessun file PDF è memorizzato al suo interno.
Per prima cosa inserire i permessi per l'accesso ad internet
Ecco come si presenta il file activity_main.xml
Ora bisogna inserire un codice simile a quello utilizzato per la WebView
Infine bisogna creare una funzione che contiene l'indirizzo Web del file PDF
Ecco come si presenta il file MainActivity.kt
Le righe dalla 27 alla 40 non sono obbligatorie ma risultano utili per verificare il caricamento del file PDF
Nell'immagine viene visualizzato anteprima non disponibile in quanto il collegamento Web al file PDF non esiste.
ESEMPIO 3:
In questo esempio vedremo come visualizzare un file PDF archiviato all'interno della memoria del dispositivo.
Per prima cosa occorre aprire il file build.gradle ed inserire le seguenti righe
Ecco come si presenta il file activity_main.xml
Ora all'interno della funzione onCreate() occorre inserire la chiamata alla funzione che permette di selezionare il file
Al di fuori della funzione onCreate() inserire queste righe di codice
Ora creiamo la funzione che permette di selezionare il file dalla memoria del dispositivo
Poi occorre creare la funzione onActivityResult() che permette di recuperare il risultato di un'altra Activity in questo caso la selezione del file PDF e la sua successiva visualizzazione
Infine occorre creare una funzione per la visualizzazione del file PDF
Ecco come si presenta il file MainActivity.kt
ESEMPIO 4:
In questo esempio vedremo come visualizzare un file PDF recuperato dal Web all'interno di un PDFView. Simile all'ESEMPIO 3 ma il file è un link Web. In pratica quando viene avviata l'applicazione viene scaricato il file PDF indicato e visualizzato all'interno del PDFView, rispetto all'ESEMPIO 2 è possibile avere maggior controllo sulla visualizzazione del file.
Per prima cosa inserire i permessi per l'accesso ad internet
E poi occorre aprire il file build.gradle ed inserire le seguenti righe
Ecco come si presenta il file activity_main.xml
Ora all'interno della funzione onCreate() occorre inserire l'inizializzazione della libreria download PDF e la chiamata alla funzione che si occupa di scaricare il file dal Web
Poi occorre creare la funzione che si occupa di visualizzare il file PDF scaricato
Poi occorre creare la funzione che si occupa di scaricare il file dal Web
Infine bisogna creare un object con queste righe di codice (questo può essere anche un file di tipo object all'interno della cartella Java dove c'è il file MainActivity.kt)
Ecco come si presenta il file MainActivity.kt
Nell'immagine non viene visualizzato alcun file PDF in quanto il collegamento Web al file PDF non esiste.
Esistono varie librerie che possono essere utilizzate per visualizzare i file PDF nella nostra applicazione. In alcuni di questi esempi vedremo come utilizzare la libreria AndroidPdfViewer.
ESEMPIO 1:
In questo esempio vedremo come visualizzare un file PDF incorporato nell'applicazione.
Questa modalità aumenta le dimensioni del file APK (file di installazione dell'applicazione) in base alla dimensione del/dei file PDF inseriti nella cartella assets
Per prima cosa occorre aprire il file build.gradle ed inserire le seguenti righe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
implementation 'com.github.barteksc:android-pdf-viewer:2.8.2' | |
implementation 'com.mindorks.android:prdownloader:0.6.0' |
Ecco come si presenta il file activity_main.xml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<RelativeLayout | |
xmlns:android="http://schemas.android.com/apk/res/android" | |
xmlns:tools="http://schemas.android.com/tools" | |
android:layout_width="match_parent" | |
android:layout_height="match_parent" | |
tools:context=".MainActivity"> | |
<com.github.barteksc.pdfviewer.PDFView | |
android:id="@+id/pdfView" | |
android:layout_width="match_parent" | |
android:layout_height="match_parent" /> | |
</RelativeLayout> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private fun getPdfNameFromAssets(): String { | |
//nome del file PDF che deve essere aperto | |
return "pdfTest.pdf" | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private fun showPdfFromAssets(pdfName: String) { | |
pdfView.fromAsset(pdfName) | |
.password(null) //se protetto da password, inserire la password qui altrimenti null | |
.defaultPage(0) //impostazione della pagina da visualizzare all'apertura | |
//0 = pagina 1 | |
.scrollHandle(DefaultScrollHandle(this)) //visualizza il numero della pagina corrente | |
.onPageError { page, _ -> | |
Toast.makeText(this, "Error at page: $page", Toast.LENGTH_LONG).show()} | |
.load() //caricamento del file | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.dm.tutorialpdfview1 | |
import androidx.appcompat.app.AppCompatActivity | |
import android.os.Bundle | |
import android.widget.Toast | |
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle | |
import kotlinx.android.synthetic.main.activity_main.* | |
class MainActivity : AppCompatActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
//visualizzazione file PDF con il richiamo della funzione per recuperare il nome del file PDF da aprire | |
showPdfFromAssets(getPdfNameFromAssets()) | |
} | |
//funzione che recupera il nome del file dalla cartella sssets | |
private fun getPdfNameFromAssets(): String { | |
//nome del file PDF che deve essere aperto | |
return "pdfTest.pdf" | |
} | |
//funzione per visualizzare il file PDF | |
private fun showPdfFromAssets(pdfName: String) { | |
pdfView.fromAsset(pdfName) | |
.password(null) //se protetto da password, inserire la password qui altrimenti null | |
.defaultPage(0) //impostazione della pagina da visualizzare all'apertura | |
//0 = pagina 1 | |
.scrollHandle(DefaultScrollHandle(this)) //visualizza il numero della pagina corrente | |
.onPageError { page, _ -> | |
Toast.makeText(this, "Error at page: $page", Toast.LENGTH_LONG).show() } | |
.load() //caricamento del file | |
} | |
} |
Download Project | ![]() |
Download file APK | ![]() |
ESEMPIO 2:
In questo esempio vedremo come visualizzare un file PDF da un sito Web all'interno della WebView.
Questa modalità rispetto all'ESEMPIO 1, riduce notevolmente le dimensioni del file APK in quanto nessun file PDF è memorizzato al suo interno.
Per prima cosa inserire i permessi per l'accesso ad internet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<uses-permission android:name="android.permission.INTERNET"/> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" | |
xmlns:tools="http://schemas.android.com/tools" | |
android:layout_width="match_parent" | |
android:layout_height="match_parent" | |
xmlns:app="http://schemas.android.com/apk/res-auto" | |
tools:context=".MainActivity"> | |
<WebView | |
android:id="@+id/webView" | |
android:layout_width="match_parent" | |
android:layout_height="match_parent" /> | |
<ProgressBar | |
android:id="@+id/progressBar" | |
android:layout_width="wrap_content" | |
android:layout_height="wrap_content" | |
android:visibility="gone" | |
app:layout_constraintBottom_toBottomOf="parent" | |
app:layout_constraintEnd_toEndOf="parent" | |
app:layout_constraintStart_toStartOf="parent" | |
app:layout_constraintTop_toTopOf="@+id/webView" /> | |
</androidx.constraintlayout.widget.ConstraintLayout> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//impostazioni della webView | |
webView.webViewClient = WebViewClient() | |
webView.settings.setSupportZoom(true) | |
webView.settings.javaScriptEnabled = true | |
//ottiene l'indirizzo specificato nella funzione getPdfurl() | |
val url = getPdfUrl() | |
//indirizzo del visualizzatore PDF Google + l'url del documento PDF | |
webView.loadUrl("https://docs.google.com/gview?embedded=true&url=$url") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private fun getPdfUrl(): String { | |
//inserire l'indirizzo completo del file PDF sul Web | |
return "https://www.google.com/document/AndroidStudio.pdf" | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.dm.tutorialpdfview2 | |
import android.graphics.Bitmap | |
import androidx.appcompat.app.AppCompatActivity | |
import android.os.Bundle | |
import android.view.View | |
import android.webkit.WebView | |
import android.webkit.WebViewClient | |
import kotlinx.android.synthetic.main.activity_main.* | |
class MainActivity : AppCompatActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
//impostazioni della webView | |
webView.webViewClient = WebViewClient() | |
webView.settings.setSupportZoom(true) | |
webView.settings.javaScriptEnabled = true | |
//ottiene l'indirizzo specificato nella funzione getPdfurl() | |
val url = getPdfUrl() | |
//indirizzo del visualizzatore PDF Google + l'url del documento PDF | |
webView.loadUrl("https://docs.google.com/gview?embedded=true&url=$url") | |
//progressBar | |
//non è indispensabile ma utile durante il caricamento del PDF | |
if(webView != null) | |
{ | |
webView.webViewClient = object: WebViewClient(){ | |
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) { | |
progressBar.visibility = View.VISIBLE | |
super.onPageStarted(view, url, favicon) | |
} | |
override fun onPageFinished(view: WebView?, url: String?) { | |
progressBar.visibility = View.GONE | |
super.onPageFinished(view, url) | |
} | |
} | |
} | |
//fine di progressBar | |
} | |
private fun getPdfUrl(): String { | |
//inserire l'indirizzo completo del file PDF sul Web | |
return "https://www.google.com/document/AndroidStudio.pdf" | |
} | |
} |

Nell'immagine viene visualizzato anteprima non disponibile in quanto il collegamento Web al file PDF non esiste.
Download Project | ![]() |
Download file APK | ![]() |
ESEMPIO 3:
In questo esempio vedremo come visualizzare un file PDF archiviato all'interno della memoria del dispositivo.
Per prima cosa occorre aprire il file build.gradle ed inserire le seguenti righe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
implementation 'com.github.barteksc:android-pdf-viewer:2.8.2' | |
implementation 'com.mindorks.android:prdownloader:0.6.0' |
Ecco come si presenta il file activity_main.xml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<RelativeLayout | |
xmlns:android="http://schemas.android.com/apk/res/android" | |
xmlns:tools="http://schemas.android.com/tools" | |
android:layout_width="match_parent" | |
android:layout_height="match_parent" | |
tools:context=".MainActivity"> | |
<com.github.barteksc.pdfviewer.PDFView | |
android:id="@+id/pdfView" | |
android:layout_width="match_parent" | |
android:layout_height="match_parent" /> | |
</RelativeLayout> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//chiamata alla funzione che permette di scegliere il file PDF dalla memoria telefono | |
selectPdfFromStorage() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//codice del file PDF | |
companion object { | |
private const val PDF_SELECTION_CODE = 99 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//funzione che permette di scegliere il file PDF dalla memoria telefono | |
private fun selectPdfFromStorage() { | |
Toast.makeText(this, "Seleziona file PDF", Toast.LENGTH_LONG).show() | |
val browseStorage = Intent(Intent.ACTION_GET_CONTENT) | |
browseStorage.type = "application/pdf" | |
browseStorage.addCategory(Intent.CATEGORY_OPENABLE) | |
startActivityForResult( | |
Intent.createChooser(browseStorage, "Seleziona PDF"), PDF_SELECTION_CODE | |
) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//funzione che resituisce il risultato di un Intent | |
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { | |
super.onActivityResult(requestCode, resultCode, data) | |
if (requestCode == PDF_SELECTION_CODE && resultCode == Activity.RESULT_OK && data != null) { | |
//dichiarazione variabile che contiene il percorso in cui è memorizzato il file PDF | |
val selectedPdfFromStorage = data.data | |
showPdfFromUri(selectedPdfFromStorage) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//funzione per visualizzare il file PDF | |
private fun showPdfFromUri(uri: Uri?) { | |
pdfView.fromUri(uri) | |
.password(null) //se protetto da password, inserire la password qui altrimenti null | |
.defaultPage(0) //impostazione della pagina da visualizzare all'apertura | |
//0 = pagina 1 | |
.scrollHandle(DefaultScrollHandle(this)) //visualizza il numero della pagina corrente | |
.onPageError { page, _ -> | |
Toast.makeText(this, "Error at page: $page", Toast.LENGTH_LONG).show() } | |
.load() //caricamento del file | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.dm.tutorialpdfview3 | |
import android.app.Activity | |
import android.content.Intent | |
import android.net.Uri | |
import androidx.appcompat.app.AppCompatActivity | |
import android.os.Bundle | |
import android.widget.Toast | |
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle | |
import kotlinx.android.synthetic.main.activity_main.* | |
class MainActivity : AppCompatActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
//chiamata alla funzione che permette di scegliere il file PDF dalla memoria telefono | |
selectPdfFromStorage() | |
} | |
//codice del file PDF | |
companion object { | |
private const val PDF_SELECTION_CODE = 99 | |
} | |
//funzione che permette di scegliere il file PDF dalla memoria telefono | |
private fun selectPdfFromStorage() { | |
Toast.makeText(this, "Seleziona file PDF", Toast.LENGTH_LONG).show() | |
val browseStorage = Intent(Intent.ACTION_GET_CONTENT) | |
browseStorage.type = "application/pdf" | |
browseStorage.addCategory(Intent.CATEGORY_OPENABLE) | |
startActivityForResult( | |
Intent.createChooser(browseStorage, "Seleziona PDF"), PDF_SELECTION_CODE | |
) | |
} | |
//funzione che resituisce il risultato di un Intent | |
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { | |
super.onActivityResult(requestCode, resultCode, data) | |
if (requestCode == PDF_SELECTION_CODE && resultCode == Activity.RESULT_OK && data != null) { | |
//dichiarazione variabile che contiene il percorso in cui è memorizzato il file PDF | |
val selectedPdfFromStorage = data.data | |
showPdfFromUri(selectedPdfFromStorage) | |
} | |
} | |
//funzione per visualizzare il file PDF | |
private fun showPdfFromUri(uri: Uri?) { | |
pdfView.fromUri(uri) | |
.password(null) //se protetto da password, inserire la password qui altrimenti null | |
.defaultPage(0) //impostazione della pagina da visualizzare all'apertura | |
//0 = pagina 1 | |
.scrollHandle(DefaultScrollHandle(this)) //visualizza il numero della pagina corrente | |
.onPageError { page, _ -> | |
Toast.makeText(this, "Error at page: $page", Toast.LENGTH_LONG).show() } | |
.load() //caricamento del file | |
} | |
} |
Download Project | ![]() |
Download file APK | ![]() |
ESEMPIO 4:
In questo esempio vedremo come visualizzare un file PDF recuperato dal Web all'interno di un PDFView. Simile all'ESEMPIO 3 ma il file è un link Web. In pratica quando viene avviata l'applicazione viene scaricato il file PDF indicato e visualizzato all'interno del PDFView, rispetto all'ESEMPIO 2 è possibile avere maggior controllo sulla visualizzazione del file.
Per prima cosa inserire i permessi per l'accesso ad internet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<uses-permission android:name="android.permission.INTERNET"/> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
implementation 'com.github.barteksc:android-pdf-viewer:2.8.2' | |
implementation 'com.mindorks.android:prdownloader:0.6.0' |
Ecco come si presenta il file activity_main.xml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<RelativeLayout | |
xmlns:android="http://schemas.android.com/apk/res/android" | |
xmlns:tools="http://schemas.android.com/tools" | |
android:layout_width="match_parent" | |
android:layout_height="match_parent" | |
tools:context=".MainActivity"> | |
<com.github.barteksc.pdfviewer.PDFView | |
android:id="@+id/pdfView" | |
android:layout_width="match_parent" | |
android:layout_height="match_parent" /> | |
</RelativeLayout> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//inizializzazione della libreria PRDownloader | |
PRDownloader.initialize(applicationContext) | |
//download del file PDF dal Web | |
val fileName = "myFile.pdf" | |
downloadPdfFromInternet(FileUtils.getPdfUrl(), FileUtils.getRootDirPath(this), fileName) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//visualizzazione del file PDF | |
private fun showPdfFromFile(file: File) { | |
pdfView.fromFile(file) | |
.password(null) | |
.defaultPage(0) | |
.scrollHandle(DefaultScrollHandle(this)) | |
.onPageError { page, _ -> | |
Toast.makeText(this, "Error at page: $page", Toast.LENGTH_LONG).show() | |
} | |
.load() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//download del file dal Web | |
//ATTENZIONE! il file PDF NON viene salvato nella memoria del dispositivo | |
private fun downloadPdfFromInternet(url: String, dirPath: String, fileName: String) { | |
PRDownloader.download(url, dirPath, fileName) | |
.build() | |
.start(object : OnDownloadListener { | |
override fun onDownloadComplete() { | |
Toast.makeText(this@MainActivity, "Download completato", Toast.LENGTH_LONG).show() | |
val downloadedFile = File(dirPath, fileName) | |
showPdfFromFile(downloadedFile) | |
} | |
override fun onError(error: com.downloader.Error?) { | |
Toast.makeText(this@MainActivity, "Errore durante il download del file: $error", Toast.LENGTH_LONG).show() | |
} | |
}) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//oggetto FileUtilis contiene il link Web del file e la cartella dove è stato scaricato il file | |
object FileUtils { | |
fun getPdfUrl(): String { | |
//inserire l'indirizzo completo del file PDF sul Web | |
return "https://www.google.com/document/AndroidStudio.pdf" | |
} | |
fun getRootDirPath(context: Context): String { | |
return if (Environment.MEDIA_MOUNTED == Environment.getExternalStorageState()) { | |
val file: File = ContextCompat.getExternalFilesDirs( | |
context.applicationContext, | |
null | |
)[0] | |
file.absolutePath | |
} else { | |
context.applicationContext.filesDir.absolutePath | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.dm.tutorialpdfview4 | |
import android.content.Context | |
import androidx.appcompat.app.AppCompatActivity | |
import android.os.Bundle | |
import android.os.Environment | |
import android.view.View | |
import android.widget.Toast | |
import androidx.core.content.ContextCompat | |
import com.downloader.OnDownloadListener | |
import com.downloader.PRDownloader //Importazione della Libreria: PRDownload | |
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle | |
import kotlinx.android.synthetic.main.activity_main.* | |
import java.io.File | |
class MainActivity : AppCompatActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
//inizializzazione della libreria PRDownloader | |
PRDownloader.initialize(applicationContext) | |
//download del file PDF dal Web | |
val fileName = "myFile.pdf" | |
downloadPdfFromInternet(FileUtils.getPdfUrl(), FileUtils.getRootDirPath(this), fileName) | |
} | |
//visualizzazione del file PDF | |
private fun showPdfFromFile(file: File) { | |
pdfView.fromFile(file) | |
.password(null) | |
.defaultPage(0) | |
.scrollHandle(DefaultScrollHandle(this)) | |
.onPageError { page, _ -> | |
Toast.makeText(this, "Error at page: $page", Toast.LENGTH_LONG).show() | |
} | |
.load() | |
} | |
//download del file dal Web | |
//ATTENZIONE! il file PDF NON viene salvato nella memoria del dispositivo | |
private fun downloadPdfFromInternet(url: String, dirPath: String, fileName: String) { | |
PRDownloader.download(url, dirPath, fileName) | |
.build() | |
.start(object : OnDownloadListener { | |
override fun onDownloadComplete() { | |
Toast.makeText(this@MainActivity, "Download completato", Toast.LENGTH_LONG).show() | |
val downloadedFile = File(dirPath, fileName) | |
showPdfFromFile(downloadedFile) | |
} | |
override fun onError(error: com.downloader.Error?) { | |
Toast.makeText(this@MainActivity, "Errore durante il download del file: $error", Toast.LENGTH_LONG).show() | |
} | |
}) | |
} | |
//oggetto FileUtilis contiene il link Web del file e la cartella dove è stato scaricato il file | |
object FileUtils { | |
fun getPdfUrl(): String { | |
//inserire l'indirizzo completo del file PDF sul Web | |
return "//https://www.google.com/document/AndroidStudio.pdf" | |
} | |
fun getRootDirPath(context: Context): String { | |
return if (Environment.MEDIA_MOUNTED == Environment.getExternalStorageState()) { | |
val file: File = ContextCompat.getExternalFilesDirs( | |
context.applicationContext, | |
null | |
)[0] | |
file.absolutePath | |
} else { | |
context.applicationContext.filesDir.absolutePath | |
} | |
} | |
} | |
} |

Nell'immagine non viene visualizzato alcun file PDF in quanto il collegamento Web al file PDF non esiste.
Download Project | ![]() |
Download file APK | ![]() |
Commenti
Posta un commento