トップへ(mam-mam.net/)

How to Generate PDF Files with TCPDF in PHP|Examples with Japanese Text, Images, and Shapes

Japanese

How to Generate PDF Files with TCPDF in PHP|Examples with Japanese Text, Images, and Shapes

This page introduces how to generate PDF files in PHP using the TCPDF library.
It includes practical code examples for displaying Japanese text, inserting images, drawing shapes and lines, and configuring headers, footers, and margins.
The content covers everything from the basics of TCPDF to more detailed customization options.

1. What Is TCPDF? A PHP Library for Generating PDF Files

TCPDF is a PHP library that allows you to generate PDF files directly from your applications.
You can add pages and output text, rectangles, lines, arcs, images, and even HTML content.
It also supports configuring headers, footers (including page numbers and total page count), and margins.

2. How to Download and Set Up TCPDF

You can download TCPDF from the following sites:
Official GitHub: tc-lib-pdf
SourceForge: TCPDF Download Page (download “tcpdf_6_3_2.zip”)

After extracting the downloaded ZIP file, you will see a structure like this:
tcpdf/ (create this directory and place the following files inside)
+-- tcpdf.php
+-- tcpdf_autoconfig.php
+-- include/ (all files inside this folder)
+-- fonts/ (all files inside this folder)

Upload the extracted files to your server by creating a tcpdf/ directory and placing everything inside it.
Once the files are in place, you can start using TCPDF in your PHP scripts right away!

3. Dynamic PDF Generation Example

Click the link below to view a PDF file dynamically generated in PHP using TCPDF.
View the actual PDF output

4. TCPDF Implementation Example for Generating PDFs [Source Code Explained]

The following code provides a detailed example of how to dynamically generate PDF files in PHP using the TCPDF library.
It demonstrates key features for flexibly customizing PDFs, including adding pages, drawing text and images, and configuring headers and footers.

<?php

// Load the TCPDF library
require_once('./tcpdf/tcpdf.php');

//Basic PDF settings (page size, character encoding, etc.)
$orientation = 'P';   // Page orientation: P = Portrait, L = Landscape
$unit = 'mm';         // Units: mm = millimeters, pt = points, cm = centimeters, in = inches
$format = 'A4';       // Paper size
$unicode = true;      // TRUE = document text is Unicode
$encoding = 'UTF-8';  // Character encoding
$diskcache = false;   // true = use disk cache (saves memory), false = do not use disk cache

// Create a TCPDF instance
$tcpdf = new TCPDF($orientation, $unit, $format, $unicode, $encoding, $diskcache);

//// Set page margins (left, top [, right]); units follow the constructor settings
// If using headers, the top margin should be set larger
$tcpdf->SetMargins(8, 10, 8);  // Right margin is optional (defaults to the left margin)

// Set PDF metadata (title, author, etc.)
$tcpdf->SetTitle('PDF Title');     // Document title
$tcpdf->SetSubject('PDF Subject'); // Document Subject
$tcpdf->SetAuthor('PDF Author');   // Author information


// Header settings (a line is drawn below the header)
  // Enable or disable header output: true = show, false = hide
  $tcpdf->setPrintHeader(false);
  //Set header font
  $tcpdf->setHeaderFont(
    /* Available fonts:
       'arialunicid0'         : Arial Uni CID0
       'kozgopromedium'       : Kozuka Gothic Pro M
       'kozminproregular'     : Kozuka Mincho Pro M
       'hysmyeongjostdmedium' : HYSMyeongJoStd-Medium
       'msungstdlight'        : MSungStd-Light
       'stsongstdlight'       : STSongStd-Light
    */
    [
      'kozminproregular', //Use "Kozuka Mincho Pro M"
      'I' ,               //Style: B = Bold, I = Italic, U = Underline, D = Strike-through
      8                   //Font size (default is 12pt)
    ]
  );
  // Set header margin (distance from the top of the page)
  // If printing a header, this value should be larger
  $tcpdf->setHeaderMargin(20);
  $tcpdf->setHeaderData(
    "logo.jpg", //Logo filename (may not work depending on TCPDF version)
    10,         //Logo width (header title and text appear at [left margin + 10] mm)
    "Header Title",
    "Header Text",
    [0,0,255],  //Text Color [r,g,b]
    [0,0,0]     //Line Color [r,g,b]
  );


