Project

General

Profile

Patch #30026 » issues_pdf_helper-redmine-3.4.6_2sec_version.rb

Dirk Rudolph, 2018-11-25 01:08

 
1
# encoding: utf-8
2
#
3
# Redmine - project management software
4
# Copyright (C) 2006-2017  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
module Redmine
21
  module Export
22
    module PDF
23
      module IssuesPdfHelper
24
        # Returns a PDF string of a single issue
25
        def issue_to_pdf(issue, assoc={})
26
          pdf = ITCPDF.new(current_language)
27
          pdf.set_title("#{issue.project} - #{issue.tracker} ##{issue.id}")
28
          pdf.alias_nb_pages
29
          pdf.footer_date = format_date(User.current.today)
30
          pdf.add_page
31
          pdf.SetFontStyle('B',11)
32
          buf = "#{issue.project} - #{issue.tracker} ##{issue.id}"
33
          pdf.RDMMultiCell(190, 5, buf)
34
          pdf.SetFontStyle('',8)
35
          base_x = pdf.get_x
36
          i = 1
37
          issue.ancestors.visible.each do |ancestor|
38
            pdf.set_x(base_x + i)
39
            buf = "#{ancestor.tracker} # #{ancestor.id} (#{ancestor.status.to_s}): #{ancestor.subject}"
40
            pdf.RDMMultiCell(190 - i, 5, buf)
41
            i += 1 if i < 35
42
          end
43
          pdf.SetFontStyle('B',11)
44
          pdf.RDMMultiCell(190 - i, 5, issue.subject.to_s)
45
          pdf.SetFontStyle('',8)
46
          pdf.RDMMultiCell(190, 5, "#{format_time(issue.created_on)} - #{issue.author}")
47
          pdf.ln
48
  
49
          left = []
50
          left << [l(:field_status), issue.status]
51
          left << [l(:field_priority), issue.priority]
52
          left << [l(:field_assigned_to), issue.assigned_to] unless issue.disabled_core_fields.include?('assigned_to_id')
53
          left << [l(:field_category), issue.category] unless issue.disabled_core_fields.include?('category_id')
54
          left << [l(:field_fixed_version), issue.fixed_version] unless issue.disabled_core_fields.include?('fixed_version_id')
55
  
56
          right = []
57
          right << [l(:field_start_date), format_date(issue.start_date)] unless issue.disabled_core_fields.include?('start_date')
58
          right << [l(:field_due_date), format_date(issue.due_date)] unless issue.disabled_core_fields.include?('due_date')
59
          right << [l(:field_done_ratio), "#{issue.done_ratio}%"] unless issue.disabled_core_fields.include?('done_ratio')
60
          right << [l(:field_estimated_hours), l_hours(issue.estimated_hours)] unless issue.disabled_core_fields.include?('estimated_hours')
61
          right << [l(:label_spent_time), l_hours(issue.total_spent_hours)] if User.current.allowed_to?(:view_time_entries, issue.project)
62
  
63
          rows = left.size > right.size ? left.size : right.size
64
          while left.size < rows
65
            left << nil
66
          end
67
          while right.size < rows
68
            right << nil
69
          end
70

    
71
          custom_field_values = issue.visible_custom_field_values.reject {|value| value.custom_field.full_width_layout?}
72
          half = (custom_field_values.size / 2.0).ceil
73
          custom_field_values.each_with_index do |custom_value, i|
74
            (i < half ? left : right) << [custom_value.custom_field.name, show_value(custom_value, false)]
75
          end
76
  
77
          if pdf.get_rtl
78
            border_first_top = 'RT'
79
            border_last_top  = 'LT'
80
            border_first = 'R'
81
            border_last  = 'L'
82
          else
83
            border_first_top = 'LT'
84
            border_last_top  = 'RT'
85
            border_first = 'L'
86
            border_last  = 'R'
87
          end
88
  
89
          rows = left.size > right.size ? left.size : right.size
90
          rows.times do |i|
91
            heights = []
92
            pdf.SetFontStyle('B',9)
