All files / src/shared/FileUpload utils.ts

32.43% Statements 12/37
56.25% Branches 9/16
40% Functions 2/5
33.33% Lines 12/36

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72        537x 4x   4x                                                                                     537x     3x 1x 1x               2x 2x 2x 2x     1x    
import * as pdfjsLib from "pdfjs-dist";
import { ChangeEvent, DragEvent } from "react";
import { IDropzoneProps } from "react-dropzone-uploader";
 
export const convertPdfToImage = async (fileUrl: string): Promise<string> => {
  try {
    // Let the browser handle CORS and omit credentials to avoid CORS issues with S3 presigned URLs
    const response = await fetch(fileUrl, {
      credentials: "omit",
    });
    if (!response.ok) {
      console.error(
        `Failed to fetch PDF: ${response.status} ${response.statusText}`,
      );
      return "";
    }
 
    const blob = await response.blob();
    const objectUrl = URL.createObjectURL(blob);
 
    const loadingTask = pdfjsLib.getDocument({
      url: objectUrl,
      httpHeaders: {},
      withCredentials: false,
    });
    const pdf = await loadingTask.promise;
    const page = await pdf.getPage(1);
 
    const viewport = page.getViewport({ scale: 1 });
 
    const canvas = document.createElement("canvas");
    const context = canvas.getContext("2d");
 
    if (!context) {
      console.error("Failed to get canvas 2D context.");
      return "";
    }
 
    canvas.width = viewport.width;
    canvas.height = viewport.height;
 
    await page.render({ canvasContext: context, viewport }).promise;
 
    return canvas.toDataURL("image/png");
  } catch (err) {
    console.error("Error converting PDF to image:", err);
    return "";
  }
};
 
export const getFilesFromEvent: IDropzoneProps["getFilesFromEvent"] = async (
  e: DragEvent<HTMLElement> | ChangeEvent<HTMLInputElement>,
) => {
  if (e.type === "drop") {
    const dragEvent = e as DragEvent<HTMLElement>;
    Iif (dragEvent.dataTransfer && dragEvent.dataTransfer.items) {
      const files = await Promise.all(
        Array.from(dragEvent.dataTransfer.items)
          .filter((item) => item.kind === "file")
          .map((item) => item.getAsFile()),
      );
      return files.filter((file): file is File => file !== null);
    }
  } else Eif (e.type === "change") {
    const changeEvent = e as ChangeEvent<HTMLInputElement>;
    Eif (changeEvent.target && changeEvent.target.files) {
      return Array.from(changeEvent.target.files);
    }
  }
  return [];
};