// Footer settings (a line is drawn above the footer, and the page/total pages
// are displayed on the right side of the footer)

  //Enable or disable footer output: true = show, false = hide
  $tcpdf->setPrintFooter(true);
  //Set Japanese font for the footer
  $tcpdf->setFooterFont(
    /* Available fonts:
       'arialunicid0'         : Arial Uni CID0
       'kozgopromedium'       : Kozuka Gothic Pro M
       'kozminproregular'     : Kozuka Mincho Pro M
       'hysmyeongjostdmedium' : HYSMyeongJoStd-Medium
       'msungstdlight'        : MSungStd-Light
       'stsongstdlight'       : STSongStd-Light
    */
    [
      'hysmyeongjostdmedium', //Use "HYSMyeongJoStd-Medium"
      'I' ,                   //Style: B = Bold, I = Italic, U = Underline, D = Strike-through
      8                       //Font size (default is 12pt)
    ]
  );
  //Set footer margin (distance from the bottom of the page)
  $tcpdf->setFooterMargin(20);
  $tcpdf->setFooterData(
    [0,0,255],  //Text Color [r,g,b]
    [0,0,0]     //Line Color [r,g,b]
  );


//Add a new page (P = Portrait, L = Landscape)
$tcpdf->AddPage('P','A4');


//Text() function
//Outputs simple text (no line breaks, limited functionality, so not used often)

  //Set Japanese font
  $tcpdf->SetFont(
    /* Available fonts:
       'arialunicid0'         : Arial Uni CID0
       'kozgopromedium'       : Kozuka Gothic Pro M
       'kozminproregular'     : Kozuka Mincho Pro M
       'hysmyeongjostdmedium' : HYSMyeongJoStd-Medium
       'msungstdlight'        : MSungStd-Light
       'stsongstdlight'       : STSongStd-Light
    */
    'hysmyeongjostdmedium', //Use "HYSMyeongJoStd-Medium"
    'D' ,                   //Style: B = Bold, I = Italic, U = Underline, D = Strike-through
    16                      //Font size (default is 12pt)
  );
  //Set text color
  $tcpdf->SetTextColor(255,0,0);//RGB
  //Output text
  $tcpdf->Text(
    20,  //x-coordinate
    30,  //y-coordinate
    '$tcpdf->Text(x,y,string) output text'
  );


