• Stars
    star
    495
  • Rank 85,603 (Top 2 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 9 years ago
  • Updated over 1 year ago

Reviews

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

Repository Details

Easy receipts and invoices for your Rails applications

travisci

Receipts Gem

Receipts, Invoices, and Statements for your Rails application that works with any payment provider. Receipts uses Prawn to generate the PDFs.

Check out the example PDFs.

Installation

Add this line to your application's Gemfile:

gem 'receipts'

And then execute:

$ bundle

Or install it yourself as:

$ gem install receipts

Usage

To generate a Receipt, Invoice, or Statement, create an instance and provide content to render:

r = Receipts::Receipt.new(
  details: [
    ["Receipt Number", "123"],
    ["Date paid", Date.today],
    ["Payment method", "ACH super long super long super long super long super long"]
  ],
  company: {
    name: "Example, LLC",
    address: "123 Fake Street\nNew York City, NY 10012",
    email: "[email protected]",
    logo: File.expand_path("./examples/images/logo.png")
  },
  recipient: [
    "Customer",
    "Their Address",
    "City, State Zipcode",
    nil,
    "[email protected]"
  ],
  line_items: [
    ["<b>Item</b>", "<b>Unit Cost</b>", "<b>Quantity</b>", "<b>Amount</b>"],
    ["Subscription", "$19.00", "1", "$19.00"],
    [nil, nil, "Subtotal", "$19.00"],
    [nil, nil, "Tax", "$1.12"],
    [nil, nil, "Total", "$20.12"],
    [nil, nil, "<b>Amount paid</b>", "$20.12"],
    [nil, nil, "Refunded on #{Date.today}", "$5.00"]
  ],
  footer: "Thanks for your business. Please contact us if you have any questions."
)

# Returns a string of the raw PDF
r.render

# Writes the PDF to disk
r.render_file "examples/receipt.pdf"

Configuration

You can specify the default font for all PDFs by defining the following in an initializer:

Receipts.default_font = {
  bold: Rails.root.join('app/assets/fonts/tradegothic/TradeGothic-Bold.ttf'),
  normal: Rails.root.join('app/assets/fonts/tradegothic/TradeGothic.ttf'),
}

Options

You can pass the following options to generate a PDF:

  • recipient - Array of customer details to include. Typically, this is name, address, email, VAT ID, etc.

  • company - Hash of your company details

    • name - Company name

    • address - Company address

    • email - Company support email address

    • phone - Company phone number - Optional

    • logo - Logo to be displayed on the receipt - Optional This can be either a Path, File, StringIO, or URL. Here are a few examples:

      logo: Rails.root.join("app/assets/images/logo.png")
      logo: File.expand_path("./logo.png")
      logo: File.open("app/assets/images/logo.png", "rb")
      logo: "https://www.ruby-lang.org/images/[email protected]" # Downloaded with OpenURI
  • details - Array of details about the Receipt, Invoice, Statement. Typically, this is receipt numbers, issue date, due date, status, etc.

  • line_items - Array of line items to be displayed in table format.

  • footer - String for a message at the bottom of the PDF.

  • font - Hash of paths to font files - Optional

    font: {
      bold: Rails.root.join('app/assets/fonts/tradegothic/TradeGothic-Bold.ttf'),
      normal: Rails.root.join('app/assets/fonts/tradegothic/TradeGothic.ttf'),
    }
  • logo_height - An integer value of how tall the logo should be. Defaults to 16

Here's an example of where each option is displayed.

options

Formatting

details and line_items allow inline formatting with Prawn. This allows you to use HTML tags to format text: <b> <i> <u> <strikethrough> <sub> <sup> <font> <color> <link>

See the Prawn docs for more information.

Page Size

You can specify a different page size by passing in the page_size keyword argument:

receipt = Receipts::Receipt.new page_size: "A4"

Internationalization (I18n)

You can use I18n.t when rendering your receipts to internationalize them.

line_items: [
  [I18n.t("receipts.date"),           created_at.to_s],
  [I18n.t("receipts.product"), "GoRails"],
  [I18n.t("receipts.transaction"), uuid]
]

Custom PDF Content

You can change the entire PDF content by instantiating an Receipts object without any options.

receipt = Receipts::Receipt.new # creates an empty PDF

Each Receipts object inherits from Prawn::Document. This allows you to choose what is rendered and include any custom Prawn content you like.

receipt.text("hello world")

You can also use the Receipts helpers in your custom PDFs at the current cursor position.

receipt.text("Custom header")
receipt.render_line_items([
  ["my line items"]
])
receipt.render_footer("This is a custom footer using the Receipts helper")

Rendering PDFs

To render a PDF in memory, use render. This is recommended for serving PDFs in your Rails controllers.

receipt.render

To render a PDF to disk, use render_file:

receipt.render_file "receipt.pdf"

Rendering PDFs in Rails controller actions

Here's an example Rails controller action you can use for serving PDFs. We'll first look up the database record for the Charge we want to render a receipt for.

The Charge model has a receipt method that returns a Receipts::Receipt instance with all the receipt data filled out.

Then we can render to generate the PDF in memory. This produces a String with the raw PDF data in it.

Using send_data from Rails, we can send the PDF contents and provide the browser with a recommended filename, content type and disposition.

class ChargesController < ApplicationController
  before_action :authenticate_user!
  before_action :set_charge

  def show
    respond_to do |format|
      format.pdf { send_pdf }
    end
  end

  private

    def set_charge
      @charge = current_user.charges.find(params[:id])
    end

  	def send_pdf
      # Render the PDF in memory and send as the response
      send_data @charge.receipt.render,
        filename: "#{@charge.created_at.strftime("%Y-%m-%d")}-gorails-receipt.pdf",
        type: "application/pdf",
        disposition: :inline # or :attachment to download
    end
end

Then, just link_to to your charge with the format of pdf. For example:

# config/routes.rb
resources :charges
<%= link_to "View Receipt", charge_path(@charge, format: :pdf) %>

Invoices

Invoices follow the exact same set of steps as above. You'll simply want to modify the details to include other information for the Invoice such as the Issue Date, Due Date, etc.

Receipts::Invoice.new(
  details: [
    ["Invoice Number", "123"],
    ["Issue Date", Date.today.strftime("%B %d, %Y")],
    ["Due Date", Date.today.strftime("%B %d, %Y")],
    ["Status", "<b><color rgb='#5eba7d'>PAID</color></b>"]
  ],
  recipient: [
    "<b>Bill To</b>",
    "Customer",
    "Address",
    "City, State Zipcode",
    "[email protected]"
  ],
  company: {
    name: "Example, LLC",
    address: "123 Fake Street\nNew York City, NY 10012",
    phone: "(555) 867-5309",
    email: "[email protected]",
    logo: File.expand_path("./examples/images/logo.png")
  },
  line_items: [
    ["<b>Item</b>", "<b>Unit Cost</b>", "<b>Quantity</b>", "<b>Amount</b>"],
    ["Subscription", "$19.00", "1", "$19.00"],
    [nil, nil, "Subtotal", "$19.00"],
    [nil, nil, "Tax Rate", "0%"],
    [nil, nil, "Amount Due", "$19.00"]
  ]
)

Statements

Statements follow the exact same set of steps as above. You'll simply want to modify the details to include other information for the Invoice such as the Issue Date, Start and End Dates, etc.

Receipts::Statement.new(
  details: [
    ["Statement Number", "123"],
    ["Issue Date", Date.today.strftime("%B %d, %Y")],
    ["Period", "#{(Date.today - 30).strftime("%B %d, %Y")} - #{Date.today.strftime("%B %d, %Y")}"]
  ],
  recipient: [
    "<b>Bill To</b>",
    "Customer",
    "Address",
    "City, State Zipcode",
    "[email protected]"
  ],
  company: {
    name: "Example, LLC",
    address: "123 Fake Street\nNew York City, NY 10012",
    email: "[email protected]",
    phone: "(555) 867-5309",
    logo: File.expand_path("./examples/images/logo.png")
  },
  line_items: [
    ["<b>Item</b>", "<b>Unit Cost</b>", "<b>Quantity</b>", "<b>Amount</b>"],
    ["Subscription", "$19.00", "1", "$19.00"],
    [nil, nil, "Subtotal", "$19.00"],
    [nil, nil, "Tax Rate", "0%"],
    [nil, nil, "Total", "$19.00"]
  ]
)

Contributing

  1. Fork it ( https://github.com/excid3/receipts/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

More Repositories

1

noticed

Notifications for Ruby on Rails applications
Ruby
2,275
star
2

simple_calendar

A wonderfully simple calendar gem for Rails
Ruby
1,476
star
3

jumpstart

Easily jumpstart a new Rails application with a bunch of great features by default
HTML
1,168
star
4

tailwindcss-stimulus-components

A set of StimulusJS components for TailwindCSS apps similar to Bootstrap JS components.
JavaScript
1,083
star
5

madmin

A robust Admin Interface for Ruby on Rails apps
JavaScript
497
star
6

simple_discussion

A simple, extensible Rails forum
Ruby
368
star
7

prefixed_ids

Friendly Prefixed IDs for your Ruby on Rails models
Ruby
198
star
8

revise_auth

A pure Rails authentication system like Devise.
Ruby
192
star
9

stack_rescue

A gem for Rails to automatically search Google for exceptions raised in your Rails applications
Ruby
171
star
10

esbuild-rails

Esbuild Rails plugin
JavaScript
137
star
11

signalman

Development tools for Ruby on Rails
Ruby
92
star
12

beginnerbounties.com

Small Projects for Junior Developers
Ruby
77
star
13

dotfiles

My personal dotfiles for macOS: zsh, MacVim, iterm, and more.
Vim Script
70
star
14

stimulus-slimselect

A Stimulus wrapper around SlimSelect
JavaScript
66
star
15

python-apt

This is a Python library interface to libapt, which allows you to query and manipulat APT package repository information using the Python programming language.
C++
63
star
16

combined_time_select

A Rails time_select like Google Calendar with combined hour and minute time_select
Ruby
60
star
17

logbot

A minimal IRC bot for logging channels
Python
59
star
18

textual-solarized

A port of the Solarized theme to Textual IRC
JavaScript
31
star
19

simple_calendar-ajax-example

An example Rails application to demonstrate SimpleCalendar AJAX next/previous links
Ruby
29
star
20

scheduled_tweets

Ruby
28
star
21

gorails-forum

Ruby
24
star
22

betterminitest.com

Learn how to write better Minitest tests
CSS
21
star
23

Rails-Learning

List of resources to learning this amazing platform for building top-quality web apps with Ruby on Rails! ❀
20
star
24

trello-stimulus-reflex

A trello clone using Stimulus Reflex
Ruby
17
star
25

railshackathon.com

The RailsHackathon.com website
HTML
17
star
26

asdf-vars

An asdf extension that safely sets global and per-project environment variables, based upon rbenv
Shell
17
star
27

railsconf-2020-actiontext

Railsconf 2020 example app for showcasing ActionText
Ruby
16
star
28

nine_to_five

Ruby
14
star
29

oauthable

Setup, test, and implement the OAuth connections to over 70 different APIs.
Ruby
13
star
30

gorails-ruby

An interactive CLI for GoRails, Railsbytes, Jumpstart, and more.
Ruby
12
star
31

animatedgif.me-v2

Ruby
11
star
32

keryx

Python
11
star
33

current_projects

Lists a user's active github projects
Ruby
9
star
34

israilsdead.com

It's pretty self explanatory I think
HTML
9
star
35

urlgrabber

A high-level cross-protocol url-grabber
Python
8
star
36

Sublime-Ruby-on-Rails.tmLanguage

8
star
37

fluttrly

An elegantly simple todo list
Ruby
8
star
38

simpyl_pastebin

A simple python pastebin
Python
8
star
39

zapier

Zapier API Rubygem
Ruby
8
star
40

excid3-wordpress-theme

My wordpress theme for excid3.com
PHP
7
star
41

animatedgifme

A ruby library for http://animatedgif.me
Ruby
7
star
42

weather_underground

A Ruby gem for the Weather Underground API
Ruby
7
star
43

wistia-player-speed

Add 2x, 1.5x, 0.5x speeds and skip 30 seconds controls to your Wistia video player
HTML
7
star
44

stimulus-js-2.0

A look at Stimulus JS 2.0's new Values and CSS Classes APIs
Ruby
6
star
45

railsconf-2021

Realtime Rails applications with Hotwire & ActionMailbox
Ruby
6
star
46

superleggera

Monitor your CSS in development to create a whitelist for PurgeCSS in Rails with Webpacker
Ruby
6
star
47

deploy_test

See how to deploy Rails to Ubuntu with Capistrano
Ruby
5
star
48

feedforward.io

Curating articles that inspire discussion
Ruby
5
star
49

particlesjs-rails-example

Ruby
5
star
50

clickable-simple_calendar

An example how to make the dates clickable with simple_calendar for creating new events
Ruby
5
star
51

webhookmonitor.com

A tool for recording and monitoring webhooks
Ruby
4
star
52

rpi-pms5003

Raspberry Pi air quality monitoring with PMS5003 and Ruby
Ruby
4
star
53

chef-rails-stack

Chef Solo recipes to setup a Rails stack on Ubuntu 12.04 LTS
Ruby
4
star
54

cfps

Conference talk submissions (CFPs)
4
star
55

react-todolist

A react todo list application with Ruby on Rails
Ruby
4
star
56

landing

My new website landing page
CSS
4
star
57

vuejs-rails-markdown-field

Use VueJS to add markdown previews to any Rails form input field or text area.
Ruby
4
star
58

better_resources

Resources routes that use the same for new and edit so users get less 404s
Ruby
3
star
59

rails-5.2-actiontext

Testing ActionText in Rails 5.2
Ruby
3
star
60

simple_calendar-example

A simple calendar gem example with Rails 6
Ruby
3
star
61

irc_bothost

A Django web application for maintaining python IRC bots
Python
3
star
62

sponsor-hub

A hub for your GitHub sponsors
Ruby
3
star
63

excid3

3
star
64

simple_calendar-full-day-example

Ruby
3
star
65

download_counter

A download counter implemented in Rails3 with an administration interface
Ruby
3
star
66

administrate-trix-editor

Episode 211: Adding the Trix Editor as an Administrate Custom Field
Ruby
3
star
67

gemspec-cheatsheet

An interactive GemSpec cheat sheet
3
star
68

excid3.com

Moving to Jekyll
HTML
3
star
69

reply_parser

Parser for email replies
Ruby
3
star
70

animatedgif.me

With Great Gifs Comes Great Responsibility
Ruby
3
star
71

turbolinks-3-example

Ruby
3
star
72

imageme

Ruby
2
star
73

unwrapt

A pure python layer for offline package managers
Python
2
star
74

chromium

cluster rendering
C
2
star
75

googleweather

Ruby client for the undocumented Google Weather API
Ruby
2
star
76

lithoslabs.com

2
star
77

cultivate

Ruby
2
star
78

blogspam

A Ruby and/or Rails client for Blogspam.net
Ruby
2
star
79

pastebot

An IRC bot that accepts pastes, uploads them, and notifies recipients
Python
2
star
80

excid3bot

A hubot
CoffeeScript
2
star
81

cdnjs-rails

A mechanized way to pull in one to many CDNJS libraries with fall back to local installed versions.
Ruby
2
star
82

keryx_profiler

A website to maintain user submitted profiles for Keryx
Ruby
2
star
83

rugby

A Ruby IRC bot
Ruby
2
star
84

trackler

A package tracker visualizing progress on Google Maps
Ruby
2
star
85

panopticode

Social Volt Contest Entry
Ruby
2
star
86

hatchbox-marketing

2
star
87

No-Net-Debs

List and download deb packages for updates (dist-upgrade included) or new package(s) for a computer without Internet. Hosting in case http://ubuntu.no.sapo.pt/nonetdebs/nonetdebs goes down.
2
star
88

fluttr-desktop

Fluttr desktop application in Python and GTK
Python
2
star
89

omniauth-stripeplatform

A strategy for omniauth and the new beta Stripe.com platofrm.
Ruby
1
star
90

simple_map

Ruby
1
star
91

hacker_rank

A Ruby interface to the HackerRank / InterviewStreet API
Ruby
1
star
92

anonykron

anonykron.com
Ruby
1
star
93

ipcommerce

Ruby
1
star
94

confab

A NodeJS IRC client in the browser
JavaScript
1
star
95

taip-parser

Ruby
1
star
96

omniauth-linode

An Omniauth Strategy for Linode's v4 API
Ruby
1
star
97

ice_rocket

A Rubygem for the IceRocket API
Ruby
1
star
98

combined_time_select-example

Ruby
1
star
99

resume

My resume!
1
star
100

shortbot

An IRC bot that shortens URLs via bit.ly
Python
1
star