SimplyPDF is an Android library for generating PDF documents inside an app, from Kotlin or Java code or from a JSON template. It lays content out for you: text, styled text, lists, tables, images and shapes flow down the page and onto new pages by themselves, so there is no need to position everything by hand. A JSON template lets the layout be controlled from a server and filled with the user's content, for reports, invoices, receipts, tickets or forms.
It is built on Android's own PDF engine, so it is small, needs no native code, embeds only the fonts it uses, and lays out every script Android supports, such as Bengali, Hindi or Arabic. It is published under the MIT license.
- Text: sizes, colors, alignment, underline and strikethrough, and styled text from Android spans or HTML, mixing bold, italic, colors and sizes in one paragraph
- Fonts: embedded from font files, assets, res/font or a Typeface, with bold and italic
- Lists: bulleted, numbered, lettered and roman, nested, with markers that line up
- Tables: widths in percent, cells merged across rows and columns, text, image and list cells, border styles and widths
- Images: from a Bitmap, or downloaded from a URL
- Shapes: lines, rectangles with square or rounded corners, circles, ovals and polygons
- Pages: any paper size, orientation, margins, page background colors, headers, footers with page numbers, and automatic page breaks that split long text and tall table rows between lines
- Document: metadata such as title and author, shown by PDF viewers
- Output: a File, an OutputStream or a Uri (MediaStore, Storage Access Framework)
- JSON: everything above from a JSON template, with custom entry types of your own
- Document metadata, from code or JSON
- A page background color for every page, kept on pages created automatically (#48)
- Table cells merged across rows with rowSpan (#47)
- Long text and tall table rows split across pages between lines
- Output to an OutputStream or a Uri, and paper setup in JSON
- Styled text, shapes, page footers with page numbers, embedded fonts and lists
- Fixes: JSON text entries render again, table border styles combine, borderWidth works, table borders stay straight, percentage widths are exact, cells report their real size, and the JSON engine skips invalid values instead of failing
The sample app generates a showcase of every change and feature from showcase_2_2_0.json.
Add JitPack and the dependency:
repositories {
maven { url 'https://jitpack.io' }
}
dependencies {
implementation 'com.github.wwdablu:SimplyPDF:2.2.0'
}
SimplyPDF needs Android 6.0 (API 23) or later. It uses Kotlin coroutines, Glide for images from URLs and Gson for JSON; they are added with it.
val document = SimplyPdf.with(context, File(context.filesDir, "hello.pdf"))
.paperSize(PrintAttributes.MediaSize.ISO_A4)
.margin(Margin(36U, 36U, 36U, 36U))
.build()
document.text.write("Hello, SimplyPDF", TextProperties().apply { textSize = 24; bold = true })
document.list.draw(listOf(ListItem("Text"), ListItem("Lists"), ListItem("Tables")),
ListProperties().apply { type = ListType.NUMBER })
lifecycleScope.launch {
val saved = document.finish() // suspend; writes the PDF, true when it succeeded
}
All sizes and positions are in PDF points, 1/72 of an inch, whatever the screen density: an A4 page is
about 595 x 842 points, and textSize = 12 is 12 point text. Table cell widths in code are points too,
while in JSON they are percentages of the usable page width.
SimplyPdf.with(...) returns a builder, and build() returns the SimplyPdfDocument that the
composers draw on.
val document = SimplyPdf.with(context, file) // or an OutputStream, or a Uri
.paperSize(PrintAttributes.MediaSize.ISO_A4)
.paperOrientation(DocumentInfo.Orientation.PORTRAIT)
.colorMode(DocumentInfo.ColorMode.COLOR)
.margin(Margin(startMargin, topMargin, endMargin, bottomMargin)) // UInt values, such as 36U
.pageBackgroundColor(Color.WHITE)
.metadata(DocumentMetadata(title = "Invoice 42", author = "Acme Ltd"))
.font("brand", FontSource.FromAsset("fonts/Brand.ttf"))
.pageModifier(PageHeader(listOf(TextCell("Acme Ltd", headerText, Cell.MATCH_PARENT))))
.pageFooter(PageFooter { page -> listOf(TextCell("Page $page", footerText, Cell.MATCH_PARENT)) })
.build()
| Builder method | Usage |
|---|---|
| with(context, File / OutputStream / Uri) | Where the PDF is written. A stream is flushed but not closed; a Uri is opened, replaced and closed |
| paperSize(MediaSize) | Any PrintAttributes.MediaSize, A4 by default |
| paperOrientation(Orientation) | PORTRAIT or LANDSCAPE |
| colorMode(ColorMode) | COLOR or MONO |
| margin(Margin) | Start, top, end and bottom margins |
| pageBackgroundColor(Int) | Background color of every page |
| firstPageBackgroundColor(Int) | Background color of the first page only |
| metadata(DocumentMetadata) | Title, author and other document properties |
| font(name, FontSource) | Registers a font for text to use by name |
| pageModifier(PageModifier) | Drawn at the top of every page, such as a PageHeader |
| pageFooter(PageFooter) | Drawn at the bottom of every page |
The document is built in memory and written when finish() is called.
| SimplyPdfDocument | Usage |
|---|---|
| text, list, table, image, shape | The composers that draw content |
| fonts | Registers fonts by name: fonts.register(name, FontSource) |
| insertEmptySpace(height) | Moves the current position down |
| insertEmptyLines(count) | Moves down by count times lineHeight |
| newPage(color) | Starts a new page, with the page background color unless a color is given |
| finish() | Suspend function that writes the PDF and returns true when it succeeded |
| usablePageWidth, usablePageHeight | Size of the page inside the margins, and above the footer |
| startMargin, topMargin, endMargin, bottomMargin | The margins in points |
| pageContentHeight | The current position from the top of the page |
| currentPage, currentPageNumber | The page being drawn, whose canvas can be drawn on directly |
| pageFooter | The footer, which can be changed or removed part way through |
| documentInfo | Paper, margins, colors and metadata of the document |
| addContentHeight(height) | Moves the current position down after drawing on the canvas directly |
SimplyPdf.with(context, file)
.pageBackgroundColor(Color.parseColor("#C8E6C9")) // every page
.firstPageBackgroundColor(Color.WHITE) // optional: the first page only
.build()
- pageBackgroundColor is used for the first page, unless firstPageBackgroundColor is set, and for pages created with newPage() without a color. It defaults to white.
- newPage(color) gives a single page its own color.
- When content does not fit and SimplyPDF starts a new page by itself, the new page keeps the color of the page the content continues from.
- The color can be changed part way through with documentInfo.pageBackgroundColor; it applies to the pages created after that.
A PageHeader draws its cells at the top of every page, each cell on its own line. Any
PageModifier can draw on each new page: override render(simplyPdfDocument), draw on
currentPage.canvas and move the position down with addContentHeight().
A footer is drawn on the bottom margin of every page, and content stops above it. It is one row of cells side by side, asked for page by page so it can show the page number.
.pageFooter(PageFooter { page -> listOf(TextCell("Page $page", textProperties, Cell.MATCH_PARENT)) })
A footer that is the same on every page can be given as a list of cells: PageFooter(cells). The
total number of pages is not known while pages are drawn, so "page X of Y" is not possible.
Content that does not fit in the space left on a page moves to a new page. Text taller than a page, and table rows taller than a page, are split between lines across as many pages as needed; only an image or a single line taller than a page is cut.
Document properties are written into the PDF, and PDF viewers show them in their document properties.
.metadata(DocumentMetadata(
title = "Annual Report",
author = "Soumya Kanti Kar",
subject = "Results for the year",
keywords = listOf("report", "annual"),
creator = "My App"))
| Property | Usage |
|---|---|
| title | Title of the document |
| author | Person or organisation that wrote the content |
| subject | What the document is about |
| keywords | Keywords describing the document |
| creator | Name of the app that created the document |
| producer | Software that produced the PDF; SimplyPDF and its version by default |
Every property is optional and any script is supported. The creation and modified dates are filled in automatically.
Composers draw content at the current position and move it down. Each document has one of each:
| Composer | Draws |
|---|---|
| document.text | Text and styled text |
| document.list | Bulleted, numbered, lettered and roman lists |
| document.table | Tables of text, image and list cells |
| document.image | Bitmaps and images from URLs |
| document.shape | Lines, rectangles, circles, ovals and polygons |
A custom composer extends UnitComposer.
document.text.write("Hello World", TextProperties().apply {
textSize = 12
textColor = "#000000"
alignment = Layout.Alignment.ALIGN_CENTER
})
write(text, properties, pageWidth, xMargin, yMargin) takes any CharSequence; pageWidth defaults to
usablePageWidth and the margins to 0.
| TextProperties | Usage |
|---|---|
| textSize | Size in points, 10 by default |
| textColor | Color such as "#000000" |
| font | Name of a registered font, or of a system font family such as "serif" or "monospace" |
| bold, italic | Bold or italic text; made artificially when the font has no such style |
| typeface | A Typeface, used instead of font when set |
| alignment | ALIGN_NORMAL, ALIGN_CENTER or ALIGN_OPPOSITE |
| underline | Underlines the text |
| strikethrough | Strikes through the text |
| bulletSymbol | A character drawn before the paragraph; use lists for proper lists |
Styled text: any CharSequence works, so Android styled text can mix bold, italic, colors, sizes
and underlines in one paragraph, for example a SpannableStringBuilder with StyleSpan or
ForegroundColorSpan, or HtmlCompat.fromHtml("Total: <b>42</b>", HtmlCompat.FROM_HTML_MODE_COMPACT).
In JSON, a text entry or text cell can have "html" instead of "content".
Fonts are registered under a name, from a file, the app's assets, res/font or a Typeface, and text uses one through the font property. Only the glyphs the document uses are embedded, so the PDF looks the same in every viewer. TrueType and OpenType fonts are supported.
val document = SimplyPdf.with(context, File(context.filesDir, "invoice.pdf"))
.font("brand", FontSource.FromAsset("fonts/Brand-Regular.ttf"))
.font("signature", FontSource.FromFile(downloadedFontFile))
.build()
// or later: document.fonts.register("heading", FontSource.FromResource(R.font.heading))
document.text.write("Invoice", TextProperties().apply { font = "brand"; textSize = 28; bold = true })
A font that cannot be loaded throws an IllegalArgumentException when it is registered. A name that is
not registered is looked up as a system font family. In styled text, a registered font is used by its
name in a TypefaceSpan or in HTML, such as <font face="brand">, on Android 9 and later.
Lists can be bulleted, numbered, lettered or roman, with nested items. The markers are right aligned in one column, so "9." and "10." end at the same place, and lines that wrap stay under the text. Items flow onto the next pages like text, and a marker always stays with the first line of its item.
document.list.draw(listOf(
ListItem("Prepare", listOf(ListItem("Gather the documents"), ListItem("Check the dates")),
childType = ListType.LOWER_LETTER),
ListItem(HtmlCompat.fromHtml("<b>Submit</b> the form", HtmlCompat.FROM_HTML_MODE_COMPACT)),
ListItem("Wait", textProperties = TextProperties().apply { textColor = "#C62828" })
), ListProperties().apply {
type = ListType.NUMBER
textProperties = TextProperties().apply { textSize = 14 }
})
| ListProperties | Usage |
|---|---|
| type | BULLET, NUMBER, LOWER_LETTER, UPPER_LETTER, LOWER_ROMAN or UPPER_ROMAN; nested items use the same type unless their parent's childType is set |
| textProperties | Text properties of the items and markers, unless an item has its own |
| start | Number of the first item; nested lists start at 1 |
| indent | Space before the markers of the top level |
| itemSpacing | Space between items, 4 by default |
| bulletSymbols | Bullets for each nesting level, "•", "◦" and "▪" by default |
| numberFormat | Format of numbered markers, where {n} is the number: "{n}." by default, or such as "({n})" |
A list can also go in a table cell with ListCell(items, listProperties, width).
A table is a list of rows, each a list of cells side by side. Cell widths are in points, or
Cell.MATCH_PARENT for the usable page width.
val widths = document.table.resolveRowWidths(listOf(30, 70))
document.table.draw(listOf(
listOf(TextCell("Name", bold, widths[0]), TextCell("Soumya Kanti Kar", text, widths[1])),
listOf(TextCell("Photo", bold, widths[0]), ImageCell(bitmap, ImageProperties(), widths[1])),
listOf(TextCell("Skills", bold, widths[0]), ListCell(skills, ListProperties(), widths[1]))
), TableProperties().apply { borderWidth = 1 })
| Cell | Holds |
|---|---|
| TextCell(text, TextProperties, width) | Text or styled text |
| ImageCell(bitmap, ImageProperties, width) | A bitmap, shrunk to fit the cell |
| ListCell(items, ListProperties, width) | A list |
Every cell has xMargin and yMargin, 10 by default, and rowSpan.
Column widths: resolveRowWidths(percents) turns percentages into widths that add up to exactly
the usable page width, with columns starting at the same percentage starting at the same point in
every row, so the borders stay straight. resolveCellWidth(percent) gives a single width. Rows over
100% are scaled to fit, and cells of 0% are left out.
Merged cells: a cell covers several rows with rowSpan; the rows below leave out a cell at its
position and their cells are placed next to it. Its content is aligned to the top, and the last row
it covers grows if it needs more room. Cells are merged across columns by giving a cell the width of
the columns it covers. Rows joined by merged cells are kept together on a page.
document.table.draw(listOf(
listOf(TextCell("Fruit", props, third).apply { rowSpan = 2 },
TextCell("Apple", props, third), TextCell("10", props, third)),
listOf(TextCell("Banana", props, third), TextCell("5", props, third))
), TableProperties())
| TableProperties | Usage |
|---|---|
| borderColor | Color of the borders |
| borderWidth | Thickness of the borders; 0, the default, draws hairlines. Wider borders are centered on the cell edges, so cells keep their size |
| drawBorder | Whether borders are drawn |
| borderStyle | BORDER_ALL (default), or a combination of BORDER_OUTER, BORDER_INNER, BORDER_HORIZONTAL and BORDER_VERTICAL, such as BORDER_OUTER or BORDER_HORIZONTAL |
| align | ALIGN_LEFT or ALIGN_CENTER for a table narrower than the page |
A cell narrower than its xMargin on both sides is drawn empty, and a row without cells is not drawn.
document.image.drawBitmap(bitmap, ImageProperties().apply { alignment = Composer.Alignment.CENTER })
lifecycleScope.launch {
document.image.drawFromUrl(url, context, ImageProperties()) // suspend; downloads with Glide
document.finish()
}
One bitmap pixel is drawn as one point, and a bitmap wider than the page is shrunk to fit. Alignment is START, CENTER or END. Bitmaps passed in are not recycled by SimplyPDF.
document.shape.draw(Shape.Rectangle(200f, 60f, cornerRadius = 12f), ShapeProperties().apply {
fillColor = "#BBDEFB"
alignment = Composer.Alignment.CENTER
})
Shapes are Shape.Line(length), Shape.Rectangle(width, height, cornerRadius),
Shape.Circle(diameter), Shape.Oval(width, height) and Shape.Polygon(points). ShapeProperties
has lineColor (null for no outline), lineWidth, fillColor (null for no fill) and alignment.
draw() draws at the current position and moves below the shape; drawAtPosition(shape, properties, x, y)
draws anywhere on the page without moving the position.
lifecycleScope.launch {
val saved = document.finish()
}
finish() draws the footer of the last page, writes the PDF and its metadata to the output, and
always closes the document. It returns false when the PDF could not be written. A document cannot be
drawn on after it is finished.
A JSON template describes the whole document, and SimplyPDF draws it without any composer code:
lifecycleScope.launch {
SimplyPdf.usingJson(context, File(context.filesDir, "report.pdf"), json) // or an OutputStream or Uri
}
The JSON can also draw into a document set up in code: SimplyPdf.usingJson(context, document, json).
Either way the document is finished, so finish() is not called.
The example below is showcase_2_2_0.json, which uses every feature: what's new in 2.2.0 as nested bullets on the first page, then text, fonts, lists, tables, images, shapes and page colors, with a header, a footer with page numbers and metadata. The sample app's "2.2.0 showcase (from JSON)" button generates it.
{
"page" : [
{
"type" : "setup",
"papersize" : "A4",
"orientation" : "portrait",
"colormode" : "color",
"margin" : { "start" : 36, "top" : 30, "end" : 36, "bottom" : 30 },
"fonts" : { "script" : "/system/fonts/DancingScript-Regular.ttf" },
"metadata" : {
"title" : "SimplyPDF 2.2.0 - What's new and feature showcase",
"author" : "Soumya Kanti Kar",
"subject" : "Every change in 2.2.0 and every feature of SimplyPDF, generated from JSON",
"keywords" : [ "SimplyPDF", "Android", "PDF", "JSON", "2.2.0" ],
"creator" : "SimplyPDF sample app"
}
},
{
"type" : "header",
"contents" : [
{ "type" : "text", "html" : "<b><font color='#00695C'>SimplyPDF 2.2.0</font></b> · Android PDF generation, from code or JSON",
"properties" : { "size" : 10, "color" : "#757575" } }
]
},
{
"type" : "footer",
"contents" : [
{ "type" : "text", "content" : "Generated by SimplyPDF from a JSON template", "width" : 70,
"properties" : { "size" : 8, "color" : "#757575" } },
{ "type" : "text", "content" : "Page {page}", "width" : 30,
"properties" : { "size" : 8, "color" : "#757575", "alignment" : "ALIGN_OPPOSITE" } }
]
}
],
"contents" : [
{ "type" : "text", "content" : "What's new in SimplyPDF 2.2.0",
"properties" : { "size" : 24, "bold" : true, "color" : "#00695C" } },
{ "type" : "text", "content" : "New features", "properties" : { "size" : 14, "bold" : true } },
{ "type" : "list", "listtype" : "bullet", "itemspacing" : 3, "properties" : { "size" : 11 },
"items" : [
"Document metadata: title, author, subject, keywords, creator and producer, from code or JSON",
"Page background color for every page, kept on pages created automatically, and newPage(color) (#48)",
"Table cells merged across rows with rowSpan (#47)",
"Long text and tall table rows split across pages between lines",
"Output to a File, an OutputStream or a Uri (MediaStore, Storage Access Framework)",
"Paper setup in JSON: paper size by name or in millimetres, orientation and color mode",
"Styled text from Android spans or HTML, in text and in table cells",
"Shapes: line, rectangle, rounded rectangle, circle, oval and polygon",
"Page footers with page numbers, and {page} in JSON footers",
"Fonts embedded from files, assets or res/font, with bold and italic",
"Lists: bulleted, numbered, lettered and roman, nested, and in table cells"
] },
{ "type" : "text", "content" : "Fixes and improvements", "properties" : { "size" : 14, "bold" : true } },
{ "type" : "list", "listtype" : "bullet", "itemspacing" : 3, "properties" : { "size" : 11 },
"items" : [
"JSON text entries are rendered again",
"Table border style flags can be combined, such as outer and horizontal",
{ "content" : "Table widths", "items" : [
"Percentage widths are exact, and borders stay straight across rows of any shape",
"Rows over 100% are scaled to fit, and 0% cells are ignored",
"borderWidth sets the thickness of table borders" ] },
{ "content" : "Cells", "items" : [
"TextCell and ImageCell report the size they are actually drawn at",
"ImageCell margins are applied the right way round" ] },
"The JSON engine skips missing or invalid values instead of failing",
"finish() always closes the document, and drawFromUrl is a suspend function"
] },
{ "type" : "text", "content" : "Sample app", "properties" : { "size" : 14, "bold" : true } },
{ "type" : "list", "listtype" : "bullet", "itemspacing" : 3, "properties" : { "size" : 11 },
"items" : [
"Covers every feature, follows the system light or dark mode, and opens the PDF it generated",
"Includes this showcase, generated from showcase_2_2_0.json in its assets"
] },
{ "type" : "newpage" },
{ "type" : "text", "content" : "SimplyPDF capabilities",
"properties" : { "size" : 24, "bold" : true, "color" : "#00695C" } },
{ "type" : "text", "html" : "Everything in this PDF, from here to the end, was drawn by SimplyPDF from <b>one JSON file</b>, which is printed on the last pages. The same features are available from Kotlin and Java.",
"properties" : { "size" : 11 } },
{ "type" : "text", "content" : "1. Document and page setup", "properties" : { "size" : 16, "bold" : true, "color" : "#00695C" } },
{ "type" : "table", "properties" : { "width" : 1, "color" : "#9E9E9E" }, "contents" : [
{ "row" : [
{ "type" : "text", "content" : "Capability", "width" : 30, "properties" : { "size" : 10, "bold" : true } },
{ "type" : "text", "content" : "How", "width" : 70, "properties" : { "size" : 10, "bold" : true } } ] },
{ "row" : [
{ "type" : "text", "content" : "Paper", "width" : 30, "properties" : { "size" : 10 } },
{ "type" : "text", "content" : "Any Android paper size such as A4, A5, Letter or Legal, or a custom size in millimetres; portrait or landscape; color or mono", "width" : 70, "properties" : { "size" : 10 } } ] },
{ "row" : [
{ "type" : "text", "content" : "Margins", "width" : 30, "properties" : { "size" : 10 } },
{ "type" : "text", "content" : "Start, top, end and bottom margins that every composer respects", "width" : 70, "properties" : { "size" : 10 } } ] },
{ "row" : [
{ "type" : "text", "content" : "Page colors", "width" : 30, "properties" : { "size" : 10 } },
{ "type" : "text", "content" : "A first page color, a background color for every page, and a color per new page", "width" : 70, "properties" : { "size" : 10 } } ] },
{ "row" : [
{ "type" : "text", "content" : "Headers and footers", "width" : 30, "properties" : { "size" : 10 } },
{ "type" : "text", "content" : "Rows of cells on every page; footers can show the page number, as at the bottom of this page", "width" : 70, "properties" : { "size" : 10 } } ] },
{ "row" : [
{ "type" : "text", "content" : "Metadata", "width" : 30, "properties" : { "size" : 10 } },
{ "type" : "text", "content" : "Title, author, subject, keywords, creator and producer, shown in the document properties of PDF viewers", "width" : 70, "properties" : { "size" : 10 } } ] },
{ "row" : [
{ "type" : "text", "content" : "Output", "width" : 30, "properties" : { "size" : 10 } },
{ "type" : "text", "content" : "A File, an OutputStream or a content Uri, with a coroutine based finish()", "width" : 70, "properties" : { "size" : 10 } } ] },
{ "row" : [
{ "type" : "text", "content" : "Automatic pages", "width" : 30, "properties" : { "size" : 10 } },
{ "type" : "text", "content" : "Content flows down the page and onto new pages by itself; long text and tall rows are split between lines", "width" : 70, "properties" : { "size" : 10 } } ] }
] },
{ "type" : "text", "content" : "2. Text", "properties" : { "size" : 16, "bold" : true, "color" : "#00695C" } },
{ "type" : "text", "content" : "Text in any size, such as 9 points,", "properties" : { "size" : 9 } },
{ "type" : "text", "content" : "or 20 points, in any color,", "properties" : { "size" : 20, "color" : "#1565C0" } },
{ "type" : "text", "content" : "aligned to the center,", "properties" : { "size" : 12, "alignment" : "ALIGN_CENTER" } },
{ "type" : "text", "content" : "or to the end of the line.", "properties" : { "size" : 12, "alignment" : "ALIGN_OPPOSITE" } },
{ "type" : "text", "content" : "Underlined text", "properties" : { "size" : 12, "underline" : true } },
{ "type" : "text", "content" : "Struck through text", "properties" : { "size" : 12, "strikethrough" : true } },
{ "type" : "text", "html" : "Styled text mixes <b>bold</b>, <i>italic</i>, <u>underline</u>, <font color='#C62828'>colors</font>, <big>bigger</big> and <small>smaller</small> text, and <sup>super</sup>/<sub>sub</sub>scripts in one paragraph.",
"properties" : { "size" : 12 } },
{ "type" : "text", "content" : "Scripts other than Latin are laid out by Android itself: সহজ পিডিএফ · सरल पीडीएफ · Ελληνικά · Русский", "properties" : { "size" : 12 } },
{ "type" : "newpage", "backgroundcolor" : "#F1F8E9" },
{ "type" : "text", "content" : "This page has a background color of its own, from its newpage entry.",
"properties" : { "size" : 10, "italic" : true, "color" : "#558B2F" } },
{ "type" : "text", "content" : "3. Fonts", "properties" : { "size" : 16, "bold" : true, "color" : "#00695C" } },
{ "type" : "text", "content" : "A font file, embedded in the PDF", "properties" : { "size" : 26, "font" : "script", "color" : "#6A1B9A" } },
{ "type" : "text", "content" : "System families: serif", "properties" : { "size" : 12, "font" : "serif" } },
{ "type" : "text", "content" : "System families: monospace", "properties" : { "size" : 12, "font" : "monospace" } },
{ "type" : "text", "content" : "System families: sans-serif-condensed", "properties" : { "size" : 12, "font" : "sans-serif-condensed" } },
{ "type" : "text", "content" : "Bold, italic, and both", "properties" : { "size" : 12, "bold" : true, "italic" : true } },
{ "type" : "text", "html" : "Fonts switch inside styled text: plain, <font face='script'>the script font</font> and <font face='monospace'>monospace</font>.",
"properties" : { "size" : 12 } },
{ "type" : "text", "content" : "4. Lists", "properties" : { "size" : 16, "bold" : true, "color" : "#00695C" } },
{ "type" : "list", "listtype" : "number", "properties" : { "size" : 11 },
"items" : [
"Numbered lists, with markers that line up",
{ "content" : "Nested lists of their own type", "listtype" : "lowerletter",
"items" : [ "lettered", { "content" : "and deeper", "listtype" : "lowerroman", "items" : [ "roman", "numerals" ] } ] },
{ "html" : "Styled items: <b>bold</b> and <font color='#C62828'>red</font>" },
"Long items wrap onto more lines and the lines that wrap stay under the text of the item, not under its marker"
] },
{ "type" : "list", "listtype" : "upperletter", "numberformat" : "({n})", "properties" : { "size" : 11 },
"items" : [ "Custom number formats", "such as (A), (B)" ] },
{ "type" : "list", "bullets" : [ "✓", "–" ], "indent" : 20, "properties" : { "size" : 11, "color" : "#2E7D32" },
"items" : [ { "content" : "Custom bullets per level", "items" : [ "and indentation" ] } ] },
{ "type" : "text", "content" : "5. Tables", "properties" : { "size" : 16, "bold" : true, "color" : "#00695C" } },
{ "type" : "table", "properties" : { "width" : 1, "color" : "#616161" }, "contents" : [
{ "row" : [
{ "type" : "text", "content" : "Widths in percent", "width" : 25, "properties" : { "size" : 10, "bold" : true } },
{ "type" : "text", "content" : "Merged across two rows", "width" : 25, "rowspan" : 2, "properties" : { "size" : 10, "bold" : true } },
{ "type" : "text", "html" : "<i>Styled</i> <b>cells</b>", "width" : 50, "properties" : { "size" : 10 } } ] },
{ "row" : [
{ "type" : "text", "content" : "25%", "width" : 25, "properties" : { "size" : 10 } },
{ "type" : "list", "width" : 50, "listtype" : "bullet", "properties" : { "size" : 10 },
"items" : [ "Lists in cells", "next to a merged cell" ] } ] },
{ "row" : [
{ "type" : "text", "content" : "An image cell", "width" : 25, "properties" : { "size" : 10 } },
{ "type" : "image", "source" : "https://avatars0.githubusercontent.com/u/28639189?s=80&v=4", "width" : 25,
"properties" : { "alignment" : "CENTER" } },
{ "type" : "text", "content" : "Rows of any shape keep the right border straight", "width" : 50, "properties" : { "size" : 10 } } ] }
] },
{ "type" : "space", "height" : 8 },
{ "type" : "text", "content" : "Border styles: outer only, inner only, and outer with horizontal lines, 2 points wide",
"properties" : { "size" : 10 } },
{ "type" : "table", "properties" : { "borderstyle" : 1, "color" : "#1565C0" }, "contents" : [
{ "row" : [ { "type" : "text", "content" : "Outer", "width" : 50, "properties" : { "size" : 10 } },
{ "type" : "text", "content" : "border", "width" : 50, "properties" : { "size" : 10 } } ] } ] },
{ "type" : "space", "height" : 6 },
{ "type" : "table", "properties" : { "borderstyle" : 2, "color" : "#1565C0" }, "contents" : [
{ "row" : [ { "type" : "text", "content" : "Inner", "width" : 50, "properties" : { "size" : 10 } },
{ "type" : "text", "content" : "border", "width" : 50, "properties" : { "size" : 10 } } ] },
{ "row" : [ { "type" : "text", "content" : "only", "width" : 50, "properties" : { "size" : 10 } },
{ "type" : "text", "content" : "here", "width" : 50, "properties" : { "size" : 10 } } ] } ] },
{ "type" : "space", "height" : 6 },
{ "type" : "table", "properties" : { "borderstyle" : 5, "width" : 2, "color" : "#1565C0" }, "contents" : [
{ "row" : [ { "type" : "text", "content" : "Outer and", "width" : 50, "properties" : { "size" : 10 } },
{ "type" : "text", "content" : "horizontal", "width" : 50, "properties" : { "size" : 10 } } ] },
{ "row" : [ { "type" : "text", "content" : "2 points", "width" : 50, "properties" : { "size" : 10 } },
{ "type" : "text", "content" : "wide", "width" : 50, "properties" : { "size" : 10 } } ] } ] },
{ "type" : "space", "height" : 10 },
{ "type" : "text", "content" : "6. Images", "properties" : { "size" : 16, "bold" : true, "color" : "#00695C" } },
{ "type" : "text", "content" : "Images from a URL, loaded with Glide, or from a Bitmap, aligned to the start, center or end:",
"properties" : { "size" : 11 } },
{ "type" : "image", "source" : "https://avatars0.githubusercontent.com/u/28639189?s=100&v=4", "properties" : { "alignment" : "CENTER" } },
{ "type" : "text", "content" : "7. Shapes", "properties" : { "size" : 16, "bold" : true, "color" : "#00695C" } },
{ "type" : "text", "content" : "Lines, rectangles with square or rounded corners, circles, ovals and polygons, outlined, filled or both:",
"properties" : { "size" : 11 } },
{ "type" : "shape", "shape" : "line", "length" : 523, "properties" : { "linecolor" : "#00695C", "linewidth" : 2 } },
{ "type" : "space", "height" : 6 },
{ "type" : "shape", "shape" : "rectangle", "width" : 160, "height" : 40, "radius" : 10,
"properties" : { "linecolor" : "#1565C0", "linewidth" : 2, "fillcolor" : "#BBDEFB" } },
{ "type" : "space", "height" : 6 },
{ "type" : "shape", "shape" : "circle", "diameter" : 50,
"properties" : { "linecolor" : null, "fillcolor" : "#EF6C00", "alignment" : "center" } },
{ "type" : "space", "height" : 6 },
{ "type" : "shape", "shape" : "oval", "width" : 120, "height" : 40,
"properties" : { "linewidth" : 2, "alignment" : "end" } },
{ "type" : "space", "height" : 6 },
{ "type" : "shape", "shape" : "polygon", "points" : [ [ 0, 50 ], [ 30, 0 ], [ 60, 50 ] ],
"properties" : { "linecolor" : "#6A1B9A", "linewidth" : 2, "fillcolor" : "#E1BEE7", "alignment" : "center" } },
{ "type" : "text", "content" : "8. JSON engine", "properties" : { "size" : 16, "bold" : true, "color" : "#00695C" } },
{ "type" : "list", "listtype" : "bullet", "properties" : { "size" : 11 },
"items" : [
"Page entries: setup, header and footer; content entries: text, image, table, list, shape, space and newpage",
"Apps add their own entry types with custom page and composer converters",
"Missing or invalid values are skipped with a warning instead of failing the whole document",
"The JSON can set up a new document, or draw into one already set up in code",
"The same JSON can be written to a File, an OutputStream or a Uri"
] },
{ "type" : "space", "height" : 6 },
{ "type" : "text", "html" : "Need help or found a bug? Open an issue at <u>github.com/wwdablu/SimplyPDF</u>.",
"properties" : { "size" : 11 } },
{ "type" : "newpage" },
{ "type" : "text", "content" : "The JSON that generated this PDF",
"properties" : { "size" : 16, "bold" : true, "color" : "#00695C" } },
{ "type" : "text", "html" : "A JSON file cannot contain a copy of itself, so the last entry holds the placeholder <b>{{JSON_SOURCE}}</b>. The sample app replaces it with the text of the file before generating the PDF, so the text below is exactly <i>showcase_2_2_0.json</i>. Being longer than a page, it also shows text continuing across pages.",
"properties" : { "size" : 9 } },
{ "type" : "text", "content" : "{{JSON_SOURCE}}", "properties" : { "size" : 7, "font" : "monospace" } }
]
}
Notes on this example:
- The last entry prints the JSON itself. A JSON file cannot contain a copy of itself, so its text is
the placeholder
{{JSON_SOURCE}}, which TestShowcase.kt replaces with the file's text before calling usingJson. Without that step the placeholder is printed as it is. - The "script" font is a file of the device,
/system/fonts/DancingScript-Regular.ttf; where it is missing, that text uses the default font. In an app, fonts usually come from assets, such as"fonts" : { "script" : "fonts/Script.ttf" }. - The images are downloaded, so generating it needs a network connection.
A shorter, older example is structure.json.
Both "page" and "contents" are optional. Entries of an unknown type are skipped, values that are not valid are ignored, mostly with a warning in the log, and "properties" left out use the defaults.
Page entries
| type | Keys |
|---|---|
| setup | "papersize": a name such as "A4", "A5", "LETTER", "LEGAL" or any PrintAttributes.MediaSize constant such as "ISO_B5", or { "width", "height" } in millimetres; "orientation": "portrait" or "landscape"; "colormode": "color" or "mono"; "margin": { "start", "top", "end", "bottom" }, no margins when left out; "backgroundcolor": the first page; "pagebackgroundcolor": every page; "metadata": { "title", "author", "subject", "keywords" (array or comma separated), "creator", "producer" }; "fonts": { name : path }, a path starting with "/" or "file://" being a file and any other a file in assets |
| header | "contents": cells, each drawn on its own line at the top of every page |
| footer | "contents": cells side by side at the bottom of every page; "{page}" in their text is the page number |
Content entries
| type | Keys |
|---|---|
| text | "content", or "html" for styled text; "properties": text properties |
| image | "source": an image URL; "properties": { "alignment": "START", "CENTER" or "END" } |
| list | "items": texts, or objects with "content" or "html", "properties", nested "items" and their "listtype"; "listtype": "bullet", "number", "lowerletter", "upperletter", "lowerroman" or "upperroman"; "start", "indent", "itemspacing", "numberformat", "bullets": [ symbols ]; "properties": text properties |
| table | "contents": [ { "row" : [ cells ] } ]; "properties": table properties |
| shape | "shape": "line" ("length"), "rectangle" ("width", "height", optional "radius"), "circle" ("diameter" or "radius"), "oval" ("width", "height") or "polygon" ("points": [ [x, y], ... ]); "properties": { "linecolor" (null for none), "linewidth", "fillcolor", "alignment": "start", "center" or "end" } |
| space | "height" |
| newpage | optional "backgroundcolor" |
Table cells are "text", "image" or "list" entries with "width", a percentage of the usable page width (100 by default), and optional "rowspan". Widths in a row over 100% are scaled to fit, cells of 0% are left out, and the widths of merged cells above a row count towards its total.
Text properties: "size", "color", "font", "bold", "italic", "underline", "strikethrough", "alignment" ("ALIGN_NORMAL", "ALIGN_CENTER" or "ALIGN_OPPOSITE") and "bulletSymbol".
Table properties: "width" (border width), "color", "drawborder", "borderstyle" (1 outer, 2 inner, 4 horizontal, 8 vertical, 128 all, added together to combine) and "align" (1 left, 2 center).
Apps add their own entry types with converters passed to usingJson. A converter for a type that already exists replaces it.
class DividerConverter(document: SimplyPdfDocument) : ComposerConverter(document) {
override fun getTypeHandler() = "divider"
override fun generate(composeJsonObject: JSONObject) {
simplyPdfDocument.shape.draw(Shape.Line(simplyPdfDocument.usablePageWidth.toFloat()), ShapeProperties())
}
}
SimplyPdf.usingJson(context, document, json, composerConverters = listOf(DividerConverter(document)))
A PageConverter handles entries in "page" the same way.
The sample app has a button for every feature, and opens the PDF it generated. It follows the system light or dark mode, and includes a form for metadata and the 2.2.0 showcase generated from JSON.
This section is for AI coding assistants, such as Claude or ChatGPT, that integrate SimplyPDF into an app. It summarises the facts needed to write correct code without reading the source.
- Artifact:
com.github.wwdablu:SimplyPDF:2.2.0from JitPack (maven { url 'https://jitpack.io' }). minSdk 23. Kotlin, usable from Java. MIT license. - Purpose: generate PDFs on Android from code or a JSON template. It does not read, edit, merge, encrypt or sign PDFs, and has no hyperlinks, bookmarks or form fields.
- Engine: Android's
android.graphics.pdf.PdfDocument. Text is real, selectable text; fonts are embedded as subsets. - Units: PDF points (1/72 inch) everywhere, independent of screen density. A4 is about 595 x 842. One bitmap pixel is drawn as one point.
- Layout model: a cursor moves down the page. Every composer draws at the cursor and moves it down.
Content that does not fit moves to a new page; text, lists and table rows taller than a page split
between lines. There is no absolute positioning, except
shape.drawAtPositionand drawing oncurrentPage.canvasdirectly.
com.wwdablu.soumya.simplypdf SimplyPdf, SimplyPdfDocument
com.wwdablu.soumya.simplypdf.document DocumentInfo, DocumentMetadata, Margin, PageHeader,
PageFooter, PageModifier, FontSource, DocumentFonts
com.wwdablu.soumya.simplypdf.composers Composer (Alignment), Shape, ListItem
com.wwdablu.soumya.simplypdf.composers.properties TextProperties, ImageProperties, TableProperties,
ShapeProperties, ListProperties, ListType
com.wwdablu.soumya.simplypdf.composers.properties.cell Cell, TextCell, ImageCell, ListCell
com.wwdablu.soumya.simplypdf.jsonengine.base ComposerConverter, PageConverter
// Builder
SimplyPdf.with(context: Context, file: File | outputStream: OutputStream | uri: Uri): SimplyPdf
.paperSize(PrintAttributes.MediaSize) .paperOrientation(DocumentInfo.Orientation.PORTRAIT|LANDSCAPE)
.colorMode(DocumentInfo.ColorMode.COLOR|MONO) .margin(Margin(start: UInt, top: UInt, end: UInt, bottom: UInt))
.pageBackgroundColor(@ColorInt Int) .firstPageBackgroundColor(@ColorInt Int)
.metadata(DocumentMetadata(title, author, subject, keywords: List<String>, creator, producer))
.font(name: String, FontSource.FromFile(File) | FromAsset(path) | FromResource(@FontRes id) | FromTypeface(tf))
.pageModifier(PageHeader(cells: List<Cell>)) .pageFooter(PageFooter { page: Int -> List<Cell> })
.build(): SimplyPdfDocument
// Document
document.text.write(text: CharSequence, TextProperties, pageWidth = usablePageWidth, xMargin = 0, yMargin = 0)
document.list.draw(items: List<ListItem>, ListProperties)
document.table.draw(rows: List<List<Cell>>, TableProperties)
document.table.resolveRowWidths(percents: List<Int>): List<Int> // points, summing to usablePageWidth
document.table.resolveCellWidth(percent: Int): Int
document.image.drawBitmap(Bitmap, ImageProperties, xMargin = 0, yMargin = 0)
suspend document.image.drawFromUrl(url: String, context, ImageProperties, xMargin = 0, yMargin = 0)
document.shape.draw(Shape, ShapeProperties) / drawAtPosition(Shape, ShapeProperties, x: Float, y: Float)
document.fonts.register(name, FontSource)
document.insertEmptySpace(height: Int); insertEmptyLines(count: Int); newPage(@ColorInt color = page background)
document.usablePageWidth; usablePageHeight; pageContentHeight; currentPage.canvas; currentPageNumber
suspend document.finish(): Boolean // must be called once, at the end
// Content
ListItem(text: CharSequence, children: List<ListItem> = emptyList(), childType: ListType? = null,
textProperties: TextProperties? = null)
TextCell(text: CharSequence, TextProperties, width: Int) / ImageCell(Bitmap, ImageProperties, width) /
ListCell(List<ListItem>, ListProperties, width) // width in points or Cell.MATCH_PARENT; .rowSpan, .xMargin, .yMargin
Shape.Line(length) / Rectangle(width, height, cornerRadius = 0f) / Circle(diameter) / Oval(width, height) /
Polygon(points: List<PointF>)
// JSON
suspend SimplyPdf.usingJson(context, file | outputStream | uri | document: SimplyPdfDocument, json: String,
pageConverters: List<PageConverter>? = null,
composerConverters: List<ComposerConverter>? = null)
Property objects are configured with apply { }: TextProperties().apply { textSize = 12; textColor = "#000000" }.
Colors in properties are strings such as "#RRGGBB"; colors in the builder and newPage are @ColorInt.
finish()andusingJson()are suspend functions: call them from a coroutine.usingJson()finishes the document itself, so do not callfinish()after it.- Images from URLs and image cells in JSON download over the network: the app needs the INTERNET permission.
- Table cell widths in code are points: use
resolveRowWidths(listOf(30, 70))for percentages. In JSON they are percentages. PageHeaderdraws its cells one per line;PageFooterdraws them side by side in one row.- Footers know the current page number but not the total page count.
- Use
ListComposerfor lists;TextProperties.bulletSymbolonly puts a symbol before one paragraph. - Registered fonts in HTML
<font face>or TypefaceSpan need Android 9; the font property works on every version. FontSourceloading errors throw IllegalArgumentException in code; in JSON a bad font is skipped.- Drawables decoded with screen density scaling have more pixels on denser screens, so they are drawn larger; decode images without density scaling for the same size on every device.
- A document can be written only once; build a new one for each PDF.
An invoice from code:
suspend fun writeInvoice(context: Context, file: File, lines: List<Pair<String, String>>): Boolean {
val document = SimplyPdf.with(context, file)
.margin(Margin(36U, 36U, 36U, 36U))
.metadata(DocumentMetadata(title = "Invoice", creator = "My App"))
.pageFooter(PageFooter { page -> listOf(TextCell("Page $page", TextProperties().apply {
textSize = 8; alignment = Layout.Alignment.ALIGN_OPPOSITE }, Cell.MATCH_PARENT)) })
.build()
document.text.write("Invoice", TextProperties().apply { textSize = 24; bold = true })
val widths = document.table.resolveRowWidths(listOf(70, 30))
val text = TextProperties().apply { textSize = 11 }
document.table.draw(lines.map { (item, price) ->
listOf(TextCell(item, text, widths[0]),
TextCell(price, TextProperties().apply { textSize = 11; alignment = Layout.Alignment.ALIGN_OPPOSITE }, widths[1]))
}, TableProperties().apply { borderWidth = 1; borderColor = "#9E9E9E" })
return document.finish()
}
The same from JSON, built from data by the app or a server:
{ "page" : [ { "type" : "setup", "margin" : { "start" : 36, "top" : 36, "end" : 36, "bottom" : 36 },
"metadata" : { "title" : "Invoice" } },
{ "type" : "footer", "contents" : [ { "type" : "text", "content" : "Page {page}",
"properties" : { "size" : 8, "alignment" : "ALIGN_OPPOSITE" } } ] } ],
"contents" : [
{ "type" : "text", "content" : "Invoice", "properties" : { "size" : 24, "bold" : true } },
{ "type" : "table", "properties" : { "width" : 1, "color" : "#9E9E9E" }, "contents" : [
{ "row" : [ { "type" : "text", "content" : "Design", "width" : 70, "properties" : { "size" : 11 } },
{ "type" : "text", "content" : "500.00", "width" : 30,
"properties" : { "size" : 11, "alignment" : "ALIGN_OPPOSITE" } } ] } ] } ] }
Saving to Downloads without storage permissions (Android 10 and later): insert a
MediaStore.Downloads entry with IS_PENDING = 1, pass its Uri to SimplyPdf.with(context, uri),
call finish(), then set IS_PENDING = 0. See
TestUriOutput.kt.
| Topic | File |
|---|---|
| Builder and JSON entry points | SimplyPdf.kt |
| Document, pages, cursor, finish | SimplyPdfDocument.kt |
| Composers | composers |
| JSON keys | Node.kt, SimplyJson.kt |
| Examples of every feature | sample app, showcase_2_2_0.json |
| Behaviour, as tests | androidTest |