epub

package module
v0.5.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 26, 2026 License: MIT Imports: 35 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

epub

Go Reference CI Ko-fi

epub is a high-performance, developer-friendly Go library for reading, writing, and editing EPUB publications. It implements the EPUB 3.3 specification, including the Open Container Format (OCF), package documents, EPUB navigation documents (NAV), and the legacy NCX format used by EPUB 2.

Documentation is available at epub.raitucarp.name.

The library provides three main entry points:

  • Reader for inspecting metadata, resources, navigation, spine order, and converting content documents to Markdown.
  • Writer for building new publications from scratch, including from Markdown manuscripts.
  • Editor for mutating existing publications in place with concise fluent chaining (reader.Edit()).

Installation

go get github.com/raitucarp/epub

Requires Go 1.25 or later.


Quick start

1. Read an EPUB
book, err := epub.OpenReader("book.epub")
if err != nil {
    log.Fatal(err)
}

fmt.Println("Title:", strings.Join(book.Title(), ", "))
fmt.Println("Author:", strings.Join(book.Author(), ", "))
fmt.Println("Language:", strings.Join(book.Language(), ", "))
fmt.Println("Identifier:", book.UID())

// Convert content documents directly to clean Markdown!
for _, id := range book.ListContentDocumentIds() {
    fmt.Println(book.ReadContentMarkdownById(id))
}
2. Write an EPUB
w := epub.New("urn:isbn:9780000000001")
w.Title("A Book")
w.Author("Jane Doe")
w.Languages("en")

w.AddContent("chapter-1.xhtml", []byte(`<html xmlns="http://www.w3.org/1999/xhtml"><body><h1>Chapter 1</h1><p>Hello, world.</p></body></html>`))

toc := epub.TOC{
    Title: "Contents",
    Items: []epub.TOC{{Title: "Chapter 1", Href: "chapter-1.xhtml"}},
}
if err := w.TableOfContents("toc", toc); err != nil {
    log.Fatal(err)
}

if err := w.Write("book.epub"); err != nil {
    log.Fatal(err)
}
3. Edit an Existing EPUB
reader, err := epub.OpenReader("book.epub")
if err != nil {
    log.Fatal(err)
}

// Enter edit mode
editor, err := reader.Edit()
if err != nil {
    log.Fatal(err)
}

// Concise fluent method chaining
editor.Title("A Book (Second Edition)").
    Author("Jane Doe, PhD").
    Description("Revised edition with new notes.")

// Add or update chapters
editor.AddContent("chapter-2.xhtml", []byte(`<h1>Chapter 2</h1><p>Continuing the journey...</p>`))

// Save in one of three ways:
// 1. Direct to file
editor.SaveAs("book-v2.epub")

// 2. Stream to any io.Writer
var buf bytes.Buffer
editor.Save(&buf)

// 3. Populate a byte slice directly
var b []byte
editor.WriteBytes(&b)

// 4. Or transition back to Reader mode in memory:
readerBack, err := editor.Reader()
4. Write an EPUB from Markdown

A single Markdown document can be converted directly:

w := epub.New("urn:isbn:9780000000001")
w.Title("A Markdown Book")
w.Languages("en")

if _, err := w.AddMarkdown("chapter-1.md", []byte("# Chapter 1\n\nOnce upon a time...\n")); err != nil {
    log.Fatal(err)
}

Or an entire directory of Markdown files can be assembled, with the table of contents automatically derived from the headings:

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 {
    log.Fatal(err)
}

if err := w.Write("book.epub"); err != nil {
    log.Fatal(err)
}

Reading

Metadata
book, _ := epub.OpenReader("book.epub")

book.Title()        // []string
book.Author()       // []string
book.Language()     // []string
book.Identifier()   // []string
book.UID()          // the resolved unique identifier
book.Version()      // the EPUB version, e.g. "3.0"
book.Description()  // []string
book.Metadata()     // map[string]any of the full metadata block
book.Refines()      // metadata refinements keyed by subject
Content documents
ids := book.ListContentDocumentIds() // manifest IDs of XHTML/SVG documents

