Manual RST
Manual RST
rst2pdf
Version 0.101 (dev20)
Page 2
Contents
1 Introduction 4
1.1 Related Reading 4
2 Command line options 5
3 Configuration File 7
4 Pipe usage 9
5 Images 10
5.1 Inline 10
5.2 Supported Image Types 10
5.3 Image Size 10
6 Styling ReStructuredText 12
6.1 Applying Styles 12
6.2 Headers and Footers 12
6.3 Footnotes 13
7 Customizing PDF Output 14
7.1 Using Stylesheets 14
7.2 Included StyleSheets 14
7.3 Default Stylesheet 15
7.4 Migrating Stylesheet Format 15
7.5 Migrating to the New Default Stylesheet 15
7.5.1 Updated Font Alias Names 15
7.5.2 Updated Pate Template Names 16
8 Creating Stylesheets 17
8.1 Styles in Detail 17
8.2 Style Elements 18
8.2.1 Inline Styles 20
8.2.2 Lists 20
8.3 Page Layout 21
8.3.1 Page Setup 21
8.3.2 Page Templates 22
8.4 Font Alias 23
8.5 Widows and Orphans 23
8.6 Table Styles 24
9 Syntax Highlighting 26
9.1 File inclusion 29
9.1.1 Include with Boundaries 29
9.1.2 Options 29
10 Fonts 30
10.1 Standard PDF Fonts 30
10.2 Font Embedding 30
10.2.1 The Easy Way 30
Page 3
1 Introduction
This document explains how to use rst2pdf. Here is the very short version:
That will, as long as mydocument.txt is a valid reStructured Text (rST) document, produce a file called
mydocument.pdf which is a PDF version of your document.
Of course, that means you just used default styles and settings. If it looks good enough for you, then you may
stop reading this document, because you are done with it. If you are reading this in a PDF, it was generated
using those default settings.
However, if you want to customize the output, or are just curious to see what can be done, let's continue.
3 Configuration File
Since version 0.8, rst2pdf will read (if it is available) configuration files in /etc/rst2pdf.conf and
~/.rst2pdf/config.
The user's file at ~/.rst2pdf/config will have priority over the system's at /etc/rst2pdf.conf 1
Here's an example file showing some of the currently available options:
[general]
# A comma-separated list of custom stylesheets. Example:
# stylesheets="fruity.json,a4paper.json,verasans.json"
stylesheets=""
font_path=""
language="en_US"
fit_mode="shrink"
fit_background_mode="center"
break_level=0
break_side="any"
blank_first_page=false
first_page_even=false
# Smart quotes.
# 0: Suppress all transformations. (Do nothing.)
# 1: Performs default SmartyPants transformations: quotes (including ‘‘backticks''
# -style), em-dashes, and ellipses. "--" (dash dash) is used to signify an em-dash;
# there is no support for en-dashes.
# 2: Same as 1, except that it uses the old-school typewriter shorthand for
# dashes: "--" (dash dash) for en-dashes, "---" (dash dash dash) for em-dashes.
# 3: Same as 2, but inverts the shorthand for dashes: "--" (dash dash) for
# em-dashes, and "---" (dash dash dash) for en-dashes.
smartquotes=0
footnote_backlinks=true
inline_footnotes=false
# custom_cover = cover.tmpl
floating_images = false
4 Pipe usage
If no input nor output are provided, stdin and stdout will be used respectively.
You may want to use rst2pdf in a linux pipe as such:
or:
5 Images
5.1 Inline
You can insert images in the middle of your text like this:
Note
Image URLs
Attempting to be more compatible with rst2html, rst2pdf will try to handle images specified as HTTP or
FTP URLs by downloading them to a temporary file and including them in the PDF.
This is probably not a good idea unless you are really sure the image won't go away.
.. image:: home.png
:width: 3in
.. image:: home.png
:width: 80%
5 Images Page 11
.. image:: home.png
:width: 7cm
The valid units you can use are: em, ex, px, in, cm, mm, pt, pc, %, "".
• px: Pixels. If you specify the size using this unit, rst2pdf will convert it to inches using the default DPI
explained above.
• No unit. If you just use a number, it will be considered as pixels. (IMPORTANT: this used to default to
points. It was changed to be more compatible with rst2html)
• em: This is the same as your base style's font size. By default: 10 points.
• ex: rst2pdf will use the same broken definition as IE: em/2. In truth this should be the height of the
lower-case x character in your base style.
• in: Inches (1 inch = 2.54 cm).
• cm: centimeters (1cm = 0.39 inches)
• mm: millimeters (10mm = 1cm)
• pt: 1/72 inch
• pc: 1/6 inch
• %: percentage of available width in the frame. Setting a percentage as a height does not work and
probably never will.
If you don't specify a size at all, rst2pdf will do its best to figure out what it should do:
Since there is no specified size, rst2pdf will try to convert the image's pixel size to inches using the DPI
information available in the image itself. You can set that value using most image editors. For example, using
Gimp, it's in the Image -> Print Size menu.
So, if your image is 6000 pixels wide, and is set to 1200DPI, it will be 5 inches wide.
If your image doesn't have a DPI property set, and doesn't have it's desired size specified, rst2pdf will
arbitrarily decide it should use 300DPI (or whatever you choose with the --default-dpi option).
Page 12 6 Styling ReStructuredText
6 Styling ReStructuredText
For well-formatted and consistent PDFs, the best starting point is well-formatted and consistent markup.
There are some excellent references for ReStructuredText which we won't reproduce here but they are highly
recommended as a starting point for working with rst2pdf.
In general, applying a stylesheet to a structured document will output a decent PDF with minimum fuss. That
said, there are plenty of customisation and styling options available so read on if that sounds interesting.
.. class:: special
Multiple styles can be listed and are applied in order where properties in the right hand styles override those
to the left:
.. role:: redtext
For more information about this, please check the rST docs, and for style information check the section in this
manual on inline styles.
.. header::
Often, you may want to put a page number there, or a section name.The following magic tokens will be
replaced (More may be added as rst2pdf evolves):
###Page###
Replaced by the current page number.
###Title###
Replaced by the document title
###Section###
Replaced by the current section title
###SectNum###
Replaced by the current section number. Important: You must use the sectnum directive for this to
work.
###Total###
Replaced by the total number of pages in the document. Keep in mind that this is the real number of
pages, not the displayed number, so if you play with page counters this number will probably be wrong.
Headers and footers are visible by default but they can be disabled by specific Page Templates for example,
cover pages. You can also set headers and footers via command line options or the configuration file.
If you want to do things like "put the page number on the out side of the page, check The oddeven directive
6.3 Footnotes
Currently rst2pdf doesn't support real footnotes, and converts them to endnotes. There is a real complicated
technical reason for this: I can't figure out a clean way to do it right.
You can get the same behaviour as with rst2html by specifying --inline-footnotes, and then the
footnotes will appear where you put them (in other words, not footnotes, but "in-the-middle-of-text-notes" or
just plain notes.)
Page 14 7 Customizing PDF Output
Often it makes sense to specify multiple stylesheets, for example to set the page size, the main styles, and
some syntax highlighting. In that case, use comma-separated values:
Order does matter: rst2pdf applies its own stylesheet first and then the list in given in order, so the last
stylesheet in the list will take precedence over the ones that went before.
Styles will always be searched in these places, in order:
• serif uses the PDF serif font (Times) instead of the default Sans Serif (Arial)
• freetype-sans uses your system's default TrueType Sans Serif font
• freetype-serif uses your system's default TrueType Serif font
• twelvepoint makes the base font 12pt (default is 10pt)
• tenpoint makes the base font 10pt
• eightpoint makes the base font 8pt
Page layout styles
These stylesheets modify your page layout.
• double-sided adds a gutter margin (margin at the "in side" of the pages)
Page size styles
Stylesheets that change the paper size.
The usual standard paper sizes are supported: A0, A1, A2, A3, A4 (default), A5, A6, B0, B1, B2, B3, B4,
B5, B6, Letter, Legal, 11x17
The name of the stylesheet is lowercase.
Code block styles
See Syntax Highlighting
So, if you want to have a two-column, legal size, serif document with code in murphy style:
rst2pdf --print-stylesheet
This makes an excellent starting point for creating a stylesheet. The default one is always included by default,
so only the values that should be changed need to be included in the new stylesheet.
The command also accepts a list of paths, or wildcards, and by default will output the new stylesheet(s) to
stdout. To write them to files instead, use the --save flag with the command above.
This table shows the old name and the equivalent new name:
Historical Current
stdFont fontSerif
stdSerif fontSerif
stdBold fontSerifBold
stdBoldItalic fontSerifBoldItalic
stdItalic fontSerifItalic
stdMono fontMono
stdMonoBold fontMonoBold
stdMonoBoldItalic fontMonoBoldItalic
stdMonoItalic fontMonoItalic
stdSans fontSans
stdSansBold fontSansBold
stdSansBoldItalic fontSansBoldItalic
stdSansItalic fontSansItalic
Historical Current
– mainPage
cutePage decoratedPage
emptyPage emptyPage
oneColumn oneColumn
twoColumn Move to separate twocolumn template file
threeColumn –
8 Creating Stylesheets
The stylesheets are YAML-formatted and give control over many aspects of how the PDF is rendered. The
main aspects are the styles of the elements, the page setup and templates, and the fonts to use . These are
described in the following sections.
Only the settings that you want to change need to be included so for example, this would be a valid
stylesheet:
pageSetup:
size: A5
fontsAlias:
fontSerif: Times-Roman
styles:
normal:
fontSize: 14
linkColor: #330099
Most of the other elements for colours and formatting are in the styles section.
There are particular styles which have great effect, they are base, normal and bodytext.
Here's an example, the twelvepoint stylesheet:
styles:
base:
fontSize: 12
Since all other styles inherit base, changing the fontSize changes the fontSize for everything in your
document.
The normal style is meant for most elements, so usually it's the same as changing base.
The bodytext style is for elements that form paragraphs. So, for example, you can set your document to be
left-aligned like this:
styles:
- bodytext:
alignment: TA_LEFT
There are elements, however, that don't inherit from bodytext, for example headings and the styles used in
the table of contents. Those are elements that are not real paragraphs, so they should not follow the
indentation and spacing you use for your document's main content.
The heading style is inherited by all sorts of titles: section titles, topic titles, admonition titles, etc.
If your document requires a style that is not defined in your stylesheet, it will print a warning and use
bodytext instead.
Also, the order of the styles is important: if styleA is the parent of styleB, styleA should be earlier in the
stylesheet.
Page 18 8.2 Style Elements
code:
parent: literal
fontName
The name of the font to use for this type of element. It can be either the name of a font on your system, or
one of the aliased fonts. The default is Helvetica as shown in the example here.
Example:
fontName: Helvetica
See also:
• Font Alias
• Fonts
fontSize
Use either a number (meaning point size) or a percentage. The default size for bodytext is 10.
Example:
fontSize: 150%
leftIndent: 0
rightIndent: 0
firstLineIndent
Example:
firstLineIndent: 0
alignment
The paragraph justification of the text. The values TA_LEFT and TA_RIGHT can be used.
Example:
alignment: TA_LEFT
8.2 Style Elements Page 19
spaceBefore: 4
spaceAfter: 8
bulletFontName: Helvetica
bulletFontSize: 10
bulletText: "\u2022"
bulletIndent: 0
See also:
• Table Styles
textColor
Use either a color name, or a hex value including the # character at the start.
Example:
textColor: black
backColor
Use either the value None, a color name, or a hex value including the # character at the start. Sets the
background color of the element.
Example:
backColor: beige
wordWrap
Can be set to None.
Example:
wordWrap: None
borderColor: darkgray
borderPadding: 6
Page 20 8.2 Style Elements
borderWidth: 0.5
borderRadius: None
allowWidows: 5
allowOrphans: 4
See also:
margin-top: 2cm
margin-bottom: 2cm
margin-left: 2cm
margin-right: 2cm
margin-gutter: 0cm
• fontName
• fontSize
• textColor
• backColor
8.2.2 Lists
Styling lists is mostly a matter of spacing and indentation.
The space before and after a list is taken from the item-list and bullet-list styles:
styles:
item-list
parent: bodytext
spaceBefore: 0
commands:
- - VALIGN: [[0, 0], [-1, -1]]
- TOP
- - RIGHTPADDING: [[0, 0], [1, -1], 0]
colWidths:
8.3 Page Layout Page 21
- 20pt
- bullet-list
parent: bodytext
spaceBefore: 0
commands:
- - VALIGN: [[0, 0], [-1, -1]]
- TOP
- - RIGHTPADDING: [[0, 0], [1, -1], 0]
colWidths:
- '20'
Yes, these are table styles, because they are implemented as tables. The RIGHTPADDING command and the
colWidths option can be used to adjust the position of the bullet/item number.
To control the separation between items, you use the item-list-item and bullet-list-item styles'
spaceBefore and spaceAfter options. For example:
bullet-list-item:
parent: bodytext
spaceBefore: 20
Remember that this is only used between items and not before the first or after the last items.
pageSetup:
size: A4
width:
height:
margin-top: 2cm
margin-bottom: 2cm
margin-left: 2cm
margin-right: 2cm
spacing-header: 5mm
spacing-footer: 5mm
margin-gutter: 0cm
pageSetup:
size: null
Page 22 8.3 Page Layout
width: 32cm
height: 18cm
When both width/height and size are specified, size will be used, and width/height ignored.
pageTemplates:
coverPage:
frames:
- [0cm, 0cm, 100%, 100%]
showHeader: false
showFooter: false
oneColumn:
frames:
- [0cm, 0cm, 100%, 100%]
twoColumn:
frames:
- [0cm, 0cm, 49%, 100%]
- [51%, 0cm, 49%, 100%]
A page template has a name (oneColumn, twoColumn), some options, and a list of frames. A frame is a list
containing this:
[ left position, bottom position, width, height, left padding, bottom padding, right padding, top padding]
You can use all the usual units, cm, mm, inch, and %, which means "percentage of the page (excluding
margins and headers or footers)". Using % is probably the smartest for columns and gives you a fluid layout,
while the other units are better for more "fixed" elements.
Since we can have more than one template, there is a way to specify which one we want to use, and a way to
change from one to another.
To specify the first template, do it in your stylesheet, in pageSetup (oneColumn is the default):
pageSetup:
firstTemplate: oneColumn
Then, to change to another template, in your document use this syntax (will change soon, though):
8.4 Font Alias Page 23
.. raw:: pdf
PageBreak twoColumn
That will trigger a page break, and the new page will use the twoColumn template.
You can see an example of this in the Montecristo folder in the source package.
The supported page template options and their defaults are:
• showHeader : True
• defaultHeader : None
Has the same effect as the header directive in the document.
• showFooter : True
• defaultFooter : None
Has the same effect as the footer directive in the document.
• background: None
The background should be an image, which will be centered in your page or stretched to match your
page size, depending on the --fit-background-mode option, so use with caution.
fontsAlias:
fontSerif: Helvetica
fontSerifBold: Helvetica-Bold
fontSerifItalic: Helvetica-Oblique
fontSerifBoldItalic: Helvetica-BoldOblique
fontMono: Courier
This defines the fonts used in the styles. You can use, for example, Helvetica directly in a style, but if later
you want to use another font all through your document, you will have to change it in each style. So, I
suggest you use aliases.
More information in the dedicated Fonts section.
A literal block::
A code block:
.. code-block:: python
def x(y):
print y**2
.. class:: thick
+-------+---------+
| A | B |
+-----------------+
2. It's a style that automatically applies to something that is drawn using a table. Currently these include:
BACKGROUND
ROWBACKGROUNDS
COLBACKGROUNDS
VALIGN
Each takes as argument a couple of coordinates, where (0,0) is top-left, and (-1,-1) is bottom-right,
and 0 or more extra arguments.
For example, INNERGRID takes a line width and a color:
That would mean "draw all lines inside the table with .25pt black"
colWidths
A list of the column widths you want, in the unit you prefer (default unit is pt).
Example:
"colWidths": ["3cm",null]
If your colWidths has fewer values than columns in your table, the rest are auto-calculated. A column
width of null means "guess".
If you don't specify column widths, the table will try to look proportional to the restructured text source.
Note
The command option used for table styles is not kept across stylesheets. For example, the default
stylesheet defines endnote with this command list:
If you redefine endnote in another stylesheet and use this to create a vertical line between the
endnote's columns:
"commands": [
[ "VALIGN", [ 0, 0 ], [ -1, -1 ], "TOP" ],
[ "LINEAFTER", [ 0, 0 ], [ 1, -1 ], .25, "black" ]
]
Page 26 9 Syntax Highlighting
9 Syntax Highlighting
rst2pdf adds a non-standard directive, called code-block, which produces syntax highlighted for many
languages using Pygments.
For example, if you want to include a Python fragment:
.. code-block:: python
def myFun(x,y):
print x+y
def myFun(x,y):
print x+y
Notice that you need to declare the language of the fragment. Here's a list of the currently supported.
You can use the linenos option to display line numbers:
1 def myFun(x,y):
2 print x+y
You can use the hl_lines option to emphasize certain lines by dimming the other lines. This parameter
takes a space separated list of line numbers. The other lines are then styled with the class pygments_diml
that defaults to gray. For example, to highlight print "line a" and print "line b":
def myFun(x,y):
print "line a"
print "line b"
print "line c"
• abap
• algol_nu
• algol
• arduino
• autumn
• borland
• bw
• colorful
• default
• emacs
• friendly
• fruity
• igor
• lovelace
• manni
9 Syntax Highlighting Page 27
• monokai
• murphy
• native
• paraiso-dark
• paraiso-light
• pastie
• perldoc
• rainbow_dash
• rrt
• sas
• solarized-dark
• solarized-light
• sphinx
• stata-dark
• stata-light
• stata
• styles
• tango
• trac
• vim
• vs
• xcode
You can use any of them instead of the default by adding, for example, a -s murphy to the command line.
If you already are using a custom stylesheet, use both:
>>> my_string.startswith('py')
True
Python traceback
'stripnl' : string_bool,
'stripall': string_bool,
'ensurenl': string_bool,
'tabsize' : directives.positive_int,
'encoding': directives.encoding,
# Lua
'func_name_hightlighting':string_bool,
'disabled_modules': string_list,
# Python Console
'python3': string_bool,
# Delphi
'turbopascal':string_bool,
'delphi' :string_bool,
'freepascal': string_bool,
'units': string_list,
# Modula2
'pim' : string_bool,
'iso' : string_bool,
'objm2' : string_bool,
'gm2ext': string_bool,
# CSharp
'unicodelevel' : csharp_unicodelevel,
# Literate haskell
'litstyle' : lhs_litstyle,
# Raw
'compress': raw_compress,
# Rst
'handlecodeblocks': string_bool,
# Php
'startinline': string_bool,
'funcnamehighlighting': string_bool,
'disabledmodules': string_list,
You can find more information about them in the pygments manual.
9.1 File inclusion Page 29
.. code-block:: python
:include: setup.py
.. code-block:: python
:include: assets/flowables.py
:start-at: class Separation(Flowable):
:end-before: class Reference(Flowable):
class Separation(Flowable):
"""A simple <hr>-like flowable"""
def draw(self):
self.canv.line(0, 0.5 * cm, self.w, 0.5 * cm)
9.1.2 Options
linenos
Display line numbers along the code
linenos_offset
If you include a file and are skipping the beginning, using the linenos_offset makes the line count
start from the real line number, instead of 1.
Page 30 10 Fonts
10 Fonts
Working with fonts on many different platforms is a challenge. Here you will find the best information we
have, but questions and updates are always welcome.
• Times_Roman
• Times-Bold
• Times-Italic
• Times-Bold-Italic
• Helvetica
• Helvetica_Bold
• Helvetica-Oblique
• Helvetica-Bold-Oblique
• Courier
• Courier-Bold
• Courier-Oblique
• Courier-Bold-Oblique
• Symbol
• Zapf-Dingbats
normal:
fontName: fonty
1. You need to have it installed in your system, and have the fc-match utility available (it's part of
fontconfig). You can test if it is so by running this command:
$ fc-match fonty
fonty.ttf: "Fonty" "Normal"
If you are in Windows, I need your help ;-) or you can use The Harder Way (True Type)
10 Fonts Page 31
2. The folder where fonty.ttf is located needs to be in your font path. You can set it using the
--font-path option. For example:
You don't need to put the exact folder, just something that is above it. In my own case, fonty is in
/usr/share/fonts/TTF
Whenever a font is embedded, you can refer to it in a style by its name, and to its variants by the aliases
Name-Oblique, Name-Bold, Name-BoldOblique.
/usr/share/texmf-dist/fonts/type1/urw/palatino/uplb8a.pfb
/usr/share/texmf-dist/fonts/type1/urw/palatino/uplbi8a.pfb
/usr/share/texmf-dist/fonts/type1/urw/palatino/uplr8a.pfb
/usr/share/texmf-dist/fonts/type1/urw/palatino/uplri8a.pfb
/usr/share/texmf-dist/fonts/afm/urw/palatino/uplb8a.afm
/usr/share/texmf-dist/fonts/afm/urw/palatino/uplbi8a.afm
/usr/share/texmf-dist/fonts/afm/urw/palatino/uplr8a.afm
/usr/share/texmf-dist/fonts/afm/urw/palatino/uplri8a.afm
title:
fontName: URWPalladioL-Bold
There are some standard aliases defined so you can use other names:
So, for example, you can use Palatino or New Century SchoolBook-Oblique And it will mean
URWPalladioL or CenturySchL-Ital, respectively.
Whenever a font is embedded, you can refer to it in a style by its name, and to its variants by the aliases
Name-Oblique, Name-Bold, Name-BoldOblique.
embeddedFonts: []
The embeddedFonts element is a list of the font files that you want to embed into your PDF document. For
each font, you provide the filenames of the four variants of the file (normal, bold, italic, bold italic).
For example, suppose you want to use the nice public domain Tuffy font, then you need to give the filenames
of all variants:
embeddedFonts:
- [Tuffy.ttf, Tuffy_Bold.ttf, Tuffy_Italic.ttf, Tuffy_Bold_Italic.ttf]
This will provide your styles with fonts called Tuffy, Tuffy_Bold and so on. They will be available with the
names based on the filenames (Tuffy_Bold) and also by standard aliases similar to those of the standard
PDF fonts (Tuffy-Bold, Tuffy-Oblique, Tuffy-BoldOblique, etc..)
Now, if you use italics in a paragraph whose style uses the Tuffy font, it will use Tuffy_Italic. That's why
it's better if you use fonts that provide the four variants, and that you lsit them in the correct order.
If your font lacks a variant, use the "normal" variant instead.
For example, if you only had Tuffy.ttf:
embeddedFonts:
- [Tuffy.ttf, Tuffy.ttf, Tuffy.ttf, Tuffy.ttf]
However, that means that italics and bold in styles using Tuffy will not work correctly (they will display as
regular text).
If you want to use this as the base font for your document, you should change the fontsAlias section
accordingly. For example:
fontsAlias:
fontSans: Tuffy
fontSansBoldfontSansBold: Tuffy_Bold
fontSansItalic: Tuffy_Italic
fontSansBoldItalic: Tuffy_Bold_Italic
fontMono: Courier
If, on the other hand, you only want a specific style to use the Tuffy font, don't change the fontAlias but
rather set the fontName properties for that style. For example:
heading1:
parent: normal
fontName: Tuffy_Bold
fontSize: 18
keepWithNext: true
spaceAfter: 6
By default, rst2pdf will search for the fonts in its fonts folder and in the current folder. You can make it search
another folder by passing the --font-folder option, or you can use absolute paths in your stylesheet.
11 Raw Directive Page 33
11 Raw Directive
11.1 Raw PDF
rst2pdf has a very limited mechanism to pass commands to reportlab, the PDF generation library. You can
use the raw directive to insert pagebreaks and spacers (other reportlab flowables may be added if there's
interest), and set page transitions.
The syntax is shell-like, here's an example:
One page
.. raw:: pdf
.. raw:: pdf
Spacer 0,200
Spacer 0 200
The unit used by the spacer by default is points, and using a space or a comma is the same thing in all
cases.
.. raw:: pdf
SetPageCounter 0 lowerroman
This sets the counter to 0, and makes it display in lower roman characters (i, ii, iii, etc) which is a style often
used for the pages before the document proper (for example, TOCs and abstracts).
It can take zero or two arguments.
SetPageCounter
When used with no arguments, it sets the counter to 0, and the style to arabic numerals.
SetPageCounter number style
When used with two arguments, the first argument must be a number, it sets the page counter to that
number.
The second number is a style of counter. Valid values are:
Note
Page counter changes take effect on the current page.
PageBreak twoColumn
In addition, two additional attributes are supported: background and fit-background-mode. These allow
setting the background image for this page and how to fit it (One of scale, scale_width or center). For
example:
or:
.. raw:: pdf
FrameBreak 50
.. raw:: pdf
.. raw:: pdf
Transition Glitter 3 90
Uses the Glitter effect, for 3 seconds, at direction 90 degrees (from the right?)
Keep in mind that Transition sets the transition from this page to the next so the natural thing is to use it
before a PageBreak:
.. raw:: pdf
Transition Dissolve 1
PageBreak
.. raw:: pdf
The optional position is a set of 4 numbers for x_begin, y_begin`, ``x_end and y_end
Note
The counter role only works in PDF, if you're reading the HTML version of the manual then this
section is broken. Sorry :/
This is a nonstandard interpreted text role, which means it will only work with rst2pdf. It implements an
unlimited number of counters you can use in your text. For example, you could use it to have numbered
figures, or numbered tables.
The syntax is this:
You can start counters from any number (this prints 12): :counter:`seq2:12`
Note
These are non-standard roles, which means they will only work with rst2pdf and not with rst2html or
any other docutils tools.
The version and revision roles can be used to get the version and revision of an installed Python
package. For example:
Important
The package in question must be installed in the same environment that you are running rst2pdf in.
14 The oddeven directive Page 39
.. oddeven::
.. container::
This will appear on even pages. It's a single paragraph, so no need for
containers.
• I intentionally have disabled splitting into pages for this, because I have no idea how that could make
sense. That means that if its content is larger than a frame, you will make rst2pdf barf with one of those
ugly errors.
• It will reserve the space of the larger of the two sets of contents. So if one is small and the other large, it
will look wrong. I may be able to fix this though.
• If you try to generate HTML (or anything other than a PDF via rst2pdf) from a file containing this, it will
not do what you want.
Page 40 15 Mathematics
15 Mathematics
If you have Matplotlib installed, rst2pdf supports a math role and a math directive. You can use them to insert
formulae and mathematical notation in your documents using a subset of LaTeX syntax, but doesn't require
you have LaTeX installed.
For example, here's how you use the math directive:
.. math::
If you want to insert mathematical notation in your text like this: that is the job of the math role:
This is :math:`\pi`
Produces: This is
Note that while the math directive embeds fonts and draws your formula as text, the math role embeds an
image. That means:
16 Hyphenation
If you want good looking documents, you want to enable hyphenation.
To do it, you first need to install the pyphen python module.
Then, you need to specify the language in each style that you want hyphenation to work. To have
hyphenation in the whole document, you can do it in the base style.
For example, for an English document, hyphenation can be turned on for the whole document with:
base:
hyphenationLang: en-US
embeddedHyphenation: 1
Notice the embeddedHyphenation option. It is optional, but it makes so that hyphenations will give
preference to splitting words at embedded hyphens in the text.
If you are creating a multilingual document, you can declare styles with specific languages. For example, you
could inherit bodytext for Spanish:
bodytext_es:
parent: bodytext
hyphenationLang: es-ES
embeddedHyphenation: 1
And all paragraphs declared using the bodytext_es style would have Spanish hyphenation:
.. class:: bodytext_es
If you want to disable hyphenation in a style that inherits hyphenationLang from its parent, you can do so
by setting hyphenationLang to 0.
Page 42 17 Smart Quotes
17 Smart Quotes
Quoted from the smartypants documentation:
This feature can perform the following transformations:
Straight quotes ( " and ' ) into "curly" quote HTML entities
Backticks-style quotes (``like this'') into "curly" quote HTML entities
Dashes (-- and ---) into en- and em-dash entities
Three consecutive dots (... or . . .) into an ellipsis entity
This means you can write, edit, and save your posts using plain old ASCII straight quotes, plain dashes,
and plain dots, but your published posts (and final PDF output) will appear with smart quotes,
em-dashes, and proper ellipses.
You can enable this by passing the --smart-quotes option in the command line. By default, it's disabled.
Here are the different values you can use (again, from the smartypants docs):
0
Suppress all transformations. (Do nothing.)
1
Performs these transformations: quotes (including ``backticks'' -style), em-dashes, and ellipses. "--"
(dash dash) is used to signify an em-dash; there is no support for en-dashes.
2
Same as smarty_pants="1", except that it uses the old-school typewriter shorthand for dashes: "--"
(dash dash) for en-dashes, "---" (dash dash dash) for em-dashes.
3
Same as smarty_pants="2", but inverts the shorthand for dashes: "--" (dash dash) for em-dashes,
and "---" (dash dash dash) for en-dashes.
Currently, even if you enable it, this transformation will only take place in regular paragraphs, titles, headers,
footers and block quotes.
18 Sphinx Page 43
18 Sphinx
Sphinx is a very popular tool. This is the description from its website:
Sphinx is a tool that makes it easy to create intelligent and beautiful documentation, written by Georg
Brandl and licensed under the BSD license.
It was originally created to translate the new Python documentation, and it has excellent support for the
documentation of Python projects, but other documents can be written with it too.
rst2pdf includes an experimental PDF extension for Sphinx.
To use it in your existing Sphinx project you need to do the following:
extensions = ['sphinx.ext.autodoc','rst2pdf.pdfbuilder']
2. Add the PDF options at the end of conf.py, adapted to your project:
pdf_documents = [
('index', 'MyProject', 'My Project', 'Author Name'),
]
# verbosity level. 0 1 or 2
# pdf_verbosity = 0
pdf:
$(SPHINXBUILD) -b pdf $(ALLSPHINXOPTS) _build/pdf
@echo
@echo "Build finished. The PDF files are in _build/pdf."
if "%1" == "pdf" (
%SPHINXBUILD% -b pdf %ALLSPHINXOPTS% %BUILDDIR%/pdf
echo.
echo.Build finished. The PDF files are in %BUILDDIR%/pdf
goto end
)
Then you can run make pdf or sphinx-build -b pdf ... similar to how you did it before.
Page 46 19 Extensions
19 Extensions
rst2pdf can get new features from extensions. Extensions are python modules that can be enabled with the
-e option.
Several are included with rst2pdf.
1. It demonstrates the technique and can be a starting point for similar user-written processing modules;
and
2. It provides a simplified syntax for documents which are targeted only at rst2pdf, rather than docutils in
general.
The design goal of "base rst2pdf" is to be completely compatible with docutils, such that a file which works as
a PDF can also work as HTML, etc.
Unfortunately, base docutils is a slow-moving target, and does not make this easy. For example, SVG
images do not work properly with the HTML backend unless you install a patch, and docutils has no concept
of page breaks or additional vertical space (other than the <hr>).
So, while it would be nice to have documents that render perfectly with any backend, this goal is hard to
achieve for some documents, and once you are restricted to a particular transformation type, then you might
as well have a slightly nicer syntax for your source document.
Preprocessor extensions:
All current extensions except style occupy a single line in the source file.
.. include::
Processes the include file as well. An include file may either be a restructured text file, OR may be an
RSON or JSON stylesheet. The determination is made by trying to parse it as RSON. If it passes, it is a
stylesheet; if not, well, we'll let the docutils parser have its way with it.
.. page::
Is translated into a raw PageBreak.
.. space::
Is translated into a raw Spacer. If only one number given, is used for vertical space. This is the canonical
use case, since horizontal space is ignored anyway!
.. style::
Allows you to create in-line stylesheets. As with other restructured text components, the stylesheet data
must be indented. Stylesheets are in RSON or JSON.
.. widths::
creates a new table style (based on table or the first non-numeric token) and creates a class using that
style specifically for the next table in the document. (Creates a .. class::, so you must specify .. widths::
immediately before the table it applies to. Allows you to set the widths for the table, using percentages.
SingleWordAtLeftColumn
19.2 Dotted_TOC (-e dotted_toc) Page 47
If a single word at the left column is surrounded by blank lines, the singleword style is automatically
applied to the word. This is a workaround for the broken interaction between docutils subtitles and
bibliographic metadata. (I found that docutils was referencing my subtitles from inside the TOC, and that
seemed silly. Perhaps there is a better workaround at a lower level in rst2pdf.)
Preprocessor operation:
The preprocessor generates a file that has the same name as the source file, with .build_temp. embedded in
the name, and then passes that file to the restructured text parser.
This file is left on the disk after operation, because any error messages from docutils will refer to line
numbers in it, rather than in the original source, so debugging could be difficult if the file were automatically
removed.
• It uses a callback to a nested function which doesn't even bother to assume the original enclosing scope
is available at callback time. This leads it to do crazy things like eval()
• It uses a single name in the canvas for the callback function (this is what kills multiple TOC capability)
when it would be extremely easy to generate a unique name.
Page 48 20 Developers
20 Developers
20.1 Guidelines
If you want to do something inside rst2pdf, you are welcome! The process looks something like this:
pytest tests/input/test_summary_of_test.txt
less tests/output/test_summary_of_test.log
xdg-open tests/output/test_summary_of_test.pdf # or 'open' on macOS
• Once resolved, copy the generated output PDF, if any, to tests/reference and commit this
along with the files in tests/input.
• Submit a pull request.
• If you added a command line option, document it in doc/rst2pdf.txt. That will make it appear in the
manual and in the man page.
• If you implemented a new feature, please document it in manual.rst (or in a separate file and add an
include in manual.rst)
• If you implement an extension, make the docstring valid restructured text and link it to the manual like
the others.
21 Initial checkout Page 49
21 Initial checkout
Clone the repo from https://github.com/rst2pdf/rst2pdf, then install and activate a venv:
Note, that on Apple Silicon Macs, you may need this to get tests passing:
21.2 Pre-commit
rst2pdf uses the pre-commit framework to automate various style checkers. This must be enabled locally.
You can install this using pip or your local package manager. For example, to install using pip:
If pre-commit locally behaves differently to CI, then run pre-commit clean to clear your cache before
further investigation.
pytest
You can also run tests in parallel using pytest-xdist by passing the -n auto flag.
Firstly install:
pytest -n auto
pytest tests/input/sphinx-repeat-table-rows
Note
Some tests require the execution of the dot command, you should install the package graphviz from
your packages manager.
22 Licenses Page 51
22 Licenses
This is the license for rst2pdf:
Copyright (c) 2007-2020 Roberto Alsina and the contributors to the rst2pdf project
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Some fragments of rstpdf are copied from ReportLab under the following license:
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE OFFICERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
Page 52 22 Licenses
1 The /etc/rst2pdf.conf location makes sense for Linux and linux-like systems. if
you are using rst2pdf in other systems, please contact me and tell me where the
system-wide config file should be.