IT News > トピックス > PDF > HTML2PDF で日本語を使う

必要ライブラリ

HTML2PDF
http://sourceforge.net/projects/html2fpdf

FPDF_japanese
http://www.fpdf.org/download/japanese.zip

ファイル配置と修正

HTML2PDFを解凍。
できたディレクトリ内でjapaneseを解凍する。

62行目

    require_once(RELATIVE_PATH.'fpdf.php');

    ↓

    require_once('japanese.php');

65行目

    class HTML2FPDF extends FPDF

    ↓

    class HTML2FPDF extends PDF_Japanese

157行目

    $this->SetFont('Arial','',11); // Changeable?(not yet...)

    $this->lineheight = 5; // Related to FontSizePt == 11

    ↓

    $this->SetFont('Arial','',11); // Changeable?(not yet...)

    $this->SetMargins(25,15,20); // 追加

    $this->SetTextColor(0,0,139); // 追加

    $this->lineheight = 5; // Related to FontSizePt == 11

352行目付近

    foreach($a as $i => $e)

    {

    if($i%2==0)

    ↓

    foreach($a as $i => $e)

    {

        $this->SetFont('SJIS','',11); // 追加

        $this->SetTextColor(0,0,139); // 追加

        $e = mb_convert_encoding($e,'SHIFT-JIS','UTF-8'); // 追加

    if($i%2==0)

369行目

    $e = str_replace(chr(160),chr(32),$e); //unify ascii code of spaces (in order to recognize all of them correctly)

    ↓

    // $e = str_replace(chr(160),chr(32),$e); //unify ascii code of spaces (in order to recognize all of them correctly)

159行目付近のArial以外のすべてのArialをSJISに変更する

    $this->SetFont('Arial');

    ↓

    $this->SetFont('SJIS');

簡単な例

<?php

define('FPDF_FONTPATH','html2fpdf-3.0.2b/font/');
require_once('html2fpdf-3.0.2b/html2fpdf.php');

$html =<<<HTML
<html>

<head><TITLE>テスト</TITLE></HEAD>
<BODY>

    <h1>タイトルなど</h1>
    
    ここにコンテンツ
    
    <hr />
    
</body>
</html>
HTML;


// PDFの書式設定
$pdf = new HTML2FPDF("L","mm","A4");
$pdf->Open();

$pdf->SetCompression(false);
$pdf->SetDisplayMode("real");
$pdf->UseCSS();
$pdf->UsePRE();
$pdf->setBasePath( "http://develop90.uusoft.co.jp/_matsumoto/pdf_html2pdf/index_matsumoto.php" );
$pdf->AddSJISFont();
$pdf->AddPage();

//ファイル情報
$pdf->SetAuthor("matsumoto");
$pdf->Bookmark( "matsumoto_Bookmark" );
$pdf->SetTitle("Title");
$pdf->SetCreator( "SetCreator" );

// 本文
$pdf->SetMargins( 10, 10 );
$pdf->DisplayPreferences('HideWindowUI');
//$pdf->SetFont( HideWindowUI,"",8);
$pdf->WriteHTML($html);

// 出力
$pdf->Output('doc.pdf', 'I');

?>