book.ReadContentHTMLById(id)       // *html.Node
book.ReadContentHTMLByHref(href)   // *html.Node
book.ReadContentMarkdownById(id)   // string (Markdown)
book.ReadContentMarkdownByHref(h)  // string (Markdown)
book.ContentDocumentXHTML()        // map[string]*html.Node
book.ContentDocumentXHTMLString()  // map[string]string
book.ContentDocumentMarkdown()     // map[string]string
book.ContentDocumentSVG()          // map[string]*html.Node
Resources and images
book.Resources()                   // []PublicationResource
book.SelectResourceById(id)        // *PublicationResource
book.SelectResourceByHref(href)    // *PublicationResource

book.ListImageIds()                // manifest IDs of image resources
book.Images()                      // map[string]image.Image
book.ImageResources()              // map[string][]byte
book.ReadImageById(id)             // *image.Image
book.ReadImageByHref(href)         // *image.Image
book.ReadImageBytesById(id)        // []byte
book.ReadImageBytesByHref(href)    // []byte
Navigation
toc, _ := book.TableOfContents()   // TOC (NAV or NCX)
book.Landmarks()                   // []Landmark
book.PageList()                    // []Landmark

for _, item := range toc.Items {
    fmt.Println(item.Title, item.Href)
}

json, _ := toc.JSON()              // serialized table of contents

Writing

Metadata
w := epub.New("urn:isbn:9780000000001")

w.Title("A Book")
w.Title("A Book", "Subtitle")       // additional titles
w.Author("Jane Doe")
w.Creator("creator-id", "Jane Doe")
w.Contributor("editor", "John Editor")
w.Languages("en")
w.Description("A short description")
w.Publisher("Example Press")
w.Subject("subject-id", "Fiction")
w.Rights("All rights reserved")
w.Date(time.Now())
w.Modified(time.Now())              // dcterms:modified
Content and resources
w.AddContent("chapter-1.xhtml", []byte("..."))   // XHTML or SVG
w.AddContentFile("chapter-1.xhtml")              // read from disk
w.AddImage("cover.png", imageBytes)
w.AddImageFile("cover.png")
w.Cover(imageBytes)                              // detect PNG/JPEG
w.CoverPNG(img)                                  // image.Image as PNG
w.CoverJPG(img)                                  // image.Image as JPEG
w.CoverFile("cover.png")
Table of contents
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"},
        }},
    },
}
w.TableOfContents("toc", toc)

Editing

editor, err := reader.Edit()

// Mutate metadata
editor.Title("Updated Title").
    Author("New Author").
    Language("en").
    Subject("Adventure", "Classics")

// Modify or inject content
editor.AddContent("text/extra.xhtml", contentBytes)
editor.UpdateContent("text/chapter-1.xhtml", updatedContentBytes)
editor.RemoveResource("text/obsolete.xhtml")

// Switch back to reader mode or save
readerBack, _ := editor.Reader()
editor.SaveAs("final.epub")
editor.Save(ioWriter)
editor.WriteBytes(&byteSlice)

Supported media types

  • Documents: application/xhtml+xml, text/html
  • Navigation: application/x-dtbncx+xml (NCX), application/xhtml+xml (NAV)
  • Styles: text/css
  • Images: image/jpeg, image/png, image/gif, image/webp, image/svg+xml
  • Fonts: font/ttf, font/otf, font/woff, font/woff2

Examples

Runnable example programs live under ./examples:


Documentation


Support

If you find this project helpful or use it in your applications, consider supporting its maintenance and development:

Support on Ko-fi

You can support the creator directly at ko-fi.com/raitucarp. Every coffee is greatly appreciated!


Contributing

git clone https://github.com/raitucarp/epub.git
cd epub
go mod download
git config core.hooksPath .githooks
go test ./...

License

MIT © Raitucarp

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:

  1. Reader: Inspect and extract data from existing EPUB publications (files or memory).
  2. Writer: Create compliant EPUB publications from scratch or from Markdown documents.
  3. 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)
	}
}
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

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func FindNode added in v0.4.0

func FindNode(node *html.Node, predicate func(*html.Node) bool) *html.Node

