app/reports/questionnaire_pdf.rb
def to_pdf  requester, user, questionnaire, url_prefix, short_version=false
    font_families.update(
      "DejaVuSans" => { # Using DejaVuSans because it provides the 'filled_check_box' and the 'check_box' icons.
        :bold => "#{Rails.root}/public/data/fonts/DejaVuSans-Bold.ttf",
        :bold_italic => "#{Rails.root}/public/data/fonts/DejaVuSans-BoldOblique.ttf",
        :italic => "#{Rails.root}/public/data/fonts/DejaVuSans-Oblique.ttf",
        :normal => "#{Prawn::BASEDIR}/data/fonts/DejaVuSans.ttf"
      }
    )
    font "DejaVuSans"
    self.font_size = 9

    #check_box = "\xE2\x98\x90"
    #filled_check_box = "\xE2\x98\x91"

    ap = ApplicationProfile.first
    current_instance = (ap && ap.sub_title) || Rails.root.to_s.split('/')[3].split('-').first
    ap_logo = ap && ap.logo && ap.logo.path
    fallback_logo = Dir.glob("public/assets/logos/#{current_instance.split('-').first}*", File::FNM_CASEFOLD).first
    logo = ap_logo || "#{Rails.root}/#{fallback_logo}"
    image logo, position: :right, width: 150 if logo
    text "#{current_instance.upcase}", size: 14, style: :bold

    move_down 10

    banner = questionnaire.header.path
    if banner.present? && File.exist?(banner)
      image banner, :position => :left, :width => 550
    end

    move_down 20

    authorization = AuthorizedSubmitter.find_by_questionnaire_id_and_user_id(questionnaire.id, user.id)
    I18n.locale = authorization.language
    questionnaire_field = ( questionnaire.questionnaire_fields.find_by_language(authorization.language) || questionnaire.questionnaire_fields.find_by_is_default_language(true) )
    text "#{questionnaire_field.title.html_safe}", :size => 16, :style => :bold
    #text "Language: #{questionnaire.language_english_name}"

    move_down 18

    text "#{OrtSanitize.white_space_cleanse(questionnaire_field.introductory_remarks).gsub("\n", "\n\n")}", :inline_format => true

    start_new_page

    fields = {}

    puts "#{Time.now} - Started generating #{short_version ? "short" : ""} PDF for - #{questionnaire_field.title} - for #{user.full_name}"
    logger.info "#{Time.now} - Started generating #{short_version ? "short" : ""} PDF for - #{questionnaire_field.title} - for #{user.full_name}"

    begin
      sections = questionnaire.sections
      sections.each_with_index do |section, i|
        fields.clear
        section.objects_fields_in authorization.language, fields
        answers = section.section_and_descendants_answers_for(user).select{ |ans| ans.filled_answer? }
        root_section_to_pdf(authorization.language, section, user, fields, answers, url_prefix, short_version)

        # new page for every new root section (if we're doing a short_version pdf only add the new page if the answers aren't empty)
        # the last check on the if is related with checking if there is any content for the next page
        if i < sections.size-1 && (!short_version || !answers.empty?) && page.content.stream !="/DeviceRGB cs\n0.000 0.000 0.000 scn\n/DeviceRGB CS\n0.000 0.000 0.000 SCN\nq\n" && cursor != 720.0
          # puts "the cursor is here #{cursor}"
          start_new_page
        end
      end

      #footer [ margin_box.left, margin_box.bottom + 25 ] do
      repeat(:all, :dynamic => true) do
        draw_text "#{questionnaire_field.title} [#{user.full_name}, #{user.country}]", :size => 7, :at => [0, -15]
        draw_text "Page #{page_number} of #{page_count}", :size => 8, :at => [500, (questionnaire.title.size > 50 ? -6 : -15)]
      end

      pdf_file = questionnaire.pdf_files.find_by_user_id_and_is_long(user.id, !short_version) || PdfFile.new(:questionnaire => questionnaire, :user => user, :is_long => !short_version)
      if !pdf_file.new_record? && File.exist?(pdf_file.location)
        FileUtils.rm(pdf_file.location)
      end

      sanitized_title = questionnaire.title[0,35].strip.
        gsub!(/[^0-9A-Za-z.\-]/, '_')

      pdf_file.name = "#{sanitized_title}_#{short_version ? "short" : "long"}_#{DateTime.now.strftime("%d%m%Y")}.pdf"
      location_rel = "private/questionnaires/#{questionnaire.id}/users/#{user.id}/"
      location_abs = "#{Rails.root}/#{location_rel}"
      if !File.directory? location_abs
        FileUtils.mkdir_p(location_abs)
      end
      pdf_file.location = location_rel + pdf_file.name
      pdf_file.save
      render_file pdf_file.location

      if File.directory?("#{Rails.root}/private/questionnaires/#{questionnaire.id}/users/#{user.id}/generating_#{short_version ? "short" : "long"}_pdf")
        FileUtils.rmdir("#{Rails.root}/private/questionnaires/#{questionnaire.id}/users/#{user.id}/generating_#{short_version ? "short" : "long"}_pdf")
      end

      puts "#{Time.now.to_s} - PDF Successfully generated - #{questionnaire_field.title} - for #{user.full_name}"
      logger.info "#{Time.now.to_s} - PDF Successfully generated - #{questionnaire_field.title} - for #{user.full_name}"

    rescue => e
      UserMailer.pdf_generation_failed(requester, user, questionnaire, e.message).deliver

      logger.info "#{Time.now.to_s} - PDF failed to generate - #{questionnaire_field.title} - for #{user.full_name} - with error: #{e.message}"
      logger.info e.backtrace

      if File.directory?("#{Rails.root}/private/questionnaires/#{questionnaire.id}/users/#{user.id}/generating_#{short_version ? "short" : "long"}_pdf")
        FileUtils.rmdir("#{Rails.root}/private/questionnaires/#{questionnaire.id}/users/#{user.id}/generating_#{short_version ? "short" : "long"}_pdf")
      end

      return
    end

    # mail the requester about the pdf being generated. (can be the user or an admin)
    UserMailer.pdf_generated(requester, questionnaire, user).deliver
  end