// Cell() function
// Creates text inside a rectangular cell (no line breaks allowed) with optional hyperlink.
// (\r\n does NOT create line breaks, no auto line wrapping, and long text may be compressed vertically)
  //Set Japanese font
  $tcpdf->SetFont(
    /* Available fonts:
       'arialunicid0'         : Arial Uni CID0
       'kozgopromedium'       : Kozuka Gothic Pro M
       'kozminproregular'     : Kozuka Mincho Pro M
       'hysmyeongjostdmedium' : HYSMyeongJoStd-Medium
       'msungstdlight'        : MSungStd-Light
       'stsongstdlight'       : STSongStd-Light
    */
    'hysmyeongjostdmedium', //Use "HYSMyeongJoStd-Medium"
    'IU' ,                  //Style: B = Bold, I = Italic, U = Underline, D = Strike-through
    12                      //Font size (default is 12pt)
  );
  //Set position
  $tcpdf->SetXY(20,50);
  //Set fill color
  $tcpdf->SetFillColor(255,255,0);//RGB
  //Set border/line style
  $tcpdf->SetLineStyle(["width"=>0.5,"cap"=>"round","join"=>"round","color"=>[0,0,255]]);//RGB
  //Output text inside a cell with fill and hyperlink
  $tcpdf->Cell(
    70,    //Cell width
    10,    //Cell height
    '$tcpdf-Cell()'."  Output text inside a cell with fill and hyperlink",
    1,     //Border: 0=none, 1=full box, 'L','R','T','B','LR' etc.
    1,     //Cursor movement after output: 0 = right, 1 = next line, 2 = below
    'L',   //Alignment: L=left, C=center, R=right, J=justify
    1,     //Fill: 0 = transparent, 1 = filled
    'https://mam-mam.net/', // Hyperlink URL
    1,     // Text stretching mode: 0 = none, 1=horizontal if needed, 2=always horizontal, 3=spacing if needed, 4=spacing
    false, // Adjust minimum cell height: false=adjust, true=do not adjust
    'T',   // Vertical alignment relative to Y: T=top, C=center, B=bottom, A=font top, L=baseline, D=font bottom
    'M'    // Vertical alignment inside cell: M=middle, T=top, B=bottom
  );


// MultiCell() function
// Creates text inside a rectangular cell with automatic line wrapping.
// (\r\n can be used to force line breaks. Text that exceeds the cell area is clipped.)
  //Set Japanese font
  $tcpdf->SetFont(
    /* Available fonts:
       'arialunicid0'         : Arial Uni CID0
       'kozgopromedium'       : Kozuka Gothic Pro M
       'kozminproregular'     : Kozuka Mincho Pro M
       'hysmyeongjostdmedium' : HYSMyeongJoStd-Medium
       'msungstdlight'        : MSungStd-Light
       'stsongstdlight'       : STSongStd-Light
    */
    'kozgopromedium', //Use "Kozuka Gothic Pro M"
    '' ,              //Style: B = Bold, I = Italic, U = Underline, D = Strike-through
    12                //Font size (default is 12pt)
  );
  //Set text color
  $tcpdf->SetTextColor(16,16,16);    //RGB
  //Set background fill color
  $tcpdf->SetFillColor(200,200,200); //RGB
  //Set border/line style (width, cap, join, color [r,g,b])
  $tcpdf->SetLineStyle(["width"=>0.5,"cap"=>"round","join"=>"round","color"=>[0,0,0]]);
  $tcpdf->MultiCell(
    85,    //Cell width
    40,    //Cell height
    'Specify the output text here. \r\n can be used for manual line breaks. Automatic wrapping is also applied. Text that exceeds the cell area is clipped.',
    1,     //Border: 0=none, 1=full box, 'L','R','T','B','LR', etc.
    'L',   //Alignment: L=left, C=center, R=right, J=justify
    1,     //Fill: 0=transparent, 1=filled
    1,     //Cursor movement: 0=right, 1=next line, 2=below
    20,    //X position
    70,    //Y position
    true,  //Reset the height of the previous cell
    0,     //Text stretching mode: 0=none, 1=horizontal if needed, 2=always horizontal, 3=spacing if needed, 4=spacing
    false, //false = plain text, true = HTML
    true,  //true = automatically adjust to line width
    40,    //Maximum height (should match cell height for vertical alignment)
    'M',   //Vertical alignment inside cell: M=middle, T=top, B=bottom
    false  //true=shrink text to fit inside the cell
  );