FindNode traverses the HTML tree recursively and returns the first node that satisfies the predicate.

func GetTextContent added in v0.4.0

func GetTextContent(node *html.Node) string

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

func (e *Editor) AddAuthor(author string) *Editor

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

func (e *Editor) AddDescription(description string) *Editor

AddDescription appends a description to the metadata.

func (*Editor) AddFile added in v0.5.0

func (e *Editor) AddFile(filePath string, content []byte) *Editor

AddFile directly adds or updates any arbitrary file path inside the container.

func (*Editor) AddIdentifier added in v0.5.0

func (e *Editor) AddIdentifier(id, value string) *Editor

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

func (e *Editor) AddLanguage(language string) *Editor

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

func (e *Editor) AddPublisher(publisher string) *Editor

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

func (e *Editor) AddSpineItem(idOrHref string) error

AddSpineItem appends a manifest item to the spine reading order.

func (*Editor) AddSubject added in v0.5.0

func (e *Editor) AddSubject(subject string) *Editor

AddSubject appends a subject to the metadata.

func (*Editor) AddTitle added in v0.5.0

func (e *Editor) AddTitle(title string) *Editor

AddTitle appends an additional title entry to the metadata.

func (*Editor) Author added in v0.5.0

func (e *Editor) Author(authors ...string) *Editor

Author sets (replaces) the publication creator/author(s).

func (*Editor) Build added in v0.5.0

func (e *Editor) Build() ([]byte, error)

Build serializes the modified publication package(s) and creates an in-memory EPUB zip archive.

func (*Editor) Contributor added in v0.5.0

func (e *Editor) Contributor(kind string, contributors ...string) *Editor

Contributor adds a contributor entry of the specified role or type.

func (*Editor) Cover added in v0.5.0

func (e *Editor) Cover(cover []byte) error

Cover sets the publication cover image from raw bytes.

func (*Editor) CoverFile added in v0.5.0

func (e *Editor) CoverFile(name string) error

CoverFile sets the cover image by reading from a file path.

func (*Editor) CoverJPG added in v0.5.0

func (e *Editor) CoverJPG(cover image.Image) error

CoverJPG sets the cover image from an image.Image encoded as JPEG.

func (*Editor) CoverPNG added in v0.5.0

func (e *Editor) CoverPNG(cover image.Image) error

CoverPNG sets the cover image from an image.Image encoded as PNG.

func (*Editor) Creator added in v0.5.0

func (e *Editor) Creator(id string, creators ...string) *Editor

Creator adds a creator with a specific identifier attribute to the metadata.

func (*Editor) CurrentPackage added in v0.5.0

func (e *Editor) CurrentPackage() *pkg.Package

CurrentPackage returns the active package publication.

func (*Editor) CurrentPackagePath added in v0.5.0

func (e *Editor) CurrentPackagePath() string

CurrentPackagePath returns the container file path of the active package document.

func (*Editor) Date added in v0.5.0

func (e *Editor) Date(date time.Time) *Editor

Date sets the publication date metadata.

func (*Editor) Description added in v0.5.0

func (e *Editor) Description(descriptions ...string) *Editor

Description sets (replaces) the publication description(s).

func (*Editor) Direction added in v0.5.0

func (e *Editor) Direction(dir string) *Editor

Direction sets the reading direction ("ltr" or "rtl").

func (*Editor) DublinCore added in v0.5.0

func (e *Editor) DublinCore(localName, value string) *Editor

DublinCore adds an arbitrary Dublin Core element to the metadata.

func (*Editor) Identifier added in v0.5.0

func (e *Editor) Identifier(identifiers ...string) *Editor

Identifier sets (replaces) the publication identifiers.

func (*Editor) Language added in v0.5.0

func (e *Editor) Language(languages ...string) *Editor

Language sets (replaces) the publication language codes.

func (*Editor) ListRenditions added in v0.5.0

func (e *Editor) ListRenditions() []string

ListRenditions returns the identifiers of all package renditions available.

func (*Editor) Meta added in v0.5.0

func (e *Editor) Meta(meta pkg.Meta) *Editor

Meta adds a meta element to the package metadata.

