DEV Community

Matt
Matt

Posted on

Turning a Build Log Into a Printed Book With Plain CSS

I run Boat Build Log, a free site where people keep a build log of the wooden boat they're building at home. A finished log is a couple of years of somebody's evenings: hundreds of photos, the hours, what the epoxy cost, the day the hull got flipped.

I've heard the same thing from a lot of builders. They want that log in the shop, not on a website. On a tablet with epoxy on their gloves, or printed and in a binder next to the plans. And a few of them want the version that outlives the site: something bound that sits on a shelf.

So every build now has a "book" button. This post covers how it works, which is mostly CSS Paged Media and a small Laravel controller, and the two bugs that made every printed copy come out wrong for a while.

The setup

Piece Version
Laravel 13
PHP 8.3+
MySQL 8.0
Renderer Chrome's own print engine (131+)

Why the browser renders the PDF, not the server

My first instinct was a server-side PDF library. It didn't survive contact with the photos.

The site stores images as WebP, which the pure-PHP PDF libraries can't read at all. A server build would mean decoding every photo through Imagick and holding the whole document in memory. That's workable for an 86-photo log. It's exactly the thing that falls over on the multi-year logs this site exists to keep.

The browser, on the other hand, streams hundreds of photos without noticing, keeps full resolution, costs the server nothing, and works the same on iOS and Android. "Save as PDF" is already the default destination in Chrome's print dialog. So the book is just an HTML page at /builds/{slug}/book with a print stylesheet, and the button calls window.print().

The controller is short. The one thing I was careful about is visibility: the book has to follow the build page's rules, not a looser copy of them.

public function printable(Request $request, Build $build)
{
    // A draft can be opened by its owner, or by anyone holding the share link.
    $viaToken = $request->query('token')
        && hash_equals($build->share_token, (string) $request->query('token'));

    if (! $viaToken) {
        $this->authorize('view', $build);   // same policy as the build page
    }

    // Everything eager-loaded: a book that lazy-loads is a few hundred
    // queries on a long log.
    $entries = $build->entriesInOrder()
        ->with(['media', 'phase', 'author', 'bookComments.user'])
        ->get();

    $book = new BookData($build, $entries, $materials);
    // ...
}
Enter fullscreen mode Exit fullscreen mode

An export route that forgot the policy check would hand out complete copies of unpublished builds.

Chapters without reordering anything

The first version was a utility: a title page, each entry on its own sheet, an expense table. A log of short days became a stack of quarter-full pages.

The rebuild treats it like a book: cover, title page, a spec sheet for the design, a numbers page, contents, chapters, the log, what it cost, launch, colophon.

Chapters were the interesting part. A log is told in the order it happened, and it has to stay that way. Somebody who goes back to fairing in month nine should get that entry in its place, not a second "Fairing" chapter and not a shuffled timeline. So a chapter opens wherever a build phase first appears, and nothing moves:

public function chapteredEntries(): Collection
{
    $seen = [];

    return $this->entries->map(function (Entry $entry) use (&$seen) {
        $slug = $entry->phase?->slug;

        // An untagged entry never opens a chapter. It stays in whatever
        // chapter it fell inside.
        $opens = $slug !== null && ! isset($seen[$slug]);

        if ($opens) {
            $seen[$slug] = true;
        }

        return [
            'entry'   => $entry,
            'chapter' => $opens ? $this->chapter($entry->phase) : null,
        ];
    });
}
Enter fullscreen mode Exit fullscreen mode

Phases are seeded in build order, so the chapters come out in sequence on their own.

The numbers page has one figure the builder can't already know: how their hours compare with everyone else who finished the same design. That comparison is held back until at least three people have finished it, because a median of two reads as authority and isn't one.

Running heads with no JavaScript library

I went in assuming I'd need a pagination polyfill for page numbers and running heads. That was true a few years ago. Chrome has supported named pages since 85 and @page margin boxes since 131, so the page numbers are the browser's own work:

@page {
  size: Letter;
  margin: 20mm 20mm 22mm 20mm;

  @bottom-center {
    content: counter(page);      /* real page numbers, drawn by Chrome */
    font-family: Georgia, serif;
    font-size: 9pt;
  }

  @top-right {
    content: "boatbuildlog.com"; /* where the rest of these logs live */
    font-size: 7.5pt;
  }
}
Enter fullscreen mode Exit fullscreen mode

The one gap is string-set, the property that would let a chapter title flow into the page margin. No browser implements it. Turns out I didn't need it, because Blade knows every chapter title at render time. So the template just writes one named @page rule per chapter, and each entry says which page it belongs to:

@foreach($chapters as $chapter)
@page chapter-{{ $chapter['slug'] }} {
  @top-center { content: "{{ addslashes($chapter['label']) }}"; }
}
@endforeach

<article class="bk-entry"
  @if($entry->phase) style="page: chapter-{{ $entry->phase->slug }}" @endif>
Enter fullscreen mode Exit fullscreen mode

