欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android iText 生成pdf

程序员文章站 2024-03-24 11:46:16
...

gradle

compile('com.itextpdf:itextg:5.5.10') {
        exclude group: 'com.itextpdf.text.pdf', module: 'fonts'
    }
compile 'org.bouncycastle:bcprov-jdk15on:1.49' //加密
compile 'org.bouncycastle:bcpkix-jdk15on:1.49' //加密

生成pdf

val base = BaseFont.createFont("assets/STSong.TTF",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED)//中文字体
val pdf = Document(PageSize.A4, 42f, 42f, 50f, 42f)
val writer = PdfWriter.getInstance(pdf, FileOutputStream(file))
pdf.open()
//居中标题
val font = Font(base, 14f)
font.style = Font.BOLD
val title = Paragraph("pdf标题",font)
title.alignment = Element.ALIGN_CENTER
pdf.add(title)
//创建表格
val table = PdfPTable(2) // columns.  2 列
table.widthPercentage = 96f // Width 100%
table.spacingBefore = 20f // Space before table
table.spacingAfter = 10f // Space after table
table.setWidths(intArrayOf(1,2)) //宽度占比
// 合并两个单元格 居中显示标题
val name = PdfPCell(Paragraph("单元格标题", font ))
name.backgroundColor =BaseColor.LIGHT_GRAY
name.colspan = 2 //占两列
name.setPadding(6f)
name.horizontalAlignment = Element.ALIGN_CENTER
table.addCell(name)
// 添加一行数据
val cell1= PdfPCell(Paragraph("单元格1", font ))
val cell2= PdfPCell(Paragraph("单元格2", font ))
table.addCell(cell1)
table.addCell(cell2)
// 添加图片
var img = Image.getInstance(imgurl)
img.scaleToFit(300f,400f) //缩放
pdf.add(img)
//添加空行
pdf.add(Chunk.NEWLINE)
pdf.close()
writer.close()

加密pdf

val OWNERPASSWORD ="123456" 
var reader = PdfReader(sourceFile)
var stamp = PdfStamper(reader, FileOutputStream(encryptedFile))
stamp.setEncryption(null, OWNERPASSWORD.toByteArray(), PdfWriter.ALLOW_PRINTING, false)
stamp.setFormFlattening(true)
stamp.close()
reader.close()

OWNERPASSWORD 是拥有者自定义密码。
PdfWriter.ALLOW_PRINTING 表示默认开放的权限级别,此处表示默认不输入密码可以进行查看打印,但是修改文档需要输入密码。
PdfWriter.ALLOW_MODIFY_CONTENTS 表示不输入密码就可以修改文档

中文字体支持

assets目录添加 STSong.TTF字体文件

val base = BaseFont.createFont("assets/STSong.TTF",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED) //创建字体

每一页添加内容

每页右下角添加logo

// 每页右下角添加logo
val pdf = Document(PageSize.A4, 42f, 42f, 50f, 42f)
val file = File(distFile)
val writer = PdfWriter.getInstance(pdf, FileOutputStream(file))
writer.pageEvent = PageFooter(logo)

class PageFooter(logo:Image):PdfPageEventHelper(){
        var logo:Image = logo
        override fun onEndPage(writer: PdfWriter, document: Document) {
            super.onEndPage(writer, document)
            logo.alignment = Element.ALIGN_RIGHT
            logo.setAbsolutePosition(document.right()-10,document.bottom()-22)
            document?.add(logo)
        }
    }