/lib/plugins/rfpdf/lib/tcpdf.rb
Ruby | 4357 lines | 2761 code | 349 blank | 1247 comment | 445 complexity | 2a69060c7993db1fa65db2ff2ce2c191 MD5 | raw file
Possible License(s): GPL-2.0
Large files files are truncated, but you can click here to view the full file
- #============================================================+
- # File name : tcpdf.rb
- # Begin : 2002-08-03
- # Last Update : 2007-03-20
- # Author : Nicola Asuni
- # Version : 1.53.0.TC031
- # License : GNU LGPL (http://www.gnu.org/copyleft/lesser.html)
- #
- # Description : This is a Ruby class for generating PDF files
- # on-the-fly without requiring external
- # extensions.
- #
- # IMPORTANT:
- # This class is an extension and improvement of the Public Domain
- # FPDF class by Olivier Plathey (http://www.fpdf.org).
- #
- # Main changes by Nicola Asuni:
- # Ruby porting;
- # UTF-8 Unicode support;
- # code refactoring;
- # source code clean up;
- # code style and formatting;
- # source code documentation using phpDocumentor (www.phpdoc.org);
- # All ISO page formats were included;
- # image scale factor;
- # includes methods to parse and printsome XHTML code, supporting the following elements: h1, h2, h3, h4, h5, h6, b, u, i, a, img, p, br, strong, em, font, blockquote, li, ul, ol, hr, td, th, tr, table, sup, sub, small;
- # includes a method to print various barcode formats using an improved version of "Generic Barcode Render Class" by Karim Mribti (http://www.mribti.com/barcode/) (require GD library: http://www.boutell.com/gd/);
- # defines standard Header() and Footer() methods.
- #
- # Ported to Ruby by Ed Moss 2007-08-06
- #
- #============================================================+
- require 'tempfile'
- require 'core/rmagick'
- #
- # TCPDF Class.
- # @package com.tecnick.tcpdf
- #
-
- @@version = "1.53.0.TC031"
- @@fpdf_charwidths = {}
- PDF_PRODUCER = 'TCPDF via RFPDF 1.53.0.TC031 (http://tcpdf.sourceforge.net)'
- module TCPDFFontDescriptor
- @@descriptors = { 'freesans' => {} }
- @@font_name = 'freesans'
- def self.font(font_name)
- @@descriptors[font_name.gsub(".rb", "")]
- end
- def self.define(font_name = 'freesans')
- @@descriptors[font_name] ||= {}
- yield @@descriptors[font_name]
- end
- end
- # This is a Ruby class for generating PDF files on-the-fly without requiring external extensions.<br>
- # This class is an extension and improvement of the FPDF class by Olivier Plathey (http://www.fpdf.org).<br>
- # This version contains some changes: [porting to Ruby, support for UTF-8 Unicode, code style and formatting, php documentation (www.phpdoc.org), ISO page formats, minor improvements, image scale factor]<br>
- # TCPDF project (http://tcpdf.sourceforge.net) is based on the Public Domain FPDF class by Olivier Plathey (http://www.fpdf.org).<br>
- # To add your own TTF fonts please read /fonts/README.TXT
- # @name TCPDF
- # @package com.tecnick.tcpdf
- # @@version 1.53.0.TC031
- # @author Nicola Asuni
- # @link http://tcpdf.sourceforge.net
- # @license http://www.gnu.org/copyleft/lesser.html LGPL
- #
- class TCPDF
- include RFPDF
- include Core::RFPDF
- include RFPDF::Math
-
- def logger
- Rails.logger
- end
- cattr_accessor :k_cell_height_ratio
- @@k_cell_height_ratio = 1.25
- cattr_accessor :k_blank_image
- @@k_blank_image = ""
-
- cattr_accessor :k_small_ratio
- @@k_small_ratio = 2/3.0
-
- cattr_accessor :k_path_cache
- @@k_path_cache = Rails.root.join('tmp')
-
- cattr_accessor :k_path_url_cache
- @@k_path_url_cache = Rails.root.join('tmp')
-
- cattr_accessor :decoder
-
- attr_accessor :barcode
-
- attr_accessor :buffer
-
- attr_accessor :diffs
-
- attr_accessor :color_flag
-
- attr_accessor :default_table_columns
- attr_accessor :max_table_columns
-
- attr_accessor :default_font
- attr_accessor :draw_color
-
- attr_accessor :encoding
-
- attr_accessor :fill_color
-
- attr_accessor :fonts
-
- attr_accessor :font_family
-
- attr_accessor :font_files
-
- cattr_accessor :font_path
-
- attr_accessor :font_style
-
- attr_accessor :font_size_pt
-
- attr_accessor :header_width
-
- attr_accessor :header_logo
-
- attr_accessor :header_logo_width
-
- attr_accessor :header_title
-
- attr_accessor :header_string
-
- attr_accessor :images
-
- attr_accessor :img_scale
-
- attr_accessor :in_footer
-
- attr_accessor :is_unicode
- attr_accessor :lasth
-
- attr_accessor :links
-
- attr_accessor :list_ordered
-
- attr_accessor :list_count
-
- attr_accessor :li_spacer
-
- attr_accessor :n
-
- attr_accessor :offsets
-
- attr_accessor :orientation_changes
-
- attr_accessor :page
-
- attr_accessor :page_links
-
- attr_accessor :pages
-
- attr_accessor :pdf_version
-
- attr_accessor :prevfill_color
-
- attr_accessor :prevtext_color
-
- attr_accessor :print_header
-
- attr_accessor :print_footer
-
- attr_accessor :state
-
- attr_accessor :tableborder
-
- attr_accessor :tdbegin
-
- attr_accessor :tdwidth
-
- attr_accessor :tdheight
-
- attr_accessor :tdalign
-
- attr_accessor :tdfill
-
- attr_accessor :tempfontsize
-
- attr_accessor :text_color
-
- attr_accessor :underline
-
- attr_accessor :ws
-
- #
- # This is the class constructor.
- # It allows to set up the page format, the orientation and
- # the measure unit used in all the methods (except for the font sizes).
- # @since 1.0
- # @param string :orientation page orientation. Possible values are (case insensitive):<ul><li>P or Portrait (default)</li><li>L or Landscape</li></ul>
- # @param string :unit User measure unit. Possible values are:<ul><li>pt: point</li><li>mm: millimeter (default)</li><li>cm: centimeter</li><li>in: inch</li></ul><br />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.
- # @param mixed :format The format used for pages. It can be either one of the following values (case insensitive) or a custom format in the form of a two-element array containing the width and the height (expressed in the unit given by unit).<ul><li>4A0</li><li>2A0</li><li>A0</li><li>A1</li><li>A2</li><li>A3</li><li>A4 (default)</li><li>A5</li><li>A6</li><li>A7</li><li>A8</li><li>A9</li><li>A10</li><li>B0</li><li>B1</li><li>B2</li><li>B3</li><li>B4</li><li>B5</li><li>B6</li><li>B7</li><li>B8</li><li>B9</li><li>B10</li><li>C0</li><li>C1</li><li>C2</li><li>C3</li><li>C4</li><li>C5</li><li>C6</li><li>C7</li><li>C8</li><li>C9</li><li>C10</li><li>RA0</li><li>RA1</li><li>RA2</li><li>RA3</li><li>RA4</li><li>SRA0</li><li>SRA1</li><li>SRA2</li><li>SRA3</li><li>SRA4</li><li>LETTER</li><li>LEGAL</li><li>EXECUTIVE</li><li>FOLIO</li></ul>
- # @param boolean :unicode TRUE means that the input text is unicode (default = true)
- # @param String :encoding charset encoding; default is UTF-8
- #
- def initialize(orientation = 'P', unit = 'mm', format = 'A4', unicode = true, encoding = "UTF-8")
-
- # Set internal character encoding to ASCII#
- #FIXME 2007-05-25 (EJM) Level=0 -
- # if (respond_to?("mb_internal_encoding") and mb_internal_encoding())
- # @internal_encoding = mb_internal_encoding();
- # mb_internal_encoding("ASCII");
- # }
-
- #Some checks
- dochecks();
-
- begin
- @@decoder = HTMLEntities.new
- rescue
- @@decoder = nil
- end
-
- #Initialization of properties
- @barcode ||= false
- @buffer ||= ''
- @diffs ||= []
- @color_flag ||= false
- @default_table_columns ||= 4
- @table_columns ||= 0
- @max_table_columns ||= []
- @tr_id ||= 0
- @max_td_page ||= []
- @max_td_y ||= []
- @t_columns ||= 0
- @default_font ||= "FreeSans" if unicode
- @default_font ||= "Helvetica"
- @draw_color ||= '0 G'
- @encoding ||= "UTF-8"
- @fill_color ||= '0 g'
- @fonts ||= {}
- @font_family ||= ''
- @font_files ||= {}
- @font_style ||= ''
- @font_size ||= 12
- @font_size_pt ||= 12
- @header_width ||= 0
- @header_logo ||= ""
- @header_logo_width ||= 30
- @header_title ||= ""
- @header_string ||= ""
- @images ||= {}
- @img_scale ||= 1
- @in_footer ||= false
- @is_unicode = unicode
- @lasth ||= 0
- @links ||= []
- @list_ordered ||= []
- @list_count ||= []
- @li_spacer ||= ""
- @li_count ||= 0
- @spacer ||= ""
- @quote_count ||= 0
- @prevquote_count ||= 0
- @quote_top ||= []
- @quote_page ||= []
- @n ||= 2
- @offsets ||= []
- @orientation_changes ||= []
- @page ||= 0
- @page_links ||= {}
- @pages ||= []
- @pdf_version ||= "1.3"
- @prevfill_color ||= [255,255,255]
- @prevtext_color ||= [0,0,0]
- @print_header ||= false
- @print_footer ||= false
- @state ||= 0
- @tableborder ||= 0
- @tdbegin ||= false
- @tdtext ||= ''
- @tdwidth ||= 0
- @tdheight ||= 0
- @tdalign ||= "L"
- @tdfill ||= 0
- @tempfontsize ||= 10
- @text_color ||= '0 g'
- @underline ||= false
- @deleted ||= false
- @ws ||= 0
-
- #Standard Unicode fonts
- @core_fonts = {
- 'courier'=>'Courier',
- 'courierB'=>'Courier-Bold',
- 'courierI'=>'Courier-Oblique',
- 'courierBI'=>'Courier-BoldOblique',
- 'helvetica'=>'Helvetica',
- 'helveticaB'=>'Helvetica-Bold',
- 'helveticaI'=>'Helvetica-Oblique',
- 'helveticaBI'=>'Helvetica-BoldOblique',
- 'times'=>'Times-Roman',
- 'timesB'=>'Times-Bold',
- 'timesI'=>'Times-Italic',
- 'timesBI'=>'Times-BoldItalic',
- 'symbol'=>'Symbol',
- 'zapfdingbats'=>'ZapfDingbats'}
- #Scale factor
- case unit.downcase
- when 'pt' ; @k=1
- when 'mm' ; @k=72/25.4
- when 'cm' ; @k=72/2.54
- when 'in' ; @k=72
- else Error("Incorrect unit: #{unit}")
- end
- #Page format
- if format.is_a?(String)
- # Page formats (45 standard ISO paper formats and 4 american common formats).
- # Paper cordinates are calculated in this way: (inches# 72) where (1 inch = 2.54 cm)
- case (format.upcase)
- when '4A0' ; format = [4767.87,6740.79]
- when '2A0' ; format = [3370.39,4767.87]
- when 'A0' ; format = [2383.94,3370.39]
- when 'A1' ; format = [1683.78,2383.94]
- when 'A2' ; format = [1190.55,1683.78]
- when 'A3' ; format = [841.89,1190.55]
- when 'A4' ; format = [595.28,841.89] # ; default
- when 'A5' ; format = [419.53,595.28]
- when 'A6' ; format = [297.64,419.53]
- when 'A7' ; format = [209.76,297.64]
- when 'A8' ; format = [147.40,209.76]
- when 'A9' ; format = [104.88,147.40]
- when 'A10' ; format = [73.70,104.88]
- when 'B0' ; format = [2834.65,4008.19]
- when 'B1' ; format = [2004.09,2834.65]
- when 'B2' ; format = [1417.32,2004.09]
- when 'B3' ; format = [1000.63,1417.32]
- when 'B4' ; format = [708.66,1000.63]
- when 'B5' ; format = [498.90,708.66]
- when 'B6' ; format = [354.33,498.90]
- when 'B7' ; format = [249.45,354.33]
- when 'B8' ; format = [175.75,249.45]
- when 'B9' ; format = [124.72,175.75]
- when 'B10' ; format = [87.87,124.72]
- when 'C0' ; format = [2599.37,3676.54]
- when 'C1' ; format = [1836.85,2599.37]
- when 'C2' ; format = [1298.27,1836.85]
- when 'C3' ; format = [918.43,1298.27]
- when 'C4' ; format = [649.13,918.43]
- when 'C5' ; format = [459.21,649.13]
- when 'C6' ; format = [323.15,459.21]
- when 'C7' ; format = [229.61,323.15]
- when 'C8' ; format = [161.57,229.61]
- when 'C9' ; format = [113.39,161.57]
- when 'C10' ; format = [79.37,113.39]
- when 'RA0' ; format = [2437.80,3458.27]
- when 'RA1' ; format = [1729.13,2437.80]
- when 'RA2' ; format = [1218.90,1729.13]
- when 'RA3' ; format = [864.57,1218.90]
- when 'RA4' ; format = [609.45,864.57]
- when 'SRA0' ; format = [2551.18,3628.35]
- when 'SRA1' ; format = [1814.17,2551.18]
- when 'SRA2' ; format = [1275.59,1814.17]
- when 'SRA3' ; format = [907.09,1275.59]
- when 'SRA4' ; format = [637.80,907.09]
- when 'LETTER' ; format = [612.00,792.00]
- when 'LEGAL' ; format = [612.00,1008.00]
- when 'EXECUTIVE' ; format = [521.86,756.00]
- when 'FOLIO' ; format = [612.00,936.00]
- #else then Error("Unknown page format: #{format}"
- end
- @fw_pt = format[0]
- @fh_pt = format[1]
- else
- @fw_pt = format[0]*@k
- @fh_pt = format[1]*@k
- end
- @fw = @fw_pt/@k
- @fh = @fh_pt/@k
- #Page orientation
- orientation = orientation.downcase
- if orientation == 'p' or orientation == 'portrait'
- @def_orientation = 'P'
- @w_pt = @fw_pt
- @h_pt = @fh_pt
- elsif orientation == 'l' or orientation == 'landscape'
- @def_orientation = 'L'
- @w_pt = @fh_pt
- @h_pt = @fw_pt
- else
- Error("Incorrect orientation: #{orientation}")
- end
- @fw = @w_pt/@k
- @fh = @h_pt/@k
-
- @cur_orientation = @def_orientation
- @w = @w_pt/@k
- @h = @h_pt/@k
- #Page margins (1 cm)
- margin = 28.35/@k
- SetMargins(margin, margin)
- #Interior cell margin (1 mm)
- @c_margin = margin / 10
- #Line width (0.2 mm)
- @line_width = 0.567 / @k
- #Automatic page break
- SetAutoPageBreak(true, 2 * margin)
- #Full width display mode
- SetDisplayMode('fullwidth')
- #Compression
- SetCompression(true)
- #Set default PDF version number
- @pdf_version = "1.3"
-
- @encoding = encoding
- @b = 0
- @i = 0
- @u = 0
- @href = ''
- @fontlist = ["arial", "times", "courier", "helvetica", "symbol"]
- @issetfont = false
- @issetcolor = false
-
- SetFillColor(200, 200, 200, true)
- SetTextColor(0, 0, 0, true)
- end
-
- #
- # Set the image scale.
- # @param float :scale image scale.
- # @author Nicola Asuni
- # @since 1.5.2
- #
- def SetImageScale(scale)
- @img_scale = scale;
- end
- alias_method :set_image_scale, :SetImageScale
-
- #
- # Returns the image scale.
- # @return float image scale.
- # @author Nicola Asuni
- # @since 1.5.2
- #
- def GetImageScale()
- return @img_scale;
- end
- alias_method :get_image_scale, :GetImageScale
-
- #
- # Returns the page width in units.
- # @return int page width.
- # @author Nicola Asuni
- # @since 1.5.2
- #
- def GetPageWidth()
- return @w;
- end
- alias_method :get_page_width, :GetPageWidth
-
- #
- # Returns the page height in units.
- # @return int page height.
- # @author Nicola Asuni
- # @since 1.5.2
- #
- def GetPageHeight()
- return @h;
- end
- alias_method :get_page_height, :GetPageHeight
-
- #
- # Returns the page break margin.
- # @return int page break margin.
- # @author Nicola Asuni
- # @since 1.5.2
- #
- def GetBreakMargin()
- return @b_margin;
- end
- alias_method :get_break_margin, :GetBreakMargin
- #
- # Returns the scale factor (number of points in user unit).
- # @return int scale factor.
- # @author Nicola Asuni
- # @since 1.5.2
- #
- def GetScaleFactor()
- return @k;
- end
- alias_method :get_scale_factor, :GetScaleFactor
- #
- # Defines the left, top and right margins. By default, they equal 1 cm. Call this method to change them.
- # @param float :left Left margin.
- # @param float :top Top margin.
- # @param float :right Right margin. Default value is the left one.
- # @since 1.0
- # @see SetLeftMargin(), SetTopMargin(), SetRightMargin(), SetAutoPageBreak()
- #
- def SetMargins(left, top, right=-1)
- #Set left, top and right margins
- @l_margin = left
- @t_margin = top
- if (right == -1)
- right = left
- end
- @r_margin = right
- end
- alias_method :set_margins, :SetMargins
- #
- # Defines the left margin. The method can be called before creating the first page. If the current abscissa gets out of page, it is brought back to the margin.
- # @param float :margin The margin.
- # @since 1.4
- # @see SetTopMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
- #
- def SetLeftMargin(margin)
- #Set left margin
- @l_margin = margin
- if ((@page>0) and (@x < margin))
- @x = margin
- end
- end
- alias_method :set_left_margin, :SetLeftMargin
- #
- # Defines the top margin. The method can be called before creating the first page.
- # @param float :margin The margin.
- # @since 1.5
- # @see SetLeftMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
- #
- def SetTopMargin(margin)
- #Set top margin
- @t_margin = margin
- end
- alias_method :set_top_margin, :SetTopMargin
- #
- # Defines the right margin. The method can be called before creating the first page.
- # @param float :margin The margin.
- # @since 1.5
- # @see SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
- #
- def SetRightMargin(margin)
- #Set right margin
- @r_margin = margin
- end
- alias_method :set_right_margin, :SetRightMargin
- #
- # Enables or disables the automatic page breaking mode. When enabling, the second parameter is the distance from the bottom of the page that defines the triggering limit. By default, the mode is on and the margin is 2 cm.
- # @param boolean :auto Boolean indicating if mode should be on or off.
- # @param float :margin Distance from the bottom of the page.
- # @since 1.0
- # @see Cell(), MultiCell(), AcceptPageBreak()
- #
- def SetAutoPageBreak(auto, margin=0)
- #Set auto page break mode and triggering margin
- @auto_page_break = auto
- @b_margin = margin
- @page_break_trigger = @h - margin
- end
- alias_method :set_auto_page_break, :SetAutoPageBreak
- #
- # Defines the way the document is to be displayed by the viewer. The zoom level can be set: pages can be displayed entirely on screen, occupy the full width of the window, use real size, be scaled by a specific zooming factor or use viewer default (configured in the Preferences menu of Acrobat). The page layout can be specified too: single at once, continuous display, two columns or viewer default. By default, documents use the full width mode with continuous display.
- # @param mixed :zoom The zoom to use. It can be one of the following string values or a number indicating the zooming factor to use. <ul><li>fullpage: displays the entire page on screen </li><li>fullwidth: uses maximum width of window</li><li>real: uses real size (equivalent to 100% zoom)</li><li>default: uses viewer default mode</li></ul>
- # @param string :layout The page layout. Possible values are:<ul><li>single: displays one page at once</li><li>continuous: displays pages continuously (default)</li><li>two: displays two pages on two columns</li><li>default: uses viewer default mode</li></ul>
- # @since 1.2
- #
- def SetDisplayMode(zoom, layout = 'continuous')
- #Set display mode in viewer
- if (zoom == 'fullpage' or zoom == 'fullwidth' or zoom == 'real' or zoom == 'default' or !zoom.is_a?(String))
- @zoom_mode = zoom
- else
- Error("Incorrect zoom display mode: #{zoom}")
- end
- if (layout == 'single' or layout == 'continuous' or layout == 'two' or layout == 'default')
- @layout_mode = layout
- else
- Error("Incorrect layout display mode: #{layout}")
- end
- end
- alias_method :set_display_mode, :SetDisplayMode
- #
- # Activates or deactivates page compression. When activated, the internal representation of each page is compressed, which leads to a compression ratio of about 2 for the resulting document. Compression is on by default.
- # Note: the Zlib extension is required for this feature. If not present, compression will be turned off.
- # @param boolean :compress Boolean indicating if compression must be enabled.
- # @since 1.4
- #
- def SetCompression(compress)
- #Set page compression
- if (respond_to?('gzcompress'))
- @compress = compress
- else
- @compress = false
- end
- end
- alias_method :set_compression, :SetCompression
- #
- # Defines the title of the document.
- # @param string :title The title.
- # @since 1.2
- # @see SetAuthor(), SetCreator(), SetKeywords(), SetSubject()
- #
- def SetTitle(title)
- #Title of document
- @title = title
- end
- alias_method :set_title, :SetTitle
- #
- # Defines the subject of the document.
- # @param string :subject The subject.
- # @since 1.2
- # @see SetAuthor(), SetCreator(), SetKeywords(), SetTitle()
- #
- def SetSubject(subject)
- #Subject of document
- @subject = subject
- end
- alias_method :set_subject, :SetSubject
- #
- # Defines the author of the document.
- # @param string :author The name of the author.
- # @since 1.2
- # @see SetCreator(), SetKeywords(), SetSubject(), SetTitle()
- #
- def SetAuthor(author)
- #Author of document
- @author = author
- end
- alias_method :set_author, :SetAuthor
- #
- # Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'.
- # @param string :keywords The list of keywords.
- # @since 1.2
- # @see SetAuthor(), SetCreator(), SetSubject(), SetTitle()
- #
- def SetKeywords(keywords)
- #Keywords of document
- @keywords = keywords
- end
- alias_method :set_keywords, :SetKeywords
- #
- # Defines the creator of the document. This is typically the name of the application that generates the PDF.
- # @param string :creator The name of the creator.
- # @since 1.2
- # @see SetAuthor(), SetKeywords(), SetSubject(), SetTitle()
- #
- def SetCreator(creator)
- #Creator of document
- @creator = creator
- end
- alias_method :set_creator, :SetCreator
- #
- # Defines an alias for the total number of pages. It will be substituted as the document is closed.<br />
- # <b>Example:</b><br />
- # <pre>
- # class PDF extends TCPDF {
- # def Footer()
- # #Go to 1.5 cm from bottom
- # SetY(-15);
- # #Select Arial italic 8
- # SetFont('Arial','I',8);
- # #Print current and total page numbers
- # Cell(0,10,'Page '.PageNo().'/{nb}',0,0,'C');
- # end
- # }
- # :pdf=new PDF();
- # :pdf->alias_nb_pages();
- # </pre>
- # @param string :alias The alias. Default valuenb}.
- # @since 1.4
- # @see PageNo(), Footer()
- #
- def AliasNbPages(alias_nb ='{nb}')
- #Define an alias for total number of pages
- @alias_nb_pages = escapetext(alias_nb)
- end
- alias_method :alias_nb_pages, :AliasNbPages
- #
- # This method is automatically called in case of fatal error; it simply outputs the message and halts the execution. An inherited class may override it to customize the error handling but should always halt the script, or the resulting document would probably be invalid.
- # 2004-06-11 :: Nicola Asuni : changed bold tag with strong
- # @param string :msg The error message
- # @since 1.0
- #
- def Error(msg)
- #Fatal error
- raise ("TCPDF error: #{msg}")
- end
- alias_method :error, :Error
- #
- # This method begins the generation of the PDF document. It is not necessary to call it explicitly because AddPage() does it automatically.
- # Note: no page is created by this method
- # @since 1.0
- # @see AddPage(), Close()
- #
- def Open()
- #Begin document
- @state = 1
- end
- # alias_method :open, :Open
- #
- # Terminates the PDF document. It is not necessary to call this method explicitly because Output() does it automatically. If the document contains no page, AddPage() is called to prevent from getting an invalid document.
- # @since 1.0
- # @see Open(), Output()
- #
- def Close()
- #Terminate document
- if (@state==3)
- return;
- end
- if (@page==0)
- AddPage();
- end
- #Page footer
- @in_footer=true;
- Footer();
- @in_footer=false;
- #Close page
- endpage();
- #Close document
- enddoc();
- end
- # alias_method :close, :Close
- #
- # Adds a new page to the document. If a page is already present, the Footer() method is called first to output the footer. Then the page is added, the current position set to the top-left corner according to the left and top margins, and Header() is called to display the header.
- # The font which was set before calling is automatically restored. There is no need to call SetFont() again if you want to continue with the same font. The same is true for colors and line width.
- # The origin of the coordinate system is at the top-left corner and increasing ordinates go downwards.
- # @param string :orientation Page orientation. Possible values are (case insensitive):<ul><li>P or Portrait</li><li>L or Landscape</li></ul> The default value is the one passed to the constructor.
- # @since 1.0
- # @see TCPDF(), Header(), Footer(), SetMargins()
- #
- def AddPage(orientation='')
- #Start a new page
- if (@state==0)
- Open();
- end
- family=@font_family;
- style=@font_style + (@underline ? 'U' : '') + (@deleted ? 'D' : '');
- size=@font_size_pt;
- lw=@line_width;
- dc=@draw_color;
- fc=@fill_color;
- tc=@text_color;
- cf=@color_flag;
- if (@page>0)
- #Page footer
- @in_footer=true;
- Footer();
- @in_footer=false;
- #Close page
- endpage();
- end
- #Start new page
- beginpage(orientation);
- #Set line cap style to square
- out('2 J');
- #Set line width
- @line_width = lw;
- out(sprintf('%.2f w', lw*@k));
- #Set font
- if (family)
- SetFont(family, style, size);
- end
- #Set colors
- @draw_color = dc;
- if (dc!='0 G')
- out(dc);
- end
- @fill_color = fc;
- if (fc!='0 g')
- out(fc);
- end
- @text_color = tc;
- @color_flag = cf;
- #Page header
- Header();
- #Restore line width
- if (@line_width != lw)
- @line_width = lw;
- out(sprintf('%.2f w', lw*@k));
- end
- #Restore font
- if (family)
- SetFont(family, style, size);
- end
- #Restore colors
- if (@draw_color != dc)
- @draw_color = dc;
- out(dc);
- end
- if (@fill_color != fc)
- @fill_color = fc;
- out(fc);
- end
- @text_color = tc;
- @color_flag = cf;
- end
- alias_method :add_page, :AddPage
-
- #
- # Rotate object.
- # @param float :angle angle in degrees for counter-clockwise rotation
- # @param int :x abscissa of the rotation center. Default is current x position
- # @param int :y ordinate of the rotation center. Default is current y position
- #
- def Rotate(angle, x="", y="")
- if (x == '')
- x = @x;
- end
-
- if (y == '')
- y = @y;
- end
-
- if (@rtl)
- x = @w - x;
- angle = -@angle;
- end
-
- y = (@h - y) * @k;
- x *= @k;
- # calculate elements of transformation matrix
- tm = []
- tm[0] = ::Math::cos(deg2rad(angle));
- tm[1] = ::Math::sin(deg2rad(angle));
- tm[2] = -tm[1];
- tm[3] = tm[0];
- tm[4] = x + tm[1] * y - tm[0] * x;
- tm[5] = y - tm[0] * y - tm[1] * x;
- # generate the transformation matrix
- Transform(tm);
- end
- alias_method :rotate, :Rotate
-
- #
- # Starts a 2D tranformation saving current graphic state.
- # This function must be called before scaling, mirroring, translation, rotation and skewing.
- # Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
- #
- def StartTransform
- out('q');
- end
- alias_method :start_transform, :StartTransform
-
- #
- # Stops a 2D tranformation restoring previous graphic state.
- # This function must be called after scaling, mirroring, translation, rotation and skewing.
- # Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
- #
- def StopTransform
- out('Q');
- end
- alias_method :stop_transform, :StopTransform
-
- #
- # Apply graphic transformations.
- # @since 2.1.000 (2008-01-07)
- # @see StartTransform(), StopTransform()
- #
- def Transform(tm)
- x = out(sprintf('%.3f %.3f %.3f %.3f %.3f %.3f cm', tm[0], tm[1], tm[2], tm[3], tm[4], tm[5]));
- end
- alias_method :transform, :Transform
-
- #
- # Set header data.
- # @param string :ln header image logo
- # @param string :lw header image logo width in mm
- # @param string :ht string to print as title on document header
- # @param string :hs string to print on document header
- #
- def SetHeaderData(ln="", lw=0, ht="", hs="")
- @header_logo = ln || ""
- @header_logo_width = lw || 0
- @header_title = ht || ""
- @header_string = hs || ""
- end
- alias_method :set_header_data, :SetHeaderData
-
- #
- # Set header margin.
- # (minimum distance between header and top page margin)
- # @param int :hm distance in millimeters
- #
- def SetHeaderMargin(hm=10)
- @header_margin = hm;
- end
- alias_method :set_header_margin, :SetHeaderMargin
-
- #
- # Set footer margin.
- # (minimum distance between footer and bottom page margin)
- # @param int :fm distance in millimeters
- #
- def SetFooterMargin(fm=10)
- @footer_margin = fm;
- end
- alias_method :set_footer_margin, :SetFooterMargin
-
- #
- # Set a flag to print page header.
- # @param boolean :val set to true to print the page header (default), false otherwise.
- #
- def SetPrintHeader(val=true)
- @print_header = val;
- end
- alias_method :set_print_header, :SetPrintHeader
-
- #
- # Set a flag to print page footer.
- # @param boolean :value set to true to print the page footer (default), false otherwise.
- #
- def SetPrintFooter(val=true)
- @print_footer = val;
- end
- alias_method :set_print_footer, :SetPrintFooter
-
- #
- # This method is used to render the page header.
- # It is automatically called by AddPage() and could be overwritten in your own inherited class.
- #
- def Header()
- if (@print_header)
- if (@original_l_margin.nil?)
- @original_l_margin = @l_margin;
- end
- if (@original_r_margin.nil?)
- @original_r_margin = @r_margin;
- end
-
- #set current position
- SetXY(@original_l_margin, @header_margin);
-
- if ((@header_logo) and (@header_logo != @@k_blank_image))
- Image(@header_logo, @original_l_margin, @header_margin, @header_logo_width);
- else
- @img_rb_y = GetY();
- end
-
- cell_height = ((@@k_cell_height_ratio * @header_font[2]) / @k).round(2)
-
- header_x = @original_l_margin + (@header_logo_width * 1.05); #set left margin for text data cell
-
- # header title
- SetFont(@header_font[0], 'B', @header_font[2] + 1);
- SetX(header_x);
- Cell(@header_width, cell_height, @header_title, 0, 1, 'L');
-
- # header string
- SetFont(@header_font[0], @header_font[1], @header_font[2]);
- SetX(header_x);
- MultiCell(@header_width, cell_height, @header_string, 0, 'L', 0);
-
- # print an ending header line
- if (@header_width)
- #set style for cell border
- SetLineWidth(0.3);
- SetDrawColor(0, 0, 0);
- SetY(1 + (@img_rb_y > GetY() ? @img_rb_y : GetY()));
- SetX(@original_l_margin);
- Cell(0, 0, '', 'T', 0, 'C');
- end
-
- #restore position
- SetXY(@original_l_margin, @t_margin);
- end
- end
- alias_method :header, :Header
-
- #
- # This method is used to render the page footer.
- # It is automatically called by AddPage() and could be overwritten in your own inherited class.
- #
- def Footer()
- if (@print_footer)
-
- if (@original_l_margin.nil?)
- @original_l_margin = @l_margin;
- end
- if (@original_r_margin.nil?)
- @original_r_margin = @r_margin;
- end
-
- #set font
- SetFont(@footer_font[0], @footer_font[1] , @footer_font[2]);
- #set style for cell border
- line_width = 0.3;
- SetLineWidth(line_width);
- SetDrawColor(0, 0, 0);
-
- footer_height = ((@@k_cell_height_ratio * @footer_font[2]) / @k).round; #footer height, was , 2)
- #get footer y position
- footer_y = @h - @footer_margin - footer_height;
- #set current position
- SetXY(@original_l_margin, footer_y);
-
- #print document barcode
- if (@barcode)
- Ln();
- barcode_width = ((@w - @original_l_margin - @original_r_margin)).round; #max width
- writeBarcode(@original_l_margin, footer_y + line_width, barcode_width, footer_height - line_width, "C128B", false, false, 2, @barcode);
- end
-
- SetXY(@original_l_margin, footer_y);
-
- #Print page number
- Cell(0, footer_height, @l['w_page'] + " " + PageNo().to_s + ' / {nb}', 'T', 0, 'R');
- end
- end
- alias_method :footer, :Footer
-
- #
- # Returns the current page number.
- # @return int page number
- # @since 1.0
- # @see alias_nb_pages()
- #
- def PageNo()
- #Get current page number
- return @page;
- end
- alias_method :page_no, :PageNo
- #
- # Defines the color used for all drawing operations (lines, rectangles and cell borders). It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page.
- # @param int :r If g et b are given, red component; if not, indicates the gray level. Value between 0 and 255
- # @param int :g Green component (between 0 and 255)
- # @param int :b Blue component (between 0 and 255)
- # @since 1.3
- # @see SetFillColor(), SetTextColor(), Line(), Rect(), Cell(), MultiCell()
- #
- def SetDrawColor(r, g=-1, b=-1)
- #Set color for all stroking operations
- if ((r==0 and g==0 and b==0) or g==-1)
- @draw_color=sprintf('%.3f G', r/255.0);
- else
- @draw_color=sprintf('%.3f %.3f %.3f RG', r/255.0, g/255.0, b/255.0);
- end
- if (@page>0)
- out(@draw_color);
- end
- end
- alias_method :set_draw_color, :SetDrawColor
- #
- # Defines the color used for all filling operations (filled rectangles and cell backgrounds). It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page.
- # @param int :r If g et b are given, red component; if not, indicates the gray level. Value between 0 and 255
- # @param int :g Green component (between 0 and 255)
- # @param int :b Blue component (between 0 and 255)
- # @param boolean :storeprev if true stores the RGB array on :prevfill_color variable.
- # @since 1.3
- # @see SetDrawColor(), SetTextColor(), Rect(), Cell(), MultiCell()
- #
- def SetFillColor(r, g=-1, b=-1, storeprev=false)
- #Set color for all filling operations
- if ((r==0 and g==0 and b==0) or g==-1)
- @fill_color=sprintf('%.3f g', r/255.0);
- else
- @fill_color=sprintf('%.3f %.3f %.3f rg', r/255.0, g/255.0, b/255.0);
- end
- @color_flag=(@fill_color!=@text_color);
- if (@page>0)
- out(@fill_color);
- end
- if (storeprev)
- # store color as previous value
- @prevfill_color = [r, g, b]
- end
- end
- alias_method :set_fill_color, :SetFillColor
- # This hasn't been ported from tcpdf, it's a variation on SetTextColor for setting cmyk colors
- def SetCmykFillColor(c, m, y, k, storeprev=false)
- #Set color for all filling operations
- @fill_color=sprintf('%.3f %.3f %.3f %.3f k', c, m, y, k);
- @color_flag=(@fill_color!=@text_color);
- if (storeprev)
- # store color as previous value
- @prevtext_color = [c, m, y, k]
- end
- if (@page>0)
- out(@fill_color);
- end
- end
- alias_method :set_cmyk_fill_color, :SetCmykFillColor
- #
- # Defines the color used for text. It can be expressed in RGB components or gray scale. The method can be called before the first page is created and the value is retained from page to page.
- # @param int :r If g et b are given, red component; if not, indicates the gray level. Value between 0 and 255
- # @param int :g Green component (between 0 and 255)
- # @param int :b Blue component (between 0 and 255)
- # @param boolean :storeprev if true stores the RGB array on :prevtext_color variable.
- # @since 1.3
- # @see SetDrawColor(), SetFillColor(), Text(), Cell(), MultiCell()
- #
- def SetTextColor(r, g=-1, b=-1, storeprev=false)
- #Set color for text
- if ((r==0 and :g==0 and :b==0) or :g==-1)
- @text_color=sprintf('%.3f g', r/255.0);
- else
- @text_color=sprintf('%.3f %.3f %.3f rg', r/255.0, g/255.0, b/255.0);
- end
- @color_flag=(@fill_color!=@text_color);
- if (storeprev)
- # store color as previous value
- @prevtext_color = [r, g, b]
- end
- end
- alias_method :set_text_color, :SetTextColor
- # This hasn't been ported from tcpdf, it's a variation on SetTextColor for setting cmyk colors
- def SetCmykTextColor(c, m, y, k, storeprev=false)
- #Set color for text
- @text_color=sprintf('%.3f %.3f %.3f %.3f k', c, m, y, k);
- @color_flag=(@fill_color!=@text_color);
- if (storeprev)
- # store color as previous value
- @prevtext_color = [c, m, y, k]
- end
- end
- alias_method :set_cmyk_text_color, :SetCmykTextColor
-
- #
- # Returns the length of a string in user unit. A font must be selected.<br>
- # Support UTF-8 Unicode [Nicola Asuni, 2005-01-02]
- # @param string :s The string whose length is to be computed
- # @return int
- # @since 1.2
- #
- def GetStringWidth(s)
- #Get width of a string in the current font
- s = s.to_s;
- cw = @current_font['cw']
- w = 0;
- if (@is_unicode)
- unicode = UTF8StringToArray(s);
- unicode.each do |char|
- if (!cw[char].nil?)
- w += cw[char];
- # This should not happen. UTF8StringToArray should guarentee the array is ascii values.
- # elsif (c!cw[char[0]].nil?)
- # w += cw[char[0]];
- # elsif (!cw[char.chr].nil?)
- # w += cw[char.chr];
- elsif (!@current_font['desc']['MissingWidth'].nil?)
- w += @current_font['desc']['MissingWidth']; # set default size
- else
- w += 500;
- end
- end
- else
- s.each_byte do |c|
- if cw[c.chr]
- w += cw[c.chr];
- elsif cw[?c.chr]
- w += cw[?c.chr]
- end
- end
- end
- return (w * @font_size / 1000.0);
- end
- alias_method :get_string_width, :GetStringWidth
- #
- # Defines the line width. By default, the value equals 0.2 mm. The method can be called before the first page is created and the value is retained from page to page.
- # @param float :width The width.
- # @since 1.0
- # @see Line(), Rect(), Cell(), MultiCell()
- #
- def SetLineWidth(width)
- #Set line width
- @line_width = width;
- if (@page>0)
- out(sprintf('%.2f w', width*@k));
- end
- end
- alias_method :set_line_width, :SetLineWidth
- #
- # Draws a line between two points.
- # @param float :x1 Abscissa of first point
- # @param float :y1 Ordinate of first point
- # @param float :x2 Abscissa of second point
- # @param float :y2 Ordinate of second point
- # @since 1.0
- # @see SetLineWidth(), SetDrawColor()
- #
- def Line(x1, y1, x2, y2)
- #Draw a line
- out(sprintf('%.2f %.2f m %.2f %.2f l S', x1 * @k, (@h - y1) * @k, x2 * @k, (@h - y2) * @k));
- end
- alias_method :line, :Line
- def Circle(mid_x, mid_y, radius, style='')
- mid_y = (@h-mid_y)*@k
- out(sprintf("q\n")) # postscript content in pdf
- # init line type etc. with /GSD gs G g (grey) RG rg (RGB) w=line witdh etc.
- out(sprintf("1 j\n")) # line join
- # translate ("move") circle to mid_y, mid_y
- out(sprintf("1 0 0 1 %f %f cm", mid_x, mid_y))
- kappa = 0.5522847498307933984022516322796
- # Quadrant 1
- x_s = 0.0 # 12 o'clock
- y_s = 0.0 + radius
- x_e = 0.0 + radius # 3 o'clock
- y_e = 0.0
- out(sprintf("%f %f m\n", x_s, y_s)) # move to 12 o'clock
- # cubic bezier control point 1, start height and kappa * radius to the right
- bx_e1 = x_s + (radius * kappa)
- by_e1 = y_s
- # cubic bezier control point 2, end and kappa * radius above
- bx_e2 = x_e
- by_e2 = y_e + (radius * kappa)
- # draw cubic bezier from current point to x_e/y_e with bx_e1/by_e1 and bx_e2/by_e2 as bezier control points
- out(sprintf("%f %f %f %f %f %f c\n", bx_e1, by_e1, bx_e2, by_e2, x_e, y_e))
- # Quadrant 2
- x_s = x_e
- y_s = y_e # 3 o'clock
- x_e = 0.0
- y_e = 0.0 - radius # 6 o'clock
- bx_e1 = x_s # cubic bezier point 1
- by_e1 = y_s - (radius * kappa)
- bx_e2 = x_e + (radius * kappa) # cubic bezier point 2
- by_e2 = y_e
- out(sprintf("%f %f %f %f %f %f c\n", bx_e1, by_e1, bx_e2, by_e2, x_e, y_e))
- # Quadrant 3
- x_s = x_e
- y_s = y_e # 6 o'clock
- x_e = 0.0 - radius
- y_e = 0.0 # 9 o'clock
- bx_e1 = x_s - (radius * kappa) # cubic bezier point 1
- by_e1 = y_s
- bx_e2 = x_e # cubic bezier point 2
- by_e2 = y_e - (radius * kappa)
- out(sprintf("%f %f %f %f %f %f c\n", bx_e1, by_e1, bx_e2, by_e2, x_e, y_e))
- # Quadrant 4
- x_s = x_e
- y_s = y_e # 9 o'clock
- x_e = 0.0
- y_e = 0.0 + radius # 12 o'clock
- bx_e1 = x_s # cubic bezier point 1
- by_e1 = y_s + (radius * kappa)
- bx_e2 = x_e - (radius * kappa) # cubic bezier point 2
- by_e2 = y_e
- out(sprintf("%f %f %f %f %f %f c\n", bx_e1, by_e1, bx_e2, by_e2, x_e, y_e))
- if style=='F'
- op='f'
- elsif style=='FD' or style=='DF'
- op='b'
- else
- op='s'
- end
- out(sprintf("#{op}\n")) # stroke circle, do not fill and close path
- # for filling etc. b, b*, f, f*
- out(sprintf("Q\n")) # finish postscript in PDF
- end
- alias_method :circle, :Circle
- #
- # Outputs a rectangle. It can be drawn (border only), filled (with no border) or both.
- # @param float :x Abscissa of upper-left corner
- # @param float :y Ordinate of upper-left corner
- # @param float :w Width
- # @param float :h Height
- # @param string :style Style of rendering. Possible values are:<ul><li>D or empty string: draw (default)</li><li>F: fill</li><li>DF or FD: draw and fill</li></ul>
- # @since 1.0
- # @see SetLineWidth(), SetDrawColor(), SetFillColor()
- #
- def Rect(x, y, w, h, style='')
- #Draw a rectangle
- if (style=='F')
- op='f';
- elsif (style=='FD' or style=='DF')
- op='B';
- else
- op='S';
- end
- out(sprintf('%.2f %.2f %.2f %.2f re %s', x * @k, (@h - y) * @k, w * @k, -h * @k, op));
- end
- alias_method :rect, :Rect
- #
- # Imports a TrueType or Type1 font and makes it available. It is necessary to generate a font definition file first with the makefont.rb utility. The definition file (and the font file itself when embedding) must be present either in the current directory or in the one indicated by FPDF_FONTPATH if the constant is defined. If it could not be found, the error "Could not include font definition file" is generated.
- # Support UTF-8 Unicode [Nicola Asuni, 2005-01-02].
- # <b>Example</b>:<br />
- # <pre>
- # :pdf->AddFont('Comic','I');
- # # is equivalent to:
- # :pdf->AddFont('Comic','I','comici.rb');
- # </pre>
- # @param string :family Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.
- # @param string :style Font style. Possible values are (case insensitive):<ul><li>empty string: regular (default)</li><li>B: bold</li><li>I: italic</li><li>BI or IB: bold italic</li></ul>
- # @param string :file The font definition file. By default, the name is built from the family and style, in lower case with no space.
- # @since 1.5
- # @see SetFont()
- #
- def AddFont(family, style='', file='')
- if (family.empty?)
- return;
- end
- #Add a TrueType or Type1 font
- family = family.downcase
- if ((!@is_unicode) and (family == 'arial'))
- family = 'helvetica';
- end
- style=style.upcase
- style=style.gsub('U','');
- style=style.gsub('D','');
- if (style == 'IB')
- style = 'BI';
- end
- fontkey = family + style;
- # check if the font has been already added
- if !@fonts[fontkey].nil?
- return;
- end
- if (file=='')
- file = family.gsub(' ', '') + style.downcase + '.rb';
- end
- font_file_name = getfontpath(file)
- if (font_file_name.nil?)
- # try to load the basic file without styles
- file = family.gsub(' ', '') + '.rb';
- font_file_name = getfontpath(file)
- end
- if font_file_name.nil?
- Error("Could not find font #{file}.")
- end
- require(getfontpath(file))
- font_desc = TCPDFFontDescriptor.font(file)
- if (font_desc[:name].nil? and @@fpdf_charwidths.nil?)
- Error('Could not include font definition file');
- end
- i = @fonts.length+1;
- if (@is_unicode)
- @fonts[fontkey] = {'i' => i, 'type' => font_desc[:type], 'name' => font_desc[:name], 'desc' => font_desc[:desc], 'up' => font_desc[:up], 'ut' => font_desc[:ut], 'cw' => font_desc[:cw], 'enc' => font_desc[:enc], 'file' => font_desc[:file], 'ctg' => font_desc[:ctg], 'cMap' => font_desc[:cMap], 'registry' => font_desc[:registry]}
- @@fpdf_charwidths[fontkey] = font_desc[:cw];
- else
- @fonts[fontkey]={'i' => i, 'type'=>'core', 'name'=>@core_fonts[fontkey], 'up'=>-100, 'ut'=>50, 'cw' => font_desc[:cw]}
- @@fpdf_charwidths[fontkey] = font_desc[:cw];
- end
- if (!font_desc[:diff].nil? and (!font_desc[:diff].empty?))
- #Search existing encodings
- d=0;
- nb=@diffs.length;
- 1.upto(nb) do |i|
- if (@diffs[i]== font_desc[:diff])
- d = i;
- break;
- end
- end
- if (d==0)
- d = nb+1;
- @diffs[d] = font_desc[:diff];
- end
- @fonts[fontkey]['diff'] = d;
- end
- if (font_desc[:file] and font_desc[:file].length > 0)
- if (font_desc[:type] == "TrueType") or (font_desc[:type] == "TrueTypeUnicode")
- @font_files[font_desc[:file]] = {'length1' => font_desc[:originalsize]}
- else
- @font_files[font_desc[:file]] = {'length1' => font_desc[:size1], 'length2' => font_desc[:size2]}
- end
- end
- end
- alias_method :add_font, :AddFont
- #
- # Sets the font used to print character strings. It is mandatory to call this method at least once before printing text or the resulting document would not be valid.
- # 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:<ul><li>They are in the current directory (the one where the running script lies)</li><li>They are in one of the directories defined by the include_path parameter</li><li>They are in the directory defined by the FPDF_FONTPATH constant</li></ul><br />
- # Example for the last case (note the trailing slash):<br />
- # <pre>
- # define('FPDF_FONTPATH','/home/www/font/');
- # require('tcpdf.rb');
- #
- # #Times regular 12
- # :pdf->SetFont('Times');
- # #Arial bold 14
- # :pdf->SetFont('Arial','B',14);
- # #Removes bold
- # :pdf->SetFont('');
- # #Times bold, italic and underlined 14
- # :pdf->SetFont('Times','BIUD');
- # </pre><br />
- # If the file corresponding to the requested font is not found, the error "Could not include font metric file" is generated.
- # @param string :family Family font. It can be either a name defined by AddFont() or one of the standard families (case insensitive):<ul><li>Courier (fixed-width)</li><li>Helvetica or Arial (synonymous; sans serif)</li><li>Times (serif)</li><li>Symbol (symbolic)</li><li>ZapfDingbats (symbolic)</li></ul>It is also possible to pass an empty string. In that case, the current family is retained.
- # @param string :style Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li></ul>or any combination. The default value is regular. Bold and italic styles do not apply to Symbol and ZapfDingbats
- # @param float :size 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
- # @since 1.0
- # @see AddFont(), SetFontSize(), Cell(), MultiCell(), Write()
- #
- def SetFont(family, style='', size=0)
- # save previous values
- @prevfont_family = @font_family;
- @prevfont_style = @font_style;
- family=family.downcase;
- if (family=='')
- family=@font_family;
- end
- if ((!@is_unicode) and (family == 'arial'))
- family = 'helvetica';
- elsif ((family=="symbol") or (family=="zapfdingbats"))
- style='';
- end
-
- style=style.upcase;
- if (style.include?('U'))
- @underline=true;
- style= style.gsub('U','');
- else
- @underline=false;
- end
- if (style.include?('D'))
- @deleted=true;
- style= style.gsub('D','');
- else
- @deleted=false;
- end
- if (style=='IB')
- style='BI';
- end
- if (size==0)
- size=@font_size_pt;
- end
- # try to add font (if not already added)
- AddFont(family, style);
-
- #Test if font is already selected
- if ((@font_family == family) and (@font_style == style) and (@font_size_pt == size))
- return;
- end
-
- fontkey = family + style;
- style = '' if (@fonts[fontkey].nil? and !@fonts[family].nil?)
-
- #Test if used for the first time
- if (@fonts[fontkey].nil?)
- #Check if one of the standard fonts
- if (!@core_fonts[fontkey].nil?)
- if @@fpdf_charwidths[fontkey].nil?
- #Load metric file
- file = family;
- if ((family!='symbol') and (family!='zapfdingbats'))
- file += style.downcase;
- end
- if (getfontpath(file + '.rb').nil?)
- # try to load the basic file without styles
- file = family;
- fontkey = family;
- end
- require(getfontpath(file + '.rb'));
- font_desc = TCPDFFontDescriptor.font(file)
- if ((@is_unicode and ctg.nil?) or ((!@is_unicode) and (@@fpdf_charwidths[fontkey].nil?)) )
- Error("Could not include font metric file [" + fontkey + "]: " + getfontpath(file + ".rb"));
- end
- end
- i = @fonts.length + 1;
- if (@is_unicode)
- @fonts[fontkey] = {'i' => i, 'type' => font_desc[:type], 'name' => font_desc[:name], 'desc' => font_desc[:desc], 'up' => font_desc[:up], 'ut' => font_desc[:ut], 'cw' => font_desc[:cw], 'enc' => font_desc[:enc], 'file' => font_desc[:file], 'ctg' => font_desc[:ctg]}
- @@fpdf_charwidths[fontkey] = font_desc[:cw];
- else
- @fonts[fontkey] = {'i' => i, 'type'=>'core', 'name'=>@core_fonts[fontkey], 'up'=>-100, 'ut'=>50, 'cw' => font_desc[:cw]}
- @@fpdf_charwidths[fontkey] = font_desc[:cw];
- end
- else
- Error('Undefined font: ' + family + ' ' + style);
- end
- end
- #Select it
- @font_family = family;
- @font_style = style;
- @font_size_pt = size;
- @font_size = size / @k;
- @current_font = @fonts[fontkey]; # was & may need deep copy?
- if (@page>0)
- out(sprintf('BT /F%d %.2f Tf ET', @current_font['i'], @font_size_pt));
- end
- end
- alias_method :set_font, :SetFont
- #
- # Defines the size of the current font.
- # @param float :size The size (in points)
- # @since 1.0
- # @see SetFont()
- #
- def SetFontSize(size)
- #Set font size in points
- if (@font_size_pt== size)
- return;
- end
- @font_size_pt = size;
- @font_size = size.to_f / @k;
- if (@page > 0)
- out(sprintf('BT /F%d %.2f Tf ET', @current_font['i'], @font_size_pt));
- end
- end
- alias_method :set_font_size, :SetFontSize
- #
- # Creates a new internal link and returns its identifier. An internal link is a clickable area which directs to another place within the document.<br />
- # The identifier can then be passed to Cell(), Write(), Image() or Link(). The destination is defined with SetLink().
- # @since 1.5
- # @see Cell(), Write(), Image(), Link(), SetLink()
- #
- def AddLink()
- #Create a new internal link
- n=@links.length+1;
- @links[n]=[0,0];
- return n;
- end
- alias_method :add_link, :AddLink
- #
- # Defines the page and position a link points to
- # @param int :link The link identifier returned by AddLink()
- # @param float :y Ordinate of target position; -1 indicates the current position. The default value is 0 (top of page)
- # @param int :page Number of target page; -1 indicates the current page. This is the default value
- # @since 1.5
- # @see AddLink()
- #
- def SetLink(link, y=0, page=-1)
- #Set destination of internal link
- if (y==-1)
- y=@y;
- end
- if (page==-1)
- page=@page;
- end
- @links[link] = [page, y]
- end
- alias_method :set_link, :SetLink
- #
- # Puts a link on a rectangular area of the page. Text or image links are generally put via Cell(), Write() or Image(), but this method can be useful for instance to define a clickable area inside an image.
- # @param float :x Abscissa of the upper-left corner of the rectangle
- # @param float :y Ordinate of the upper-left corner of the rectangle
- # @param float :w Width of the rectangle
- # @param float :h Height of the rectangle
- # @param mixed :link URL or identifier returned by AddLink()
- # @since 1.5
- # @see AddLink(), Cell(), Write(), Image()
- #
- def Link(x, y, w, h, link)
- #Put a link on the page
- @page_links…
Large files files are truncated, but you can click here to view the full file