render html text to bitmap using javascript without serverSide code

后端 未结 1 840
轮回少年
轮回少年 2021-01-03 14:12

i need to use a javascript code to convert the articles, posts in html to be viewed to the end user as a bitmap, is there any way to do it, without server side code?

相关标签:
1条回答
  • 2021-01-03 14:32

    You can use for example html2canvas to convert your page to bitmap.

    If your HTML does not contain any external references you can also use my following function:

    /**
     *    Canvas extension: drawHTMLText(txt, options)
     *    By Ken Nilsen, Epistemex
     *    http://epistemex.com/
     *
     *    USAGE:
     *        myContext.drawHTMLText(txt [, options]);
     *
     *    var options = {x: startPosition,
     *                   y: startPosition,
     *                   width: maxWidth,
     *                   height: maxHeight,
     *                   callback: myFunction,
     *                   callbackError: myErrorFunction}
     *
     *    Each individual option is optional in themself. The callback
     *    on success contains an object with reference to result and
     *    originalText. Error callback is provided with the error object.
     *
     *    License: MIT
     */
    
    CanvasRenderingContext2D.prototype.drawHTMLText = function(txt, options) {
    
        /// make sure we have an object if none was provided
        options = options || {};
    
        var ctx = this,
    
            /// build inline SVG
            iSVG =
    
            '<svg xmlns="http://www.w3.org/2000/svg" width="' +
            (options.width ? options.width : ctx.canvas.width) +
    
            '" height="' +
            (options.height ? options.height : ctx.canvas.height) +
            '"><foreignObject width="100%" height="100%">' +
    
            '<div xmlns="http://www.w3.org/1999/xhtml" style="font:' +
            ctx.font + ';color:' + ctx.fillStyle + '">' +
    
            txt +
    
            "</div></foreignObject></svg>",
    
            /// create Blob of inlined SVG
            svg = new Blob([iSVG],{type:"image/svg+xml;charset=utf-8"}),
    
            /// create URL (handle prefixed version)
            domURL = self.URL || self.webkitURL || self,
            url = domURL.createObjectURL(svg),
    
            /// create Image
            img = new Image;
    
        /// handle image loading
        img.onload = function () {
    
            /// draw SVG to canvas
            ctx.drawImage(img,
                          (options.x ? options.x : 0),
                          (options.y ? options.y : 0));
    
            domURL.revokeObjectURL(url);
    
            /// invoke callback if provided
            if (typeof options.callback === 'function')
                options.callback({result: img,
                                  originalText: txt});
        };
    
        /// handle potential errors
        img.onerror = function(e) {
            if (typeof options.callbackError === 'function') {
                options.callbackError(e);
            } else {
                console.log(e);
            }
        }
    
        img.src = url;
    }
    

    Usage

    var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d');
    
    canvas.width = 800;  /// size of your resulting bitmap
    canvas.height = 600;
    
    ctx.drawHTMLText(...html here...);
    
    var dataUri = canvas.toDataURL();
    

    dataUri now contains the bitmap encoded as a data-uri (which is in string format). This string can be sent to server or set as href on an anchor tag together with a download attribute:

    <a id="downloadLink">Click here to download</a>
    

    From JS:

    /// obtain dataUri here
    downloadLink.href = dataUri;
    downloadLink.download = 'filename.png';
    

    Important: The HTML code you want to draw must not contain any external references (CSS, images etc.) as the browser will restrict the SVG from being drawn as an image to canvas due to security reasons.

    0 讨论(0)
提交回复
热议问题