Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing stuff in rails (literally to a printer)

I'm wondering if there was any library or gem available in Rails for printing the contents of a web page, as in literally on to paper via a printer. I was also wondering if there was any way you can specify that only a specific part of the page (e.g. a div or something) would be printed? Any pointers, advice, or links to tutorials would be appreciated!

EDIT

so I've made a stab at creating a stylesheet which will create a print friendly view, let's call it "print.css":

div.transpose-keys, div#editSong, div#navigation, div#debug{
    display: none;
}

And I was wondering if there was any way I could apply it only when my application fires the print action? So that when the following is link is clicked the application applies the css above before it prints? Here's the link in my embedded ruby html:

<%= link_to "PRINT", '#', onclick: "printpage()" %>

And finally my javascript calling the print function:

function printpage()
  {
  window.print()
  }
like image 584
TangoKilo Avatar asked Jul 19 '12 14:07

TangoKilo


People also ask

What is the difference between print and puts?

Hi, The difference between print and puts is that puts automatically moves the output cursor to the next line (that is, it adds a newline character to start a new line unless the string already ends with a newline), whereas print continues printing text onto the same line as the previous time.

What is the difference between print and puts in Ruby?

While the print method allows you to print information in the same line even multiple times, the puts method adds a new line at the end of the object. On the other hand, p is useful when you are trying to understand what your code does, e.g. when you are trying to figure out a certain error.

What is Ruby type printing?

The Ruby print function is used to display output on the screen. The string or integer value to be printed is passed as an argument to this function. The puts function also displays output. However, puts automatically inserts a newline at the end of the line being printed.


2 Answers

If you add your print.css as follows

<link rel="stylesheet" type="text/css" media="print" href="print.css">

and use browser print dialog, it should automatically format the page according to the style in print.css

like image 179
Peter Pajchl Avatar answered Oct 08 '22 00:10

Peter Pajchl


I got around my problem by using this simple solution:

print.css:

@media print {
  div.info, div#editStuff, div#navigation, div#debug {
    display: none;
  }
}

the @media tag ensures these are not displayed in the printed version

application.js:

function printpage()
{
   window.print()
}

show.html.erb:

<%= link_to "PRINT", '#', onclick: "printpage()" %>
like image 43
TangoKilo Avatar answered Oct 08 '22 01:10

TangoKilo