func (*Editor) MetaContent added in v0.5.0

func (e *Editor) MetaContent(keyVal map[string]string) *Editor

MetaContent adds metadata key/value entries that do not require refinements.

func (*Editor) MetaProperty added in v0.5.0

func (e *Editor) MetaProperty(id, property, value string) *Editor

MetaProperty adds a property-based metadata refinement entry.

func (*Editor) Modified added in v0.5.0

func (e *Editor) Modified(date time.Time) *Editor

Modified sets the last modification date (dcterms:modified) metadata.

func (*Editor) Package added in v0.5.0

func (e *Editor) Package() *pkg.Package

Package returns the currently active package document for direct inspection or modification.

func (*Editor) Publisher added in v0.5.0

func (e *Editor) Publisher(publishers ...string) *Editor

Publisher sets (replaces) the publication publisher(s).

func (*Editor) Reader added in v0.5.0

func (e *Editor) Reader() (Reader, error)

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

func (e *Editor) Refines(refines, property, value string, otherAttributes ...pkg.Meta) *Editor

Refines applies a metadata refinement to an existing metadata item.

func (*Editor) RemoveMeta added in v0.5.0

func (e *Editor) RemoveMeta(propertyOrName string) *Editor

RemoveMeta removes meta elements whose Property or Name matches propertyOrName.

func (*Editor) RemoveMetadata added in v0.5.0

func (e *Editor) RemoveMetadata(xmlLocalName string) *Editor

RemoveMetadata removes optional Dublin Core elements matching the given XML local name.

func (*Editor) RemoveResource added in v0.5.0

func (e *Editor) RemoveResource(idOrHref string) error

RemoveResource removes a resource from the manifest, spine (if referenced), and container.

func (*Editor) RemoveSpineItem added in v0.5.0

func (e *Editor) RemoveSpineItem(idOrHref string) error

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) Rights added in v0.5.0

func (e *Editor) Rights(rights string) *Editor

Rights sets the copyright or licensing information.

func (*Editor) Save added in v0.5.0

func (e *Editor) Save(writer io.Writer) error

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

func (e *Editor) SaveAs(filename string) error

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

func (e *Editor) SaveByte(b *[]byte) error

SaveByte is an alias for WriteBytes for backwards compatibility.

func (*Editor) SaveBytes added in v0.5.0

func (e *Editor) SaveBytes() ([]byte, error)

SaveBytes returns the edited EPUB archive as a byte slice.

func (*Editor) SelectPackageRendition added in v0.5.0

func (e *Editor) SelectPackageRendition(rendition string) error

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

func (e *Editor) SetMeta(property, value string) *Editor

SetMeta sets or updates a meta element matching the specified property.

func (*Editor) Subject added in v0.5.0

func (e *Editor) Subject(subjects ...string) *Editor

Subject sets (replaces) the publication subjects/themes.

func (*Editor) TableOfContents added in v0.5.0

func (e *Editor) TableOfContents(name string, toc TOC) error

TableOfContents generates and updates the EPUB navigation document (XHTML) and legacy NCX.

func (*Editor) Title added in v0.5.0

func (e *Editor) Title(titles ...string) *Editor

Title sets (replaces) the publication title(s).

func (*Editor) UniqueIdentifier added in v0.5.0

func (e *Editor) UniqueIdentifier(id string) *Editor

UniqueIdentifier sets the package unique-identifier attribute.

func (*Editor) UpdateContent added in v0.5.0

func (e *Editor) UpdateContent(idOrHref string, content []byte) error

UpdateContent updates the byte content of an existing content document identified by ID or Href.

func (*Editor) UpdateResource added in v0.5.0

func (e *Editor) UpdateResource(idOrHref string, content []byte) error

UpdateResource updates the byte content of an existing resource identified by ID or Href.

func (*Editor) Version added in v0.5.0

func (e *Editor) Version(v string) *Editor

Version sets the EPUB publication version (e.g. "3.0" or "2.0").

func (*Editor) WriteBytes added in v0.5.0

func (e *Editor) WriteBytes(b *[]byte) error

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

func (epub *Epub) DefaultPackage() *pkg.Package

