Rotate JPEG EXIF Once, Then Build a US Letter PDF in the Browser
A phone can save a portrait photo with landscape pixels and set EXIF orientation to 6. The browser can display it upright by applying that tag. An export pipeline that assumes the pixels are already upright can produce a
A phone can save a portrait photo with landscape pixels and set EXIF orientation to 6. The browser can display it upright by applying that tag. An export pipeline that assumes the pixels are already upright can produce a sideways PDF. Applying a Canvas rotation to an already oriented decode can also rotate twice.
CloseoutPack fixes this at the photo input. It reads the JPEG header, decodes a copy without its EXIF APP1 segments, and paints the orientation into a new JPEG. The PDF generator uses that copy. The excerpts below come from src/lib/closeout/.
Read the orientation, then remove the decoder's copy
The JPEG scanner walks markers from FF D8 to the start of compressed scan data, checking for FF E1 and the six-byte EXIF signature. In the TIFF payload, the byte-order flag determines how the directory is read. Tag 0x0112 must contain one SHORT in the range 1–8.
const main = tags(long(4));
const orient = main.get(0x0112);
if (orient !== undefined && short(orient + 2) === 3 && long(orient + 4) === 1) {
const value = short(orient + 8);
if (value >= 1 && value <= 8) orientation = value;
}
The parser also extracts a capture time when it can. Before calling createImageBitmap, the normalizer leaves out the EXIF segments it found. That keeps the browser from applying the orientation tag before the app applies its own matrix.
const bytes = new Uint8Array(await file.arrayBuffer());
const segments = file.type === 'image/jpeg' ? jpegExifSegments(bytes) : [];
const { orientation, takenAt } = readExif(bytes, segments);
// Decode without JPEG EXIF so the browser cannot apply the transform twice.
const parts: BlobPart[] = [];
let offset = 0;
for (const segment of segments) {
parts.push(bytes.subarray(offset, segment.start));
offset = segment.end;
}
parts.push(bytes.subarray(offset));
const bitmap = await createImageBitmap(new Blob(parts, { type: file.type }));
Canvas draws the scaled bitmap onto white and encodes a fresh JPEG at quality 0.82. The longest output edge is capped at 1,400 pixels. For orientations 5–8, the canvas dimensions swap. Orientation 6 uses [0, 1, -1, 0, h, 0], which maps the source point (x, y) to (h - y, x).
ctx.setTransform(...matrix[orientation - 1]);
ctx.drawImage(bitmap, 0, 0, w, h);
return { photo: canvas.toDataURL('image/jpeg', 0.82), takenAt };
The encoded JPEG does not inherit source EXIF or GPS tags. The time that was read for the audit is stored separately in the draft.
Use the timestamps as a review cue
A Before photo dated later than After is worth checking. The audit requires both photos, and an absent or invalid date makes the comparison false. Missing photos have their own findings. The swap operation keeps each timestamp with its photo and preserves the line number.
if (!item.beforePhoto) flag('missingBefore');
if (!item.afterPhoto) flag('missingAfter');
if (
item.beforePhoto &&
item.afterPhoto &&
Date.parse(item.beforeTakenAt ?? '') > Date.parse(item.afterTakenAt ?? '')
)
flag('swappedPhotos');
The audit CSV writes each cell through the same function. Double quotes preserve cell boundaries. An apostrophe prefix mitigates formula interpretation for the prefixes checked by the helper. Verify behavior for the spreadsheet and save/reopen workflow in use. OWASP CSV Injection
export function csvCell(value: string): string {
const safe = /^\s*[\t\r\n=+\-@]/u.test(value) ? `'${value}` : value;
return `"${safe.replaceAll('"', '""')}"`;
}
Fit pictures and text onto Letter pages
The PDF uses pdf.addPage([...letter]) with letter = [612, 792]. Each work-order item starts on its own page with Before on the left and After on the right. The frame is 256 × 236 points. This excerpt shows what happens when a photo is present.
const image = await pdf.embedJpg(photo);
const size = image.scaleToFit(254, 234);
page.drawImage(image, {
x: x + (256 - size.width) / 2,
y: bottom + (236 - size.height) / 2,
...size,
});
The text path tries the standard Helvetica font first. When font.encodeText cannot encode a line in WinAnsi, the exporter paints it onto a browser Canvas and embeds it as PNG. Browser fonts supply the glyphs, and the resulting line behaves as an image in the PDF.
The $0 workbench preview shows a watermarked cover and the first two photo pairs. Full PDF and CSV exports unlock with a $9 One-Time Job Pass (up to 30 photo-bearing lines) or Pro ($9/month or $69/year). Try the Job Photo Report workbench
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.