通过ajax发送图像数据,转换为pdf,下载


Send image data though ajax, convert to pdf, download?

我正在使用html2canvas为我的页面拍照,通过ajax将图像数据发送到php,现在我正在尝试让php将图像数据转换为pdf。这是我的:

$("a[name='download_report']").click(function(e) {
    e.preventDefault();
    var button = $(this);
    button.addClass("disabled").attr("disabled", "disabled");
    html2canvas($('#report-wrapper'), {
      onrendered: function(canvas) {
         var img = canvas.toDataURL("image/png");
         $.ajax({
             'url' : "{{route('report.download')}}",
             'type' : 'POST',
             'dataType' : "json",
             'data' : {img:img},
             'timeout' : 15000
         }).success(function() {
            button.removeClass("disabled").removeAttr("disabled");
         }).error(function() {
            alert("There was a problem converting this report to a PDF.");
            button.removeClass("disabled").removeAttr("disabled");
         });
      }
    });
});

以下是我在php端的内容:

public function download(Request $request) {
    $img = str_replace('data:image/png;base64,', '', $request->get('img'));
    $img = str_replace(' ', '+', $img);
    $img = base64_decode($img);
}

我不知道该从哪里把png变成pdf,然后把它发送回ajax请求,让浏览器自动下载成pdf。

我知道图像数据是正确的,因为我可以用javascript将其输出到浏览器,并看到正确的图像。

如有任何进一步指示,我们将不胜感激。仅供参考,这是一个laravel应用程序,因此使用了blade语法。

任何仍在寻找这个问题答案的人,这对我来说都很有效:

JS

$('button').on( 'click', function() {
    var screenshot = {};
    html2canvas( [ document.getElementById( 'main-container' ) ], {
        onrendered: function( canvas ) {
            screenshot.img = canvas.toDataURL( "image/png" );
            screenshot.data = { 'image' : screenshot.img };
            $.ajax({
                url: "/image_handler.php",
                data: screenshot.data,
                type: 'post',
                success: function( result ) {
                    console.log( result );
                }
            });
        }
    });
});

PHP

$result = file_put_contents( 'myimage.png', base64_decode( str_replace('data:image/png;base64,','',$_POST['image'] ) ) );

引用此链接上"halburgiss"的代码