Sample code for 30+ languages & platforms
Swift Requires Chilkat v11.7.0+

Embed a QR Code in HTML as a Data URI

See more QR Code Examples

Demonstrates putting a QR code directly into an HTML page or HTML email with no separate image file. The base64 PNG returned by QrCode becomes the src of an img tag as a data URI, which is the MIME type from outputs[0].mimeType followed by the base64 from outputs[0].base64.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    //  This example requires the Chilkat API to have been previously unlocked.
    //  See Global Unlock Sample for sample code.

    let json = CkoJsonObject()!
    json.updateString(jsonPath: "payload.text", value: "https://www.chilkatsoft.com/")
    json.updateInt(jsonPath: "render.moduleSize", value: 5)

    let fmt = CkoFormats()!
    let jsonOut = CkoJsonObject()!
    success = fmt.qrCode(op: "generate", jsonIn: json, jsonOut: jsonOut)
    if success == false {
        print("\(fmt.lastErrorText!)")
        return
    }

    //  A data URI has the form  data:<MIME type>;base64,<base64 data>
    let sbHtml = CkoStringBuilder()!
    sbHtml.append(value: "<html><body><p>Scan to visit chilkatsoft.com</p><img alt=\"QR code\" width=\"")
    sbHtml.appendInt(value: jsonOut.int(of: "outputs[0].width").intValue)
    sbHtml.append(value: "\" height=\"")
    sbHtml.appendInt(value: jsonOut.int(of: "outputs[0].height").intValue)
    sbHtml.append(value: "\" src=\"data:")
    sbHtml.append(value: jsonOut.string(of: "outputs[0].mimeType"))
    sbHtml.append(value: ";base64,")
    sbHtml.append(value: jsonOut.string(of: "outputs[0].base64"))
    sbHtml.append(value: "\"></body></html>")

    success = sbHtml.writeFile(path: "qa_output/qr_page.html", charset: "utf-8", emitBom: false)
    if success == false {
        print("\(sbHtml.lastErrorText!)")
        return
    }

    print("image: \(jsonOut.int(of: "outputs[0].width").intValue) x \(jsonOut.int(of: "outputs[0].height").intValue) pixels")
    print("HTML length: \(sbHtml.length.intValue)")

    //  The page, as a browser shows it:

    //  image

    //  Sample output:

    //  image: 185 x 185 pixels
    //  HTML length: 1211

}