代码之家  ›  专栏  ›  技术社区  ›  Feralheart

PHP:HTML到PNG服务器端?[关闭]

php
  •  -2
  • Feralheart  · 技术社区  · 6 年前

    我需要一个工具,什么转换成jpg或png服务器端,只有数据和可用的 php .

    我试过了 wkhtmltoimage phantomjs mink 但他们也能捕捉到整个屏幕。

    我将使用此表进行测试:

    <div class="capturable">
        <table>
            <tr><td>This is one of my tables</td></tr>
        </table>
    </div>
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Thomas J.    6 年前

    您可以尝试使用mPDF或TCPDF轻松地将表转换为PDF,然后简单地将PDF转换为png/jpg。

        2
  •  0
  •   Veerendra    6 年前

    根据您的要求,您可以在点击启动电子邮件的事件时调用js。

    你可以用 HTML to Canvas

    你只需要包括JS https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js 进入你的html。

    然后你可以使用下面的脚本

    html2canvas(jQuery(".main-content"), {
     useCORS: true,
     onrendered: function(canvas) {
     theCanvas = canvas;
     document.body.appendChild(canvas);
     dataOverview = canvas.toDataURL('image/png');
     uploadImage(dataOverview);//this is custom build function 
    }});
    

    .main内容是要转换为图像的节的选择器

    function uploadImage(dataOverview)
    {
        if(dataOverview)
        {
            jQuery.ajax({
                url: 'ajax url to post image data',
                type : 'POST',
                data : {
                    dataOverview:  dataOverview,
                },
                dataType : 'JSON',
                success: function(response)
                {
                    if(response.code == 200)
                    {
                        //perform your action on success
                    }
                }
            });
        }
    }
    

    $dataOverview = $_POST['dataOverview'];
    $dataOverviewData=substr($dataOverview, strpos($dataOverview, ",")+1);
    $dataOverviewunencodedData=base64_decode($dataOverviewData);
    $rand = rand();
    $dataOverViewfname_png = $rand.'.png';
    $dataOverimgfile_png='path to the directory where you want to save the image';
    $imagegerated=file_put_contents($dataOverimgfile_png, $dataOverviewunencodedData);
    

    这将生成您在选择器中传递的html元素的png图像。

    这是一个工作代码,因为我已经在我的一些项目中使用它。

    或者如果你想把原始的html转换成图像,你可以使用下面的代码

    <?php
    require 'pdfcrowd.php';
    
    try
    {
        // create the API client instance
        $client = new \Pdfcrowd\HtmlToImageClient("your_username", "your_apikey");
    
        // configure the conversion
        $client->setOutputFormat("png");
    
        // run the conversion and write the result to a file
        $client->convertFileToFile("/path/to/MyLayout.html", "MyLayout.png");
    }
    catch(\Pdfcrowd\Error $why)
    {
        // report the error
        error_log("Pdfcrowd Error: {$why}\n");
    
        // handle the exception here or rethrow and handle it at a higher level
        throw $why;
    }
    
    ?>
    

    PDFCROWD