Получение PDF из WickedPDF для вложения через Carrierwave - программирование
Подтвердить что ты не робот

Получение PDF из WickedPDF для вложения через Carrierwave

В Rails3 я использую WickedPDF gem для рендеринга PDF-формата одной из моих моделей. Это нормально работает: /invoices/123 возвращает HTML, /invoices/123.pdf загружает PDF файл.

В моей модели счета-фактуры я использую драгоценный камень state_machine для отслеживания состояния счета-фактуры. Когда счет-фактура переходит из состояния "невыполненный" в "выставленный счет", я хотел бы получить копию счета-фактуры PDF и прикрепить его к модели счета-фактуры с использованием CarrierWave.

У меня три части, которые работают отдельно: контроллер создает представление в формате PDF, модель отслеживает состояние и вызывает обратный вызов при правильном переходе, а CarrierWave настроен правильно. Тем не менее, у меня есть чертовски время заставить их играть красиво вместе.

Если бы я просто хотел захватить HTML-версию счета, я мог бы вызвать render_to_string из модели. Но render_to_string, похоже, задыхается при получении двоичного файла PDF. Если я смогу вернуть поток данных, довольно легко записать эти данные в файл tempfile и прикрепить его к загрузчику, но я не могу понять, как получить поток данных.

Любые мысли? Код ниже:

Контроллер счетов

def show
  @invoice = @agg_class.find(params[:id])

  respond_to do |format|
    format.pdf do
      render_pdf
    end
    format.html # show.html.erb
    format.json { render json: @aggregation }
  end
end

...

def render_pdf(options = {})
  options[:pdf] = pdf_filename
  options[:layout] = 'pdf.html'
  options[:page_size] = 'Letter'
  options[:wkhtmltopdf] = '/usr/local/bin/wkhtmltopdf'
  options[:margin] = {
    :top      => '0.5in',
    :bottom   => '1in',
    :left     => '0in',
    :right    => '0in'
  }
  options[:footer] = {
    :html => {
      :template   => 'aggregations/footer.pdf.haml',
      :layout     => false,
    }
  }
  options[:header] = {
    :html => {
      :template   => 'aggregations/header.pdf.haml',
      :layout     => false,
    }
  }
  render options
end

Invoice.rb

def create_pdf_copy

   # This does not work.    
   pdf_file = ApplicationController.new.render_to_string(
    :action => 'aggregations/show',
    :format => :pdf,
    :locals => { 
      :invoice => self
    }
  )

  # This part works fine if the above works.
  unless pdf_file.blank?
    self.uploads.clear
    self.uploads.create(:fileinfo => File.new(pdf_file), :job_id => self.job.id)
  end

end

UPDATE Найдите решение.

def create_pdf_copy

    wicked = WickedPdf.new

    # Make a PDF in memory
    pdf_file = wicked.pdf_from_string( 
        ActionController::Base.new().render_to_string(
            :template   => 'aggregations/show.pdf.haml', 
            :layout     => 'layouts/pdf.html.haml',
            :locals     => { 
                :aggregation => self
            } 
        ),
        :pdf => "#{self.type}-#{self}",
        :layout => 'pdf.html',
        :page_size => 'Letter',
        :wkhtmltopdf => '/usr/local/bin/wkhtmltopdf',
        :margin => {
            :top      => '0.5in',
            :bottom   => '1in',
            :left     => '0in',
            :right    => '0in'
        },
        :footer => {
            :content => ActionController::Base.new().render_to_string({
                :template => 'aggregations/footer.pdf.haml', 
                :layout => false
            })
        },
        :header => {
            :content => ActionController::Base.new().render_to_string({
                :template => 'aggregations/header.pdf.haml', 
                :layout => false
            })
        }
    )

    # Write it to tempfile
    tempfile = Tempfile.new(['invoice', '.pdf'], Rails.root.join('tmp'))
    tempfile.binmode
    tempfile.write pdf_file
    tempfile.close

    # Attach that tempfile to the invoice
    unless pdf_file.blank?
        self.uploads.clear
        self.uploads.create(:fileinfo => File.open(tempfile.path), :job_id => self.job.id)
        tempfile.unlink
    end

end
4b9b3361

Ответ 1

Решение:

def create_pdf_copy

    wicked = WickedPdf.new

    # Make a PDF in memory
    pdf_file = wicked.pdf_from_string( 
        ActionController::Base.new().render_to_string(
            :template   => 'aggregations/show.pdf.haml', 
            :layout     => 'layouts/pdf.html.haml',
            :locals     => { 
                :aggregation => self
            } 
        ),
        :pdf => "#{self.type}-#{self}",
        :layout => 'pdf.html',
        :page_size => 'Letter',
        :wkhtmltopdf => '/usr/local/bin/wkhtmltopdf',
        :margin => {
            :top      => '0.5in',
            :bottom   => '1in',
            :left     => '0in',
            :right    => '0in'
        },
        :footer => {
            :content => ActionController::Base.new().render_to_string({
                :template => 'aggregations/footer.pdf.haml', 
                :layout => false
            })
        },
        :header => {
            :content => ActionController::Base.new().render_to_string({
                :template => 'aggregations/header.pdf.haml', 
                :layout => false
            })
        }
    )

    # Write it to tempfile
    tempfile = Tempfile.new(['invoice', '.pdf'], Rails.root.join('tmp'))
    tempfile.binmode
    tempfile.write pdf_file
    tempfile.close

    # Attach that tempfile to the invoice
    unless pdf_file.blank?
        self.uploads.clear
        self.uploads.create(:fileinfo => File.open(tempfile.path), :job_id => self.job.id)
        tempfile.unlink
    end

end