Completed
Pull Request — master (#10)
by KAWANO
01:09
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
     *
156
     * @param string $fontFilePath 読み込みフォントファイルのパス
157
     * @return void
158
     */
159
    public function setFontFilePath($fontFilePath)
160
    {
161
        $this->fontFilePath = $fontFilePath;
162
    }
163
164
    /**
165
    * setFont
166
    *
167
    * @param string $name フォント名
168
    * @param string $path フォントパス nullでデフォルトセット
169
    * @author hagiwara
170
    */
171
    public function setFont($name, $path)
172
    {
173
        $this->__fonts[$name] = $this->__tcpdfFonts->addTTFfont($path, '', '', 32, $this->fontSettingCacheFileOutDir);
174
    }
175
176
    /**
177
    * addPage
178
    *
179
    * @param string $template テンプレートパス
180
    * @param integer $templateIndex テンプレートページ
181
    * @author hagiwara
182
    */
183
    public function addPage($template, $templateIndex)
184
    {
185
        // ページを追加
186
        $this->__pdf->AddPage();
187
188
        // テンプレートを読み込み
189
        $this->__pdf->setSourceFile($template);
190
191
        // 読み込んだPDFの1ページ目のインデックスを取得
192
        $tplIdx = $this->__pdf->importPage($templateIndex);
193
194
        // 読み込んだPDFの1ページ目をテンプレートとして使用
195
        $this->__pdf->useTemplate($tplIdx, null, null, null, null, true);
196
    }
197
198
    /**
199
    * setVal
200
    *
201
    * @param string $text テキスト
202
    * @param array $option オプション
203
    * @param array $rotateOption 回転オプション(縦書き対応用)
204
    * @author hagiwara
205
    */
206
    public function setVal($text, $option, $rotateOption = [])
207
    {
208
        $default_option = [
209
            'w' => 0,
210
            'h' => 0,
211
            'border' => 0,
212
            'align' => '',
213
            'fill' => false,
214
            'link' => '',
215
            'x' => 0,
216
            'y' => 0,
217
            'color' => '000000',
218
            'font' => '',
219
            'size' => 11,
220
            'stretch' => 0,
221
            'auto_size' => false,
222
        ];
223
        $option = array_merge($default_option ,$option);
224
        
225
        // 自動で枠に収めるかどうかのチェック
226
        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...
227
            $fontDefaultWidth = $this->getStringWidth($text, $option['font'], '', $option['size']);
228
            if ($fontDefaultWidth > $option['w']) {
229
                $option['align'] ='J';
230
                $option['stretch'] =1;
231
            }
232
        }
233
234
        // 書き込む文字列のフォントを指定(フォントの設定キャッシュファイルの出力先がセットされていない場合はデフォルト値)
235
        $fontSettingCacheFilePath = $this->generateFontSettingCacheFilePath($option['font']);
236
        $this->__pdf->SetFont($this->getFont($option['font']), '', $option['size'], $fontSettingCacheFilePath);
237
        // 書き込む文字列の文字色を指定
238
        $concertColor = $this->colorCodeConvert($option['color']);
239
        $this->__pdf->SetTextColor($concertColor['r'], $concertColor['g'], $concertColor['b']);
240
241
        $this->__pdf->SetXY($option['x'], $option['y']);
242
        if (!empty($rotateOption)) {
243
            $default_rotate_option = [
244
                'angle' => 0,
245
                'x' => '',
246
                'y' => '',
247
            ];
248
            $rotateOption = array_merge($default_rotate_option ,$rotateOption);
249
            $this->__pdf->Rotate($rotateOption['angle'], $rotateOption['x'], $rotateOption['y']);
250
        }
251
        // 文字列を書き込む
252
        $this->__pdf->Cell($option['w'], $option['h'], $text, $option['border'], 0, $option['align'], $option['fill'], $option['link'], $option['stretch']);
253
        // 元に戻しておく
254
        if (!empty($rotateOption)) {
255
            $this->__pdf->Rotate($rotateOption['angle'] * -1, $rotateOption['x'], $rotateOption['y']);
256
        }
257
    }
258
259
    /**
260
    * setValTategaki
261
    * 縦書き対応/改行は対応しきれない。折り返しもしない
262
    *
263
    * @param string $text テキスト
264
    * @param array $option オプション
265
    * @author hagiwara
266
    */
267
    public function setValTategaki($text, $option)
