Back to blog

Fixing JPEG EXIF Orientation, Stripping Metadata, and Building US Letter Photo PDFs in the Browser

Nov 24, 2026

How CloseoutPack parses JPEG orientation, normalizes photos on Canvas, audits Before and After by line, and exports Letter PDFs and formula-defended CSVs.

A portrait JPEG can open upright in the browser and still have sideways pixels in the file. The viewer can read the orientation instruction in EXIF. If the export path embeds the original image without applying that instruction, the report can put a sideways After photo next to an upright Before photo. CloseoutPack resolves that ambiguity at import. Each work-order line stores a normalized JPEG for each slot and, when available, a separate capture timestamp. The JPEG goes into the PDF. The timestamp helps the audit spot pairs that deserve a second look.

Read APP1 before decoding the JPEG

In photo-normalizer.ts, the scanner first checks the JPEG start-of-image bytes, FF D8. It walks markers from byte two, skips repeated FF bytes and standalone markers, and stops at start-of-scan (DA), end-of-image (D9), or an invalid segment length. Segment lengths come from a big-endian read and include the length field itself. The APP1 marker E1 can carry other formats, so the scanner also checks for the six-byte Exif\0\0 signature. The recorded payload starts at the embedded TIFF header.

function jpegExifSegments(bytes: Uint8Array): Segment[] {
  if (bytes[0] !== 0xff || bytes[1] !== 0xd8) return [];
  const segments: Segment[] = [];
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
  let offset = 2;
  while (offset + 3 < bytes.length && bytes[offset] === 0xff) {
    const start = offset;
    while (bytes[offset] === 0xff) offset++;
    const marker = bytes[offset++];
    if (marker === 0xda || marker === 0xd9 || offset + 2 > bytes.length) break;
    if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) continue;
    const length = view.getUint16(offset);
    const end = offset + length;
    if (length < 2 || end > bytes.length) break;
    if (
      marker === 0xe1 &&
      length >= 8 &&
      view.getUint32(offset + 2) === 0x45786966 &&
      view.getUint16(offset + 6) === 0
    )
      segments.push({ start, end, payload: offset + 8 });
    offset = end;
  }
  return segments;
}

The TIFF header has its own byte order. The parser accepts II or MM, checks the magic value 42, and uses the first directory offset to read a count followed by 12-byte entries. It checks that the directory fits inside that segment before indexing it. Orientation is tag 0x0112 in the first directory. It must be one SHORT, stored inline at entry offset eight. Values 1 through 8 map to the eight supported transforms. The starting value is 1, so unfamiliar data leaves the default in place unless the parser finds a valid orientation.

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

For the audit, the parser also reads DateTimeOriginal from the EXIF subdirectory, falling back to the main directory's DateTime when the former is empty. It looks for the corresponding offset tag and accepts an offset shaped like ±HH:MM. When that field is absent or fails the shape check, the parser appends Z. A date the runtime can parse is converted to an ISO string. This UTC assumption gives the code a comparable value, but the camera's clock and EXIF offset still determine whether the resulting chronology is useful. No filesystem timestamp fills an empty EXIF date.

Decode once, then bake the transform into the pixels

The import path accepts JPEG, PNG, and WebP with a nonzero size of at most 24 MiB. Only JPEG runs through the EXIF segment scanner. CloseoutPack first builds a decode blob without the recognized EXIF APP1 segments, so the decoder sees the raw JPEG orientation. It then paints a new image into a Canvas and encodes that Canvas as JPEG. The original file is left intact.

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 }));
try {
  const scale = Math.min(
    1,
    MAX_DIMENSION / Math.max(bitmap.width, bitmap.height)
  );
  const w = Math.max(1, Math.round(bitmap.width * scale));
  const h = Math.max(1, Math.round(bitmap.height * scale));
  const canvas = document.createElement('canvas');
  canvas.width = orientation >= 5 ? h : w;
  canvas.height = orientation >= 5 ? w : h;
  const ctx = canvas.getContext('2d');
  if (!ctx) throw new Error('Canvas is unavailable');
  ctx.fillStyle = '#fff';
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  const matrix: [number, number, number, number, number, number][] = [
    [1, 0, 0, 1, 0, 0],
    [-1, 0, 0, 1, w, 0],
    [-1, 0, 0, -1, w, h],
    [1, 0, 0, -1, 0, h],
    [0, 1, 1, 0, 0, 0],
    [0, 1, -1, 0, h, 0],
    [0, -1, -1, 0, h, w],
    [0, -1, 1, 0, 0, w],
  ];
  ctx.setTransform(...matrix[orientation - 1]);
  ctx.drawImage(bitmap, 0, 0, w, h);
  return { photo: canvas.toDataURL('image/jpeg', 0.82), takenAt };
} finally {
  bitmap.close();
}

The w and h values describe the scaled source rectangle before rotation. The scale caps its longest side at 1,400 pixels and keeps smaller images at their original size. Orientations 5 through 8 exchange the canvas axes. Each Canvas matrix maps (x, y) to (ax + cy + e, bx + dy + f). For orientation 6, the mapping is (h - y, x), which rotates the rectangle clockwise and translates it back into the new bounds. The mirrored cases need their own matrices too. A white fill precedes the transform, so transparent pixels in PNG and WebP land on white in the JPEG.

The export uses the pixels produced by drawImage and the browser's JPEG encoder at quality 0.82. The new JPEG contains freshly encoded pixels, independent of the source camera tags and GPS metadata. The retained capture time is a separate field in the browser draft. Pixels are still pixels: an address visible on a door or a date burned into an image will remain visible. The bitmap is closed in a finally block even if drawing or encoding fails.

