https://kotlinlang.org logo
#javascript
Title
# javascript
r

Reuben F

07/04/2022, 6:33 PM
Hello, I wrapped html2pdf; the basic function works, but I haven't figured out a way to get it to accept its options dictionary. Anybody have a few minutes to try it out?
Copy code
import org.w3c.dom.Element

@JsModule("html2pdf.js")
@JsNonModule
external fun html2pdf(element: Element, opts: PdfOptions)

data class PdfOptions(val filename: String, val margin: Int)
Copy code
implementation(npm("html2pdf.js", "0.9.3"))
Copy code
html2pdf(someElement,
    PdfOptions("janet", 100)
)
whatever I try, it always downloads "file.pdf". seems like it should just work https://www.npmjs.com/package/html2pdf.js/v/0.9.3#image-type-and-quality
b

Big Chungus

07/04/2022, 6:43 PM
Make PdfOpts external class or interference and then initialize it like this js("{}"). unsafeCast<PdfOpts>().apply { ... }
r

Reuben F

07/04/2022, 6:48 PM
You mean like this?
Copy code
html2pdf(Root.getFirstRoot()!!.getElement()!! as HTMLElement,
                            js("{}").unsafeCast<PdfOptions>().apply {
                                filename = "janet"
                            }
                        )
doesn't apply options, still
b

Big Chungus

07/04/2022, 6:49 PM
PdfOptions being an external entity is key to this
Otherwise properties get mangled
r

Reuben F

07/04/2022, 6:56 PM
Copy code
html2pdf(Root.getFirstRoot()!!.getElement()!! as HTMLElement,
                            js("{}").unsafeCast<PdfOptions>().apply {
                                filename = "janet"
                            }
                        )

@JsModule("html2pdf.js")
@JsNonModule
external fun html2pdf(element: Element, opts: PdfOptions)

@JsModule("html2pdf.js")
@JsNonModule
external interface PdfOptions {
    var filename: String
    var margin: Int
}
this worked, thanks! really ugly though - is there any way around the unsafeCast? It doesn't work as:
Copy code
object: PdfOptions {
                                override val filename: String
                                    get() = "janet"
                                override val margin: Int
                                    get() = 10
                            }
b

Big Chungus

07/04/2022, 6:58 PM
Just write an inline Constructor function that hides this mess for free
fun PdfOptions(filename: String, margin: Int) = ...
23 Views