1
votes

I am trying to download my dynamic content as a pdf file. The pdf is being generated but with no content in it, not even a simple text(when I test with that).

As I need a lot of data which I need to calculate and send parameters without refreshing page so I am doing it through an Ajax request.

$("#download_pdf").click(function() {
    report_type = $("#report_type").val();
    start_date = $("#start_date").val();
    end_date = $("#end_date").val();
    date_type = $("#date_type").val();

    $.ajax({
    data: { report_type: report_type, start_date: start_date, end_date: end_date, date_type: date_type },
    url: '/reports/generate_pdf.pdf',
        success: function(data) {
          var blob=new Blob([data]);
          var link=document.createElement('a');
          link.href=window.URL.createObjectURL(blob);
          link.download="Report_"+new Date()+".pdf";
          link.click();
          console.log("pdf printed");
        }
    });
});

Here is my ruby code in the controller:

def generate_pdf

    @results = get_report_result_by_datetype(params[:report_type], params[:start_date], params[:end_date], params[:date_type]) 
    @type = params[:report_type].to_i


    @start_date = params[:start_date]
    @end_date = params[:end_date]

    respond_to do |format|
      format.html
      format.pdf do
        render  pdf:  "report",
          layout:              'pdf_layout',
          template:            'reports/generate_pdf.html.erb',
          encoding:            'UTF8',
          print_media_type:    true,
          disposition:         'attachment',
          page_size:           'letter',
          orientation:         'landscape',
          lowquality:          'false',
          debug:                true
      end
    end
end  

There is no issue in the data which I am fetching.

Note: The most strange thing I noticed is that when the calculated array is small the generated pdf has one page and if it is big the generated pdf shows multiple pages.

I would really appreciate if someone points where I am going wrong.

Thanks in Advance!!

1

1 Answers

0
votes

Although I don't know how to fix your wicked_pdf code, I can recommend the following using the gem prawn (which is not rails-specific and removes some of the Rails magic from the equation):

 format.pdf do
   pdf_path = Rails.root.join("tmp", "my_file_name.pdf")
   template_path = Rails.root.join("app", "views", "reports", "generate_pdf.html.erb")
   this = binding
   Prawn::Document.generate(pdf_path) do
    text Erb.new(template_path).result(this)
   end   
   render file: pdf_path       
 end

Haven't actually tested it so apologies if it doesn't work.