Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 11 additions & 14 deletions src/StudentsController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import path from "path";
import { PDFDocument, PDFImage } from "pdf-lib";
import qrCodeLib from "qrcode";
import { SchoolFileDTO, Student, StudentAuditLog, StudentAuditLogEntry, StudentDTO, StudentStatus } from "./types";
import { getFileTypeForBuffer } from "./utils/getFiletypeForBuffer";

export class StudentsController {
#studentsCollection: IDatabaseCollection;
Expand Down Expand Up @@ -340,21 +341,17 @@ export class StudentsController {
if (schoolLogoBase64 === undefined) return await this.getAssetImage(pdfDoc);

const bytes = Buffer.from(schoolLogoBase64, "base64");
const fistBytesAsHex = bytes.toString("hex", 0, 4);

const pdfMagicBytes = "89504e47";
if (fistBytesAsHex === pdfMagicBytes) {
const schoolLogoImage = await pdfDoc.embedPng(bytes);
return schoolLogoImage;
}

const jpgMagicBytes = "ffd8";
if (fistBytesAsHex.startsWith(jpgMagicBytes)) {
const schoolLogoImage = await pdfDoc.embedJpg(bytes);
return schoolLogoImage;
const filetype = getFileTypeForBuffer(bytes);
if (!filetype) throw new ApplicationError("error.schoolModule.onboardingInvalidLogo", "The logo is not a valid PNG or JPG file. Please check the logo and try again.");

switch (filetype) {
case "png":
const pngImage = await pdfDoc.embedPng(bytes);
return pngImage;
case "jpg":
const jpgImage = await pdfDoc.embedJpg(bytes);
return jpgImage;
}

throw new ApplicationError("error.schoolModule.onboardingInvalidLogo", "The logo is not a valid PNG or JPG file. Please check the logo and try again.");
}

private async getAssetImage(pdfDoc: PDFDocument): Promise<PDFImage | undefined> {
Expand Down
11 changes: 11 additions & 0 deletions src/utils/getFiletypeForBuffer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export function getFileTypeForBuffer(buffer: Buffer): "png" | "jpg" | undefined {
const fistBytesAsHex = buffer.toString("hex", 0, 4);

const pngMagicBytes = "89504e47";
if (fistBytesAsHex === pngMagicBytes) return "png";

const jpgMagicBytes = "ffd8";
if (fistBytesAsHex.startsWith(jpgMagicBytes)) return "jpg";

return undefined;
}