PHP code example of adrorocker / epub-builder

1. Go to this page and download the library: Download adrorocker/epub-builder library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

adrorocker / epub-builder example snippets




use AdroSoftware\EpubBuilder\EpubBuilder;

$poemJson = json_decode(file_get_contents('poem.json'), true);

$output = EpubBuilder::create()
    ->setMetadata(fn($m) => $m
        ->title('Selected Poems')
        ->author('Robert Frost')
        ->language('en')
        ->coverImage('/path/to/cover.jpg')
    )
    ->addChapter('The Road Not Taken', $poemJson)
    ->addChapter('Stopping by Woods', $poemJson)
    ->build('/output/path/book.epub');

echo $output->getPath();   // /output/path/book.epub
echo $output->getSize();   // 2,760,000 (bytes)

$output = EpubBuilder::create()
    ->setMetadata(fn($m) => $m
        // Required
        ->title('White Nights and Other Stories')
        ->language('en')

        // Recommended
        ->author('Fyodor Dostoyevsky')
        ->author('Other Co-author')           // call again for multiple authors
        ->publisher('epubBooks Classics')
        ->description('A collection of short stories.')
        ->rights('Public domain')
        ->coverImage('/path/to/cover.jpg')

        // Genre / category tags (Apple Books, Google Play, calibre use these)
        ->subject('Classic Fiction')
        ->subject('Short Stories')

        // Contributors with MARC relator role codes (see table below)
        ->contributor('Constance Garnett', 'trl')   // translator
        ->contributor('Anne Editor', 'edt')         // editor

        // Optional extras
        ->isbn('978-3-16-148410-0')
        ->series('My Collection', 1)
        ->direction('ltr')                          // 'ltr' (default) or 'rtl'
        ->identifier('urn:uuid:...')                // defaults to a generated UUIDv4
        ->modified(new \DateTimeImmutable())        // defaults to now (UTC)
    )
    ->addChapter('Chapter One', $tiptapJson)
    ->build();

$builder
    ->addChapter('Introduction', $intro)
    ->addChapter('Chapter One', $ch1)
    ->addChapter('Chapter Two', $ch2);

->setMetadata(fn($m) => $m
    ->title('Book')
    ->coverImage('/path/to/cover.jpg')   // jpg, png, gif, webp, svg
);

$output = $builder->build('/optional/explicit/path.epub');

$output->getPath();         // string — path on disk
$output->getSize();         // int    — byte size
$output->getContents();     // string — raw .epub bytes
$output->delete();          // remove the file

// HTTP response — Apache/nginx/PHP-FPM, framework-agnostic
$output->download('book.epub');   // sets headers, streams, exit()

// Chunked streaming — write into any resource
$output->streamTo(STDOUT);                    // returns int bytes written
foreach ($output->chunks(8192) as $chunk) {   // generator, no buffer
    // ...
}

// Write straight to the HTTP response body. Temp file is removed.
header('Content-Type: application/epub+zip');
header('Content-Disposition: attachment; filename="book.epub"');
$out = fopen('php://output', 'wb');
EpubBuilder::create()
    ->setMetadata(fn($m) => $m->title('Book')->author('Author'))
    ->addChapter('Chapter 1', $tiptapJson)
    ->buildToStream($out);

// Or load the bytes (small books, in-memory pipelines).
$bytes = $builder->buildToString();

use AdroSoftware\EpubBuilder\EpubBuilder;
use Illuminate\Http\Response;

public function downloadEpub(EpubBuilder $builder): Response
{
    $output = $builder
        ->setMetadata(fn($m) => $m->title('Book')->author('Author'))
        ->addChapter('Chapter 1', $tiptapJson)
        ->build(storage_path('app/temp/book.epub'));

    return response()->download($output->getPath(), 'book.epub', [
        'Content-Type' => 'application/epub+zip',
    ]);
}