# Generates a PDF file for questionnaire with the user's answers.
# If short_version is true it will only print the section and/or questions that have answers
Generates a PDF file for questionnaire with the user's answers.
If short_version is true it will only print the section and/or questions that have answers
Generates a PDF file for questionnaire with the user ' s answers . If short_version is true it will only print the section and / or questions that have answers
def to_pdf  requester, user, questionnaire, url_prefix, short_version=false
    font_families.update(
      "DejaVuSans" => { 
        :bold => "#{Rails.root}/public/data/fonts/DejaVuSans-Bold.ttf",
        :bold_italic => "#{Rails.root}/public/data/fonts/DejaVuSans-BoldOblique.ttf",
        :italic => "#{Rails.root}/public/data/fonts/DejaVuSans-Oblique.ttf",
        :normal => "#{Prawn::BASEDIR}/data/fonts/DejaVuSans.ttf"
      }
    )
    font "DejaVuSans"
    self.font_size = 9
    ap = ApplicationProfile.first
    current_instance = (ap && ap.sub_title) || Rails.root.to_s.split('/')[3].split('-').first
    ap_logo = ap && ap.logo && ap.logo.path
    fallback_logo = Dir.glob("public/assets/logos/#{current_instance.split('-').first}*", File::FNM_CASEFOLD).first
    logo = ap_logo || "#{Rails.root}/#{fallback_logo}"
    image logo, position: :right, width: 150 if logo
    text "#{current_instance.upcase}", size: 14, style: :bold
    move_down 10
    banner = questionnaire.header.path
    if banner.present? && File.exist?(banner)
      image banner, :position => :left, :width => 550
    end
    move_down 20
    authorization = AuthorizedSubmitter.find_by_questionnaire_id_and_user_id(questionnaire.id, user.id)
    I18n.locale = authorization.language
    questionnaire_field = ( questionnaire.questionnaire_fields.find_by_language(authorization.language) || questionnaire.questionnaire_fields.find_by_is_default_language(true) )
    text "#{questionnaire_field.title.html_safe}", :size => 16, :style => :bold
    move_down 18
    text "#{OrtSanitize.white_space_cleanse(questionnaire_field.introductory_remarks).gsub("\n", "\n\n")}", :inline_format => true
    start_new_page
    fields = {}
    puts "#{Time.now} - Started generating #{short_version ? "short" : ""} PDF for - #{questionnaire_field.title} - for #{user.full_name}"
    logger.info "#{Time.now} - Started generating #{short_version ? "short" : ""} PDF for - #{questionnaire_field.title} - for #{user.full_name}"
    begin
      sections = questionnaire.sections
      sections.each_with_index do |section, i|
        fields.clear
        section.objects_fields_in authorization.language, fields
        answers = section.section_and_descendants_answers_for(user).select{ |ans| ans.filled_answer? }
        root_section_to_pdf(authorization.language, section, user, fields, answers, url_prefix, short_version)
        if i < sections.size-1 && (!short_version || !answers.empty?) && page.content.stream !="/DeviceRGB cs\n0.000 0.000 0.000 scn\n/DeviceRGB CS\n0.000 0.000 0.000 SCN\nq\n" && cursor != 720.0
          start_new_page
        end
      end
      repeat(:all, :dynamic => true) do
        draw_text "#{questionnaire_field.title} [#{user.full_name}, #{user.country}]", :size => 7, :at => [0, -15]
        draw_text "Page #{page_number} of #{page_count}", :size => 8, :at => [500, (questionnaire.title.size > 50 ? -6 : -15)]
      end
      pdf_file = questionnaire.pdf_files.find_by_user_id_and_is_long(user.id, !short_version) || PdfFile.new(:questionnaire => questionnaire, :user => user, :is_long => !short_version)
      if !pdf_file.new_record? && File.exist?(pdf_file.location)
        FileUtils.rm(pdf_file.location)
      end
      sanitized_title = questionnaire.title[0,35].strip.
        gsub!(/[^0-9A-Za-z.\-]/, '_')
      pdf_file.name = "#{sanitized_title}_#{short_version ? "short" : "long"}_#{DateTime.now.strftime("%d%m%Y")}.pdf"
      location_rel = "private/questionnaires/#{questionnaire.id}/users/#{user.id}/"
      location_abs = "#{Rails.root}/#{location_rel}"
      if !File.directory? location_abs
        FileUtils.mkdir_p(location_abs)
      end
      pdf_file.location = location_rel + pdf_file.name
      pdf_file.save
      render_file pdf_file.location
      if File.directory?("#{Rails.root}/private/questionnaires/#{questionnaire.id}/users/#{user.id}/generating_#{short_version ? "short" : "long"}_pdf")
        FileUtils.rmdir("#{Rails.root}/private/questionnaires/#{questionnaire.id}/users/#{user.id}/generating_#{short_version ? "short" : "long"}_pdf")
      end
      puts "#{Time.now.to_s} - PDF Successfully generated - #{questionnaire_field.title} - for #{user.full_name}"
      logger.info "#{Time.now.to_s} - PDF Successfully generated - #{questionnaire_field.title} - for #{user.full_name}"
    rescue => e
      UserMailer.pdf_generation_failed(requester, user, questionnaire, e.message).deliver
      logger.info "#{Time.now.to_s} - PDF failed to generate - #{questionnaire_field.title} - for #{user.full_name} - with error: #{e.message}"
      logger.info e.backtrace
      if File.directory?("#{Rails.root}/private/questionnaires/#{questionnaire.id}/users/#{user.id}/generating_#{short_version ? "short" : "long"}_pdf")
        FileUtils.rmdir("#{Rails.root}/private/questionnaires/#{questionnaire.id}/users/#{user.id}/generating_#{short_version ? "short" : "long"}_pdf")
      end
      return
    end
    UserMailer.pdf_generated(requester, questionnaire, user).deliver
  end