A chapter title is only "dynamic" if you don't know it when you render the page. On the server, you always do.

What went wrong: every book printed at 77%

This is the part I'd want to read if I were building the same thing.

After the rebuild, every printed book came out scaled down, sitting small in the top corner of the page inside a white band. Cover and all. There turned out to be two causes stacked on top of each other.

Bug one: the paper size

The stylesheet said size: A4 and nothing else. I assumed picking Letter in Chrome's print dialog would override it. It doesn't. With "Save as PDF", Chrome takes the page size from the CSS, not from the paper dropdown in its own dialog. So the PDF came out A4, and printing that on Letter paper shrank it to fit.

The fix was to make Letter the default in the stylesheet (so it's correct with JavaScript off) and add a small paper chooser that writes an A4 override into an empty <style> tag:

function applyPaper(paper) {
  if (!PAPERS[paper]) { paper = 'letter'; }

  // The cover and screen preview size themselves from this attribute.
  document.documentElement.setAttribute('data-paper', paper);

  // @page size can't be a custom property, so write the rule itself.
  var sheet = document.getElementById('bk-paper');
  if (sheet) {
    sheet.textContent = paper === 'letter' ? '' : '@page { size: A4; }';
  }
  return paper;
}
Enter fullscreen mode Exit fullscreen mode

The first guess comes from the region in navigator.languages (US, Canada, Mexico and a short list of others get Letter, everyone else gets A4), and the choice is remembered in localStorage inside a try/catch, since private windows throw instead of returning null.

That fix shipped with its own small bug, too. I looked the chooser up with [data-paper], and applyPaper puts that same attribute on <html>. On a re-query <html> matched first. The follow-up commit changed the selector to select[data-paper]. One line, and a good reminder not to reuse an attribute name for two jobs.

Bug two: a negative margin pushed the page wider than the paper

Fixing the paper size helped, but books still printed small. The bigger cause was my layout for the marginalia.

Each entry's date and hours sit in a narrow band beside the text, like a note in the margin of a workshop notebook. I'd built that band out of page margin: a wide 48mm outer margin, with the note pulled into it using margin-right: -44mm.

It looked right on screen. It printed wrong. A negative margin doesn't move a box into the page margin. It moves it outside the page, and the document then measures wider than the paper. Chrome's answer to a document wider than the paper is to scale the whole thing down to fit. I measured it at 76.85% on the books I checked.

The fix was to stop borrowing from the page margin at all. Margins are even now, the band is padding inside the page, and the note is pulled into that padding:

.bk-entry-meta {
  float: right;
  width: 38mm;
  /* Pull into the band, which is padding on the entry, so the note
     sits beside the column and still inside the page. */
  margin-right: calc(0mm - var(--bk-band));
  font-size: 8pt;
}
Enter fullscreen mode Exit fullscreen mode

After that, the page box measured exactly 816 x 1056 CSS px (612 x 792 pt, which is Letter), the cover photo went edge to edge, and the content drew at 1:1. The mirrored left/right page rules went away with it, since there's no wide side left to mirror.

Because this one is easy to reintroduce, there's a test that reads the stylesheet and fails if anything hangs outside the page:

public function test_nothing_hangs_outside_the_printed_page(): void
{
    $css = file_get_contents(public_path('css/book.css'));

    $this->assertStringNotContainsString('margin-right: -', $css);
    $this->assertStringNotContainsString('margin-left: -', $css);
    $this->assertStringContainsString('margin: 20mm 20mm 22mm 20mm;', $css);
}
Enter fullscreen mode Exit fullscreen mode

It's blunt, but it guards a mistake that cost me every printed book.

Photos keep their own shape

One more thing measuring caught that reading the CSS didn't. The old export locked every photo to a 4:3 box with object-fit: contain, which letterboxed every portrait shot in a gray frame. On a boat build a great many photos are portrait: frames, stems, someone standing in the hull.

My first fix used width: 100% with a max-height cap. Sixteen of 86 photos in one log still came out a different shape from the file. The cap made the box a shape the photo wasn't, and object-fit padded the difference. Same letterboxing, from the other direction.

.bk-photos img {
  display: block;
  width: auto;          /* let the width shrink instead of the box */
  max-width: 100%;
  max-height: 150mm;    /* a full-width portrait would run off the page */
  margin: 0 auto;
}
.bk-photos figure { break-inside: avoid; }  /* never split a photo */
Enter fullscreen mode Exit fullscreen mode

Two maximums and an auto width, and every photo keeps its own proportions. If you want to see what these logs look like before they're books, the wooden boat build logs page has all of them.

Wrapping up

The short version: let the browser do the PDF, let Blade write the per-chapter @page rules that string-set would have given you, and never pull anything past the page edge with a negative margin. Then measure the printed output, because the screen preview will lie to you.

Feel free to borrow any of this for your own print exports. And if you're building a boat yourself, come keep the log at boatbuildlog.com. You'll get the book at the end.

Top comments (0)