我有一个上传器(仅限内部使用),它将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。