// MultiCell() function
// Create HTML content inside a rectangular cell.
// (CSS is supported, but many properties may not apply. Text that exceeds the cell is NOT clipped;
// instead, the cell height automatically expands.)
  //Set Japanese font
  $tcpdf->SetFont(
    /* Available fonts:
       'arialunicid0'         : Arial Uni CID0
       'kozgopromedium'       : Kozuka Gothic Pro M
       'kozminproregular'     : Kozuka Mincho Pro M
       'hysmyeongjostdmedium' : HYSMyeongJoStd-Medium
       'msungstdlight'        : MSungStd-Light
       'stsongstdlight'       : STSongStd-Light
    */
    'kozgopromedium', //Use "Kozuka Gothic Pro M"
    '' ,              //Style: B = Bold, I = Italic, U = Underline, D = Strike-through
    12                //Font size (default is 12pt)
  );
  //Set text color
  $tcpdf->SetTextColor(16,16,16);//RGB
  //Set background fill color
  $tcpdf->SetFillColor(200,200,200);//RGB
  //Set border/line style (width, cap, join, color [r,g,b])
  $tcpdf->SetLineStyle(["width"=>0.5,"cap"=>"round","join"=>"round","color"=>[0,0,0]]);
  $tcpdf->MultiCell(
    60,    //Cell width
    10,    //Cell height(auto-expands when using HTML)
    '<style>h4,p{margin:0px;padding:0px;font-size:12px;}</style><h4>Title</h4>'.
      '<p>Specify the output text here.Line breaks can be inserted with <br>'.
      'Automatic wrapping is applied. Text that exceeds the cell is not clipped; the cell height expands automatically.</p>',
    1,     //Border: 0=none, 1=full box, 'L','R','T','B','LR', etc.
    'L',   //Alignment: L=left, C=center, R=right, J=justify
    1,     //Fill: 0=transparent, 1=filled
    1,     //Cursor movement: 0=right, 1=next line, 2=below
    120,   //X position
    70,    //Y position
    true,  //Reset the height of the previous cell
    0,     //Text stretching mode: 0=none, 1=horizontal if needed, 2=always horizontal, 3=spacing if needed, 4=spacing
    true,  //false = plain text, true = HTML
    true,  //true = automatically adjust to line width
    20,    //Max height(ignored for HTML)
    'B',   //Vertical alignment (HTML forces top alignment)
    false  //true = shrink text to fit inside the cell
  );


// Line() function
// Draws a line (useful for borders, separators, etc.)
  //Set Line style
  $tcpdf->SetLineStyle(["width"=>1,"cap"=>"round","join"=>"round","color"=>[0,255,0]]);//RGB
  //Draw the line
  $tcpdf->Line(10,140,100,160);


//Draw a filled rectangle
  $tcpdf->SetLineStyle(["width"=>1,"cap"=>"round","join"=>"round","color"=>[0,255,255]]);//RGB
  //Set fill color
  $tcpdf->SetFillColor(255,255,0);//RGB
  //Draw the rectangle
  $tcpdf->Rect(
    10,   //Upper-left x
    165,  //Upper-left y
    50,   //Width
    20,   //Height
    'DF'  // 'D'=border only, 'F'=fill only, 'DF'=border + fill
  );


//Circle() function
//Draw a filled arc
  //Set line style
  $tcpdf->SetLineStyle(["width"=>1,"cap"=>"round","join"=>"round","color"=>[0,0,255]]);//RGB
  //Set line style
  $tcpdf->SetFillColor(0,0,0);//RGB
  //Draw the arc
  $tcpdf->Circle(
    30,   //Center x
    200,  //Center y
    10,   //Radius
    0,    //Start angle (0deg=right, counterclockwise)
    270,  //円弧の終了角度(中心から真右が0度で反時計回り)
    'DF'  //'D'=arc only, 'F'=fill only, 'DF'=arc + fill, 'C'=close path
  );


// Ellipse() function
// Draws a filled elliptical arc
  //Set line style
  $tcpdf->SetLineStyle(["width"=>1,"cap"=>"round","join"=>"round","color"=>[255,0,0]]);//RGB
  //Set fill color
  $tcpdf->SetFillColor(0,0,255);//RGB
  $tcpdf->Ellipse(
    40,   //Center x
    230,  //Center y
    20,   //Horizontal radius (rx)
    10,   //Vertical radius (ry)
    45,   //Rotation angle of the entire ellipse (counterclockwise).  Example: 45 rotates the ellipse 45deg CCW around its center.
    0,    //Start angle (0° = right, counterclockwise)
    315,  //End angle (counterclockwise)
    'DF'  //'D'=arc only, 'F'=fill only, 'DF'=arc + fill, 'C'=close path
  );


