Creating Ebooks with borb in Python
Last Updated :
06 Jun, 2024
Creating ebooks can be a rewarding endeavor, whether for sharing knowledge, storytelling, or distributing documentation. The borb
library in Python is a powerful tool that enables developers to generate PDFs with rich formatting and various multimedia elements. This article will guide you through the process of creating a well-formatted ebook using the borb
library, covering the basics and demonstrating how to incorporate different types of content.
Setting Up the Environment
Before you start, ensure you have Python installed. You can install the borb
library using pip:
pip install borb
Step to Creating Ebooks with Borb
Let's create an ebook that includes text, images, barcodes, charts, maps, and lists. We'll also style the content and add custom fonts.
Importing Necessary Modules
Here, we import various classes and functions from the borb library that we'll use to create and manipulate the PDF.
Python
from decimal import Decimal
from borb.pdf import Document, Page, Paragraph, PDF, SingleColumnLayout, HexColor, Alignment
from borb.pdf.canvas.font.simple_font.true_type_font import TrueTypeFont
from borb.pdf import FixedColumnWidthTable, Image
from borb.pdf.canvas.layout.image.barcode import Barcode, BarcodeType
from borb.pdf import Chart
from borb.pdf import MapOfTheWorld
from borb.pdf import InlineFlow, ChunkOfText, Emojis
from borb.pdf import ProgressBar
from borb.pdf import UnorderedList
Creating the Document and Page:
We start by creating a Document object and then a Page object with specific dimensions. The page is added to the document.
Python
pdf = Document()
page = Page(width=Decimal(1400), height=Decimal(800))
pdf.add_page(page)
Setting Up the Layout:
A SingleColumnLayout is created for the page to manage the placement of elements.
Python
layout = SingleColumnLayout(page)
Adding a Title:
We add a centered paragraph as a title to the layout.
Python
layout.add(Paragraph("Table", font_size=20, horizontal_alignment=Alignment.CENTERED))
Defining a Table:
A FixedColumnWidthTable is defined with 3 columns and 3 rows, along with custom border properties.
Python
table = FixedColumnWidthTable(number_of_columns=3, number_of_rows=3, border_top=True,
border_right=True,
border_bottom=True,
border_left=True,
border_color=HexColor("#00ff00"),
border_radius_bottom_left=Decimal(0.1),
border_radius_bottom_right=Decimal(0.1),
border_width=Decimal(0.1)
)
Adding an Image:
An image is added to the table using its URL.
Python
image = Image(
"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210420155809/gfg-new-logo.png",
width=Decimal(150),
height=Decimal(100),
)
Creating Barcodes:
Two barcodes are created: a QR code and a Code 128 barcode.
Python
qr_code = Barcode(data="https://www.geeksforgeeks.org", type=BarcodeType.QR, width=Decimal(128), height=Decimal(128))
bar = Barcode(data="https://www.geeksforgeeks.org", type=BarcodeType.CODE_128, width=Decimal(128), height=Decimal(128))
Creating a Chart:
A function is defined to create a scatter plot using Matplotlib, which is then added to the PDF as a chart.
Python
def create_plot():
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(dpi=800)
ax = plt.axes()
x = np.linspace(0, 10, 30)
y = np.sin(x)
ax.plot(x, y)
return plt.gcf()
chart = Chart(create_plot(), width=Decimal(350), height=Decimal(300))
Adding a Map:
A map is added with custom fill and stroke colors.
Python
map = MapOfTheWorld(
horizontal_alignment=Alignment.CENTERED,
fill_color=HexColor("#00ffff"),
stroke_color=HexColor("#ffffff"),
line_width=Decimal(0.1),
).set_fill_color(fill_color=HexColor("#0b5394"), key="India")
Adding Emojis:
Emojis are included in an inline flow alongside text.
Python
flow = InlineFlow()
flow.add(ChunkOfText("Hello", font_size=72))
flow.add(Emojis.EARTH_AMERICAS.value)
flow.add(ChunkOfText("!", font_size=72))
Adding Elements to the Table:
Various elements like the image, barcodes, chart, map, and emojis are added to the table.
Python
table.add(image)
table.add(qr_code)
table.add(chart)
table.add(bar)
table.add(map)
table.add(flow)
table.add(Paragraph("Text-data", padding_left=Decimal(100),
font_size=24 , background_color=HexColor("00FF00")))
Adding ProgressBars and Nested Tables:
A nested table with progress bars is added.
Python
table.add(FixedColumnWidthTable(number_of_columns=2, number_of_rows=3)
.add(Paragraph("Coders"))
.add(ProgressBar(percentage=0.45))
.add(Paragraph("Non-Coders"))
.add(ProgressBar(percentage=0.55))
.add(Paragraph("Hehe ^_^"))
.add(ProgressBar(percentage=1))
.set_padding_on_all_cells(Decimal(3), Decimal(3), Decimal(3), Decimal(3))
)
Adding an Unordered List:
An unordered list is created and added to the table.
Python
ul = UnorderedList()
ul.add(Paragraph("Item 1"))
ul.add(Paragraph("Item 2"))
ul.add(Paragraph("Item 3"))
table.add(ul)
Adding the Table to the Layout:
The table is added to the layout.
Python
Adding a Styled Paragraph:
A styled paragraph with custom font, size, color, and alignment is added to the layout.
Python
layout.add(Paragraph(
"This is a custom styled paragraph.",
font="Helvetica",
font_size=72,
font_color=HexColor("ff0000"),
horizontal_alignment=Alignment.CENTERED,
vertical_alignment=Alignment.TOP
))
Saving the PDF:
Finally, the document is saved to a file named styled_ebook.pdf.
Python
with open("styled_ebook.pdf", "wb") as pdf_file_handle:
PDF.dumps(pdf_file_handle, pdf)
Output
Similar Reads
Creating a Discord Bot in Python
If you are familiar with online communities and if you are a part of one or you own one, you must have heard about discord and in discord, you may have seen bots managing those communities. So in this article, we are going to set up our discord developer portal account and will create a discord bot.
9 min read
Python SQLite - Creating a New Database
In this article, we will discuss how to create a Database in SQLite using Python. Creating a Database You do not need any special permissions to create a database. The sqlite3 command used to create the database has the following basic syntax Syntax: $ sqlite3 <database_name_with_db_extension>
3 min read
Creating Your First Application in Python
Python is one of the simplest and most beginner-friendly programming languages available today. It was designed with the goal of making programming easy and accessible, especially for newcomers. In this article, we will guide you through creating your very first Python application from a simple prin
4 min read
How to call a function in Python
Python is an object-oriented language and it uses functions to reduce the repetition of the code. In this article, we will get to know what are parts, How to Create processes, and how to call them.In Python, there is a reserved keyword "def" which we use to define a function in Python, and after "de
5 min read
Create Bucket Policy in AWS S3 Bucket with Python
Bucket policy of s3 bucket means permission and action which can be applied on the particular bucket. AWS S3 has an optional policy that can be used to restrict or grant access to an S3 bucket resource. It is important to note that bucket policies are defined in JSON format. For creating a bucket po
2 min read
How to create charts in bokeh with flask
In this post, we will use the Flask framework to create our web application in Python. The Bokeh library will be used to create interactive bar graphs and we will visualize this graph through a simple frontend HTML page. For this, we will first write the endpoints in Flask which will help us to crea
5 min read
Working with MySQL BLOB in Python
In Python Programming, We can connect with several databases like MySQL, Oracle, SQLite, etc., using inbuilt support. We have separate modules for each database. We can use SQL Language as a mediator between the python program and database. We will write all queries in our python program and send th
4 min read
Hashing Passwords in Python with BCrypt
In this article, we will see how to hash passwords in Python with BCrypt. Storing passwords in plain text is a bad practice as it is vulnerable to various hacking attempts. That's why it is recommended to keep them in a hashed form. What is hashing? It's a process of converting one string to anothe
4 min read
Handling Categorical Data with Bokeh - Python
As a data scientist, you will often come across datasets with categorical data. Categorical data is a type of data that can be divided into distinct categories or groups. For example, a dataset might have a column with the categories "red", "green", and "blue". Handling categorical data can be chall
5 min read
How to create modules in Python 3 ?
Modules are simply python code having functions, classes, variables. Any python file with .py extension can be referenced as a module. Although there are some modules available through the python standard library which are installed through python installation, Other modules can be installed using t
4 min read