268
    {
269
        $default_option = [
270
            'h' => 0,
271
            'border' => 0,
272
            'fill' => false,
273
            'link' => '',
274
            'x' => 0,
275
            'y' => 0,
276
            'color' => '000000',
277
            'font' => '',
278
            'size' => 11,
279
        ];
280
        $option = array_merge($default_option ,$option);
281
282
        // 設定している固定の高さとする
283
        $wordHeight = $option['h'];
284
        // 文字の幅は対応する文字の一番幅の大きい文字とする
285
        $wordWidth = max($this->getStringWidth($text, $option['font'], '', $option['size'], true));
286
        $splitWord = preg_split("//u", $text, -1, PREG_SPLIT_NO_EMPTY);
287
        $top = $option['y'];
288
        foreach ($splitWord as $word) {
289
            // 一文字ことにオプションを設定
290
            $partsOption = $option;
291
            $partsOption['w'] = $wordWidth;
292
            $partsOption['h'] = $wordHeight;
293
            $partsOption['auto_size'] = false;
294
            $partsOption['align'] = 'C';
295
            $partsOption['stretch'] = '0';
296
            $partsOption['y'] = $top;
297
298
            // 縦書き対応
299
            $rotateOption = [];
300
            switch ($this->getTategakiWordType($word)) {
301
                // 回転が必要な文字
302
                case self::TATEGAKI_TYPE_ROUND:
303
                    $rotateOption = [
304
                        'angle' => -90,
305
                        'x' => $partsOption['x'] + ($partsOption['w'] * 0.5),
306
                        'y' => $partsOption['y'] + ($partsOption['h'] * 0.5),
307
                    ];
308
                    break;
309
                // 小さいゃゅょ、句読点を少し右寄せする
310
                case self::TATEGAKI_TYPE_RIGHT:
311
                    $partsOption['x'] += $partsOption['size'] * 0.05;
312
                    break;
313
314
                default:
315
                    break;
316
            }
317
318
            $this->setVal($word, $partsOption, $rotateOption);
319
320
            // 固定の高さ分文字幅を取る
321
            $top += $wordHeight;
322
        }
323
    }
324
325
    /**
326
    * getTategakiWordType
327
    * 縦書きに必要な種別の取得
328
    *
329
    * @param string $word テキスト
330
    * @return int
331
    * @author hagiwara
332
    */
333
    private function getTategakiWordType($word)
334
    {
335
        if (in_array($word, $this->setTategakiType[self::TATEGAKI_TYPE_ROUND], true)) {
336
            return self::TATEGAKI_TYPE_ROUND;
337
        } elseif (in_array($word, $this->setTategakiType[self::TATEGAKI_TYPE_RIGHT], true)) {
338
            return self::TATEGAKI_TYPE_RIGHT;
339
        } else {
340
            return self::TATEGAKI_TYPE_NORMAL;
341
        }
342
    }
343
344
    /**
345
    * setHtml
346
    *
347
    * @param string $html HTML
348
    * @param array $option オプション
349
    * @author hagiwara
350
    */
351
    public function setHtml($html, $option)
352
    {
353
        $default_option = [
354
            'w' => 0,
355
            'h' => 0,
356
            'border' => 0,
357
            'align' => '',
358
            'fill' => false,
359
            'link' => '',
360
            'x' => 0,
361
            'y' => 0,
362
            'color' => '000000',
363
            'font' => '',
364
            'size' => '',
365
            'reseth' => true,
366
            'autopadding' => false,
367
        ];
368
        $option = array_merge($default_option ,$option);
369
        // 書き込む文字列の文字色を指定
370
        //$concertColor = $this->colorCodeConvert($option['color']);
371
        //var_dump($concertColor);
372
        //$this->__pdf->SetTextColor($concertColor['r'], $concertColor['g'], $concertColor['b']);
373
374
        // 書き込む文字列のフォントを指定(フォントの設定キャッシュファイルの出力先がセットされていない場合はデフォルト値)
375
        $fontSettingCacheFilePath = $this->generateFontSettingCacheFilePath($option['font']);
376
        $this->__pdf->SetFont($this->getFont($option['font']), '', $option['size'], $fontSettingCacheFilePath);
377
        
378
        $this->__pdf->writeHTMLCell( $option['w'], $option['h'], $option['x'], $option['y'], $html, $option['border'], 0, $option['fill'], $option['reseth'], $option['align'], $option['autopadding']);
379
    }
380
381
    /**
382
    * getFont
383
    *
384
    * @param string $font フォント名
385
    * @author hagiwara
386
    */
387
    private function getFont($font)
388
    {
389
        if (array_key_exists($font, $this->__fonts)) {
390
            return $this->__fonts[$font];
391
        } else {
392
            return $font;
393
        }
394
    }
395
396
    /**
397
    * setImage
398
    *
399
    * @param string $image 画像パス
400
    * @param array $option オプション
401
    * @author hagiwara
402
    */
403
    public function setImage($image, $option)
