• Stars
    star
    175
  • Rank 218,059 (Top 5 %)
  • Language
    HTML
  • License
    MIT License
  • Created about 6 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A reliable way to generate PDF of any complexity in Ruby on Rails apps

Rails PDF

RailsJazz https://www.patreon.com/igorkasyanchuk Listed on OpenSource-Heroes.com

Create PDF documents in Rails your app from HTML, CSS and JS.

Features:

  • Basically, you can create any HTML/CSS/JS/Images page and save into PDF
  • Generate PDF on the fly or save to disk
  • With header, footer, page numbers, layout support
  • Has few starter templates to help with most popular reports. Just create some and re-edit it
  • Support for Charts libraries
  • ERB/SCSS support
  • Custome & Google fonts
  • Separates PDF templates from app views
  • Doesn't insert any middleware into your app
  • Pub format is similar to slim
  • Pass locals to the view
  • Works with ActiveStorage

It's uses ReLaXedJS tool, which is wrapper arround chromium headless.

The idea of this gem is to separate logic of PDF creation from regular Rails views/controllers. Make it independent and easy to maintain.

Template starters (build-it with generator)

If you want to contribute and add more templates - it' very easy to do. See #Templates section of this doc.

Template: simple_invoice Template: basic_invoice Template: chart1
Template: products

Usage

You can use predefined starter templates (and you are welcome to contribute and create additional templates):

Use template starters:

  • rails g rails_pdf new invoice_report (create blank template for PDF)
  • rails g rails_pdf basic_invoice report
  • rails g rails_pdf chart1 report
  • rails g rails_pdf simple_invoice report

After you've generated PDF template, you can edit it in app/pdf/<folder>/<file> file.

You can use JS/CSS files from app/pdf/shared (which includes bootstrap 4, foundation 6, Found Awesome 5, Charts.js).

This is how you can generate and send PDF files on the fly:

  def report
    RailsPDF.template("report2/invoice.pug.erb").render do |data|
      send_data(data, type: 'application/pdf', disposition: 'inline', filename: 'report.pdf')
    end
  end

  # or return file as attachment

  def invoice
    RailsPDF.template("report2/invoice.pug.erb").render do |data|
      send_data(data, type: 'application/pdf', disposition: 'attachment', filename: 'report.pdf')
    end
  end

  # sample with locals
  # works similar how regular partials works

  def report
    @invoice = Invoice.find(params[:id])
    RailsPDF.template("report2/invoice.pug.erb").locals(invoice: @invoice).render do |data|
      send_data(data, type: 'application/pdf', disposition: 'inline', filename: 'report.pdf')
    end
  end

If you need to create PDF file and save to file on drive:

RailsPDF.template("report/chart.pug.erb").render_to_file('path/docs/report.pdf') # File

# or for html template

RailsPDF.template("sales/invoice.html.erb").render_to_file('path/docs/report.pdf') # File

Same but save PDF into Temfile:

RailsPDF.template("report/chart.pug.erb").render_to_tempfile('report.pdf') # Tempfile

With ERB files you can use App code (like models, etc). For example you can iterate over @users and output in PDF.

JS/CSS/Images

Basically you need to put an absolute path to asset or remote URL (for example on CDN. but local files works faster).

style
  include:scss <%= Rails.root %>/app/pdf/report/stylesheets/invoice.scss

img(src="<%= Rails.root %>/app/pdf/shared/images/rails_pdf.png")

script(src='<%= Rails.root %>/app/pdf/shared/javascripts/Chart.bundle.min.js')

ActiveStorage integration

You need to specify path to file on disk (or URL to the image if stored in the cloud).

# model
class Project < ApplicationRecord
  has_one_attached :logo
end

# simple controller
def download_project
  RailsPDF.template("report3/invoice.pug.erb").locals(project: Project.first).render do |data|
    send_data(data, type: 'application/pdf', disposition: 'inline', filename: 'report.pdf')
  end
end
body
  header.clearfix
    #logo
      img(src="<%= ActiveStorage::Blob.service.send(:path_for, project.logo.key) %>")
    h1 <%= project.title %>

