Files
online-energieausweis/src/lib/pdf/elements/Layout.ts
2025-04-01 09:35:15 -03:00

79 lines
1.5 KiB
TypeScript

import { PDFPage } from "pdf-lib";
import { PDFElement, Size } from "./PDFElement.js";
export type Margin = {
top: number,
left: number,
right: number,
bottom: number
}
export type Padding = Margin;
export class Layout extends PDFElement {
public margin: Margin
public padding: Padding
protected _height: Size = "auto";
protected _width: Size = "auto";
public children: PDFElement[];
constructor(children: PDFElement[] = [], options?: {
margin?: Margin,
padding?: Padding
}) {
super()
this.children = children
this.margin = options?.margin || {
bottom: 0,
left: 0,
right: 0,
top: 0
};
this.padding = options?.padding || {
bottom: 0,
left: 0,
right: 0,
top: 0
};
}
get height(): number {
if (typeof this._height === "number") {
return this._height;
}
let currentHeight = 0
for (const child of this.children) {
currentHeight += child.height;
}
return currentHeight;
}
set height(value: number) {
this._height = value;
}
async draw(page: PDFPage, x: number, y: number) {
let currentY = y - this.margin.top - this.padding.top;
for (const child of this.children) {
await child.draw(page, x + this.margin.left + this.padding.left, currentY);
currentY -= child.height + child.margin.top + child.margin.bottom;
}
}
addChild(...children: PDFElement[]): void {
this.children.push(...children)
}
}
export function layout(...args: ConstructorParameters<typeof Layout>) {
return new Layout(...args);
}