93
            item = left[i]
94
            heights << pdf.get_string_height(35, textilizable(item ? "#{item.first}:" : ""))
95
            item = right[i]
96
            heights << pdf.get_string_height(35, textilizable(item ? "#{item.first}:" : ""))
97
            pdf.SetFontStyle('',9)
98
            item = left[i]
99
            heights << pdf.get_string_height(60, textilizable(item ? item.last.to_s  : ""))
100
            item = right[i]
101
            heights << pdf.get_string_height(60, textilizable(item ? item.last.to_s  : ""))
102
            height = heights.max
103
  
104
            item = left[i]
105
            pdf.SetFontStyle('B',9)
106
            pdf.RDMMultiCell(35, height, item ? "#{item.first}:" : "", (i == 0 ? border_first_top : border_first), '', 0, 0)
107
            pdf.SetFontStyle('',9)
108
            pdf.RDMwriteFormattedCell(60, height, '', '', textilizable(item ? item.last.to_s : ""), issue.attachments,(i == 0 ? border_last_top : border_last), 0)
109
            #pdf.RDMMultiCell(60, height, item ? item.last.to_s : "", (i == 0 ? border_last_top : border_last), '', 0, 0)
110

    
111
            item = right[i]
112
            pdf.SetFontStyle('B',9)
113
            pdf.RDMMultiCell(35, height, item ? "#{item.first}:" : "",  (i == 0 ? border_first_top : border_first), '', 0, 0)
114
            pdf.SetFontStyle('',9)
115
            pdf.RDMwriteFormattedCell(60, height, '', '', textilizable(item ? item.last.to_s : ""), issue.attachments, (i == 0 ? border_last_top : border_last), 2)
116
  
117
            pdf.set_x(base_x)
118
          end
119
  
120
          pdf.SetFontStyle('B',9)
121
          pdf.RDMCell(35+155, 5, l(:field_description), "LRT", 1)
122
          pdf.SetFontStyle('',9)
123
  
124
          # Set resize image scale
125
          pdf.set_image_scale(1.6)
126
          text = textilizable(issue, :description,
127
            :only_path => false,
128
            :edit_section_links => false,
129
            :headings => false,
130
            :inline_attachments => false
131
          )
132
          pdf.RDMwriteFormattedCell(35+155, 5, '', '', text, issue.attachments, "LRB")
133

    
134
            custom_field_values = issue.visible_custom_field_values.select {|value| value.custom_field.full_width_layout?}
135
            custom_field_values.each do |value|
136
            text = show_value(value, true)
137
            next if text.blank?
138

    
139
            pdf.SetFontStyle('B',9)
140
            pdf.RDMCell(35+155, 5, value.custom_field.name, "LRT", 1)
141
            pdf.SetFontStyle('',9)
142
            pdf.RDMwriteFormattedCell(35+155, 5, '', '', text, issue.attachments, "LRB")
143
          end
144

    
145
          unless issue.leaf?
146
            truncate_length = (!is_cjk? ? 90 : 65)
147
            pdf.SetFontStyle('B',9)
148
            pdf.RDMCell(35+155,5, l(:label_subtask_plural) + ":", "LTR")
149
            pdf.ln
150
            issue_list(issue.descendants.visible.sort_by(&:lft)) do |child, level|
151
              buf = "#{child.tracker} # #{child.id}: #{child.subject}".
152
                      truncate(truncate_length)
153
              level = 10 if level >= 10
154
              pdf.SetFontStyle('',8)
155
              pdf.RDMCell(35+135,5, (level >=1 ? "  " * level : "") + buf, border_first)
156
              pdf.SetFontStyle('B',8)
157
              pdf.RDMCell(20,5, child.status.to_s, border_last)
158
              pdf.ln
159
            end
160
          end
161
  
162
          relations = issue.relations.select { |r| r.other_issue(issue).visible? }
163
          unless relations.empty?
164
            truncate_length = (!is_cjk? ? 80 : 60)
165
            pdf.SetFontStyle('B',9)
