#CSS, Print, Rails 🇬🇧
Printable views with css in RubyOnRails
Jeanro Krupa
Jeanro Krupa
3 min read
Why use print mode ?
At Komin.io some of our clients have requested a printable version of the playbook they create through our application.
There are two main use cases for this feature:
There are two main use cases for this feature:
- Training companies need a "paper" version to provide to their customers, allowing them to follow the training and have a reference after the training is finished.
- Second, industrial companies without Wi-Fi access in their workshops require a print mode for practical purposes.
2 solutions for the feature
Two technical solutions were considered, although there may be others that I am not aware of:
- Using a gem like PDFKit or WickedPdf to generate the PDF on the backend and attach it to our Playbook model. However, I encountered some difficulties with these gems, particularly in terms of designing the generated PDF.
- Utilizing the power of Css and the page media
I chose the latter option to provide more flexibility in design and for the sake of simplicity.
Css media Print
The page I needed to design is the show view of a Playbook. To achieve this, I divided the view into two sections: one for the classic web mode and another for the print mode. Here is an example: 👇
<%# Classic Web mode %> <div class="print:hidden"> ... </div> <%# Print mode %> <div class="print-only"> ... </div>
To enable this functionality, update the
tailwind.config.js
file:module.exports = { purge: [], theme: { extend: { screens: { print: { raw: 'print' }, }, }, }, }
With this configuration, you can use the
print:
prefix, similar to other media queries such as md:
or lg:
.Next, define the
print-only
class in your CSS:.print-only { display: none; } @media print { .print-only { display: block; } }
For example, if you have a navbar that should not be displayed in the printable version, simply add the
print:hidden
class.Now that everything is in place, you can test the result in Chrome by entering print mode using the
Cmd+P
shortcut.The `@page` media css
Now that we have set up the print version, we can work on our view as usual. However, you may notice that the pagination looks less than ideal. Luckily, you can define different rules for the
@page
media. Here is an example of CSS with useful classes:@page { size: A4; } @page:first { margin-top: 0; } .frontcover { width: 100%; page-break-after: always; } .chapter.first-chapter { page-break-before: avoid; } .print-content { page-break-inside: avoid; }
Good to know
Always using the
Cmd+P
shortcut can become tedious. In Chrome, you can stay in print mode to preview your work. However, this feature is not very user-friendly. To address this, you can refer to this post for an alternative solution:Resources:
If you're looking for more information about designing for print with CSS, I highly recommend this amazing blog article: https://www.smashingmagazine.com/2015/01/designing-for-print-with-css/