TcpdfWrapper::setPrintHeader()   A
last analyzed

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