Documentation
¶
Overview ¶
Package epub provides a comprehensive, high-performance, and idiomatic Go library for reading, writing, and in-place editing of EPUB 2 and EPUB 3 publications.
The package strictly implements modern specifications, including EPUB 3.3, the Open Container Format (OCF), the Open Packaging Format (OPF), the EPUB Navigation Document (XHTML), and legacy NCX tables of contents. It is verified against the W3C EPUB conformance test suite and real-world high-quality books from Standard Ebooks.
For in-depth tutorials, guides, and an interactive live web book showcase, visit https://epub.raitucarp.name/.
Architecture & Workflows ¶
The library is organized around three primary paradigms:
- Reader: Inspect and extract data from existing EPUB publications (files or memory).
- Writer: Create compliant EPUB publications from scratch or from Markdown documents.
- Editor: Mutate existing EPUB files with fluent method chaining and bidirectional Reader transitions.
1. Reading Publications ¶
Open a publication using OpenReader (from disk) or NewReader (from in-memory bytes). Use the methods on Reader to access metadata, resources, spine order, and contents:
book, err := epub.OpenReader("path/to/book.epub")
if err != nil {
log.Fatalf("failed to open epub: %v", err)
}
// Access metadata
fmt.Println("Titles: ", book.Title())
fmt.Println("Authors: ", book.Author())
fmt.Println("Languages: ", book.Language())
fmt.Println("Identifier: ", book.UID())
fmt.Println("Version: ", book.Version())
// Extract table of contents hierarchy
toc, err := book.TableOfContents()
if err == nil {
for _, item := range toc.Items {
fmt.Printf("- %s (%s)\n", item.Title, item.Href)
}
}
// Read chapter content directly as clean Markdown
md := book.ReadContentMarkdownById("chapter-1")
fmt.Println(md)
// Extract cover image
coverImg := book.Cover()
if coverImg != nil {
// process *image.Image
}
2. Creating Publications ¶
Initialize a Writer with a unique publication identifier using New. Add metadata, XHTML documents, images, styles, and a table of contents, then serialize to disk or an in-memory buffer:
w := epub.New("urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6")
w.Title("My Adventure")
w.Author("Jane Doe")
w.Languages("en")
w.Publisher("Open Press")
w.Date(time.Now())
// Add content documents
w.AddContent("chapter-1.xhtml", []byte(`<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Chapter 1</title></head>
<body><h1>Chapter 1</h1><p>The journey begins.</p></body>
</html>`))
// Define navigation
w.TableOfContents("toc", epub.TOC{
Title: "Table of Contents",
Items: []epub.TOC{
{Title: "Chapter 1", Href: "chapter-1.xhtml"},
},
})
// Write directly to file
if err := w.Write("output.epub"); err != nil {
log.Fatalf("failed to write epub: %v", err)
}
// Or obtain bytes directly without touching the filesystem:
// data, err := w.WriteBytes()
3. In-Place Editing ¶
The Editor allows you to load an existing EPUB, modify its metadata, replace or append chapters and assets, and write the result back to disk, stream to an io.Writer, or write into a byte buffer:
reader, err := epub.OpenReader("original.epub")
if err != nil {
log.Fatal(err)
}
// Transition from Reader into fluent Editor mode
editor, err := reader.Edit()
if err != nil {
log.Fatal(err)
}
// Chained metadata mutations
editor.Title("Updated Title", "Subtitle").
Author("Updated Author").
Publisher("Revised Edition Publishing").
Subject("Fiction", "Adventure").
Language("en").
Modified(time.Now())
// Add or update content
editor.AddContent("epilogue.xhtml", []byte(`<h1>Epilogue</h1><p>The end.</p>`))
// Multiple persistence targets:
// Target A: Save directly to disk
if err := editor.SaveAs("updated.epub"); err != nil {
log.Fatal(err)
}
// Target B: Stream to io.Writer (HTTP response, cloud storage, pipe)
// err := editor.Save(writer)
// Target C: Write into an existing byte buffer
// var b []byte
// err := editor.WriteBytes(&b)
// Target D: Seamlessly switch back to Reader mode in memory
// r, err := editor.Reader()
4. Markdown Integration ¶
Content documents can be compiled directly from Markdown sources. AddMarkdown converts a single markdown document into compliant XHTML, while AddMarkdownDirectory converts every Markdown file within a folder and extracts headings to construct the table of contents:
w := epub.New("urn:isbn:9780000000001")
w.Title("Markdown Collection")
w.Languages("en")
// Automatically process all *.md files in the manuscript directory
if err := w.AddMarkdownDirectory("manuscript"); err != nil {
log.Fatal(err)
}
w.Write("manuscript.epub")
5. Advanced Capabilities ¶
- Font Obfuscation: Transparently de-obfuscates and decrypts embedded fonts using both the IDPF (http://www.idpf.org/2008/embedding) and Adobe (http://ns.adobe.com/pdf/enc/2006/type) obfuscation algorithms.
- Multi-Rendition Publications: Support for publications declaring multiple renditions (e.g. reflowable text vs. fixed-layout comics) via ListRenditions and SelectPackageRendition.
- Accessibility & Landmarks: Reading systems can access structural landmarks (bodymatter, cover, toc) and page lists via Landmarks() and PageList().
See the runnable Example functions in this package and the programs under the examples/ directory for comprehensive recipes.
Example ¶
Example demonstrates the core write-then-read workflow. A publication is built in memory, serialized to bytes, and read back to verify its metadata.
package main
import (
"bytes"
"fmt"
"image"
"image/color"
"image/png"
"strings"
"github.com/raitucarp/epub"
)
// Example demonstrates the core write-then-read workflow. A publication is
// built in memory, serialized to bytes, and read back to verify its metadata.
func main() {
w := epub.New("urn:example:book")
w.Title("The Example Book")
w.Author("Jane Doe")
w.Languages("en")
w.AddContent("chapter-1.xhtml", sampleChapter("Chapter 1"))
if err := w.TableOfContents("toc", epub.TOC{
Title: "Contents",
Items: []epub.TOC{{Title: "Chapter 1", Href: "chapter-1.xhtml"}},
}); err != nil {
panic(err)
}
data, err := w.WriteBytes()
if err != nil {
panic(err)
}
book, err := epub.NewReader(data)
if err != nil {
panic(err)
}
fmt.Println(strings.Join(book.Title(), ", "))
fmt.Println(strings.Join(book.Author(), ", "))
fmt.Println(book.UID())
}
// sampleChapter returns a minimal XHTML content document for use in examples.
func sampleChapter(title string) []byte {
return []byte(`<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<h1>` + title + `</h1>
<p>This is a sample paragraph.</p>
</body>
</html>`)
}
// samplePNG returns a small in-memory PNG image for use in the image and cover
// examples.
func samplePNG() []byte {
img := image.NewRGBA(image.Rect(0, 0, 2, 2))
img.Set(0, 0, color.RGBA{R: 255, G: 0, B: 0, A: 255})
var buf bytes.Buffer
if err := png.Encode(&buf, img); err != nil {
panic(err)
}
return buf.Bytes()
}
// buildSampleBook constructs a complete in-memory EPUB and returns its bytes.
// It is used by the reading examples so they can operate without a file on
// disk.
func buildSampleBook() []byte {
w := epub.New("urn:example:sample")
w.Title("The Sample Book")
w.Author("Jane Doe")
w.Languages("en")
w.AddContent("chapter-1.xhtml", sampleChapter("Chapter 1"))
w.AddContent("chapter-2.xhtml", sampleChapter("Chapter 2"))
toc := epub.TOC{
Title: "Contents",
Items: []epub.TOC{
{Title: "Chapter 1", Href: "chapter-1.xhtml"},
{Title: "Chapter 2", Href: "chapter-2.xhtml"},
},
}
if err := w.TableOfContents("toc", toc); err != nil {
panic(err)
}
data, err := w.WriteBytes()
if err != nil {
panic(err)
}
return data
}
Output: The Example Book Jane Doe urn:example:book
Example (BookPipeline) ¶
Example_bookPipeline demonstrates assembling a complete publication in one pass: full metadata, a cover, multiple chapters, guide references, and a nested table of contents.
w := epub.New("urn:isbn:9780000000001")
w.Title("A Complete Book")
w.Author("Jane Doe")
w.Languages("en")
w.Description("An example of a complete book.")
w.Publisher("Example Press")
w.Rights("All rights reserved")
if err := w.Cover(samplePNG()); err != nil {
panic(err)
}
w.AddContent("cover.xhtml", sampleChapter("Cover"))
w.AddContent("chapter-1.xhtml", sampleChapter("Chapter 1"))
w.AddContent("chapter-2.xhtml", sampleChapter("Chapter 2"))
w.AddGuide(pkg.GuideRefCover, "cover.xhtml", "Cover")
toc := epub.TOC{
Title: "Contents",
Items: []epub.TOC{
{Title: "Chapter 1", Href: "chapter-1.xhtml", Items: []epub.TOC{
{Title: "Section 1.1", Href: "chapter-1.xhtml#section-1-1"},
}},
{Title: "Chapter 2", Href: "chapter-2.xhtml"},
},
}
if err := w.TableOfContents("toc", toc); err != nil {
panic(err)
}
if err := w.Write("book.epub"); err != nil {
panic(err)
}
Example (EpubToMarkdown) ¶
Example_epubToMarkdown demonstrates converting every content document to a Markdown file on disk.
book, err := epub.NewReader(buildSampleBook())
if err != nil {
panic(err)
}
dir, err := os.MkdirTemp("", "epub-markdown")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
for _, id := range book.ListContentDocumentIds() {
markdown := book.ReadContentMarkdownById(id)
path := filepath.Join(dir, id+".md")
if err := os.WriteFile(path, []byte(markdown), 0o644); err != nil {
panic(err)
}
fmt.Println(path)
}
Example (EpubToText) ¶
Example_epubToText demonstrates extracting the plain text of every spine document in reading order.
book, err := epub.NewReader(buildSampleBook())
if err != nil {
panic(err)
}
for _, res := range book.Spine() {
node := book.ReadContentHTMLById(res.ID)
fmt.Println("==", res.Href, "==")
fmt.Println(epub.GetTextContent(node))
}
Example (ReproduceStandardEbook) ¶
Example_reproduceStandardEbook demonstrates reproducing a publication from the repository's Standard Ebooks sample. The source path is relative to the repository root.
package main
import (
"strings"
"github.com/raitucarp/epub"
)
func main() {
src := "tests/data/arthur-conan-doyle_the-white-company.epub"
book, err := epub.OpenReader(src)
if err != nil {
panic(err)
}
w := epub.New(strings.Join(book.Identifier(), ", "))
w.Title(book.Title()...)
w.Author(book.Author()...)
w.Languages(book.Language()...)
if cover, err := book.CoverBytes(); err == nil {
if err := w.Cover(cover); err != nil {
panic(err)
}
}
for name, data := range book.ImageResources() {
w.AddImage(name, data)
}
for _, res := range book.Spine() {
w.AddContent(res.Href, res.Content)
}
toc, err := book.TableOfContents()
if err != nil {
panic(err)
}
if err := w.TableOfContents("toc", toc); err != nil {
panic(err)
}
if err := w.Write("reproduced.epub"); err != nil {
panic(err)
}
}
Output:
Example (RoundTrip) ¶
Example_roundTrip demonstrates reading an existing publication, adjusting its metadata, and writing a new EPUB while preserving the content and table of contents.
book, err := epub.NewReader(buildSampleBook())
if err != nil {
panic(err)
}
w := epub.New(book.UID())
w.Title(append([]string{"Second Edition"}, book.Title()...)...)
w.Author(book.Author()...)
w.Languages(book.Language()...)
for _, res := range book.Spine() {
w.AddContent(res.Href, res.Content)
}
toc, err := book.TableOfContents()
if err != nil {
panic(err)
}
if err := w.TableOfContents("toc", toc); err != nil {
panic(err)
}
if err := w.Write("second-edition.epub"); err != nil {
panic(err)
}
Index ¶
- func FindNode(node *html.Node, predicate func(*html.Node) bool) *html.Node
- func GetTextContent(node *html.Node) string
- type Editor
- func (e *Editor) AddAuthor(author string) *Editor
- func (e *Editor) AddContent(filename string, content []byte) (PublicationResource, error)
- func (e *Editor) AddContentFile(name string) (PublicationResource, error)
- func (e *Editor) AddDescription(description string) *Editor
- func (e *Editor) AddFile(filePath string, content []byte) *Editor
- func (e *Editor) AddIdentifier(id, value string) *Editor
- func (e *Editor) AddImage(name string, content []byte) (PublicationResource, error)
- func (e *Editor) AddImageFile(name string) (PublicationResource, error)
- func (e *Editor) AddLanguage(language string) *Editor
- func (e *Editor) AddMarkdown(filename string, content []byte) (PublicationResource, error)
- func (e *Editor) AddMarkdownFile(name string) (PublicationResource, error)
- func (e *Editor) AddPublisher(publisher string) *Editor
- func (e *Editor) AddResource(id, href, mimeType string, properties pkg.ManifestProperty, content []byte) (PublicationResource, error)
- func (e *Editor) AddSpineItem(idOrHref string) error
- func (e *Editor) AddSubject(subject string) *Editor
- func (e *Editor) AddTitle(title string) *Editor
- func (e *Editor) Author(authors ...string) *Editor
- func (e *Editor) Build() ([]byte, error)
- func (e *Editor) Contributor(kind string, contributors ...string) *Editor
- func (e *Editor) Cover(cover []byte) error
- func (e *Editor) CoverFile(name string) error
- func (e *Editor) CoverJPG(cover image.Image) error
- func (e *Editor) CoverPNG(cover image.Image) error
- func (e *Editor) Creator(id string, creators ...string) *Editor
- func (e *Editor) CurrentPackage() *pkg.Package
- func (e *Editor) CurrentPackagePath() string
- func (e *Editor) Date(date time.Time) *Editor
- func (e *Editor) Description(descriptions ...string) *Editor
- func (e *Editor) Direction(dir string) *Editor
- func (e *Editor) DublinCore(localName, value string) *Editor
- func (e *Editor) Identifier(identifiers ...string) *Editor
- func (e *Editor) Language(languages ...string) *Editor
- func (e *Editor) ListRenditions() []string
- func (e *Editor) Meta(meta pkg.Meta) *Editor
- func (e *Editor) MetaContent(keyVal map[string]string) *Editor
- func (e *Editor) MetaProperty(id, property, value string) *Editor
- func (e *Editor) Modified(date time.Time) *Editor
- func (e *Editor) Package() *pkg.Package
- func (e *Editor) Publisher(publishers ...string) *Editor
- func (e *Editor) Reader() (Reader, error)
- func (e *Editor) Refines(refines, property, value string, otherAttributes ...pkg.Meta) *Editor
- func (e *Editor) RemoveMeta(propertyOrName string) *Editor
- func (e *Editor) RemoveMetadata(xmlLocalName string) *Editor
- func (e *Editor) RemoveResource(idOrHref string) error
- func (e *Editor) RemoveSpineItem(idOrHref string) error
- func (e *Editor) Resources() []PublicationResource
- func (e *Editor) Rights(rights string) *Editor
- func (e *Editor) Save(writer io.Writer) error
- func (e *Editor) SaveAs(filename string) error
- func (e *Editor) SaveByte(b *[]byte) error
- func (e *Editor) SaveBytes() ([]byte, error)
- func (e *Editor) SelectPackageRendition(rendition string) error
- func (e *Editor) SelectResourceByHref(href string) *PublicationResource
- func (e *Editor) SelectResourceById(id string) *PublicationResource
- func (e *Editor) SetMeta(property, value string) *Editor
- func (e *Editor) Subject(subjects ...string) *Editor
- func (e *Editor) TableOfContents(name string, toc TOC) error
- func (e *Editor) Title(titles ...string) *Editor
- func (e *Editor) UniqueIdentifier(id string) *Editor
- func (e *Editor) UpdateContent(idOrHref string, content []byte) error
- func (e *Editor) UpdateResource(idOrHref string, content []byte) error
- func (e *Editor) Version(v string) *Editor
- func (e *Editor) WriteBytes(b *[]byte) error
- type Epub
- type Landmark
- type PublicationResource
- type Reader
- func (r *Reader) Author() []string
- func (r *Reader) ContentDocumentMarkdown() (documents map[string]string)
- func (r *Reader) ContentDocumentSVG() (documents map[string]*html.Node)
- func (r *Reader) ContentDocumentXHTML() (documents map[string]*html.Node)
- func (r *Reader) ContentDocumentXHTMLString() (documents map[string]string)
- func (r *Reader) Cover() (cover *image.Image)
- func (r *Reader) CoverBytes() (cover []byte, err error)
- func (r *Reader) CurrentSelectedPackage() *pkg.Package
- func (r *Reader) CurrentSelectedPackagePath() string
- func (r *Reader) Description() []string
- func (r *Reader) Edit() (*Editor, error)
- func (r *Reader) Identifier() []string
- func (r *Reader) ImageResources() (images map[string][]byte)
- func (r *Reader) Images() (images map[string]image.Image)
- func (r *Reader) Landmarks() []Landmark
- func (r *Reader) Language() []string
- func (r *Reader) ListContentDocumentIds() (ids []string)
- func (r *Reader) ListImageIds() (ids []string)
- func (r *Reader) ListRenditions() []string
- func (r *Reader) Metadata() (metadata map[string]any)
- func (r *Reader) NavigationCenterExtended() *ncx.NCX
- func (r *Reader) PageList() []Landmark
- func (r *Reader) ReadContentHTMLByHref(href string) (doc *html.Node)
- func (r *Reader) ReadContentHTMLById(id string) (doc *html.Node)
- func (r *Reader) ReadContentMarkdownByHref(href string) (md string)
- func (r *Reader) ReadContentMarkdownById(id string) (md string)
- func (r *Reader) ReadImageByHref(href string) (img *image.Image)
- func (r *Reader) ReadImageById(id string) (img *image.Image)
- func (r *Reader) ReadImageBytesByHref(href string) []byte
- func (r *Reader) ReadImageBytesById(id string) []byte
- func (r *Reader) References() (references map[pkg.GuideReferenceType]*html.Node)
- func (r *Reader) Refines() (refines map[string]map[string][]string)
- func (r *Reader) Resources() (resources []PublicationResource)
- func (r *Reader) SelectPackageRendition(rendition string)
- func (r *Reader) SelectResourceByHref(href string) (resource *PublicationResource)
- func (r *Reader) SelectResourceById(id string) (resource *PublicationResource)
- func (r *Reader) Spine() (orderedResources []PublicationResource)
- func (r *Reader) TableOfContents() (toc TOC, err error)
- func (r *Reader) Title() []string
- func (r *Reader) UID() (identifier string)
- func (r *Reader) Version() (version string)
- type TOC
- type Writer
- func (w *Writer) AddContent(filename string, content []byte) (res PublicationResource)
- func (w *Writer) AddContentFile(name string) (res PublicationResource, err error)
- func (w *Writer) AddGuide(kind pkg.GuideReferenceType, href string, title string)
- func (w *Writer) AddImage(name string, content []byte) (res PublicationResource)
- func (w *Writer) AddImageFile(name string) (res PublicationResource)
- func (w *Writer) AddMarkdown(filename string, content []byte) (PublicationResource, error)
- func (w *Writer) AddMarkdownDirectory(dir string) error
- func (w *Writer) AddMarkdownFile(name string) (PublicationResource, error)
- func (w *Writer) AddSpineItem(res PublicationResource)
- func (w *Writer) Author(creator ...string)
- func (w *Writer) Build() ([]byte, error)
- func (w *Writer) Contributor(kind string, contributor ...string)
- func (w *Writer) Cover(cover []byte) (err error)
- func (w *Writer) CoverFile(name string) error
- func (w *Writer) CoverJPG(cover image.Image) (err error)
- func (w *Writer) CoverPNG(cover image.Image) (err error)
- func (w *Writer) Creator(id string, creator ...string)
- func (w *Writer) Date(date time.Time)
- func (w *Writer) Description(description ...string)
- func (w *Writer) Direction(dir string)
- func (w *Writer) DublinCores(keyVal map[string]string)
- func (w *Writer) Identifiers(identifier ...string)
- func (w *Writer) Languages(language ...string)
- func (w *Writer) LongDescription(description string)
- func (w *Writer) Meta(meta pkg.Meta)
- func (w *Writer) MetaContent(keyVal map[string]string)
- func (w *Writer) MetaProperty(id string, property string, value string)
- func (w *Writer) Modified(date time.Time)
- func (w *Writer) Publisher(publisher ...string)
- func (w *Writer) Refines(refines string, property string, value string, otherAttributes ...pkg.Meta)
- func (w *Writer) Rights(rights string)
- func (w *Writer) SetContentDir(dir string)
- func (w *Writer) SetImageDir(dir string)
- func (w *Writer) SetTextDir(dir string)
- func (w *Writer) Subject(id string, subject ...string)
- func (w *Writer) TableOfContents(name string, toc TOC) (err error)
- func (w *Writer) Title(title ...string)
- func (w *Writer) Write(filename string) (err error)
- func (w *Writer) WriteBytes() ([]byte, error)
Examples ¶
- Package
- Package (BookPipeline)
- Package (EpubToMarkdown)
- Package (EpubToText)
- Package (ReproduceStandardEbook)
- Package (RoundTrip)
- Editor
- Editor.AddMarkdown
- Editor.Reader
- Editor.Save
- Editor.SaveAs
- Editor.WriteBytes
- New
- NewReader
- OpenReader
- Reader
- Reader.Author
- Reader.ContentDocumentMarkdown
- Reader.Cover
- Reader.Description
- Reader.Edit
- Reader.Identifier
- Reader.Landmarks
- Reader.Language
- Reader.ListContentDocumentIds
- Reader.Metadata
- Reader.PageList
- Reader.ReadContentHTMLById
- Reader.ReadContentMarkdownById
- Reader.References
- Reader.Resources
- Reader.SelectPackageRendition
- Reader.Spine
- Reader.TableOfContents
- Reader.Title
- Reader.Version
- TOC
- TOC.JSON
- Writer
- Writer.AddContent
- Writer.AddContentFile
- Writer.AddGuide
- Writer.AddImage
- Writer.AddMarkdown
- Writer.AddMarkdownDirectory
- Writer.AddMarkdownFile
- Writer.Author
- Writer.Contributor
- Writer.Cover
- Writer.CoverPNG
- Writer.Creator
- Writer.Date
- Writer.Description
- Writer.DublinCores
- Writer.Identifiers
- Writer.Languages
- Writer.Meta
- Writer.Publisher
- Writer.Rights
- Writer.Subject
- Writer.TableOfContents
- Writer.Title
- Writer.WriteBytes
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func FindNode ¶ added in v0.4.0
FindNode traverses the HTML tree recursively and returns the first node that satisfies the predicate.
func GetTextContent ¶ added in v0.4.0
GetTextContent extracts and concatenates all text content within an HTML node recursively.
Types ¶
type Editor ¶ added in v0.5.0
type Editor struct {
// contains filtered or unexported fields
}
Editor provides an interface for mutating and updating an existing EPUB publication, including its metadata, resources, spine reading order, and table of contents, and saving the edited publication back to disk, an io.Writer, or a byte buffer.
Example ¶
ExampleEditor demonstrates loading an existing EPUB publication, editing its metadata using fluent method chaining, appending new content, and saving the result.
// Start with an existing publication
r, err := epub.NewReader(buildSampleBook())
if err != nil {
panic(err)
}
// Switch from Reader to Editor mode
editor, err := r.Edit()
if err != nil {
panic(err)
}
// Chain metadata modifications
editor.Title("The Sample Book (Second Edition)").
Author("Jane Doe", "John Smith").
Subject("Software Engineering", "Go").
Publisher("Tech Publishing").
Language("en")
// Append a new chapter
if _, err := editor.AddContent("chapter-3.xhtml", sampleChapter("Chapter 3")); err != nil {
panic(err)
}
// Switch back to Reader mode in memory to verify
updatedReader, err := editor.Reader()
if err != nil {
panic(err)
}
fmt.Println(strings.Join(updatedReader.Title(), ", "))
fmt.Println(strings.Join(updatedReader.Author(), ", "))
fmt.Println("Total Spine Items:", len(updatedReader.Spine()))
Output: The Sample Book (Second Edition) Jane Doe, John Smith Total Spine Items: 3
func (*Editor) AddAuthor ¶ added in v0.5.0
AddAuthor appends an additional author/creator to the metadata.
func (*Editor) AddContent ¶ added in v0.5.0
func (e *Editor) AddContent(filename string, content []byte) (PublicationResource, error)
AddContent adds a content document (e.g. XHTML) to the publication manifest, spine, and container.
func (*Editor) AddContentFile ¶ added in v0.5.0
func (e *Editor) AddContentFile(name string) (PublicationResource, error)
AddContentFile adds a content document by reading it from the local filesystem.
func (*Editor) AddDescription ¶ added in v0.5.0
AddDescription appends a description to the metadata.
func (*Editor) AddFile ¶ added in v0.5.0
AddFile directly adds or updates any arbitrary file path inside the container.
func (*Editor) AddIdentifier ¶ added in v0.5.0
AddIdentifier appends an identifier to the package metadata.
func (*Editor) AddImage ¶ added in v0.5.0
func (e *Editor) AddImage(name string, content []byte) (PublicationResource, error)
AddImage adds an image resource to the publication manifest and container.
func (*Editor) AddImageFile ¶ added in v0.5.0
func (e *Editor) AddImageFile(name string) (PublicationResource, error)
AddImageFile adds an image resource by reading it from the local filesystem.
func (*Editor) AddLanguage ¶ added in v0.5.0
AddLanguage appends a language code to the publication metadata.
func (*Editor) AddMarkdown ¶ added in v0.5.1
func (e *Editor) AddMarkdown(filename string, content []byte) (PublicationResource, error)
AddMarkdown converts content from Markdown to compliant XHTML and adds it to the publication as a spine content document. The file extension is automatically converted to .xhtml.
Example ¶
ExampleEditor_AddMarkdown demonstrates appending a Markdown chapter directly to an existing EPUB.
r, _ := epub.NewReader(buildSampleBook())
editor, _ := r.Edit()
// Append Markdown content
md := `# Appendix
This appendix was appended in Markdown!
- Item 1
- Item 2
`
res, err := editor.AddMarkdown("appendix.md", []byte(md))
if err != nil {
panic(err)
}
updatedReader, _ := editor.Reader()
fmt.Println("New resource href:", res.Href)
fmt.Println("Total spine items:", len(updatedReader.Spine()))
Output: New resource href: appendix.xhtml Total spine items: 3
func (*Editor) AddMarkdownFile ¶ added in v0.5.1
func (e *Editor) AddMarkdownFile(name string) (PublicationResource, error)
AddMarkdownFile reads the Markdown file at name from disk, converts it to compliant XHTML, and adds it to the publication as a spine content document.
func (*Editor) AddPublisher ¶ added in v0.5.0
AddPublisher appends a publisher to the metadata.
func (*Editor) AddResource ¶ added in v0.5.0
func (e *Editor) AddResource(id, href, mimeType string, properties pkg.ManifestProperty, content []byte) (PublicationResource, error)
AddResource adds a resource to the publication manifest and container.
func (*Editor) AddSpineItem ¶ added in v0.5.0
AddSpineItem appends a manifest item to the spine reading order.
func (*Editor) AddSubject ¶ added in v0.5.0
AddSubject appends a subject to the metadata.
func (*Editor) AddTitle ¶ added in v0.5.0
AddTitle appends an additional title entry to the metadata.
func (*Editor) Build ¶ added in v0.5.0
Build serializes the modified publication package(s) and creates an in-memory EPUB zip archive.
func (*Editor) Contributor ¶ added in v0.5.0
Contributor adds a contributor entry of the specified role or type.
func (*Editor) CoverFile ¶ added in v0.5.0
CoverFile sets the cover image by reading from a file path.
func (*Editor) CoverJPG ¶ added in v0.5.0
CoverJPG sets the cover image from an image.Image encoded as JPEG.
func (*Editor) CoverPNG ¶ added in v0.5.0
CoverPNG sets the cover image from an image.Image encoded as PNG.
func (*Editor) Creator ¶ added in v0.5.0
Creator adds a creator with a specific identifier attribute to the metadata.
func (*Editor) CurrentPackage ¶ added in v0.5.0
CurrentPackage returns the active package publication.
func (*Editor) CurrentPackagePath ¶ added in v0.5.0
CurrentPackagePath returns the container file path of the active package document.
func (*Editor) Description ¶ added in v0.5.0
Description sets (replaces) the publication description(s).
func (*Editor) DublinCore ¶ added in v0.5.0
DublinCore adds an arbitrary Dublin Core element to the metadata.
func (*Editor) Identifier ¶ added in v0.5.0
Identifier sets (replaces) the publication identifiers.
func (*Editor) ListRenditions ¶ added in v0.5.0
ListRenditions returns the identifiers of all package renditions available.
func (*Editor) MetaContent ¶ added in v0.5.0
MetaContent adds metadata key/value entries that do not require refinements.
func (*Editor) MetaProperty ¶ added in v0.5.0
MetaProperty adds a property-based metadata refinement entry.
func (*Editor) Modified ¶ added in v0.5.0
Modified sets the last modification date (dcterms:modified) metadata.
func (*Editor) Package ¶ added in v0.5.0
Package returns the currently active package document for direct inspection or modification.
func (*Editor) Reader ¶ added in v0.5.0
Reader finalizes all pending edits and converts the publication back into a Reader instance.
Example ¶
ExampleEditor_Reader demonstrates switching back to Reader mode after performing edits.
w := epub.New("urn:example:reader-mode")
w.Title("Draft Book")
w.Author("Jane Doe")
w.Languages("en")
w.AddContent("ch1.xhtml", sampleChapter("Chapter 1"))
if err := w.TableOfContents("toc", epub.TOC{
Title: "Contents",
Items: []epub.TOC{{Title: "Chapter 1", Href: "ch1.xhtml"}},
}); err != nil {
panic(err)
}
data, _ := w.WriteBytes()
book, _ := epub.NewReader(data)
// Enter edit mode
editor, err := book.Edit()
if err != nil {
panic(err)
}
editor.Title("Final Published Book").
Author("Jane Doe, PhD")
// Switch back to reader mode without saving to a separate file first
readerBack, err := editor.Reader()
if err != nil {
panic(err)
}
fmt.Println(strings.Join(readerBack.Title(), ", "))
fmt.Println(strings.Join(readerBack.Author(), ", "))
Output: Final Published Book Jane Doe, PhD
func (*Editor) Refines ¶ added in v0.5.0
Refines applies a metadata refinement to an existing metadata item.
func (*Editor) RemoveMeta ¶ added in v0.5.0
RemoveMeta removes meta elements whose Property or Name matches propertyOrName.
func (*Editor) RemoveMetadata ¶ added in v0.5.0
RemoveMetadata removes optional Dublin Core elements matching the given XML local name.
func (*Editor) RemoveResource ¶ added in v0.5.0
RemoveResource removes a resource from the manifest, spine (if referenced), and container.
func (*Editor) RemoveSpineItem ¶ added in v0.5.0
RemoveSpineItem removes an item from the spine reading order without removing the resource.
func (*Editor) Resources ¶ added in v0.5.0
func (e *Editor) Resources() []PublicationResource
Resources returns all publication resources declared in the manifest.
func (*Editor) Save ¶ added in v0.5.0
Save writes the edited EPUB archive to an io.Writer.
Example ¶
ExampleEditor_Save demonstrates saving an edited publication to an io.Writer.
w := epub.New("urn:example:stream")
w.Title("Original Book")
w.Author("Jane Doe")
w.Languages("en")
w.AddContent("ch1.xhtml", sampleChapter("Chapter 1"))
if err := w.TableOfContents("toc", epub.TOC{
Title: "Contents",
Items: []epub.TOC{{Title: "Chapter 1", Href: "ch1.xhtml"}},
}); err != nil {
panic(err)
}
data, _ := w.WriteBytes()
reader, _ := epub.NewReader(data)
editor, err := reader.Edit()
if err != nil {
panic(err)
}
// Update title and add a second chapter
editor.Title("Expanded Edition")
if _, err := editor.AddContent("ch2.xhtml", sampleChapter("Chapter 2")); err != nil {
panic(err)
}
var buf bytes.Buffer
if err := editor.Save(&buf); err != nil {
panic(err)
}
editedReader, _ := epub.NewReader(buf.Bytes())
fmt.Println(strings.Join(editedReader.Title(), ", "))
fmt.Println("Spine items count:", len(editedReader.Spine()))
Output: Expanded Edition Spine items count: 2
func (*Editor) SaveAs ¶ added in v0.5.0
SaveAs writes the edited EPUB archive to the specified file on disk.
Example ¶
ExampleEditor_SaveAs demonstrates reading an existing EPUB, modifying its description and subject tags, and saving the result directly to disk.
tempDir, err := os.MkdirTemp("", "epub_example")
if err != nil {
panic(err)
}
defer os.RemoveAll(tempDir)
origPath := filepath.Join(tempDir, "original.epub")
w := epub.New("urn:example:saveas")
w.Title("File-backed Book")
w.Author("Jane Doe")
w.Languages("en")
w.AddContent("ch1.xhtml", sampleChapter("Chapter 1"))
if err := w.TableOfContents("toc", epub.TOC{
Title: "Contents",
Items: []epub.TOC{{Title: "Chapter 1", Href: "ch1.xhtml"}},
}); err != nil {
panic(err)
}
if err := w.Write(origPath); err != nil {
panic(err)
}
// Open with OpenReader
reader, err := epub.OpenReader(origPath)
if err != nil {
panic(err)
}
editor, err := reader.Edit()
if err != nil {
panic(err)
}
editor.Title("Updated File-backed Book").
Description("A book edited and saved with SaveAs")
savedPath := filepath.Join(tempDir, "updated.epub")
if err := editor.SaveAs(savedPath); err != nil {
panic(err)
}
updatedReader, err := epub.OpenReader(savedPath)
if err != nil {
panic(err)
}
fmt.Println(strings.Join(updatedReader.Title(), ", "))
Output: Updated File-backed Book
func (*Editor) SaveByte ¶ added in v0.5.0
SaveByte is an alias for WriteBytes for backwards compatibility.
func (*Editor) SaveBytes ¶ added in v0.5.0
SaveBytes returns the edited EPUB archive as a byte slice.
func (*Editor) SelectPackageRendition ¶ added in v0.5.0
SelectPackageRendition switches the active package rendition.
func (*Editor) SelectResourceByHref ¶ added in v0.5.0
func (e *Editor) SelectResourceByHref(href string) *PublicationResource
SelectResourceByHref retrieves a publication resource by its manifest Href.
func (*Editor) SelectResourceById ¶ added in v0.5.0
func (e *Editor) SelectResourceById(id string) *PublicationResource
SelectResourceById retrieves a publication resource by its manifest ID.
func (*Editor) SetMeta ¶ added in v0.5.0
SetMeta sets or updates a meta element matching the specified property.
func (*Editor) TableOfContents ¶ added in v0.5.0
TableOfContents generates and updates the EPUB navigation document (XHTML) and legacy NCX.
func (*Editor) UniqueIdentifier ¶ added in v0.5.0
UniqueIdentifier sets the package unique-identifier attribute.
func (*Editor) UpdateContent ¶ added in v0.5.0
UpdateContent updates the byte content of an existing content document identified by ID or Href.
func (*Editor) UpdateResource ¶ added in v0.5.0
UpdateResource updates the byte content of an existing resource identified by ID or Href.
func (*Editor) Version ¶ added in v0.5.0
Version sets the EPUB publication version (e.g. "3.0" or "2.0").
func (*Editor) WriteBytes ¶ added in v0.5.0
WriteBytes writes the edited EPUB bytes into the byte slice pointed to by b.
Example ¶
ExampleEditor_WriteBytes demonstrates writing edited EPUB bytes into an existing buffer pointer.
r, _ := epub.NewReader(buildSampleBook())
editor, _ := r.Edit()
editor.Title("Buffer Output Edition")
var output []byte
if err := editor.WriteBytes(&output); err != nil {
panic(err)
}
updatedReader, _ := epub.NewReader(output)
fmt.Println(strings.Join(updatedReader.Title(), ", "))
Output: Buffer Output Edition
type Epub ¶
type Epub struct {
// contains filtered or unexported fields
}
Epub represents a full EPUB publication, including metadata, package information, resources, and navigation.
func (*Epub) DefaultPackage ¶ added in v0.2.0
DefaultPackage returns the package document registered under the conventional "content" key.
func (*Epub) SelectPackage ¶ added in v0.2.0
SelectPackage returns the package document registered under the given name, or nil if no such package exists. Use Reader.SelectPackageRendition to switch the active package instead.
func (*Epub) SelectedPackage ¶ added in v0.2.0
SelectedPackage returns the currently active package document.
type Landmark ¶ added in v0.4.0
type Landmark struct {
Title string `json:"title,omitempty"`
Href string `json:"href,omitempty"`
Type string `json:"type,omitempty"`
}
Landmark represents an entry in the landmarks navigation of the EPUB navigation document. The Type field holds the epub:type semantic applied to the landmark (e.g., "cover", "bodymatter", "toc").
type PublicationResource ¶
type PublicationResource struct {
ID string
Href string
MIMEType string
Content []byte
Filepath string
Properties pkg.ManifestProperty
}
PublicationResource represents a single resource inside the EPUB container. Resources may include XHTML documents, images, stylesheets, SVG files, and auxiliary data referenced by the publication manifest.
type Reader ¶
type Reader struct {
// contains filtered or unexported fields
}
Reader provides an interface for reading and accessing EPUB publication data. It offers methods for retrieving metadata, navigation structures, content documents, resources, and images.
Example ¶
ExampleReader demonstrates inspecting metadata, spine reading order, and table of contents from an opened EPUB publication.
book, err := epub.NewReader(buildSampleBook())
if err != nil {
panic(err)
}
fmt.Println("Title:", strings.Join(book.Title(), ", "))
fmt.Println("Author:", strings.Join(book.Author(), ", "))
fmt.Println("Language:", strings.Join(book.Language(), ", "))
fmt.Println("Spine Items:", len(book.Spine()))
toc, err := book.TableOfContents()
if err != nil {
panic(err)
}
fmt.Println("TOC Entries:", len(toc.Items))
Output: Title: The Sample Book Author: Jane Doe Language: en Spine Items: 2 TOC Entries: 2
func NewReader ¶
NewReader creates a new Reader instance from a raw EPUB byte slice. The byte slice must represent a valid EPUB container.
Example ¶
ExampleNewReader demonstrates reading an EPUB from an in-memory byte slice.
book, err := epub.NewReader(buildSampleBook())
if err != nil {
panic(err)
}
fmt.Println(strings.Join(book.Title(), ", "))
fmt.Println(book.UID())
Output: The Sample Book urn:example:sample
func OpenReader ¶
OpenReader opens an EPUB file from the provided file path and returns a Reader instance. The file must exist and be a valid EPUB container.
Example ¶
ExampleOpenReader demonstrates opening an EPUB file from disk.
package main
import (
"fmt"
"strings"
"github.com/raitucarp/epub"
)
func main() {
book, err := epub.OpenReader("book.epub")
if err != nil {
panic(err)
}
fmt.Println(strings.Join(book.Title(), ", "))
fmt.Println(book.Version())
}
Output:
func (*Reader) Author ¶
Author returns the author (creator) metadata of the publication.
Example ¶
ExampleReader_Author demonstrates reading the creator metadata.
book, err := epub.NewReader(buildSampleBook())
if err != nil {
panic(err)
}
fmt.Println(strings.Join(book.Author(), ", "))
Output: Jane Doe
func (*Reader) ContentDocumentMarkdown ¶
ContentDocumentMarkdown returns content documents converted into Markdown form. The returned map is keyed by EPUB manifest item ID.
Example ¶
ExampleReader_ContentDocumentMarkdown demonstrates converting every content document to Markdown at once.
book, err := epub.NewReader(buildSampleBook())
if err != nil {
panic(err)
}
for id, markdown := range book.ContentDocumentMarkdown() {
fmt.Printf("== %s ==\n%s\n", id, markdown)
}
func (*Reader) ContentDocumentSVG ¶
ContentDocumentSVG returns SVG content documents parsed into html.Node trees. The returned map is keyed by EPUB manifest item ID.
func (*Reader) ContentDocumentXHTML ¶
ContentDocumentXHTML returns XHTML content documents parsed into html.Node trees. The returned map is keyed by EPUB manifest item ID.
func (*Reader) ContentDocumentXHTMLString ¶
ContentDocumentXHTMLString returns XHTML content documents as raw strings. The returned map is keyed by EPUB manifest item ID.
func (*Reader) Cover ¶
Cover returns the publication's cover image if present.
Example ¶
ExampleReader_Cover demonstrates extracting the cover image.
package main
import (
"fmt"
"github.com/raitucarp/epub"
)
func main() {
book, err := epub.OpenReader("book.epub")
if err != nil {
panic(err)
}
cover := book.Cover()
if cover == nil {
fmt.Println("no cover")
return
}
fmt.Println("cover bounds:", (*cover).Bounds())
}
Output:
func (*Reader) CoverBytes ¶ added in v0.2.0
CoverBytes returns the raw byte representation of the cover image. An error is returned if the publication does not define a cover.
func (*Reader) CurrentSelectedPackage ¶
CurrentSelectedPackage returns the currently active package rendition. EPUB publications may have multiple renditions.
func (*Reader) CurrentSelectedPackagePath ¶
CurrentSelectedPackagePath returns the internal path to the currently selected package document.
func (*Reader) Description ¶
Description returns the publication's description metadata if defined.
Example ¶
ExampleReader_Description demonstrates reading the publication description.
package main
import (
"fmt"
"strings"
"github.com/raitucarp/epub"
)
func main() {
book, err := epub.OpenReader("book.epub")
if err != nil {
panic(err)
}
fmt.Println(strings.Join(book.Description(), "\n"))
}
Output:
func (*Reader) Edit ¶ added in v0.5.0
Edit creates an Editor instance from this Reader, allowing modification of metadata, resources, spine order, and content before writing back to disk or memory.
Example ¶
ExampleReader_Edit demonstrates how to read an existing EPUB publication, edit its metadata using concise chained methods, and save the result to a byte slice.
// 1. Create a base publication in memory
w := epub.New("urn:example:orig")
w.Title("Original Title")
w.Author("Original Author")
w.Languages("en")
w.AddContent("ch1.xhtml", sampleChapter("Chapter 1"))
if err := w.TableOfContents("toc", epub.TOC{
Title: "Contents",
Items: []epub.TOC{{Title: "Chapter 1", Href: "ch1.xhtml"}},
}); err != nil {
panic(err)
}
data, err := w.WriteBytes()
if err != nil {
panic(err)
}
// 2. Open the publication using Reader
reader, err := epub.NewReader(data)
if err != nil {
panic(err)
}
// 3. Obtain an Editor instance
editor, err := reader.Edit()
if err != nil {
panic(err)
}
// 4. Modify metadata concisely
editor.Title("Updated Title").
Author("Updated Author").
Language("id")
// 5. Write the modified EPUB into a byte pointer
var editedBytes []byte
if err := editor.WriteBytes(&editedBytes); err != nil {
panic(err)
}
// 6. Read back the modified EPUB to verify changes
editedReader, err := epub.NewReader(editedBytes)
if err != nil {
panic(err)
}
fmt.Println(strings.Join(editedReader.Title(), ", "))
fmt.Println(strings.Join(editedReader.Author(), ", "))
fmt.Println(strings.Join(editedReader.Language(), ", "))
Output: Updated Title Updated Author id
func (*Reader) Identifier ¶ added in v0.2.0
Identifier returns the primary identifier of the publication as declared in the package metadata (often equivalent to UID).
Example ¶
ExampleReader_Identifier demonstrates reading identifiers and resolving the unique identifier.
book, err := epub.NewReader(buildSampleBook())
if err != nil {
panic(err)
}
fmt.Println("Identifiers:", book.Identifier())
fmt.Println("Unique:", book.UID())
Output: Identifiers: [urn:example:sample] Unique: urn:example:sample
func (*Reader) ImageResources ¶ added in v0.2.0
ImageResources returns all image resources in byte form, keyed by manifest ID. Useful when direct decoding to image.Image is not required.
func (*Reader) Images ¶
Images returns all image resources in the publication, keyed by manifest ID.
func (*Reader) Landmarks ¶ added in v0.4.0
Landmarks returns the landmarks navigation, which identifies the key structural points of the publication (e.g., cover, table of contents, and body matter).
Example ¶
ExampleReader_Landmarks demonstrates reading the landmarks navigation.
package main
import (
"fmt"
"github.com/raitucarp/epub"
)
func main() {
book, err := epub.OpenReader("book.epub")
if err != nil {
panic(err)
}
for _, landmark := range book.Landmarks() {
fmt.Printf("%s: %s\n", landmark.Type, landmark.Href)
}
}
Output:
func (*Reader) Language ¶ added in v0.2.0
Language returns the primary language of the publication, as declared in the package metadata (dc:language).
Example ¶
ExampleReader_Language demonstrates reading the publication languages.
book, err := epub.NewReader(buildSampleBook())
if err != nil {
panic(err)
}
fmt.Println(book.Language())
Output: [en]
func (*Reader) ListContentDocumentIds ¶ added in v0.1.2
ListContentDocumentIds returns the IDs of all content documents (XHTML/SVG) registered in the publication manifest.
Example ¶
ExampleReader_ListContentDocumentIds demonstrates listing the manifest IDs of all content documents.
book, err := epub.NewReader(buildSampleBook())
if err != nil {
panic(err)
}
for _, id := range book.ListContentDocumentIds() {
fmt.Println(id)
}
func (*Reader) ListImageIds ¶ added in v0.1.2
ListImageIds returns the IDs of all image-based resources (e.g., PNG, JPEG, SVG) in the publication manifest.
func (*Reader) ListRenditions ¶ added in v0.4.0
ListRenditions returns the identifiers of all package renditions available in the publication. The first rendition is always named "default".
func (*Reader) Metadata ¶
Metadata returns the complete metadata block of the publication. The returned map may include standard as well as extended metadata fields.
Example ¶
ExampleReader_Metadata demonstrates reading the full metadata block and the metadata refinements in one pass.
book, err := epub.NewReader(buildSampleBook())
if err != nil {
panic(err)
}
for key, value := range book.Metadata() {
fmt.Printf("%s: %v\n", key, value)
}
func (*Reader) NavigationCenterExtended ¶
NavigationCenterExtended returns the NCX navigation document (if available). This is primarily used for EPUB 2.x backward compatibility.
func (*Reader) PageList ¶ added in v0.4.0
PageList returns the page-list navigation, which maps the print page breakpoints of the publication to their content locations.
Example ¶
ExampleReader_PageList demonstrates reading the page-list navigation.
package main
import (
"fmt"
"github.com/raitucarp/epub"
)
func main() {
book, err := epub.OpenReader("book.epub")
if err != nil {
panic(err)
}
for _, page := range book.PageList() {
fmt.Printf("%s -> %s\n", page.Title, page.Href)
}
}
Output:
func (*Reader) ReadContentHTMLByHref ¶ added in v0.1.3
ReadContentHTMLByHref returns the content document associated with the given manifest href. The returned document is parsed into an html.Node tree.
func (*Reader) ReadContentHTMLById ¶
ReadContentHTMLById returns the XHTML/HTML content document associated with the given manifest ID, parsed into an html.Node tree.
Example ¶
ExampleReader_ReadContentHTMLById demonstrates reading a content document as a parsed HTML node and extracting its text.
book, err := epub.NewReader(buildSampleBook())
if err != nil {
panic(err)
}
node := book.ReadContentHTMLById("chapter-1.xhtml")
fmt.Println(epub.GetTextContent(node))
func (*Reader) ReadContentMarkdownByHref ¶ added in v0.4.0
ReadContentMarkdownByHref returns a Markdown string representation of the content document associated with the given manifest href.
func (*Reader) ReadContentMarkdownById ¶ added in v0.1.1
ReadContentMarkdownById returns a Markdown string representation of the content document associated with the given manifest ID.
Example ¶
ExampleReader_ReadContentMarkdownById demonstrates reading a content document converted to Markdown.
book, err := epub.NewReader(buildSampleBook())
if err != nil {
panic(err)
}
fmt.Println(book.ReadContentMarkdownById("chapter-1.xhtml"))
func (*Reader) ReadImageByHref ¶
ReadImageByHref returns the image resource referenced by the given href, if present in the manifest.
func (*Reader) ReadImageById ¶
ReadImageById returns the image resource associated with the given manifest ID.
func (*Reader) ReadImageBytesByHref ¶ added in v0.4.0
ReadImageBytesByHref returns the raw bytes of the image resource referenced by the given href, if present in the manifest.
func (*Reader) ReadImageBytesById ¶ added in v0.4.0
ReadImageBytesById returns the raw bytes of the image resource associated with the given manifest ID.
func (*Reader) References ¶ added in v0.2.1
func (r *Reader) References() (references map[pkg.GuideReferenceType]*html.Node)
References returns the structural guide references defined in the package, such as "cover", "title-page", "toc", etc. The returned map is keyed by reference type and mapped to corresponding HTML content.
Example ¶
ExampleReader_References demonstrates reading the structural guide references.
package main
import (
"fmt"
"github.com/raitucarp/epub"
)
func main() {
book, err := epub.OpenReader("book.epub")
if err != nil {
panic(err)
}
for kind, node := range book.References() {
fmt.Printf("%s: %v\n", kind, node != nil)
}
}
Output:
func (*Reader) Refines ¶
Refines returns metadata refinement relationships. The returned map is keyed by subject identifier, mapping to properties and their assigned values.
func (*Reader) Resources ¶
func (r *Reader) Resources() (resources []PublicationResource)
Resources returns all publication resources declared in the manifest.
Example ¶
ExampleReader_Resources demonstrates iterating resources and selecting them by manifest ID and href.
book, err := epub.NewReader(buildSampleBook())
if err != nil {
panic(err)
}
for _, res := range book.Resources() {
fmt.Printf("%s (%s)\n", res.ID, res.MIMEType)
}
if res := book.SelectResourceByHref("chapter-1.xhtml"); res != nil {
fmt.Println("selected:", res.ID)
}
func (*Reader) SelectPackageRendition ¶
SelectPackageRendition changes the active package rendition by its rendition identifier. Useful when multiple reading layouts are available.
Example ¶
ExampleReader_SelectPackageRendition demonstrates switching between package renditions in a publication that ships multiple layouts.
package main
import (
"fmt"
"github.com/raitucarp/epub"
)
func main() {
book, err := epub.OpenReader("book.epub")
if err != nil {
panic(err)
}
for _, rendition := range book.ListRenditions() {
fmt.Println(rendition)
}
book.SelectPackageRendition("default")
fmt.Println("Active package:", book.CurrentSelectedPackagePath())
}
Output:
func (*Reader) SelectResourceByHref ¶
func (r *Reader) SelectResourceByHref(href string) (resource *PublicationResource)
SelectResourceByHref retrieves a resource referenced by its manifest href.
func (*Reader) SelectResourceById ¶
func (r *Reader) SelectResourceById(id string) (resource *PublicationResource)
SelectResourceById retrieves a resource referenced by its manifest ID.
func (*Reader) Spine ¶
func (r *Reader) Spine() (orderedResources []PublicationResource)
Spine returns the publication's spine, an ordered list of resources that defines the default reading order.
Example ¶
ExampleReader_Spine demonstrates reading the default reading order.
book, err := epub.NewReader(buildSampleBook())
if err != nil {
panic(err)
}
for _, res := range book.Spine() {
fmt.Println(res.Href)
}
Output: chapter-1.xhtml chapter-2.xhtml
func (*Reader) TableOfContents ¶
TableOfContents returns the TOC version present (e.g., NAV or NCX). If both exist, behavior depends on publication version and priority rules.
Example ¶
ExampleReader_TableOfContents demonstrates reading a nested table of contents.
book, err := epub.NewReader(buildSampleBook())
if err != nil {
panic(err)
}
toc, err := book.TableOfContents()
if err != nil {
panic(err)
}
fmt.Println(toc.Title)
for _, item := range toc.Items {
fmt.Printf("- %s -> %s\n", item.Title, item.Href)
}
Output: Table of Contents - Chapter 1 -> chapter-1.xhtml - Chapter 2 -> chapter-2.xhtml
func (*Reader) Title ¶
Title returns the publication's title metadata.
Example ¶
ExampleReader_Title demonstrates reading every title declared in the package metadata.
book, err := epub.NewReader(buildSampleBook())
if err != nil {
panic(err)
}
for i, title := range book.Title() {
fmt.Printf("%d. %s\n", i+1, title)
}
Output: 1. The Sample Book
func (*Reader) UID ¶
UID returns the unique identifier of the publication. It resolves the package's unique-identifier attribute to the matching dc:identifier entry.
type TOC ¶ added in v0.1.3
type TOC struct {
Title string `json:"title,omitempty"`
Href string `json:"href,omitempty"`
Items []TOC `json:"items,omitempty"`
// contains filtered or unexported fields
}
TOC represents the publication's table of contents in normalized form. The structure abstracts differences between NAV (EPUB 3) and NCX (EPUB 2) so higher-level code can work with a unified interface.
Example ¶
ExampleTOC demonstrates inspecting the hierarchical navigation structure of an EPUB.
book, err := epub.NewReader(buildSampleBook())
if err != nil {
panic(err)
}
toc, err := book.TableOfContents()
if err != nil {
panic(err)
}
fmt.Printf("%s (%d entries)\n", toc.Title, len(toc.Items))
for _, item := range toc.Items {
fmt.Printf(" • %s => %s\n", item.Title, item.Href)
}
Output: Table of Contents (2 entries) • Chapter 1 => chapter-1.xhtml • Chapter 2 => chapter-2.xhtml
func (*TOC) JSON ¶ added in v0.1.3
JSON marshals the table of contents structure into JSON format. This is useful for external tools, logging, debugging, or serialization to other formats.
Example ¶
ExampleTOC_JSON demonstrates serializing the table of contents to JSON.
book, err := epub.NewReader(buildSampleBook())
if err != nil {
panic(err)
}
toc, err := book.TableOfContents()
if err != nil {
panic(err)
}
data, err := toc.JSON()
if err != nil {
panic(err)
}
fmt.Println(string(data))
func (*TOC) ReadContentHTML ¶ added in v0.1.3
ReadContentHTML returns the content document associated with the currently selected table of contents entry. The returned document is parsed into an html.Node tree. Behavior depends on TOC internal navigation selection state.
type Writer ¶
type Writer struct {
// contains filtered or unexported fields
}
Writer provides an interface for constructing and writing EPUB publications to disk or memory.
Example ¶
ExampleWriter demonstrates creating an EPUB publication, adding chapters, configuring metadata and navigation, and producing the binary archive.
w := epub.New("urn:isbn:9780000000001")
w.Title("Adventures in Go")
w.Author("Jane Doe")
w.Languages("en")
w.Description("A complete guide to building software with Go.")
w.AddContent("chapter-1.xhtml", sampleChapter("Chapter 1: The Beginning"))
w.AddContent("chapter-2.xhtml", sampleChapter("Chapter 2: Concurrency"))
if err := w.TableOfContents("toc", epub.TOC{
Title: "Table of Contents",
Items: []epub.TOC{
{Title: "Chapter 1", Href: "chapter-1.xhtml"},
{Title: "Chapter 2", Href: "chapter-2.xhtml"},
},
}); err != nil {
panic(err)
}
data, err := w.WriteBytes()
if err != nil {
panic(err)
}
// Verify publication was generated
book, err := epub.NewReader(data)
if err != nil {
panic(err)
}
fmt.Println(strings.Join(book.Title(), ", "))
fmt.Println(strings.Join(book.Author(), ", "))
fmt.Println("Chapters in Spine:", len(book.Spine()))
Output: Adventures in Go Jane Doe Chapters in Spine: 2
func New ¶ added in v0.2.0
New creates a new Writer with the given publication identifier. The identifier is assigned to the package metadata (dc:identifier).
Example ¶
ExampleNew demonstrates creating a Writer with complete metadata and writing a minimal publication.
w := epub.New("urn:isbn:9780000000001")
w.Title("A Book")
w.Author("Jane Doe")
w.Languages("en")
w.Description("A short description")
w.Publisher("Example Press")
w.Rights("All rights reserved")
w.Date(time.Now())
w.Modified(time.Now())
w.AddContent("chapter-1.xhtml", sampleChapter("Chapter 1"))
if err := w.TableOfContents("toc", epub.TOC{
Items: []epub.TOC{{Title: "Chapter 1", Href: "chapter-1.xhtml"}},
}); err != nil {
panic(err)
}
if err := w.Write("book.epub"); err != nil {
panic(err)
}
func (*Writer) AddContent ¶ added in v0.2.0
func (w *Writer) AddContent(filename string, content []byte) (res PublicationResource)
AddContent adds a content file (such as XHTML or SVG) to the publication using the provided filename and raw bytes. Returns the created resource. The media type is inferred from the filename extension; unknown extensions default to XHTML.
Example ¶
ExampleWriter_AddContent demonstrates adding multiple chapter documents.
w := epub.New("urn:isbn:9780000000001")
w.Title("A Book")
w.Languages("en")
w.AddContent("chapter-1.xhtml", sampleChapter("Chapter 1"))
w.AddContent("chapter-2.xhtml", sampleChapter("Chapter 2"))
if err := w.TableOfContents("toc", epub.TOC{
Items: []epub.TOC{
{Title: "Chapter 1", Href: "chapter-1.xhtml"},
{Title: "Chapter 2", Href: "chapter-2.xhtml"},
},
}); err != nil {
panic(err)
}
if err := w.Write("book.epub"); err != nil {
panic(err)
}
func (*Writer) AddContentFile ¶ added in v0.2.0
func (w *Writer) AddContentFile(name string) (res PublicationResource, err error)
AddContentFile adds a content file to the publication by reading the file from disk. Returns the created resource and any file access error.
Example ¶
ExampleWriter_AddContentFile demonstrates adding a content document read from disk.
package main
import (
"github.com/raitucarp/epub"
)
func main() {
w := epub.New("urn:isbn:9780000000001")
w.Title("A Book")
w.Languages("en")
if _, err := w.AddContentFile("chapter-1.xhtml"); err != nil {
panic(err)
}
if err := w.TableOfContents("toc", epub.TOC{
Items: []epub.TOC{{Title: "Chapter 1", Href: "chapter-1.xhtml"}},
}); err != nil {
panic(err)
}
if err := w.Write("book.epub"); err != nil {
panic(err)
}
}
Output:
func (*Writer) AddGuide ¶ added in v0.2.0
func (w *Writer) AddGuide(kind pkg.GuideReferenceType, href string, title string)
AddGuide adds a guide reference entry (e.g., "cover", "toc", "title-page") to the package metadata.
Example ¶
ExampleWriter_AddGuide demonstrates adding structural guide references.
w := epub.New("urn:isbn:9780000000001")
w.Title("A Book")
w.Languages("en")
w.AddContent("cover.xhtml", sampleChapter("Cover"))
w.AddContent("chapter-1.xhtml", sampleChapter("Chapter 1"))
w.AddGuide(pkg.GuideRefCover, "cover.xhtml", "Cover")
w.AddGuide(pkg.GuideRefText, "chapter-1.xhtml", "Chapter 1")
if err := w.TableOfContents("toc", epub.TOC{
Items: []epub.TOC{{Title: "Chapter 1", Href: "chapter-1.xhtml"}},
}); err != nil {
panic(err)
}
if err := w.Write("book.epub"); err != nil {
panic(err)
}
func (*Writer) AddImage ¶ added in v0.2.0
func (w *Writer) AddImage(name string, content []byte) (res PublicationResource)
AddImage adds an image resource from raw bytes to the publication.
Example ¶
ExampleWriter_AddImage demonstrates embedding an image resource.
w := epub.New("urn:isbn:9780000000001")
w.Title("A Book")
w.Languages("en")
w.AddImage("figure-1.png", samplePNG())
w.AddContent("chapter-1.xhtml", sampleChapter("Chapter 1"))
if err := w.TableOfContents("toc", epub.TOC{
Items: []epub.TOC{{Title: "Chapter 1", Href: "chapter-1.xhtml"}},
}); err != nil {
panic(err)
}
if err := w.Write("book.epub"); err != nil {
panic(err)
}
func (*Writer) AddImageFile ¶ added in v0.2.0
func (w *Writer) AddImageFile(name string) (res PublicationResource)
AddImageFile adds an image resource to the publication by reading from disk.
func (*Writer) AddMarkdown ¶ added in v0.4.0
func (w *Writer) AddMarkdown(filename string, content []byte) (PublicationResource, error)
AddMarkdown converts content from Markdown to XHTML and adds it to the publication as a spine content document. The extension of filename is replaced with .xhtml to derive the href of the resulting document.
Example ¶
ExampleWriter_AddMarkdown demonstrates converting a Markdown string into a content document.
package main
import (
"fmt"
"github.com/raitucarp/epub"
)
func main() {
w := epub.New("urn:isbn:9780000000001")
w.Title("A Markdown Book")
w.Languages("en")
res, err := w.AddMarkdown("chapter-1.md", []byte("# Chapter 1\n\nOnce upon a time...\n"))
if err != nil {
panic(err)
}
fmt.Println(res.Href)
fmt.Println(res.MIMEType)
}
Output: chapter-1.xhtml application/xhtml+xml
func (*Writer) AddMarkdownDirectory ¶ added in v0.4.0
AddMarkdownDirectory reads every Markdown file in dir, converts each to an XHTML content document, and adds them to the spine in file-name order. A table of contents is generated from the heading structure of the documents and registered with the publication. The publication identifier, title, author, and language must be set on the Writer before calling Write.
Example ¶
ExampleWriter_AddMarkdownDirectory demonstrates building an EPUB from a directory of Markdown files, with the table of contents derived from the headings in each file.
package main
import (
"github.com/raitucarp/epub"
)
func main() {
w := epub.New("urn:isbn:9780000000001")
w.Title("A Markdown Book")
w.Author("Jane Doe")
w.Languages("en")
if err := w.AddMarkdownDirectory("manuscript"); err != nil {
panic(err)
}
if err := w.Write("book.epub"); err != nil {
panic(err)
}
}
Output:
func (*Writer) AddMarkdownFile ¶ added in v0.4.0
func (w *Writer) AddMarkdownFile(name string) (PublicationResource, error)
AddMarkdownFile reads the Markdown file at name from disk and adds it to the publication as a spine content document.
Example ¶
ExampleWriter_AddMarkdownFile demonstrates converting a Markdown file read from disk into a content document.
package main
import (
"github.com/raitucarp/epub"
)
func main() {
w := epub.New("urn:isbn:9780000000001")
w.Title("A Markdown Book")
w.Languages("en")
if _, err := w.AddMarkdownFile("chapter-1.md"); err != nil {
panic(err)
}
if err := w.Write("book.epub"); err != nil {
panic(err)
}
}
Output:
func (*Writer) AddSpineItem ¶ added in v0.2.0
func (w *Writer) AddSpineItem(res PublicationResource)
AddSpineItem appends the given resource to the spine reading order.
func (*Writer) Author ¶ added in v0.2.0
Author sets the primary creator/author in the package metadata.
Example ¶
ExampleWriter_Author demonstrates setting the primary author.
w := epub.New("urn:isbn:9780000000001")
w.Title("A Book")
w.Author("Jane Doe")
w.Languages("en")
w.AddContent("chapter-1.xhtml", sampleChapter("Chapter 1"))
if err := w.TableOfContents("toc", epub.TOC{
Items: []epub.TOC{{Title: "Chapter 1", Href: "chapter-1.xhtml"}},
}); err != nil {
panic(err)
}
if err := w.Write("book.epub"); err != nil {
panic(err)
}
func (*Writer) Build ¶ added in v0.4.0
Build assembles the package and container documents and serializes the publication to an in-memory ZIP archive.
func (*Writer) Contributor ¶ added in v0.2.0
Contributor adds a contributor entry of the specified role or type.
Example ¶
ExampleWriter_Contributor demonstrates adding a contributor of a given role.
w := epub.New("urn:isbn:9780000000001")
w.Title("A Book")
w.Author("Jane Doe")
w.Contributor("editor", "John Editor")
w.Languages("en")
w.AddContent("chapter-1.xhtml", sampleChapter("Chapter 1"))
if err := w.TableOfContents("toc", epub.TOC{
Items: []epub.TOC{{Title: "Chapter 1", Href: "chapter-1.xhtml"}},
}); err != nil {
panic(err)
}
if err := w.Write("book.epub"); err != nil {
panic(err)
}
func (*Writer) Cover ¶ added in v0.2.0
Cover sets the publication cover from a raw image byte slice.
Example ¶
ExampleWriter_Cover demonstrates setting the cover from raw image bytes.
w := epub.New("urn:isbn:9780000000001")
w.Title("A Book")
w.Languages("en")
if err := w.Cover(samplePNG()); err != nil {
panic(err)
}
w.AddContent("chapter-1.xhtml", sampleChapter("Chapter 1"))
if err := w.TableOfContents("toc", epub.TOC{
Items: []epub.TOC{{Title: "Chapter 1", Href: "chapter-1.xhtml"}},
}); err != nil {
panic(err)
}
if err := w.Write("book.epub"); err != nil {
panic(err)
}
func (*Writer) CoverJPG ¶ added in v0.2.0
CoverJPG sets the publication cover image from an image.Image encoded as JPEG.
func (*Writer) CoverPNG ¶ added in v0.2.0
CoverPNG sets the publication cover image from an image.Image encoded as PNG.
Example ¶
ExampleWriter_CoverPNG demonstrates setting the cover from an image.Image.
w := epub.New("urn:isbn:9780000000001")
w.Title("A Book")
w.Languages("en")
cover := image.NewRGBA(image.Rect(0, 0, 100, 150))
cover.Set(0, 0, color.RGBA{R: 255, A: 255})
if err := w.CoverPNG(cover); err != nil {
panic(err)
}
w.AddContent("chapter-1.xhtml", sampleChapter("Chapter 1"))
if err := w.TableOfContents("toc", epub.TOC{
Items: []epub.TOC{{Title: "Chapter 1", Href: "chapter-1.xhtml"}},
}); err != nil {
panic(err)
}
if err := w.Write("book.epub"); err != nil {
panic(err)
}
func (*Writer) Creator ¶ added in v0.2.0
Creator adds a creator with a specific identifier attribute to the metadata.
Example ¶
ExampleWriter_Creator demonstrates adding a creator with an explicit identifier attribute.
w := epub.New("urn:isbn:9780000000001")
w.Title("A Book")
w.Creator("creator-1", "Jane Doe")
w.Languages("en")
w.AddContent("chapter-1.xhtml", sampleChapter("Chapter 1"))
if err := w.TableOfContents("toc", epub.TOC{
Items: []epub.TOC{{Title: "Chapter 1", Href: "chapter-1.xhtml"}},
}); err != nil {
panic(err)
}
if err := w.Write("book.epub"); err != nil {
panic(err)
}
func (*Writer) Date ¶ added in v0.2.0
Date sets the publication date metadata.
Example ¶
ExampleWriter_Date demonstrates setting the publication and modification dates.
w := epub.New("urn:isbn:9780000000001")
w.Title("A Book")
w.Languages("en")
w.Date(time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC))
w.Modified(time.Now())
w.AddContent("chapter-1.xhtml", sampleChapter("Chapter 1"))
if err := w.TableOfContents("toc", epub.TOC{
Items: []epub.TOC{{Title: "Chapter 1", Href: "chapter-1.xhtml"}},
}); err != nil {
panic(err)
}
if err := w.Write("book.epub"); err != nil {
panic(err)
}
func (*Writer) Description ¶ added in v0.2.0
Description sets a short description or summary for the publication.
Example ¶
ExampleWriter_Description demonstrates setting a short and a long description.
w := epub.New("urn:isbn:9780000000001")
w.Title("A Book")
w.Languages("en")
w.Description("A short summary.")
w.LongDescription("A much longer and more detailed description of the work.")
w.AddContent("chapter-1.xhtml", sampleChapter("Chapter 1"))
if err := w.TableOfContents("toc", epub.TOC{
Items: []epub.TOC{{Title: "Chapter 1", Href: "chapter-1.xhtml"}},
}); err != nil {
panic(err)
}
if err := w.Write("book.epub"); err != nil {
panic(err)
}
func (*Writer) Direction ¶ added in v0.2.0
Direction sets the writing direction (ltr or rtl) used by the spine.
func (*Writer) DublinCores ¶ added in v0.2.0
DublinCores sets multiple Dublin Core metadata fields at once.
Example ¶
ExampleWriter_DublinCores demonstrates setting Dublin Core fields in bulk.
w := epub.New("urn:isbn:9780000000001")
w.Title("A Book")
w.Languages("en")
w.DublinCores(map[string]string{
"publisher": "Example Press",
"rights": "All rights reserved",
})
w.AddContent("chapter-1.xhtml", sampleChapter("Chapter 1"))
if err := w.TableOfContents("toc", epub.TOC{
Items: []epub.TOC{{Title: "Chapter 1", Href: "chapter-1.xhtml"}},
}); err != nil {
panic(err)
}
if err := w.Write("book.epub"); err != nil {
panic(err)
}
func (*Writer) Identifiers ¶ added in v0.2.0
Identifiers adds one or more identifiers to the package metadata.
Example ¶
ExampleWriter_Identifiers demonstrates adding multiple identifiers.
w := epub.New("urn:isbn:9780000000001")
w.Title("A Book")
w.Languages("en")
w.Identifiers("urn:isbn:9780000000002", "urn:uuid:0f1f1e7e-0000-0000-0000-000000000000")
w.AddContent("chapter-1.xhtml", sampleChapter("Chapter 1"))
if err := w.TableOfContents("toc", epub.TOC{
Items: []epub.TOC{{Title: "Chapter 1", Href: "chapter-1.xhtml"}},
}); err != nil {
panic(err)
}
if err := w.Write("book.epub"); err != nil {
panic(err)
}
func (*Writer) Languages ¶ added in v0.2.0
Languages adds one or more language codes to the publication metadata.
Example ¶
ExampleWriter_Languages demonstrates setting multiple language codes.
w := epub.New("urn:isbn:9780000000001")
w.Title("A Book")
w.Languages("en", "fr")
w.AddContent("chapter-1.xhtml", sampleChapter("Chapter 1"))
if err := w.TableOfContents("toc", epub.TOC{
Items: []epub.TOC{{Title: "Chapter 1", Href: "chapter-1.xhtml"}},
}); err != nil {
panic(err)
}
if err := w.Write("book.epub"); err != nil {
panic(err)
}
func (*Writer) LongDescription ¶ added in v0.2.0
LongDescription sets an extended descriptive summary.
func (*Writer) Meta ¶ added in v0.2.0
Meta adds a meta element to the package metadata as-is.
Example ¶
ExampleWriter_Meta demonstrates adding custom metadata and refinements.
w := epub.New("urn:isbn:9780000000001")
w.Title("A Book")
w.Languages("en")
w.Meta(pkg.Meta{Property: "schema:accessMode", Value: "textual"})
w.Refines("#title", "title-type", "main")
w.AddContent("chapter-1.xhtml", sampleChapter("Chapter 1"))
if err := w.TableOfContents("toc", epub.TOC{
Items: []epub.TOC{{Title: "Chapter 1", Href: "chapter-1.xhtml"}},
}); err != nil {
panic(err)
}
if err := w.Write("book.epub"); err != nil {
panic(err)
}
func (*Writer) MetaContent ¶ added in v0.2.0
MetaContent adds metadata key/value entries that do not require refinements.
func (*Writer) MetaProperty ¶ added in v0.2.0
MetaProperty adds a property-based metadata refinement entry.
func (*Writer) Modified ¶ added in v0.4.0
Modified sets the last modification date (dcterms:modified) metadata, which the EPUB specification requires in every package document. The value is expressed in UTC using the extended ISO 8601 format (YYYY-MM-DDThh:mm:ssZ).
func (*Writer) Publisher ¶ added in v0.2.0
Publisher sets the publication publisher.
Example ¶
ExampleWriter_Publisher demonstrates setting the publisher.
w := epub.New("urn:isbn:9780000000001")
w.Title("A Book")
w.Languages("en")
w.Publisher("Example Press")
w.AddContent("chapter-1.xhtml", sampleChapter("Chapter 1"))
if err := w.TableOfContents("toc", epub.TOC{
Items: []epub.TOC{{Title: "Chapter 1", Href: "chapter-1.xhtml"}},
}); err != nil {
panic(err)
}
if err := w.Write("book.epub"); err != nil {
panic(err)
}
func (*Writer) Refines ¶ added in v0.2.0
func (w *Writer) Refines(refines string, property string, value string, otherAttributes ...pkg.Meta)
Refines applies a metadata refinement to an existing metadata item.
func (*Writer) Rights ¶ added in v0.2.0
Rights sets the copyright or licensing information for the publication.
Example ¶
ExampleWriter_Rights demonstrates setting copyright information.
w := epub.New("urn:isbn:9780000000001")
w.Title("A Book")
w.Languages("en")
w.Rights("Copyright 2026 Jane Doe. All rights reserved.")
w.AddContent("chapter-1.xhtml", sampleChapter("Chapter 1"))
if err := w.TableOfContents("toc", epub.TOC{
Items: []epub.TOC{{Title: "Chapter 1", Href: "chapter-1.xhtml"}},
}); err != nil {
panic(err)
}
if err := w.Write("book.epub"); err != nil {
panic(err)
}
func (*Writer) SetContentDir ¶ added in v0.2.0
SetContentDir sets the directory used for storing content documents.
func (*Writer) SetImageDir ¶ added in v0.2.0
SetImageDir sets the directory used for storing image resources.
func (*Writer) SetTextDir ¶ added in v0.2.0
SetTextDir sets the directory used for text document organization.
func (*Writer) Subject ¶ added in v0.2.0
Subject adds a subject or theme classification to the publication.
Example ¶
ExampleWriter_Subject demonstrates adding subject classifications.
w := epub.New("urn:isbn:9780000000001")
w.Title("A Book")
w.Author("Jane Doe")
w.Subject("subject-1", "Fiction", "Adventure")
w.Languages("en")
w.AddContent("chapter-1.xhtml", sampleChapter("Chapter 1"))
if err := w.TableOfContents("toc", epub.TOC{
Items: []epub.TOC{{Title: "Chapter 1", Href: "chapter-1.xhtml"}},
}); err != nil {
panic(err)
}
if err := w.Write("book.epub"); err != nil {
panic(err)
}
func (*Writer) TableOfContents ¶ added in v0.2.0
TableOfContents generates the EPUB navigation document and its legacy NCX counterpart from the given TOC structure, using name as the base for the generated file names.
Example ¶
ExampleWriter_TableOfContents demonstrates writing a nested table of contents.
w := epub.New("urn:isbn:9780000000001")
w.Title("A Book")
w.Languages("en")
w.AddContent("chapter-1.xhtml", sampleChapter("Chapter 1"))
toc := epub.TOC{
Title: "Contents",
Items: []epub.TOC{
{
Title: "Chapter 1",
Href: "chapter-1.xhtml",
Items: []epub.TOC{
{Title: "Section 1.1", Href: "chapter-1.xhtml#section-1-1"},
{Title: "Section 1.2", Href: "chapter-1.xhtml#section-1-2"},
},
},
},
}
if err := w.TableOfContents("toc", toc); err != nil {
panic(err)
}
if err := w.Write("book.epub"); err != nil {
panic(err)
}
func (*Writer) Title ¶ added in v0.2.0
Title sets one or more title entries in the metadata.
Example ¶
ExampleWriter_Title demonstrates setting a title with an additional subtitle.
w := epub.New("urn:isbn:9780000000001")
w.Title("A Book", "The Subtitled Edition")
w.Languages("en")
w.AddContent("chapter-1.xhtml", sampleChapter("Chapter 1"))
if err := w.TableOfContents("toc", epub.TOC{
Items: []epub.TOC{{Title: "Chapter 1", Href: "chapter-1.xhtml"}},
}); err != nil {
panic(err)
}
if err := w.Write("book.epub"); err != nil {
panic(err)
}
func (*Writer) Write ¶ added in v0.2.0
Write finalizes the EPUB structure and writes it to the specified filename.
func (*Writer) WriteBytes ¶ added in v0.4.0
WriteBytes finalizes the EPUB structure and returns the resulting bytes without touching the filesystem.
Example ¶
ExampleWriter_WriteBytes demonstrates serializing to an in-memory byte slice and reading it back.
w := epub.New("urn:isbn:9780000000001")
w.Title("A Book")
w.Languages("en")
w.AddContent("chapter-1.xhtml", sampleChapter("Chapter 1"))
if err := w.TableOfContents("toc", epub.TOC{
Items: []epub.TOC{{Title: "Chapter 1", Href: "chapter-1.xhtml"}},
}); err != nil {
panic(err)
}
data, err := w.WriteBytes()
if err != nil {
panic(err)
}
book, err := epub.NewReader(data)
if err != nil {
panic(err)
}
_ = book
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
docs
|
|
|
scripts
command
|
|
|
examples
|
|
|
edit
command
|
|
|
read
command
|
|
|
write
command
|
|
|
write/advanced_multilingual_rtl
command
|
|
|
write/basic
command
|
|
|
write/markdown
command
|
|
|
write/nested_toc_and_guide
command
|
|
|
write/reconstruct_standardebooks
command
|
|
|
write/with_cover
command
|
|
|
w3c/w3ctest
Package w3ctest provides shared helpers for the W3C EPUB test suite port.
|
Package w3ctest provides shared helpers for the W3C EPUB test suite port. |