2012-06-28 31 views
4

我正在使用PDFKit中間件來呈現PDF。這是它的作用:如何讓Rails爲PDFKit呈現PDF特定的HTML?

  • 檢查傳入的請求到應用程序。如果它們是PDF格式,請從應用程序隱藏該事實,但準備修改響應。
  • 讓應用程序呈現爲HTML
  • 取回響應和HTML發送它

一般情況下,我想這種行爲之前轉換爲PDF。但我有一個案例,實際上我需要我的應用根據請求的PDF提供不同的內容。

PDFKit爲我提供了一個標記,用於檢測它是否計劃呈現我的回覆:它將env["Rack-Middleware-PDFKit"]設置爲true。

但我需要告訴Rails,基於那個標誌,我想讓它渲染show.pdf.haml。我怎樣才能做到這一點?

+1

對於2014年在家中的任何人,我發現這個現在是'request.env [「Rack-Middleware-PDFKit」]'並且它返回一個字符串,例如: ' 「真」'。 – pdobb

回答

5

設置請求。格式和響應標頭

找出來。根據the Rails sourcerequest.format = 'pdf'將手動將響應格式設置爲PDF。這意味着Rails將渲染,例如,show.pdf.haml

但是,現在PDFKit不會將響應轉換爲實際PDF,因爲Content-Type標題表示它已經是PDF,因爲實際上我們只生成HTML。所以我們還需要重寫Rails的響應頭,以表示它仍然是HTML。

該控制器的方法處理它:

# By default, when PDF format is requested, PDFKit's middleware asks the app 
# to respond with HTML. If we actually need to generate different HTML based 
# on the fact that a PDF was requested, this method reverts us back to the 
# normal Rails `respond_to` for PDF. 
def use_pdf_specific_template 
    return unless env['Rack-Middleware-PDFKit'] 

    # Tell the controller that the request is for PDF so it 
    # will use a PDF-specific template 
    request.format = 'pdf' 
    # Tell PDFKit that the response is HTML so it will convert to PDF 
    response.headers['Content-Type'] = 'text/html' 
end 

這意味着控制器動作的樣子:

def show 
    @invoice = Finance::Invoice.get!(params[:id]) 

    # Only call this if PDF responses should not use the same templates as HTML 
    use_pdf_specific_template 

    respond_to do |format| 
    format.html 
    format.pdf 
    end 
end 
1

你也可以使用PDFKit沒有中間件。