Add app/src/main/java/space/bloggin/scribe/Export.kt
This commit is contained in:
@@ -0,0 +1,118 @@
|
||||
package space.bloggin.scribe
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Typeface
|
||||
import android.graphics.pdf.PdfDocument
|
||||
import androidx.core.content.FileProvider
|
||||
import java.io.File
|
||||
import java.util.zip.ZipEntry
|
||||
import java.util.zip.ZipOutputStream
|
||||
|
||||
/** Turns notes into a PDF or Word (.docx) file and hands it to the share sheet. */
|
||||
object Export {
|
||||
const val PDF_MIME = "application/pdf"
|
||||
const val DOCX_MIME = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
||||
|
||||
private fun heading(n: Note) = Ui.fmtDate(n.created)
|
||||
|
||||
fun share(act: Activity, notes: List<Note>, name: String, docx: Boolean) {
|
||||
val list = notes.filter { it.text.isNotBlank() }
|
||||
if (list.isEmpty()) {
|
||||
android.widget.Toast.makeText(act, "Nothing to export yet", android.widget.Toast.LENGTH_SHORT).show()
|
||||
return
|
||||
}
|
||||
val dir = File(act.cacheDir, "exports").also { it.mkdirs() }
|
||||
dir.listFiles()?.forEach { it.delete() }
|
||||
val safe = name.replace(Regex("[^A-Za-z0-9 ._-]"), "").trim().ifEmpty { "Notes" }
|
||||
val f = File(dir, safe + if (docx) ".docx" else ".pdf")
|
||||
if (docx) writeDocx(f, list) else writePdf(f, list)
|
||||
val uri = FileProvider.getUriForFile(act, act.packageName + ".files", f)
|
||||
val i = Intent(Intent.ACTION_SEND)
|
||||
.setType(if (docx) DOCX_MIME else PDF_MIME)
|
||||
.putExtra(Intent.EXTRA_STREAM, uri)
|
||||
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||
act.startActivity(Intent.createChooser(i, if (docx) "Save or send Word file" else "Save or send PDF"))
|
||||
}
|
||||
|
||||
fun fileName(notes: List<Note>): String =
|
||||
if (notes.size == 1) "Note " + java.text.SimpleDateFormat("yyyy-MM-dd HHmm", java.util.Locale.US).format(java.util.Date(notes[0].created))
|
||||
else "Hey Dumby notes " + java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.US).format(java.util.Date())
|
||||
|
||||
// ---------- PDF ----------
|
||||
private fun writePdf(out: File, notes: List<Note>) {
|
||||
val pageW = 612
|
||||
val pageH = 792
|
||||
val margin = 54f
|
||||
val body = Paint().apply { textSize = 12f; color = 0xFF111111.toInt(); isAntiAlias = true }
|
||||
val head = Paint().apply { textSize = 11f; color = 0xFF6B6B73.toInt(); isAntiAlias = true; typeface = Typeface.DEFAULT_BOLD }
|
||||
val lineH = 17f
|
||||
val maxW = pageW - margin * 2
|
||||
val doc = PdfDocument()
|
||||
var pageNo = 0
|
||||
var page: PdfDocument.Page? = null
|
||||
var y = 0f
|
||||
fun newPage() {
|
||||
page?.let { doc.finishPage(it) }
|
||||
pageNo++
|
||||
page = doc.startPage(PdfDocument.PageInfo.Builder(pageW, pageH, pageNo).create())
|
||||
y = margin
|
||||
}
|
||||
fun ensure(h: Float) { if (page == null || y + h > pageH - margin) newPage() }
|
||||
|
||||
for ((idx, n) in notes.withIndex()) {
|
||||
ensure(lineH * 3)
|
||||
if (idx > 0) y += lineH
|
||||
page!!.canvas.drawText(heading(n), margin, y + 11f, head)
|
||||
y += lineH + 4f
|
||||
for (para in n.text.split("\n")) {
|
||||
if (para.isBlank()) { ensure(lineH); y += lineH; continue }
|
||||
var line = StringBuilder()
|
||||
for (word in para.split(" ")) {
|
||||
val trial = if (line.isEmpty()) word else "$line $word"
|
||||
if (body.measureText(trial) <= maxW) { line = StringBuilder(trial); continue }
|
||||
if (line.isNotEmpty()) {
|
||||
ensure(lineH); page!!.canvas.drawText(line.toString(), margin, y + 12f, body); y += lineH
|
||||
}
|
||||
line = StringBuilder(word)
|
||||
}
|
||||
if (line.isNotEmpty()) { ensure(lineH); page!!.canvas.drawText(line.toString(), margin, y + 12f, body); y += lineH }
|
||||
}
|
||||
}
|
||||
page?.let { doc.finishPage(it) }
|
||||
out.outputStream().use { doc.writeTo(it) }
|
||||
doc.close()
|
||||
}
|
||||
|
||||
// ---------- Word (.docx) ----------
|
||||
private fun esc(s: String) = s.replace("&", "&").replace("<", "<").replace(">", ">")
|
||||
|
||||
private fun writeDocx(out: File, notes: List<Note>) {
|
||||
val sb = StringBuilder()
|
||||
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>")
|
||||
sb.append("<w:document xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"><w:body>")
|
||||
for ((idx, n) in notes.withIndex()) {
|
||||
if (idx > 0) sb.append("<w:p><w:r><w:br w:type=\"page\"/></w:r></w:p>")
|
||||
sb.append("<w:p><w:r><w:rPr><w:b/><w:color w:val=\"6B6B73\"/></w:rPr><w:t xml:space=\"preserve\">")
|
||||
.append(esc(heading(n))).append("</w:t></w:r></w:p>")
|
||||
for (para in n.text.split("\n")) {
|
||||
sb.append("<w:p><w:r><w:t xml:space=\"preserve\">").append(esc(para)).append("</w:t></w:r></w:p>")
|
||||
}
|
||||
}
|
||||
sb.append("<w:sectPr><w:pgSz w:w=\"12240\" w:h=\"15840\"/><w:pgMar w:top=\"1440\" w:right=\"1440\" w:bottom=\"1440\" w:left=\"1440\" w:header=\"720\" w:footer=\"720\" w:gutter=\"0\"/></w:sectPr>")
|
||||
sb.append("</w:body></w:document>")
|
||||
ZipOutputStream(out.outputStream()).use { z ->
|
||||
fun put(name: String, text: String) { z.putNextEntry(ZipEntry(name)); z.write(text.toByteArray(Charsets.UTF_8)); z.closeEntry() }
|
||||
put("[Content_Types].xml",
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">" +
|
||||
"<Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>" +
|
||||
"<Default Extension=\"xml\" ContentType=\"application/xml\"/>" +
|
||||
"<Override PartName=\"/word/document.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml\"/></Types>")
|
||||
put("_rels/.rels",
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">" +
|
||||
"<Relationship Id=\"rId1\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument\" Target=\"word/document.xml\"/></Relationships>")
|
||||
put("word/document.xml", sb.toString())
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user