return response()->stream(
    function () use ($builder) {
        $builder->buildToStream(fopen('php://output', 'wb'));
    },
    200,
    [
        'Content-Type'        => 'application/epub+zip',
        'Content-Disposition' => 'attachment; filename="book.epub"',
    ],
);

use Symfony\Component\HttpFoundation\BinaryFileResponse;

$output = EpubBuilder::create()
    ->setMetadata(fn($m) => $m->title('Book')->author('Author'))
    ->addChapter('Chapter 1', $tiptapJson)
    ->build();

return new BinaryFileResponse(
    $output->getPath(),
    headers: ['Content-Type' => 'application/epub+zip'],
);

use Symfony\Component\HttpFoundation\StreamedResponse;

return new StreamedResponse(
    function () use ($builder) {
        $builder->buildToStream(fopen('php://output', 'wb'));
    },
    200,
    [
        'Content-Type'        => 'application/epub+zip',
        'Content-Disposition' => 'attachment; filename="book.epub"',
    ],
);

use AdroSoftware\EpubBuilder\Contracts\NodeHandlerInterface;
use AdroSoftware\EpubBuilder\Renderers\DefaultTiptapRenderer;

final class CalloutHandler implements NodeHandlerInterface
{
    public function render(array $node, callable $renderChildren): string
    {
        $type = htmlspecialchars($node['attrs']['type'] ?? 'info', ENT_XML1 | ENT_QUOTES, 'UTF-8');
        $content = $renderChildren($node['content'] ?? []);
        return "<aside class=\"callout callout--{$type}\">{$content}</aside>\n";
    }
}

$builder = EpubBuilder::create();
$renderer = $builder->getRenderer();
if ($renderer instanceof DefaultTiptapRenderer) {
    $renderer->register('callout', new CalloutHandler());
}

use AdroSoftware\EpubBuilder\Contracts\NodeHandlerInterface;
use AdroSoftware\EpubBuilder\Epub\AssetManager;

final class UnsplashImageHandler implements NodeHandlerInterface
{
    public function __construct(private readonly AssetManager $assetManager) {}

    public function render(array $node, callable $renderChildren): string
    {
        $src = (string) ($node['attrs']['src'] ?? '');
        if ($src === '') return '';

        // AssetManager downloads remote URLs into OEBPS/images/ at zip-write time.
        // The 'jpg' hint is for URLs without a file extension in the path.
        $epubSrc = $this->assetManager->addImage($src, 'jpg');

        $alt = htmlspecialchars($node['attrs']['alt'] ?? '', ENT_XML1 | ENT_QUOTES, 'UTF-8');
        return "<figure><img src=\"{$epubSrc}\" alt=\"{$alt}\"/></figure>\n";
    }
}

$builder->getRenderer()->register('unsplashImage', new UnsplashImageHandler(
    $builder->assetManager(),
));

$renderer->override('image', new MyCdnImageHandler($builder->assetManager()));

use AdroSoftware\EpubBuilder\Contracts\MarkHandlerInterface;

final class SmallCapsMark implements MarkHandlerInterface
{
    public function render(string $content, array $mark): string
    {
        return "<span class=\"smallcaps\">{$content}</span>";
    }
}

$renderer->registerMark('smallCaps', new SmallCapsMark());

use AdroSoftware\EpubBuilder\Contracts\ContentRendererInterface;

final class MyRenderer implements ContentRendererInterface
{
    public function render(array $tiptapJson): string
    {
        // Your own rendering logic. Return a well-formed XHTML body fragment
        // (no <html>, <body> wrapper — the library wraps it).
        return $myExistingTiptapEngine->toHtml($tiptapJson);
    }
}

EpubBuilder::create()
    ->setRenderer(new MyRenderer())
    ->setMetadata(fn($m) => $m->title('Book')->author('A'))
    ->addChapter('One', $json)
    ->build();

// Replace the default with your own CSS file
$builder->setStylesheet('/path/to/my-styles.css');

// Or append additional rules on top of the default
$builder->addCss('
  body { font-family: "Iowan Old Style", Georgia, serif; }
  blockquote { font-style: italic; }
');