DefaultPackage returns the package document registered under the conventional "content" key.

func (*Epub) SelectPackage added in v0.2.0

func (epub *Epub) SelectPackage(name string) *pkg.Package

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

func (epub *Epub) SelectedPackage() *pkg.Package

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

func NewReader(b []byte) (reader Reader, err error)

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

func OpenReader(name string) (reader Reader, err error)

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())
}

func (*Reader) Author

func (r *Reader) Author() []string

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

func (r *Reader) ContentDocumentMarkdown() (documents map[string]string)

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

func (r *Reader) ContentDocumentSVG() (documents map[string]*html.Node)

ContentDocumentSVG returns SVG content documents parsed into html.Node trees. The returned map is keyed by EPUB manifest item ID.

func (*Reader) ContentDocumentXHTML

func (r *Reader) ContentDocumentXHTML() (documents map[string]*html.Node)

ContentDocumentXHTML returns XHTML content documents parsed into html.Node trees. The returned map is keyed by EPUB manifest item ID.

func (*Reader) ContentDocumentXHTMLString

func (r *Reader) ContentDocumentXHTMLString() (documents map[string]string)

ContentDocumentXHTMLString returns XHTML content documents as raw strings. The returned map is keyed by EPUB manifest item ID.

func (*Reader) Cover

func (r *Reader) Cover() (cover *image.Image)

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())
}

func (*Reader) CoverBytes added in v0.2.0

func (r *Reader) CoverBytes() (cover []byte, err error)

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

func (r *Reader) CurrentSelectedPackage() *pkg.Package

CurrentSelectedPackage returns the currently active package rendition. EPUB publications may have multiple renditions.

func (*Reader) CurrentSelectedPackagePath

func (r *Reader) CurrentSelectedPackagePath() string

CurrentSelectedPackagePath returns the internal path to the currently selected package document.

func (*Reader) Description

func (r *Reader) Description() []string

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"))
}

func (*Reader) Edit added in v0.5.0

func (r *Reader) Edit() (*Editor, error)

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

func (r *Reader) Identifier() []string

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

func (r *Reader) ImageResources() (images map[string][]byte)

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

func (r *Reader) Images() (images map[string]image.Image)

Images returns all image resources in the publication, keyed by manifest ID.

func (*Reader) Landmarks added in v0.4.0

func (r *Reader) Landmarks() []Landmark

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)
	}
}

func (*Reader) Language added in v0.2.0

func (r *Reader) Language() []string

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

func (r *Reader) ListContentDocumentIds() (ids []string)

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

func (r *Reader) ListImageIds() (ids []string)

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

func (r *Reader) ListRenditions() []string

ListRenditions returns the identifiers of all package renditions available in the publication. The first rendition is always named "default".

func (*Reader) Metadata

func (r *Reader) Metadata() (metadata map[string]any)

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

func (r *Reader) NavigationCenterExtended() *ncx.NCX

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

func (r *Reader) PageList() []Landmark

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)
	}
}

func (*Reader) ReadContentHTMLByHref added in v0.1.3

func (r *Reader) ReadContentHTMLByHref(href string) (doc *html.Node)

ReadContentHTMLByHref returns the content document associated with the given manifest href. The returned document is parsed into an html.Node tree.

func (*Reader) ReadContentHTMLById

func (r *Reader) ReadContentHTMLById(id string) (doc *html.Node)

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

func (r *Reader) ReadContentMarkdownByHref(href string) (md string)

ReadContentMarkdownByHref returns a Markdown string representation of the content document associated with the given manifest href.

func (*Reader) ReadContentMarkdownById added in v0.1.1

func (r *Reader) ReadContentMarkdownById(id string) (md string)

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

func (r *Reader) ReadImageByHref(href string) (img *image.Image)

ReadImageByHref returns the image resource referenced by the given href, if present in the manifest.

func (*Reader) ReadImageById

func (r *Reader) ReadImageById(id string) (img *image.Image)

ReadImageById returns the image resource associated with the given manifest ID.

func (*Reader) ReadImageBytesByHref added in v0.4.0

