我正在尝试从 URL 下载 pdf 并通过 Jetpack Compose 中的 PDF 渲染器显示它。我使用以下代码:
@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
}
但我不断收到一个 IOException 异常,表明文件无效,尽管文件扩展名是 .pdf 并且 body.contentType() 也打印“application/pdf”。
谁能帮我解决这个问题吗?
应用程序加载的示例 URL:https://accorm.ginastic.co/200/IGCSE/accounting/QP/0452_w23_qp_11.pdf
嗯...第三方库似乎是更好的选择,所以我切换到
io.github.grizzi91:bouquet