Lambda: Code snippet to image

    0

    1

    Jose Romero

    imagesnippetlambda

    Lambda function to convert code snippet into an image, package.json should be provided. The recommended package.json would be:

    {
        "name": "snippet-renderer",
        "version": "0.0.1",
        "scripts": {
            "locally": "NODE_ENV=dev node -e \"require('./index').handler(require('./event.json'));\""
        },
        "dependencies": {
            "node-html-to-image": "3.2.0"
        }
      }
    

    The event it receives, which in the example is stored in an event.json file, has the format:

        "code": "def area_circle(radius): \n return pi * radius ** 2",
        "language": "python"
    }```
    
    const nodeHtmlToImage = require("node-html-to-image");
    
    exports.handler = async (event) => {
      nodeHtmlToImage({
        output: "./image.png",
        html: `<html>
        <head>
            <style>
                body {
                    background-image: linear-gradient(90deg,#f81c9d,#fc8926);
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }
                .CodeMirror {
                    width: 100%;
                    font-size: 20px;
                }
            </style>
        <link rel="stylesheet"
            href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.1/codemirror.min.css">
        <link rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.1/theme/darcula.min.css">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.1/codemirror.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.1/mode/${event.language}/${event.language}.min.js"></script>
        </head>
        <body>
        <textarea id="textarea">${event.code}</textarea>
        <script>
          var editor = CodeMirror.fromTextArea(document.querySelector("#textarea"), 
            {
              mode: '${event.language}',
              lineNumbers: true,
            }
          )
          editor.save();
        </script>
        </body>
        </html>`,
      });
      return {
        statusCode: 200,
        body: JSON.stringify("Hello from Lambda!"),
      };
    };
    
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    Legal
    • Security
    • Privacy Policy
    • Code Privacy
    • Terms of Service
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.