How to Create a PDF file with PHP

in #utopian-io7 years ago (edited)

Screenshot_19.png

This tutorial we will learn how to use PDF in PHP, so this PDF we can use as virtual document, so if you want to build a payment system you can send invoice order in the form of PDF to look more professional. there are lots of packages to help us create PDFs. one of them is TCPDF. How to use and its implementation, we just start this tutorial.

What Will I Learn?

  • Installation TCPDF
  • Setting PDF in PHP
  • Add Document Information
  • Styling PDF

Requirements

  • Php >= 5.6
  • Composer
  • Localhost (xampp,wampp, or etc)
  • Basic php

Difficulty

  • Basic

Install and Preparation

The first step we have to download the first package tcpdf, we can download it from https://packagist.org/packages/tecnickcom/tcpdf . and then you open the folder where you will start the project in this tutorial my folder is tcpdf and run command prompt in there.

composer require tecnickcom/tcpdf

package.json


{
    "require": {
        "tecnickcom/tcpdf": "^6.2"
    }
}

Screenshot_15.png

Use PDF in Php

After we finish the installation process. now we will start using TCPDF in PHP. I will create an index.php file which will use the existing functions in TCPDF.
index.php

  • Create New Documment
  • Well... to create PDF document I provide variable with name $pdf to initialize new TCPDF(). If you want to see what functions are provided by TCPDF, We can see it in vendor/tecnickcom/tcpdf/tcpdf.php .
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION,PDF_UNIT,PDF_PAGE_FORMAT, true, 'UTF-8',false);.



    PDF_PAGE_ORIENTATION: $orientation (string) page orientation. Possible values are (case insensitive)

  • :P or Portrait (default)
  • L or Landscape
  • '' (empty string) for automatic orientation

  • PDF_UNIT $unit (string) User measure unit. Possible values are:
    • pt: point
    • mm: millimeter (default)
    • cm: centimeter
    • in: inch

    A point equals 1/72 of inch, that is to say about 0.35 mm (an inch being 2.54 cm). This is a very common unit in typography; font sizes are expressed in that unit.



    PDF_PAGE_FORMAT
    $format (mixed) The format used for pages. It can be either: one of the string values specified at getPageSizeFromFormat() or an array of parameters specified at setPageFormat().



    $unicode=true
    $unicode (boolean) TRUE means that the input text is unicode (default = true)

    'UTF-8'
    $encoding (string) Charset encoding (used only when converting back html entities); default is UTF-8.

    $pdfa=false
    $pdfa (boolean) If TRUE set the document to PDF/A mode.

    Functions in TCPDF

    We will learn and understand the functions that we can use to create PDFs and organize PDF files
    We can add information from the pdf document we created.

  • Add Document Information
  • 
    $pdf->SetCreator('ANONYMOUS');
    $pdf->SetTitle('Create PDF with PHP');
    $pdf->SetSubject('TPDF TUTORIAL UTOPIAN');
    
    

    $pdf->SetCreator('ANONYMOUS'); : $creator (string) The name of the creator.

    $pdf->SetTitle('Create PDF with PHP'); :$title (string) The title of document PDF.

    $pdf->SetSubject('TPDF TUTORIAL UTOPIAN');:$subject (string) The subject of document PDF.

  • Set Header Data
  • TCPDF provides the function to set margin on PDF
    
    $pdf->SetHeaderData('',30,'Tutorial Create PDF in Php with TCPDF', 'This is tutorial from Creator @alfarisi94',array(48,89,112));
    $pdf->SetFooterData(array(0,0,0),array(0,0,0));
    $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN,'',PDF_FONT_SIZE_MAIN));
    $pdf->setFooterFont(Array(PDF_FONT_NAME_MAIN,'',PDF_FONT_SIZE_MAIN));
    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
    
    

    $pdf->SetHeaderData('utopian.jpg',30,'Tutorial Create PDF in Php with TCPDF', 'This is tutorial from Creator @alfarisi94',array(48,89,112)); :
    There are 5 parameters that represent different uses. I will explain one by one :

  • @param 'utopian.jpg'
  • : (string) header image logo. adjust to the location of your image
  • @param 30
  • : (string) header image logo width in mm
  • @param 'Tutorial Create PDF in Php with TCPDF'
  • :(string) string to print as title on document header
  • @param 'This is tutorial from Creator @alfarisi94'
  • :(string) string to print on document header
  • @param(array(48,89,112))
  • :(array) RGB array color for text.


    $pdf->SetFooterData(array(0,0,0),array(0,0,0));
    in SetFooterData function there are 2 parameters

  • @param array(0,0,0)
  • : RGB array color for text.
  • @param array(0,0,0
  • : RGB array color for line.


    $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN,'',PDF_FONT_SIZE_MAIN));
    There are 3 parameters that we can pass in this function.

  • @param PDF_FONT_NAME_MAIN
  • : To setting font family.
  • @param ' '
  • : I give empty value in the second parameter, this is for setting the font style.
  • @param PDF_FONT_SIZE_MAIN
  • :To setting size font.



    $pdf->setFooterFont(Array(PDF_FONT_NAME_MAIN,'',PDF_FONT_SIZE_MAIN));
    There are 3 parameters that we can pass in this function.

  • @param PDF_FONT_NAME_MAIN
  • : To setting font family.
  • @param ' '
  • : I give empty value in the second parameter, this is for setting the font style.
  • @param PDF_FONT_SIZE_MAIN
  • :To setting size font.



    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
    Defines the default monospaced font. * @param $font (string) Font name.

  • Set Margin
  • We will set the margin of the PDF we created with the following functions.
    
    $pdf->SetMargins(PDF_MARGIN_LEFT,PDF_MARGIN_TOP,PDF_MARGIN_RIGHT);
    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
    $pdf->SetAutoPageBreak(true,PDF_MARGIN_BOTTOM);
    
    

    $pdf->SetMargins(PDF_MARGIN_LEFT,PDF_MARGIN_TOP,PDF_MARGIN_RIGHT);

  • @param PDF_MARGIN_LEFT : Left margin.
  • @param PDF_MARGIN_TOP Top margin.
  • @param PDF_MARGIN_RIGHT Right margin. Default value is the left one.

  • $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
  • Set header margin. (minimum distance between header and top page margin) @param PDF_MARGIN_HEADER distance in user units

  • $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
  • Set header margin. (minimum distance between footer and bottom page margin) @param PDF_MARGIN_HEADER distance in user units

  • $pdf->SetAutoPageBreak(true,PDF_MARGIN_BOTTOM);
  • @param $auto (boolean) Boolean indicating if mode should be on or off.
  • @param PDF_MARGIN_BOTTOM (float) Distance from the bottom of the page.

  • Scalling image
  • We can also scaling image with passing parameters as follows
  • $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

  • Font Subsetting
  • 
    $pdf->setFontSubsetting(true);
    $pdf->SetFont('helvetica','',14,'',true);
    $pdf->AddPage();
    
    

    $pdf->setFontSubsetting(true);

  • @param $enable (boolean) if true enable font subsetting by default.

  • $pdf->SetFont('helvetica', ' ' , 14 , '' , true);

    @param $family (string) Family font. It can be either a name defined by AddFont() or one of the standard Type1 families (case insensitive):

    • times (Times-Roman)
    • timesb (Times-Bold)
    • timesi (Times-Italic)
    • timesbi (Times-BoldItalic)
    • helvetica (Helvetica)
    • helveticab (Helvetica-Bold)
    • helveticai (Helvetica-Oblique)
    • helveticabi (Helvetica-BoldOblique)
    • courier (Courier)
    • courierb (Courier-Bold)
    • courieri (Courier-Oblique)
    • courierbi (Courier-BoldOblique)
    • symbol (Symbol)
    • zapfdingbats (ZapfDingbats)
    It is also possible to pass an empty string. In that case, the current family is retained.


    @param $style (string) Font style. Possible values are (case insensitive):
    • empty string: regular
    • B: bold
    • I: italic
    • U: underline
    • D: line through
    • O: overline
    or any combination. The default value is regular. Bold and italic styles do not apply to Symbol and ZapfDingbats basic fonts or other fonts when not defined.



    @param $size (float) Font size in points. The default value is the current size. If no size has been specified since the beginning of the document, the value taken is 12.



    @param $fontfile (string) The font definition file. By default, the name is built from the family and style, in lower case with no spaces.



    @param $subset (mixed) if true embedd only a subset of the font (stores only the information related to the used characters); if false embedd full font; if 'default' uses the default value set using setFontSubsetting(). This option is valid only for TrueTypeUnicode fonts. If you want to enable users to change the document, set this parameter to false. If you subset the font, the person who receives your PDF would need to have your same font in order to make changes to your PDF. The file size of the PDF would also be smaller because you are embedding only part of a font.



    @param $out (boolean) if true output the font size command, otherwise only set the font properties.

    Add PDF file

  • Add Content PDF
  • $pdf->AddPage(); : To add all the settings we've made before


  • Content PDF

  • $html=<<<EOD
    <h1>Thank you for following this tutorial</h1>
    <p>I hope you get a lot of benefits in this tutorial, see you in the next tutorial in <span style="color:#ccccc;">utopian</span></p>
    EOD;
    
    
    $pdf->writeHTMLCell(0,0,'','',$html,0,1,0,true,'',true);
    $pdf->Output('tutorial_PDF.pdf','I');
    
    

    $pdf->writeHTMLCell(0,0,'','',$html,0,1,0,true,'',true);

    @param $w (float) Cell width. If 0, the cell extends up to the right margin.
    * @param $h (float) Cell minimum height. The cell extends automatically if needed.
    * @param $x (float) upper-left corner X coordinate
    * @param $y (float) upper-left corner Y coordinate
    * @param $html (string) html text to print. Default value: empty string.
    * @param $border (mixed) Indicates if borders must be drawn around the cell. The value can be a number:

    • 0: no border (default)
    • 1: frame
    or a string containing some or all of the following characters (in any order):
    • L: left
    • T: top
    • R: right
    • B: bottom
    or an array of line styles for each border group - for example: array('LTRB' => array('width' => 2, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)))
    * @param $ln (int) Indicates where the current position should go after the call. Possible values are:
    • 0: to the right (or left for RTL language)
    • 1: to the beginning of the next line
    • 2: below

    Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
    * @param $fill (boolean) Indicates if the cell background must be painted (true) or transparent (false).
    * @param $reseth (boolean) if true reset the last cell height (default true).
    * @param $align (string) Allows to center or align the text. Possible values are:
    • L : left align
    • C : center
    • R : right align
    • '' : empty string : left for LTR or right for RTL

    * @param $autopadding (boolean) if true, uses internal padding and automatically adjust it to account for line width.

    $pdf->Output('tutorial_PDF.pdf','I');

    @param $name (string) The name of the file when saved. Note that special characters are removed and blanks characters are replaced with the underscore character.
    * @param $dest (string) Destination where to send the document. It can take one of the following values:

    • I: send the file inline to the browser (default). The plug-in is used if available. The name given by name is used when one selects the "Save as" option on the link generating the PDF.
    • D: send to the browser and force a file download with the name given by name.
    • F: save to a local server file with the name given by name.
    • S: return the document as a string (name is ignored).
    • FI: equivalent to F + I option
    • FD: equivalent to F + D option
    • E: return the document as base64 mime multi-part email attachment (RFC 2045)

    Result Code Tutorial

    I share every part I describe one by one in each section, now I want to merge files and functions into one. all my code is only in one file that is index.php.

    index.php

    <?php 
    require_once 'vendor/autoload.php';
    define('K_PATH_IMAGES','images/');
    //create new document
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION,PDF_UNIT,PDF_PAGE_FORMAT, true, 'UTF-8',false);
    //document information
    $pdf->SetCreator('ANONYMOUS');
    $pdf->SetTitle('Create PDF with PHP');
    $pdf->SetSubject('TPDF TUTORIAL UTOPIAN');
    //header data
    $pdf->SetHeaderData('utopian.jpg',30,'Tutorial Create PDF in Php with TCPDF', 'This is tutorial from Creator @alfarisi94',array(48,89,112));
    $pdf->SetFooterData(array(0,0,0),array(0,0,0));
    $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN,'',PDF_FONT_SIZE_MAIN));
    $pdf->setFooterFont(Array(PDF_FONT_NAME_MAIN,'',PDF_FONT_SIZE_MAIN));
    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
    //set margin
    $pdf->SetMargins(PDF_MARGIN_LEFT,PDF_MARGIN_TOP,PDF_MARGIN_RIGHT);
    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
    $pdf->SetAutoPageBreak(true,PDF_MARGIN_BOTTOM);
    //set scalling image
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
    //font subsetting
    $pdf->setFontSubsetting(true);
    $pdf->SetFont('helvetica','',14,'',true);
    $pdf->AddPage();
    $html=<<<EOD
    <h1>Thank you for following this tutorial</h1>
    <p>I hope you get a lot of benefits in this tutorial, see you in the next tutorial in <span style="color:#ccccc;">utopian</span></p>
    EOD;
    $pdf->writeHTMLCell(0,0,'','',$html,0,1,0,true,'',true);
    $pdf->Output('tutorial_PDF.pdf','I');
    

    Run your localhost to your index.php. and we will see the pdf file we have created.

    Screenshot_19.png

    Screenshot_20.png

    We finally managed to create a pdf file using PHP, many settings that we build to create a PDF file but after we managed to make its settting, we can use it repeatedly. just so much of me I hope you benefit from the tutorial I have created. Thank you for following this tutorial



    Posted on Utopian.io - Rewarding Open Source Contributors

    Sort:  

    It will be easier if u use FPDF.. and lets check the originality of this post since @amosbastian i accusing you... @OriginalWorks

    Your contribution cannot be approved because it does not follow the Utopian Rules, and is considered as plagiarism. Plagiarism is not allowed on Utopian, and posts that engage in plagiarism will be flagged and hidden forever.

    The only real difference between your tutorial and e.g. this example on the official website is that you have copied and pasted (plagiarised) the documentation of each function's parameters from tcpdf.php.

    You can contact us on Discord.
    [utopian-moderator]

    Hey Guys, I am looking for the services to merge pdf online. Here I found this website which are providing these services at free of cost at basic levels. You can also try these merge services for documents if you are also looking for the same.

    Coin Marketplace

    STEEM 0.19
    TRX 0.15
    JST 0.029
    BTC 63179.13
    ETH 2573.33
    USDT 1.00
    SBD 2.72