File size: 1,566 Bytes
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import type { SheetPrintSettings, Workbook } from "./types";
import { planSheetPdf } from "./sheetExport";

/** Page geometry in document pixels, before the grid applies zoom and scrolling. */
export interface SheetPageGrid {
  /** Distinct ascending page starts, always beginning at zero. */
  xs: number[];
  ys: number[];
  /** One printable page, in sheet pixels. */
  pageWidth: number;
  pageHeight: number;
  /** Margins in sheet pixels for the Page layout insets. */
  marginX: number;
  marginY: number;
}

/** Use the PDF's boundaries; invalid print settings must never take down a view. */
export const sheetPageGrid = (
  book: Workbook, sheetId: string, settings: SheetPrintSettings | undefined,
): SheetPageGrid | null => {
  try {
    const plan = planSheetPdf(book, {
      ...(settings ?? { sheetIds: [], paper: "letter", orientation: "landscape", fit: "width" }),
      sheetIds: [sheetId], from: undefined, to: undefined,
    });
    const pages = plan.pages.filter(page => page.sheetId === sheetId);
    if (!pages.length) return null;
    const scale = pages[0].scale;
    if (!Number.isFinite(scale) || scale <= 0) return null;
    return {
      xs: [...new Set(pages.map(page => page.x))].sort((a, b) => a - b),
      ys: [...new Set(pages.map(page => page.y))].sort((a, b) => a - b),
      pageWidth: plan.contentWidth / scale,
      pageHeight: plan.contentHeight / scale,
      marginX: (plan.width - plan.contentWidth) / 2 / scale,
      marginY: (plan.height - plan.contentHeight) / 2 / scale,
    };
  } catch {
    return null;
  }
};