Audit the work-order line

In audit.ts, each finding carries the work-order line's internal item ID and its displayed line number when applicable. A missing Before and a missing After are separate findings. With both images present, the audit compares their stored capture times and flags a possible swap only when Before sorts strictly later than After. Equal timestamps do not trigger it. A null or invalid timestamp parses to NaN, which also makes the comparison false.

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');
if (item.status !== 'completed') flag(item.status);

That comparison can identify a likely reversal, but it cannot determine whether the photos depict the same room or whether work is finished. The operator can review the pair and invoke the explicit swap, which exchanges each photo together with its timestamp. The line number, notes, scope, and status stay with the item. A separate pass counts trimmed, uppercased line numbers so entries such as L-03 and l-03 are flagged as duplicates. That check gives the two exports a usable reference back to the same work.

Serialize every CSV field through the same function

The audit CSV contains a header and a row for each item, plus a row for work-order-level findings when present. Multiple findings for one line are joined with a vertical bar padded with spaces inside its findings cell. The CSV writer applies its escaping helper to every field, including line numbers and notes, then joins rows with CRLF and prepends a UTF-8 BOM.

export function csvCell(value: string): string {
  const safe = /^\s*[\t\r\n=+\-@]/u.test(value) ? `'${value}` : value;
  return `"${safe.replaceAll('"', '""')}"`;
}

Doubling internal quotes and enclosing each value in double quotes preserve the boundaries of a field. Formula interpretation is a separate concern once a spreadsheet reads that field. The leading test looks for tabs, carriage returns, newlines, or =, +, -, and @ at the start or after whitespace. Matching values receive a leading apostrophe inside the quoted cell. That is a mitigation for the characters the code checks. Behavior after a spreadsheet has saved and reopened the file depends on the application, and this helper has no explicit full-width prefix handling. OWASP's CSV Injection guidance

Lay out Letter pages in points

In export.ts, letter is [612, 792] and the page factory calls pdf.addPage([...letter]). At 72 points per inch, that is 8.5 by 11 inches in portrait. The cover includes the work-order and invoice references and counts completed lines separately from open or blocked lines. Each item starts a fresh page. Its note can continue onto another page with the item heading repeated.

export const letter = [612, 792] as const;
async function addPage() {
  const page = pdf.addPage([...letter]);
  page.drawRectangle({ x: 0, y: 782, width: 612, height: 10, color: teal });
  page.drawLine({
    start: { x: 44, y: 58 },
    end: { x: 568, y: 58 },
    thickness: 1,
    color: rule,
  });
  await draw(page, 'CloseoutPack', 44, 736, 15, true);
  await draw(page, String(pdf.getPageCount()), 548, 39, 10);
  return page;
}
for (const [index, side] of (['before', 'after'] as const).entries()) {
  const x = 44 + index * 268;
  await draw(page, labels[side], x, y - 22, 12, true);
  const photo = side === 'before' ? item.beforePhoto : item.afterPhoto;
  const bottom = y - 270;
  page.drawRectangle({
    x,
    y: bottom,
    width: 256,
    height: 236,
    borderColor: rule,
    borderWidth: 1,
  });
  if (photo) {
    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,
    });
  } else {
    await draw(page, labels.missing, x + 12, bottom + 114, 11);
  }
}

The photo frames start at x = 44 and x = 312 and measure 256 by 236 points. The PDF scales each embedded JPEG proportionally to fit inside 254 by 234 points and centers it in the corresponding frame. A missing slot gets the localized placeholder in that same frame, keeping both columns and their labels visible for review.

Standard Helvetica and Helvetica Bold handle WinAnsi text. The renderer first asks the chosen font to encode the line. If encoding fails, it draws that line on a browser Canvas and embeds it as PNG at half the Canvas dimensions. The text wrapper also uses Canvas measurements for paragraphs the PDF font cannot encode.

const font = bold ? boldFont : regular;
if (!value) return;
if (fitsFont(font, value)) {
  page.drawText(value, { x, y, size, font, color: ink });
  return;
}
const { canvas, context, font: browserFont } = rasterContext(size, bold);
canvas.width = Math.ceil(context.measureText(value).width) + 4;
canvas.height = size * 3;
context.font = browserFont;
context.fillStyle = '#1c2929';
context.fillText(value, 0, size * 2);
const image = await pdf.embedPng(canvas.toDataURL('image/png'));
page.drawImage(image, {
  x,
  y: y - size / 2,
  width: canvas.width / 2,
  height: canvas.height / 2,
});

The raster path can render Chinese when the browser has the necessary glyphs. Rasterized lines are images, so they cannot be selected or searched as PDF text. The PDF writer also sets its own title and creator and fixes the creation and modification dates. Source image metadata and document metadata are separate. Browser font availability and rendering can still affect rasterized output.

Follow a line from preview to export

The workbench keeps photo processing, draft storage, and file generation in the browser. The server authorizes paid export access with the project ID, pair count, and artifact type. File generation uses the local draft. The PDF is the visual handoff, while its companion audit CSV gives the reviewer a line-numbered list to work through.

The $0 preview covers one work order and displays the watermarked cover and up to two watermarked, complete photo pairs. Open the Job Photo Report workbench

A $9 One-Time Job Pass unlocks the full PDF and CSV for one work order (up to 30 photo-bearing work-order lines / photo pairs) with repeat exports of that job. Pro costs $9/month or $69/year and includes 10 new jobs per UTC calendar month plus two saved property templates. See CloseoutPack pricing