PageRenderTime 76ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 2ms

/lib/plugins/rfpdf/lib/tcpdf.rb

https://bitbucket.org/eimajenthat/redmine
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

  1. #============================================================+
  2. # File name : tcpdf.rb
  3. # Begin : 2002-08-03
  4. # Last Update : 2007-03-20
  5. # Author : Nicola Asuni
  6. # Version : 1.53.0.TC031
  7. # License : GNU LGPL (http://www.gnu.org/copyleft/lesser.html)
  8. #
  9. # Description : This is a Ruby class for generating PDF files
  10. # on-the-fly without requiring external
  11. # extensions.
  12. #
  13. # IMPORTANT:
  14. # This class is an extension and improvement of the Public Domain
  15. # FPDF class by Olivier Plathey (http://www.fpdf.org).
  16. #
  17. # Main changes by Nicola Asuni:
  18. # Ruby porting;
  19. # UTF-8 Unicode support;
  20. # code refactoring;
  21. # source code clean up;
  22. # code style and formatting;
  23. # source code documentation using phpDocumentor (www.phpdoc.org);
  24. # All ISO page formats were included;
  25. # image scale factor;
  26. # 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;
  27. # 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/);
  28. # defines standard Header() and Footer() methods.
  29. #
  30. # Ported to Ruby by Ed Moss 2007-08-06
  31. #
  32. #============================================================+
  33. require 'tempfile'
  34. require 'core/rmagick'
  35. #
  36. # TCPDF Class.
  37. # @package com.tecnick.tcpdf
  38. #
  39. @@version = "1.53.0.TC031"
  40. @@fpdf_charwidths = {}
  41. PDF_PRODUCER = 'TCPDF via RFPDF 1.53.0.TC031 (http://tcpdf.sourceforge.net)'
  42. module TCPDFFontDescriptor
  43. @@descriptors = { 'freesans' => {} }
  44. @@font_name = 'freesans'
  45. def self.font(font_name)
  46. @@descriptors[font_name.gsub(".rb", "")]
  47. end
  48. def self.define(font_name = 'freesans')
  49. @@descriptors[font_name] ||= {}
  50. yield @@descriptors[font_name]
  51. end
  52. end
  53. # This is a Ruby class for generating PDF files on-the-fly without requiring external extensions.<br>
  54. # This class is an extension and improvement of the FPDF class by Olivier Plathey (http://www.fpdf.org).<br>
  55. # 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>
  56. # TCPDF project (http://tcpdf.sourceforge.net) is based on the Public Domain FPDF class by Olivier Plathey (http://www.fpdf.org).<br>
  57. # To add your own TTF fonts please read /fonts/README.TXT
  58. # @name TCPDF
  59. # @package com.tecnick.tcpdf
  60. # @@version 1.53.0.TC031
  61. # @author Nicola Asuni
  62. # @link http://tcpdf.sourceforge.net
  63. # @license http://www.gnu.org/copyleft/lesser.html LGPL
  64. #
  65. class TCPDF
  66. include RFPDF
  67. include Core::RFPDF
  68. include RFPDF::Math
  69. def logger
  70. Rails.logger
  71. end
  72. cattr_accessor :k_cell_height_ratio
  73. @@k_cell_height_ratio = 1.25
  74. cattr_accessor :k_blank_image
  75. @@k_blank_image = ""
  76. cattr_accessor :k_small_ratio
  77. @@k_small_ratio = 2/3.0
  78. cattr_accessor :k_path_cache
  79. @@k_path_cache = Rails.root.join('tmp')
  80. cattr_accessor :k_path_url_cache
  81. @@k_path_url_cache = Rails.root.join('tmp')
  82. cattr_accessor :decoder
  83. attr_accessor :barcode
  84. attr_accessor :buffer
  85. attr_accessor :diffs
  86. attr_accessor :color_flag
  87. attr_accessor :default_table_columns
  88. attr_accessor :max_table_columns
  89. attr_accessor :default_font
  90. attr_accessor :draw_color
  91. attr_accessor :encoding
  92. attr_accessor :fill_color
  93. attr_accessor :fonts
  94. attr_accessor :font_family
  95. attr_accessor :font_files
  96. cattr_accessor :font_path
  97. attr_accessor :font_style
  98. attr_accessor :font_size_pt
  99. attr_accessor :header_width
  100. attr_accessor :header_logo
  101. attr_accessor :header_logo_width
  102. attr_accessor :header_title
  103. attr_accessor :header_string
  104. attr_accessor :images
  105. attr_accessor :img_scale
  106. attr_accessor :in_footer
  107. attr_accessor :is_unicode
  108. attr_accessor :lasth
  109. attr_accessor :links
  110. attr_accessor :list_ordered
  111. attr_accessor :list_count
  112. attr_accessor :li_spacer
  113. attr_accessor :n
  114. attr_accessor :offsets
  115. attr_accessor :orientation_changes
  116. attr_accessor :page
  117. attr_accessor :page_links
  118. attr_accessor :pages
  119. attr_accessor :pdf_version
  120. attr_accessor :prevfill_color
  121. attr_accessor :prevtext_color
  122. attr_accessor :print_header
  123. attr_accessor :print_footer
  124. attr_accessor :state
  125. attr_accessor :tableborder
  126. attr_accessor :tdbegin
  127. attr_accessor :tdwidth
  128. attr_accessor :tdheight
  129. attr_accessor :tdalign
  130. attr_accessor :tdfill
  131. attr_accessor :tempfontsize
  132. attr_accessor :text_color
  133. attr_accessor :underline
  134. attr_accessor :ws
  135. #
  136. # This is the class constructor.
  137. # It allows to set up the page format, the orientation and
  138. # the measure unit used in all the methods (except for the font sizes).
  139. # @since 1.0
  140. # @param string :orientation page orientation. Possible values are (case insensitive):<ul><li>P or Portrait (default)</li><li>L or Landscape</li></ul>
  141. # @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.
  142. # @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>
  143. # @param boolean :unicode TRUE means that the input text is unicode (default = true)
  144. # @param String :encoding charset encoding; default is UTF-8
  145. #
  146. def initialize(orientation = 'P', unit = 'mm', format = 'A4', unicode = true, encoding = "UTF-8")
  147. # Set internal character encoding to ASCII#
  148. #FIXME 2007-05-25 (EJM) Level=0 -
  149. # if (respond_to?("mb_internal_encoding") and mb_internal_encoding())
  150. # @internal_encoding = mb_internal_encoding();
  151. # mb_internal_encoding("ASCII");
  152. # }
  153. #Some checks
  154. dochecks();
  155. begin
  156. @@decoder = HTMLEntities.new
  157. rescue
  158. @@decoder = nil
  159. end
  160. #Initialization of properties
  161. @barcode ||= false
  162. @buffer ||= ''
  163. @diffs ||= []
  164. @color_flag ||= false
  165. @default_table_columns ||= 4
  166. @table_columns ||= 0
  167. @max_table_columns ||= []
  168. @tr_id ||= 0
  169. @max_td_page ||= []
  170. @max_td_y ||= []
  171. @t_columns ||= 0
  172. @default_font ||= "FreeSans" if unicode
  173. @default_font ||= "Helvetica"
  174. @draw_color ||= '0 G'
  175. @encoding ||= "UTF-8"
  176. @fill_color ||= '0 g'
  177. @fonts ||= {}
  178. @font_family ||= ''
  179. @font_files ||= {}
  180. @font_style ||= ''
  181. @font_size ||= 12
  182. @font_size_pt ||= 12
  183. @header_width ||= 0
  184. @header_logo ||= ""
  185. @header_logo_width ||= 30
  186. @header_title ||= ""
  187. @header_string ||= ""
  188. @images ||= {}
  189. @img_scale ||= 1
  190. @in_footer ||= false
  191. @is_unicode = unicode
  192. @lasth ||= 0
  193. @links ||= []
  194. @list_ordered ||= []
  195. @list_count ||= []
  196. @li_spacer ||= ""
  197. @li_count ||= 0
  198. @spacer ||= ""
  199. @quote_count ||= 0
  200. @prevquote_count ||= 0
  201. @quote_top ||= []
  202. @quote_page ||= []
  203. @n ||= 2
  204. @offsets ||= []
  205. @orientation_changes ||= []
  206. @page ||= 0
  207. @page_links ||= {}
  208. @pages ||= []
  209. @pdf_version ||= "1.3"
  210. @prevfill_color ||= [255,255,255]
  211. @prevtext_color ||= [0,0,0]
  212. @print_header ||= false
  213. @print_footer ||= false
  214. @state ||= 0
  215. @tableborder ||= 0
  216. @tdbegin ||= false
  217. @tdtext ||= ''
  218. @tdwidth ||= 0
  219. @tdheight ||= 0
  220. @tdalign ||= "L"
  221. @tdfill ||= 0
  222. @tempfontsize ||= 10
  223. @text_color ||= '0 g'
  224. @underline ||= false
  225. @deleted ||= false
  226. @ws ||= 0
  227. #Standard Unicode fonts
  228. @core_fonts = {
  229. 'courier'=>'Courier',
  230. 'courierB'=>'Courier-Bold',
  231. 'courierI'=>'Courier-Oblique',
  232. 'courierBI'=>'Courier-BoldOblique',
  233. 'helvetica'=>'Helvetica',
  234. 'helveticaB'=>'Helvetica-Bold',
  235. 'helveticaI'=>'Helvetica-Oblique',
  236. 'helveticaBI'=>'Helvetica-BoldOblique',
  237. 'times'=>'Times-Roman',
  238. 'timesB'=>'Times-Bold',
  239. 'timesI'=>'Times-Italic',
  240. 'timesBI'=>'Times-BoldItalic',
  241. 'symbol'=>'Symbol',
  242. 'zapfdingbats'=>'ZapfDingbats'}
  243. #Scale factor
  244. case unit.downcase
  245. when 'pt' ; @k=1
  246. when 'mm' ; @k=72/25.4
  247. when 'cm' ; @k=72/2.54
  248. when 'in' ; @k=72
  249. else Error("Incorrect unit: #{unit}")
  250. end
  251. #Page format
  252. if format.is_a?(String)
  253. # Page formats (45 standard ISO paper formats and 4 american common formats).
  254. # Paper cordinates are calculated in this way: (inches# 72) where (1 inch = 2.54 cm)
  255. case (format.upcase)
  256. when '4A0' ; format = [4767.87,6740.79]
  257. when '2A0' ; format = [3370.39,4767.87]
  258. when 'A0' ; format = [2383.94,3370.39]
  259. when 'A1' ; format = [1683.78,2383.94]
  260. when 'A2' ; format = [1190.55,1683.78]
  261. when 'A3' ; format = [841.89,1190.55]
  262. when 'A4' ; format = [595.28,841.89] # ; default
  263. when 'A5' ; format = [419.53,595.28]
  264. when 'A6' ; format = [297.64,419.53]
  265. when 'A7' ; format = [209.76,297.64]
  266. when 'A8' ; format = [147.40,209.76]
  267. when 'A9' ; format = [104.88,147.40]
  268. when 'A10' ; format = [73.70,104.88]
  269. when 'B0' ; format = [2834.65,4008.19]
  270. when 'B1' ; format = [2004.09,2834.65]
  271. when 'B2' ; format = [1417.32,2004.09]
  272. when 'B3' ; format = [1000.63,1417.32]
  273. when 'B4' ; format = [708.66,1000.63]
  274. when 'B5' ; format = [498.90,708.66]
  275. when 'B6' ; format = [354.33,498.90]
  276. when 'B7' ; format = [249.45,354.33]
  277. when 'B8' ; format = [175.75,249.45]
  278. when 'B9' ; format = [124.72,175.75]
  279. when 'B10' ; format = [87.87,124.72]
  280. when 'C0' ; format = [2599.37,3676.54]
  281. when 'C1' ; format = [1836.85,2599.37]
  282. when 'C2' ; format = [1298.27,1836.85]
  283. when 'C3' ; format = [918.43,1298.27]
  284. when 'C4' ; format = [649.13,918.43]
  285. when 'C5' ; format = [459.21,649.13]
  286. when 'C6' ; format = [323.15,459.21]
  287. when 'C7' ; format = [229.61,323.15]
  288. when 'C8' ; format = [161.57,229.61]
  289. when 'C9' ; format = [113.39,161.57]
  290. when 'C10' ; format = [79.37,113.39]
  291. when 'RA0' ; format = [2437.80,3458.27]
  292. when 'RA1' ; format = [1729.13,2437.80]
  293. when 'RA2' ; format = [1218.90,1729.13]
  294. when 'RA3' ; format = [864.57,1218.90]
  295. when 'RA4' ; format = [609.45,864.57]
  296. when 'SRA0' ; format = [2551.18,3628.35]
  297. when 'SRA1' ; format = [1814.17,2551.18]
  298. when 'SRA2' ; format = [1275.59,1814.17]
  299. when 'SRA3' ; format = [907.09,1275.59]
  300. when 'SRA4' ; format = [637.80,907.09]
  301. when 'LETTER' ; format = [612.00,792.00]
  302. when 'LEGAL' ; format = [612.00,1008.00]
  303. when 'EXECUTIVE' ; format = [521.86,756.00]
  304. when 'FOLIO' ; format = [612.00,936.00]
  305. #else then Error("Unknown page format: #{format}"
  306. end
  307. @fw_pt = format[0]
  308. @fh_pt = format[1]
  309. else
  310. @fw_pt = format[0]*@k
  311. @fh_pt = format[1]*@k
  312. end
  313. @fw = @fw_pt/@k
  314. @fh = @fh_pt/@k
  315. #Page orientation
  316. orientation = orientation.downcase
  317. if orientation == 'p' or orientation == 'portrait'
  318. @def_orientation = 'P'
  319. @w_pt = @fw_pt
  320. @h_pt = @fh_pt
  321. elsif orientation == 'l' or orientation == 'landscape'
  322. @def_orientation = 'L'
  323. @w_pt = @fh_pt
  324. @h_pt = @fw_pt
  325. else
  326. Error("Incorrect orientation: #{orientation}")
  327. end
  328. @fw = @w_pt/@k
  329. @fh = @h_pt/@k
  330. @cur_orientation = @def_orientation
  331. @w = @w_pt/@k
  332. @h = @h_pt/@k
  333. #Page margins (1 cm)
  334. margin = 28.35/@k
  335. SetMargins(margin, margin)
  336. #Interior cell margin (1 mm)
  337. @c_margin = margin / 10
  338. #Line width (0.2 mm)
  339. @line_width = 0.567 / @k
  340. #Automatic page break
  341. SetAutoPageBreak(true, 2 * margin)
  342. #Full width display mode
  343. SetDisplayMode('fullwidth')
  344. #Compression
  345. SetCompression(true)
  346. #Set default PDF version number
  347. @pdf_version = "1.3"
  348. @encoding = encoding
  349. @b = 0
  350. @i = 0
  351. @u = 0
  352. @href = ''
  353. @fontlist = ["arial", "times", "courier", "helvetica", "symbol"]
  354. @issetfont = false
  355. @issetcolor = false
  356. SetFillColor(200, 200, 200, true)
  357. SetTextColor(0, 0, 0, true)
  358. end
  359. #
  360. # Set the image scale.
  361. # @param float :scale image scale.
  362. # @author Nicola Asuni
  363. # @since 1.5.2
  364. #
  365. def SetImageScale(scale)
  366. @img_scale = scale;
  367. end
  368. alias_method :set_image_scale, :SetImageScale
  369. #
  370. # Returns the image scale.
  371. # @return float image scale.
  372. # @author Nicola Asuni
  373. # @since 1.5.2
  374. #
  375. def GetImageScale()
  376. return @img_scale;
  377. end
  378. alias_method :get_image_scale, :GetImageScale
  379. #
  380. # Returns the page width in units.
  381. # @return int page width.
  382. # @author Nicola Asuni
  383. # @since 1.5.2
  384. #
  385. def GetPageWidth()
  386. return @w;
  387. end
  388. alias_method :get_page_width, :GetPageWidth
  389. #
  390. # Returns the page height in units.
  391. # @return int page height.
  392. # @author Nicola Asuni
  393. # @since 1.5.2
  394. #
  395. def GetPageHeight()
  396. return @h;
  397. end
  398. alias_method :get_page_height, :GetPageHeight
  399. #
  400. # Returns the page break margin.
  401. # @return int page break margin.
  402. # @author Nicola Asuni
  403. # @since 1.5.2
  404. #
  405. def GetBreakMargin()
  406. return @b_margin;
  407. end
  408. alias_method :get_break_margin, :GetBreakMargin
  409. #
  410. # Returns the scale factor (number of points in user unit).
  411. # @return int scale factor.
  412. # @author Nicola Asuni
  413. # @since 1.5.2
  414. #
  415. def GetScaleFactor()
  416. return @k;
  417. end
  418. alias_method :get_scale_factor, :GetScaleFactor
  419. #
  420. # Defines the left, top and right margins. By default, they equal 1 cm. Call this method to change them.
  421. # @param float :left Left margin.
  422. # @param float :top Top margin.
  423. # @param float :right Right margin. Default value is the left one.
  424. # @since 1.0
  425. # @see SetLeftMargin(), SetTopMargin(), SetRightMargin(), SetAutoPageBreak()
  426. #
  427. def SetMargins(left, top, right=-1)
  428. #Set left, top and right margins
  429. @l_margin = left
  430. @t_margin = top
  431. if (right == -1)
  432. right = left
  433. end
  434. @r_margin = right
  435. end
  436. alias_method :set_margins, :SetMargins
  437. #
  438. # 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.
  439. # @param float :margin The margin.
  440. # @since 1.4
  441. # @see SetTopMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
  442. #
  443. def SetLeftMargin(margin)
  444. #Set left margin
  445. @l_margin = margin
  446. if ((@page>0) and (@x < margin))
  447. @x = margin
  448. end
  449. end
  450. alias_method :set_left_margin, :SetLeftMargin
  451. #
  452. # Defines the top margin. The method can be called before creating the first page.
  453. # @param float :margin The margin.
  454. # @since 1.5
  455. # @see SetLeftMargin(), SetRightMargin(), SetAutoPageBreak(), SetMargins()
  456. #
  457. def SetTopMargin(margin)
  458. #Set top margin
  459. @t_margin = margin
  460. end
  461. alias_method :set_top_margin, :SetTopMargin
  462. #
  463. # Defines the right margin. The method can be called before creating the first page.
  464. # @param float :margin The margin.
  465. # @since 1.5
  466. # @see SetLeftMargin(), SetTopMargin(), SetAutoPageBreak(), SetMargins()
  467. #
  468. def SetRightMargin(margin)
  469. #Set right margin
  470. @r_margin = margin
  471. end
  472. alias_method :set_right_margin, :SetRightMargin
  473. #
  474. # 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.
  475. # @param boolean :auto Boolean indicating if mode should be on or off.
  476. # @param float :margin Distance from the bottom of the page.
  477. # @since 1.0
  478. # @see Cell(), MultiCell(), AcceptPageBreak()
  479. #
  480. def SetAutoPageBreak(auto, margin=0)
  481. #Set auto page break mode and triggering margin
  482. @auto_page_break = auto
  483. @b_margin = margin
  484. @page_break_trigger = @h - margin
  485. end
  486. alias_method :set_auto_page_break, :SetAutoPageBreak
  487. #
  488. # 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.
  489. # @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>
  490. # @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>
  491. # @since 1.2
  492. #
  493. def SetDisplayMode(zoom, layout = 'continuous')
  494. #Set display mode in viewer
  495. if (zoom == 'fullpage' or zoom == 'fullwidth' or zoom == 'real' or zoom == 'default' or !zoom.is_a?(String))
  496. @zoom_mode = zoom
  497. else
  498. Error("Incorrect zoom display mode: #{zoom}")
  499. end
  500. if (layout == 'single' or layout == 'continuous' or layout == 'two' or layout == 'default')
  501. @layout_mode = layout
  502. else
  503. Error("Incorrect layout display mode: #{layout}")
  504. end
  505. end
  506. alias_method :set_display_mode, :SetDisplayMode
  507. #
  508. # 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.
  509. # Note: the Zlib extension is required for this feature. If not present, compression will be turned off.
  510. # @param boolean :compress Boolean indicating if compression must be enabled.
  511. # @since 1.4
  512. #
  513. def SetCompression(compress)
  514. #Set page compression
  515. if (respond_to?('gzcompress'))
  516. @compress = compress
  517. else
  518. @compress = false
  519. end
  520. end
  521. alias_method :set_compression, :SetCompression
  522. #
  523. # Defines the title of the document.
  524. # @param string :title The title.
  525. # @since 1.2
  526. # @see SetAuthor(), SetCreator(), SetKeywords(), SetSubject()
  527. #
  528. def SetTitle(title)
  529. #Title of document
  530. @title = title
  531. end
  532. alias_method :set_title, :SetTitle
  533. #
  534. # Defines the subject of the document.
  535. # @param string :subject The subject.
  536. # @since 1.2
  537. # @see SetAuthor(), SetCreator(), SetKeywords(), SetTitle()
  538. #
  539. def SetSubject(subject)
  540. #Subject of document
  541. @subject = subject
  542. end
  543. alias_method :set_subject, :SetSubject
  544. #
  545. # Defines the author of the document.
  546. # @param string :author The name of the author.
  547. # @since 1.2
  548. # @see SetCreator(), SetKeywords(), SetSubject(), SetTitle()
  549. #
  550. def SetAuthor(author)
  551. #Author of document
  552. @author = author
  553. end
  554. alias_method :set_author, :SetAuthor
  555. #
  556. # Associates keywords with the document, generally in the form 'keyword1 keyword2 ...'.
  557. # @param string :keywords The list of keywords.
  558. # @since 1.2
  559. # @see SetAuthor(), SetCreator(), SetSubject(), SetTitle()
  560. #
  561. def SetKeywords(keywords)
  562. #Keywords of document
  563. @keywords = keywords
  564. end
  565. alias_method :set_keywords, :SetKeywords
  566. #
  567. # Defines the creator of the document. This is typically the name of the application that generates the PDF.
  568. # @param string :creator The name of the creator.
  569. # @since 1.2
  570. # @see SetAuthor(), SetKeywords(), SetSubject(), SetTitle()
  571. #
  572. def SetCreator(creator)
  573. #Creator of document
  574. @creator = creator
  575. end
  576. alias_method :set_creator, :SetCreator
  577. #
  578. # Defines an alias for the total number of pages. It will be substituted as the document is closed.<br />
  579. # <b>Example:</b><br />
  580. # <pre>
  581. # class PDF extends TCPDF {
  582. # def Footer()
  583. # #Go to 1.5 cm from bottom
  584. # SetY(-15);
  585. # #Select Arial italic 8
  586. # SetFont('Arial','I',8);
  587. # #Print current and total page numbers
  588. # Cell(0,10,'Page '.PageNo().'/{nb}',0,0,'C');
  589. # end
  590. # }
  591. # :pdf=new PDF();
  592. # :pdf->alias_nb_pages();
  593. # </pre>
  594. # @param string :alias The alias. Default valuenb}.
  595. # @since 1.4
  596. # @see PageNo(), Footer()
  597. #
  598. def AliasNbPages(alias_nb ='{nb}')
  599. #Define an alias for total number of pages
  600. @alias_nb_pages = escapetext(alias_nb)
  601. end
  602. alias_method :alias_nb_pages, :AliasNbPages
  603. #
  604. # 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.
  605. # 2004-06-11 :: Nicola Asuni : changed bold tag with strong
  606. # @param string :msg The error message
  607. # @since 1.0
  608. #
  609. def Error(msg)
  610. #Fatal error
  611. raise ("TCPDF error: #{msg}")
  612. end
  613. alias_method :error, :Error
  614. #
  615. # This method begins the generation of the PDF document. It is not necessary to call it explicitly because AddPage() does it automatically.
  616. # Note: no page is created by this method
  617. # @since 1.0
  618. # @see AddPage(), Close()
  619. #
  620. def Open()
  621. #Begin document
  622. @state = 1
  623. end
  624. # alias_method :open, :Open
  625. #
  626. # 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.
  627. # @since 1.0
  628. # @see Open(), Output()
  629. #
  630. def Close()
  631. #Terminate document
  632. if (@state==3)
  633. return;
  634. end
  635. if (@page==0)
  636. AddPage();
  637. end
  638. #Page footer
  639. @in_footer=true;
  640. Footer();
  641. @in_footer=false;
  642. #Close page
  643. endpage();
  644. #Close document
  645. enddoc();
  646. end
  647. # alias_method :close, :Close
  648. #
  649. # 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.
  650. # 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.
  651. # The origin of the coordinate system is at the top-left corner and increasing ordinates go downwards.
  652. # @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.
  653. # @since 1.0
  654. # @see TCPDF(), Header(), Footer(), SetMargins()
  655. #
  656. def AddPage(orientation='')
  657. #Start a new page
  658. if (@state==0)
  659. Open();
  660. end
  661. family=@font_family;
  662. style=@font_style + (@underline ? 'U' : '') + (@deleted ? 'D' : '');
  663. size=@font_size_pt;
  664. lw=@line_width;
  665. dc=@draw_color;
  666. fc=@fill_color;
  667. tc=@text_color;
  668. cf=@color_flag;
  669. if (@page>0)
  670. #Page footer
  671. @in_footer=true;
  672. Footer();
  673. @in_footer=false;
  674. #Close page
  675. endpage();
  676. end
  677. #Start new page
  678. beginpage(orientation);
  679. #Set line cap style to square
  680. out('2 J');
  681. #Set line width
  682. @line_width = lw;
  683. out(sprintf('%.2f w', lw*@k));
  684. #Set font
  685. if (family)
  686. SetFont(family, style, size);
  687. end
  688. #Set colors
  689. @draw_color = dc;
  690. if (dc!='0 G')
  691. out(dc);
  692. end
  693. @fill_color = fc;
  694. if (fc!='0 g')
  695. out(fc);
  696. end
  697. @text_color = tc;
  698. @color_flag = cf;
  699. #Page header
  700. Header();
  701. #Restore line width
  702. if (@line_width != lw)
  703. @line_width = lw;
  704. out(sprintf('%.2f w', lw*@k));
  705. end
  706. #Restore font
  707. if (family)
  708. SetFont(family, style, size);
  709. end
  710. #Restore colors
  711. if (@draw_color != dc)
  712. @draw_color = dc;
  713. out(dc);
  714. end
  715. if (@fill_color != fc)
  716. @fill_color = fc;
  717. out(fc);
  718. end
  719. @text_color = tc;
  720. @color_flag = cf;
  721. end
  722. alias_method :add_page, :AddPage
  723. #
  724. # Rotate object.
  725. # @param float :angle angle in degrees for counter-clockwise rotation
  726. # @param int :x abscissa of the rotation center. Default is current x position
  727. # @param int :y ordinate of the rotation center. Default is current y position
  728. #
  729. def Rotate(angle, x="", y="")
  730. if (x == '')
  731. x = @x;
  732. end
  733. if (y == '')
  734. y = @y;
  735. end
  736. if (@rtl)
  737. x = @w - x;
  738. angle = -@angle;
  739. end
  740. y = (@h - y) * @k;
  741. x *= @k;
  742. # calculate elements of transformation matrix
  743. tm = []
  744. tm[0] = ::Math::cos(deg2rad(angle));
  745. tm[1] = ::Math::sin(deg2rad(angle));
  746. tm[2] = -tm[1];
  747. tm[3] = tm[0];
  748. tm[4] = x + tm[1] * y - tm[0] * x;
  749. tm[5] = y - tm[0] * y - tm[1] * x;
  750. # generate the transformation matrix
  751. Transform(tm);
  752. end
  753. alias_method :rotate, :Rotate
  754. #
  755. # Starts a 2D tranformation saving current graphic state.
  756. # This function must be called before scaling, mirroring, translation, rotation and skewing.
  757. # Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
  758. #
  759. def StartTransform
  760. out('q');
  761. end
  762. alias_method :start_transform, :StartTransform
  763. #
  764. # Stops a 2D tranformation restoring previous graphic state.
  765. # This function must be called after scaling, mirroring, translation, rotation and skewing.
  766. # Use StartTransform() before, and StopTransform() after the transformations to restore the normal behavior.
  767. #
  768. def StopTransform
  769. out('Q');
  770. end
  771. alias_method :stop_transform, :StopTransform
  772. #
  773. # Apply graphic transformations.
  774. # @since 2.1.000 (2008-01-07)
  775. # @see StartTransform(), StopTransform()
  776. #
  777. def Transform(tm)
  778. x = out(sprintf('%.3f %.3f %.3f %.3f %.3f %.3f cm', tm[0], tm[1], tm[2], tm[3], tm[4], tm[5]));
  779. end
  780. alias_method :transform, :Transform
  781. #
  782. # Set header data.
  783. # @param string :ln header image logo
  784. # @param string :lw header image logo width in mm
  785. # @param string :ht string to print as title on document header
  786. # @param string :hs string to print on document header
  787. #
  788. def SetHeaderData(ln="", lw=0, ht="", hs="")
  789. @header_logo = ln || ""
  790. @header_logo_width = lw || 0
  791. @header_title = ht || ""
  792. @header_string = hs || ""
  793. end
  794. alias_method :set_header_data, :SetHeaderData
  795. #
  796. # Set header margin.
  797. # (minimum distance between header and top page margin)
  798. # @param int :hm distance in millimeters
  799. #
  800. def SetHeaderMargin(hm=10)
  801. @header_margin = hm;
  802. end
  803. alias_method :set_header_margin, :SetHeaderMargin
  804. #
  805. # Set footer margin.
  806. # (minimum distance between footer and bottom page margin)
  807. # @param int :fm distance in millimeters
  808. #
  809. def SetFooterMargin(fm=10)
  810. @footer_margin = fm;
  811. end
  812. alias_method :set_footer_margin, :SetFooterMargin
  813. #
  814. # Set a flag to print page header.
  815. # @param boolean :val set to true to print the page header (default), false otherwise.
  816. #
  817. def SetPrintHeader(val=true)
  818. @print_header = val;
  819. end
  820. alias_method :set_print_header, :SetPrintHeader
  821. #
  822. # Set a flag to print page footer.
  823. # @param boolean :value set to true to print the page footer (default), false otherwise.
  824. #
  825. def SetPrintFooter(val=true)
  826. @print_footer = val;
  827. end
  828. alias_method :set_print_footer, :SetPrintFooter
  829. #
  830. # This method is used to render the page header.
  831. # It is automatically called by AddPage() and could be overwritten in your own inherited class.
  832. #
  833. def Header()
  834. if (@print_header)
  835. if (@original_l_margin.nil?)
  836. @original_l_margin = @l_margin;
  837. end
  838. if (@original_r_margin.nil?)
  839. @original_r_margin = @r_margin;
  840. end
  841. #set current position
  842. SetXY(@original_l_margin, @header_margin);
  843. if ((@header_logo) and (@header_logo != @@k_blank_image))
  844. Image(@header_logo, @original_l_margin, @header_margin, @header_logo_width);
  845. else
  846. @img_rb_y = GetY();
  847. end
  848. cell_height = ((@@k_cell_height_ratio * @header_font[2]) / @k).round(2)
  849. header_x = @original_l_margin + (@header_logo_width * 1.05); #set left margin for text data cell
  850. # header title
  851. SetFont(@header_font[0], 'B', @header_font[2] + 1);
  852. SetX(header_x);
  853. Cell(@header_width, cell_height, @header_title, 0, 1, 'L');
  854. # header string
  855. SetFont(@header_font[0], @header_font[1], @header_font[2]);
  856. SetX(header_x);
  857. MultiCell(@header_width, cell_height, @header_string, 0, 'L', 0);
  858. # print an ending header line
  859. if (@header_width)
  860. #set style for cell border
  861. SetLineWidth(0.3);
  862. SetDrawColor(0, 0, 0);
  863. SetY(1 + (@img_rb_y > GetY() ? @img_rb_y : GetY()));
  864. SetX(@original_l_margin);
  865. Cell(0, 0, '', 'T', 0, 'C');
  866. end
  867. #restore position
  868. SetXY(@original_l_margin, @t_margin);
  869. end
  870. end
  871. alias_method :header, :Header
  872. #
  873. # This method is used to render the page footer.
  874. # It is automatically called by AddPage() and could be overwritten in your own inherited class.
  875. #
  876. def Footer()
  877. if (@print_footer)
  878. if (@original_l_margin.nil?)
  879. @original_l_margin = @l_margin;
  880. end
  881. if (@original_r_margin.nil?)
  882. @original_r_margin = @r_margin;
  883. end
  884. #set font
  885. SetFont(@footer_font[0], @footer_font[1] , @footer_font[2]);
  886. #set style for cell border
  887. line_width = 0.3;
  888. SetLineWidth(line_width);
  889. SetDrawColor(0, 0, 0);
  890. footer_height = ((@@k_cell_height_ratio * @footer_font[2]) / @k).round; #footer height, was , 2)
  891. #get footer y position
  892. footer_y = @h - @footer_margin - footer_height;
  893. #set current position
  894. SetXY(@original_l_margin, footer_y);
  895. #print document barcode
  896. if (@barcode)
  897. Ln();
  898. barcode_width = ((@w - @original_l_margin - @original_r_margin)).round; #max width
  899. writeBarcode(@original_l_margin, footer_y + line_width, barcode_width, footer_height - line_width, "C128B", false, false, 2, @barcode);
  900. end
  901. SetXY(@original_l_margin, footer_y);
  902. #Print page number
  903. Cell(0, footer_height, @l['w_page'] + " " + PageNo().to_s + ' / {nb}', 'T', 0, 'R');
  904. end
  905. end
  906. alias_method :footer, :Footer
  907. #
  908. # Returns the current page number.
  909. # @return int page number
  910. # @since 1.0
  911. # @see alias_nb_pages()
  912. #
  913. def PageNo()
  914. #Get current page number
  915. return @page;
  916. end
  917. alias_method :page_no, :PageNo
  918. #
  919. # 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.
  920. # @param int :r If g et b are given, red component; if not, indicates the gray level. Value between 0 and 255
  921. # @param int :g Green component (between 0 and 255)
  922. # @param int :b Blue component (between 0 and 255)
  923. # @since 1.3
  924. # @see SetFillColor(), SetTextColor(), Line(), Rect(), Cell(), MultiCell()
  925. #
  926. def SetDrawColor(r, g=-1, b=-1)
  927. #Set color for all stroking operations
  928. if ((r==0 and g==0 and b==0) or g==-1)
  929. @draw_color=sprintf('%.3f G', r/255.0);
  930. else
  931. @draw_color=sprintf('%.3f %.3f %.3f RG', r/255.0, g/255.0, b/255.0);
  932. end
  933. if (@page>0)
  934. out(@draw_color);
  935. end
  936. end
  937. alias_method :set_draw_color, :SetDrawColor
  938. #
  939. # 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.
  940. # @param int :r If g et b are given, red component; if not, indicates the gray level. Value between 0 and 255
  941. # @param int :g Green component (between 0 and 255)
  942. # @param int :b Blue component (between 0 and 255)
  943. # @param boolean :storeprev if true stores the RGB array on :prevfill_color variable.
  944. # @since 1.3
  945. # @see SetDrawColor(), SetTextColor(), Rect(), Cell(), MultiCell()
  946. #
  947. def SetFillColor(r, g=-1, b=-1, storeprev=false)
  948. #Set color for all filling operations
  949. if ((r==0 and g==0 and b==0) or g==-1)
  950. @fill_color=sprintf('%.3f g', r/255.0);
  951. else
  952. @fill_color=sprintf('%.3f %.3f %.3f rg', r/255.0, g/255.0, b/255.0);
  953. end
  954. @color_flag=(@fill_color!=@text_color);
  955. if (@page>0)
  956. out(@fill_color);
  957. end
  958. if (storeprev)
  959. # store color as previous value
  960. @prevfill_color = [r, g, b]
  961. end
  962. end
  963. alias_method :set_fill_color, :SetFillColor
  964. # This hasn't been ported from tcpdf, it's a variation on SetTextColor for setting cmyk colors
  965. def SetCmykFillColor(c, m, y, k, storeprev=false)
  966. #Set color for all filling operations
  967. @fill_color=sprintf('%.3f %.3f %.3f %.3f k', c, m, y, k);
  968. @color_flag=(@fill_color!=@text_color);
  969. if (storeprev)
  970. # store color as previous value
  971. @prevtext_color = [c, m, y, k]
  972. end
  973. if (@page>0)
  974. out(@fill_color);
  975. end
  976. end
  977. alias_method :set_cmyk_fill_color, :SetCmykFillColor
  978. #
  979. # 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.
  980. # @param int :r If g et b are given, red component; if not, indicates the gray level. Value between 0 and 255
  981. # @param int :g Green component (between 0 and 255)
  982. # @param int :b Blue component (between 0 and 255)
  983. # @param boolean :storeprev if true stores the RGB array on :prevtext_color variable.
  984. # @since 1.3
  985. # @see SetDrawColor(), SetFillColor(), Text(), Cell(), MultiCell()
  986. #
  987. def SetTextColor(r, g=-1, b=-1, storeprev=false)
  988. #Set color for text
  989. if ((r==0 and :g==0 and :b==0) or :g==-1)
  990. @text_color=sprintf('%.3f g', r/255.0);
  991. else
  992. @text_color=sprintf('%.3f %.3f %.3f rg', r/255.0, g/255.0, b/255.0);
  993. end
  994. @color_flag=(@fill_color!=@text_color);
  995. if (storeprev)
  996. # store color as previous value
  997. @prevtext_color = [r, g, b]
  998. end
  999. end
  1000. alias_method :set_text_color, :SetTextColor
  1001. # This hasn't been ported from tcpdf, it's a variation on SetTextColor for setting cmyk colors
  1002. def SetCmykTextColor(c, m, y, k, storeprev=false)
  1003. #Set color for text
  1004. @text_color=sprintf('%.3f %.3f %.3f %.3f k', c, m, y, k);
  1005. @color_flag=(@fill_color!=@text_color);
  1006. if (storeprev)
  1007. # store color as previous value
  1008. @prevtext_color = [c, m, y, k]
  1009. end
  1010. end
  1011. alias_method :set_cmyk_text_color, :SetCmykTextColor
  1012. #
  1013. # Returns the length of a string in user unit. A font must be selected.<br>
  1014. # Support UTF-8 Unicode [Nicola Asuni, 2005-01-02]
  1015. # @param string :s The string whose length is to be computed
  1016. # @return int
  1017. # @since 1.2
  1018. #
  1019. def GetStringWidth(s)
  1020. #Get width of a string in the current font
  1021. s = s.to_s;
  1022. cw = @current_font['cw']
  1023. w = 0;
  1024. if (@is_unicode)
  1025. unicode = UTF8StringToArray(s);
  1026. unicode.each do |char|
  1027. if (!cw[char].nil?)
  1028. w += cw[char];
  1029. # This should not happen. UTF8StringToArray should guarentee the array is ascii values.
  1030. # elsif (c!cw[char[0]].nil?)
  1031. # w += cw[char[0]];
  1032. # elsif (!cw[char.chr].nil?)
  1033. # w += cw[char.chr];
  1034. elsif (!@current_font['desc']['MissingWidth'].nil?)
  1035. w += @current_font['desc']['MissingWidth']; # set default size
  1036. else
  1037. w += 500;
  1038. end
  1039. end
  1040. else
  1041. s.each_byte do |c|
  1042. if cw[c.chr]
  1043. w += cw[c.chr];
  1044. elsif cw[?c.chr]
  1045. w += cw[?c.chr]
  1046. end
  1047. end
  1048. end
  1049. return (w * @font_size / 1000.0);
  1050. end
  1051. alias_method :get_string_width, :GetStringWidth
  1052. #
  1053. # 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.
  1054. # @param float :width The width.
  1055. # @since 1.0
  1056. # @see Line(), Rect(), Cell(), MultiCell()
  1057. #
  1058. def SetLineWidth(width)
  1059. #Set line width
  1060. @line_width = width;
  1061. if (@page>0)
  1062. out(sprintf('%.2f w', width*@k));
  1063. end
  1064. end
  1065. alias_method :set_line_width, :SetLineWidth
  1066. #
  1067. # Draws a line between two points.
  1068. # @param float :x1 Abscissa of first point
  1069. # @param float :y1 Ordinate of first point
  1070. # @param float :x2 Abscissa of second point
  1071. # @param float :y2 Ordinate of second point
  1072. # @since 1.0
  1073. # @see SetLineWidth(), SetDrawColor()
  1074. #
  1075. def Line(x1, y1, x2, y2)
  1076. #Draw a line
  1077. out(sprintf('%.2f %.2f m %.2f %.2f l S', x1 * @k, (@h - y1) * @k, x2 * @k, (@h - y2) * @k));
  1078. end
  1079. alias_method :line, :Line
  1080. def Circle(mid_x, mid_y, radius, style='')
  1081. mid_y = (@h-mid_y)*@k
  1082. out(sprintf("q\n")) # postscript content in pdf
  1083. # init line type etc. with /GSD gs G g (grey) RG rg (RGB) w=line witdh etc.
  1084. out(sprintf("1 j\n")) # line join
  1085. # translate ("move") circle to mid_y, mid_y
  1086. out(sprintf("1 0 0 1 %f %f cm", mid_x, mid_y))
  1087. kappa = 0.5522847498307933984022516322796
  1088. # Quadrant 1
  1089. x_s = 0.0 # 12 o'clock
  1090. y_s = 0.0 + radius
  1091. x_e = 0.0 + radius # 3 o'clock
  1092. y_e = 0.0
  1093. out(sprintf("%f %f m\n", x_s, y_s)) # move to 12 o'clock
  1094. # cubic bezier control point 1, start height and kappa * radius to the right
  1095. bx_e1 = x_s + (radius * kappa)
  1096. by_e1 = y_s
  1097. # cubic bezier control point 2, end and kappa * radius above
  1098. bx_e2 = x_e
  1099. by_e2 = y_e + (radius * kappa)
  1100. # 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
  1101. out(sprintf("%f %f %f %f %f %f c\n", bx_e1, by_e1, bx_e2, by_e2, x_e, y_e))
  1102. # Quadrant 2
  1103. x_s = x_e
  1104. y_s = y_e # 3 o'clock
  1105. x_e = 0.0
  1106. y_e = 0.0 - radius # 6 o'clock
  1107. bx_e1 = x_s # cubic bezier point 1
  1108. by_e1 = y_s - (radius * kappa)
  1109. bx_e2 = x_e + (radius * kappa) # cubic bezier point 2
  1110. by_e2 = y_e
  1111. out(sprintf("%f %f %f %f %f %f c\n", bx_e1, by_e1, bx_e2, by_e2, x_e, y_e))
  1112. # Quadrant 3
  1113. x_s = x_e
  1114. y_s = y_e # 6 o'clock
  1115. x_e = 0.0 - radius
  1116. y_e = 0.0 # 9 o'clock
  1117. bx_e1 = x_s - (radius * kappa) # cubic bezier point 1
  1118. by_e1 = y_s
  1119. bx_e2 = x_e # cubic bezier point 2
  1120. by_e2 = y_e - (radius * kappa)
  1121. out(sprintf("%f %f %f %f %f %f c\n", bx_e1, by_e1, bx_e2, by_e2, x_e, y_e))
  1122. # Quadrant 4
  1123. x_s = x_e
  1124. y_s = y_e # 9 o'clock
  1125. x_e = 0.0
  1126. y_e = 0.0 + radius # 12 o'clock
  1127. bx_e1 = x_s # cubic bezier point 1
  1128. by_e1 = y_s + (radius * kappa)
  1129. bx_e2 = x_e - (radius * kappa) # cubic bezier point 2
  1130. by_e2 = y_e
  1131. out(sprintf("%f %f %f %f %f %f c\n", bx_e1, by_e1, bx_e2, by_e2, x_e, y_e))
  1132. if style=='F'
  1133. op='f'
  1134. elsif style=='FD' or style=='DF'
  1135. op='b'
  1136. else
  1137. op='s'
  1138. end
  1139. out(sprintf("#{op}\n")) # stroke circle, do not fill and close path
  1140. # for filling etc. b, b*, f, f*
  1141. out(sprintf("Q\n")) # finish postscript in PDF
  1142. end
  1143. alias_method :circle, :Circle
  1144. #
  1145. # Outputs a rectangle. It can be drawn (border only), filled (with no border) or both.
  1146. # @param float :x Abscissa of upper-left corner
  1147. # @param float :y Ordinate of upper-left corner
  1148. # @param float :w Width
  1149. # @param float :h Height
  1150. # @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>
  1151. # @since 1.0
  1152. # @see SetLineWidth(), SetDrawColor(), SetFillColor()
  1153. #
  1154. def Rect(x, y, w, h, style='')
  1155. #Draw a rectangle
  1156. if (style=='F')
  1157. op='f';
  1158. elsif (style=='FD' or style=='DF')
  1159. op='B';
  1160. else
  1161. op='S';
  1162. end
  1163. out(sprintf('%.2f %.2f %.2f %.2f re %s', x * @k, (@h - y) * @k, w * @k, -h * @k, op));
  1164. end
  1165. alias_method :rect, :Rect
  1166. #
  1167. # 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.
  1168. # Support UTF-8 Unicode [Nicola Asuni, 2005-01-02].
  1169. # <b>Example</b>:<br />
  1170. # <pre>
  1171. # :pdf->AddFont('Comic','I');
  1172. # # is equivalent to:
  1173. # :pdf->AddFont('Comic','I','comici.rb');
  1174. # </pre>
  1175. # @param string :family Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.
  1176. # @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>
  1177. # @param string :file The font definition file. By default, the name is built from the family and style, in lower case with no space.
  1178. # @since 1.5
  1179. # @see SetFont()
  1180. #
  1181. def AddFont(family, style='', file='')
  1182. if (family.empty?)
  1183. return;
  1184. end
  1185. #Add a TrueType or Type1 font
  1186. family = family.downcase
  1187. if ((!@is_unicode) and (family == 'arial'))
  1188. family = 'helvetica';
  1189. end
  1190. style=style.upcase
  1191. style=style.gsub('U','');
  1192. style=style.gsub('D','');
  1193. if (style == 'IB')
  1194. style = 'BI';
  1195. end
  1196. fontkey = family + style;
  1197. # check if the font has been already added
  1198. if !@fonts[fontkey].nil?
  1199. return;
  1200. end
  1201. if (file=='')
  1202. file = family.gsub(' ', '') + style.downcase + '.rb';
  1203. end
  1204. font_file_name = getfontpath(file)
  1205. if (font_file_name.nil?)
  1206. # try to load the basic file without styles
  1207. file = family.gsub(' ', '') + '.rb';
  1208. font_file_name = getfontpath(file)
  1209. end
  1210. if font_file_name.nil?
  1211. Error("Could not find font #{file}.")
  1212. end
  1213. require(getfontpath(file))
  1214. font_desc = TCPDFFontDescriptor.font(file)
  1215. if (font_desc[:name].nil? and @@fpdf_charwidths.nil?)
  1216. Error('Could not include font definition file');
  1217. end
  1218. i = @fonts.length+1;
  1219. if (@is_unicode)
  1220. @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]}
  1221. @@fpdf_charwidths[fontkey] = font_desc[:cw];
  1222. else
  1223. @fonts[fontkey]={'i' => i, 'type'=>'core', 'name'=>@core_fonts[fontkey], 'up'=>-100, 'ut'=>50, 'cw' => font_desc[:cw]}
  1224. @@fpdf_charwidths[fontkey] = font_desc[:cw];
  1225. end
  1226. if (!font_desc[:diff].nil? and (!font_desc[:diff].empty?))
  1227. #Search existing encodings
  1228. d=0;
  1229. nb=@diffs.length;
  1230. 1.upto(nb) do |i|
  1231. if (@diffs[i]== font_desc[:diff])
  1232. d = i;
  1233. break;
  1234. end
  1235. end
  1236. if (d==0)
  1237. d = nb+1;
  1238. @diffs[d] = font_desc[:diff];
  1239. end
  1240. @fonts[fontkey]['diff'] = d;
  1241. end
  1242. if (font_desc[:file] and font_desc[:file].length > 0)
  1243. if (font_desc[:type] == "TrueType") or (font_desc[:type] == "TrueTypeUnicode")
  1244. @font_files[font_desc[:file]] = {'length1' => font_desc[:originalsize]}
  1245. else
  1246. @font_files[font_desc[:file]] = {'length1' => font_desc[:size1], 'length2' => font_desc[:size2]}
  1247. end
  1248. end
  1249. end
  1250. alias_method :add_font, :AddFont
  1251. #
  1252. # 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.
  1253. # The font can be either a standard one or a font added via the AddFont() method. Standard fonts use Windows encoding cp1252 (Western Europe).
  1254. # The method can be called before the first page is created and the font is retained from page to page.
  1255. # If you just wish to change the current font size, it is simpler to call SetFontSize().
  1256. # 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 />
  1257. # Example for the last case (note the trailing slash):<br />
  1258. # <pre>
  1259. # define('FPDF_FONTPATH','/home/www/font/');
  1260. # require('tcpdf.rb');
  1261. #
  1262. # #Times regular 12
  1263. # :pdf->SetFont('Times');
  1264. # #Arial bold 14
  1265. # :pdf->SetFont('Arial','B',14);
  1266. # #Removes bold
  1267. # :pdf->SetFont('');
  1268. # #Times bold, italic and underlined 14
  1269. # :pdf->SetFont('Times','BIUD');
  1270. # </pre><br />
  1271. # If the file corresponding to the requested font is not found, the error "Could not include font metric file" is generated.
  1272. # @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.
  1273. # @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
  1274. # @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
  1275. # @since 1.0
  1276. # @see AddFont(), SetFontSize(), Cell(), MultiCell(), Write()
  1277. #
  1278. def SetFont(family, style='', size=0)
  1279. # save previous values
  1280. @prevfont_family = @font_family;
  1281. @prevfont_style = @font_style;
  1282. family=family.downcase;
  1283. if (family=='')
  1284. family=@font_family;
  1285. end
  1286. if ((!@is_unicode) and (family == 'arial'))
  1287. family = 'helvetica';
  1288. elsif ((family=="symbol") or (family=="zapfdingbats"))
  1289. style='';
  1290. end
  1291. style=style.upcase;
  1292. if (style.include?('U'))
  1293. @underline=true;
  1294. style= style.gsub('U','');
  1295. else
  1296. @underline=false;
  1297. end
  1298. if (style.include?('D'))
  1299. @deleted=true;
  1300. style= style.gsub('D','');
  1301. else
  1302. @deleted=false;
  1303. end
  1304. if (style=='IB')
  1305. style='BI';
  1306. end
  1307. if (size==0)
  1308. size=@font_size_pt;
  1309. end
  1310. # try to add font (if not already added)
  1311. AddFont(family, style);
  1312. #Test if font is already selected
  1313. if ((@font_family == family) and (@font_style == style) and (@font_size_pt == size))
  1314. return;
  1315. end
  1316. fontkey = family + style;
  1317. style = '' if (@fonts[fontkey].nil? and !@fonts[family].nil?)
  1318. #Test if used for the first time
  1319. if (@fonts[fontkey].nil?)
  1320. #Check if one of the standard fonts
  1321. if (!@core_fonts[fontkey].nil?)
  1322. if @@fpdf_charwidths[fontkey].nil?
  1323. #Load metric file
  1324. file = family;
  1325. if ((family!='symbol') and (family!='zapfdingbats'))
  1326. file += style.downcase;
  1327. end
  1328. if (getfontpath(file + '.rb').nil?)
  1329. # try to load the basic file without styles
  1330. file = family;
  1331. fontkey = family;
  1332. end
  1333. require(getfontpath(file + '.rb'));
  1334. font_desc = TCPDFFontDescriptor.font(file)
  1335. if ((@is_unicode and ctg.nil?) or ((!@is_unicode) and (@@fpdf_charwidths[fontkey].nil?)) )
  1336. Error("Could not include font metric file [" + fontkey + "]: " + getfontpath(file + ".rb"));
  1337. end
  1338. end
  1339. i = @fonts.length + 1;
  1340. if (@is_unicode)
  1341. @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]}
  1342. @@fpdf_charwidths[fontkey] = font_desc[:cw];
  1343. else
  1344. @fonts[fontkey] = {'i' => i, 'type'=>'core', 'name'=>@core_fonts[fontkey], 'up'=>-100, 'ut'=>50, 'cw' => font_desc[:cw]}
  1345. @@fpdf_charwidths[fontkey] = font_desc[:cw];
  1346. end
  1347. else
  1348. Error('Undefined font: ' + family + ' ' + style);
  1349. end
  1350. end
  1351. #Select it
  1352. @font_family = family;
  1353. @font_style = style;
  1354. @font_size_pt = size;
  1355. @font_size = size / @k;
  1356. @current_font = @fonts[fontkey]; # was & may need deep copy?
  1357. if (@page>0)
  1358. out(sprintf('BT /F%d %.2f Tf ET', @current_font['i'], @font_size_pt));
  1359. end
  1360. end
  1361. alias_method :set_font, :SetFont
  1362. #
  1363. # Defines the size of the current font.
  1364. # @param float :size The size (in points)
  1365. # @since 1.0
  1366. # @see SetFont()
  1367. #
  1368. def SetFontSize(size)
  1369. #Set font size in points
  1370. if (@font_size_pt== size)
  1371. return;
  1372. end
  1373. @font_size_pt = size;
  1374. @font_size = size.to_f / @k;
  1375. if (@page > 0)
  1376. out(sprintf('BT /F%d %.2f Tf ET', @current_font['i'], @font_size_pt));
  1377. end
  1378. end
  1379. alias_method :set_font_size, :SetFontSize
  1380. #
  1381. # 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 />
  1382. # The identifier can then be passed to Cell(), Write(), Image() or Link(). The destination is defined with SetLink().
  1383. # @since 1.5
  1384. # @see Cell(), Write(), Image(), Link(), SetLink()
  1385. #
  1386. def AddLink()
  1387. #Create a new internal link
  1388. n=@links.length+1;
  1389. @links[n]=[0,0];
  1390. return n;
  1391. end
  1392. alias_method :add_link, :AddLink
  1393. #
  1394. # Defines the page and position a link points to
  1395. # @param int :link The link identifier returned by AddLink()
  1396. # @param float :y Ordinate of target position; -1 indicates the current position. The default value is 0 (top of page)
  1397. # @param int :page Number of target page; -1 indicates the current page. This is the default value
  1398. # @since 1.5
  1399. # @see AddLink()
  1400. #
  1401. def SetLink(link, y=0, page=-1)
  1402. #Set destination of internal link
  1403. if (y==-1)
  1404. y=@y;
  1405. end
  1406. if (page==-1)
  1407. page=@page;
  1408. end
  1409. @links[link] = [page, y]
  1410. end
  1411. alias_method :set_link, :SetLink
  1412. #
  1413. # 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.
  1414. # @param float :x Abscissa of the upper-left corner of the rectangle
  1415. # @param float :y Ordinate of the upper-left corner of the rectangle
  1416. # @param float :w Width of the rectangle
  1417. # @param float :h Height of the rectangle
  1418. # @param mixed :link URL or identifier returned by AddLink()
  1419. # @since 1.5
  1420. # @see AddLink(), Cell(), Write(), Image()
  1421. #
  1422. def Link(x, y, w, h, link)
  1423. #Put a link on the page
  1424. @page_links

Large files files are truncated, but you can click here to view the full file