Completed
Push — master ( e59ed7...1e8aac )
by satoru
14s queued 10s
created

TcpdfWrapper::setFontFilePath()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace TcpdfWrapper;
4
5
use setasign\Fpdi\Tcpdf\Fpdi;
6
use \TCPDF_FONTS;
7
/**
8
* TcpdfWrapper
9
* TcpdfWrapperを記載しやすくするためのラッパー
10
*/
11
class TcpdfWrapper
12
{
13
    private $__pdf;
14
    private $__fonts = [];
15
    private $__tcpdfFonts;
16
    // 読み込みフォントファイルのパス
17
    private $fontFilePath;
18
    // フォントの設定キャッシュファイル出力先ディレクトリ
19
    private $fontSettingCacheFileOutDir = '';
20
21
    const TATEGAKI_TYPE_NORMAL = 1;
22
    const TATEGAKI_TYPE_ROUND = 2;
23
    const TATEGAKI_TYPE_RIGHT = 3;
24
25
    // publicにしておくので必要に応じて設定
26
    public $setTategakiType = [
27
        self::TATEGAKI_TYPE_ROUND => [
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
        self::TATEGAKI_TYPE_RIGHT => [
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
    * __construct
110
    *
111
    * @author hagiwara
112
    */
113
    public function __construct()
114
    {
115
        $this->__pdf = new Fpdi();
116
        $this->__tcpdfFonts = new TCPDF_FONTS();
117
    }
118
119
    /**
120
     * setfontSettingCacheFileOutDir
121
     *
122
     * @param string $fontSettingCacheFileOutDir
123
     * @return void
124
     * @author kawano
125
     */
126
    public function setFontSettingCacheFileOutDir($fontSettingCacheFileOutDir)
127
    {
128
        $this->fontSettingCacheFileOutDir = $fontSettingCacheFileOutDir;
129
    }
130
131
    /**
132
    * setPrintHeader
133
    *
134
    * @param boolean $print 出力フラグ
135
    * @author hagiwara
136
    */
137
    public function setPrintHeader($print)
138
    {
139
        $this->__pdf->setPrintHeader($print);
140
    }
141
142
    /**
143
    * setPrintFooter
144
    *
145
    * @param boolean $print 出力フラグ
146
    * @author hagiwara
147
    */
148
    public function setPrintFooter($print)
149
    {
150
        $this->__pdf->setPrintFooter($print);
151
    }
152
153
    /**
154
     * setFontFilePath
155
     * setFont($name, $path)で指定された$pathをプロパティにセット
156
     *
157
     * @param string $fontFilePath 読み込みフォントファイルのパス
158
     * @return void
159
     */
160
    private function setFontFilePath($fontFilePath)
161
    {
162
        $this->fontFilePath = $fontFilePath;
163
    }
164
165
    /**
166
    * setFont
167
    *
168
    * @param string $name フォント名
169
    * @param string $path フォントパス nullでデフォルトセット
170
    * @author hagiwara
171
    */
172
    public function setFont($name, $path)
173
    {
174
        $this->__fonts[$name] = $this->__tcpdfFonts->addTTFfont($path, '', '', 32, $this->fontSettingCacheFileOutDir);
175
        // 読み込むフォントファイルのパスを設定
176
        $this->setFontFilePath($path);
177
    }
178
179
    /**
180
    * addPage
181
    *
182
    * @param string $template テンプレートパス
183
    * @param integer $templateIndex テンプレートページ
184
    * @author hagiwara
185
    */
186
    public function addPage($template, $templateIndex)
187
    {
188
        // ページを追加
189
        $this->__pdf->AddPage();
190
191
        // テンプレートを読み込み
192
        $this->__pdf->setSourceFile($template);
193
194
        // 読み込んだPDFの1ページ目のインデックスを取得
195
        $tplIdx = $this->__pdf->importPage($templateIndex);
196
197
        // 読み込んだPDFの1ページ目をテンプレートとして使用
198
        $this->__pdf->useTemplate($tplIdx, null, null, null, null, true);
199
    }
200
201
    /**
202
    * setVal
203
    *
204
    * @param string $text テキスト
205
    * @param array $option オプション
206
    * @param array $rotateOption 回転オプション(縦書き対応用)
207
    * @author hagiwara
208
    */
209
    public function setVal($text, $option, $rotateOption = [])
210
    {
211
        $default_option = [
212
            'w' => 0,
213
            'h' => 0,
214
            'border' => 0,
215
            'align' => '',
216
            'fill' => false,
217
            'link' => '',
218
            'x' => 0,
219
            'y' => 0,
220
            'color' => '000000',
221
            'font' => '',
222
            'size' => 11,
223
            'stretch' => 0,
224
            'auto_size' => false,
225
        ];
226
        $option = array_merge($default_option ,$option);
227
        
228
        // 自動で枠に収めるかどうかのチェック
229
        if ($option['auto_size'] == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
230
            $fontDefaultWidth = $this->getStringWidth($text, $option['font'], '', $option['size']);
231
            if ($fontDefaultWidth > $option['w']) {
232
                $option['align'] ='J';
233
                $option['stretch'] =1;
234
            }
235
        }
236
237
        // 書き込む文字列のフォントを指定(フォントの設定キャッシュファイルの出力先がセットされていない場合はデフォルト値)
238
        $fontSettingCacheFilePath = $this->generateFontSettingCacheFilePath($option['font']);
239
        $this->__pdf->SetFont($this->getFont($option['font']), '', $option['size'], $fontSettingCacheFilePath);
240
        // 書き込む文字列の文字色を指定
241
        $concertColor = $this->colorCodeConvert($option['color']);
242
        $this->__pdf->SetTextColor($concertColor['r'], $concertColor['g'], $concertColor['b']);
243
244
        $this->__pdf->SetXY($option['x'], $option['y']);
245
        if (!empty($rotateOption)) {
246
            $default_rotate_option = [
247
                'angle' => 0,
248
                'x' => '',
249
                'y' => '',
250
            ];
251
            $rotateOption = array_merge($default_rotate_option ,$rotateOption);
252
            $this->__pdf->Rotate($rotateOption['angle'], $rotateOption['x'], $rotateOption['y']);
253
        }
254
        // 文字列を書き込む
255
        $this->__pdf->Cell($option['w'], $option['h'], $text, $option['border'], 0, $option['align'], $option['fill'], $option['link'], $option['stretch']);
256
        // 元に戻しておく
257
        if (!empty($rotateOption)) {
258
            $this->__pdf->Rotate($rotateOption['angle'] * -1, $rotateOption['x'], $rotateOption['y']);
259
        }
260
    }
261
262
    /**
263
    * setValTategaki
264
    * 縦書き対応/改行は対応しきれない。折り返しもしない
265
    *
266
    * @param string $text テキスト
267
    * @param array $option オプション
268
    * @author hagiwara
269
    */
270
    public function setValTategaki($text, $option)
271
    {
272
        $default_option = [
273
            'h' => 0,
274
            'border' => 0,
275
            'fill' => false,
276
            'link' => '',
277
            'x' => 0,
278
            'y' => 0,
279
            'color' => '000000',
280
            'font' => '',
281
            'size' => 11,
282
        ];
283
        $option = array_merge($default_option ,$option);
284
285
        // 設定している固定の高さとする
286
        $wordHeight = $option['h'];
287
        // 文字の幅は対応する文字の一番幅の大きい文字とする
288
        $wordWidth = max($this->getStringWidth($text, $option['font'], '', $option['size'], true));
289
        $splitWord = preg_split("//u", $text, -1, PREG_SPLIT_NO_EMPTY);
290
        $top = $option['y'];
291
        foreach ($splitWord as $word) {
292
            // 一文字ことにオプションを設定
293
            $partsOption = $option;
294
            $partsOption['w'] = $wordWidth;
295
            $partsOption['h'] = $wordHeight;
296
            $partsOption['auto_size'] = false;
297
            $partsOption['align'] = 'C';
298
            $partsOption['stretch'] = '0';
299
            $partsOption['y'] = $top;
300
301
            // 縦書き対応
302
            $rotateOption = [];
303
            switch ($this->getTategakiWordType($word)) {
304
                // 回転が必要な文字
305
                case self::TATEGAKI_TYPE_ROUND:
306
                    $rotateOption = [
307
                        'angle' => -90,
308
                        'x' => $partsOption['x'] + ($partsOption['w'] * 0.5),
309
                        'y' => $partsOption['y'] + ($partsOption['h'] * 0.5),
310
                    ];
311
                    break;
312
                // 小さいゃゅょ、句読点を少し右寄せする
313
                case self::TATEGAKI_TYPE_RIGHT:
314
                    $partsOption['x'] += $partsOption['size'] * 0.05;
315
                    break;
316
317
                default:
318
                    break;
319
            }
320
321
            $this->setVal($word, $partsOption, $rotateOption);
322
323
            // 固定の高さ分文字幅を取る
324
            $top += $wordHeight;
325
        }
326
    }
327
328
    /**
329
    * getTategakiWordType
330
    * 縦書きに必要な種別の取得
331
    *
332
    * @param string $word テキスト
333
    * @return int
334
    * @author hagiwara
335
    */
336
    private function getTategakiWordType($word)
337
    {
338
        if (in_array($word, $this->setTategakiType[self::TATEGAKI_TYPE_ROUND], true)) {
339
            return self::TATEGAKI_TYPE_ROUND;
340
        } elseif (in_array($word, $this->setTategakiType[self::TATEGAKI_TYPE_RIGHT], true)) {
341
            return self::TATEGAKI_TYPE_RIGHT;
342
        } else {
343
            return self::TATEGAKI_TYPE_NORMAL;
344
        }
345
    }
346
347
    /**
348
    * setHtml
349
    *
350
    * @param string $html HTML
351
    * @param array $option オプション
352
    * @author hagiwara
353
    */
354
    public function setHtml($html, $option)
355
    {
356
        $default_option = [
357
            'w' => 0,
358
            'h' => 0,
359
            'border' => 0,
360
            'align' => '',
361
            'fill' => false,
362
            'link' => '',
363
            'x' => 0,
364
            'y' => 0,
365
            'color' => '000000',
366
            'font' => '',
367
            'size' => '',
368
            'reseth' => true,
369
            'autopadding' => false,
370
        ];
371
        $option = array_merge($default_option ,$option);
372
        // 書き込む文字列の文字色を指定
373
        //$concertColor = $this->colorCodeConvert($option['color']);
374
        //var_dump($concertColor);
375
        //$this->__pdf->SetTextColor($concertColor['r'], $concertColor['g'], $concertColor['b']);
376
377
        // 書き込む文字列のフォントを指定(フォントの設定キャッシュファイルの出力先がセットされていない場合はデフォルト値)
378
        $fontSettingCacheFilePath = $this->generateFontSettingCacheFilePath($option['font']);
379
        $this->__pdf->SetFont($this->getFont($option['font']), '', $option['size'], $fontSettingCacheFilePath);
380
        
381
        $this->__pdf->writeHTMLCell( $option['w'], $option['h'], $option['x'], $option['y'], $html, $option['border'], 0, $option['fill'], $option['reseth'], $option['align'], $option['autopadding']);
382
    }
383
384
    /**
385
    * getFont
386
    *
387
    * @param string $font フォント名
388
    * @author hagiwara
389
    */
390
    private function getFont($font)
391
    {
392
        if (array_key_exists($font, $this->__fonts)) {
393
            return $this->__fonts[$font];
394
        } else {
395
            return $font;
396
        }
397
    }
398
399
    /**
400
    * setImage
401
    *
402
    * @param string $image 画像パス
403
    * @param array $option オプション
404
    * @author hagiwara
405
    */
406
    public function setImage($image, $option)
407
    {
408
        $default_option = [
409
            'x' => 0,
410
            'y' => 0,
411
            'w' => 0,
412
            'h' => 0,
413
            'link' => '',
414
            'resize' => true,
415
            'dpi' => '300',
416
        ];
417
        $option = array_merge($default_option ,$option);
418
        $this->__pdf->Image($image, $option['x'], $option['y'], $option['w'], $option['h'], '', $option['link'], '', $option['resize'], $option['dpi']);
419
    }
420
421
422
    /**
423
    * colorCodeConvert
424
    *
425
    * @param string $color カラーコード(16進数)
426
    * @author hagiwara
427
    */
428
    private function colorCodeConvert($color)
429
    {
430
        if (
431
            preg_match('/^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/', $color, $colorCheck)
432
        ) {
433
            return [
434
                'r' => hexdec($colorCheck[1]),
435
                'g' => hexdec($colorCheck[2]),
436
                'b' => hexdec($colorCheck[3]),
437
            ];
438
        } else {
439
            return [
440
                'r' => 0,
441
                'g' => 0,
442
                'b' => 0,
443
            ];
444
        }
445
    }
446
447
    /**
448
     * setAutoPageBreak
449
     * page brackeを自動で行うかどうか。画像を下部に埋め込む際には切っておいたほうが良さげ
450
     * @param int $auto
451
     * @param int $margin
452
     */
453
    public function setAutoPageBreak($auto, $margin = 0)
454
    {
455
        $this->__pdf->SetAutoPageBreak($auto, $margin);
456
    }
457
    
458
   /**
459
    * getStringWidth
460
    *
461
    * @param string $text テキスト
462
    * @param string $font フォント名
463
    * @param string $fontstyle フォントスタイル
464
    * @param integer $fontsize サイズ
465
    * @param bool $getarray 結果を1文字ずつ配列で返すか
466
    * @author hagiwara
467
    */
468
    public function getStringWidth($text, $font, $fontstyle, $fontsize, $getarray = false) {
469
        return $this->__pdf->GetStringWidth( $text, $font, $fontstyle, $fontsize, $getarray);
470
    }
471
472
    /**
473
    * write
474
    *
475
    * @param string $file 出力ファイル
476
    * @author hagiwara
477
    */
478
    public function write($file)
479
    {
480
        $pdf_info = $this->__pdf->Output(null, 'S');
481
482
        $fp = fopen($file, 'w');
483
        fwrite($fp ,$pdf_info);
484
        fclose($fp);
485
    }
486
487
    /**
488
     * フォント設定キャッシュファイルのパスを返す
489
     * $this->fontSettingCacheFileOutDir (上記ファイルの出力先ディレクトリ) を指定した場合のみ呼ばれる
490
     * [関数中のアルゴリズムで生成されたフォント名].php が作られているので、そのpathを返す
491
     * @param string $font フォント名
492
     * @return string
493
     * @author kawano
494
     */
495
    private function generateFontSettingCacheFilePath($font)
0 ignored issues
show
Unused Code introduced by
The parameter $font is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
496
    {
497
        // フォントの設定キャッシュファイル出力先ディレクトリが未指定の場合
498
        if (empty($this->fontSettingCacheFileOutDir)) {
499
            return '';
500
        }
501
502
        // TCPDFの処理の互換性のために、設定キャッシュファイルには、以下(参照)のアルゴリズムで、元の名称から改めて名称が付け直されている
503
        // 参照: https://github.com/tecnickcom/TCPDF/blob/master/include/tcpdf_fonts.php#L79 〜 https://github.com/tecnickcom/TCPDF/blob/master/include/tcpdf_fonts.php#L92
504
        // そのため、設定キャッシュファイルは、同様のアルゴリズムで生成した上で、そのパスを指定する必要がある
505
        $fontPathParts = pathinfo($this->fontFilePath);
506
        if (!isset($fontPathParts['filename'])) {
507
            $fontPathParts['filename'] = substr($fontPathParts['basename'], 0, -(strlen($fontPathParts['extension']) + 1));
508
        }
509
        // ファイル名を生成
510
        $fontName = strtolower($fontPathParts['filename']);
511
        $fontName = preg_replace('/[^a-z0-9_]/', '', $fontName);
512
        $search  = array('bold', 'oblique', 'italic', 'regular');
513
        $replace = array('b', 'i', 'i', '');
514
        $fontName = str_replace($search, $replace, $fontName);
515
        // $fontNameが空であった場合、 "tcpdffont" という名称が設定キャッシュファイルに付けられている
516
        if (empty($fontName)) {
517
            return $this->fontSettingCacheFileOutDir . 'tcpdffont' . '.php';
518
        }
519
520
        return $this->fontSettingCacheFileOutDir . $fontName . '.php';
521
    }
522
}
523