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)
//創(chuàng)建表格
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)
// 添加一行數(shù)據(jù)
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) //創(chuàng)建字體
每一頁添加內容
每頁右下角添加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)
}
}