PDF generation plug-in -- TcPDF

preface

Last week, we added a markdown editor to BiShe website. Then at the weekend, I suddenly thought that it would be good to add a function of exporting pdf to the editor (why can't we export pdf for simple books), so I found a PHP plug-in for generating pdf from the Internet, called tcpdf. It's very big, and the example file is close to 16m. I spent a day doing this.

In fact, according to the example of this plug-in, I can quickly produce pdf, but I spent the rest of the time studying how to make the generated pdf look better. Obviously, I failed. Normal text is OK. If there is such a code, it will either not be displayed, and the displayed part is also messy. As follows:

 

Incorrect code display

 

code cannot be displayed

Although it's of no value to me, after all, I've studied it and wrote a small log.

File import

from TCPDF Download the latest version. Although 65 demo s are included in the download package, it doesn't tell me which documents must be introduced. Let's go straight to the program file. Open the main program file tcpdf PHP, as can be seen from the starting code, the following files must be included:

tcpdf_autoconfig.php
include folder

Require in search of all files_ Once, there are the following files:

tcpdf_barcodes_1d.php
tcpdf_barcodes_2d.php

ok, tcpdf PHP and the above files are copied to the project folder,

require_once('./tcpdf.php');
$pdf = new TCPDF();

Execution, and then an error occurred:

Warning: opendir(C:\Practice\Apache24\htdocs\demo\PDF/fonts/,C:\Practice\Apache24\htdocs\demo\PDF/fonts/): in C:\Practice\Apache24\htdocs\demo\PDF\tcpdf.php on line 4148
Warning: opendir(C:\Practice\Apache24\htdocs\demo\PDF/fonts/): failed to open dir: No such file or directory in C:\Practice\Apache24\htdocs\demo\PDF\tcpdf.php on line 4148
TCPDF ERROR: Could not include font definition file: helvetica

Obviously, copy the fonts folder in the download package to the project.

implement

After the above introduction and debugging, it can now be instantiated normally. In the above code, I instantiated tcpdf method without passing any parameters, but in fact, the method has 7 parameters to pass, as follows:

attributeexplainDefault value
$orientationSet the orientation of the pdf pagePortrait
$unitSets the unit of measurement for pdf cellsmm
$formatPage layoutA4
$unicodeUse unicodetrue
$encodingCharacter encodingutf-8
$diskcacheThis function is obsoletefalse
$pdfaEnable / disable pdf/atrue

The details are as follows:

$orientation

It is used to set the direction of pdf pages. There are two parameters:

Parameter namemeaningdefault
P/Portraitportraittrue
L/Landscapetransversefalse

$unit

It is used to set the measurement unit of pdf unit. There are four parameters

Parameter namemeaningdefault
pt: pointpointfalse
mm: millimetermillimetertrue
cm: centimetercentimeterfalse
in: inchinchfalse

$format

Indicates the layout of the page, such as A4, etc. And his default is A4. Tcpdf supports many formats. You can go to tcpdf_ static. $page in PHP_ Formats property.

$unicode

Boolean type. True means that the input text is $unicode. There's nothing to say about this. It's generally unicode, and the default is true.

$encoding

Character encoding. The default is utf-8.

$diskcache

This parameter is not explained on the official website, nor is the program file. However, it is written in the detailed feature. Obviously, this function is abandoned and is not recommended. It can be set to false directly.

$pdfa

PDF/A is the ISO standard of pdf. It is designed for long-term preservation of files and shields some editing functions. That is, if ` $pdfa = true * *, the generated pdf cannot be edited.

Well, you can instantiate these seven parameters after you have figured them out. Of course, if you just use them briefly, you can instantiate them directly, because these seven parameters have default values, and generally these default values do not need to be modified.

to configure

tcpdf has many configuration options, which are roughly divided into four parts, including document information setting, header and footer setting, text spacing setting and text setting. It is divided into several small parts. Before completing the function, briefly introduce the necessary methods in these parts.

As follows:

1. Document information settings

Including setcreator (document creator name), setauthor (set author), settitle (set document title), setkeywords (document keywords). There is nothing to say about the parameters of these methods. string type is mainly used to set the properties of documents, as shown in the following:

 

document property

2 header and footer settings

Including SetHeaderData, setFooterData, setHeaderFont and setFooterFont

SetHeaderData method has 6 parameters, including:

attributeexplainDefault value
$lnlogo file path''
$lwlogo width0
$htHeader title''
$hsHeader description text''
$tcrgb color of text0,0 (black)
$lcColor of header underlinearray(0,0,0) (black)

setFooterData has only two parameters, the color of footer text and the color of underline.

setHeaderFont and setFooterFont respectively set the font of the header and footer. There is only one parameter. Note that they are array types, and the passed array format is as follows:

 

array(family, style, size)

Corresponding to font family, font style and font size.

In addition, if you do not want to use the header and footer, you can use setPrintHeader and setPrintFooter methods to close the header and footer, as long as you pass the parameter false.

3 text spacing setting

Spacing includes text spacing and header footer spacing. There are three methods: SetMargins, SetHeaderMargin and SetFooterMargin.

SetMargins is used for text. It has three parameters, which respectively represent the spacing on the left, upper and right sides. SetHeaderMargin and SetFooterMargin are the spacing between the header and footer respectively.

4. Set text

Text settings include pagination, picture proportion, text font, etc.

First, use SetAutoPageBreak to start paging. This method passes two parameters. Parameter 1 enables or disables automatic paging, while parameter 2 works only when parameter 1 is equal to true. It defines the distance from the page to the bottom.

Then use the AddPage method to add a new page. At the same time, if there is a previous page in this method, this method will add the footer to the page and automatically add the next page, otherwise directly add a new page.

Font settings include setFontSubsetting, SetFont and SetDefaultMonospacedFont.

I don't understand the method of setFontSubsetting, because I don't know what font construction subset is. Skip. SetFont is used to set the text font. Parameter passing is similar to setHeaderFont, but this method divides the three options into three parameter passing instead of passing an array. In addition, if you are generating Chinese pdf, you need to pay special attention. You must set the font to stsongstdlight, otherwise Chinese garbled code will appear.

Of course, the text is written. If it's just an ordinary document, the Write method is generally used. There are 12 parameters in total, so I won't introduce them one by one. Let's talk about the two required parameters, that is, the first two parameters, $h represents the row height and $txt represents the content to be printed. Others can be defaulted.

If you print an html document and include css files, you need to use the writeHTML method. This method has six parameters, but only one is the content to be printed. Other parameters can be the default values.

Well, after the introduction of configuration and parameters, follow the steps I introduced step by step to generate pdf. Here is the generation code I wrote myself:

class pdf {

    # Constant setting
    const PDF_LOGO       = '\Logo\logo_big.png';                    // LOGO path this path is under tcpdf
    const PDF_LOGO_WIDTH = '20';                                    // LOGO width
    const PDF_TITLE      = 'www.liuweime.me';                       // 
    const PDF_HEAD       = 'Take a computer class';
    const PDF_FONT       = 'stsongstdlight';
    const PDF_FONT_STYLE = '';
    const PDF_FONT_SIZE  = 10;
    const PDF_FONT_MONOSPACED = 'courier';
    const PDF_IMAGE_SCALE='1.25';


    # tcpdf object storage
    protected $pdf = null;
    
    /**
     * Constructor introduces the plug-in and instantiates it
     */
    public function __construct() {     
        # Instantiate the plug-in
        $this->pdf = new TCPDF(); 
    }

    /**
     * Set document information    
     * @param  $user        string  Document author
     * @param  $title       string  document title
     * @param  $subject     string  Document subject
     * @param  $keywords    string  Document keywords
     * @return null
     */
    protected function setDocumentInfo($user = '', $title = '', $subject ='', $keywords = '') {
        if(empty($user) || empty($title)) return false;
        # Document creator name
        $this->pdf->SetCreator(APP_NAME);
        # author
        $this->pdf->SetAuthor($user);
        # document title
        $this->pdf->SetTitle($title);
        # Document subject
        if(!empty($subject)) $this->pdf->SetSubject($subject);
        # Document keywords
        if(!empty($keywords)) $this->pdf->SetKeywords($keywords);       

    }

    /**
     * Set header and footer information of the document
     * @param  null
     * @return null
     */
    protected function setHeaderFooter() {
        # Set header information 
        # Format logo address logo width header title header description text header font color header underline color
        $this->pdf->SetHeaderData(self::PDF_LOGO , self::PDF_LOGO_WIDTH , self::PDF_TITLE , self::PDF_HEAD , array(35 , 35 , 35) , array(221,221,221));
        # Set footer information
        # Format footer font color footer underline color
        $this->pdf->setFooterData(array(35 , 35 , 35) , array(221,221,221));
        
        # Set header and footer font
        $this->pdf->setHeaderFont(array('stsongstdlight' , self::PDF_FONT_STYLE , self::PDF_FONT_SIZE));
        $this->pdf->setFooterFont(array('helvetica' , self::PDF_FONT_STYLE , self::PDF_FONT_SIZE));
    }

    /**
     * Close header and footer
     * @param  null
     * @return null
     */
    protected function closeHeaderFooter() {
        # Close header
        $this->pdf->setPrintHeader(false);
        # Close footer
        $this->pdf->setPrintFooter(false);
    }

    /**
     * Set spacing, including text spacing, header and footer spacing
     * @param  null
     * @return null
     */
    protected function setMargin() {
        # Sets the default constant width font
        $this->pdf->SetDefaultMonospacedFont('courier');
        # Space between left and right sides of text
        $this->pdf->SetMargins(15, 7, 15);
        # Header spacing
        $this->pdf->SetHeaderMargin(5);
        # Footer spacing
        $this->pdf->SetFooterMargin(10);
    }

    /**
     * Text settings include paging picture scale and text font
     * @param  null
     * @return null  
     */
    protected function setMainBody() {
        
        # Turn on paging true turn on false turn off when turning on paging parameter 2 works, indicating the space between the text and the bottom
        $this->pdf->SetAutoPageBreak(true , 25);
        # Set picture scale
        $this->pdf->setImageScale(self::PDF_IMAGE_SCALE);
        #
        $this->pdf->setFontSubsetting(true);
        # Set body font stsongstdlight is Adobe Reader's default font
>       $this->pdf->SetFont('stsongstdlight', '', 14); 
        # Add page this method will add the footer to the page and automatically add the next page if there is an existing page. Otherwise, add a new page
        $this->pdf->AddPage();      
    }

    /**
     * Generate pdf
     * @param  $info    array   
     *   array(
     *          'user'=>'Document author ', 
     *          'title'=>'Document title ', 
     *          'subject'=>'Document subject ', 
     *          'keywords'=>'Document keyword ', 
     *          'content'=>'Document body content ', 
     *          'HT'=>'Whether to open header and footer ', 
     *          'path'=>'Document saving path ');
     * @return null  
     */
    public function createPDF($info = array()) {
        if(empty($info) || !is_array($info)) return false;

        $this->setDocumentInfo($info['user'] , $info['title'] , $info['subject'] , $info['keywords']);
        if(!$info['HT']) {

            $this->closeHeaderFooter();
        } else {
            $this->setHeaderFooter();
        }
        
        $this->setMargin();
        $this->setMainBody();

        # Write content
        $this->pdf->writeHTML($info['content'], true, false, true, false, '');

        # Output I output to browser F output to specified path
        $this->pdf->Output($info['path'] , 'F');
    }
}

epilogue

Although I didn't achieve the desired effect, I still got some results. Moreover, I saw a PHP file with more than 20000 lines of code in one file for the first time. It was a little 66. I was going to look at the source code and learn it. I felt a little empty after seeing the code, ha ha.



Author: ah V mint and coke
Link: https://www.jianshu.com/p/3c0ad038cee7
Source: Jianshu
The copyright belongs to the author. For commercial reprint, please contact the author for authorization. For non-commercial reprint, please indicate the source.

Keywords: PHP

Added by zrocker on Sat, 19 Feb 2022 03:16:41 +0200