Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
NishantGupta2325 committed Sep 30, 2024
1 parent a40629e commit cb8aa40
Show file tree
Hide file tree
Showing 3 changed files with 198 additions and 1 deletion.
107 changes: 107 additions & 0 deletions src/app/adminupload/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ const Upload: React.FC = () => {
useState<(CloudinaryUploadResult | string | undefined)[]>();
const [file, setFile] = useState<File | undefined>();
const [error, setError] = useState<string | null>(null);
const [files, setFiles] = useState<File[]>([]);
const [pdfUrl, setPdfUrl] = useState<string | null>(null);


useEffect(() => {
async function makeTage() {
Expand Down Expand Up @@ -173,6 +176,64 @@ const Upload: React.FC = () => {
}
};

const handleFileChangeMerged = (e: React.ChangeEvent<HTMLInputElement>) => {
const selectedFiles = Array.from(e.target.files || []);
setFiles(selectedFiles);
};

const handleSubmitMerged = async (e: React.FormEvent) => {
e.preventDefault();
console.log(files);
if (files.length === 0) {
alert('Please upload at least one file');
return;
}

const formData = new FormData();
files.forEach((file) => {
formData.append('files', file);
});

try {
const response = await axios.post('/api/admin/imgtopdf', formData);
setPdfUrl(response.data.url);
} catch (error: unknown) {
if (error instanceof AxiosError) {
const status = error.response?.status;
if (status === 401) {
router.push("/papersadminlogin");
} else {
toast.error("Failed to upload papers.");
}
} else {
toast.error("An unexpected error occurred");
}
}
};

const handleDeleteMerged = async () => {
if (!pdfUrl) return;

try {
const response = await axios.delete('/api/admin/imgtopdf', {
data: { filePath: pdfUrl },
});
alert(response.data.message);
setPdfUrl(null);
} catch (error: unknown) {
if (error instanceof AxiosError) {
const status = error.response?.status;
if (status === 401) {
router.push("/papersadminlogin");
} else {
toast.error("Failed to upload papers.");
}
} else {
toast.error("An unexpected error occurred");
}
}
};

async function completeUpload() {
const token = localStorage.getItem("token");
if (!token) {
Expand Down Expand Up @@ -353,6 +414,52 @@ const Upload: React.FC = () => {
</div>
</div>
</div>
<div className="flex">
<div className="w-full max-w-md rounded bg-white p-8 shadow-md">
<h1 className="mb-6 text-2xl font-bold">
Upload Images to Convert to PDF
</h1>
<form onSubmit={handleSubmitMerged}>
<div className="mb-4">
<label className="mb-2 block font-semibold text-gray-700">
Images:
</label>
<input
type="file"
accept="image/*"
multiple
onChange={handleFileChangeMerged}
className="block w-full cursor-pointer rounded-lg border border-gray-300 bg-gray-50 text-sm text-gray-900 focus:outline-none"
/>
</div>
<button
type="submit"
className="w-full rounded bg-blue-500 px-4 py-2 font-semibold text-white hover:bg-blue-600"
>
Convert to PDF
</button>
</form>
{pdfUrl && (
<div className="mt-6 text-center">
<h2 className="mb-2 text-xl font-semibold">PDF Created</h2>
<a
href={pdfUrl}
target="_blank"
rel="noopener noreferrer"
className="mb-4 inline-block text-blue-500 hover:text-blue-600"
>
Download PDF
</a>
<button
onClick={handleDeleteMerged}
className="w-full rounded bg-red-500 px-4 py-2 font-semibold text-white hover:bg-red-600"
>
Delete PDF
</button>
</div>
)}
</div>
</div>
</div>
<div className="mt-6 w-[65%]">
<h2 className="mb-4 text-xl font-semibold">Uploaded Assets:</h2>
Expand Down
90 changes: 90 additions & 0 deletions src/app/api/admin/imgtopdf/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { NextApiRequest, NextApiResponse } from "next";
import { PDFDocument, rgb } from "pdf-lib";
import multer from "multer";
import fs from "fs";
import path from "path";
import { promisify } from "util";
import { NextResponse } from "next/server";
import { writeFile } from "fs/promises";

const upload = multer({ dest: "uploads/" });

const uploadMiddleware = promisify(upload.array("files"));

export async function POST(req: Request, res: NextApiResponse) {
await uploadMiddleware(req as any, res as any);

const formData = await req.formData();
const files = formData.getAll("files");

if (!files) {
return NextResponse.json({ error: "No files received." }, { status: 400 });
}

try {
const pdfDoc = await PDFDocument.create();

for (const file of files) {
console.log(file);
const fileBlob = new Blob([file]);
const imgBytes = Buffer.from(await fileBlob.arrayBuffer());
let img;
if (file instanceof File) {
if (file.type === "image/png") {
img = await pdfDoc.embedPng(imgBytes);
} else if (file.type === "image/jpeg" || file.type === "image/jpg") {
img = await pdfDoc.embedJpg(imgBytes);
} else {
continue; // Skip unsupported file types
}
const page = pdfDoc.addPage([img.width, img.height]);
page.drawImage(img, {
x: 0,
y: 0,
width: img.width,
height: img.height,
});
}
}

const pdfBytes = await pdfDoc.save();
const pdfPath = path.join(process.cwd(), "public", "merged.pdf");
await writeFile(pdfPath, pdfBytes);

return NextResponse.json(
{ url: `/${path.basename(pdfPath)}` },
{ status: 200 },
);
} catch (error) {
return NextResponse.json(
{ error: "Failed to process PDF" },
{ status: 500 },
);
}
}

export async function DELETE(req: Request, res: NextApiResponse) {
const filePath = path.resolve("./public/merged.pdf");
try {
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
return NextResponse.json(
{ message: "Deleted watermarked PDF file successfully" },
{ status: 200 },
);
} else {
return NextResponse.json(
{ error: "Watermarked PDF file not found" },
{ status: 400 },
);
}
} catch (error) {
console.error("Error deleting PDF file:", error);
return NextResponse.json(
{
error: "Failed to delete watermarked PDF file",
},
{ status: 500 },
);
}
}
2 changes: 1 addition & 1 deletion src/app/api/admin/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export async function POST(req: Request) {
const response = (await cloudinary.v2.uploader.multi({
urls: urls,
format: "pdf",
density: 40,
density: 50,
})) as ConverttoPDFResponse;
console.log("Result:", response);
finalUrl = response.url;
Expand Down

0 comments on commit cb8aa40

Please sign in to comment.