forked from jkuchar/PdfResponse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PDFResponse.php
437 lines (367 loc) · 10.1 KB
/
PDFResponse.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
<?php
/**
* PdfResponse
* -----------
* Wrapper of mPDF.
* Generate PDF from Nette Framework in one line.
*
* @author Jan Kuchař
* @copyright Copyright (c) 2010 Jan Kuchař (http://mujserver.net)
* @license LGPL
* @link http://addons.nettephp.com/cs/pdfresponse
*/
namespace PdfResponse;
use Nette\Utils\Strings;
use Nette\Object;
use Nette\Http\IRequest;
use Nette\Http\IResponse;
use Nette\Callback;
/**
* @property-read mPDFExtended $mPDF
*/
class PdfResponse extends Object implements \Nette\Application\IResponse {
/**
* Source data
* @var mixed
*/
private $source;
/**
* Callback - create mPDF object
* @var Callback
*/
public $createMPDF = null;
/**
* Portrait page orientation
*/
const ORIENTATION_PORTRAIT = "P";
/**
* Landscape page orientation
*/
const ORIENTATION_LANDSCAPE = "L";
/**
* Specifies page orientation.
*
* You can use constants:
* <ul>
* <li>PdfResponse::ORIENTATION_PORTRAIT (default)
* <li>PdfResponse::ORIENTATION_LANDSCAPE
* </ul>
*
* <b>In some usages this may not work.</b>
* If this setting does not work for you,
* you can specify page orientation by setting
* page size and orientation in style sheet of
* source document.
* <pre>
* @page { sheet-size: A4-L; }
* </pre>
*
* @var string
*/
public $pageOrientaion = self::ORIENTATION_PORTRAIT;
/**
* Specifies format of the document<br>
* <br>
* Allowed values: (Values are case-<b>in</b>sensitive)
* <ul>
* <li>A0 - A10
* <li>B0 - B10
* <li>C0 - C10
* <li>4A0
* <li>2A0
* <li>RA0 - RA4
* <li>SRA0 - SRA4
* <li>Letter
* <li>Legal
* <li>Executive
* <li>Folio
* <li>Demy
* <li>Royal
* <li>A<i> (Type A paperback 111x178mm)</i>
* <li>B<i> (Type B paperback 128x198mm)</i>
* </ul>
*
* @var string
*/
public $pageFormat = "A4";
/**
* Margins in this order:
* <ol>
* <li>top
* <li>right
* <li>bottom
* <li>left
* <li>header
* <li>footer
* </ol>
*
* Please use values <b>higer than 0</b>. In some PDF browser zero values may
* cause problems!
*
* @var string
*/
public $pageMargins = "16,15,16,15,9,9";
/**
* Author of the document
* @var string
*/
public $documentAuthor = "Nette Framework - Pdf response";
/**
* Title of the document
* @var string
*/
public $documentTitle = "Unnamed document";
/**
* This parameter specifies the magnification (zoom) of the display when the document is opened.<br>
* Values (case-<b>sensitive</b>)
* <ul>
* <li><b>fullpage</b>: Fit a whole page in the screen
* <li><b>fullwidth</b>: Fit the width of the page in the screen
* <li><b>real</b>: Display at real size
* <li><b>default</b>: User's default setting in Adobe Reader
* <li><i>integer</i>: Display at a percentage zoom (e.g. 90 will display at 90% zoom)
* </ul>
*
* @var string|int
*/
public $displayZoom = "default";
/**
* Specify the page layout to be used when the document is opened.<br>
* Values (case-<b>sensitive</b>)
* <ul>
* <li><b>single</b>: Display one page at a time
* <li><b>continuous</b>: Display the pages in one column
* <li><b>two</b>: Display the pages in two columns
* <li><b>default</b>: User's default setting in Adobe Reader
* </ul>
*
* @var string
*/
public $displayLayout = "continuous";
/**
* Before document output starts
* @var callback
*/
public $onBeforeComplete = array();
/**
* Multi-language document?
* @var bool
*/
public $multiLanguage = false;
/**
* Additional stylesheet as a <b>string</b>
* @var string
*/
public $styles = "";
/**
* <b>Ignore</b> styles in HTML document
* When using this feature, you MUST also install SimpleHTMLDom to your application!
* @var bool
*/
public $ignoreStylesInHTMLDocument = false;
/**
* mPDFExtended instance
* @var mPDFExtended
*/
private $mPDF = null;
/**
* Document name on output
* @var string
*/
public $outputName = null;
/**
* send the file inline to the browser. The plug-in is used if available. The name given by filename is used when one selects the "Save as" option on the link generating the PDF.
*/
const OUTPUT_INLINE = "I";
/**
* send to the browser and force a file download with the name given by filename.
*/
const OUTPUT_DOWNLOAD = "D";
/**
* save to a local file with the name given by filename (may include a path).
*/
const OUTPUT_FILE = "F";
/**
* return the document as a string. filename is ignored.
*/
const OUTPUT_STRING = "S";
/**
* Output destination
* @var string
*/
public $outputDestination = self::OUTPUT_INLINE;
/**
* Getts margins as <b>array</b>
* @return array
*/
function getMargins() {
$margins = explode(",", $this->pageMargins);
if(count($margins) !== 6) {
throw new \Nette\InvalidStateException("You must specify all margins! For example: 16,15,16,15,9,9");
}
$dictionary = array(
0 => "top",
1 => "right",
2 => "bottom",
3 => "left",
4 => "header",
5 => "footer"
);
$marginsOut = array();
foreach($margins AS $key => $val) {
$val = (int)$val;
if($val < 0) {
throw new \Nette\InvalidArgumentException("Margin must not be negative number!");
}
$marginsOut[$dictionary[$key]] = $val;
}
return $marginsOut;
}
/**
* @param mixed renderable variable
*/
public function __construct($source) {
$this->createMPDF = callback($this,"createMPDF");
$this->source = $source;
}
/**
* Getts source document html
* @return string
* @throws \Nette\InvalidStateException
*/
public function getSource() {
$source = $this->getRawSource();
// String given
if(is_string($source)) {
return $source;
};
// Nette template given
if ($source instanceof \Nette\Templating\ITemplate || $source instanceof \Nette\Application\UI\ITemplate ) {
$source->pdfResponse = $this;
$source->mPDF = $this->getMPDF();
return $source->__toString();
};
// Other case - not supported
throw new \Nette\InvalidStateException("Source is not supported! (type: ".
(is_object($source) ? ("object of class " . get_class($source)) : gettype($source)).
")");
}
public function getRawSource() {
if(!$this->source) {
throw new \Nette\InvalidStateException("Source is not defined!");
}
return $this->source;
}
/**
* Sends response to output.
* @return void
*/
public function send(IRequest $httpRequest, IResponse $httpResponse) {
// Throws exception if sources can not be processed
$html = $this->getSource();
// Fix: $html can't be empty (mPDF generates Fatal error)
if(empty($html)) {
$html = "<html><body></body></html>";
}
$mpdf = $this->getMPDF();
$mpdf->biDirectional = $this->multiLanguage;
$mpdf->SetAuthor($this->documentAuthor);
$mpdf->SetTitle($this->documentTitle);
$mpdf->SetDisplayMode($this->displayZoom,$this->displayLayout);
// @see: http://mpdf1.com/manual/index.php?tid=121&searchstring=writeHTML
if($this->ignoreStylesInHTMLDocument) {
// copied from mPDF -> removes comments
$html = preg_replace('/<!--mpdf/i','',$html);
$html = preg_replace('/mpdf-->/i','',$html);
$html = preg_replace('/<\!\-\-.*?\-\->/s','',$html);
// deletes all <style> tags
$parsedHtml = new simple_html_dom($html);
foreach($parsedHtml->find("style") AS $el) {
$el->outertext = "";
}
$html = $parsedHtml->__toString();
$mode = 2; // If <body> tags are found, all html outside these tags are discarded, and the rest is parsed as content for the document. If no <body> tags are found, all html is parsed as content. Prior to mPDF 4.2 the default CSS was not parsed when using mode #2
}else {
$mode = 0; // Parse all: HTML + CSS
}
if(class_exists('\\simple_html_dom',true)) {
// Support for base64 encoded images - workaround
$parsedHtml = new \simple_html_dom($html);
$i = 1000;
foreach($parsedHtml->find("img") AS $element) {
$boundary1 = "data:";
$pos1 = strlen($boundary1);
if(!substr($element->src,0,$pos1) == $boundary1) continue;
$pos2 = strpos($element->src,";",$pos1);
if($pos2 === false) continue;
$mime = substr($element->src, $pos1, $pos2-$pos1);
$boundary = "base64,";
$base64 = substr($element->src, $pos2+strlen($boundary)+1);
$data = base64_decode($base64);
if($data === false) continue;
$propertyName = "base64Image".$i;
$mpdf->$propertyName = $data;
$element->src = "var:".$propertyName;
$i++;
}
$html = $parsedHtml->__toString();
}
// Add content
$mpdf->WriteHTML(
$html,
$mode
);
// Add styles
if(!empty($this->styles)) {
$mpdf->WriteHTML(
$this->styles,
1
);
}
$this->onBeforeComplete($mpdf);
if(!$this->outputName) {
$this->outputName = Strings::webalize($this->documentTitle).".pdf";
}
$mpdf->Output($this->outputName,$this->outputDestination);
}
/**
* Returns mPDF object
* @return mPDFExtended
*/
public function getMPDF() {
if(!$this->mPDF instanceof mPDF) {
if($this->createMPDF instanceof Callback && $this->createMPDF->isCallable()) {
$mpdf = $this->createMPDF->invoke($this);
if(!($mpdf instanceof \mPDF)) {
throw new \Nette\InvalidStateException("Callback function createMPDF must return mPDF object!");
}
$this->mPDF = $mpdf;
}else
throw new \Nette\InvalidStateException("Callback createMPDF is not callable or is not instance of Nette\Callback!");
}
return $this->mPDF;
}
/**
* Creates and returns mPDF object
* @param PDFResponse $response
* @return mPDFExtended
*/
public function createMPDF() {
$margins = $this->getMargins();
// [ float $margin_header , float $margin_footer [, string $orientation ]]]]]])
$mpdf = new mPDFExtended(
'utf-8', // string $codepage
$this->pageFormat, // mixed $format
'', // float $default_font_size
'', // string $default_font
$margins["left"], // float $margin_left
$margins["right"], // float $margin_right
$margins["top"], // float $margin_top
$margins["bottom"], // float $margin_bottom
$margins["header"], // float $margin_header
$margins["footer"], // float $margin_footer
$this->pageOrientaion
);
return $mpdf;
}
}