-
Notifications
You must be signed in to change notification settings - Fork 36
/
PdfResponseFormatter.php
102 lines (82 loc) · 2.37 KB
/
PdfResponseFormatter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
/**
*
* @author Ricardo Obregón <[email protected]>
* @created 15/05/14 12:35 PM
*/
namespace robregonm\pdf;
use Yii;
use yii\base\Component;
use yii\web\Response;
use yii\web\ResponseFormatterInterface;
/**
* PdfResponseFormatter formats the given HTML data into a PDF response content.
*
* It is used by [[Response]] to format response data.
*
* @author Ricardo Obregón <[email protected]>
* @since 2.0
*/
class PdfResponseFormatter extends Component implements ResponseFormatterInterface
{
public $mode = '';
public $format = 'A4';
public $defaultFontSize = 0;
public $defaultFont = '';
public $marginLeft = 15;
public $marginRight = 15;
public $marginTop = 16;
public $marginBottom = 16;
public $marginHeader = 9;
public $marginFooter = 9;
/**
* @var string 'Landscape' or 'Portrait'
* Default to 'Portrait'
*/
public $orientation = 'P';
public $options = [];
/**
* @var Closure function($mpdf, $data){}
*/
public $beforeRender;
/**
* Formats the specified response.
*
* @param Response $response the response to be formatted.
*/
public function format($response)
{
$response->getHeaders()->set('Content-Type', 'application/pdf');
$response->content = $this->formatPdf($response);
}
/**
* Formats response HTML in PDF
*
* @param Response $response
*/
protected function formatPdf($response)
{
$mpdf = new \Mpdf\Mpdf([
'mode' => $this->mode,
'format' => $this->format,
'default_font_size' => $this->defaultFontSize,
'default_font' => $this->defaultFont,
'margin_left' => $this->marginLeft,
'margin_right' => $this->marginRight,
'margin_top' => $this->marginTop,
'margin_bottom' => $this->marginBottom,
'margin_header' => $this->marginHeader,
'margin_footer' => $this->marginFooter,
'orientation' => $this->orientation,
]
);
foreach ($this->options as $key => $option) {
$mpdf->$key = $option;
}
if ($this->beforeRender instanceof \Closure) {
call_user_func($this->beforeRender, $mpdf, $response->data);
}
$mpdf->WriteHTML($response->data);
return $mpdf->Output('', 'S');
}
}