404
    {
405
        $default_option = [
406
            'x' => 0,
407
            'y' => 0,
408
            'w' => 0,
409
            'h' => 0,
410
            'link' => '',
411
            'resize' => true,
412
            'dpi' => '300',
413
        ];
414
        $option = array_merge($default_option ,$option);
415
        $this->__pdf->Image($image, $option['x'], $option['y'], $option['w'], $option['h'], '', $option['link'], '', $option['resize'], $option['dpi']);
416
    }
417
418
419
    /**
420
    * colorCodeConvert
421
    *
422
    * @param string $color カラーコード(16進数)
423
    * @author hagiwara
424
    */
425
    private function colorCodeConvert($color)
426
    {
427
        if (
428
            preg_match('/^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/', $color, $colorCheck)
429
        ) {
430
            return [
431
                'r' => hexdec($colorCheck[1]),
432
                'g' => hexdec($colorCheck[2]),
433
                'b' => hexdec($colorCheck[3]),
434
            ];
435
        } else {
436
            return [
437
                'r' => 0,
438
                'g' => 0,
439
                'b' => 0,
440
            ];
441
        }
442
    }
443
444
    /**
445
     * setAutoPageBreak
446
     * page brackeを自動で行うかどうか。画像を下部に埋め込む際には切っておいたほうが良さげ
447
     * @param int $auto
448
     * @param int $margin
449
     */
450
    public function setAutoPageBreak($auto, $margin = 0)
451
    {
452
        $this->__pdf->SetAutoPageBreak($auto, $margin);
453
    }
454
    
455
   /**
456
    * getStringWidth
457
    *
458
    * @param string $text テキスト
459
    * @param string $font フォント名
460
    * @param string $fontstyle フォントスタイル
461
    * @param integer $fontsize サイズ
462
    * @param bool $getarray 結果を1文字ずつ配列で返すか
463
    * @author hagiwara
464
    */
465
    public function getStringWidth($text, $font, $fontstyle, $fontsize, $getarray = false) {
466
        return $this->__pdf->GetStringWidth( $text, $font, $fontstyle, $fontsize, $getarray);
467
    }
468
469
    /**
470
    * write
471
    *
472
    * @param string $file 出力ファイル
473
    * @author hagiwara
474
    */
475
    public function write($file)
476
    {
477
        $pdf_info = $this->__pdf->Output(null, 'S');
478
479
        $fp = fopen($file, 'w');
480
        fwrite($fp ,$pdf_info);
481
        fclose($fp);
482
    }
483
484
    /**
485
     * フォント設定キャッシュファイルのパスを返す
486
     * $this->fontSettingCacheFileOutDir (上記ファイルの出力先ディレクトリ) を指定した場合のみ呼ばれる
487
     * [関数中ののアルゴリズムで生成されたフォント名].php が作られているので、そのpathを返す
488
     * @param string $font フォント名
489
     * @return string
490
     * @author kawano
491
     */
492
    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...
493
    {
494
        // フォントの設定キャッシュファイル出力先ディレクトリが未指定の場合
495
        if (empty($this->fontSettingCacheFileOutDir)) {
496
            return '';
497
        }
498
499
        // TCPDFの処理の互換性のために、設定キャッシュファイルには、以下(参照)のアルゴリズムで、元の名称から改めて名称が付け直されている
500
        // 参照: https://github.com/tecnickcom/TCPDF/blob/master/include/tcpdf_fonts.php#L79 〜 https://github.com/tecnickcom/TCPDF/blob/master/include/tcpdf_fonts.php#L92
501
        // そのため、設定キャッシュファイルは、同様のアルゴリズムで生成した上で、そのパスを指定する必要がある
502
        $fontPathParts = pathinfo($this->fontFilePath);
503
        if (!isset($fontPathParts['filename'])) {
504
            $fontPathParts['filename'] = substr($fontPathParts['basename'], 0, -(strlen($fontPathParts['extension']) + 1));
505
        }
506
        // ファイル名を生成
507
        $fontName = strtolower($fontPathParts['filename']);
508
        $fontName = preg_replace('/[^a-z0-9_]/', '', $fontName);
509
        $search  = array('bold', 'oblique', 'italic', 'regular');
510
        $replace = array('b', 'i', 'i', '');
511
        $fontName = str_replace($search, $replace, $fontName);
512
        // $fontNameが空であった場合、 "tcpdffont" という名称が設定キャッシュファイルに付けられている
513
        if (empty($fontName)) {
514
            return $this->fontSettingCacheFileOutDir . 'tcpdffont' . '.php';
515
        }
516
517
        return $this->fontSettingCacheFileOutDir . $fontName . '.php';
518
    }
519
}
520