PageRenderTime 42ms CodeModel.GetById 35ms RepoModel.GetById 0ms app.codeStats 1ms

/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
  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 ||= Array.new
  1425. @page_links[@page] ||= Array.new
  1426. @page_links[@page].push([x * @k, @h_pt - y * @k, w * @k, h*@k, link]);
  1427. end
  1428. alias_method :link, :Link
  1429. #
  1430. # Prints a character string. The origin is on the left of the first charcter, on the baseline. This method allows to place a string precisely on the page, but it is usually easier to use Cell(), MultiCell() or Write() which are the standard methods to print text.
  1431. # @param float :x Abscissa of the origin
  1432. # @param float :y Ordinate of the origin
  1433. # @param string :txt String to print
  1434. # @since 1.0
  1435. # @see SetFont(), SetTextColor(), Cell(), MultiCell(), Write()
  1436. #
  1437. def Text(x, y, txt)
  1438. #Output a string
  1439. s=sprintf('BT %.2f %.2f Td (%s) Tj ET', x * @k, (@h-y) * @k, escapetext(txt));
  1440. if (@underline and (txt!=''))
  1441. s += ' ' + dolinetxt(x, y, txt);
  1442. end
  1443. if (@color_flag)
  1444. s='q ' + @text_color + ' ' + s + ' Q';
  1445. end
  1446. out(s);
  1447. end
  1448. alias_method :text, :Text
  1449. #
  1450. # Whenever a page break condition is met, the method is called, and the break is issued or not depending on the returned value. The default implementation returns a value according to the mode selected by SetAutoPageBreak().<br />
  1451. # This method is called automatically and should not be called directly by the application.<br />
  1452. # <b>Example:</b><br />
  1453. # The method is overriden in an inherited class in order to obtain a 3 column layout:<br />
  1454. # <pre>
  1455. # class PDF extends TCPDF {
  1456. # var :col=0;
  1457. #
  1458. # def SetCol(col)
  1459. # #Move position to a column
  1460. # @col = col;
  1461. # :x=10+:col*65;
  1462. # SetLeftMargin(x);
  1463. # SetX(x);
  1464. # end
  1465. #
  1466. # def AcceptPageBreak()
  1467. # if (@col<2)
  1468. # #Go to next column
  1469. # SetCol(@col+1);
  1470. # SetY(10);
  1471. # return false;
  1472. # end
  1473. # else
  1474. # #Go back to first column and issue page break
  1475. # SetCol(0);
  1476. # return true;
  1477. # end
  1478. # end
  1479. # }
  1480. #
  1481. # :pdf=new PDF();
  1482. # :pdf->Open();
  1483. # :pdf->AddPage();
  1484. # :pdf->SetFont('Arial','',12);
  1485. # for(i=1;:i<=300;:i++)
  1486. # :pdf->Cell(0,5,"Line :i",0,1);
  1487. # }
  1488. # :pdf->Output();
  1489. # </pre>
  1490. # @return boolean
  1491. # @since 1.4
  1492. # @see SetAutoPageBreak()
  1493. #
  1494. def AcceptPageBreak()
  1495. #Accept automatic page break or not
  1496. return @auto_page_break;
  1497. end
  1498. alias_method :accept_page_break, :AcceptPageBreak
  1499. def BreakThePage?(h)
  1500. if ((@y + h) > @page_break_trigger and !@in_footer and AcceptPageBreak())
  1501. true
  1502. else
  1503. false
  1504. end
  1505. end
  1506. alias_method :break_the_page?, :BreakThePage?
  1507. #
  1508. # Prints a cell (rectangular area) with optional borders, background color and character string. The upper-left corner of the cell corresponds to the current position. The text can be aligned or centered. After the call, the current position moves to the right or to the next line. It is possible to put a link on the text.<br />
  1509. # If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
  1510. # @param float :w Cell width. If 0, the cell extends up to the right margin.
  1511. # @param float :h Cell height. Default value: 0.
  1512. # @param string :txt String to print. Default value: empty string.
  1513. # @param mixed :border Indicates if borders must be drawn around the cell. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
  1514. # @param int :ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>
  1515. # Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
  1516. # @param string :align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align (default value)</li><li>C: center</li><li>R: right align</li></ul>
  1517. # @param int :fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
  1518. # @param mixed :link URL or identifier returned by AddLink().
  1519. # @since 1.0
  1520. # @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), AddLink(), Ln(), MultiCell(), Write(), SetAutoPageBreak()
  1521. #
  1522. def Cell(w, h=0, txt='', border=0, ln=0, align='', fill=0, link=nil)
  1523. #Output a cell
  1524. k=@k;
  1525. if ((@y + h) > @page_break_trigger and !@in_footer and AcceptPageBreak())
  1526. #Automatic page break
  1527. if @pages[@page+1].nil?
  1528. x = @x;
  1529. ws = @ws;
  1530. if (ws > 0)
  1531. @ws = 0;
  1532. out('0 Tw');
  1533. end
  1534. AddPage(@cur_orientation);
  1535. @x = x;
  1536. if (ws > 0)
  1537. @ws = ws;
  1538. out(sprintf('%.3f Tw', ws * k));
  1539. end
  1540. else
  1541. @page += 1;
  1542. @y=@t_margin;
  1543. end
  1544. end
  1545. if (w == 0)
  1546. w = @w - @r_margin - @x;
  1547. end
  1548. s = '';
  1549. if ((fill.to_i == 1) or (border.to_i == 1))
  1550. if (fill.to_i == 1)
  1551. op = (border.to_i == 1) ? 'B' : 'f';
  1552. else
  1553. op = 'S';
  1554. end
  1555. s = sprintf('%.2f %.2f %.2f %.2f re %s ', @x * k, (@h - @y) * k, w * k, -h * k, op);
  1556. end
  1557. if (border.is_a?(String))
  1558. x=@x;
  1559. y=@y;
  1560. if (border.include?('L'))
  1561. s<<sprintf('%.2f %.2f m %.2f %.2f l S ', x*k,(@h-y)*k, x*k,(@h-(y+h))*k);
  1562. end
  1563. if (border.include?('T'))
  1564. s<<sprintf('%.2f %.2f m %.2f %.2f l S ', x*k,(@h-y)*k,(x+w)*k,(@h-y)*k);
  1565. end
  1566. if (border.include?('R'))
  1567. s<<sprintf('%.2f %.2f m %.2f %.2f l S ',(x+w)*k,(@h-y)*k,(x+w)*k,(@h-(y+h))*k);
  1568. end
  1569. if (border.include?('B'))
  1570. s<<sprintf('%.2f %.2f m %.2f %.2f l S ', x*k,(@h-(y+h))*k,(x+w)*k,(@h-(y+h))*k);
  1571. end
  1572. end
  1573. if (txt != '')
  1574. width = GetStringWidth(txt);
  1575. if (align == 'R' || align == 'right')
  1576. dx = w - @c_margin - width;
  1577. elsif (align=='C' || align == 'center')
  1578. dx = (w - width)/2;
  1579. else
  1580. dx = @c_margin;
  1581. end
  1582. if (@color_flag)
  1583. s << 'q ' + @text_color + ' ';
  1584. end
  1585. txt2 = escapetext(txt);
  1586. s<<sprintf('BT %.2f %.2f Td (%s) Tj ET', (@x + dx) * k, (@h - (@y + 0.5 * h + 0.3 * @font_size)) * k, txt2);
  1587. if (@underline)
  1588. s<<' ' + dolinetxt(@x + dx, @y + 0.5 * h + 0.3 * @font_size, txt);
  1589. end
  1590. if (@deleted)
  1591. s<<' ' + dolinetxt(@x + dx, @y + 0.3 * h + 0.2 * @font_size, txt);
  1592. end
  1593. if (@color_flag)
  1594. s<<' Q';
  1595. end
  1596. if link && !link.empty?
  1597. Link(@x + dx, @y + 0.5 * h - 0.5 * @font_size, width, @font_size, link);
  1598. end
  1599. end
  1600. if (s)
  1601. out(s);
  1602. end
  1603. @lasth = h;
  1604. if (ln.to_i>0)
  1605. # Go to next line
  1606. @y += h;
  1607. if (ln == 1)
  1608. @x = @l_margin;
  1609. end
  1610. else
  1611. @x += w;
  1612. end
  1613. end
  1614. alias_method :cell, :Cell
  1615. #
  1616. # This method allows printing text with line breaks. They can be automatic (as soon as the text reaches the right border of the cell) or explicit (via the \n character). As many cells as necessary are output, one below the other.<br />
  1617. # Text can be aligned, centered or justified. The cell block can be framed and the background painted.
  1618. # @param float :w Width of cells. If 0, they extend up to the right margin of the page.
  1619. # @param float :h Height of cells.
  1620. # @param string :txt String to print
  1621. # @param mixed :border Indicates if borders must be drawn around the cell block. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
  1622. # @param string :align Allows to center or align the text. Possible values are:<ul><li>L or empty string: left align</li><li>C: center</li><li>R: right align</li><li>J: justification (default value)</li></ul>
  1623. # @param int :fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
  1624. # @param int :ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right</li><li>1: to the beginning of the next line [DEFAULT]</li><li>2: below</li></ul>
  1625. # @since 1.3
  1626. # @see SetFont(), SetDrawColor(), SetFillColor(), SetTextColor(), SetLineWidth(), Cell(), Write(), SetAutoPageBreak()
  1627. #
  1628. def MultiCell(w, h, txt, border=0, align='J', fill=0, ln=1)
  1629. # save current position
  1630. prevx = @x;
  1631. prevy = @y;
  1632. prevpage = @page;
  1633. #Output text with automatic or explicit line breaks
  1634. if (w == 0)
  1635. w = @w - @r_margin - @x;
  1636. end
  1637. wmax = (w - 3 * @c_margin);
  1638. s = txt.gsub("\r", ''); # remove carriage returns
  1639. nb = s.length;
  1640. b=0;
  1641. if (border)
  1642. if (border==1)
  1643. border='LTRB';
  1644. b='LRT';
  1645. b2='LR';
  1646. elsif border.is_a?(String)
  1647. b2='';
  1648. if (border.include?('L'))
  1649. b2<<'L';
  1650. end
  1651. if (border.include?('R'))
  1652. b2<<'R';
  1653. end
  1654. b=(border.include?('T')) ? b2 + 'T' : b2;
  1655. end
  1656. end
  1657. sep=-1;
  1658. to_index=0;
  1659. from_j=0;
  1660. l=0;
  1661. ns=0;
  1662. nl=1;
  1663. while to_index < nb
  1664. #Get next character
  1665. c = s[to_index];
  1666. if c == "\n"[0]
  1667. #Explicit line break
  1668. if @ws > 0
  1669. @ws = 0
  1670. out('0 Tw')
  1671. end
  1672. #Ed Moss - change begin
  1673. end_i = to_index == 0 ? 0 : to_index - 1
  1674. # Changed from s[from_j..to_index] to fix bug reported by Hans Allis.
  1675. from_j = to_index == 0 ? 1 : from_j
  1676. Cell(w, h, s[from_j..end_i], b, 2, align, fill)
  1677. #change end
  1678. to_index += 1
  1679. sep=-1
  1680. from_j=to_index
  1681. l=0
  1682. ns=0
  1683. nl += 1
  1684. b = b2 if border and nl==2
  1685. next
  1686. end
  1687. if (c == " "[0])
  1688. sep = to_index;
  1689. ls = l;
  1690. ns += 1;
  1691. end
  1692. l = GetStringWidth(s[from_j, to_index - from_j]);
  1693. if (l > wmax)
  1694. #Automatic line break
  1695. if (sep == -1)
  1696. if (to_index == from_j)
  1697. to_index += 1;
  1698. end
  1699. if (@ws > 0)
  1700. @ws = 0;
  1701. out('0 Tw');
  1702. end
  1703. Cell(w, h, s[from_j..to_index-1], b, 2, align, fill) # my FPDF version
  1704. else
  1705. if (align=='J' || align=='justify' || align=='justified')
  1706. @ws = (ns>1) ? (wmax-ls)/(ns-1) : 0;
  1707. out(sprintf('%.3f Tw', @ws * @k));
  1708. end
  1709. Cell(w, h, s[from_j..sep], b, 2, align, fill);
  1710. to_index = sep + 1;
  1711. end
  1712. sep=-1;
  1713. from_j = to_index;
  1714. l=0;
  1715. ns=0;
  1716. nl += 1;
  1717. if (border and (nl==2))
  1718. b = b2;
  1719. end
  1720. else
  1721. to_index += 1;
  1722. end
  1723. end
  1724. #Last chunk
  1725. if (@ws>0)
  1726. @ws=0;
  1727. out('0 Tw');
  1728. end
  1729. if (border.is_a?(String) and border.include?('B'))
  1730. b<<'B';
  1731. end
  1732. Cell(w, h, s[from_j, to_index-from_j], b, 2, align, fill);
  1733. # move cursor to specified position
  1734. # since 2007-03-03
  1735. if (ln == 1)
  1736. # go to the beginning of the next line
  1737. @x = @l_margin;
  1738. elsif (ln == 0)
  1739. # go to the top-right of the cell
  1740. @page = prevpage;
  1741. @y = prevy;
  1742. @x = prevx + w;
  1743. elsif (ln == 2)
  1744. # go to the bottom-left of the cell
  1745. @x = prevx;
  1746. end
  1747. end
  1748. alias_method :multi_cell, :MultiCell
  1749. #
  1750. # This method prints text from the current position. When the right margin is reached (or the \n character is met) a line break occurs and text continues from the left margin. Upon method exit, the current position is left just at the end of the text. It is possible to put a link on the text.<br />
  1751. # <b>Example:</b><br />
  1752. # <pre>
  1753. # #Begin with regular font
  1754. # :pdf->SetFont('Arial','',14);
  1755. # :pdf->Write(5,'Visit ');
  1756. # #Then put a blue underlined link
  1757. # :pdf->SetTextColor(0,0,255);
  1758. # :pdf->SetFont('','U');
  1759. # :pdf->Write(5,'www.tecnick.com','http://www.tecnick.com');
  1760. # </pre>
  1761. # @param float :h Line height
  1762. # @param string :txt String to print
  1763. # @param mixed :link URL or identifier returned by AddLink()
  1764. # @param int :fill Indicates if the background must be painted (1) or transparent (0). Default value: 0.
  1765. # @since 1.5
  1766. # @see SetFont(), SetTextColor(), AddLink(), MultiCell(), SetAutoPageBreak()
  1767. #
  1768. def Write(h, txt, link=nil, fill=0)
  1769. #Output text in flowing mode
  1770. w = @w - @r_margin - @x;
  1771. wmax = (w - 3 * @c_margin);
  1772. s = txt.gsub("\r", '');
  1773. nb = s.length;
  1774. # handle single space character
  1775. if ((nb==1) and (s == " "))
  1776. @x += GetStringWidth(s);
  1777. return;
  1778. end
  1779. sep=-1;
  1780. i=0;
  1781. j=0;
  1782. l=0;
  1783. nl=1;
  1784. while(i<nb)
  1785. #Get next character
  1786. c = s[i];
  1787. if (c == "\n"[0])
  1788. #Explicit line break
  1789. Cell(w, h, s[j,i-j], 0, 2, '', fill, link);
  1790. i += 1;
  1791. sep = -1;
  1792. j = i;
  1793. l = 0;
  1794. if (nl == 1)
  1795. @x = @l_margin;
  1796. w = @w - @r_margin - @x;
  1797. wmax = (w - 3 * @c_margin);
  1798. end
  1799. nl += 1;
  1800. next
  1801. end
  1802. if (c == " "[0])
  1803. sep= i;
  1804. end
  1805. l = GetStringWidth(s[j, i - j]);
  1806. if (l > wmax)
  1807. #Automatic line break (word wrapping)
  1808. if (sep == -1)
  1809. if (@x > @l_margin)
  1810. #Move to next line
  1811. @x = @l_margin;
  1812. @y += h;
  1813. w=@w - @r_margin - @x;
  1814. wmax=(w - 3 * @c_margin);
  1815. i += 1
  1816. nl += 1
  1817. next
  1818. end
  1819. if (i == j)
  1820. i += 1
  1821. end
  1822. Cell(w, h, s[j, (i-1)], 0, 2, '', fill, link);
  1823. else
  1824. Cell(w, h, s[j, (sep-j)], 0, 2, '', fill, link);
  1825. i = sep+1;
  1826. end
  1827. sep = -1;
  1828. j = i;
  1829. l = 0;
  1830. if (nl==1)
  1831. @x = @l_margin;
  1832. w = @w - @r_margin - @x;
  1833. wmax = (w - 3 * @c_margin);
  1834. end
  1835. nl += 1;
  1836. else
  1837. i += 1;
  1838. end
  1839. end
  1840. #Last chunk
  1841. if (i != j)
  1842. Cell(GetStringWidth(s[j..i]), h, s[j..i], 0, 0, '', fill, link);
  1843. end
  1844. end
  1845. alias_method :write, :Write
  1846. #
  1847. # Puts an image in the page. The upper-left corner must be given. The dimensions can be specified in different ways:<ul><li>explicit width and height (expressed in user unit)</li><li>one explicit dimension, the other being calculated automatically in order to keep the original proportions</li><li>no explicit dimension, in which case the image is put at 72 dpi</li></ul>
  1848. # Supported formats are JPEG and PNG.
  1849. # For JPEG, all flavors are allowed:<ul><li>gray scales</li><li>true colors (24 bits)</li><li>CMYK (32 bits)</li></ul>
  1850. # For PNG, are allowed:<ul><li>gray scales on at most 8 bits (256 levels)</li><li>indexed colors</li><li>true colors (24 bits)</li></ul>
  1851. # but are not supported:<ul><li>Interlacing</li><li>Alpha channel</li></ul>
  1852. # If a transparent color is defined, it will be taken into account (but will be only interpreted by Acrobat 4 and above).<br />
  1853. # The format can be specified explicitly or inferred from the file extension.<br />
  1854. # It is possible to put a link on the image.<br />
  1855. # Remark: if an image is used several times, only one copy will be embedded in the file.<br />
  1856. # @param string :file Name of the file containing the image.
  1857. # @param float :x Abscissa of the upper-left corner.
  1858. # @param float :y Ordinate of the upper-left corner.
  1859. # @param float :w Width of the image in the page. If not specified or equal to zero, it is automatically calculated.
  1860. # @param float :h Height of the image in the page. If not specified or equal to zero, it is automatically calculated.
  1861. # @param string :type Image format. Possible values are (case insensitive): JPG, JPEG, PNG. If not specified, the type is inferred from the file extension.
  1862. # @param mixed :link URL or identifier returned by AddLink().
  1863. # @since 1.1
  1864. # @see AddLink()
  1865. #
  1866. def Image(file, x, y, w=0, h=0, type='', link=nil)
  1867. #Put an image on the page
  1868. if (@images[file].nil?)
  1869. #First use of image, get info
  1870. if (type == '')
  1871. pos = File::basename(file).rindex('.');
  1872. if (pos.nil? or pos == 0)
  1873. Error('Image file has no extension and no type was specified: ' + file);
  1874. end
  1875. pos = file.rindex('.');
  1876. type = file[pos+1..-1];
  1877. end
  1878. type.downcase!
  1879. if (type == 'jpg' or type == 'jpeg')
  1880. info=parsejpg(file);
  1881. elsif (type == 'png')
  1882. info=parsepng(file);
  1883. elsif (type == 'gif')
  1884. tmpFile = imageToPNG(file);
  1885. info=parsepng(tmpFile.path);
  1886. tmpFile.delete
  1887. else
  1888. #Allow for additional formats
  1889. mtd='parse' + type;
  1890. if (!self.respond_to?(mtd))
  1891. Error('Unsupported image type: ' + type);
  1892. end
  1893. info=send(mtd, file);
  1894. end
  1895. info['i']=@images.length+1;
  1896. @images[file] = info;
  1897. else
  1898. info=@images[file];
  1899. end
  1900. #Automatic width and height calculation if needed
  1901. if ((w == 0) and (h == 0))
  1902. rescale_x = (@w - @r_margin - x) / (info['w'] / (@img_scale * @k))
  1903. rescale_x = 1 if rescale_x >= 1
  1904. if (y + info['h'] * rescale_x / (@img_scale * @k) > @page_break_trigger and !@in_footer and AcceptPageBreak())
  1905. #Automatic page break
  1906. if @pages[@page+1].nil?
  1907. ws = @ws;
  1908. if (ws > 0)
  1909. @ws = 0;
  1910. out('0 Tw');
  1911. end
  1912. AddPage(@cur_orientation);
  1913. if (ws > 0)
  1914. @ws = ws;
  1915. out(sprintf('%.3f Tw', ws * @k));
  1916. end
  1917. else
  1918. @page += 1;
  1919. end
  1920. y=@t_margin;
  1921. end
  1922. rescale_y = (@page_break_trigger - y) / (info['h'] / (@img_scale * @k))
  1923. rescale_y = 1 if rescale_y >= 1
  1924. rescale = rescale_y >= rescale_x ? rescale_x : rescale_y
  1925. #Put image at 72 dpi
  1926. # 2004-06-14 :: Nicola Asuni, scale factor where added
  1927. w = info['w'] * rescale / (@img_scale * @k);
  1928. h = info['h'] * rescale / (@img_scale * @k);
  1929. elsif (w == 0)
  1930. w = h * info['w'] / info['h'];
  1931. elsif (h == 0)
  1932. h = w * info['h'] / info['w'];
  1933. end
  1934. out(sprintf('q %.2f 0 0 %.2f %.2f %.2f cm /I%d Do Q', w*@k, h*@k, x*@k, (@h-(y+h))*@k, info['i']));
  1935. if (link)
  1936. Link(x, y, w, h, link);
  1937. end
  1938. #2002-07-31 - Nicola Asuni
  1939. # set right-bottom corner coordinates
  1940. @img_rb_x = x + w;
  1941. @img_rb_y = y + h;
  1942. end
  1943. alias_method :image, :Image
  1944. #
  1945. # Performs a line break. The current abscissa goes back to the left margin and the ordinate increases by the amount passed in parameter.
  1946. # @param float :h The height of the break. By default, the value equals the height of the last printed cell.
  1947. # @since 1.0
  1948. # @see Cell()
  1949. #
  1950. def Ln(h='')
  1951. #Line feed; default value is last cell height
  1952. @x=@l_margin;
  1953. if (h.is_a?(String))
  1954. @y += @lasth;
  1955. else
  1956. @y += h;
  1957. end
  1958. k=@k;
  1959. if (@y > @page_break_trigger and !@in_footer and AcceptPageBreak())
  1960. #Automatic page break
  1961. if @pages[@page+1].nil?
  1962. x = @x;
  1963. ws = @ws;
  1964. if (ws > 0)
  1965. @ws = 0;
  1966. out('0 Tw');
  1967. end
  1968. AddPage(@cur_orientation);
  1969. @x = x;
  1970. if (ws > 0)
  1971. @ws = ws;
  1972. out(sprintf('%.3f Tw', ws * k));
  1973. end
  1974. else
  1975. @page += 1;
  1976. @y=@t_margin;
  1977. end
  1978. end
  1979. end
  1980. alias_method :ln, :Ln
  1981. #
  1982. # Returns the abscissa of the current position.
  1983. # @return float
  1984. # @since 1.2
  1985. # @see SetX(), GetY(), SetY()
  1986. #
  1987. def GetX()
  1988. #Get x position
  1989. return @x;
  1990. end
  1991. alias_method :get_x, :GetX
  1992. #
  1993. # Defines the abscissa of the current position. If the passed value is negative, it is relative to the right of the page.
  1994. # @param float :x The value of the abscissa.
  1995. # @since 1.2
  1996. # @see GetX(), GetY(), SetY(), SetXY()
  1997. #
  1998. def SetX(x)
  1999. #Set x position
  2000. if (x>=0)
  2001. @x = x;
  2002. else
  2003. @x=@w+x;
  2004. end
  2005. end
  2006. alias_method :set_x, :SetX
  2007. #
  2008. # Returns the ordinate of the current position.
  2009. # @return float
  2010. # @since 1.0
  2011. # @see SetY(), GetX(), SetX()
  2012. #
  2013. def GetY()
  2014. #Get y position
  2015. return @y;
  2016. end
  2017. alias_method :get_y, :GetY
  2018. #
  2019. # Moves the current abscissa back to the left margin and sets the ordinate. If the passed value is negative, it is relative to the bottom of the page.
  2020. # @param float :y The value of the ordinate.
  2021. # @since 1.0
  2022. # @see GetX(), GetY(), SetY(), SetXY()
  2023. #
  2024. def SetY(y)
  2025. #Set y position and reset x
  2026. @x=@l_margin;
  2027. if (y>=0)
  2028. @y = y;
  2029. else
  2030. @y=@h+y;
  2031. end
  2032. end
  2033. alias_method :set_y, :SetY
  2034. #
  2035. # Defines the abscissa and ordinate of the current position. If the passed values are negative, they are relative respectively to the right and bottom of the page.
  2036. # @param float :x The value of the abscissa
  2037. # @param float :y The value of the ordinate
  2038. # @since 1.2
  2039. # @see SetX(), SetY()
  2040. #
  2041. def SetXY(x, y)
  2042. #Set x and y positions
  2043. SetY(y);
  2044. SetX(x);
  2045. end
  2046. alias_method :set_xy, :SetXY
  2047. #
  2048. # Send the document to a given destination: string, local file or browser. In the last case, the plug-in may be used (if present) or a download ("Save as" dialog box) may be forced.<br />
  2049. # The method first calls Close() if necessary to terminate the document.
  2050. # @param string :name The name of the file. If not given, the document will be sent to the browser (destination I) with the name doc.pdf.
  2051. # @param string :dest Destination where to send the document. It can take one of the following values:<ul><li>I: send the file inline to the browser. The plug-in is used if available. The name given by name is used when one selects the "Save as" option on the link generating the PDF.</li><li>D: send to the browser and force a file download with the name given by name.</li><li>F: save to a local file with the name given by name.</li><li>S: return the document as a string. name is ignored.</li></ul>If the parameter is not specified but a name is given, destination is F. If no parameter is specified at all, destination is I.<br />
  2052. # @since 1.0
  2053. # @see Close()
  2054. #
  2055. def Output(name='', dest='')
  2056. #Output PDF to some destination
  2057. #Finish document if necessary
  2058. if (@state < 3)
  2059. Close();
  2060. end
  2061. #Normalize parameters
  2062. # Boolean no longer supported
  2063. # if (dest.is_a?(Boolean))
  2064. # dest = dest ? 'D' : 'F';
  2065. # end
  2066. dest = dest.upcase
  2067. if (dest=='')
  2068. if (name=='')
  2069. name='doc.pdf';
  2070. dest='I';
  2071. else
  2072. dest='F';
  2073. end
  2074. end
  2075. case (dest)
  2076. when 'I'
  2077. # This is PHP specific code
  2078. ##Send to standard output
  2079. # if (ob_get_contents())
  2080. # Error('Some data has already been output, can\'t send PDF file');
  2081. # end
  2082. # if (php_sapi_name()!='cli')
  2083. # #We send to a browser
  2084. # header('Content-Type: application/pdf');
  2085. # if (headers_sent())
  2086. # Error('Some data has already been output to browser, can\'t send PDF file');
  2087. # end
  2088. # header('Content-Length: ' + @buffer.length);
  2089. # header('Content-disposition: inline; filename="' + name + '"');
  2090. # end
  2091. return @buffer;
  2092. when 'D'
  2093. # PHP specific
  2094. #Download file
  2095. # if (ob_get_contents())
  2096. # Error('Some data has already been output, can\'t send PDF file');
  2097. # end
  2098. # if (!_SERVER['HTTP_USER_AGENT'].nil? && SERVER['HTTP_USER_AGENT'].include?('MSIE'))
  2099. # header('Content-Type: application/force-download');
  2100. # else
  2101. # header('Content-Type: application/octet-stream');
  2102. # end
  2103. # if (headers_sent())
  2104. # Error('Some data has already been output to browser, can\'t send PDF file');
  2105. # end
  2106. # header('Content-Length: '+ @buffer.length);
  2107. # header('Content-disposition: attachment; filename="' + name + '"');
  2108. return @buffer;
  2109. when 'F'
  2110. open(name,'wb') do |f|
  2111. f.write(@buffer)
  2112. end
  2113. # PHP code
  2114. # #Save to local file
  2115. # f=open(name,'wb');
  2116. # if (!f)
  2117. # Error('Unable to create output file: ' + name);
  2118. # end
  2119. # fwrite(f,@buffer,@buffer.length);
  2120. # f.close
  2121. when 'S'
  2122. #Return as a string
  2123. return @buffer;
  2124. else
  2125. Error('Incorrect output destination: ' + dest);
  2126. end
  2127. return '';
  2128. end
  2129. alias_method :output, :Output
  2130. # Protected methods
  2131. #
  2132. # Check for locale-related bug
  2133. # @access protected
  2134. #
  2135. def dochecks()
  2136. #Check for locale-related bug
  2137. if (1.1==1)
  2138. Error('Don\'t alter the locale before including class file');
  2139. end
  2140. #Check for decimal separator
  2141. if (sprintf('%.1f',1.0)!='1.0')
  2142. setlocale(LC_NUMERIC,'C');
  2143. end
  2144. end
  2145. #
  2146. # Return fonts path
  2147. # @access protected
  2148. #
  2149. def getfontpath(file)
  2150. # Is it in the @@font_path?
  2151. if @@font_path
  2152. fpath = File.join @@font_path, file
  2153. if File.exists?(fpath)
  2154. return fpath
  2155. end
  2156. end
  2157. # Is it in this plugin's font folder?
  2158. fpath = File.join File.dirname(__FILE__), 'fonts', file
  2159. if File.exists?(fpath)
  2160. return fpath
  2161. end
  2162. # Could not find it.
  2163. nil
  2164. end
  2165. #
  2166. # Start document
  2167. # @access protected
  2168. #
  2169. def begindoc()
  2170. #Start document
  2171. @state=1;
  2172. out('%PDF-1.3');
  2173. end
  2174. #
  2175. # putpages
  2176. # @access protected
  2177. #
  2178. def putpages()
  2179. nb = @page;
  2180. if (@alias_nb_pages)
  2181. nbstr = UTF8ToUTF16BE(nb.to_s, false);
  2182. #Replace number of pages
  2183. 1.upto(nb) do |n|
  2184. @pages[n].gsub!(@alias_nb_pages, nbstr)
  2185. end
  2186. end
  2187. if @def_orientation=='P'
  2188. w_pt=@fw_pt
  2189. h_pt=@fh_pt
  2190. else
  2191. w_pt=@fh_pt
  2192. h_pt=@fw_pt
  2193. end
  2194. filter=(@compress) ? '/Filter /FlateDecode ' : ''
  2195. 1.upto(nb) do |n|
  2196. #Page
  2197. newobj
  2198. out('<</Type /Page')
  2199. out('/Parent 1 0 R')
  2200. unless @orientation_changes[n].nil?
  2201. out(sprintf('/MediaBox [0 0 %.2f %.2f]', h_pt, w_pt))
  2202. end
  2203. out('/Resources 2 0 R')
  2204. if @page_links[n]
  2205. #Links
  2206. annots='/Annots ['
  2207. @page_links[n].each do |pl|
  2208. rect=sprintf('%.2f %.2f %.2f %.2f', pl[0], pl[1], pl[0]+pl[2], pl[1]-pl[3]);
  2209. annots<<'<</Type /Annot /Subtype /Link /Rect [' + rect + '] /Border [0 0 0] ';
  2210. if (pl[4].is_a?(String))
  2211. annots<<'/A <</S /URI /URI (' + escape(pl[4]) + ')>>>>';
  2212. else
  2213. l=@links[pl[4]];
  2214. h=!@orientation_changes[l[0]].nil? ? w_pt : h_pt;
  2215. annots<<sprintf('/Dest [%d 0 R /XYZ 0 %.2f null]>>',1+2*l[0], h-l[1]*@k);
  2216. end
  2217. end
  2218. out(annots + ']');
  2219. end
  2220. out('/Contents ' + (@n+1).to_s + ' 0 R>>');
  2221. out('endobj');
  2222. #Page content
  2223. p=(@compress) ? gzcompress(@pages[n]) : @pages[n];
  2224. newobj();
  2225. out('<<' + filter + '/Length '+ p.length.to_s + '>>');
  2226. putstream(p);
  2227. out('endobj');
  2228. end
  2229. #Pages root
  2230. @offsets[1]=@buffer.length;
  2231. out('1 0 obj');
  2232. out('<</Type /Pages');
  2233. kids='/Kids [';
  2234. 0.upto(nb) do |i|
  2235. kids<<(3+2*i).to_s + ' 0 R ';
  2236. end
  2237. out(kids + ']');
  2238. out('/Count ' + nb.to_s);
  2239. out(sprintf('/MediaBox [0 0 %.2f %.2f]', w_pt, h_pt));
  2240. out('>>');
  2241. out('endobj');
  2242. end
  2243. #
  2244. # Adds fonts
  2245. # putfonts
  2246. # @access protected
  2247. #
  2248. def putfonts()
  2249. nf=@n;
  2250. @diffs.each do |diff|
  2251. #Encodings
  2252. newobj();
  2253. out('<</Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences [' + diff + ']>>');
  2254. out('endobj');
  2255. end
  2256. @font_files.each do |file, info|
  2257. #Font file embedding
  2258. newobj();
  2259. @font_files[file]['n']=@n;
  2260. font='';
  2261. open(getfontpath(file),'rb') do |f|
  2262. font = f.read();
  2263. end
  2264. compressed=(file[-2,2]=='.z');
  2265. if (!compressed && !info['length2'].nil?)
  2266. header=((font[0][0])==128);
  2267. if (header)
  2268. #Strip first binary header
  2269. font=font[6];
  2270. end
  2271. if header && (font[info['length1']][0] == 128)
  2272. #Strip second binary header
  2273. font=font[0..info['length1']] + font[info['length1']+6];
  2274. end
  2275. end
  2276. out('<</Length '+ font.length.to_s);
  2277. if (compressed)
  2278. out('/Filter /FlateDecode');
  2279. end
  2280. out('/Length1 ' + info['length1'].to_s);
  2281. if (!info['length2'].nil?)
  2282. out('/Length2 ' + info['length2'].to_s + ' /Length3 0');
  2283. end
  2284. out('>>');
  2285. open(getfontpath(file),'rb') do |f|
  2286. putstream(font)
  2287. end
  2288. out('endobj');
  2289. end
  2290. @fonts.each do |k, font|
  2291. #Font objects
  2292. @fonts[k]['n']=@n+1;
  2293. type = font['type'];
  2294. name = font['name'];
  2295. if (type=='core')
  2296. #Standard font
  2297. newobj();
  2298. out('<</Type /Font');
  2299. out('/BaseFont /' + name);
  2300. out('/Subtype /Type1');
  2301. if (name!='Symbol' && name!='ZapfDingbats')
  2302. out('/Encoding /WinAnsiEncoding');
  2303. end
  2304. out('>>');
  2305. out('endobj');
  2306. elsif type == 'Type0'
  2307. putType0(font)
  2308. elsif (type=='Type1' || type=='TrueType')
  2309. #Additional Type1 or TrueType font
  2310. newobj();
  2311. out('<</Type /Font');
  2312. out('/BaseFont /' + name);
  2313. out('/Subtype /' + type);
  2314. out('/FirstChar 32 /LastChar 255');
  2315. out('/Widths ' + (@n+1).to_s + ' 0 R');
  2316. out('/FontDescriptor ' + (@n+2).to_s + ' 0 R');
  2317. if (font['enc'])
  2318. if (!font['diff'].nil?)
  2319. out('/Encoding ' + (nf+font['diff']).to_s + ' 0 R');
  2320. else
  2321. out('/Encoding /WinAnsiEncoding');
  2322. end
  2323. end
  2324. out('>>');
  2325. out('endobj');
  2326. #Widths
  2327. newobj();
  2328. cw=font['cw']; # &
  2329. s='[';
  2330. 32.upto(255) do |i|
  2331. s << cw[i.chr] + ' ';
  2332. end
  2333. out(s + ']');
  2334. out('endobj');
  2335. #Descriptor
  2336. newobj();
  2337. s='<</Type /FontDescriptor /FontName /' + name;
  2338. font['desc'].each do |k, v|
  2339. s<<' /' + k + ' ' + v;
  2340. end
  2341. file = font['file'];
  2342. if (file)
  2343. s<<' /FontFile' + (type=='Type1' ? '' : '2') + ' ' + @font_files[file]['n'] + ' 0 R';
  2344. end
  2345. out(s + '>>');
  2346. out('endobj');
  2347. else
  2348. #Allow for additional types
  2349. mtd='put' + type.downcase;
  2350. if (!self.respond_to?(mtd))
  2351. Error('Unsupported font type: ' + type)
  2352. else
  2353. self.send(mtd,font)
  2354. end
  2355. end
  2356. end
  2357. end
  2358. def putType0(font)
  2359. #Type0
  2360. newobj();
  2361. out('<</Type /Font')
  2362. out('/Subtype /Type0')
  2363. out('/BaseFont /'+font['name']+'-'+font['cMap'])
  2364. out('/Encoding /'+font['cMap'])
  2365. out('/DescendantFonts ['+(@n+1).to_s+' 0 R]')
  2366. out('>>')
  2367. out('endobj')
  2368. #CIDFont
  2369. newobj()
  2370. out('<</Type /Font')
  2371. out('/Subtype /CIDFontType0')
  2372. out('/BaseFont /'+font['name'])
  2373. out('/CIDSystemInfo <</Registry (Adobe) /Ordering ('+font['registry']['ordering']+') /Supplement '+font['registry']['supplement'].to_s+'>>')
  2374. out('/FontDescriptor '+(@n+1).to_s+' 0 R')
  2375. w='/W [1 ['
  2376. font['cw'].keys.sort.each {|key|
  2377. w+=font['cw'][key].to_s + " "
  2378. # ActionController::Base::logger.debug key.to_s
  2379. # ActionController::Base::logger.debug font['cw'][key].to_s
  2380. }
  2381. out(w+'] 231 325 500 631 [500] 326 389 500]')
  2382. out('>>')
  2383. out('endobj')
  2384. #Font descriptor
  2385. newobj()
  2386. out('<</Type /FontDescriptor')
  2387. out('/FontName /'+font['name'])
  2388. out('/Flags 6')
  2389. out('/FontBBox [0 -200 1000 900]')
  2390. out('/ItalicAngle 0')
  2391. out('/Ascent 800')
  2392. out('/Descent -200')
  2393. out('/CapHeight 800')
  2394. out('/StemV 60')
  2395. out('>>')
  2396. out('endobj')
  2397. end
  2398. #
  2399. # putimages
  2400. # @access protected
  2401. #
  2402. def putimages()
  2403. filter=(@compress) ? '/Filter /FlateDecode ' : '';
  2404. @images.each do |file, info| # was while(list(file, info)=each(@images))
  2405. newobj();
  2406. @images[file]['n']=@n;
  2407. out('<</Type /XObject');
  2408. out('/Subtype /Image');
  2409. out('/Width ' + info['w'].to_s);
  2410. out('/Height ' + info['h'].to_s);
  2411. if (info['cs']=='Indexed')
  2412. out('/ColorSpace [/Indexed /DeviceRGB ' + (info['pal'].length/3-1).to_s + ' ' + (@n+1).to_s + ' 0 R]');
  2413. else
  2414. out('/ColorSpace /' + info['cs']);
  2415. if (info['cs']=='DeviceCMYK')
  2416. out('/Decode [1 0 1 0 1 0 1 0]');
  2417. end
  2418. end
  2419. out('/BitsPerComponent ' + info['bpc'].to_s);
  2420. if (!info['f'].nil?)
  2421. out('/Filter /' + info['f']);
  2422. end
  2423. if (!info['parms'].nil?)
  2424. out(info['parms']);
  2425. end
  2426. if (!info['trns'].nil? and info['trns'].kind_of?(Array))
  2427. trns='';
  2428. 0.upto(info['trns'].length) do |i|
  2429. trns << ("#{info['trns'][i]} " * 2);
  2430. end
  2431. out('/Mask [' + trns + ']');
  2432. end
  2433. out('/Length ' + info['data'].length.to_s + '>>');
  2434. putstream(info['data']);
  2435. @images[file]['data']=nil
  2436. out('endobj');
  2437. #Palette
  2438. if (info['cs']=='Indexed')
  2439. newobj();
  2440. pal=(@compress) ? gzcompress(info['pal']) : info['pal'];
  2441. out('<<' + filter + '/Length ' + pal.length.to_s + '>>');
  2442. putstream(pal);
  2443. out('endobj');
  2444. end
  2445. end
  2446. end
  2447. #
  2448. # putxobjectdict
  2449. # @access protected
  2450. #
  2451. def putxobjectdict()
  2452. @images.each_value do |image|
  2453. out('/I' + image['i'].to_s + ' ' + image['n'].to_s + ' 0 R');
  2454. end
  2455. end
  2456. #
  2457. # putresourcedict
  2458. # @access protected
  2459. #
  2460. def putresourcedict()
  2461. out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
  2462. out('/Font <<');
  2463. @fonts.each_value do |font|
  2464. out('/F' + font['i'].to_s + ' ' + font['n'].to_s + ' 0 R');
  2465. end
  2466. out('>>');
  2467. out('/XObject <<');
  2468. putxobjectdict();
  2469. out('>>');
  2470. end
  2471. #
  2472. # putresources
  2473. # @access protected
  2474. #
  2475. def putresources()
  2476. putfonts();
  2477. putimages();
  2478. #Resource dictionary
  2479. @offsets[2]=@buffer.length;
  2480. out('2 0 obj');
  2481. out('<<');
  2482. putresourcedict();
  2483. out('>>');
  2484. out('endobj');
  2485. end
  2486. #
  2487. # putinfo
  2488. # @access protected
  2489. #
  2490. def putinfo()
  2491. out('/Producer ' + textstring(PDF_PRODUCER));
  2492. if (!@title.nil?)
  2493. out('/Title ' + textstring(@title));
  2494. end
  2495. if (!@subject.nil?)
  2496. out('/Subject ' + textstring(@subject));
  2497. end
  2498. if (!@author.nil?)
  2499. out('/Author ' + textstring(@author));
  2500. end
  2501. if (!@keywords.nil?)
  2502. out('/Keywords ' + textstring(@keywords));
  2503. end
  2504. if (!@creator.nil?)
  2505. out('/Creator ' + textstring(@creator));
  2506. end
  2507. out('/CreationDate ' + textstring('D:' + Time.now.strftime('%Y%m%d%H%M%S')));
  2508. end
  2509. #
  2510. # putcatalog
  2511. # @access protected
  2512. #
  2513. def putcatalog()
  2514. out('/Type /Catalog');
  2515. out('/Pages 1 0 R');
  2516. if (@zoom_mode=='fullpage')
  2517. out('/OpenAction [3 0 R /Fit]');
  2518. elsif (@zoom_mode=='fullwidth')
  2519. out('/OpenAction [3 0 R /FitH null]');
  2520. elsif (@zoom_mode=='real')
  2521. out('/OpenAction [3 0 R /XYZ null null 1]');
  2522. elsif (!@zoom_mode.is_a?(String))
  2523. out('/OpenAction [3 0 R /XYZ null null ' + (@zoom_mode/100) + ']');
  2524. end
  2525. if (@layout_mode=='single')
  2526. out('/PageLayout /SinglePage');
  2527. elsif (@layout_mode=='continuous')
  2528. out('/PageLayout /OneColumn');
  2529. elsif (@layout_mode=='two')
  2530. out('/PageLayout /TwoColumnLeft');
  2531. end
  2532. end
  2533. #
  2534. # puttrailer
  2535. # @access protected
  2536. #
  2537. def puttrailer()
  2538. out('/Size ' + (@n+1).to_s);
  2539. out('/Root ' + @n.to_s + ' 0 R');
  2540. out('/Info ' + (@n-1).to_s + ' 0 R');
  2541. end
  2542. #
  2543. # putheader
  2544. # @access protected
  2545. #
  2546. def putheader()
  2547. out('%PDF-' + @pdf_version);
  2548. end
  2549. #
  2550. # enddoc
  2551. # @access protected
  2552. #
  2553. def enddoc()
  2554. putheader();
  2555. putpages();
  2556. putresources();
  2557. #Info
  2558. newobj();
  2559. out('<<');
  2560. putinfo();
  2561. out('>>');
  2562. out('endobj');
  2563. #Catalog
  2564. newobj();
  2565. out('<<');
  2566. putcatalog();
  2567. out('>>');
  2568. out('endobj');
  2569. #Cross-ref
  2570. o=@buffer.length;
  2571. out('xref');
  2572. out('0 ' + (@n+1).to_s);
  2573. out('0000000000 65535 f ');
  2574. 1.upto(@n) do |i|
  2575. out(sprintf('%010d 00000 n ',@offsets[i]));
  2576. end
  2577. #Trailer
  2578. out('trailer');
  2579. out('<<');
  2580. puttrailer();
  2581. out('>>');
  2582. out('startxref');
  2583. out(o);
  2584. out('%%EOF');
  2585. @state=3;
  2586. end
  2587. #
  2588. # beginpage
  2589. # @access protected
  2590. #
  2591. def beginpage(orientation)
  2592. @page += 1;
  2593. @pages[@page]='';
  2594. @state=2;
  2595. @x=@l_margin;
  2596. @y=@t_margin;
  2597. @font_family='';
  2598. #Page orientation
  2599. if (orientation.empty?)
  2600. orientation=@def_orientation;
  2601. else
  2602. orientation.upcase!
  2603. if (orientation!=@def_orientation)
  2604. @orientation_changes[@page]=true;
  2605. end
  2606. end
  2607. if (orientation!=@cur_orientation)
  2608. #Change orientation
  2609. if (orientation=='P')
  2610. @w_pt=@fw_pt;
  2611. @h_pt=@fh_pt;
  2612. @w=@fw;
  2613. @h=@fh;
  2614. else
  2615. @w_pt=@fh_pt;
  2616. @h_pt=@fw_pt;
  2617. @w=@fh;
  2618. @h=@fw;
  2619. end
  2620. @page_break_trigger=@h-@b_margin;
  2621. @cur_orientation = orientation;
  2622. end
  2623. end
  2624. #
  2625. # End of page contents
  2626. # @access protected
  2627. #
  2628. def endpage()
  2629. @state=1;
  2630. end
  2631. #
  2632. # Begin a new object
  2633. # @access protected
  2634. #
  2635. def newobj()
  2636. @n += 1;
  2637. @offsets[@n]=@buffer.length;
  2638. out(@n.to_s + ' 0 obj');
  2639. end
  2640. #
  2641. # Underline and Deleted text
  2642. # @access protected
  2643. #
  2644. def dolinetxt(x, y, txt)
  2645. up = @current_font['up'];
  2646. ut = @current_font['ut'];
  2647. w = GetStringWidth(txt) + @ws * txt.count(' ');
  2648. sprintf('%.2f %.2f %.2f %.2f re f', x * @k, (@h - (y - up / 1000.0 * @font_size)) * @k, w * @k, -ut / 1000.0 * @font_size_pt);
  2649. end
  2650. #
  2651. # Extract info from a JPEG file
  2652. # @access protected
  2653. #
  2654. def parsejpg(file)
  2655. a=getimagesize(file);
  2656. if (a.empty?)
  2657. Error('Missing or incorrect image file: ' + file);
  2658. end
  2659. if (!a[2].nil? and a[2]!='JPEG')
  2660. Error('Not a JPEG file: ' + file);
  2661. end
  2662. if (a['channels'].nil? or a['channels']==3)
  2663. colspace='DeviceRGB';
  2664. elsif (a['channels']==4)
  2665. colspace='DeviceCMYK';
  2666. else
  2667. colspace='DeviceGray';
  2668. end
  2669. bpc=!a['bits'].nil? ? a['bits'] : 8;
  2670. #Read whole file
  2671. data='';
  2672. open(file,'rb') do |f|
  2673. data<<f.read();
  2674. end
  2675. return {'w' => a[0],'h' => a[1],'cs' => colspace,'bpc' => bpc,'f'=>'DCTDecode','data' => data}
  2676. end
  2677. def imageToPNG(file)
  2678. return unless Object.const_defined?(:Magick)
  2679. img = Magick::ImageList.new(file)
  2680. img.format = 'PNG' # convert to PNG from gif
  2681. img.opacity = 0 # PNG alpha channel delete
  2682. #use a temporary file....
  2683. tmpFile = Tempfile.new(['', '_' + File::basename(file) + '.png'], @@k_path_cache);
  2684. tmpFile.binmode
  2685. tmpFile.print img.to_blob
  2686. tmpFile
  2687. ensure
  2688. tmpFile.close
  2689. end
  2690. #
  2691. # Extract info from a PNG file
  2692. # @access protected
  2693. #
  2694. def parsepng(file)
  2695. f=open(file,'rb');
  2696. #Check signature
  2697. if (f.read(8)!=137.chr + 'PNG' + 13.chr + 10.chr + 26.chr + 10.chr)
  2698. Error('Not a PNG file: ' + file);
  2699. end
  2700. #Read header chunk
  2701. f.read(4);
  2702. if (f.read(4)!='IHDR')
  2703. Error('Incorrect PNG file: ' + file);
  2704. end
  2705. w=freadint(f);
  2706. h=freadint(f);
  2707. bpc=f.read(1).unpack('C')[0];
  2708. if (bpc>8)
  2709. Error('16-bit depth not supported: ' + file);
  2710. end
  2711. ct=f.read(1).unpack('C')[0];
  2712. if (ct==0)
  2713. colspace='DeviceGray';
  2714. elsif (ct==2)
  2715. colspace='DeviceRGB';
  2716. elsif (ct==3)
  2717. colspace='Indexed';
  2718. else
  2719. Error('Alpha channel not supported: ' + file);
  2720. end
  2721. if (f.read(1).unpack('C')[0] != 0)
  2722. Error('Unknown compression method: ' + file);
  2723. end
  2724. if (f.read(1).unpack('C')[0] != 0)
  2725. Error('Unknown filter method: ' + file);
  2726. end
  2727. if (f.read(1).unpack('C')[0] != 0)
  2728. Error('Interlacing not supported: ' + file);
  2729. end
  2730. f.read(4);
  2731. parms='/DecodeParms <</Predictor 15 /Colors ' + (ct==2 ? 3 : 1).to_s + ' /BitsPerComponent ' + bpc.to_s + ' /Columns ' + w.to_s + '>>';
  2732. #Scan chunks looking for palette, transparency and image data
  2733. pal='';
  2734. trns='';
  2735. data='';
  2736. begin
  2737. n=freadint(f);
  2738. type=f.read(4);
  2739. if (type=='PLTE')
  2740. #Read palette
  2741. pal=f.read( n);
  2742. f.read(4);
  2743. elsif (type=='tRNS')
  2744. #Read transparency info
  2745. t=f.read( n);
  2746. if (ct==0)
  2747. trns = t[1].unpack('C')[0]
  2748. elsif (ct==2)
  2749. trns = t[[1].unpack('C')[0], t[3].unpack('C')[0], t[5].unpack('C')[0]]
  2750. else
  2751. pos=t.index(0.chr);
  2752. unless (pos.nil?)
  2753. trns = [pos]
  2754. end
  2755. end
  2756. f.read(4);
  2757. elsif (type=='IDAT')
  2758. #Read image data block
  2759. data<<f.read( n);
  2760. f.read(4);
  2761. elsif (type=='IEND')
  2762. break;
  2763. else
  2764. f.read( n+4);
  2765. end
  2766. end while(n)
  2767. if (colspace=='Indexed' and pal.empty?)
  2768. Error('Missing palette in ' + file);
  2769. end
  2770. return {'w' => w, 'h' => h, 'cs' => colspace, 'bpc' => bpc, 'f'=>'FlateDecode', 'parms' => parms, 'pal' => pal, 'trns' => trns, 'data' => data}
  2771. ensure
  2772. f.close
  2773. end
  2774. #
  2775. # Read a 4-byte integer from file
  2776. # @access protected
  2777. #
  2778. def freadint(f)
  2779. # Read a 4-byte integer from file
  2780. a = f.read(4).unpack('N')
  2781. return a[0]
  2782. end
  2783. #
  2784. # Format a text string
  2785. # @access protected
  2786. #
  2787. def textstring(s)
  2788. if (@is_unicode)
  2789. #Convert string to UTF-16BE
  2790. s = UTF8ToUTF16BE(s, true);
  2791. end
  2792. return '(' + escape(s) + ')';
  2793. end
  2794. #
  2795. # Format a text string
  2796. # @access protected
  2797. #
  2798. def escapetext(s)
  2799. if (@is_unicode)
  2800. #Convert string to UTF-16BE
  2801. s = UTF8ToUTF16BE(s, false);
  2802. end
  2803. return escape(s);
  2804. end
  2805. #
  2806. # Add \ before \, ( and )
  2807. # @access protected
  2808. #
  2809. def escape(s)
  2810. # Add \ before \, ( and )
  2811. s.gsub('\\','\\\\\\').gsub('(','\\(').gsub(')','\\)').gsub(13.chr, '\r')
  2812. end
  2813. #
  2814. #
  2815. # @access protected
  2816. #
  2817. def putstream(s)
  2818. out('stream');
  2819. out(s);
  2820. out('endstream');
  2821. end
  2822. #
  2823. # Add a line to the document
  2824. # @access protected
  2825. #
  2826. def out(s)
  2827. if (@state==2)
  2828. @pages[@page] << s.to_s + "\n";
  2829. else
  2830. @buffer << s.to_s + "\n";
  2831. end
  2832. end
  2833. #
  2834. # Adds unicode fonts.<br>
  2835. # Based on PDF Reference 1.3 (section 5)
  2836. # @access protected
  2837. # @author Nicola Asuni
  2838. # @since 1.52.0.TC005 (2005-01-05)
  2839. #
  2840. def puttruetypeunicode(font)
  2841. # Type0 Font
  2842. # A composite font composed of other fonts, organized hierarchically
  2843. newobj();
  2844. out('<</Type /Font');
  2845. out('/Subtype /Type0');
  2846. out('/BaseFont /' + font['name'] + '');
  2847. out('/Encoding /Identity-H'); #The horizontal identity mapping for 2-byte CIDs; may be used with CIDFonts using any Registry, Ordering, and Supplement values.
  2848. out('/DescendantFonts [' + (@n + 1).to_s + ' 0 R]');
  2849. out('/ToUnicode ' + (@n + 2).to_s + ' 0 R');
  2850. out('>>');
  2851. out('endobj');
  2852. # CIDFontType2
  2853. # A CIDFont whose glyph descriptions are based on TrueType font technology
  2854. newobj();
  2855. out('<</Type /Font');
  2856. out('/Subtype /CIDFontType2');
  2857. out('/BaseFont /' + font['name'] + '');
  2858. out('/CIDSystemInfo ' + (@n + 2).to_s + ' 0 R');
  2859. out('/FontDescriptor ' + (@n + 3).to_s + ' 0 R');
  2860. if (!font['desc']['MissingWidth'].nil?)
  2861. out('/DW ' + font['desc']['MissingWidth'].to_s + ''); # The default width for glyphs in the CIDFont MissingWidth
  2862. end
  2863. w = "";
  2864. font['cw'].each do |cid, width|
  2865. w << '' + cid.to_s + ' [' + width.to_s + '] '; # define a specific width for each individual CID
  2866. end
  2867. out('/W [' + w + ']'); # A description of the widths for the glyphs in the CIDFont
  2868. out('/CIDToGIDMap ' + (@n + 4).to_s + ' 0 R');
  2869. out('>>');
  2870. out('endobj');
  2871. # ToUnicode
  2872. # is a stream object that contains the definition of the CMap
  2873. # (PDF Reference 1.3 chap. 5.9)
  2874. newobj();
  2875. out('<</Length 383>>');
  2876. out('stream');
  2877. out('/CIDInit /ProcSet findresource begin');
  2878. out('12 dict begin');
  2879. out('begincmap');
  2880. out('/CIDSystemInfo');
  2881. out('<</Registry (Adobe)');
  2882. out('/Ordering (UCS)');
  2883. out('/Supplement 0');
  2884. out('>> def');
  2885. out('/CMapName /Adobe-Identity-UCS def');
  2886. out('/CMapType 2 def');
  2887. out('1 begincodespacerange');
  2888. out('<0000> <FFFF>');
  2889. out('endcodespacerange');
  2890. out('1 beginbfrange');
  2891. out('<0000> <FFFF> <0000>');
  2892. out('endbfrange');
  2893. out('endcmap');
  2894. out('CMapName currentdict /CMap defineresource pop');
  2895. out('end');
  2896. out('end');
  2897. out('endstream');
  2898. out('endobj');
  2899. # CIDSystemInfo dictionary
  2900. # A dictionary containing entries that define the character collection of the CIDFont.
  2901. newobj();
  2902. out('<</Registry (Adobe)'); # A string identifying an issuer of character collections
  2903. out('/Ordering (UCS)'); # A string that uniquely names a character collection issued by a specific registry
  2904. out('/Supplement 0'); # The supplement number of the character collection.
  2905. out('>>');
  2906. out('endobj');
  2907. # Font descriptor
  2908. # A font descriptor describing the CIDFont default metrics other than its glyph widths
  2909. newobj();
  2910. out('<</Type /FontDescriptor');
  2911. out('/FontName /' + font['name']);
  2912. font['desc'].each do |key, value|
  2913. out('/' + key.to_s + ' ' + value.to_s);
  2914. end
  2915. if (font['file'])
  2916. # A stream containing a TrueType font program
  2917. out('/FontFile2 ' + @font_files[font['file']]['n'].to_s + ' 0 R');
  2918. end
  2919. out('>>');
  2920. out('endobj');
  2921. # Embed CIDToGIDMap
  2922. # A specification of the mapping from CIDs to glyph indices
  2923. newobj();
  2924. ctgfile = getfontpath(font['ctg'])
  2925. if (!ctgfile)
  2926. Error('Font file not found: ' + ctgfile);
  2927. end
  2928. size = File.size(ctgfile);
  2929. out('<</Length ' + size.to_s + '');
  2930. if (ctgfile[-2,2] == '.z') # check file extension
  2931. # Decompresses data encoded using the public-domain
  2932. # zlib/deflate compression method, reproducing the
  2933. # original text or binary data#
  2934. out('/Filter /FlateDecode');
  2935. end
  2936. out('>>');
  2937. open(ctgfile, "rb") do |f|
  2938. putstream(f.read())
  2939. end
  2940. out('endobj');
  2941. end
  2942. #
  2943. # Converts UTF-8 strings to codepoints array.<br>
  2944. # Invalid byte sequences will be replaced with 0xFFFD (replacement character)<br>
  2945. # Based on: http://www.faqs.org/rfcs/rfc3629.html
  2946. # <pre>
  2947. # Char. number range | UTF-8 octet sequence
  2948. # (hexadecimal) | (binary)
  2949. # --------------------+-----------------------------------------------
  2950. # 0000 0000-0000 007F | 0xxxxxxx
  2951. # 0000 0080-0000 07FF | 110xxxxx 10xxxxxx
  2952. # 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
  2953. # 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  2954. # ---------------------------------------------------------------------
  2955. #
  2956. # ABFN notation:
  2957. # ---------------------------------------------------------------------
  2958. # UTF8-octets =#( UTF8-char )
  2959. # UTF8-char = UTF8-1 / UTF8-2 / UTF8-3 / UTF8-4
  2960. # UTF8-1 = %x00-7F
  2961. # UTF8-2 = %xC2-DF UTF8-tail
  2962. #
  2963. # UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) /
  2964. # %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail )
  2965. # UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) /
  2966. # %xF4 %x80-8F 2( UTF8-tail )
  2967. # UTF8-tail = %x80-BF
  2968. # ---------------------------------------------------------------------
  2969. # </pre>
  2970. # @param string :str string to process.
  2971. # @return array containing codepoints (UTF-8 characters values)
  2972. # @access protected
  2973. # @author Nicola Asuni
  2974. # @since 1.53.0.TC005 (2005-01-05)
  2975. #
  2976. def UTF8StringToArray(str)
  2977. if (!@is_unicode)
  2978. return str; # string is not in unicode
  2979. end
  2980. unicode = [] # array containing unicode values
  2981. bytes = [] # array containing single character byte sequences
  2982. numbytes = 1; # number of octetc needed to represent the UTF-8 character
  2983. str = str.to_s; # force :str to be a string
  2984. str.each_byte do |char|
  2985. if (bytes.length == 0) # get starting octect
  2986. if (char <= 0x7F)
  2987. unicode << char # use the character "as is" because is ASCII
  2988. numbytes = 1
  2989. elsif ((char >> 0x05) == 0x06) # 2 bytes character (0x06 = 110 BIN)
  2990. bytes << ((char - 0xC0) << 0x06)
  2991. numbytes = 2
  2992. elsif ((char >> 0x04) == 0x0E) # 3 bytes character (0x0E = 1110 BIN)
  2993. bytes << ((char - 0xE0) << 0x0C)
  2994. numbytes = 3
  2995. elsif ((char >> 0x03) == 0x1E) # 4 bytes character (0x1E = 11110 BIN)
  2996. bytes << ((char - 0xF0) << 0x12)
  2997. numbytes = 4
  2998. else
  2999. # use replacement character for other invalid sequences
  3000. unicode << 0xFFFD
  3001. bytes = []
  3002. numbytes = 1
  3003. end
  3004. elsif ((char >> 0x06) == 0x02) # bytes 2, 3 and 4 must start with 0x02 = 10 BIN
  3005. bytes << (char - 0x80)
  3006. if (bytes.length == numbytes)
  3007. # compose UTF-8 bytes to a single unicode value
  3008. char = bytes[0]
  3009. 1.upto(numbytes-1) do |j|
  3010. char += (bytes[j] << ((numbytes - j - 1) * 0x06))
  3011. end
  3012. if (((char >= 0xD800) and (char <= 0xDFFF)) or (char >= 0x10FFFF))
  3013. # The definition of UTF-8 prohibits encoding character numbers between
  3014. # U+D800 and U+DFFF, which are reserved for use with the UTF-16
  3015. # encoding form (as surrogate pairs) and do not directly represent
  3016. # characters
  3017. unicode << 0xFFFD; # use replacement character
  3018. else
  3019. unicode << char; # add char to array
  3020. end
  3021. # reset data for next char
  3022. bytes = []
  3023. numbytes = 1;
  3024. end
  3025. else
  3026. # use replacement character for other invalid sequences
  3027. unicode << 0xFFFD;
  3028. bytes = []
  3029. numbytes = 1;
  3030. end
  3031. end
  3032. return unicode;
  3033. end
  3034. #
  3035. # Converts UTF-8 strings to UTF16-BE.<br>
  3036. # Based on: http://www.faqs.org/rfcs/rfc2781.html
  3037. # <pre>
  3038. # Encoding UTF-16:
  3039. #
  3040. # Encoding of a single character from an ISO 10646 character value to
  3041. # UTF-16 proceeds as follows. Let U be the character number, no greater
  3042. # than 0x10FFFF.
  3043. #
  3044. # 1) If U < 0x10000, encode U as a 16-bit unsigned integer and
  3045. # terminate.
  3046. #
  3047. # 2) Let U' = U - 0x10000. Because U is less than or equal to 0x10FFFF,
  3048. # U' must be less than or equal to 0xFFFFF. That is, U' can be
  3049. # represented in 20 bits.
  3050. #
  3051. # 3) Initialize two 16-bit unsigned integers, W1 and W2, to 0xD800 and
  3052. # 0xDC00, respectively. These integers each have 10 bits free to
  3053. # encode the character value, for a total of 20 bits.
  3054. #
  3055. # 4) Assign the 10 high-order bits of the 20-bit U' to the 10 low-order
  3056. # bits of W1 and the 10 low-order bits of U' to the 10 low-order
  3057. # bits of W2. Terminate.
  3058. #
  3059. # Graphically, steps 2 through 4 look like:
  3060. # U' = yyyyyyyyyyxxxxxxxxxx
  3061. # W1 = 110110yyyyyyyyyy
  3062. # W2 = 110111xxxxxxxxxx
  3063. # </pre>
  3064. # @param string :str string to process.
  3065. # @param boolean :setbom if true set the Byte Order Mark (BOM = 0xFEFF)
  3066. # @return string
  3067. # @access protected
  3068. # @author Nicola Asuni
  3069. # @since 1.53.0.TC005 (2005-01-05)
  3070. # @uses UTF8StringToArray
  3071. #
  3072. def UTF8ToUTF16BE(str, setbom=true)
  3073. if (!@is_unicode)
  3074. return str; # string is not in unicode
  3075. end
  3076. outstr = ""; # string to be returned
  3077. unicode = UTF8StringToArray(str); # array containing UTF-8 unicode values
  3078. numitems = unicode.length;
  3079. if (setbom)
  3080. outstr << "\xFE\xFF"; # Byte Order Mark (BOM)
  3081. end
  3082. unicode.each do |char|
  3083. if (char == 0xFFFD)
  3084. outstr << "\xFF\xFD"; # replacement character
  3085. elsif (char < 0x10000)
  3086. outstr << (char >> 0x08).chr;
  3087. outstr << (char & 0xFF).chr;
  3088. else
  3089. char -= 0x10000;
  3090. w1 = 0xD800 | (char >> 0x10);
  3091. w2 = 0xDC00 | (char & 0x3FF);
  3092. outstr << (w1 >> 0x08).chr;
  3093. outstr << (w1 & 0xFF).chr;
  3094. outstr << (w2 >> 0x08).chr;
  3095. outstr << (w2 & 0xFF).chr;
  3096. end
  3097. end
  3098. return outstr;
  3099. end
  3100. # ====================================================
  3101. #
  3102. # Set header font.
  3103. # @param array :font font
  3104. # @since 1.1
  3105. #
  3106. def SetHeaderFont(font)
  3107. @header_font = font;
  3108. end
  3109. alias_method :set_header_font, :SetHeaderFont
  3110. #
  3111. # Set footer font.
  3112. # @param array :font font
  3113. # @since 1.1
  3114. #
  3115. def SetFooterFont(font)
  3116. @footer_font = font;
  3117. end
  3118. alias_method :set_footer_font, :SetFooterFont
  3119. #
  3120. # Set language array.
  3121. # @param array :language
  3122. # @since 1.1
  3123. #
  3124. def SetLanguageArray(language)
  3125. @l = language;
  3126. end
  3127. alias_method :set_language_array, :SetLanguageArray
  3128. #
  3129. # Set document barcode.
  3130. # @param string :bc barcode
  3131. #
  3132. def SetBarcode(bc="")
  3133. @barcode = bc;
  3134. end
  3135. #
  3136. # Print Barcode.
  3137. # @param int :x x position in user units
  3138. # @param int :y y position in user units
  3139. # @param int :w width in user units
  3140. # @param int :h height position in user units
  3141. # @param string :type type of barcode (I25, C128A, C128B, C128C, C39)
  3142. # @param string :style barcode style
  3143. # @param string :font font for text
  3144. # @param int :xres x resolution
  3145. # @param string :code code to print
  3146. #
  3147. def writeBarcode(x, y, w, h, type, style, font, xres, code)
  3148. require(File.dirname(__FILE__) + "/barcode/barcode.rb");
  3149. require(File.dirname(__FILE__) + "/barcode/i25object.rb");
  3150. require(File.dirname(__FILE__) + "/barcode/c39object.rb");
  3151. require(File.dirname(__FILE__) + "/barcode/c128aobject.rb");
  3152. require(File.dirname(__FILE__) + "/barcode/c128bobject.rb");
  3153. require(File.dirname(__FILE__) + "/barcode/c128cobject.rb");
  3154. if (code.empty?)
  3155. return;
  3156. end
  3157. if (style.empty?)
  3158. style = BCS_ALIGN_LEFT;
  3159. style |= BCS_IMAGE_PNG;
  3160. style |= BCS_TRANSPARENT;
  3161. #:style |= BCS_BORDER;
  3162. #:style |= BCS_DRAW_TEXT;
  3163. #:style |= BCS_STRETCH_TEXT;
  3164. #:style |= BCS_REVERSE_COLOR;
  3165. end
  3166. if (font.empty?) then font = BCD_DEFAULT_FONT; end
  3167. if (xres.empty?) then xres = BCD_DEFAULT_XRES; end
  3168. scale_factor = 1.5 * xres * @k;
  3169. bc_w = (w * scale_factor).round #width in points
  3170. bc_h = (h * scale_factor).round #height in points
  3171. case (type.upcase)
  3172. when "I25"
  3173. obj = I25Object.new(bc_w, bc_h, style, code);
  3174. when "C128A"
  3175. obj = C128AObject.new(bc_w, bc_h, style, code);
  3176. when "C128B"
  3177. obj = C128BObject.new(bc_w, bc_h, style, code);
  3178. when "C128C"
  3179. obj = C128CObject.new(bc_w, bc_h, style, code);
  3180. when "C39"
  3181. obj = C39Object.new(bc_w, bc_h, style, code);
  3182. end
  3183. obj.SetFont(font);
  3184. obj.DrawObject(xres);
  3185. #use a temporary file....
  3186. tmpName = tempnam(@@k_path_cache,'img');
  3187. imagepng(obj.getImage(), tmpName);
  3188. Image(tmpName, x, y, w, h, 'png');
  3189. obj.DestroyObject();
  3190. obj = nil
  3191. unlink(tmpName);
  3192. end
  3193. #
  3194. # Returns the PDF data.
  3195. #
  3196. def GetPDFData()
  3197. if (@state < 3)
  3198. Close();
  3199. end
  3200. return @buffer;
  3201. end
  3202. # --- HTML PARSER FUNCTIONS ---
  3203. #
  3204. # Allows to preserve some HTML formatting.<br />
  3205. # Supports: h1, h2, h3, h4, h5, h6, b, u, i, a, img, p, br, strong, em, ins, del, font, blockquote, li, ul, ol, hr, td, th, tr, table, sup, sub, small
  3206. # @param string :html text to display
  3207. # @param boolean :ln if true add a new line after text (default = true)
  3208. # @param int :fill Indicates if the background must be painted (1) or transparent (0). Default value: 0.
  3209. #
  3210. def writeHTML(html, ln=true, fill=0, h=0)
  3211. @lasth = h if h > 0
  3212. if (@lasth == 0)
  3213. #set row height
  3214. @lasth = @font_size * @@k_cell_height_ratio;
  3215. end
  3216. @href = nil
  3217. @style = "";
  3218. @t_cells = [[]];
  3219. @table_id = 0;
  3220. # pre calculate
  3221. html.split(/(<[^>]+>)/).each do |element|
  3222. if "<" == element[0,1]
  3223. #Tag
  3224. if (element[1, 1] == '/')
  3225. closedHTMLTagCalc(element[2..-2].downcase);
  3226. else
  3227. #Extract attributes
  3228. # get tag name
  3229. tag = element.scan(/([a-zA-Z0-9]*)/).flatten.delete_if {|x| x.length == 0}
  3230. tag = tag[0].to_s.downcase;
  3231. # get attributes
  3232. attr_array = element.scan(/([^=\s]*)=["\']?([^"\']*)["\']?/)
  3233. attrs = {}
  3234. attr_array.each do |name, value|
  3235. attrs[name.downcase] = value;
  3236. end
  3237. openHTMLTagCalc(tag, attrs);
  3238. end
  3239. end
  3240. end
  3241. @table_id = 0;
  3242. html.split(/(<[A-Za-z!?\/][^>]*?>)/).each do |element|
  3243. if "<" == element[0,1]
  3244. #Tag
  3245. if (element[1, 1] == '/')
  3246. closedHTMLTagHandler(element[2..-2].downcase);
  3247. else
  3248. #Extract attributes
  3249. # get tag name
  3250. tag = element.scan(/([a-zA-Z0-9]*)/).flatten.delete_if {|x| x.length == 0}
  3251. tag = tag[0].to_s.downcase;
  3252. # get attributes
  3253. attr_array = element.scan(/([^=\s]*)=["\']?([^"\']*)["\']?/)
  3254. attrs = {}
  3255. attr_array.each do |name, value|
  3256. attrs[name.downcase] = value;
  3257. end
  3258. openHTMLTagHandler(tag, attrs, fill);
  3259. end
  3260. else
  3261. #Text
  3262. if (@tdbegin)
  3263. element.gsub!(/[\t\r\n\f]/, "");
  3264. @tdtext << element.gsub(/&nbsp;/, " ");
  3265. elsif (@href)
  3266. element.gsub!(/[\t\r\n\f]/, "");
  3267. addHtmlLink(@href, element, fill);
  3268. elsif (@pre_state == true and element.length > 0)
  3269. Write(@lasth, unhtmlentities(element), '', fill);
  3270. elsif (element.strip.length > 0)
  3271. element.gsub!(/[\t\r\n\f]/, "");
  3272. element.gsub!(/&nbsp;/, " ");
  3273. Write(@lasth, unhtmlentities(element), '', fill);
  3274. end
  3275. end
  3276. end
  3277. if (ln)
  3278. Ln(@lasth);
  3279. end
  3280. end
  3281. alias_method :write_html, :writeHTML
  3282. #
  3283. # Prints a cell (rectangular area) with optional borders, background color and html text string. The upper-left corner of the cell corresponds to the current position. After the call, the current position moves to the right or to the next line.<br />
  3284. # If automatic page breaking is enabled and the cell goes beyond the limit, a page break is done before outputting.
  3285. # @param float :w Cell width. If 0, the cell extends up to the right margin.
  3286. # @param float :h Cell minimum height. The cell extends automatically if needed.
  3287. # @param float :x upper-left corner X coordinate
  3288. # @param float :y upper-left corner Y coordinate
  3289. # @param string :html html text to print. Default value: empty string.
  3290. # @param mixed :border Indicates if borders must be drawn around the cell. The value can be either a number:<ul><li>0: no border (default)</li><li>1: frame</li></ul>or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
  3291. # @param int :ln Indicates where the current position should go after the call. Possible values are:<ul><li>0: to the right</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>
  3292. # Putting 1 is equivalent to putting 0 and calling Ln() just after. Default value: 0.
  3293. # @param int :fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
  3294. # @see Cell()
  3295. #
  3296. def writeHTMLCell(w, h, x, y, html='', border=0, ln=1, fill=0)
  3297. if (@lasth == 0)
  3298. #set row height
  3299. @lasth = @font_size * @@k_cell_height_ratio;
  3300. end
  3301. if (x == 0)
  3302. x = GetX();
  3303. end
  3304. if (y == 0)
  3305. y = GetY();
  3306. end
  3307. # get current page number
  3308. pagenum = @page;
  3309. SetX(x);
  3310. SetY(y);
  3311. if (w == 0)
  3312. w = @fw - x - @r_margin;
  3313. end
  3314. b=0;
  3315. if (border)
  3316. if (border==1)
  3317. border='LTRB';
  3318. b='LRT';
  3319. b2='LR';
  3320. elsif border.is_a?(String)
  3321. b2='';
  3322. if (border.include?('L'))
  3323. b2<<'L';
  3324. end
  3325. if (border.include?('R'))
  3326. b2<<'R';
  3327. end
  3328. b=(border.include?('T')) ? b2 + 'T' : b2;
  3329. end
  3330. end
  3331. # store original margin values
  3332. l_margin = @l_margin;
  3333. r_margin = @r_margin;
  3334. # set new margin values
  3335. SetLeftMargin(x);
  3336. SetRightMargin(@fw - x - w);
  3337. # calculate remaining vertical space on page
  3338. restspace = GetPageHeight() - GetY() - GetBreakMargin();
  3339. writeHTML(html, true, fill); # write html text
  3340. SetX(x)
  3341. currentY = GetY();
  3342. @auto_page_break = false;
  3343. # check if a new page has been created
  3344. if (@page > pagenum)
  3345. # design a cell around the text on first page
  3346. currentpage = @page;
  3347. @page = pagenum;
  3348. SetY(GetPageHeight() - restspace - GetBreakMargin());
  3349. SetX(x)
  3350. Cell(w, restspace - 1, "", b, 0, 'L', 0);
  3351. b = b2;
  3352. @page += 1;
  3353. while @page < currentpage
  3354. SetY(@t_margin); # put cursor at the beginning of text
  3355. SetX(x)
  3356. Cell(w, @page_break_trigger - @t_margin, "", b, 0, 'L', 0);
  3357. @page += 1;
  3358. end
  3359. if (border.is_a?(String) and border.include?('B'))
  3360. b<<'B';
  3361. end
  3362. # design a cell around the text on last page
  3363. SetY(@t_margin); # put cursor at the beginning of text
  3364. SetX(x)
  3365. Cell(w, currentY - @t_margin, "", b, 0, 'L', 0);
  3366. else
  3367. SetY(y); # put cursor at the beginning of text
  3368. # design a cell around the text
  3369. SetX(x)
  3370. Cell(w, [h, (currentY - y)].max, "", border, 0, 'L', 0);
  3371. end
  3372. @auto_page_break = true;
  3373. # restore original margin values
  3374. SetLeftMargin(l_margin);
  3375. SetRightMargin(r_margin);
  3376. @lasth = h
  3377. # move cursor to specified position
  3378. if (ln == 0)
  3379. # go to the top-right of the cell
  3380. @x = x + w;
  3381. @y = y;
  3382. elsif (ln == 1)
  3383. # go to the beginning of the next line
  3384. @x = @l_margin;
  3385. @y = currentY;
  3386. elsif (ln == 2)
  3387. # go to the bottom-left of the cell (below)
  3388. @x = x;
  3389. @y = currentY;
  3390. end
  3391. end
  3392. alias_method :write_html_cell, :writeHTMLCell
  3393. #
  3394. # Check html table tag position.
  3395. #
  3396. # @param array :table potision array
  3397. # @param int :current tr tag id number
  3398. # @param int :current td tag id number
  3399. # @access private
  3400. # @return int : next td_id position.
  3401. # value 0 mean that can use position.
  3402. #
  3403. def checkTableBlockingCellPosition(table, tr_id, td_id )
  3404. 0.upto(tr_id) do |j|
  3405. 0.upto(@t_cells[table][j].size - 1) do |i|
  3406. if @t_cells[table][j][i]['i0'] <= td_id and td_id <= @t_cells[table][j][i]['i1']
  3407. if @t_cells[table][j][i]['j0'] <= tr_id and tr_id <= @t_cells[table][j][i]['j1']
  3408. return @t_cells[table][j][i]['i1'] - td_id + 1;
  3409. end
  3410. end
  3411. end
  3412. end
  3413. return 0;
  3414. end
  3415. #
  3416. # Calculate opening tags.
  3417. #
  3418. # html table cell array : @t_cells
  3419. #
  3420. # i0: table cell start position
  3421. # i1: table cell end position
  3422. # j0: table row start position
  3423. # j1: table row end position
  3424. #
  3425. # +------+
  3426. # |i0,j0 |
  3427. # | i1,j1|
  3428. # +------+
  3429. #
  3430. # example html:
  3431. # <table>
  3432. # <tr><td></td><td></td><td></td></tr>
  3433. # <tr><td colspan=2></td><td></td></tr>
  3434. # <tr><td rowspan=2></td><td></td><td></td></tr>
  3435. # <tr><td></td><td></td></tr>
  3436. # </table>
  3437. #
  3438. # i: 0 1 2
  3439. # j+----+----+----+
  3440. # :|0,0 |1,0 |2,0 |
  3441. # 0| 0,0| 1,0| 2,0|
  3442. # +----+----+----+
  3443. # |0,1 |2,1 |
  3444. # 1| 1,1| 2,1|
  3445. # +----+----+----+
  3446. # |0,2 |1,2 |2,2 |
  3447. # 2| | 1,2| 2,2|
  3448. # + +----+----+
  3449. # | |1,3 |2,3 |
  3450. # 3| 0,3| 1,3| 2,3|
  3451. # +----+----+----+
  3452. #
  3453. # html table cell array :
  3454. # [[[i0=>0,j0=>0,i1=>0,j1=>0],[i0=>1,j0=>0,i1=>1,j1=>0],[i0=>2,j0=>0,i1=>2,j1=>0]],
  3455. # [[i0=>0,j0=>1,i1=>1,j1=>1],[i0=>2,j0=>1,i1=>2,j1=>1]],
  3456. # [[i0=>0,j0=>2,i1=>0,j1=>3],[i0=>1,j0=>2,i1=>1,j1=>2],[i0=>2,j0=>2,i1=>2,j1=>2]]
  3457. # [[i0=>1,j0=>3,i1=>1,j1=>3],[i0=>2,j0=>3,i1=>2,j1=>3]]]
  3458. #
  3459. # @param string :tag tag name (in upcase)
  3460. # @param string :attr tag attribute (in upcase)
  3461. # @access private
  3462. #
  3463. def openHTMLTagCalc(tag, attrs)
  3464. #Opening tag
  3465. case (tag)
  3466. when 'table'
  3467. @max_table_columns[@table_id] = 0;
  3468. @t_columns = 0;
  3469. @tr_id = -1;
  3470. when 'tr'
  3471. if @max_table_columns[@table_id] < @t_columns
  3472. @max_table_columns[@table_id] = @t_columns;
  3473. end
  3474. @t_columns = 0;
  3475. @tr_id += 1;
  3476. @td_id = -1;
  3477. @t_cells[@table_id].push []
  3478. when 'td', 'th'
  3479. @td_id += 1;
  3480. if attrs['colspan'].nil? or attrs['colspan'] == ''
  3481. colspan = 1;
  3482. else
  3483. colspan = attrs['colspan'].to_i;
  3484. end
  3485. if attrs['rowspan'].nil? or attrs['rowspan'] == ''
  3486. rowspan = 1;
  3487. else
  3488. rowspan = attrs['rowspan'].to_i;
  3489. end
  3490. i = 0;
  3491. while true
  3492. next_i_distance = checkTableBlockingCellPosition(@table_id, @tr_id, @td_id + i);
  3493. if next_i_distance == 0
  3494. @t_cells[@table_id][@tr_id].push "i0"=>@td_id + i, "j0"=>@tr_id, "i1"=>(@td_id + i + colspan - 1), "j1"=>@tr_id + rowspan - 1
  3495. break;
  3496. end
  3497. i += next_i_distance;
  3498. end
  3499. @t_columns += colspan;
  3500. end
  3501. end
  3502. #
  3503. # Calculate closing tags.
  3504. # @param string :tag tag name (in upcase)
  3505. # @access private
  3506. #
  3507. def closedHTMLTagCalc(tag)
  3508. #Closing tag
  3509. case (tag)
  3510. when 'table'
  3511. if @max_table_columns[@table_id] < @t_columns
  3512. @max_table_columns[@table_id] = @t_columns;
  3513. end
  3514. @table_id += 1;
  3515. @t_cells.push []
  3516. end
  3517. end
  3518. #
  3519. # Convert to accessible file path
  3520. # @param string :attrname image file name
  3521. #
  3522. def getImageFilename( attrname )
  3523. nil
  3524. end
  3525. #
  3526. # Process opening tags.
  3527. # @param string :tag tag name (in upcase)
  3528. # @param string :attr tag attribute (in upcase)
  3529. # @param int :fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
  3530. # @access private
  3531. #
  3532. def openHTMLTagHandler(tag, attrs, fill=0)
  3533. #Opening tag
  3534. case (tag)
  3535. when 'pre'
  3536. @pre_state = true;
  3537. @l_margin += 5;
  3538. @r_margin += 5;
  3539. @x += 5;
  3540. when 'table'
  3541. Ln();
  3542. if @default_table_columns < @max_table_columns[@table_id]
  3543. @table_columns = @max_table_columns[@table_id];
  3544. else
  3545. @table_columns = @default_table_columns;
  3546. end
  3547. @l_margin += 5;
  3548. @r_margin += 5;
  3549. @x += 5;
  3550. if attrs['border'].nil? or attrs['border'] == ''
  3551. @tableborder = 0;
  3552. else
  3553. @tableborder = attrs['border'];
  3554. end
  3555. @tr_id = -1;
  3556. @max_td_page[0] = @page;
  3557. @max_td_y[0] = @y;
  3558. when 'tr', 'td', 'th'
  3559. if tag == 'th'
  3560. SetStyle('b', true);
  3561. @tdalign = "C";
  3562. end
  3563. if ((!attrs['width'].nil?) and (attrs['width'] != ''))
  3564. @tdwidth = (attrs['width'].to_i/4);
  3565. else
  3566. @tdwidth = ((@w - @l_margin - @r_margin) / @table_columns);
  3567. end
  3568. if tag == 'tr'
  3569. @tr_id += 1;
  3570. @td_id = -1;
  3571. else
  3572. @td_id += 1;
  3573. @x = @l_margin + @tdwidth * @t_cells[@table_id][@tr_id][@td_id]['i0'];
  3574. end
  3575. if attrs['colspan'].nil? or attrs['border'] == ''
  3576. @colspan = 1;
  3577. else
  3578. @colspan = attrs['colspan'].to_i;
  3579. end
  3580. @tdwidth *= @colspan;
  3581. if ((!attrs['height'].nil?) and (attrs['height'] != ''))
  3582. @tdheight=(attrs['height'].to_i / @k);
  3583. else
  3584. @tdheight = @lasth;
  3585. end
  3586. if ((!attrs['align'].nil?) and (attrs['align'] != ''))
  3587. case (attrs['align'])
  3588. when 'center'
  3589. @tdalign = "C";
  3590. when 'right'
  3591. @tdalign = "R";
  3592. when 'left'
  3593. @tdalign = "L";
  3594. end
  3595. end
  3596. if ((!attrs['bgcolor'].nil?) and (attrs['bgcolor'] != ''))
  3597. coul = convertColorHexToDec(attrs['bgcolor']);
  3598. SetFillColor(coul['R'], coul['G'], coul['B']);
  3599. @tdfill=1;
  3600. end
  3601. @tdbegin=true;
  3602. when 'hr'
  3603. margin = 1;
  3604. if ((!attrs['width'].nil?) and (attrs['width'] != ''))
  3605. hrWidth = attrs['width'];
  3606. else
  3607. hrWidth = @w - @l_margin - @r_margin - margin;
  3608. end
  3609. SetLineWidth(0.2);
  3610. Line(@x + margin, @y, @x + hrWidth, @y);
  3611. Ln();
  3612. when 'strong'
  3613. SetStyle('b', true);
  3614. when 'em'
  3615. SetStyle('i', true);
  3616. when 'ins'
  3617. SetStyle('u', true);
  3618. when 'del'
  3619. SetStyle('d', true);
  3620. when 'b', 'i', 'u'
  3621. SetStyle(tag, true);
  3622. when 'a'
  3623. @href = attrs['href'];
  3624. when 'img'
  3625. if (!attrs['src'].nil?)
  3626. # Don't generates image inside table tag
  3627. if (@tdbegin)
  3628. @tdtext << attrs['src'];
  3629. return
  3630. end
  3631. # Only generates image include a pdf if RMagick is avalaible
  3632. unless Object.const_defined?(:Magick)
  3633. Write(@lasth, attrs['src'], '', fill);
  3634. return
  3635. end
  3636. file = getImageFilename(attrs['src'])
  3637. if (file.nil?)
  3638. Write(@lasth, attrs['src'], '', fill);
  3639. return
  3640. end
  3641. if (attrs['width'].nil?)
  3642. attrs['width'] = 0;
  3643. end
  3644. if (attrs['height'].nil?)
  3645. attrs['height'] = 0;
  3646. end
  3647. begin
  3648. Image(file, GetX(),GetY(), pixelsToMillimeters(attrs['width']), pixelsToMillimeters(attrs['height']));
  3649. #SetX(@img_rb_x);
  3650. SetY(@img_rb_y);
  3651. rescue => err
  3652. logger.error "pdf: Image: error: #{err.message}"
  3653. Write(@lasth, attrs['src'], '', fill);
  3654. end
  3655. end
  3656. when 'ul', 'ol'
  3657. if @li_count == 0
  3658. Ln() if @prevquote_count == @quote_count; # insert Ln for keeping quote lines
  3659. @prevquote_count = @quote_count;
  3660. end
  3661. if @li_state == true
  3662. Ln();
  3663. @li_state = false;
  3664. end
  3665. if tag == 'ul'
  3666. @list_ordered[@li_count] = false;
  3667. else
  3668. @list_ordered[@li_count] = true;
  3669. end
  3670. @list_count[@li_count] = 0;
  3671. @li_count += 1
  3672. when 'li'
  3673. Ln() if @li_state == true
  3674. if (@list_ordered[@li_count - 1])
  3675. @list_count[@li_count - 1] += 1;
  3676. @li_spacer = " " * @li_count + (@list_count[@li_count - 1]).to_s + ". ";
  3677. else
  3678. #unordered list simbol
  3679. @li_spacer = " " * @li_count + "- ";
  3680. end
  3681. Write(@lasth, @spacer + @li_spacer, '', fill);
  3682. @li_state = true;
  3683. when 'blockquote'
  3684. if (@quote_count == 0)
  3685. SetStyle('i', true);
  3686. @l_margin += 5;
  3687. else
  3688. @l_margin += 5 / 2;
  3689. end
  3690. @x = @l_margin;
  3691. @quote_top[@quote_count] = @y;
  3692. @quote_page[@quote_count] = @page;
  3693. @quote_count += 1
  3694. when 'br'
  3695. Ln();
  3696. if (@li_spacer.length > 0)
  3697. @x += GetStringWidth(@li_spacer);
  3698. end
  3699. when 'p'
  3700. Ln();
  3701. 0.upto(@quote_count - 1) do |i|
  3702. if @quote_page[i] == @page;
  3703. if @quote_top[i] == @y - @lasth; # fix start line
  3704. @quote_top[i] = @y;
  3705. end
  3706. else
  3707. if @quote_page[i] == @page - 1;
  3708. @quote_page[i] = @page; # fix start line
  3709. @quote_top[i] = @t_margin;
  3710. end
  3711. end
  3712. end
  3713. when 'sup'
  3714. currentfont_size = @font_size;
  3715. @tempfontsize = @font_size_pt;
  3716. SetFontSize(@font_size_pt * @@k_small_ratio);
  3717. SetXY(GetX(), GetY() - ((currentfont_size - @font_size)*(@@k_small_ratio)));
  3718. when 'sub'
  3719. currentfont_size = @font_size;
  3720. @tempfontsize = @font_size_pt;
  3721. SetFontSize(@font_size_pt * @@k_small_ratio);
  3722. SetXY(GetX(), GetY() + ((currentfont_size - @font_size)*(@@k_small_ratio)));
  3723. when 'small'
  3724. currentfont_size = @font_size;
  3725. @tempfontsize = @font_size_pt;
  3726. SetFontSize(@font_size_pt * @@k_small_ratio);
  3727. SetXY(GetX(), GetY() + ((currentfont_size - @font_size)/3));
  3728. when 'font'
  3729. if (!attrs['color'].nil? and attrs['color']!='')
  3730. coul = convertColorHexToDec(attrs['color']);
  3731. SetTextColor(coul['R'], coul['G'], coul['B']);
  3732. @issetcolor=true;
  3733. end
  3734. if (!attrs['face'].nil? and @fontlist.include?(attrs['face'].downcase))
  3735. SetFont(attrs['face'].downcase);
  3736. @issetfont=true;
  3737. end
  3738. if (!attrs['size'].nil?)
  3739. headsize = attrs['size'].to_i;
  3740. else
  3741. headsize = 0;
  3742. end
  3743. currentfont_size = @font_size;
  3744. @tempfontsize = @font_size_pt;
  3745. SetFontSize(@font_size_pt + headsize);
  3746. @lasth = @font_size * @@k_cell_height_ratio;
  3747. when 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
  3748. Ln();
  3749. headsize = (4 - tag[1,1].to_f) * 2
  3750. @tempfontsize = @font_size_pt;
  3751. SetFontSize(@font_size_pt + headsize);
  3752. SetStyle('b', true);
  3753. @lasth = @font_size * @@k_cell_height_ratio;
  3754. end
  3755. end
  3756. #
  3757. # Process closing tags.
  3758. # @param string :tag tag name (in upcase)
  3759. # @access private
  3760. #
  3761. def closedHTMLTagHandler(tag)
  3762. #Closing tag
  3763. case (tag)
  3764. when 'pre'
  3765. @pre_state = false;
  3766. @l_margin -= 5;
  3767. @r_margin -= 5;
  3768. @x = @l_margin;
  3769. Ln();
  3770. when 'td','th'
  3771. base_page = @page;
  3772. base_x = @x;
  3773. base_y = @y;
  3774. MultiCell(@tdwidth, @tdheight, unhtmlentities(@tdtext.strip), @tableborder, @tdalign, @tdfill, 1);
  3775. tr_end = @t_cells[@table_id][@tr_id][@td_id]['j1'] + 1;
  3776. if @max_td_page[tr_end].nil? or (@max_td_page[tr_end] < @page)
  3777. @max_td_page[tr_end] = @page
  3778. @max_td_y[tr_end] = @y
  3779. elsif (@max_td_page[tr_end] == @page)
  3780. @max_td_y[tr_end] = @y if @max_td_y[tr_end].nil? or (@max_td_y[tr_end] < @y)
  3781. end
  3782. @page = base_page;
  3783. @x = base_x + @tdwidth;
  3784. @y = base_y;
  3785. @tdtext = '';
  3786. @tdbegin = false;
  3787. @tdwidth = 0;
  3788. @tdheight = 0;
  3789. @tdalign = "L";
  3790. SetStyle('b', false);
  3791. @tdfill = 0;
  3792. SetFillColor(@prevfill_color[0], @prevfill_color[1], @prevfill_color[2]);
  3793. when 'tr'
  3794. @y = @max_td_y[@tr_id + 1];
  3795. @x = @l_margin;
  3796. @page = @max_td_page[@tr_id + 1];
  3797. when 'table'
  3798. # Write Table Line
  3799. width = (@w - @l_margin - @r_margin) / @table_columns;
  3800. 0.upto(@t_cells[@table_id].size - 1) do |j|
  3801. 0.upto(@t_cells[@table_id][j].size - 1) do |i|
  3802. @page = @max_td_page[j]
  3803. i0=@t_cells[@table_id][j][i]['i0'];
  3804. j0=@t_cells[@table_id][j][i]['j0'];
  3805. i1=@t_cells[@table_id][j][i]['i1'];
  3806. j1=@t_cells[@table_id][j][i]['j1'];
  3807. Line(@l_margin + width * i0, @max_td_y[j0], @l_margin + width * (i1+1), @max_td_y[j0]) # top
  3808. if ( @page == @max_td_page[j1 + 1])
  3809. Line(@l_margin + width * i0, @max_td_y[j0], @l_margin + width * i0, @max_td_y[j1+1]) # left
  3810. Line(@l_margin + width * (i1+1), @max_td_y[j0], @l_margin + width * (i1+1), @max_td_y[j1+1]) # right
  3811. else
  3812. Line(@l_margin + width * i0, @max_td_y[j0], @l_margin + width * i0, @page_break_trigger) # left
  3813. Line(@l_margin + width * (i1+1), @max_td_y[j0], @l_margin + width * (i1+1), @page_break_trigger) # right
  3814. @page += 1;
  3815. while @page < @max_td_page[j1 + 1]
  3816. Line(@l_margin + width * i0, @t_margin, @l_margin + width * i0, @page_break_trigger) # left
  3817. Line(@l_margin + width * (i1+1), @t_margin, @l_margin + width * (i1+1), @page_break_trigger) # right
  3818. @page += 1;
  3819. end
  3820. Line(@l_margin + width * i0, @t_margin, @l_margin + width * i0, @max_td_y[j1+1]) # left
  3821. Line(@l_margin + width * (i1+1), @t_margin, @l_margin + width * (i1+1), @max_td_y[j1+1]) # right
  3822. end
  3823. Line(@l_margin + width * i0, @max_td_y[j1+1], @l_margin + width * (i1+1), @max_td_y[j1+1]) # bottom
  3824. end
  3825. end
  3826. @l_margin -= 5;
  3827. @r_margin -= 5;
  3828. @tableborder=0;
  3829. @table_id += 1;
  3830. when 'strong'
  3831. SetStyle('b', false);
  3832. when 'em'
  3833. SetStyle('i', false);
  3834. when 'ins'
  3835. SetStyle('u', false);
  3836. when 'del'
  3837. SetStyle('d', false);
  3838. when 'b', 'i', 'u'
  3839. SetStyle(tag, false);
  3840. when 'a'
  3841. @href = nil;
  3842. when 'p'
  3843. Ln();
  3844. when 'sup'
  3845. currentfont_size = @font_size;
  3846. SetFontSize(@tempfontsize);
  3847. @tempfontsize = @font_size_pt;
  3848. SetXY(GetX(), GetY() - ((currentfont_size - @font_size)*(@@k_small_ratio)));
  3849. when 'sub'
  3850. currentfont_size = @font_size;
  3851. SetFontSize(@tempfontsize);
  3852. @tempfontsize = @font_size_pt;
  3853. SetXY(GetX(), GetY() + ((currentfont_size - @font_size)*(@@k_small_ratio)));
  3854. when 'small'
  3855. currentfont_size = @font_size;
  3856. SetFontSize(@tempfontsize);
  3857. @tempfontsize = @font_size_pt;
  3858. SetXY(GetX(), GetY() - ((@font_size - currentfont_size)/3));
  3859. when 'font'
  3860. if (@issetcolor == true)
  3861. SetTextColor(@prevtext_color[0], @prevtext_color[1], @prevtext_color[2]);
  3862. end
  3863. if (@issetfont)
  3864. @font_family = @prevfont_family;
  3865. @font_style = @prevfont_style;
  3866. SetFont(@font_family);
  3867. @issetfont = false;
  3868. end
  3869. currentfont_size = @font_size;
  3870. SetFontSize(@tempfontsize);
  3871. @tempfontsize = @font_size_pt;
  3872. #@text_color = @prevtext_color;
  3873. @lasth = @font_size * @@k_cell_height_ratio;
  3874. when 'blockquote'
  3875. @quote_count -= 1
  3876. if (@quote_page[@quote_count] == @page)
  3877. Line(@l_margin - 1, @quote_top[@quote_count], @l_margin - 1, @y) # quoto line
  3878. else
  3879. cur_page = @page;
  3880. cur_y = @y;
  3881. @page = @quote_page[@quote_count];
  3882. if (@quote_top[@quote_count] < @page_break_trigger)
  3883. Line(@l_margin - 1, @quote_top[@quote_count], @l_margin - 1, @page_break_trigger) # quoto line
  3884. end
  3885. @page += 1;
  3886. while @page < cur_page
  3887. Line(@l_margin - 1, @t_margin, @l_margin - 1, @page_break_trigger) # quoto line
  3888. @page += 1;
  3889. end
  3890. @y = cur_y;
  3891. Line(@l_margin - 1, @t_margin, @l_margin - 1, @y) # quoto line
  3892. end
  3893. if (@quote_count <= 0)
  3894. SetStyle('i', false);
  3895. @l_margin -= 5;
  3896. else
  3897. @l_margin -= 5 / 2;
  3898. end
  3899. @x = @l_margin;
  3900. Ln() if @quote_count == 0
  3901. when 'ul', 'ol'
  3902. @li_count -= 1
  3903. if @li_state == true
  3904. Ln();
  3905. @li_state = false;
  3906. end
  3907. when 'li'
  3908. @li_spacer = "";
  3909. if @li_state == true
  3910. Ln();
  3911. @li_state = false;
  3912. end
  3913. when 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
  3914. SetFontSize(@tempfontsize);
  3915. @tempfontsize = @font_size_pt;
  3916. SetStyle('b', false);
  3917. Ln();
  3918. @lasth = @font_size * @@k_cell_height_ratio;
  3919. if tag == 'h1' or tag == 'h2' or tag == 'h3' or tag == 'h4'
  3920. margin = 1;
  3921. hrWidth = @w - @l_margin - @r_margin - margin;
  3922. if tag == 'h1' or tag == 'h2'
  3923. SetLineWidth(0.2);
  3924. else
  3925. SetLineWidth(0.1);
  3926. end
  3927. Line(@x + margin, @y, @x + hrWidth, @y);
  3928. end
  3929. end
  3930. end
  3931. #
  3932. # Sets font style.
  3933. # @param string :tag tag name (in lowercase)
  3934. # @param boolean :enable
  3935. # @access private
  3936. #
  3937. def SetStyle(tag, enable)
  3938. #Modify style and select corresponding font
  3939. ['b', 'i', 'u', 'd'].each do |s|
  3940. if tag.downcase == s
  3941. if enable
  3942. @style << s if ! @style.include?(s)
  3943. else
  3944. @style = @style.gsub(s,'')
  3945. end
  3946. end
  3947. end
  3948. SetFont('', @style);
  3949. end
  3950. #
  3951. # Output anchor link.
  3952. # @param string :url link URL
  3953. # @param string :name link name
  3954. # @param int :fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
  3955. # @access public
  3956. #
  3957. def addHtmlLink(url, name, fill=0)
  3958. #Put a hyperlink
  3959. SetTextColor(0, 0, 255);
  3960. SetStyle('u', true);
  3961. Write(@lasth, name, url, fill);
  3962. SetStyle('u', false);
  3963. SetTextColor(0);
  3964. end
  3965. #
  3966. # Returns an associative array (keys: R,G,B) from
  3967. # a hex html code (e.g. #3FE5AA).
  3968. # @param string :color hexadecimal html color [#rrggbb]
  3969. # @return array
  3970. # @access private
  3971. #
  3972. def convertColorHexToDec(color = "#000000")
  3973. tbl_color = {}
  3974. tbl_color['R'] = color[1,2].hex.to_i;
  3975. tbl_color['G'] = color[3,2].hex.to_i;
  3976. tbl_color['B'] = color[5,2].hex.to_i;
  3977. return tbl_color;
  3978. end
  3979. #
  3980. # Converts pixels to millimeters in 72 dpi.
  3981. # @param int :px pixels
  3982. # @return float millimeters
  3983. # @access private
  3984. #
  3985. def pixelsToMillimeters(px)
  3986. return px.to_f * 25.4 / 72;
  3987. end
  3988. #
  3989. # Reverse function for htmlentities.
  3990. # Convert entities in UTF-8.
  3991. #
  3992. # @param :text_to_convert Text to convert.
  3993. # @return string converted
  3994. #
  3995. def unhtmlentities(string)
  3996. if @@decoder.nil?
  3997. CGI.unescapeHTML(string)
  3998. else
  3999. @@decoder.decode(string)
  4000. end
  4001. end
  4002. end # END OF CLASS
  4003. #TODO 2007-05-25 (EJM) Level=0 -
  4004. #Handle special IE contype request
  4005. # if (!_SERVER['HTTP_USER_AGENT'].nil? and (_SERVER['HTTP_USER_AGENT']=='contype'))
  4006. # header('Content-Type: application/pdf');
  4007. # exit;
  4008. # }