This repository has been archived by the owner on May 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Dompdf.php
116 lines (96 loc) · 2.7 KB
/
Dompdf.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
<?php
namespace WeProvide\Dompdf\Controller\Result;
use Dompdf\Dompdf as PDF;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\App\Response\HttpInterface as HttpResponseInterface;
use Magento\Framework\Controller\AbstractResult;
class Dompdf extends AbstractResult
{
public $pdf;
protected $fileName = 'document.pdf';
protected $attachment = 'attachment';
protected $output;
/**
* Dompdf constructor.
*/
public function __construct(PDF $domPdf)
{
$this->pdf = $domPdf;
}
/**
* Load html
*
* @param $html
*/
public function setData($html)
{
$this->pdf->loadHtml($html);
}
/**
* Set output from $this->renderOutput() to allow multiple renders
*
* @param $output
*/
public function setOutput($output) {
$this->output = $output;
}
/**
* Set filename
*
* @param $fileName
*/
public function setFileName($fileName)
{
$this->fileName = $fileName;
}
/**
* Set attachment type, either 'attachment' or 'inline'
*
* @param $mode
*/
public function setAttachment($mode)
{
$this->attachment = $mode;
}
/**
* Render PDF output
*
* @return string
*/
public function renderOutput()
{
if($this->output) {
return $this->output;
}
$this->pdf->render();
return $this->pdf->output();
}
/**
* Render PDF
*
* @param ResponseInterface $response
*
* @return $this
*/
protected function render(HttpResponseInterface $response)
{
$output = $this->renderOutput();
// Below is a port of Dompdf's stream function
// https://github.com/dompdf/dompdf/blob/af914c2cdcaea0c4b3e0efed3354f58caecf13ba/lib/Cpdf.php#L3479-L3536
$response->setHeader('Cache-Control', 'private');
$response->setHeader('Content-type', 'application/pdf');
$response->setHeader('Content-Length', mb_strlen($output, '8bit'));
$filename = $this->fileName;
$filename = str_replace(["\n", "'"], '', basename($filename, '.pdf')) . '.pdf';
$encoding = mb_detect_encoding($filename);
$fallbackfilename = mb_convert_encoding($filename, "ISO-8859-1", $encoding);
$encodedfallbackfilename = rawurlencode($fallbackfilename);
$encodedfilename = rawurlencode($filename);
$response->setHeader(
'Content-Disposition',
$this->attachment . '; filename=' . $encodedfallbackfilename . "; filename*=UTF-8''" . $encodedfilename
);
$response->setBody($output);
return $this;
}
}