OSDN Git Service

Wrap long text fields properly in PDF exports (#5629).
[redminele/redmine.git] / lib / redmine / export / pdf.rb
1 # encoding: utf-8
2 #
3 # Redmine - project management software
4 # Copyright (C) 2006-2009  Jean-Philippe Lang
5 #
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License
8 # as published by the Free Software Foundation; either version 2
9 # of the License, or (at your option) any later version.
10
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19
20 require 'iconv'
21 require 'rfpdf/fpdf'
22 require 'fpdf/chinese'
23 require 'fpdf/japanese'
24 require 'fpdf/korean'
25
26 module Redmine
27   module Export
28     module PDF
29       include ActionView::Helpers::TextHelper
30       include ActionView::Helpers::NumberHelper
31       
32       class ITCPDF < TCPDF
33         include Redmine::I18n
34         attr_accessor :footer_date
35         
36         def initialize(lang)
37           super()
38           set_language_if_valid lang
39           @font_for_content = 'FreeSans'
40           @font_for_footer  = 'FreeSans'
41           SetCreator(Redmine::Info.app_name)
42           SetFont(@font_for_content)
43         end
44         
45         def SetFontStyle(style, size)
46           SetFont(@font_for_content, style, size)
47         end
48         
49         def SetTitle(txt)
50           txt = begin
51             utf16txt = Iconv.conv('UTF-16BE', 'UTF-8', txt)
52             hextxt = "<FEFF"  # FEFF is BOM
53             hextxt << utf16txt.unpack("C*").map {|x| sprintf("%02X",x) }.join
54             hextxt << ">"
55           rescue
56             txt
57           end || ''
58           super(txt)
59         end
60     
61         def textstring(s)
62           # Format a text string
63           if s =~ /^</  # This means the string is hex-dumped.
64             return s
65           else
66             return '('+escape(s)+')'
67           end
68         end
69          
70         alias RDMCell Cell
71         alias RDMMultiCell MultiCell
72          
73         def Footer
74           SetFont(@font_for_footer, 'I', 8)
75           SetY(-15)
76           SetX(15)
77           RDMCell(0, 5, @footer_date, 0, 0, 'L')
78           SetY(-15)
79           SetX(-30)
80           RDMCell(0, 5, PageNo().to_s + '/{nb}', 0, 0, 'C')
81         end
82       end
83
84       class IFPDF < FPDF
85         include Redmine::I18n
86         attr_accessor :footer_date
87
88         def initialize(lang)
89           super()
90           set_language_if_valid lang
91           case l(:general_pdf_encoding).upcase
92           when 'CP949'
93             extend(PDF_Korean)
94             AddUHCFont()
95             @font_for_content = 'UHC'
96             @font_for_footer  = 'UHC'
97           when 'CP932'
98             extend(PDF_Japanese)
99             AddSJISFont()
100             @font_for_content = 'SJIS'
101             @font_for_footer  = 'SJIS'
102           when 'GB18030'
103             extend(PDF_Chinese)
104             AddGBFont()
105             @font_for_content = 'GB'
106             @font_for_footer  = 'GB'
107           when 'BIG5'
108             extend(PDF_Chinese)
109             AddBig5Font()
110             @font_for_content = 'Big5'
111             @font_for_footer  = 'Big5'
112           else
113             @font_for_content = 'Arial'
114             @font_for_footer  = 'Helvetica'
115           end
116           SetCreator(Redmine::Info.app_name)
117           SetFont(@font_for_content)
118         end
119
120         def SetFontStyle(style, size)
121           SetFont(@font_for_content, style, size)
122         end
123
124         def SetTitle(txt)
125           txt = begin
126             utf16txt = Iconv.conv('UTF-16BE', 'UTF-8', txt)
127             hextxt = "<FEFF"  # FEFF is BOM
128             hextxt << utf16txt.unpack("C*").map {|x| sprintf("%02X",x) }.join
129             hextxt << ">"
130           rescue
131             txt
132           end || ''
133           super(txt)
134         end
135
136         def textstring(s)
137           # Format a text string
138           if s =~ /^</  # This means the string is hex-dumped.
139             return s
140           else
141             return '('+escape(s)+')'
142           end
143         end
144
145         def fix_text_encoding(txt)
146           txt ||= ''
147           if txt.respond_to?(:force_encoding)
148             txt.force_encoding('UTF-8')
149             txt = txt.encode(l(:general_pdf_encoding), :invalid => :replace,
150                               :undef => :replace, :replace => '?')
151             txt.force_encoding('ASCII-8BIT')
152           else
153             @ic ||= Iconv.new(l(:general_pdf_encoding), 'UTF-8')
154             txtar = ""
155             begin
156               txtar += @ic.iconv(txt)
157             rescue Iconv::IllegalSequence
158               txtar += $!.success
159               txt = '?' + $!.failed[1,$!.failed.length]
160               retry
161             rescue
162               txtar += $!.success
163             end
164             txt = txtar
165           end
166           txt
167         end
168
169         def RDMCell(w,h=0,txt='',border=0,ln=0,align='',fill=0,link='')
170             Cell(w,h,fix_text_encoding(txt),border,ln,align,fill,link)
171         end
172
173         def RDMMultiCell(w,h=0,txt='',border=0,align='',fill=0)
174             MultiCell(w,h,fix_text_encoding(txt),border,align,fill)
175         end
176
177         def Footer
178           SetFont(@font_for_footer, 'I', 8)
179           SetY(-15)
180           SetX(15)
181           RDMCell(0, 5, @footer_date, 0, 0, 'L')
182           SetY(-15)
183           SetX(-30)
184           RDMCell(0, 5, PageNo().to_s + '/{nb}', 0, 0, 'C')
185         end
186         alias alias_nb_pages AliasNbPages
187       end
188
189       # Returns a PDF string of a list of issues
190       def issues_to_pdf(issues, project, query)
191         if l(:general_pdf_encoding).upcase != 'UTF-8'
192           pdf = IFPDF.new(current_language)
193         else
194           pdf = ITCPDF.new(current_language)
195         end
196         title = query.new_record? ? l(:label_issue_plural) : query.name
197         title = "#{project} - #{title}" if project
198         pdf.SetTitle(title)
199         pdf.alias_nb_pages
200         pdf.footer_date = format_date(Date.today)
201         pdf.SetAutoPageBreak(false)
202         pdf.AddPage("L")
203
204         # Landscape A4 = 210 x 297 mm
205         page_height   = 210
206         page_width    = 297
207         right_margin  = 10
208         bottom_margin = 20
209         col_id_width  = 10
210         row_height    = 5
211
212         # column widths
213         table_width = page_width - right_margin - 10  # fixed left margin
214         col_width = []
215         unless query.columns.empty?
216           col_width = query.columns.collect do |c|
217             (c.name == :subject || (c.is_a?(QueryCustomFieldColumn) && ['string', 'text'].include?(c.custom_field.field_format)))? 4.0 : 1.0
218           end
219           ratio = (table_width - col_id_width) / col_width.inject(0) {|s,w| s += w}
220           col_width = col_width.collect {|w| w * ratio}
221         end
222
223         # title
224         pdf.SetFontStyle('B',11)
225         pdf.RDMCell(190,10, title)
226         pdf.Ln
227         
228         # headers
229         pdf.SetFontStyle('B',8)
230         pdf.SetFillColor(230, 230, 230)
231         pdf.RDMCell(col_id_width, row_height, "#", 1, 0, 'C', 1)
232         query.columns.each_with_index do |column, i|
233           pdf.RDMCell(col_width[i], row_height, column.caption, 1, 0, 'L', 1)
234         end
235         pdf.Ln
236         
237         # rows
238         pdf.SetFontStyle('',8)
239         pdf.SetFillColor(255, 255, 255)
240         previous_group = false
241         issues.each do |issue|
242           if query.grouped? &&
243                (group = query.group_by_column.value(issue)) != previous_group
244             pdf.SetFontStyle('B',9)
245             pdf.RDMCell(277, row_height, 
246               (group.blank? ? 'None' : group.to_s) + " (#{query.issue_count_by_group[group]})",
247               1, 1, 'L')
248             pdf.SetFontStyle('',8)
249             previous_group = group
250           end
251           # fetch all the row values
252           col_values = query.columns.collect do |column|
253             s = if column.is_a?(QueryCustomFieldColumn)
254               cv = issue.custom_values.detect {|v| v.custom_field_id == column.custom_field.id}
255               show_value(cv)
256             else
257               value = issue.send(column.name)
258               if value.is_a?(Date)
259                 format_date(value)
260               elsif value.is_a?(Time)
261                 format_time(value)
262               else
263                 value
264               end
265             end
266             s.to_s
267           end
268           
269           # render it off-page to find the max height used
270           base_x = pdf.GetX
271           base_y = pdf.GetY
272           pdf.SetY(2 * page_height)
273           max_height = issues_to_pdf_write_cells(pdf, col_values, col_width, row_height)
274           pdf.SetXY(base_x, base_y)
275           
276           # make new page if it doesn't fit on the current one
277           space_left = page_height - base_y - bottom_margin
278           if max_height > space_left
279             pdf.AddPage("L")
280             base_x = pdf.GetX
281             base_y = pdf.GetY
282           end
283
284           # write the cells on page
285           pdf.RDMCell(col_id_width, row_height, issue.id.to_s, "T", 0, 'C', 1)
286           issues_to_pdf_write_cells(pdf, col_values, col_width, row_height)
287           issues_to_pdf_draw_borders(pdf, base_x, base_y, base_y + max_height, col_id_width, col_width)
288           pdf.SetY(base_y + max_height);
289         end
290         
291         if issues.size == Setting.issues_export_limit.to_i
292           pdf.SetFontStyle('B',10)
293           pdf.RDMCell(0, row_height, '...')
294         end
295         pdf.Output
296       end
297       
298       # Renders MultiCells and returns the maximum height used
299       def issues_to_pdf_write_cells(pdf, col_values, col_widths, row_height)
300         base_y = pdf.GetY
301         max_height = row_height
302         col_values.each_with_index do |column, i|
303           col_x = pdf.GetX
304           pdf.RDMMultiCell(col_widths[i], row_height, col_values[i], "T", 'L', 1)
305           max_height = (pdf.GetY - base_y) if (pdf.GetY - base_y) > max_height
306           pdf.SetXY(col_x + col_widths[i], base_y);
307         end
308         return max_height
309       end
310       
311       # Draw lines to close the row (MultiCell border drawing in not uniform)
312       def issues_to_pdf_draw_borders(pdf, top_x, top_y, lower_y, id_width, col_widths)
313         col_x = top_x + id_width
314         pdf.Line(col_x, top_y, col_x, lower_y)    # id right border
315         col_widths.each do |width|
316           col_x += width
317           pdf.Line(col_x, top_y, col_x, lower_y)  # columns right border
318         end
319         pdf.Line(top_x, top_y, top_x, lower_y)    # left border
320         pdf.Line(top_x, lower_y, col_x, lower_y)  # bottom border
321       end
322       
323       # Returns a PDF string of a single issue
324       def issue_to_pdf(issue)
325         if l(:general_pdf_encoding).upcase != 'UTF-8'
326           pdf = IFPDF.new(current_language)
327         else
328           pdf = ITCPDF.new(current_language)
329         end
330         pdf.SetTitle("#{issue.project} - ##{issue.tracker} #{issue.id}")
331         pdf.alias_nb_pages
332         pdf.footer_date = format_date(Date.today)
333         pdf.AddPage
334         pdf.SetFontStyle('B',11)    
335         pdf.RDMMultiCell(190,5, "#{issue.project} - #{issue.tracker} # #{issue.id}: #{issue.subject}")
336         pdf.Ln
337
338         y0 = pdf.GetY
339
340         pdf.SetFontStyle('B',9)
341         pdf.RDMCell(35,5, l(:field_status) + ":","LT")
342         pdf.SetFontStyle('',9)
343         pdf.RDMCell(60,5, issue.status.to_s,"RT")
344         pdf.SetFontStyle('B',9)
345         pdf.RDMCell(35,5, l(:field_priority) + ":","LT")
346         pdf.SetFontStyle('',9)
347         pdf.RDMCell(60,5, issue.priority.to_s,"RT")
348         pdf.Ln
349         
350         pdf.SetFontStyle('B',9)
351         pdf.RDMCell(35,5, l(:field_author) + ":","L")
352         pdf.SetFontStyle('',9)
353         pdf.RDMCell(60,5, issue.author.to_s,"R")
354         pdf.SetFontStyle('B',9)
355         pdf.RDMCell(35,5, l(:field_category) + ":","L")
356         pdf.SetFontStyle('',9)
357         pdf.RDMCell(60,5, issue.category.to_s,"R")
358         pdf.Ln   
359         
360         pdf.SetFontStyle('B',9)
361         pdf.RDMCell(35,5, l(:field_created_on) + ":","L")
362         pdf.SetFontStyle('',9)
363         pdf.RDMCell(60,5, format_date(issue.created_on),"R")
364         pdf.SetFontStyle('B',9)
365         pdf.RDMCell(35,5, l(:field_assigned_to) + ":","L")
366         pdf.SetFontStyle('',9)
367         pdf.RDMCell(60,5, issue.assigned_to.to_s,"R")
368         pdf.Ln
369         
370         pdf.SetFontStyle('B',9)
371         pdf.RDMCell(35,5, l(:field_updated_on) + ":","LB")
372         pdf.SetFontStyle('',9)
373         pdf.RDMCell(60,5, format_date(issue.updated_on),"RB")
374         pdf.SetFontStyle('B',9)
375         pdf.RDMCell(35,5, l(:field_due_date) + ":","LB")
376         pdf.SetFontStyle('',9)
377         pdf.RDMCell(60,5, format_date(issue.due_date),"RB")
378         pdf.Ln
379         
380         for custom_value in issue.custom_field_values
381           pdf.SetFontStyle('B',9)
382           pdf.RDMCell(35,5, custom_value.custom_field.name + ":","L")
383           pdf.SetFontStyle('',9)
384           pdf.RDMMultiCell(155,5, (show_value custom_value),"R")
385         end
386         
387         pdf.SetFontStyle('B',9)
388         pdf.RDMCell(35,5, l(:field_subject) + ":","LT")
389         pdf.SetFontStyle('',9)
390         pdf.RDMMultiCell(155,5, issue.subject,"RT")
391
392         pdf.SetFontStyle('B',9)
393         pdf.RDMCell(35,5, l(:field_description) + ":","LT")
394         pdf.SetFontStyle('',9)
395         pdf.RDMMultiCell(155,5, issue.description.to_s,"RT")
396
397         pdf.Line(pdf.GetX, y0, pdf.GetX, pdf.GetY)
398         pdf.Line(pdf.GetX, pdf.GetY, pdf.GetX + 190, pdf.GetY)
399         pdf.Ln
400         
401         if issue.changesets.any? &&
402              User.current.allowed_to?(:view_changesets, issue.project)
403           pdf.SetFontStyle('B',9)
404           pdf.RDMCell(190,5, l(:label_associated_revisions), "B")
405           pdf.Ln
406           for changeset in issue.changesets
407             pdf.SetFontStyle('B',8)
408             pdf.RDMCell(190,5,
409               format_time(changeset.committed_on) + " - " + changeset.author.to_s)
410             pdf.Ln
411             unless changeset.comments.blank?
412               pdf.SetFontStyle('',8)
413               pdf.RDMMultiCell(190,5, changeset.comments.to_s)
414             end   
415             pdf.Ln
416           end
417         end
418         
419         pdf.SetFontStyle('B',9)
420         pdf.RDMCell(190,5, l(:label_history), "B")
421         pdf.Ln  
422         for journal in issue.journals.find(
423                           :all, :include => [:user, :details],
424                           :order => "#{Journal.table_name}.created_on ASC")
425           pdf.SetFontStyle('B',8)
426           pdf.RDMCell(190,5,
427              format_time(journal.created_on) + " - " + journal.user.name)
428           pdf.Ln
429           pdf.SetFontStyle('I',8)
430           for detail in journal.details
431             pdf.RDMMultiCell(190,5, "- " + show_detail(detail, true))
432           end
433           if journal.notes?
434             pdf.Ln unless journal.details.empty?
435             pdf.SetFontStyle('',8)
436             pdf.RDMMultiCell(190,5, journal.notes.to_s)
437           end   
438           pdf.Ln
439         end
440
441         if issue.attachments.any?
442           pdf.SetFontStyle('B',9)
443           pdf.RDMCell(190,5, l(:label_attachment_plural), "B")
444           pdf.Ln
445           for attachment in issue.attachments
446             pdf.SetFontStyle('',8)
447             pdf.RDMCell(80,5, attachment.filename)
448             pdf.RDMCell(20,5, number_to_human_size(attachment.filesize),0,0,"R")
449             pdf.RDMCell(25,5, format_date(attachment.created_on),0,0,"R")
450             pdf.RDMCell(65,5, attachment.author.name,0,0,"R")
451             pdf.Ln
452           end
453         end
454         pdf.Output
455       end
456     end
457   end
458 end