def to_pdf requester , user , questionnaire , url_prefix , short_version = false font_families . update ( "DejaVuSans" => { :bold => "#{Rails.root}/public/data/fonts/DejaVuSans-Bold.ttf" , :bold_italic => "#{Rails.root}/public/data/fonts/DejaVuSans-BoldOblique.ttf" , :italic => "#{Rails.root}/public/data/fonts/DejaVuSans-Oblique.ttf" , :normal => "#{Prawn::BASEDIR}/data/fonts/DejaVuSans.ttf" } ) font "DejaVuSans" self . font_size = 9 ap = ApplicationProfile . first current_instance = ( ap && ap . sub_title ) || Rails . root . to_s . split ( '/' ) [ 3 ] . split ( '-' ) . first ap_logo = ap && ap . logo && ap . logo . path fallback_logo = Dir . glob ( "public/assets/logos/#{current_instance.split('-').first}*" , File :: FNM_CASEFOLD ) . first logo = ap_logo || "#{Rails.root}/#{fallback_logo}" image logo , position : :right , width : 150 if logo text "#{current_instance.upcase}" , size : 14 , style : :bold move_down 10 banner = questionnaire . header . path if banner . present? && File . exist? ( banner ) image banner , :position => :left , :width => 550 end move_down 20 authorization = AuthorizedSubmitter . find_by_questionnaire_id_and_user_id ( questionnaire . id , user . id ) I18n . locale = authorization . language questionnaire_field = ( questionnaire . questionnaire_fields . find_by_language ( authorization . language ) || questionnaire . questionnaire_fields . find_by_is_default_language ( true ) ) text "#{questionnaire_field.title.html_safe}" , :size => 16 , :style => :bold move_down 18 text "#{OrtSanitize.white_space_cleanse(questionnaire_field.introductory_remarks).gsub("\n", "\n\n")}" , :inline_format => true start_new_page fields = { } puts "#{Time.now} - Started generating #{short_version ? "short" : ""} PDF for - #{questionnaire_field.title} - for #{user.full_name}" logger . info "#{Time.now} - Started generating #{short_version ? "short" : ""} PDF for - #{questionnaire_field.title} - for #{user.full_name}" begin sections = questionnaire . sections sections . each_with_index do | section , i | fields . clear section . objects_fields_in authorization . language , fields answers = section . section_and_descendants_answers_for ( user ) . select { | ans | ans . filled_answer? } root_section_to_pdf ( authorization . language , section , user , fields , answers , url_prefix , short_version ) if i < sections . size - 1 && ( ! short_version || ! answers . empty? ) && page . content . stream != "/DeviceRGB cs\n0.000 0.000 0.000 scn\n/DeviceRGB CS\n0.000 0.000 0.000 SCN\nq\n" && cursor != 720.0 start_new_page end end repeat ( :all , :dynamic => true ) do draw_text "#{questionnaire_field.title} [#{user.full_name}, #{user.country}]" , :size => 7 , :at => [ 0 , - 15 ] draw_text "Page #{page_number} of #{page_count}" , :size => 8 , :at => [ 500 , ( questionnaire . title . size > 50 ? - 6 : - 15 ) ] end pdf_file = questionnaire . pdf_files . find_by_user_id_and_is_long ( user . id , ! short_version ) || PdfFile . new ( :questionnaire => questionnaire , :user => user , :is_long => ! short_version ) if ! pdf_file . new_record? && File . exist? ( pdf_file . location ) FileUtils . rm ( pdf_file . location ) end sanitized_title = questionnaire . title [ 0 , 35 ] . strip . gsub! ( / [^0-9A-Za-z. \- ] / , '_' ) pdf_file . name = "#{sanitized_title}_#{short_version ? "short" : "long"}_#{DateTime.now.strftime("%d%m%Y")}.pdf" location_rel = "private/questionnaires/#{questionnaire.id}/users/#{user.id}/" location_abs = "#{Rails.root}/#{location_rel}" if ! File . directory? location_abs FileUtils . mkdir_p ( location_abs ) end pdf_file . location = location_rel + pdf_file . name pdf_file . save render_file pdf_file . location if File . directory? ( "#{Rails.root}/private/questionnaires/#{questionnaire.id}/users/#{user.id}/generating_#{short_version ? "short" : "long"}_pdf" ) FileUtils . rmdir ( "#{Rails.root}/private/questionnaires/#{questionnaire.id}/users/#{user.id}/generating_#{short_version ? "short" : "long"}_pdf" ) end puts "#{Time.now.to_s} - PDF Successfully generated - #{questionnaire_field.title} - for #{user.full_name}" logger . info "#{Time.now.to_s} - PDF Successfully generated - #{questionnaire_field.title} - for #{user.full_name}" rescue => e UserMailer . pdf_generation_failed ( requester , user , questionnaire , e . message ) . deliver logger . info "#{Time.now.to_s} - PDF failed to generate - #{questionnaire_field.title} - for #{user.full_name} - with error: #{e.message}" logger . info e . backtrace if File . directory? ( "#{Rails.root}/private/questionnaires/#{questionnaire.id}/users/#{user.id}/generating_#{short_version ? "short" : "long"}_pdf" ) FileUtils . rmdir ( "#{Rails.root}/private/questionnaires/#{questionnaire.id}/users/#{user.id}/generating_#{short_version ? "short" : "long"}_pdf" ) end return end UserMailer . pdf_generated ( requester , questionnaire , user ) . deliver end
Generates a PDF file for questionnaire with the user's answers.
Generates a PDF file for questionnaire with the user ' s answers .
# Using DejaVuSans because it provides the 'filled_check_box' and the 'check_box' icons. #check_box = "\xE2\x98\x90" #filled_check_box = "\xE2\x98\x91" #text "Language: #{questionnaire.language_english_name}" # new page for every new root section (if we're doing a short_version pdf only add the new page if the answers aren't empty) # the last check on the if is related with checking if there is any content for the next page # puts "the cursor is here #{cursor}" #footer [ margin_box.left, margin_box.bottom + 25 ] do # mail the requester about the pdf being generated. (can be the user or an admin)
requester
user
questionnaire
url_prefix
short_version