php-phantomjs icon indicating copy to clipboard operation
php-phantomjs copied to clipboard

[bug] sometimes doesn't work

Open askme-gpt opened this issue 6 years ago • 0 comments

works:

{
    "message": "Successfuly!",
    "status_code": 200,
    "data": [
        "https://kid.nbfuli.top/storage/capture/5bfde9e972bfc.jpg",
        "https://zhidao.baidu.com/question/1241254892809348899.html"
    ]
}

not work:

{
    "message": "Successfuly!",
    "status_code": 200,
    "data": [
        "https://kid.nbfuli.top/storage/capture/5bfd40ac9f9c3.jpg",
        "https://kid.nbfuli.top/storage/capture/html/5bfd40ac9d669.html"
    ]
}

my php code :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use JonnyW\PhantomJs\Client;
use Storage;

class GeneratePropagandaController extends Controller
{
    public function htmlToImage($data)
    {
        $url = $this->htmlToImageView($data);
        // $url = 'https://wap.51kid.com/a/free-lesson';
        // $url = 'https://zhidao.baidu.com/question/1241254892809348899.html';
        $client = Client::getInstance();
        if (PHP_OS == 'WINNT') {
            $client->getEngine()->setPath(base_path() . '\\bin\\phantomjs.exe');
        } else {
            $client->getEngine()->setPath(base_path() . '/bin/phantomjs');
        }

        //设置截图的边界
        $width = 0;
        $height = 0;
        $top = 0;
        $left = 0;

        // $method = request()->getMethod();
        $method = 'GET';
        $request = $client->getMessageFactory()->createCaptureRequest($url, $method);
        //传输参数
        $request->addHeader('X-CSRF-TOKEN', csrf_token());
        $request->addHeader('cookie', request()->header('cookie'));
        $request->setBodyStyles(array('backgroundColor' => '#FFFFFF')); #设置背景颜色

        $name = 'capture/' . uniqid() . '.jpg';
        $storage_path = Storage::disk('public')->path($name);
        $image_url = Storage::disk('public')->url($name);
        //注意,不论是windows还是linux,这里都需要linux格式的分隔符,不然识别不了
        $storage_path = str_replace('\\', '/', $storage_path);
        $request->setOutputFile($storage_path); #设置输出图片的绝对路径
        $request->setViewportSize($width, $height);
        $request->setCaptureDimensions($width, $height, $top, $left);
        $response = $client->getMessageFactory()->createResponse();
        try {
            $client->send($request, $response);
            return $this->outPutJson([$image_url, $url]);
        } catch (\Exception $e) {
            return $this->outPutJson('', 201, $e->getMessage());
        }
    }

    public function htmlToImageView($data)
    {
        $view = request('view', 'test.experience_report');
        $htmlCode = view($view, compact('data'))->render();
        $fileName = 'capture/html/' . uniqid() . '.html';
        Storage::disk('public')->put($fileName, $htmlCode);
        return Storage::disk('public')->url($fileName);
    }
}

askme-gpt avatar Nov 28 '18 01:11 askme-gpt