Installation

Installation of gem is very simple, it's just requires one additional step to install RelaxedJS tool which is using Chrome headless.

Requirements

  • RelaxedJS 0.2.0+ (check with relaxed --version)
  • Chrome headless (bundled with relaxedjs)
  • Rails 4.2+ app

Install RelaxedJS

$ git clone https://github.com/RelaxedJS/ReLaXed.git .
$ npm install
$ sudo npm link --unsafe-perm=true

Verify it's installed with: relaxed --version.

Gemfile

gem 'rails_pdf'

And then execute:

$ bundle

Templates

Tips

  • if you want to add a page-break in document: div(style="page-break-before:always")
  • if you are using bootstrap and you want to use columns - include bootstrap.print.css and use styles from it.
  • if you are using Charts.js and you want to clear and readable text put in options: devicePixelRatio: 3,
  • you can define size of page using in SCSS:
  // A4
  $page-width: 8.27in;
  $page-height: 11.69in;
  • if you want to add header/footer (sample: lib/generators/rails_pdf/templates/simple_invoice/invoice.pug.erb)
  h1 My document
  p some paragraph

  template#page-header
    p I appear at the top of the page

  template#page-footer
    p I appear at the bottom of the page
  • if you see an error, or something is not generated check TMP folder (e.g. /tmp) tmp/*.html file (see most recent files).
  • if you have problems with Charts.js you can add setTimeout(...) and execute chart creation in 200-300ms.

Development

  • open test/dummy
  • bundle exec rake db:migrate
  • bundle exec rails s -b 0.0.0.0
  • open localhost:3000/report.pdf
  • modify templates in app/pdf

Adding a new template

  • add new template in lib/generators/rails_pdf/templates and add folder with template (html,css,js)
  • you can use CSS/JS from templates/shared folder
  • edit lib/generators/rails_pdf/rails_pdf_generator.rb add new type of report
  • create screenshot of template and put in docs folder
  • update docs
  • create PR

TODO

  • more starter templates
    • add starter template with page numbers
  • add different charts
  • better way to include JS/CSS/images
  • maybe we don't need to include all views
  • support non-rails apps
  • specs
  • travis CI
  • codeclimate
  • check support for older Rails (should work but check is needed)
  • check embedding in emails
  • maybe add ability to save webpage by url or HTML snippet to PDF, e.g. RailsPDF.url("http://google.com").render_to_file("google.com.pdf")
  • better gem logo :)

Production

Before deploy app to production please don't forget to install Relaxed.JS on it.

Contributing

You are welcome to contribute.

Contributors

License

The gem is available as open source under the terms of the MIT License.

More Repositories

1

rails_db

Rails Database Viewer and SQL Query Runner
JavaScript
1,447
star
2

active_storage_validations

Do it like => validates :photos, attached: true, content_type: ['image/png', 'image/jpg', 'image/jpeg'], size: { less_than: 500.kilobytes }, limit: { min: 1, max: 3 }, aspect_ratio: :landscape, dimension: { width: { in: 800..1600 }
Ruby
959
star
3

rails_performance

Monitor performance of you Rails applications (self-hosted and free)
Ruby
793
star
4

any_login

Easy way to login as any user in system
Ruby
376
star
5

log_analyzer

Rails logs analyzer (see how fast your views are rendering)
Ruby
349
star
6

fake_api

The fastest way to prototype API in your Rails application
Ruby
142
star
7

execution_time

How fast is your code? See it directly in Rails console.
Ruby
111
star
8

benchmark_methods

Benchmark and measure execution time your Ruby methods without an additional code changes
Ruby
89
star
9

new_google_recaptcha

reCAPTCHA v3 Ruby on Rails gem
Ruby
82
star
10

transactify

Wrap your methods in DB Transactions
Ruby
55
star
11

sql_view

Rails SQL Views made easy ;)
Ruby
49
star
12

sweet_staging

Access your Rails console, see logs, execute rake commands directly from the browser. Great addition to your Staging ENV.
JavaScript
46
star
13

execute_sql

Execute SQL inside Rails console, or app itself
Ruby
41
star
14

cache_with_locale

Easy wait to do view caching with automatically added "locale" value to the cached key.
Ruby
37
star
15

avatarro

Generate google-style avatars in your application
Ruby
37
star
16

awesome_back_url

Redirect the user to the proper "back" page
Ruby
33
star
17

records_count

See in development logs how many records your queries returns. It can help with solving performance issues.
Ruby
31
star
18

new_ckeditor

Ruby on Rails + CKEditor 5
Ruby
31
star
19

amazon_static_site

Static website using https with your own domain name using Amazon S3 and Cloudflare for FREE
Ruby
29
star
20

omg_image

Generate PNG previews for HTML snippets (html/css/js). Any complexity.
Ruby
28
star
21

wrapped_print

Easy print debug information to your console in Ruby/Rails app.
Ruby
23
star
22

calculate_in_group

Group Active Record by ranges or set of values with a single SQL query.
Ruby
22
star
23

embed_view

Embed ERB files inside another ERB files for faster performance (5-20% BOOST!!!)
HTML
21
star
24

rails_time_travel

HTML
19
star
25

sabotage

Coding & debugging must be fun. Make life a bit harder for your colleagues :)
Ruby
18
star
26

mechanical

All models in a single table, new attributes without migrations. Works like regular AR model
Ruby
17
star
27

secrett11tto

Simple way to protect your content from copy-pasting
Ruby
15
star
28

rails_live

Ruby
15
star
29

mini-guard

Ruby
14
star
30

railsjazz.com

Rails Jazz (personal web site)
JavaScript
14
star
31

sidekiq_log_analyzer

SidekiqLogAnalyser gem allows to see summary of your sidekiq workers (based on log file).
Ruby
13
star
32

hasharay_ext

Painless work with complex Ruby hashes/arrays.
Ruby
13
star
33

active_storage_silent_logs

The idea of this gem is to hide as much as possible Active Storage logs from console so you can see only important information and requests
Ruby
13
star
34

rails_cached_method

Simple way to cache results of methods.
Ruby
11
star
35

with_record

Returns relations/association for soft deleted records in DB
Ruby
10
star
36

rrr

Run recent rspec files only (the only recently modified).
Ruby
9
star
37

font_awesome_file_icons

Ruby
4
star
38

unwhere

Ruby
4
star
39

travel_and_talk

JavaScript
3
star
40

lazy_mobile_tester

Rails Lazy Mobile Tester
Ruby
3
star
41

serpjazz

SERP keywords tracking
JavaScript
3
star
42

jeanappv2

JavaScript
2
star
43

slim_erb_backport

Slim 4+ and ERB friends again :)
Ruby
2
star
44

mega-simple-authorization

mega simple authorization plugin for RoR
Ruby
2
star
45

tv

eb5 tv
JavaScript
2
star
46

spring_rspec_commands_addon

rails+spring+rspec = friends :)
Ruby
2
star
47

layouts_from_db_sample

Allow store layouts to DB (Sample)
2
star
48

CheaperDrinker

CheaperDrinker web site
JavaScript
2
star
49

tell_my_env

Ruby
2
star
50

any_login_test

AnyLogin gem test application
Ruby
2
star
51

VerySimple

1
star
52

ShareT

online translations
JavaScript
1
star
53

test-ec2

test-ec2
1
star
54

sa1

1
star
55

better_tempfile

Ruby
1
star
56

ar_enumerations_test_application

ActiveRecord enumeration field type - test application
Ruby
1
star
57

tophouse.com.ua

JavaScript
1
star
58

capistranotest

1
star
59

zip_and_phone

Zips & Phones
Ruby
1
star
60

portfolio

1
star
61

tdemo

tdemo
Ruby
1
star
62

cisarska_and_frankivska

Cisarska & Frankivska
JavaScript
1
star
63

seminars

JavaScript
1
star
64

deprecations_collector

Save all Rails deprecation in log file for future investigation
Ruby
1
star
65

just_for_fun

Do you want to call 42.to_user, [42, 43, 44].to_users? Try this gem :)
Ruby
1
star
66

rails_logs

Ruby
1
star