作者:游泳 | 来源:互联网 | 2023-09-18 19:00
篇首语:本文由编程笔记#小编为大家整理,主要介绍了Android中Kotlin创建PDF相关的知识,希望对你有一定的参考价值。
一、创建 PDF 流程
首先看官网的文档,下面介绍基于 SDK 怎么样来创建 PDF 文件的流程。
//先创建一个 PdfDocument 对象 document
PdfDocument document = new PdfDocument();
//创建 PageInfo 对象,用于描述 PDF 中单个的页面
PageInfo pageInfo = new PageInfo.Builder(new Rect(0, 0, 100, 100), 1).create();
//开始启动内容填写
Page page = document.startPage(pageInfo);
//绘制文字。
page.canvas.drawText("PDF绘制",70.0f,200.0f, mPaint)
//停止对页面的填写
document.finishPage(page);
. . .
//将文件写入流
document.writeTo(getOutputStream());
//关闭流
document.close();
二、创建PDF实例
接下来参考创建流程进行代码的编写,创建Activity。
进行一个简单的例子,在一页PDF中绘制一个标题、内容及加载图片。
class PdfActivity
private val CODE_WRITE_EXTERNAL = 1
var file : File? = null
var mPaint : Paint? = null
var matrix : Matrix? = null
var screenWidth : Int = 210*28/10
var screenHeight : Int = 297*28/10
val document = PdfDocument()
var str : String = ""
public fun creatPDF(file:String)
str = "pdfFile"
mPaint = Paint()
mPaint?.isAntiAlias = true
mPaint?.strokeWidth = 10.0f
mPaint?.isFakeBoldText = true
mPaint?.color = Color.BLACK
mPaint?.textSize = 35.0f
matrix = Matrix()
matrix?.setScale(0.5f, 0.5f)
matrix?.postScale(0.15f,0.15f)
val root = Environment.getExternalStorageDirectory()
//val showBitmap : Bitmap = BitmapFactory.decodeResource(getResources(), 'banlei.png')
val showBitmap = BitmapFactory.decodeFile("/sdcard/test.png") //放到设备中的一张图片路径
var bitMapWidth : Int = showBitmap.getWidth()
var bitMapHeight : Int = showBitmap.getHeight()
val bm : Bitmap = Bitmap.createBitmap(
showBitmap, 0, 0, showBitmap.width,
showBitmap.height, matrix, true
)
val info1 = PdfDocument.PageInfo.Builder(
screenWidth, screenHeight, 1
).create()
val page1 = document.startPage(info1)
mPaint?.let page1.canvas.drawText("PDF文档报告",170.0f,130.0f, it)
mPaint?.textSize = 20.0f
mPaint?.let page1.canvas.drawText("PDF中的内容信息描述",70.0f,200.0f, it)
mPaint?.let page1.canvas.drawBitmap(bm, 350.0f, 500.0f, it)
document.finishPage(page1)
try
document.writeTo(outputStream)
catch (e: IOException)
e.printStackTrace()
//toast("生成pdf成功,路径:$file")
document.close()
private val outputStream: OutputStream?
get()
val root = Environment.getExternalStorageDirectory()
val filePath = Environment.getExternalStorageDirectory().absolutePath + "/PdfPath/" +str
var file = File(filePath)
if (!file.exists())
//cleanDir(file)
//file.delete()
file.mkdirs()
var filepdf = File(file, str+".pdf")
try
val os = FileOutputStream(filepdf)
os.flush()
//强制文件系统刷新
os.getFD().sync()
return os
catch (e: FileNotFoundException)
e.printStackTrace()
return null
fun cleanDir(f: File)
val listf = f.listFiles()
for (index in 0 until listf.size)
listf[index].delete()
以上PDF中文字插入及图片加载功能基本实现