166
            pdf.RDMCell(35+155,5, l(:label_related_issues) + ":", "LTR")
167
            pdf.ln
168
            relations.each do |relation|
169
              buf = relation.to_s(issue) {|other|
170
                text = ""
171
                if Setting.cross_project_issue_relations?
172
                  text += "#{relation.other_issue(issue).project} - "
173
                end
174
                text += "#{other.tracker} ##{other.id}: #{other.subject}"
175
                text
176
              }
177
              buf = buf.truncate(truncate_length)
178
              pdf.SetFontStyle('', 8)
179
              pdf.RDMCell(35+155-60, 5, buf, border_first)
180
              pdf.SetFontStyle('B',8)
181
              pdf.RDMCell(20,5, relation.other_issue(issue).status.to_s, "")
182
              pdf.RDMCell(20,5, format_date(relation.other_issue(issue).start_date), "")
183
              pdf.RDMCell(20,5, format_date(relation.other_issue(issue).due_date), border_last)
184
              pdf.ln
185
            end
186
          end
187
          pdf.RDMCell(190,5, "", "T")
188
          pdf.ln
189
  
190
          if issue.changesets.any? &&
191
               User.current.allowed_to?(:view_changesets, issue.project)
192
            pdf.SetFontStyle('B',9)
193
            pdf.RDMCell(190,5, l(:label_associated_revisions), "B")
194
            pdf.ln
195
            for changeset in issue.changesets
196
              pdf.SetFontStyle('B',8)
197
              csstr  = "#{l(:label_revision)} #{changeset.format_identifier} - "
198
              csstr += format_time(changeset.committed_on) + " - " + changeset.author.to_s
199
              pdf.RDMCell(190, 5, csstr)
200
              pdf.ln
201
              unless changeset.comments.blank?
202
                pdf.SetFontStyle('',8)
203
                pdf.RDMwriteHTMLCell(190,5,'','',
204
                      changeset.comments.to_s, issue.attachments, "")
205
              end
206
              pdf.ln
207
            end
208
          end
209
  
210
          if assoc[:journals].present?
211
            pdf.SetFontStyle('B',9)
212
            pdf.RDMCell(190,5, l(:label_history), "B")
213
            pdf.ln
214
            assoc[:journals].each do |journal|
215
              pdf.SetFontStyle('B',8)
216
              title = "##{journal.indice} - #{format_time(journal.created_on)} - #{journal.user}"
217
              title << " (#{l(:field_private_notes)})" if journal.private_notes?
218
              pdf.RDMCell(190,5, title)
219
              pdf.ln
220
              pdf.SetFontStyle('I',8)
221
              details_to_strings(journal.visible_details, true).each do |string|
222
                pdf.RDMMultiCell(190,5, "- " + string)
223
              end
224
              if journal.notes?
225
                pdf.ln unless journal.details.empty?
226
                pdf.SetFontStyle('',8)
227
                text = textilizable(journal, :notes,
228
                  :only_path => false,
229
                  :edit_section_links => false,
230
                  :headings => false,
231
                  :inline_attachments => false
232
                )
233
                pdf.RDMwriteFormattedCell(190,5,'','', text, issue.attachments, "")
234
              end
235
              pdf.ln
236
            end
237
          end
238
  
239
          if issue.attachments.any?
240
            pdf.SetFontStyle('B',9)
241
            pdf.RDMCell(190,5, l(:label_attachment_plural), "B")
242
            pdf.ln
243
            for attachment in issue.attachments
244
              pdf.SetFontStyle('',8)
245
              pdf.RDMCell(80,5, attachment.filename)
246
              pdf.RDMCell(20,5, number_to_human_size(attachment.filesize),0,0,"R")
247
              pdf.RDMCell(25,5, format_date(attachment.created_on),0,0,"R")
248
              pdf.RDMCell(65,5, attachment.author.name,0,0,"R")
249
              pdf.ln
250
            end
251
          end
252
          pdf.output
253
        end
254

    
255
        # Returns a PDF string of a list of issues
256
        def issues_to_pdf(issues, project, query)
