fun ggsave()

in plot-api/src/jvmMain/kotlin/org/jetbrains/letsPlot/export/ggsave.kt [104:180]


fun ggsave(
    plot: Figure,
    filename: String,
    scale: Number? = null,
    dpi: Number? = null,
    path: String? = null,
    w: Number? = null,
    h: Number? = null,
    unit: String? = null
): String {

    @Suppress("NAME_SHADOWING")
    val filename = filename.trim()
    require(filename.indexOf('.') >= 0) {
        "File extension is missing: \"$filename\"."
    }
    require(filename.substringBeforeLast('.', "").isNotEmpty()) {
        "Malformed filename: \"$filename\"."
    }
    val ext = filename.substringAfterLast('.', "").lowercase(Locale.getDefault())
    require(ext.isNotEmpty()) { "Missing file extension: \"$filename\"." }

    val dir = path?.let { Path(path) } ?: Path(System.getProperty("user.dir"), DEF_EXPORT_DIR)
    dir.createDirectories()
    val file = dir.resolve(filename)

    val spec: MutableMap<String, Any> = plot.toSpec()
    val sizeUnit = PlotExportCommon.SizeUnit.fromName(unit ?: "")
    val plotSize = toDoubleVector(w, h)

    when (ext) {
        "svg" -> {
            val svg = PlotSvgExport.buildSvgImageFromRawSpecs(
                spec,
                plotSize = plotSize,
                sizeUnit = sizeUnit ?: PlotExportCommon.SizeUnit.PX,
            )
            if (file.notExists()) {
                file.createFile()
            }
            file.writeText(svg)
        }

        "html", "htm" -> {
            val html = PlotHtmlExport.buildHtmlFromRawSpecs(
                spec,
                scriptUrl = scriptUrl(VersionChecker.letsPlotJsVersion),
                iFrame = true,
                plotSize = plotSize
            )
            if (file.notExists()) {
                file.createFile()
            }
            file.writeText(html)
        }

        "png", "jpeg", "jpg", "tiff", "tif" -> {
            exportRasterImage(
                spec,
                file,
                scalingFactor = scale,
                plotSize = plotSize,
                unit = sizeUnit,
                targetDPI = dpi
            )
        }

        else -> throw java.lang.IllegalArgumentException(
            """
            Unsupported file extension: "$ext".
            Please use one of: "svg", "html", "htm", "png", "jpeg", "jpg", "tiff", "tif". 
        """.trimIndent()
        )
    }

    return file.toRealPath().toString()
}