OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub
Ruby agile-developmentangularbcfboardsbug-trackerganttgantt-chartifcissue-trackerjira-alternativekanbanopenprojectproduct-managementproject-managementproject-planningroadmaprubyscrumtimelineworkflows
wip: pdf-export by work packages query
as-opaaa527dd09bc
diff --git a/app/models/work_package/pdf_export/attachments.rb b/app/models/work_package/pdf_export/attachments.rbindex be491f41f6d..ccd9f813c4b 100644--- a/app/models/work_package/pdf_export/attachments.rb+++ b/app/models/work_package/pdf_export/attachments.rb@@ -26,6 +26,8 @@# See COPYRIGHT and LICENSE files for more details.#+++require 'mini_magick'+module WorkPackage::PDFExport::Attachments### Creates cells for each attachment of the work packagediff --git a/app/models/work_package/pdf_export/common.rb b/app/models/work_package/pdf_export/common.rbindex 60b315057d2..186305f01f8 100644--- a/app/models/work_package/pdf_export/common.rb+++ b/app/models/work_package/pdf_export/common.rb@@ -54,7 +54,7 @@ module WorkPackage::PDFExport::Commondef success(content)::Exports::Result- .new format: :csv,+ .new format: :pdf,title:,content:,mime_type: 'application/pdf'@@ -88,4 +88,95 @@ module WorkPackage::PDFExport::Commondef position_diff(position_a, position_b)position_a.y - position_b.y + ((position_b.page - position_a.page) * pdf.bounds.height)end++ def with_margin(opts, &)+ with_vertical_margin(opts) do+ pdf.indent(opts[:margin_left] || 0, opts[:margin_right] || 0, &)+ end+ end++ def with_vertical_margin(opts)+ pdf.move_down(opts[:margin_top]) if opts.key?(:margin_top)+ yield+ pdf.move_down(opts[:margin_bottom]) if opts.key?(:margin_bottom)+ end++ def write_optional_page_break(threshold)+ space_from_bottom = pdf.y - pdf.bounds.bottom+ if space_from_bottom < threshold+ pdf.start_new_page+ end+ end++ def get_column_value(work_package, column)+ formatter = formatter_for(column)+ formatter.format(work_package)+ end++ def get_column_value_cell(work_package, column)+ value = ERB::Util.html_escape(get_column_value(work_package, column))+ return get_id_column_cell(work_package, value) if column == :id+ return get_subject_column_cell(work_package, value) if with_descriptions? && column == :subject++ value+ end++ def get_id_column_cell(work_package, value)+ href = url_helpers.work_package_url(work_package)+ make_link_href_cell(href, value)+ end++ def get_subject_column_cell(work_package, value)+ make_link_anchor_cell(work_package.id, value)+ end++ def make_link_href_cell(href, caption)+ "<link href='#{href}'>#{caption}</link>"+ end++ def make_link_anchor_cell(anchor, caption)+ "<link anchor=\"#{anchor}\">#{caption}</link>"+ end++ def pdf_table_auto_widths(data, column_widths, options = {}, force_fixed_columns, &)+ return pdf.table(data, options.merge({ column_widths: }), &) if force_fixed_columns++ begin+ pdf.table(data, options.merge({ width: pdf.bounds.width }), &)+ rescue Prawn::Errors::CannotFit+ pdf.table(data, options.merge({ column_widths: }), &)+ end+ end++ def text_column?(column)+ column.is_a?(Queries::WorkPackages::Columns::CustomFieldColumn) &&+ %w(string text).include?(column.custom_field.field_format)+ end++ def url_helpers+ @url_helpers ||= OpenProject::StaticRouting::StaticUrlHelpers.new+ end++ def api_url_helpers+ API::V3::Utilities::PathHelper::ApiV3Path+ end++ def make_group_label(group)+ if group.blank?+ I18n.t(:label_none_parentheses)+ elsif group.is_a? Array+ group.join(', ')+ else+ group.to_s+ end+ end++ def with_descriptions?+ options[:show_descriptions]+ end++ def with_attachments?+ options[:show_attachments]+ end+enddiff --git a/app/models/work_package/pdf_export/overview_table.rb b/app/models/work_package/pdf_export/overview_table.rbnew file mode 100644index 00000000000..66476bf5d85--- /dev/null+++ b/app/models/work_package/pdf_export/overview_table.rb@@ -0,0 +1,189 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2023 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See COPYRIGHT and LICENSE files for more details.+#++++module WorkPackage::PDFExport::OverviewTable++ def write_work_packages_overview!(work_packages)+ if query.grouped?+ write_grouped!(work_packages)+ else+ with_margin(overview_table_margins_style) do+ write_table!(work_packages, get_total_sums)+ end+ end+ end++ private++ def write_grouped!(work_packages)+ groups = {}+ work_packages.each do |work_package|+ group = query.group_by_column.value(work_package)+ groups[group] = (groups[group] || []).concat([work_package])+ end+ groups.each do |group, grouped_work_packages|+ write_group!(group, grouped_work_packages, get_group_sums(group))+ end+ end++ def table_columns_objects+ @table_columns_objects ||= limit_table_columns_objects+ end++ def limit_table_columns_objects+ list = column_objects+ list = list.reject { |c| c == query.group_by_column } if query.grouped?+ list = list.take(4) if with_descriptions?+ list+ end++ def table_column_widths+ widths = table_columns_objects.map do |col|+ if col.name == :subject || text_column?(col)+ 4.0+ else+ 1.0+ end+ end+ ratio = pdf.bounds.width / widths.sum++ widths.map { |w| w * ratio }+ end++ def write_group!(group, work_packages, sums)+ write_optional_page_break(200) # TODO: move page break threshold const to style settings+ with_margin(overview_table_margins_style) do+ label = make_group_label(group)+ with_margin(overview_group_header_margins_style) do+ pdf.formatted_text([overview_group_header_style.merge({ text: label })])+ end+ write_table!(work_packages, sums)+ end+ end++ def write_table!(work_packages, sums)+ rows = build_table_rows(work_packages, sums)+ pdf_table_auto_widths(rows, table_column_widths,+ { header: true, cell_style: overview_table_cell_style.merge({ inline_format: true }) },+ query.grouped?) do |table|+ format_header_cells table.cells.columns(0..-1).rows(0)+ format_sum_cells table.cells.columns(0..-1).rows(-1) if query.display_sums?+ end+ end++ def format_header_cells(header_cells)+ header_style = overview_table_header_cell_style+ header_cells.each do |cell|+ apply_cell_style cell, header_style+ end+ end++ def format_sum_cells(sums_cells)+ sums_style = overview_table_sums_cell_style+ sums_cells.each do |cell|+ apply_cell_style cell, sums_style+ end+ end++ def apply_cell_style(cell, style)+ cell.background_color = style[:background_color]+ cell.font_style = style[:font_style]+ cell.text_color = style[:text_color]+ cell.size = style[:size]+ end++ def get_total_sums()+ query.results.all_total_sums if query.display_sums?+ end++ def get_group_sums(group)+ return nil unless query.display_sums?++ @group_sums ||= query.results.all_group_sums+ @group_sums[group]+ end++ def build_table_rows(work_packages, sums)+ rows = work_packages.map do |work_package|+ build_table_row work_package+ end+ rows.unshift build_header_row+ rows.push build_sum_row(sums) unless sums.nil?+ rows+ end++ def build_table_row(work_package)+ table_columns_objects.map do |col|+ get_column_value_cell work_package, col.name+ end+ end++ def build_header_row+ table_columns_objects.map { |col| (col.caption || '').upcase }+ end++ def build_sum_row(sums)+ sum_row = table_columns_objects.map do |col|+ sums[col].to_s+ end+ sum_row[0] = 'Sum' # TODO: I18n and in which column should the sum text be+ sum_row+ end++ def overview_group_header_style+ { size: 11, styles: [:bold] }+ end++ def overview_group_header_margins_style+ { margin_bottom: 4 }+ end++ def overview_table_margins_style+ { margin_top: 20, margin_bottom: 0, margin_left: 0, margin_right: 0 }+ end++ def overview_table_header_cell_style+ { size: 9, text_color: "000000", font_style: :bold }+ end++ def overview_table_sums_cell_style+ { size: 8, text_color: "000000", font_style: :bold }+ end++ def overview_table_cell_style+ { size: 9,+ text_color: "000000",+ border_widths: [0.25, 0.25, 0.25, 0.25],+ padding_left: 5,+ padding_right: 5,+ padding_top: 0,+ padding_bottom: 4+ }+ end++enddiff --git a/app/models/work_package/pdf_export/work_package_detail.rb b/app/models/work_package/pdf_export/work_package_detail.rbnew file mode 100644index 00000000000..a9a5fa78cd3--- /dev/null+++ b/app/models/work_package/pdf_export/work_package_detail.rb@@ -0,0 +1,199 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2023 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See COPYRIGHT and LICENSE files for more details.+#++++module WorkPackage::PDFExport::WorkPackageDetail++ def write_work_packages_details!(work_packages)+ work_packages.each_with_index do |work_package, index|+ write_detail!(work_package, [index + 1])+ end+ end++ private++ def write_detail!(work_package, level_path)+ # TODO: move page break threshold const to style settings and implement conditional break with height measuring+ write_optional_page_break(300)+ with_margin(work_package_detail_margins_style) do+ write_work_package_subject! work_package, level_path+ write_attributes_table! work_package+ write_description! work_package+ end+ end++ def write_work_package_subject!(work_package, level_path)+ with_margin(work_package_subject_margins_style) do+ pdf_dest = pdf.dest_xyz(0, pdf.y)+ pdf.add_dest(work_package.id.to_s, pdf_dest)+ title = get_column_value work_package, :subject+ opts = { text: "#{level_path.join('.')}. #{title}" }+ pdf.formatted_text([work_package_subject_style.merge(opts)])+ end+ end++ def write_attributes_table!(work_package)+ rows = build_attributes_table_rows work_package+ with_margin(attributes_table_margins_style) do+ pdf.table(+ rows, column_widths: attributes_table_column_widths,+ cell_style: attributes_table_cell_style.merge({ inline_format: true })+ )+ end+ end++ def attributes_table_column_widths+ # calculate fixed work package attribute table columns width+ widths = [1.0, 2.0, 1.0, 2.0] # label | value | label | value+ ratio = pdf.bounds.width / widths.sum+ widths.map { |w| w * ratio }+ end++ def build_attributes_table_rows(work_package)+ # get work package attribute table rows data [[label, value, label, value]]+ attrs = %i[+ id+ updated_at+ type+ started_at+ status+ due_date+ version+ priority+ duration+ work+ category+ assigned_to+ ]+ 0.step(attrs.length - 1, 2).map do |i|+ build_attributes_table_cells(attrs[i], work_package) ++ build_attributes_table_cells(attrs[i + 1], work_package)+ end+ end++ def build_attributes_table_cells(attribute, work_package)+ # get work package attribute table cell data: [label, value]+ return ['', ''] if attribute.nil?++ label = WorkPackage.human_attribute_name(attribute) || ''+ [+ pdf.make_cell(label.upcase, attributes_table_label_font_style),+ get_column_value_cell(work_package, attribute.to_sym)+ ]+ end++ def write_description!(work_package)+ return if work_package.description.blank?++ write_description_label!+ write_description_content! work_package+ end++ def write_description_label!+ label = WorkPackage.human_attribute_name(:description)+ with_margin(description_header_margins_style) do+ pdf.formatted_text([description_header_style.merge({ text: label })])+ end+ end++ def write_description_content!(work_package)+ configure_markup work_package+ markup = format_text(work_package.description, object: work_package, format: :html)+ .gsub('class="op-uc-image"', 'style="width:100"') # TODO: this is a workaround image formatting+ pdf.markup markup+ end++ def configure_markup(work_package)+ # configure prawn markup gem in context of our work package+ images_enabled = options[:show_attachments] && work_package.attachments.exists?+ pdf.font work_package_detail_font_style+ pdf.markup_options = {+ image: {+ loader: ->(src) {+ images_enabled ? attachment_image_filepath(work_package, src) : nil+ },+ placeholder: "<i>[#{I18n.t('export.image.omitted')}]</i>"+ }+ }+ end++ def attachment_image_filepath(work_package, src)+ # images are embedded into markup with the api-path as img.src+ attachment = attachment_by_api_content_src(work_package, src)+ return nil if attachment.nil? || !pdf_embeddable?(attachment)++ resize_image(attachment.file.local_file.path)+ end++ def attachment_by_api_content_src(work_package, src)+ # find attachment by api-path+ work_package.attachments.detect { |a| api_url_helpers.attachment_content(a.id) == src }+ end++ def work_package_detail_margins_style+ { margin_top: 20 }+ end++ def work_package_detail_font_style+ { style: :normal, size: 9 }+ end++ def work_package_subject_margins_style+ {}+ end++ def work_package_subject_style+ { size: 14, styles: [:bold] }+ end++ def attributes_table_margins_style+ { margin_top: 4 }+ end++ def attributes_table_label_font_style+ { font_style: :bold }+ end++ def attributes_table_cell_style+ { size: 9,+ text_color: "000000",+ border_widths: [0.25, 0.25, 0.25, 0.25],+ padding_left: 5,+ padding_right: 5,+ padding_top: 0,+ padding_bottom: 4 }+ end++ def description_header_margins_style+ { margin_top: 8, margin_bottom: 4 }+ end++ def description_header_style+ { size: 11, styles: [:bold] }+ end++enddiff --git a/app/models/work_package/pdf_export/work_package_list_to_pdf.rb b/app/models/work_package/pdf_export/work_package_list_to_pdf.rbindex cefb22daf2d..98d53cb8097 100644--- a/app/models/work_package/pdf_export/work_package_list_to_pdf.rb+++ b/app/models/work_package/pdf_export/work_package_list_to_pdf.rb@@ -26,30 +26,15 @@# See COPYRIGHT and LICENSE files for more details.#++-# Exporter for work package table.-#-# It can optionally export a work package with-# - description, or with-# - attached images, or with-# - description and attached images.-#-# When exporting with attached images then the memory consumption can quickly-# grow beyond limits. Therefore we create multiple smaller PDFs that we finally-# merge do one file.--require 'mini_magick'-require 'open3'-class WorkPackage::PDFExport::WorkPackageListToPdf < WorkPackage::Exports::QueryExporterinclude WorkPackage::PDFExport::Common- include WorkPackage::PDFExport::Formattableinclude WorkPackage::PDFExport::Attachments+ include WorkPackage::PDFExport::OverviewTable+ include WorkPackage::PDFExport::WorkPackageDetailattr_accessor :pdf,:options- WORK_PACKAGES_PER_BATCH = 100-def self.keyend@@ -58,19 +43,17 @@ class WorkPackage::PDFExport::WorkPackageListToPdf < WorkPackage::Exports::Querysuper@cell_padding = options.delete(:cell_padding)- prepare_batch! if batch_supported?+ @start_page_count = 0setup_page!enddef export!- return render_batched! if batch_supported?-file = render_work_packages query.results.work_packagessuccess(file)rescue Prawn::Errors::CannotFiterror(I18n.t(:error_pdf_export_too_many_columns))rescue StandardError => e- Rails.logger.error { "Failed to generated PDF export: #{e} #{e.message}." }+ Rails.logger.error { "Failed to generated PDF export: #{e} #{e.message}}." }error(I18n.t(:error_pdf_failed_to_export, error: e.message))end@@ -80,80 +63,24 @@ class WorkPackage::PDFExport::WorkPackageListToPdf < WorkPackage::Exports::Queryself.pdf = get_pdf(current_language)configure_page_size- configure_markup- end-- def prepare_batch!- total_wp_count = query.results.work_packages.count- @work_packages_per_batch = 100- @batches_count = total_wp_count.fdiv(@work_packages_per_batch).ceil- @batch_files = []- @page_count = -1- end-- def render_batched!- (1..@batches_count).each do |batch_index|- @batch_files << run_batch!(batch_index)- end-- merged_pdf_file = merge_pdfs-- delete_tmp_files-- success(merged_pdf_file)- end-- def on_first_render- write_title!- write_headers!- end-- def delete_tmp_files- @batch_files.each(&:delete)enddef configure_page_size- pdf.options[:page_size] = 'EXECUTIVE'- pdf.options[:page_layout] = :landscape+ pdf.options[:page_size] = 'EXECUTIVE' # TODO: 'A4'?+ pdf.options[:page_layout] = with_descriptions? ? :portrait : :landscapeend- def merge_pdfs- merged_pdf = Tempfile.new- # We use the command line tool "pdfunite" for concatenating the PDFs.- # That tool comes with the system package "poppler-utils" which we- # fortunately already have installed for text extraction purposes.- Open3.capture2e("pdfunite", *@batch_files.map(&:path), merged_pdf.path)-- merged_pdf- end-- def run_batch!(batch_index)- first = batch_index == 1-- # We need to clear the page after the first one- setup_page!-- batch_file = render_work_packages(- work_packages_batch(batch_index),- first:,- filename: "pdf_batch_#{batch_index}"- ) do- write_footers!- end-- @page_count += pdf.page_count- batch_file.close- batch_file- end-- def render_work_packages(work_packages, first: true, filename: "pdf_export")+ def render_work_packages(work_packages, filename: "pdf_export")@resized_image_paths = []- on_first_render if first- write_work_packages! work_packages+ write_title!+ write_work_packages_overview! work_packages+ write_work_packages_details! work_packages if with_descriptions?yield if block_given?+ write_footers!+file = Tempfile.new(filename)pdf.render_file(file.path)@@ -168,9 +95,7 @@ class WorkPackage::PDFExport::WorkPackageListToPdf < WorkPackage::Exports::Querydef write_title!pdf.title = heading- pdf.font style: :bold, size: 11- pdf.text heading- pdf.move_down 20+ pdf.formatted_text([page_heading_style.merge({ text: heading })])enddef title@@ -188,135 +113,26 @@ class WorkPackage::PDFExport::WorkPackageListToPdf < WorkPackage::Exports::Queryenddef write_footers!- @page_count += 1- pdf.number_pages format_date(Date.today),- at: [pdf.bounds.left, 0],- style: :italic-- pdf.number_pages "<page>",- start_count_at: @page_count,- at: [pdf.bounds.right - 25, 0],- style: :italic- end-- def column_widths- widths = column_objects.map do |col|- if col.name == :subject || text_column?(col)- 4.0- else- 1.0- end- end- ratio = pdf.bounds.width / widths.sum+ date_string = format_date(Date.today)+ title_string = heading+ title_string_width = pdf.width_of(title_string, page_footer_style)- widths.map { |w| w * ratio }- end-- def formattable_colspan- column_objects.size- end-- def text_column?(column)- column.is_a?(Queries::WorkPackages::Columns::CustomFieldColumn) &&- %w(string text).include?(column.custom_field.field_format)- end-- def write_headers!- pdf.font style: :normal, size: 8- pdf.table([data_headers], column_widths:)- end-- def data_headers- column_objects.map(&:caption).map do |caption|- pdf.make_cell caption, font_style: :bold, background_color: 'CCCCCC'- end- end-- def write_work_packages!(work_packages)- pdf.font style: :normal, size: 8- previous_group = nil-- work_packages.each do |work_package|- previous_group = write_group_header!(work_package, previous_group)-- write_attributes!(work_package)-- if options[:show_descriptions]- write_formattable! work_package,- markdown: work_package.description,- label: WorkPackage.human_attribute_name(:description)- end+ pdf.repeat :all, dynamic: true do+ page_string = pdf.page_number.to_s+ page_string_width = pdf.width_of(page_string, page_footer_style)- if options[:show_attachments] && work_package.attachments.exists?- write_attachments!(work_package)- end+ pdf.draw_text date_string, page_footer_style.merge({ at: [pdf.bounds.left, 0] })+ pdf.draw_text page_string, page_footer_style.merge({ at: [(pdf.bounds.width - page_string_width) / 2, 0] })+ pdf.draw_text title_string, page_footer_style.merge({ at: [pdf.bounds.right - title_string_width, 0] })endend- def work_packages_batch(batch_index)- query- .results- .work_packages- .page(batch_index)- .per_page(@work_packages_per_batch)+ def page_heading_style+ { size: 14, styles: [:bold] }end- def write_attributes!(work_package)- values = columns.map do |column|- make_column_value work_package, column[:name]- end-- pdf.table([values], column_widths:)+ def page_footer_style+ { size: 8, style: :normal }end- def write_attachments!(work_package)- attachments = make_attachments_cells(work_package.attachments)-- pdf.table([attachments], width: pdf.bounds.width) if attachments.any?- end-- def write_group_header!(work_package, previous_group)- if query.grouped? && (group = query.group_by_column.value(work_package)) != previous_group- label = make_group_label(group)- group_cell = pdf.make_cell(label,- font_style: :bold,- colspan: column_objects.size,- background_color: 'DDDDDD')-- pdf.table([[group_cell]], column_widths:)-- group- else- previous_group- end- end-- def make_column_value(work_package, column)- formatter = formatter_for(column)-- pdf.make_cell formatter.format(work_package),- padding: cell_padding- end-- def make_group_label(group)- if group.blank?- I18n.t(:label_none_parentheses)- elsif group.is_a? Array- group.join(', ')- else- group.to_s- end- end-- def batch_supported?- return @batch_supported if defined?(@batch_supported)-- @batch_supported = begin- _, status = Open3.capture2e('pdfunite', '-h')- status.success?- rescue StandardError => e- Rails.logger.error "Failed to test pdfunite version: #{e.message}"- false- end- endend