Created
January 10, 2020 13:53
-
-
Save reuniware/a89b505197f41a28ab334aa1049b989b to your computer and use it in GitHub Desktop.
(Android/Kotlin) Write unlimited number of lines to PDF (A4).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun createAndWritePdf() { | |
initPdfDocument() | |
writeToPdfDocument("One line...") | |
writeToPdfDocument("Another line...") | |
closePdfDocument() | |
savePdfDocument() | |
} | |
lateinit var document : PdfDocument | |
lateinit var pageInfo: PdfDocument.PageInfo | |
lateinit var page: PdfDocument.Page | |
lateinit var canvas : Canvas | |
lateinit var paint : Paint | |
val textSize = 16F | |
val marginLeft = 8F | |
var y = textSize | |
val pageHeight = 842 | |
val pageWidth = 595 | |
var currentPage = 1 | |
fun initPdfDocument() { | |
document = PdfDocument() | |
pageInfo = PdfDocument.PageInfo.Builder(pageWidth, pageHeight, currentPage).create() | |
page = document.startPage(pageInfo) | |
canvas = page.canvas | |
paint = Paint() | |
paint.color = Color.BLACK | |
paint.textSize = textSize | |
} | |
fun writeToPdfDocument(strToWrite: String) { | |
if (y > pageHeight) { | |
document.finishPage(page) | |
currentPage++ | |
pageInfo = PdfDocument.PageInfo.Builder(pageWidth, pageHeight, currentPage).create() | |
page = document.startPage(pageInfo) | |
canvas = page.canvas | |
y = textSize | |
} | |
canvas.drawText(strToWrite, marginLeft, y, paint) | |
y += textSize | |
} | |
fun closePdfDocument() { | |
document.finishPage(page) | |
} | |
fun savePdfDocument() { | |
val directory = Environment.getExternalStorageDirectory().path + "/MyPdfOutputDir/" | |
val file = File(directory) | |
if (!file.exists()) | |
{ | |
val result = file.mkdirs() | |
} | |
val targetPdf = directory + "MyFilename.pdf" | |
val filePath = File(targetPdf) | |
try { | |
document.writeTo(FileOutputStream(filePath)) | |
} catch (t: Throwable) { | |
} | |
document.close() | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment