Printing pages in Rails

Ever needed to allow a user to print out a certain page or subset of data using rails? I initially went down the road of generating a PDF and using send_data to let the user download it. However this morning, TJ gave me an all too familiar random revelatory suggestion:

use the built in print functionality of the browser



This can be done quite simply. Start off by creating a controller action and a view for the page you would like to print. Set all instance variables for the erb as you normally would. And somewhere in your view, include the code to print the current page:


(script tag)
$(function(){
window.print()
});
(script tag)


In your controller, if you'd like to bypass the application layout, you can do so, but I opted to only exclude the nav-bar so i would still have access to all of the styles included in the application layout, like so:


class ApplicationController < ActionController::Base
def disable_nav
@disable_nav = true
end
end


I also added the following to the controller that contains my printed page's actions.


before_filter :disable_nav, only: [:print_list, :print_records]


You may want to add the following to your css to control where the page breaks. This keeps the page from breaking inside the print-records div.


.print-records { page-break-inside: avoid; }



And one last thing...i chose to add _blank to all of my links to make the page open in a separate tab.

target="_blank"



Picked by Jared
Jul. 07 2016
note