You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于Kotlin与Jetpack Compose将应用屏幕内容转PDF?

在Jetpack Compose中生成屏幕可见内容为PDF的实现方法

方法一:捕获Compose视图为Bitmap后转PDF

这种方法先将屏幕可见的Compose内容转为Bitmap,再通过Android原生PdfDocument生成PDF,适合自定义生成逻辑的场景。

步骤1:捕获Compose视图的Bitmap

通过LocalView.current获取当前Compose对应的Android View,将其绘制到Bitmap上:

val context = LocalContext.current
val view = LocalView.current

// 建议在按钮点击等用户触发事件中执行,确保视图已完成布局
val captureBitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(captureBitmap)
view.draw(canvas)

步骤2:将Bitmap写入PDF文件

使用PdfDocument创建文档,将Bitmap绘制到PDF页面并保存:

val pdfDocument = PdfDocument()
// 创建与Bitmap尺寸一致的页面
val pageInfo = PdfDocument.PageInfo.Builder(captureBitmap.width, captureBitmap.height, 1).create()
val page = pdfDocument.startPage(pageInfo)
val pdfCanvas = page.canvas
// 绘制Bitmap到PDF画布
pdfCanvas.drawBitmap(captureBitmap, 0f, 0f, null)
pdfDocument.finishPage(page)

// 保存到应用私有目录(无需存储权限)
val pdfFile = File(context.getExternalFilesDir(null), "screen_content.pdf")
try {
    pdfDocument.writeTo(FileOutputStream(pdfFile))
} catch (e: IOException) {
    e.printStackTrace()
} finally {
    pdfDocument.close()
}

方法二:利用系统打印服务生成PDF

通过Android的PrintManager将Compose内容作为打印任务,可通过系统界面选择保存为PDF,适合标准化打印格式的场景:

val context = LocalContext.current
val composeView = LocalView.current

val printManager = context.getSystemService(Context.PRINT_SERVICE) as PrintManager
// 创建打印适配器
val printAdapter = composeView.createPrintDocumentAdapter("Screen_PDF")
// 自定义打印属性(页面尺寸、分辨率等)
val printAttributes = PrintAttributes.Builder()
    .setMediaSize(PrintAttributes.MediaSize.ISO_A4)
    .setResolution(PrintAttributes.Resolution("pdf_res", Context.PRINT_SERVICE, 300, 300))
    .setColorMode(PrintAttributes.COLOR_MODE_COLOR)
    .build()

// 发起打印请求,系统弹出预览界面后可选择保存为PDF
printManager.print("导出屏幕内容为PDF", printAdapter, printAttributes)

注意事项

  • 捕获Bitmap时需确保视图已完成测量布局,避免在Compose重组初期调用导致尺寸异常。
  • 若保存到外部公共存储,Android 10+需使用MediaStore API,Android 9及以下需申请WRITE_EXTERNAL_STORAGE权限。
  • 大尺寸视图需考虑分页处理,避免内存溢出。

内容的提问来源于stack exchange,提问作者Javier García

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 10:33:36