cssruby-on-railswicked-pdf

rendering an image from a rails css file for wicked PDF


A cascading nesting of objects is identified via an image relative to the level of nesting:

#nestedlist, #nestedlist li {
  font-size: 12px;
  list-style-type: none;
}
#nestedlist ul  {
  list-style-image: url("/yellow_dark.png"); 
} 
/* UL Layer # Rules based on quantity_of_ul */
#nestedlist ul ul  {
  list-style-image: url("red_base.png"); 
}
#nestedlist ul ul ul {
  list-style-image: url("/green_light.png");
}

etc.

this renders properly in the browser, notwithstanding the location of the image, in the public directory or in the assets directory. However wicked PDF requires an absolute path for images and cannot handle the above; it will return a blank if list-style-type: none; or a black bullet if that is not specified. attempted to use list-type: square; but that, alas, does not take colour options.

How could a css file be cast to provide absolute urls for images in a precompiled css file invoked by the pdflayout for wicked_pdf?


Solution

  • You have to configure asset_host, because, when it is not specificly set wickedpdf will use local file:// urls, which didn't work for me:

    if pathname =~ URI_REGEXP
      # asset_path returns an absolute URL using asset_host if asset_host is set
      pathname
    else
      File.join(Rails.public_path, asset.sub(/\A#{Rails.application.config.action_controller.relative_url_root}/, ''))
    end
    

    https://github.com/mileszs/wicked_pdf/blob/2.6.3/lib/wicked_pdf/wicked_pdf_helper/assets.rb#L131


    # config/environment/development.rb
    
    config.action_controller.asset_host = "http://localhost:3000"
    
    /* app/assets/stylesheets/pdf.css */
    
    ul {
      list-style-image: url("circle.svg");
    }
    
    <!-- show.pdf.erb -->
    
    <%= wicked_pdf_stylesheet_link_tag "pdf" %>
    
    <ul>
      <li>Peaches</li>
      <li>Apples</li>
      <li>Plums</li>
    </ul>
    

    wicked_pdf_stylesheet_link_tag helper now outputs this:

    <style type='text/css'>
    ul {
      list-style-image: url(http://localhost:3000/assets/circle-a438dbaaf222a262201c1d46bd32e81d2ecb96f95fd50d00a5ad9b57a7778248.svg);
    }
    </style>
    

    pdf


    You could also try using asset_url("circle.svg") explicitly to get a full url or wicked_pdf_asset_base64("circle.svg") to inline a data url.