我有一個上傳器(僅限內部使用),它將HTML文檔上傳到面向客戶端的網站中的表格的二進制列。面向客戶的網站有一個索引,允許用戶將該網頁視爲普通網站(使用send_data h_t.html_code, :type => "html", :disposition => "inline"
)。我也想讓用戶能夠下載頁面的PDF。爲此我使用了wicked_pdf。Wicked PDF,從數據庫表格圖像和樣式問題生成PDF
整個問題似乎源於數據存儲在數據庫中的事實。聽起來很奇怪,對於業務操作來說,我對格式化的準確性至關重要。問題是我看不到任何圖像,樣式表/樣式標籤沒有任何效果。
什麼我tried-
Gsub-
def show
html = HtmlTranscript.find(params[:id])
html_code = html.html_code.gsub('<img src="/images/bwTranscriptLogo.gif" alt="Logo">','<%= wicked_pdf_image_tag "bwTranscriptLogo.gif" %>')
html_code = html_code.gsub('<link rel="StyleSheet" href="" type="text/css">','<%= wicked_pdf_stylesheet_link_tag "transcripts.css" %>')
transcript = WickedPdf.new.pdf_from_string(html_code)
respond_to do |format|
format.html do
send_data transcript, :type => "pdf", :disposition => "attachment"
end
##### i never could get this part figured out, so if you have a fix for this...
# format.pdf do
# render :pdf => "transcript_for_#{@html.created_at}", :template => "html_transcripts/show.html.erb", :layout => false
# end
end
end
使用模板 -
#Controller (above, modified)
html = HtmlTranscript.find(params[:id])
@html_code = html.html_code.gsub('<img src="/images/bwTranscriptLogo.gif" alt="Logo">','<%= wicked_pdf_image_tag "bwTranscriptLogo.gif" %>')
@html_code = @html_code.gsub('<link rel="StyleSheet" href="" type="text/css">','<%= wicked_pdf_stylesheet_link_tag "transcripts.css" %>')
transcript = WickedPdf.new.pdf_from_string(render_to_string(:template => "html_transcripts/show.html.erb", :layout => false))
#view
<!-- tried with stylesheet & image link tags, with wicked_pdf stylesheet & image link tags, with html style & img tags, etc -->
<%= raw(@html_code) %>
,都將產生一個transcript-但也不會有風格或圖像。
創建initializer-
module WickedPdfHelper
def wicked_pdf_stylesheet_link_tag(*sources)
sources.collect { |source|
"<style type='text/css'>#{Rails.application.assets.find_asset("#{source}.css")}</style>"
}.join("\n").gsub(/url\(['"](.+)['"]\)(.+)/,%[url("#{wicked_pdf_image_location("\\1")}")\\2]).html_safe
end
def wicked_pdf_image_tag(img, options={})
image_tag wicked_pdf_image_location(img), options
end
def wicked_pdf_image_location(img)
"file://#{Rails.root.join('app', 'assets', 'images', img)}"
end
def wicked_pdf_javascript_src_tag(source)
"<script type='text/javascript'>#{Rails.application.assets.find_asset("#{source}.js").body}</script>"
end
def wicked_pdf_javascript_include_tag(*sources)
sources.collect{ |source| wicked_pdf_javascript_src_tag(source) }.join("\n").html_safe
end
end
做絕對沒有,我不知道下一個嘗試的東西。
作爲一個側面說明,查看成績單的HTML版本的代碼如下:
def transcript_data
h_t = HtmlTranscript.find(params[:id])
send_data h_t.html_code, :type => "html", :disposition => "inline"
end
它不要求來看,作爲HTML數據存儲在數據庫中,但我得到的圖像,風格等等。一切都適用於HTML版本 - 僅僅是PDF。
我在紅寶石1.8.7與軌道3.0.20。