Prasad Surase
Prasad Surase

Reputation: 6574

PDFkit *.css stylesheets not being applied

I am trying to convert a html page that displays images from facebook cdn to pdf using pdfkit. I am using rails 4.2, pdfkit 0.6.2 and wkhtmltopdf-binary 0.9.9.3.

# Gemfile
gem 'pdfkit'
gem 'wkhtmltopdf-binary'

# controller
def generate_pdf
  @booklet = Booklet.find params[:id]
  @cover = Image.last
  @images = @booklet.images.sort_by(&:uploaded_at)
  respond_to do |format|
    format.html
    format.pdf do
      html = render_to_string(layout: true , action: "generate_pdf.html.haml")
      kit = PDFKit.new(html, page_size: 'A4', orientation: 'Landscape')
      `sass vendor/assets/stylesheets/bootstrap.scss tmp/bootstrap.css`
      `sass vendor/assets/stylesheets/custom.scss tmp/custom.css`
      kit.stylesheets << "#{Rails.root}/tmp/bootstrap.css"
      kit.stylesheets << "#{Rails.root}/tmp/custom.css"
      pdf = kit.to_pdf
      send_data pdf, filename: 'booklet.pdf', type: 'application/pdf'
    end
  end
end

# application.scss
@import 'bootstrap';                                                                                                                                           
@import 'custom';

# config/application.rb
require 'pdfkit'
config.middleware.use PDFKit::Middleware

# config/initializers/mime_types.rb
Mime::Type.register "application/pdf", :pdf unless Mime::Type.lookup_by_extension(:pdf)

The pdf is getting generated and the facebook cdn images are displayed but the stylesheets arent being applied.What am I missing?

I have created a sample repository for the above problem here: https://github.com/prasadsurase/topdf

FYI, the bootstrap.css and custom.css are placed in vendor/assets and have extensions have been renamed to scss. In sass, the assets(fonts and images) have been referred using 'font-path' and 'image-url' rails helper. The assets were precompiled and the application-....css was copied to pdf.css and the assets are referred from the root path(/)

Upvotes: 7

Views: 4106

Answers (1)

igreka
igreka

Reputation: 350

Does Bootstrap work correctly for other pages in your application? -- The aim is to make sure that you configured the meta tags correctly to include the Bootstrap files, and that you are pointing to the Bootstrap files (which seem to be in /tmp?)

Also, on what OS are you coding? May I recommend to substitute "#{Rails.root}/tmp/bootstrap.css" with Rails.root.join('tmp','bootstrap.css')

Let me know if these help at all -- or not.

Upvotes: 0

Related Questions