func (r *Reader) ReadImageBytesByHref(href string) []byte

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

func (r *Reader) ReadImageBytesById(id string) []byte

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)
	}
}

func (*Reader) Refines

func (r *Reader) Refines() (refines map[string]map[string][]string)

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

func (r *Reader) SelectPackageRendition(rendition string)

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())
}

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

func (r *Reader) TableOfContents() (toc TOC, err error)

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

func (r *Reader) Title() []string

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

func (r *Reader) UID() (identifier string)

UID returns the unique identifier of the publication. It resolves the package's unique-identifier attribute to the matching dc:identifier entry.

func (*Reader) Version

func (r *Reader) Version() (version string)

Version returns the EPUB specification version of the publication.

Example

ExampleReader_Version demonstrates reading the EPUB specification version.

book, err := epub.NewReader(buildSampleBook())
if err != nil {
	panic(err)
}

fmt.Println(book.Version())
Output:
3.0

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

func (t *TOC) JSON() ([]byte, error)

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

func (t *TOC) ReadContentHTML() (content *html.Node)

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

func New(pubId string) *Writer

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)
	}
}

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

func (w *Writer) AddMarkdownDirectory(dir string) error

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)
	}
}

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)
	}
}

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

func (w *Writer) Author(creator ...string)

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

func (w *Writer) Build() ([]byte, error)

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

func (w *Writer) Contributor(kind string, contributor ...string)

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

func (w *Writer) Cover(cover []byte) (err error)

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) CoverFile added in v0.2.0

func (w *Writer) CoverFile(name string) error

CoverFile sets the publication cover image by file path.

func (*Writer) CoverJPG added in v0.2.0

func (w *Writer) CoverJPG(cover image.Image) (err error)

CoverJPG sets the publication cover image from an image.Image encoded as JPEG.

func (*Writer) CoverPNG added in v0.2.0

func (w *Writer) CoverPNG(cover image.Image) (err error)

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

func (w *Writer) Creator(id string, creator ...string)

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

func (w *Writer) Date(date time.Time)

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

func (w *Writer) Description(description ...string)

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

func (w *Writer) Direction(dir string)

Direction sets the writing direction (ltr or rtl) used by the spine.

func (*Writer) DublinCores added in v0.2.0

func (w *Writer) DublinCores(keyVal map[string]string)

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

func (w *Writer) Identifiers(identifier ...string)

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

func (w *Writer) Languages(language ...string)

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

func (w *Writer) LongDescription(description string)

LongDescription sets an extended descriptive summary.

func (*Writer) Meta added in v0.2.0

func (w *Writer) Meta(meta pkg.Meta)

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

func (w *Writer) MetaContent(keyVal map[string]string)

MetaContent adds metadata key/value entries that do not require refinements.

func (*Writer) MetaProperty added in v0.2.0

func (w *Writer) MetaProperty(id string, property string, value string)

MetaProperty adds a property-based metadata refinement entry.

func (*Writer) Modified added in v0.4.0

func (w *Writer) Modified(date time.Time)

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

func (w *Writer) Publisher(publisher ...string)

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

func (w *Writer) Rights(rights string)

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

func (w *Writer) SetContentDir(dir string)

SetContentDir sets the directory used for storing content documents.

func (*Writer) SetImageDir added in v0.2.0

func (w *Writer) SetImageDir(dir string)

SetImageDir sets the directory used for storing image resources.

func (*Writer) SetTextDir added in v0.2.0

func (w *Writer) SetTextDir(dir string)

SetTextDir sets the directory used for text document organization.

func (*Writer) Subject added in v0.2.0

func (w *Writer) Subject(id string, subject ...string)

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

func (w *Writer) TableOfContents(name string, toc TOC) (err error)

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

func (w *Writer) Title(title ...string)

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

func (w *Writer) Write(filename string) (err error)

Write finalizes the EPUB structure and writes it to the specified filename.

func (*Writer) WriteBytes added in v0.4.0

func (w *Writer) WriteBytes() ([]byte, error)

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

Directories

Path Synopsis
docs
scripts command
examples
edit command
read command
write command
write/basic command
write/markdown 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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址