Skip to content


Prawn and Scribd in the same controller action

I realized that I solved a problem that others may have encountered before. I’m not using ruport, but just using prawn and prawnto to generate pdfs for my application. In the process I wanted to have the ability to generate the PDF and either send it back as a response to the user or put it up on scribd to display embedded within a webpage within the application. I had to hack a little bit of code to get it to work, but overall, I’m pleased with the final solution.

Here’s what the key part of the controller looks like:

    respond_to do |format|
      format.html {
        source_filename = "#{RAILS_ROOT}/app/views/management/employees/print_ids.pdf.prawn"
        prawn_params = {:employees => @employees}
        print_scribd(source_filename, prawn_params, "globaltrack,\"employee ids\",#{RAILS_ENV}")
      }
      format.pdf {
        prawnto :dsl_pdf=> {'@employees' => @employees}, :inline => false
        render :layout => false
      }
    end

Then I can do whatever I want with the template and not worry about really different code in the template because it either is or isn’t running in prawn or prawnto.

So, my alteration (see hack) to make this all work happened in the prawnto library code. I added the :dsl_pdf option in the render method of the Base template handler. So, the final render method looks like this:

      def render(template)
        pull_prawnto_options
        build_headers
 
        source = build_source_to_establish_locals(template)
        if @prawnto_options[:dsl] || @prawnto_options[:dsl_pdf]
          source += "pdf.instance_eval do\n#{template.source}\nend"
        else
          source += "\n#{template.source}"
        end
 
        pdf = Prawn::Document.new(@prawnto_options[:prawn])
        if @prawnto_options[:dsl_pdf]
          @prawnto_options[:dsl_pdf].each { |key,value|
            pdf.instance_variable_set( "#{key}", value)
          }
        end
        @view.instance_eval source, template.filename, 1
        pdf.render
      end

Posted in Uncategorized.


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.