257
          pdf = ITCPDF.new(current_language, "L")
258
          title = query.new_record? ? l(:label_issue_plural) : query.name
259
          title = "#{project} - #{title}" if project
260
          pdf.set_title(title)
261
          pdf.alias_nb_pages
262
          pdf.footer_date = format_date(User.current.today)
263
          pdf.set_auto_page_break(false)
264
          pdf.add_page("L")
265
  
266
          # Landscape A4 = 210 x 297 mm
267
          page_height   = pdf.get_page_height # 210
268
          page_width    = pdf.get_page_width  # 297
269
          left_margin   = pdf.get_original_margins['left'] # 10
270
          right_margin  = pdf.get_original_margins['right'] # 10
271
          bottom_margin = pdf.get_footer_margin
272
          row_height    = 4
273
  
274
          # column widths
275
          table_width = page_width - right_margin - left_margin
276
          col_width = []
277
          unless query.inline_columns.empty?
278
            col_width = calc_col_width(issues, query, table_width, pdf)
279
            table_width = col_width.inject(0, :+)
280
          end
281
  
282
          # use full width if the description or last_notes are displayed
283
          if table_width > 0 && (query.has_column?(:description) || query.has_column?(:last_notes))
284
            col_width = col_width.map {|w| w * (page_width - right_margin - left_margin) / table_width}
285
            table_width = col_width.inject(0, :+)
286
          end
287
  
288
          # title
289
          pdf.SetFontStyle('B',11)
290
          pdf.RDMCell(190, 8, title)
291
          pdf.ln
292

    
293
          # totals
294
          totals = query.totals.map {|column, total| "#{column.caption}: #{total}"}
295
          if totals.present?
296
            pdf.SetFontStyle('B',10)
297
            pdf.RDMCell(table_width, 6, totals.join("  "), 0, 1, 'R')
298
          end
299

    
300
          totals_by_group = query.totals_by_group
301
          render_table_header(pdf, query, col_width, row_height, table_width)
302
          previous_group = false
303
          result_count_by_group = query.result_count_by_group
304

    
305
          issue_list(issues) do |issue, level|
306
            if query.grouped? &&
307
                 (group = query.group_by_column.value(issue)) != previous_group
308
              pdf.SetFontStyle('B',10)
309
              group_label = group.blank? ? 'None' : group.to_s.dup
310
              group_label << " (#{result_count_by_group[group]})"
311
              pdf.bookmark group_label, 0, -1
312
              pdf.RDMCell(table_width, row_height * 2, group_label, 'LR', 1, 'L')
313
              pdf.SetFontStyle('',8)
314

    
315
              totals = totals_by_group.map {|column, total| "#{column.caption}: #{total[group]}"}.join("  ")
316
              if totals.present?
317
                pdf.RDMCell(table_width, row_height, totals, 'LR', 1, 'L')
318
              end
319
              previous_group = group
320
            end
321
  
322
            # fetch row values
323
            col_values = fetch_row_values(issue, query, level)
324
  
325
            # make new page if it doesn't fit on the current one
326
            base_y     = pdf.get_y
327
            max_height = get_issues_to_pdf_write_cells(pdf, col_values.map, col_width)
328
            space_left = page_height - base_y - bottom_margin
329
            if max_height > space_left
330
              pdf.add_page("L")
331
              render_table_header(pdf, query, col_width, row_height, table_width)
332
              base_y = pdf.get_y
333
            end
334
  
335
            # write the cells on page
336
            issues_to_pdf_write_cells(pdf, col_values, col_width, max_height)
337
            pdf.set_y(base_y + max_height)
338
  
339
            if query.has_column?(:description) && issue.description?
340
              pdf.set_x(10)
341
              pdf.set_auto_page_break(true, bottom_margin)
342
              pdf.RDMwriteFormattedCell(0, 5, 10, '', textilizable(issue, :description), issue.attachments, "LRBT")
343
              pdf.set_auto_page_break(false)
344
            end
345

    
346
            if query.has_column?(:last_notes) && issue.last_notes.present?