// Image() function
// Draw an existing image
  $tcpdf->Image(
    './imgs/car2.jpg', //File path
    100,               //Upper-left x-coordinate
    160,               //Upper-left y-coordinate
    80,                //Width (auto-calculated if omitted or set to 0)
    0,                 //Height (auto-calculated if omitted or set to 0)
    '',                //Image format. If not using GD, specify 'JPEG' or 'PNG'. ''=auto-detect
    'https://mam-mam.net' //URL to open when the image is clicked
  );


// Image() function
// Create an image dynamically using GD (useful for graphs or generating dynamic icons)
  $w=50;  //Width
  $h=50;  //Height
  $img = imagecreatetruecolor($w,$h);  //Create a true color image (50x50)
  $tranColor = imagecolorallocate($img, 254, 253, 252);  //Set background color
  imagefill($img, 0, 0, $tranColor);       // Fill background
  imagecolortransparent($img,$tranColor);  // Make background transparent
  imagesavealpha($img, true);              //Preserve alpha channel
  //Draw random rectangles
  for($i=0;$i<10;$i++){
    $col=imagecolorallocate($img,random_int(0,255),random_int(0,255),random_int(0,255));
    $x1=random_int(0,$w);
    $y1=random_int(0,$h);
    $x2=random_int($x1,$w);
    $y2=random_int($y1,$h);
    imagefilledrectangle($img, $x1, $y1, $x2, $y2, $col);
  }
  ob_start();
  imagepng($img);
  $buf = ob_get_clean();
  //ob_end_clean();
  $tcpdf->Image(
    '@'.$buf,            //'@'=this string is raw binary image data, not a filename.
    100,220,50,50,'',''
  );


//Add a new page
$tcpdf->AddPage('P','A4'); // P=portrait, L=landscape

// writeHTML() function [limited support]
// Output an HTML table layout (useful for rendering data tables in a PDF)
  // Create the HTML
  $html ="
    <style>
    * {margin:0; padding:0; color:#000;}
    table{border:none;width:200px;border-collapse:collapse;}
    th,td{border:1px solid #000;}
    h1{background-color:#fff;}
    </style>
    <h1>Written in HTML</h1>
    <table>
      <tr><td>1</td><td>Very Good</td></tr>
      <tr><td>2</td><td>Good</td></tr>
      <tr><td>3</td><td>Average</td></tr>
      <tr><td>4</td><td>Poor</td></tr>
    </table>";
  //Set Position
  $tcpdf->SetXY(20,50);  //Position on page 2: 20mm from left, 50mm from top
  // Write HTML into the PDF
  $tcpdf->writeHTML($html, true, true, true, true);




// Output() function
// Display, download, save, or retrieve the generated PDF
  // 'I': Display in browser (default)
  // 'D': Force file download
  // 'F': Save to local server with the specified filename
  // 'S': Return the PDF document as a string (filename is ignored)
  // 'FI': Same as F + I
  // 'FD': Same as F + D
  //PDF output to
  $pdfData = $tcpdf->Output(rawurlencode('sample.pdf'), 'S');



//Display the PDF in the browser
  $filename="sample.pdf";
  header('Content-Type: application/pdf');
  header("Content-Disposition: inline; filename*=UTF-8''".rawurlencode($fileName));
  echo $pdfData;


/*
//Force the PDF file to download
  header('Content-Type: application/octet-stream', false);
  header("Content-Disposition: attachment; filename*=UTF-8''".rawurlencode($fileName));
  echo $pdfData;
*/

PHP | Samples