I am trying to download a pdf from URL and display it via PDF Renderer in Jetpack Compose. I use the following code:
@Composable
actual fun openFile(url: String): Boolean {
var display by remember {
mutableStateOf(false)
}
val file = File.createTempFile("file", ".pdf")
file.deleteOnExit()
LaunchedEffect(true) {
val response = withContext(Dispatchers.IO) {
val client = OkHttpClient()
val request = Request.Builder().url(url).build()
val body = client.newCall(request).execute().body()
println(body.contentType())
body.bytes()
}
file.writeBytes(response)
display = true
}
if (display) {
val parcelFileDescriptor =
ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
val pdfRenderer: PdfRenderer
try {
pdfRenderer = PdfRenderer(parcelFileDescriptor)
} catch (e: Exception) {
println(e)
return false
}
val pages = mutableListOf<ImageBitmap>()
for (i in 0 until pdfRenderer.pageCount) {
val page = pdfRenderer.openPage(i)
val bitmap = Bitmap.createBitmap(page.width, page.height, Bitmap.Config.ARGB_8888)
page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
pages.add(bitmap.asImageBitmap())
page.close()
}
pdfRenderer.close()
parcelFileDescriptor.close()
file.delete()
LazyColumn {
pages.forEach { image ->
item {
Image(
bitmap = image,
contentDescription = "PDF page"
)
}
}
}
} else {
CircularProgressIndicator(color = Color.White)
}
return true
}
But I keep getting an IOException that the file is invalid despite the fact that file extension is .pdf and body.contentType() also prints "application/pdf".
Can anyone help me resolve the issue?
Example URL that app loads: https://accorm.ginastic.co/200/IGCSE/accounting/QP/0452_w23_qp_11.pdf
Well...3rd party libraries seemed a better option, so I switched to
https://github.com/GRizzi91/bouquet
io.github.grizzi91:bouquet