Skip to content

Instantly share code, notes, and snippets.

@NyxCode
Created April 25, 2019 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NyxCode/f26abcda8e888346d6d1ff418b40d3a1 to your computer and use it in GitHub Desktop.
Save NyxCode/f26abcda8e888346d6d1ff418b40d3a1 to your computer and use it in GitHub Desktop.
use all fonts available on fonts.google.com in Kotlin JVM applications
import org.apache.commons.io.FileUtils
import java.awt.Font
import java.awt.GraphicsEnvironment
import java.io.File
import java.io.FileNotFoundException
import java.net.URL
private const val FONTS_REPOSITORY = "https://github.com/google/fonts/raw/master"
private val LICENSES = arrayOf("apache", "ofl", "ufl")
private val SANITIZE_EXPR = Regex("\\W+")
enum class Emphasis {
Regular,
Bold,
Italic,
Light,
Medium,
Thin,
Black
}
fun installFont(name: String, vararg emphasis: Emphasis) {
print("Downloading Font..")
val file = downloadFont(_fontName = name, emphasis = *emphasis)
print("Installing Font..")
GraphicsEnvironment
.getLocalGraphicsEnvironment()
.registerFont(Font.createFont(Font.TRUETYPE_FONT, file))
print("Done!")
}
fun downloadFont(directory: File = createTempDir(), _fontName: String, vararg emphasis: Emphasis): File {
assert(directory.isDirectory) { "$directory is not a directory" }
val fontName = _fontName.replace(SANITIZE_EXPR, "")
val fileName = constructFilename(fontName, *emphasis)
val targetFile = File(directory, fileName)
if (targetFile.isFile) {
println("$targetFile already exists, skipping download")
return targetFile
}
for (license in LICENSES) {
try {
val url = URL("$FONTS_REPOSITORY/$license/${fontName.toLowerCase()}/$fileName")
FileUtils.copyURLToFile(url, targetFile)
return targetFile
} catch (_: FileNotFoundException) {
// Ignore
}
}
throw FileNotFoundException()
}
private fun constructFilename(sanitizedName: String, vararg emphasis: Emphasis): String {
val emphasisStr = if (emphasis.isEmpty()) {
"Regular"
} else {
emphasis
.distinct()
.map(Emphasis::name)
.joinToString(separator = "")
}
return "$sanitizedName-$emphasisStr.ttf"
}
@NyxCode
Copy link
Author

NyxCode commented Apr 25, 2019

installFont("Roboto", Emphasis.BOLD)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment