Проект TCPDF возник в 2002 году и в настоящее время является одним из самых активных в мире проектов с открытым исходным кодом. Текущая версия 8.0.x находится в разработке и не готова к использованию, при этом найти предыдущую версии не просто но возможно.
Официальный сайт проекта TCPDF //tcpdf.org
Содержит описание, документацию и много примеров к версиям до 6.x.
Download TCPDF 6.3.2 https://sourceforge.net/projects/tcpdf/files/latest/download
Новая версия еще не готова и находится на //github.com/tecnickcom/tc-lib-pdf
Введение
Проект TCPDF является далеким потомком проекта FPDF, поэтому сохраняет ряд сходств со своим предком.
Документ
//
-
1public __construct([string $orientation = 'P' ][, string $unit = 'mm' ][, mixed $format = 'A4' ][, bool $unicode = true ][, string $encoding = 'UTF-8' ][, bool $diskcache = false ][, false|int $pdfa = false ]) : mixed
It allows to set up the page format, the orientation and the measure unit used in all the methods (except for the font sizes). - $orientation : string page orientation. Possible values are (case insensitive):
- P or Portrait (default)
- L or Landscape
- '' (empty string) for automatic orientation
- $unit : string = 'mm' 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.
- $format : mixed = 'A4' 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 : bool = true TRUE means that the input text is unicode (default = true)
- $encoding : string = 'UTF-8' Charset encoding (used only when converting back html entities); default is UTF-8
- $diskcache : bool = false
- $pdfa : false|int = false DEPRECATED FEATURE If not false, set the document to PDF/A mode and the good version (1 or 3).
//
Вывод документа
Вывод документа происходит в только финале использования fpdf-объекта, однако метод вывода , как и конструктор, применяются в любом случае, поэтом по значимости метод вывода занимает второе место:
-
1public Output([string $name = 'doc.pdf' ][, string $dest = 'I' ]) : string
Send the document to a given destination: string, local file or browser. In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.
The method first calls Close() if necessary to terminate the document.- $name : string = 'doc.pdf' The name of the file when saved
- $dest : string = 'I' 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)
Опции вывода
Страницы
//
- Adds a new page to the document. If a page is already present, the Footer() method is called first to output the footer (if enabled). Then the page is added, the current position set to the top-left corner according to the left and top margins (or top-right if in RTL mode), and Header() is called to display the header (if enabled).
1public AddPage([string $orientation = '' ][, mixed $format = '' ][, bool $keepmargins = false ][, bool $tocpage = false ]) : mixed
The origin of the coordinate system is at the top-left corner (or top-right for RTL) and increasing ordinates go downwards.- $orientation : string = '' page orientation. Possible values are (case insensitive):
- P or PORTRAIT (default)
L or LANDSCAPE
$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().
- P or PORTRAIT (default)
- $keepmargins : bool = false if true overwrites the default page margins with the current margins
- $tocpage : bool = false if true set the tocpage state to true (the added page will be used to display Table Of Content)
- $orientation : string = '' page orientation. Possible values are (case insensitive):
- Устанавливает режим вывода верхнего колонтитула
1public setPrintHeader([bool $val = true ]) : mixed
Следует выполнять до метода AddPage() - Устанавливает режим вывода верхнего колонтитула
1public setPrintFooter([bool $val = true ]) : mixed
Следует выполнить до автоматической смены страницы и/или до AddPage() - Метод устанавливает содержание верхнего колонтитула
1public setHeaderData([string $ln = '' ], int $lw[, string $ht = '' ][, string $hs = '' ][, array<string|int, int> $tc = array(0, 0, 0) ][, array<string|int, int> $lc = array(0, 0, 0) ]) : mixed- $ln : string = '' header image logo
- $lw : int header image logo width in mm
- $ht : string = '' string to print as title on document header
- $hs : string = '' string to print on document header
- $tc : array<string|int, int> = array(0, 0, 0) RGB array color for text
- $lc : array<string|int, int> = array(0, 0, 0) RGB array color for line
Вывод строк
// Text(), Cell(), Write(), MultiCell(), WriteHTML(), WriteHTMLCell()
- This method prints text from the current position
1public Write(float $h, string $txt[, mixed $link = '' ][, bool $fill = false ][, string $align = '' ][, bool $ln = false ], int $stretch[, bool $firstline = false ][, bool $firstblock = false ], float $maxh, float $wadj[, array<string|int, mixed>|null $margin = null ]) : mixed- $h : float Line height
- $txt : string String to print
- $link : mixed = '' URL or identifier returned by AddLink()
- $fill : bool = false Indicates if the cell background must be painted (true) or transparent (false).
- $align : string = '' Allows to center or align the text. Possible values are:
- L or empty string: left align (default value)
- C: center
- R: right align
- J: justify
- $ln : bool = false если true установить курсор в нижней части строки, в противном случае установить курсор в верхней части строки
- $stretch : int font stretch mode:
- 0 = disabled
- 1 = horizontal scaling only if text is larger than cell width
- 2 = forced horizontal scaling to fit cell width
- 3 = character spacing only if text is larger than cell width
- 4 = forced character spacing to fit cell width
General font stretching and scaling values will be preserved when possible.
- $firstline : bool = false если true печатает только первую строку и возвращает оставшуюся строку
- $firstblock : bool = false если true, строка является началом строки
- $maxh : float maximum height. It should be >= $h and less then remaining space to the bottom of the page, or 0 for disable this feature.
- $wadj : float first line width will be reduced by this amount (used in HTML mode).
- $margin : array<string|int, mixed>|null = null margin array of the parent container
Шрифты
Шрифты, которые TCPDF использует при создании документа и включает в файл лежат в каталоге fonts. Каждому шрифту соответствует пакет из трех файлов *.php, *.z и *.ctg.z.
Методы TCPDF
// Перед выводом текстовых строк на страницу
-
1public setFont(string $family[, string $style = '' ][, float|null $size = null ][, string $fontfile = '' ][, mixed $subset = 'default' ][, bool $out = true ]) : mixed
The font can be either a standard one or a font added via the AddFont() method. Standard fonts use Windows encoding cp1252 (Western Europe). The method can be called before the first page is created and the font is retained from page to page. If you just wish to change the current font size, it is simpler to call SetFontSize(). Note: for the standard fonts, the font metric files must be accessible. There are three possibilities for this:- They are in the current directory (the one where the running script lies)
They are in one of the directories defined by the include_path parameter
They are in the directory defined by the K_PATH_FONTS constant - $family : string имя семейства шрифтов, заданное в AddFont() или одно из стандертных Type1 (не чувствительно к регистру):
- 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.
- $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.
$size : float|null = null
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
- $fontfile : string = '' The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
- $subset : mixed = 'default'
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.$out : bool = true
if true output the font size command, otherwise only set the font properties.
- They are in the current directory (the one where the running script lies)
- Imports a TrueType, Type1, core, or CID0 font and makes it available
1public AddFont(string $family[, string $style = '' ][, string $fontfile = '' ][, mixed $subset = 'default' ]) : array<string|int, mixed>|false
It is necessary to generate a font definition file first (read /fonts/utils/README.TXT). The definition file (and the font file itself when embedding) must be present either in the current directory or in the one indicated by K_PATH_FONTS if the constant is defined. If it could not be found, the error "Could not include font definition file" is generated.- $family : string Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.
- $style : string = '' Font style. Possible values are (case insensitive):
- empty string: regular (default)
- B: bold
- I: italic
- BI or IB: bold italic
- $fontfile : string = ''
The font definition file. By default, the name is built from the family and style, in lower case with no spaces. - $subset : mixed = 'default'
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.
Шрифты TCPDF и шрифты TTF
Шрифт для применения в TCPDF должен использоваться пакетом файлов *.php, *.z и *.ctg.z. В наборе шрифтов TCPDF 6.3 имеется более 70ти шрифтов, но при необходимости пакет дополнительного шрифта можно получить из файла TTF, воспользовавшись онлайн сервисом, например //fonts.palettize.me/
В Интернет есть инструкция по самостоятельной подготовке пакета шрифта, которая описывает два этапа. На первом из файла TTF получают файл метрик UFM утилитой ttf2ufm:
1 |
ttf2ufm -a -F Lato.ttf |
На втором этапе применяется локальный или серверный вызов PHP:
1 |
php -q makefont.php Lato.ttf Lato.ufm |
1 2 3 4 |
<?php require('makefont.php'); MakeFont('Lato.ttf', 'Lato.ufm', true,' iso-8859-5'); ?> |
По неизвестной причине в моем случае утилита ttf2ufm формировала пустые файлы и результат мне получить не удалось.
Непроверенное мнение
Источник: https://truewebstories.ru/zametki/tcpdf-prakticheskie-zametki-dokumentaciya-na-russkom
Последняя версия TCPDF автоматически преобразует шрифты в формат TCPDF с использованием метода addTTFfont(). Старые шрифтовые программы и скрипты были удалены.
Например:
1 2 3 |
// convert TTF font to TCPDF format and store it on the fonts folder $fontname = $pdf->addTTFfont ('/path-to-font/FreeSerifItalic.ttf', 'TrueTypeUnicode', '', 96); // use the font $pdf->SetFont ($fontname, '', 14, '', false); |
ПРИМЕЧАНИЕ. После того, как шрифт был преобразован, TCPDF больше не требует, чтобы TTF файл или вышеупомянутый вызов.
addTTFfont ()
** У меня не получилось сделать по примеру, что показан выше, я использовал такой код:
1 2 |
$path_to_ttf = $_SERVER["DOCUMENT_ROOT"] . '/tcpdf/fonts/arial/arial.ttf'; $fontname = TCPDF_FONTS::addTTFfont ($path_to_ttf , 'TrueTypeUnicode', '', 96); |
Картинки
//
- Puts an image in the page
123456789101112public Image(string $file[, float|null $x = null ][, float|null $y = null ], float $w, float $h[, string $type = '' ][, mixed $link = '' ][, string $align = '' ][, mixed $resize = false ][, int $dpi = 300 ][, string $palign = '' ][, bool $ismask = false ][, mixed $imgmask = false ],mixed $border[, mixed $fitbox = false ][, bool $hidden = false ][, bool $fitonpage = false ][, bool $alt = false ][, array<string|int, mixed> $altimgs = array() ]) : mixed|false
The upper-left corner must be given. The dimensions can be specified in different ways:explicit width and height (expressed in user unit)
one explicit dimension, the other being calculated automatically in order to keep the original proportions
no explicit dimension, in which case the image is put at 72 dpi
Supported formats are JPEG and PNG images whitout GD library and all images supported by GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM; The format can be specified explicitly or inferred from the file extension.
It is possible to put a link on the image.
Remark: if an image is used several times, only one copy will be embedded in the file.- $file : string
Name of the file containing the image or a '@' character followed by the image data string. To link an image without embedding it on the document, set an asterisk character before the URL (i.e.: '*http://www.example.com/image.jpg'). - $x : float|null = null Abscissa of the upper-left corner (LTR) or upper-right corner (RTL).
- $y : float|null = null Ordinate of the upper-left corner (LTR) or upper-right corner (RTL).
- $w : float Width of the image in the page. If not specified or equal to zero, it is automatically calculated
- $h : float Height of the image in the page. If not specified or equal to zero, it is automatically calculated
- $type : string = '' формат файла, по умолчанию определяется по расширению, но при явном указания чрезвычайно важно задать правильно одно из значений (в любом регистре):
- JPEG и PNG (без GD библиотеки) и все форматы поддерживаемые GD: GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM
- $link : mixed = '' URL or identifier returned by AddLink()
- $align : string = '' устанавливает выравнивание текущий позиции указателя рядом с вставкой изображения относительно высоты изображения. Значение может быть:
- T: top-right for LTR or top-left for RTL
- M: middle-right for LTR or middle-left for RTL
- B: bottom-right for LTR or bottom-left for RTL
- N: next line
- $resize : mixed = false If true resize (reduce) the image to fit $w and $h (requires GD or ImageMagick library); if false do not resize; if 2 force resize in all cases (upscaling and downscaling)
- $dpi : int = 300 dot-per-inch resolution used on resize
- $palign : string = '' Allows to center or align the image on the current line. Possible values are:
- L : left align
- C : center
- R : right align
'' : empty string : left for LTR or right for RTL
- $ismask : bool = false true if this image is a mask, false otherwise
- $imgmask : mixed = false объект изображения, возвращаемый этой функцией, или false
- $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))) - $fitbox : mixed = false
If not false scale image dimensions proportionally to fit within the ($w, $h) box. $fitbox can be true or a 2 characters string indicating the image alignment inside the box. The first character indicate the horizontal alignment (L = left, C = center, R = right) the second character indicate the vertical algnment (T = top, M = middle, B = bottom). - $hidden : bool = false
If true do not display the image. - $fitonpage : bool = false
If true the image is resized to not exceed page dimensions. - $alt : bool = false Если true, изображение будет добавлено как альтернативное, а не распечатано напрямую (будет возвращен идентификатор изображения)
- $altimgs : array<string|int, mixed> = array()
Array of alternate images IDs. Each alternative image must be an array with two values: an integer representing the image ID (the value returned by the Image method) and a boolean value to indicate if the image is the default for printing.
- 1: frame
- $file : string