Skip to content

Instantly share code, notes, and snippets.

@cotcotquedec
Created November 2, 2017 13:48
Show Gist options
  • Save cotcotquedec/622133d1c9deff57fe85a526923831dc to your computer and use it in GitHub Desktop.
Save cotcotquedec/622133d1c9deff57fe85a526923831dc to your computer and use it in GitHub Desktop.
Generation de PDF Laravel / wkhtmltopdf API
<?php namespace Models;
use GuzzleHttp\Client;
/**
* Geenration d'un pdf
*
* Class Pdf
* @package Models
*/
class Pdf
{
/**
* @var URL de wkhtml2pdf
*/
protected $url;
/**
* @var string
*/
protected $content;
/**
* @var string
*/
protected $filename;
/**
* Pdf constructor.
*/
public function __construct($url = null)
{
$this->url = is_null($url) ? env('WKHTML2PDF_URL', 'http://pdf') : $url;
}
/**
* @param $view
* @param array $params
*/
static public function fromView($view, $params = [])
{
$class = new static();
$class->setContent(view($view, $params));
return $class;
}
/**
* Return content
*
* @return string
*/
public function getContent()
{
return $this->content;
}
/**
* Setter for $content
*
* @param $content
* @return $this
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Set filename
*
* @param $filename
* @return $this
*/
public function setFilename($filename)
{
$this->filename = $filename;
return $this;
}
/**
* Renvoie une reponse laravel
*
* @return \Illuminate\Http\Response
*/
public function show()
{
return \response()->make($this->request(), 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="' . $this->filename . '"'
]);
}
/**
* Requete sur l'api de wkhtml
*
*
* @return string
*/
protected function request()
{
// request
$client = new Client();
$response = $client->request('POST', $this->url, [
'headers' => ['Content-Type' => 'application/json'],
'json' => ['contents' => base64_encode($this->content)]
]);
return $response->getBody()->getContents();
}
/**
* Return raw data PDF
*
* @return string
*/
public function raw()
{
return $this->request();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment