• Stars
    star
    659
  • Rank 68,396 (Top 2 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 16 years ago
  • Updated about 1 year ago

Reviews

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

Repository Details

A framework for creating e-books from Markdown using Ruby. Using the Prince PDF generator, you'll be able to get high quality PDFs. Also supports EPUB, Mobi, Text and HTML generation.

kitabu

Tests Gem Gem MIT License

Kitabu is a framework for creating e-books from Markdown using Ruby. Using Prince PDF generator, you'll be able to get high quality PDFs. Also supports EPUB, Mobi, and HTML generation.

While Prince is too expensive (495USD for a single user license), the free version available at http://www.princexml.com/download generates a PDF with a small logo on the first page, which is removed when sent to a printer; you can use it locally for viewing the results immediately. When you're done writing your e-book, you can use DocRaptor, which have plans starting at $15/mo.

Features

  • Write using Markdown
  • Book layout support
  • Syntax highlight
  • Generate HTML, PDF, e-Pub (version 3.3), and Mobi
  • Table of Contents automatically generated from chapter titles

Installation

To install Kitabu, you'll need a working Ruby 3.2+ installation. If you're cool with it, just run the following command to install it.

gem install kitabu

After installing Kitabu, run the following command to check your external dependencies.

$ kitabu check

Prince XML: Converts HTML files into PDF files.
Installed.

Calibre's ebook-convert: Converts ePub e-books into .mobi files.
Installed.

There are no hard requirements here; just make sure you cleared the correct dependency based on the formats you want to export to.

Usage

To create a new e-book, just run

$ kitabu new mybook

This command creates a directory mybook with the following structure:

.
β”œβ”€β”€ Gemfile
β”œβ”€β”€ Gemfile.lock
β”œβ”€β”€ Guardfile
β”œβ”€β”€ assets
β”‚Β Β  β”œβ”€β”€ fonts
β”‚Β Β  β”œβ”€β”€ images
β”‚Β Β  β”‚Β Β  β”œβ”€β”€ cover.png
β”‚Β Β  β”‚Β Β  β”œβ”€β”€ kitabu.svg
β”‚Β Β  β”‚Β Β  β”œβ”€β”€ markdown.svg
β”‚Β Β  β”‚Β Β  └── up.svg
β”‚Β Β  β”œβ”€β”€ scripts
β”‚Β Β  └── styles
β”‚Β Β      β”œβ”€β”€ epub.css
β”‚Β Β      β”œβ”€β”€ html.css
β”‚Β Β      β”œβ”€β”€ pdf.css
β”‚Β Β      β”œβ”€β”€ print.css
β”‚Β Β      └── support
β”‚Β Β          β”œβ”€β”€ kitabu.css
β”‚Β Β          β”œβ”€β”€ normalize.css
β”‚Β Β          β”œβ”€β”€ notes.css
β”‚Β Β          └── toc.css
β”œβ”€β”€ config
β”‚Β Β  β”œβ”€β”€ helpers.rb
β”‚Β Β  β”œβ”€β”€ kitabu.yml
β”‚Β Β  └── locales
β”‚Β Β      └── en.yml
β”œβ”€β”€ templates
β”‚Β Β  β”œβ”€β”€ epub
β”‚Β Β  β”‚Β Β  β”œβ”€β”€ cover.erb
β”‚Β Β  β”‚Β Β  β”œβ”€β”€ page.erb
β”‚Β Β  β”‚Β Β  └── toc.erb
β”‚Β Β  └── html
β”‚Β Β      └── layout.erb
└── text
    β”œβ”€β”€ 01_Getting_Started.md
    β”œβ”€β”€ 02_Creating_Chapters.md
    β”œβ”€β”€ 03_Syntax_Highlighting.md.erb
    β”œβ”€β”€ 04_Dynamic_Content.md.erb
    β”œβ”€β”€ 05_Exporting_Files.md
    └── 06_Changelog.md

13 directories, 28 files

The config/kitabu.yml file holds some information about your book; so you'll always change it.

The generated structure is actually a good example. So make sure you try it!

Kitabu - Sample Book

There's a generated sample available on the attachments directory β€’ PDF / EPUB / MOBI / HTML.

Now it's time to write your e-book. All your book content will be placed on the text directory. Kitabu requires you to separate your book into chapters. A chapter is nothing but a directory that holds lots of text files. The e-book will be generated using every folder/file alphabetically. So be sure to use a sequential numbering as the name. Here's a sample:

* text
  * 01_Introduction
    * 01_introduction.md
  * 02_What_is_Ruby_on_Rails
    * 01_MVC.md
    * 02_DRY.md
    * 03_Convention_Over_Configuration.md
  * 03_Installing_Ruby_on_Rails
    * 01_Installing.md
    * 02_Mac_OS_X_instructions.md
    * 03_Windows_instructions.md
    * 04_Ubuntu_Linux_instructions.md

If you prefer, you can add a chapter per file:

* text
  * 01_Introduction.md
  * 02_What_is_Ruby_on_Rails.md
  * 03_Installing_Ruby_on_Rails.md

You'll want to see your progress eventually; it's time for you to generate the book PDF. Just run the command kitabu export and your book will be created on the output directory.

Kitabu can generate a Table of Contents (TOC) based on your h1-h6 tags. To print the TOC, you need to print a variable called toc, using the eRb tag.

<%= toc %>

Frontmatter

Markdown files (and their .md.erb counterparts) support frontmatter, a section that can inject variables to the page. Notice that the contents inside the --- delimiters must be valid YAML annotation and only basic types can be used (booleans, numbers, strings, nils and hashes/arrays with these same types).

Right now there's only one special value called section, which defines the class section when generating files. This allows you to have files inside your text directory that doesn't necessarily should have styling like regular chapters. For instance, this is how you can define a changelog section:

---
section: changelog
---

## Changelog

### Jan 26, 2024

- Initial release

Note

Notice that section will be retrieved from the first file, even if you have multiple files defining a section with a directory.

This meta data will be inject on your template using the variable meta. If you have other variables, you could print them as <%= meta["varname"] %>.

Using ERB

You can also have .md.erb files. You can mix Markdown and HTML, like the following:

## This the chapter title

<%= image_tag "myimage.png" %>

The above content must be placed in a .md.erb file. The generated content will be something like this:

<img src="images/myimage.png" />

You book's helpers can be added to config/helpers.rb, as this file is loaded automatically by kitabu.

You can see available helpers on https://github.com/fnando/kitabu/blob/main/lib/kitabu/helpers.rb.

Syntax Highlighting

To highlight code, use fenced code blocks.

``` ruby
class User < ActiveRecord::Base
  validates_presence_of :login, :password, :email
  validates_uniqueness_of :login, :email
end
```

You can even provide options:

```php?start_line=1&line_numbers=1
echo "Hello World";
```
  • We use Redcarpet for Markdown processing.
  • We use Rouge for syntax highlighting.

The following Redcarpet options are enabled:

  • autolink
  • fenced_code_blocks
  • footnotes
  • hard_wrap
  • highlight
  • no_intra_emphasis
  • safe_links_only
  • space_after_headers
  • strikethrough
  • superscript
  • tables

Hooks

There are a few hooks that allows manipulating the content. You can use before_render and after_render to process the Markdown content. You can add such hooks to your config/helpers.rb file.

Kitabu::Markdown.add_hook(:before_render) do |content|
  # manipulate content and return it.
  content
end

Kitabu::Markdown.add_hook(:after_render) do |content|
  # manipulate content and return it.
  content
end

Using custom fonts

You can use custom fonts on your ebooks. Just add them to the fonts directory (you can create this directory on your book's root directory if it doesn't exist).

Then, on assets/styles/support/fonts.css you can add the @font-face declaration.

@font-face {
  font-family: "Open Sans Condensed Bold";
  src: url("../../fonts/OpenSans-CondBold.ttf");
}

Finally, to use this font, do something like this:

.chapter > h1 {
  font-family: "Open Sans Condensed Bold";
}

Instead of doing the above manually, you can also use Prince's --scanfonts option.

$ prince --scanfonts assets/fonts/* > assets/styles/support/fonts.css

Just remember to replace the generated path to be something like ../../fonts instead.

Tip

In most cases, it's easier to redefine sans-serif, serif and monospace fonts. To know more about how to do this, read Prince's Redefining the generic font families documentation.

If you're unsure if fonts are actually being used on PDF files, use the environment variable PRINCEOPT to disable system fonts.

$ PRINCEOPT='--no-system-fonts --debug --log output/prince.log' kitabu export --only pdf
=> e-book couldn't be exported

$ tail -n10 output/prince.log
Sat Jan 27 18:39:10 2024: debug: font request: Caslon, serif
Sat Jan 27 18:39:10 2024: warning: Ensure fonts are available on the system or load them via a @font-face rule.
Sat Jan 27 18:39:10 2024: warning: For more information see:
Sat Jan 27 18:39:10 2024: warning: https://www.princexml.com/doc/help-install/#missing-glyphs-or-fonts
Sat Jan 27 18:39:10 2024: internal error: Unable to find any available fonts.
Sat Jan 27 18:39:10 2024: finished: failure
Sat Jan 27 18:39:10 2024: ---- end

Configuring Markdown

Kitabu uses Redcarpet as the Markdown engine. You can override the default processor by setting Kitabu::Markdown.processor. This can be done by adding something like the following to config/helpers.rb:

Kitabu::Markdown.processor = Redcarpet::Markdown.new(
  Kitabu::Markdown::Renderer.new(hard_wrap: false, safe_links_only: true),
  tables: true,
  footnotes: true,
  space_after_headers: true,
  superscript: true,
  highlight: true,
  strikethrough: true,
  autolink: true,
  fenced_code_blocks: true,
  no_intra_emphasis: true
)

The above options are Kitabu's defaults.

Exporting PDFs using DocRaptor

If you're not planning to buy PrinceXML, consider using DocRaptor. Here's how you can easily do it:

curl -H "Content-Type:application/json" -d'{"user_credentials":"YOUR_CREDENTIALS_HERE", "doc":{"name":"kitabu.pdf", "document_type":"pdf", "test":"false", "document_url":"https://example.com/output/kitabu.pdf.html"}}' http://docraptor.com/docs > kitabu.pdf

References

Legal Notes

Maintainer

Contributors

Contributing

For more details about how to contribute, please read https://github.com/fnando/kitabu/blob/main/CONTRIBUTING.md.

License

The gem is available as open source under the terms of the MIT License. A copy of the license can be found at https://github.com/fnando/kitabu/blob/main/LICENSE.md.

Code of Conduct

Everyone interacting in the kitabu project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.

More Repositories

1

i18n-js

It's a small library to provide the I18n translations on the Javascript. It comes with Rails support.
Ruby
3,702
star
2

browser

Do some browser detection with Ruby. Includes ActionController integration.
Ruby
2,388
star
3

recurrence

A simple library that handles recurring events.
Ruby
556
star
4

sparkline

Generate SVG sparklines with JavaScript without any external dependency.
JavaScript
501
star
5

paypal-recurring

PayPal Express Checkout API Client for recurring billing.
Ruby
257
star
6

cpf_cnpj

πŸ‡§πŸ‡· Validate, generate and format CPF/CNPJ numbers. Include command-line tools.
Ruby
220
star
7

password_strength

Check password strength against several rules. Includes ActiveRecord/ActiveModel support.
JavaScript
182
star
8

cpf

πŸ‡§πŸ‡· Validate, generate and format CPF numbers
TypeScript
161
star
9

pagseguro

Um plugin para o Ruby on Rails que permite utilizar o PagSeguro
Ruby
141
star
10

coupons

Coupons is a Rails engine for creating discount coupons.
Ruby
140
star
11

cpf_cnpj.js

Validate, generate and format CPF/CNPJ numbers
JavaScript
118
star
12

i18n

A small library to provide the I18n translations on the JavaScript.
TypeScript
113
star
13

uptime_checker

Check if your sites are online for $7/mo.
112
star
14

module

Define namespaces as constructor functions (or any object).
JavaScript
105
star
15

qe

A simple interface over several background job libraries like Resque, Sidekiq and DelayedJob.
Ruby
102
star
16

has_calendar

A view helper that creates a calendar using a table. You can easily add events with any content.
Ruby
101
star
17

sinatra-subdomain

Separate routes for subdomains in Sinatra apps
Ruby
96
star
18

validators

Some ActiveModel/ActiveRecord validators
Ruby
96
star
19

dotfiles

My dotfiles
Shell
88
star
20

rack-api

Create web app APIs that respond to one or more formats using an elegant DSL.
Ruby
86
star
21

notifier

Send system notifications on several platforms with a simple and unified API. Currently supports Notification Center, Libnotify, OSD, KDE (Knotify and Kdialog) and Snarl
Ruby
84
star
22

factory_bot-preload

Preload factories (factory_bot) just like fixtures. It will be easy and, probably, faster!
Ruby
83
star
23

cnpj

πŸ‡§πŸ‡· Validate, generate and format CNPJ numbers
TypeScript
81
star
24

dispatcher-js

Simple jQuery dispatcher for web apps.
JavaScript
75
star
25

gem-open

Open gems into your favorite editor by running a specific gem command
Ruby
69
star
26

test_notifier

Display system notifications (dbus, growl and snarl) after running tests. It works on Mac OS X, Linux and Windows. Powerful when used with Autotest ZenTest gem for Rails apps.
Ruby
63
star
27

test_squad

Running JavaScript tests on your Rails app, the easy way.
Ruby
56
star
28

vscode-linter

Extension for code linting, all in one package. New linters can be easily added through an extension framework.
TypeScript
56
star
29

has_friends

Add friendship support to Rails apps with this plugin
Ruby
55
star
30

breadcrumbs

Breadcrumbs is a simple Rails plugin that adds a breadcrumbs object to controllers and views.
Ruby
55
star
31

minitest-utils

Some utilities for your Minitest day-to-day usage.
Ruby
52
star
32

photomatic

Your photography is what matters.
Ruby
50
star
33

normalize_attributes

Sometimes you want to normalize data before saving it to the database like down casing e-mails, removing spaces and so on. This Rails plugin allows you to do so in a simple way.
Ruby
49
star
34

burgundy

A simple wrapper for objects (think of Burgundy as a decorator/presenter) in less than 150 lines.
Ruby
49
star
35

ar-uuid

Override migration methods to support UUID columns without having to be explicit about it.
Ruby
46
star
36

rubygems_proxy

Rack app for caching RubyGems files. Very useful in our build server that sometimes fails due to our network or rubygems.org timeout.
Ruby
43
star
37

post_commit

Post commit allows you to notify several services with a simple and elegant DSL. Five services are supported for now: Basecamp, Campfire, FriendFeed, LightHouse and Twitter.
Ruby
42
star
38

permalink

Add permalink support to Rails apps with this plugin
Ruby
40
star
39

keyring-node

Simple encryption-at-rest with key rotation support for Node.js.
JavaScript
39
star
40

superconfig

Access environment variables. Also includes presence validation, type coercion and default values.
Ruby
38
star
41

sublime-better-ruby

Sublime Text Ruby package (snippets, builder, syntax highlight)
Ruby
37
star
42

simple_presenter

A simple presenter/facade/decorator/whatever implementation.
Ruby
33
star
43

voltage

A simple observer implementation on POROs (Plain Old Ruby Object) and ActiveRecord objects.
Ruby
31
star
44

redis-settings

Store application and user settings on Redis. Comes with ActiveRecord support.
Ruby
31
star
45

tokens

Add token support to Rails apps with this plugin
Ruby
31
star
46

boppers

A simple bot framework for individuals.
Ruby
29
star
47

babel-schmooze-sprockets

Add Babel support to sprockets using Schmooze.
JavaScript
29
star
48

streamdeck

A lean framework for developing Elgato Stream Deck plugins.
TypeScript
28
star
49

sublime-text

My SublimeText settings
26
star
50

has_ratings

Add rating support to Rails apps with this plugin
Ruby
25
star
51

commentable

Add comment support to Rails apps with this plugin
Ruby
23
star
52

sinatra-basic-auth

Authentication with BasicAuth that can require different credentials for different realms.
Ruby
23
star
53

rails-routes

Enable config/routes/*.rb on your Rails application.
Ruby
23
star
54

swiss_knife

Here's my swiss-knife Rails helpers.
Ruby
21
star
55

aitch

A simple HTTP client.
Ruby
21
star
56

messages-app

Use alert messages in your README.
HTML
19
star
57

rails-env

Avoid environment detection on Rails
Ruby
19
star
58

svg_optimizer

Some SVG optimization based on Node's SVGO
Ruby
18
star
59

defaults

Add default value for ActiveRecord attributes
Ruby
18
star
60

ar-check

Enable PostgreSQL's CHECK constraints on ActiveRecord migrations
Ruby
17
star
61

email_data

This project is a compilation of datasets related to emails. Includes disposable emails, disposable domains, and free email services.
Ruby
17
star
62

simple_auth

SimpleAuth is an authentication library to be used when everything else is just too complicated.
Ruby
17
star
63

attr_keyring

Simple encryption-at-rest with key rotation support for Ruby.
Ruby
17
star
64

has_bookmarks

Add bookmark support to Rails apps with this plugin
Ruby
17
star
65

sublime-text-screencasts

Screencasts sobre Sublime Text
HTML
17
star
66

paginate

Paginate collections using SIZE+1 to determine if there is a next page. Includes ActiveRecord and ActionView support.
Ruby
16
star
67

pry-meta

Meta package that requires several pry extensions.
Ruby
15
star
68

react-starter-pack

Starter-pack for react + webpack + hot reload + mocha + enzyme + production build
JavaScript
15
star
69

check_files

Check non-reloadable files changes on Rails apps.
Ruby
15
star
70

url_signature

Create and verify signed urls. Supports expiration time.
Ruby
15
star
71

activities

Activities is a gem that enables social activities in ActiveRecord objects.
Ruby
14
star
72

using-es6-with-asset-pipeline-on-ruby-on-rails

Example for my article about ES6 + Asset Pipeline
Ruby
14
star
73

whiteboard

A small app using Canvas + Socket.IO to provide a shared whiteboard.
JavaScript
14
star
74

sublime-better-rspec

Better RSpec syntax highlighting, with matchers for v3. Also includes implementation/spec toggling command.
Python
13
star
75

ar-sequence

Add support for PostgreSQL's SEQUENCE on ActiveRecord migrations.
Ruby
13
star
76

page_meta

Easily define <meta> and <link> tags. I18n support for descriptions, keywords and titles.
Ruby
13
star
77

boppers-uptime

A bopper to check if your sites are online.
Ruby
13
star
78

has_versions

A simple plugin to version ActiveRecord objects
Ruby
13
star
79

csr

Generate CSR (Certificate Signing Request) using Ruby and OpenSSL.
Ruby
13
star
80

haikunate

Generate Heroku-like memorable random names like adorable-ox-1234.
Ruby
13
star
81

module-component

Define auto-discoverable HTML UI components using Module.js.
JavaScript
12
star
82

alfred-workflows

Alfred workflows
12
star
83

twitter_cleanup

Remove old tweets periodically using Github Actions
Ruby
12
star
84

storage

This gem provides a simple API for multiple storage backends. Supported storages: Amazon S3 and FileSystem.
Ruby
12
star
85

has_layout

Add conditional layouts with ease
Ruby
11
star
86

kalendar

A view helper that creates a calendar using a table. You can easily add events with any content.
Ruby
11
star
87

stellar-paperwallet

Make paper wallets to keep your Stellar addresses safe.
JavaScript
10
star
88

tagger

Tagging plugin for Ruby on Rails apps
Ruby
10
star
89

page_title

Set the page title on Rails apps.
Ruby
10
star
90

dogo

A simple URL shortener service backed by Redis.
Ruby
10
star
91

has_notifications

This plugin was created to act as a proxy between different notification systems (Mail, Jabber, etc) based on the user's preferences.
Ruby
10
star
92

formatter

has_markup is an ActiveRecord plugin that integrates Tidy, Markdown, Textile and sanitize helper method into a single plugin.
Ruby
10
star
93

ar-enum

Add support for creating `ENUM` types in PostgreSQL with ActiveRecord
Ruby
9
star
94

shortcuts

Because mouse is for noobies.
Ruby
9
star
95

ar-timestamptz

Make ActiveRecord's PostgreSQL adapter use timestamptz as datetime columns.
Ruby
9
star
96

parsel-js

Encrypt and decrypt data with a given key.
JavaScript
8
star
97

ember-and-rails

Ruby
8
star
98

access_token

Access token for client-side and API authentication.
Ruby
8
star
99

sinatra-oauth-twitter

Sample app used on Guru-SP meetup
Ruby
8
star
100

need_help

A simple help/FAQ system using Rails Engine.
Ruby
8
star