php-phantomjs
php-phantomjs copied to clipboard
I want to use php-phantomjs in Laravel but I dont know how to use.
https://packagist.org/packages/josh/laravel-phantomjs
@smaddy I tried that package but I encountered a lot of errors
@feralheart what kind of errors? for me its working with the latest laravel version on linux. i couldnt get the windows version working.
This error for example: Call to undefined method JonnyW\PhantomJs\Engine::cache().
"jonnyw/php-phantomjs": "^4.6.1",
"josh/laravel-phantomjs": "^1.0",
@nioperas06 I have the same error, did you find a solution?
@Legend23 No, but you can use Browsershot instead.
you can use in laravel just like below:
composer require "jonnyw/php-phantomjs:4.*"
code,it works for me ,and I can render variable in the template .
<?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);
}
}