347
              pdf.set_x(10)
348
              pdf.set_auto_page_break(true, bottom_margin)
349
              pdf.RDMwriteHTMLCell(0, 5, 10, '', issue.last_notes.to_s, [], "LRBT")
350
              pdf.set_auto_page_break(false)
351
          end
352
          end
353
  
354
          if issues.size == Setting.issues_export_limit.to_i
355
            pdf.SetFontStyle('B',10)
356
            pdf.RDMCell(0, row_height, '...')
357
          end
358
          pdf.output
359
        end
360

    
361
        def is_cjk?
362
          case current_language.to_s.downcase
363
          when 'ja', 'zh-tw', 'zh', 'ko'
364
            true
365
          else
366
            false
367
          end
368
        end
369

    
370
        # fetch row values
371
        def fetch_row_values(issue, query, level)
372
          query.inline_columns.collect do |column|
373
            s = if column.is_a?(QueryCustomFieldColumn)
374
              cv = issue.visible_custom_field_values.detect {|v| v.custom_field_id == column.custom_field.id}
375
              show_value(cv, true )
376
            else
377
              value = issue.send(column.name)
378
              case column.name
379
              when :subject
380
                value = "  " * level + value
381
              when :attachments
382
                value = value.to_a.map {|a| a.filename}.join("\n")
383

    
384
              end
385
              if value.is_a?(Date)
386
                format_date(value)
387
              elsif value.is_a?(Time)
388
                format_time(value)
389
              else
390
                value
391
              end
392
                end
393
            s.to_s
394
          end
395
        end
396

    
397
        # calculate columns width
398
        def calc_col_width(issues, query, table_width, pdf)
399
          # calculate statistics
400
          #  by captions
401
          pdf.SetFontStyle('B',8)
402
          margins = pdf.get_margins
403
          col_padding = margins['cell']
404
          col_width_min = query.inline_columns.map {|v| pdf.get_string_width(v.caption) + col_padding}
405
          col_width_max = Array.new(col_width_min)
406
          col_width_avg = Array.new(col_width_min)
407
          col_min = pdf.get_string_width('OO') + col_padding * 2
408
          if table_width > col_min * col_width_avg.length
409
            table_width -= col_min * col_width_avg.length
410
          else
411
            col_min = pdf.get_string_width('O') + col_padding * 2
412
            if table_width > col_min * col_width_avg.length
413
              table_width -= col_min * col_width_avg.length
414
            else
415
              ratio = table_width / col_width_avg.inject(0, :+)
416
              return col_width = col_width_avg.map {|w| w * ratio}
417
            end
418
          end
419
          word_width_max = query.inline_columns.map {|c|
420
            n = 10
421
            c.caption.split.each {|w|
422
              x = pdf.get_string_width(w) + col_padding
423
              n = x if n < x
424
            }
425
            n
426
          }
427

    
428
          #  by properties of issues
429
          pdf.SetFontStyle('',8)
430
          k = 1
431
          issue_list(issues) {|issue, level|
432
            k += 1
433
            values = fetch_row_values(issue, query, level)
434
            values.each_with_index {|v,i|
435
              n = pdf.get_string_width(v) + col_padding * 2
436
              col_width_max[i] = n if col_width_max[i] < n
437
              col_width_min[i] = n if col_width_min[i] > n
438
              col_width_avg[i] += n
439
              v.split.each {|w|
440
                x = pdf.get_string_width(w) + col_padding
441
                word_width_max[i] = x if word_width_max[i] < x
442
              }
443
            }
444
          }
445
          col_width_avg.map! {|x| x / k}
446

    
447
          # calculate columns width
448
          ratio = table_width / col_width_avg.inject(0, :+)
449
          col_width = col_width_avg.map {|w| w * ratio}
450

    
451
          # correct max word width if too many columns
452
          ratio = table_width / word_width_max.inject(0, :+)
453
          word_width_max.map! {|v| v * ratio} if ratio < 1
454

    
455
          # correct and lock width of some columns
