添加pdf的第一页图片资源,缓存到app目录中,保存路径到数据库。
This commit is contained in:
parent
167b5574ec
commit
9b5cd5e014
@ -1,12 +1,18 @@
|
||||
package com.all.pdfreader.pro.app.util
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.pdf.PdfRenderer
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.util.Log
|
||||
import com.all.pdfreader.pro.app.room.entity.PdfDocumentEntity
|
||||
import com.all.pdfreader.pro.app.room.repository.PdfRepository
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.util.concurrent.TimeUnit
|
||||
import androidx.core.graphics.createBitmap
|
||||
|
||||
class PdfScanner(
|
||||
private val context: Context,
|
||||
@ -55,6 +61,8 @@ class PdfScanner(
|
||||
|
||||
if (existingDoc == null) {
|
||||
LogUtil.logDebug("ocean", "PdfScanner: 🆕 发现新PDF文件: ${file.name}")
|
||||
val thumbnailPath = generateThumbnail(context, file)
|
||||
|
||||
val metadata =
|
||||
PdfMetadataExtractor.extractMetadata(file.absolutePath)
|
||||
val document = PdfDocumentEntity(
|
||||
@ -64,6 +72,7 @@ class PdfScanner(
|
||||
fileSize = file.length(),
|
||||
lastModified = file.lastModified(),
|
||||
pageCount = metadata?.pageCount ?: 0,
|
||||
thumbnailPath = thumbnailPath,
|
||||
metadataTitle = metadata?.title,
|
||||
metadataAuthor = metadata?.author,
|
||||
metadataSubject = metadata?.subject,
|
||||
@ -124,4 +133,41 @@ class PdfScanner(
|
||||
val lastScan = getLastScanTime()
|
||||
return TimeUnit.MILLISECONDS.toHours(System.currentTimeMillis() - lastScan)
|
||||
}
|
||||
|
||||
|
||||
private fun generateThumbnail(context: Context, pdfFile: File): String? {
|
||||
return try {
|
||||
val fileDescriptor = ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_ONLY)
|
||||
val pdfRenderer = PdfRenderer(fileDescriptor)
|
||||
|
||||
if (pdfRenderer.pageCount > 0) {
|
||||
val page = pdfRenderer.openPage(0)
|
||||
val bitmap = createBitmap(page.width, page.height)
|
||||
page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
|
||||
page.close()
|
||||
|
||||
// 保存到缓存目录
|
||||
val cacheDir = File(context.cacheDir, "thumbnails")
|
||||
if (!cacheDir.exists()) cacheDir.mkdirs()
|
||||
val thumbFile = File(cacheDir, pdfFile.nameWithoutExtension + ".jpg")
|
||||
|
||||
FileOutputStream(thumbFile).use { out ->
|
||||
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out)
|
||||
}
|
||||
|
||||
pdfRenderer.close()
|
||||
fileDescriptor.close()
|
||||
|
||||
thumbFile.absolutePath
|
||||
} else {
|
||||
pdfRenderer.close()
|
||||
fileDescriptor.close()
|
||||
null
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user