This repository has been archived by the owner on Jan 10, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathCallback.php
88 lines (78 loc) · 2.62 KB
/
Callback.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
<?php
/**
* @link https://github.com/yii2tech
* @copyright Copyright (c) 2015 Yii2tech
* @license [New BSD License](http://www.opensource.org/licenses/bsd-license.php)
*/
namespace yii2tech\html2pdf\converters;
use Yii;
use yii\base\InvalidConfigException;
use yii\helpers\FileHelper;
use yii2tech\html2pdf\BaseConverter;
/**
* Callback converter uses a custom PHP callback for the file conversion.
*
* @author Paul Klimov <klimov.paul@gmail.com>
* @since 1.0
*/
class Callback extends BaseConverter
{
/**
* @var callable PHP callback, which should be called in order to perform conversion of HTML content into a PDF file.
* Callback should have following signature:
*
* ```php
* function (string $htmlContent, string $outputFileName, array $options) {...}
* ```
*
* This field can be omitted in case {@see fileCallback} is set.
*/
public $callback;
/**
* @var callable PHP callback, which should be called in order to perform conversion of HTML file into a PDF file.
* Callback should have following signature:
*
* ```php
* function (string $sourceFileName, string $outputFileName, array $options) {...}
* ```
*
* This field can be omitted in case {@see callback} is set.
*/
public $fileCallback;
/**
* {@inheritdoc}
*/
public function convertFile($sourceFileName, $outputFileName, $options = [])
{
if ($this->fileCallback === null) {
parent::convertFile($sourceFileName, $outputFileName, $options);
} else {
$options = array_merge($this->defaultOptions, $options);
call_user_func($this->fileCallback, $sourceFileName, $outputFileName, $options);
}
}
/**
* {@inheritdoc}
*/
protected function convertInternal($html, $outputFileName, $options)
{
if ($this->callback === null) {
if ($this->fileCallback === null) {
throw new InvalidConfigException("Either 'callback' or 'fileCallback' must be set.");
}
$tempPath = Yii::getAlias('@runtime/html2pdf');
FileHelper::createDirectory($tempPath);
$sourceFileName = tempnam($tempPath, 'wkhtmltopdf');
file_put_contents($sourceFileName, $html);
try {
$this->convertFile($sourceFileName, $outputFileName, $options);
} catch (\Exception $e) {
unlink($sourceFileName);
throw $e;
}
unlink($sourceFileName);
} else {
call_user_func($this->callback, $html, $outputFileName, $options);
}
}
}