456
          done = 1
457
          col_fix = []
458
          col_width.each_with_index do |w,i|
459
            if w > col_width_max[i]
460
              col_width[i] = col_width_max[i]
461
              col_fix[i] = 1
462
              done = 0
463
            elsif w < word_width_max[i]
464
              col_width[i] = word_width_max[i]
465
              col_fix[i] = 1
466
              done = 0
467
            else
468
              col_fix[i] = 0
469
            end
470
          end
471

    
472
          # iterate while need to correct and lock coluns width
473
          while done == 0
474
            # calculate free & locked columns width
475
            done = 1
476
            ratio = table_width / col_width.inject(0, :+)
477

    
478
            # correct columns width
479
            col_width.each_with_index do |w,i|
480
              if col_fix[i] == 0
481
                col_width[i] = w * ratio
482

    
483
                # check if column width less then max word width
484
                if col_width[i] < word_width_max[i]
485
                  col_width[i] = word_width_max[i]
486
                  col_fix[i] = 1
487
                  done = 0
488
                elsif col_width[i] > col_width_max[i]
489
                  col_width[i] = col_width_max[i]
490
                  col_fix[i] = 1
491
                  done = 0
492
                end
493
              end
494
            end
495
          end
496

    
497
          ratio = table_width / col_width.inject(0, :+)
498
          col_width.map! {|v| v * ratio + col_min}
499
          col_width
500
        end
501

    
502
        def render_table_header(pdf, query, col_width, row_height, table_width)
503
          # headers
504
          pdf.SetFontStyle('B',8)
505
          pdf.set_fill_color(230, 230, 230)
506

    
507
          base_x     = pdf.get_x
508
          base_y     = pdf.get_y
509
          max_height = get_issues_to_pdf_write_cells(pdf, query.inline_columns, col_width, true)
510

    
511
          # write the cells on page
512
          issues_to_pdf_write_cells(pdf, query.inline_columns, col_width, max_height, true)
513
          pdf.set_xy(base_x, base_y + max_height)
514

    
515
          # rows
516
          pdf.SetFontStyle('',8)
517
          pdf.set_fill_color(255, 255, 255)
518
        end
519

    
520
        # returns the maximum height of MultiCells
521
        def get_issues_to_pdf_write_cells(pdf, col_values, col_widths, head=false)
522
          heights = []
523
          col_values.each_with_index do |column, i|
524
            heights << pdf.get_string_height(col_widths[i], head ? column.caption : textilizable(column))
525
          end
526
          return heights.max
527
        end
528

    
529
        # Renders MultiCells and returns the maximum height used
530
        def issues_to_pdf_write_cells(pdf, col_values, col_widths, row_height, head=false)
531
          col_values.each_with_index do |column, i|
532
            if head
533
            pdf.RDMMultiCell(col_widths[i], row_height, head ? column.caption : column.strip, 1, '', 1, 0)
534
            else
535
            # cell(w, h, txt, border, ln, align, fill, link)
536
            pdf.RDMwriteFormattedCell(col_widths[i], row_height, '', '', column.strip, [], 1, 0, 1)
537
            end
538
            end
539
        end
540

    
541
        # Draw lines to close the row (MultiCell border drawing in not uniform)
542
        #
543
        #  parameter "col_id_width" is not used. it is kept for compatibility.
544
        def issues_to_pdf_draw_borders(pdf, top_x, top_y, lower_y,
545
                                       col_id_width, col_widths, rtl=false)
546
          col_x = top_x
547
          pdf.line(col_x, top_y, col_x, lower_y)    # id right border
548
          col_widths.each do |width|
549
            if rtl
550
              col_x -= width
551
            else
552
              col_x += width
553
            end
554
            pdf.line(col_x, top_y, col_x, lower_y)  # columns right border
555
          end
556
          pdf.line(top_x, top_y, top_x, lower_y)    # left border
557
          pdf.line(top_x, lower_y, col_x, lower_y)  # bottom border
558
        end
559
      end
560
    end
561
  end
562
end
(3-3/6)