Merge pull request #9 from theoleuthardt/feat/doc-converter

feat: doc-converter implemented
This commit is contained in:
Theo Leuthardt 2025-02-18 10:18:25 +01:00 committed by GitHub
commit e348ea2aa9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 340 additions and 138 deletions

View file

@ -6,7 +6,7 @@ import { colorConvert } from "./src/routes/colorconvert.route";
const app = Fastify({ logger: true });
app.register(cors, { origin: "*" });
app.register(cors, { origin: "*", exposedHeaders: 'Content-Disposition' });
app.register(multipart);
app.register(libreConvert);
app.register(colorConvert);

View file

@ -1,33 +1,65 @@
import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import * as libre from "libreoffice-convert";
import { promisify } from "util";
import { MultipartValue } from "@fastify/multipart";
const libreConvertAsync = promisify(libre.convert);
const mimeTypes: { [key: string]: string } = {
'pdf': 'application/pdf',
'html': 'text/html',
'doc': 'application/msword',
'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'txt': 'text/plain',
'rtf': 'application/rtf',
'odt': 'application/vnd.oasis.opendocument.text',
'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'xls': 'application/vnd.ms-excel',
'ods': 'application/vnd.oasis.opendocument.spreadsheet',
'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'ppt': 'application/vnd.ms-powerpoint',
'odp': 'application/vnd.oasis.opendocument.presentation'
};
export async function libreConvert(app: FastifyInstance) {
app.post(
"/api/libre-convert",
async (request: FastifyRequest, reply: FastifyReply) => {
app.post("/api/libre-convert", async (request: FastifyRequest, reply: FastifyReply) => {
try {
const data = await request.file();
if (!data) {
return reply.status(400).send({ error: "No file uploaded!" });
const parts = request.parts();
let fileBuffer: Buffer | null = null;
let outputFileExt = "";
for await (const part of parts) {
if (part.type === "file") {
fileBuffer = await part.toBuffer();
} else if (part.fieldname === "outputFormat" && part.type === "field") {
outputFileExt = (part as MultipartValue<string>).value;
console.log("Output format:", outputFileExt);
}
}
const ext = ".pdf";
const format = ext.substring(1);
const fileBuffer = await data.toBuffer();
if (!fileBuffer) {
return reply.status(400).send({ error: "No file uploaded!" });
}
if (!outputFileExt) {
return reply.status(400).send({ error: "No output format provided!" });
}
if (!outputFileExt.startsWith(".")) {
outputFileExt = "." + outputFileExt;
}
const pdfBuffer = await libreConvertAsync(fileBuffer, ext, undefined);
const format = outputFileExt.substring(1);
const mimeType = mimeTypes[format] || 'application/octet-stream';
const convertedBuffer = await libreConvertAsync(fileBuffer, outputFileExt, undefined);
reply
.header("Content-Type", "application/" + format)
.header("Content-Disposition", "attachment; filename=converted" + ext)
.send(pdfBuffer);
.header("Content-Type", mimeType)
.header("Content-Disposition", `attachment; filename="converted${outputFileExt}"`)
.send(convertedBuffer);
} catch (error) {
console.error("Convert error:", error);
reply.status(500).send({ error: "Error while converting!" });
}
},
);
});
}

View file

@ -4,7 +4,7 @@ import { toolLinks } from "@/constants";
export const metadata: Metadata = {
title: toolLinks[0].title,
description: "Converter for documents to pdf format!",
description: "Converter for documents!",
};
export default function RootLayout({

View file

@ -1,26 +1,50 @@
"use client";
import React, { useState } from "react";
import Navbar from "../../components/Navbar";
import Footer from "../../components/Footer";
import Button from "../../components/Button";
import Link from "next/link";
import { ChevronDown, ChevronUp } from "lucide-react";
import Dropdown from "@/components/Dropdown";
import { FileFormatsTable, outputFileFormats } from "@/constants";
export default function Home() {
export default function DocConverter() {
const [file, setFile] = useState<File | null>(null);
const [downloadUrl, setDownloadUrl] = useState<string>("");
const [loading, setLoading] = useState(false);
const [tableOpen, setTableOpen] = useState(false);
const [filteredOptions, setFilteredOptions] = useState<string[]>([]);
const [selectedOutputFormat, setSelectedOutputFormat] = useState<string | "">(
"",
);
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
if (event.target.files && event.target.files.length > 0) {
setFile(event.target.files[0]);
const selectedFile = event.target.files[0];
const fileExtension = selectedFile.name.split(".").pop()?.toLowerCase();
const isSupported = outputFileFormats.some((format) =>
format.input.toLowerCase().includes(fileExtension || ""),
);
if (!isSupported) {
console.error("Not supported file uploaded!");
alert("File format not supported!");
event.target.value = "";
return;
}
setFile(selectedFile);
setDownloadUrl("");
const matchedFormat = outputFileFormats.find((format) =>
format.input.toLowerCase().includes(fileExtension || ""),
);
setFilteredOptions(matchedFormat ? matchedFormat.output : []);
}
};
const convertToPdf = async () => {
const convertDoc = async () => {
if (!file) {
alert("No file selected");
return;
@ -28,6 +52,7 @@ export default function Home() {
const formData = new FormData();
formData.append("file", file);
formData.append("outputFormat", selectedOutputFormat);
setLoading(true);
@ -45,7 +70,9 @@ export default function Home() {
}
const blob = await response.blob();
console.log("Blob:", blob);
const url = window.URL.createObjectURL(blob);
console.log("Download URL:", url);
setDownloadUrl(url);
} catch (error) {
console.error("Error while converting:", error);
@ -56,16 +83,31 @@ export default function Home() {
};
return (
<div className="h-screen w-screen bg-black text-white font-noto flex flex-col items-center">
<div className="w-screen h-auto min-h-screen bg-black text-white font-noto flex flex-col items-center">
<Navbar renderHomeLink={true} />
<div className="w-screen h-screen flex flex-col items-center justify-center">
<div className="w-screen h-auto min-h-[calc(100vh-80px-60px)] flex flex-1 flex-col items-center justify-center">
<h2 className="text-5xl font-bold text-white mb-16">doc-converter</h2>
<div className="h-36 flex flex-row items-center justify-center gap-4">
<input
type="file"
className="border-2 border-white p-3 rounded-xl text-center text-white"
className="h-16 border-2 border-white p-3 rounded-xl text-2xl text-center text-white"
id="documentUpload"
onChange={handleFileChange}
/>
<Dropdown
content={
file
? `Convert to: ${selectedOutputFormat}`
: "output file format"
}
options={filteredOptions.length > 0 ? filteredOptions : [""]}
onClick={(event) => {
const selectedFormat =
event.currentTarget.textContent?.trim() || "";
setSelectedOutputFormat(selectedFormat);
}}
/>
</div>
<div className={"flex flex-row items-center gap-4 mt-4 mb-16"}>
{downloadUrl ? (
<Link id="downloadPDF" href={downloadUrl}>
@ -80,127 +122,58 @@ export default function Home() {
"convert"
)
}
onClick={convertToPdf}
onClick={convertDoc}
/>
)}
</div>
{
// TODO: Fix Table Head widths (fixed and the same as the max body width)
// TODO: Add hover animation to table head (scale-110, blue text, blue border)
// TODO: Fix general site height and add scrolling
// TODO: Add animated pop in for the table body
}
<div className="overflow-hidden text-xl rounded-lg border border-white">
<div className="overflow-hidden text-xl rounded-lg border border-white mb-16 transition-all duration-300 ease-in-out hover:border-blue-400">
<div
className="cursor-pointer flex justify-between items-center"
onClick={() => setTableOpen(!tableOpen)}
>
<table className="w-full px-6 py-4 border-b">
<table className="px-6 py-4 border-b">
<thead>
<tr className="border-b border-white">
<th className="w-sm px-6 py-4 border-r">📥 Input Format</th>
<th className="w-sm px-6 py-4 flex flex-row">
<p className="pr-4">📤 Output Format</p>
<th className="min-w-96 px-6 py-4 border-r border-white">
📥 Input Format
</th>
<th className="min-w-[398px] px-6 py-4 flex flex-row justify-between items-center">
<p className="pr-4 mx-auto">📤 Output Format</p>
<div className="flex items-end justify-end place-content-end">
{tableOpen ? (
<ChevronUp className="h-6 w-6" />
) : (
<ChevronDown className="h-6 w-6" />
)}
</div>
</th>
</tr>
</thead>
</table>
</div>
{tableOpen && (
<table className="w-full text-left border-collapse">
<div
className={`
}overflow-hidden transition-all duration-700 ease-in-out ${tableOpen ? "max-h-[900px]" : "max-h-0"}`}
>
<table className="w-full h-auto text-left border-collapse border-white">
<tbody>
<tr className="border-b">
<td className="px-6 py-4 border-r">.doc (MS Word)</td>
<td className="px-6 py-4">
.pdf, .docx, .odt, .txt, .rtf, .html, .epub
{FileFormatsTable.map((format) => (
<tr key={format.input} className="border-b">
<td className="min-w-96 px-6 py-4 border-r">
{format.input}
</td>
<td className="min-w-96 px-6 py-4">
{format.output.join(", ")}
</td>
</tr>
<tr className="border-b">
<td className="px-6 py-4 border-r">.docx (MS Word)</td>
<td className="px-6 py-4">
.pdf, .odt, .txt, .rtf, .html, .epub
</td>
</tr>
<tr className="border-b">
<td className="px-6 py-4 border-r">
.odt (OpenDocument Text)
</td>
<td className="px-6 py-4">
.pdf, .doc, .docx, .txt, .rtf, .html, .epub
</td>
</tr>
<tr className="border-b">
<td className="px-6 py-4 border-r">
.rtf (Rich Text Format)
</td>
<td className="px-6 py-4">
.pdf, .doc, .docx, .odt, .txt, .html
</td>
</tr>
<tr className="border-b">
<td className="px-6 py-4 border-r">.txt (Text)</td>
<td className="px-6 py-4">
.pdf, .doc, .docx, .odt, .txt, .html
</td>
</tr>
<tr className="border-b">
<td className="px-6 py-4 border-r">.html (Webseite)</td>
<td className="px-6 py-4">
.pdf, .doc, .docx, .odt, .rtf, .txt
</td>
</tr>
<tr className="border-b">
<td className="px-6 py-4 border-r">.epub (E-Book)</td>
<td className="px-6 py-4">
.pdf, .doc, .docx, .odt, .rtf, .txt
</td>
</tr>
<tr className="border-b">
<td className="px-6 py-4 border-r">.xls (MS Excel)</td>
<td className="px-6 py-4">.pdf, .xlsx, .ods, .csv</td>
</tr>
<tr className="border-b">
<td className="px-6 py-4 border-r">.xlsx (MS Excel)</td>
<td className="px-6 py-4">.pdf, .xls, .ods, .csv</td>
</tr>
<tr className="border-b">
<td className="px-6 py-4 border-r">
.ods (OpenDocument Spreadsheet)
</td>
<td className="px-6 py-4">.pdf, .xls, .xlsx, .csv</td>
</tr>
<tr className="border-b">
<td className="px-6 py-4 border-r">
.csv (Comma-Separated Values)
</td>
<td className="px-6 py-4">.pdf, .xls, .xlsx, .ods</td>
</tr>
<tr className="border-b">
<td className="px-6 py-4 border-r">.ppt (MS PowerPoint)</td>
<td className="px-6 py-4">.pdf, .pptx, .odp</td>
</tr>
<tr className="border-b">
<td className="px-6 py-4 border-r">.pptx (MS PowerPoint)</td>
<td className="px-6 py-4">.pdf, .ppt, .odp</td>
</tr>
<tr className="border-b">
<td className="px-6 py-4 border-r">
.odp (OpenDocument Presentation)
</td>
<td className="px-6 py-4">.pdf, .ppt, .pptx</td>
</tr>
))}
</tbody>
</table>
)}
</div>
</div>
<Footer />
</div>
<Footer className="flex justify-center items-end" />
</div>
);
}

View file

@ -0,0 +1,79 @@
"use client";
import React, { useState } from "react";
import Link from "next/link";
interface DropdownProps {
content: string;
options: string[];
className?: string;
onClick?: (event: React.MouseEvent<HTMLAnchorElement>) => void;
}
const Dropdown = (props: DropdownProps) => {
const [isOpen, setIsOpen] = useState(false);
const toggleDropdown = () => {
setIsOpen(!isOpen);
};
const closeDropdown = (event: React.MouseEvent<HTMLAnchorElement>) => {
setIsOpen(false);
if (props.onClick) props.onClick(event);
};
return (
<div className={`w-full ${props.className}`}>
<div className="relative">
<button
type="button"
className="h-16 px-4 py-2 text-white bg-black rounded-lg text-2xl inline-flex items-center
border-white border-2 hover:text-blue-400 hover:border-blue-400"
onClick={toggleDropdown}
>
{props.content}{" "}
<svg
className="w-2.5 h-2.5 ml-2.5"
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 10 6"
>
<path
stroke="currentColor"
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="m1 1 4 4 4-4"
/>
</svg>
</button>
<div
className={`absolute left-0 mt-2 w-full rounded-lg shadow-lg ring-1 ring-white
ring-opacity-5 border-2 border-white transition-all duration-500 ease-in-out text-center
${isOpen ? "opacity-100 scale-100 visible" : "opacity-0 scale-95 invisible"}`}
>
<ul
role="menu"
aria-orientation="vertical"
aria-labelledby="options-menu"
className="max-h-[164px] w-full overflow-y-auto"
>
{props.options?.map((option) => (
<li key={option}>
<Link
href="#"
className="block px-4 py-2 rounded-lg hover:text-blue-400 hover:border-2 hover:border-blue-400"
onClick={closeDropdown}
>
{option}
</Link>
</li>
))}
</ul>
</div>
</div>
</div>
);
};
export default Dropdown;

View file

@ -36,3 +36,121 @@ export const toolLinks = [
link: "/pomodoro-timer",
},
];
export const outputFileFormats = [
{
input: ".doc",
output: [".pdf", ".docx", ".odt", ".txt", ".rtf", ".html", ".epub"],
},
{
input: ".docx",
output: [".pdf", ".odt", ".txt", ".rtf", ".html", ".epub"],
},
{
input: ".odt",
output: [".pdf", ".doc", ".docx", ".txt", ".rtf", ".html", ".epub"],
},
{
input: ".rtf",
output: [".pdf", ".doc", ".docx", ".odt", ".txt", ".html"],
},
{
input: ".txt",
output: [".pdf", ".doc", ".docx", ".odt", ".txt", ".html"],
},
{
input: ".html",
output: [".pdf", ".doc", ".docx", ".odt", ".rtf", ".txt"],
},
{
input: ".epub",
output: [".pdf", ".doc", ".docx", ".odt", ".rtf", ".txt"],
},
{
input: ".xls",
output: [".pdf", ".xlsx", ".ods", ".csv"],
},
{
input: ".xlsx",
output: [".pdf", ".xls", ".ods", ".csv"],
},
{
input: ".ods",
output: [".pdf", ".xls", ".xlsx", ".csv"],
},
{
input: ".csv",
output: [".pdf", ".xls", ".xlsx", ".ods"],
},
{
input: ".ppt",
output: [".pdf", ".pptx", ".odp"],
},
{
input: ".pptx",
output: [".pdf", ".ppt", ".odp"],
},
{
input: ".odp",
output: [".pdf", ".ppt", ".pptx"],
},
];
export const FileFormatsTable = [
{
input: ".doc (MS Word)",
output: [".pdf", ".docx", ".odt", ".txt", ".rtf", ".html", ".epub"],
},
{
input: ".docx (MS Word)",
output: [".pdf", ".odt", ".txt", ".rtf", ".html", ".epub"],
},
{
input: ".odt (OpenDocument Text)",
output: [".pdf", ".doc", ".docx", ".txt", ".rtf", ".html", ".epub"],
},
{
input: ".rtf (Rich Text Format)",
output: [".pdf", ".doc", ".docx", ".odt", ".txt", ".html"],
},
{
input: ".txt (Text)",
output: [".pdf", ".doc", ".docx", ".odt", ".txt", ".html"],
},
{
input: ".html (Webseite)",
output: [".pdf", ".doc", ".docx", ".odt", ".rtf", ".txt"],
},
{
input: ".epub (E-Book)",
output: [".pdf", ".doc", ".docx", ".odt", ".rtf", ".txt"],
},
{
input: ".xls (MS Excel)",
output: [".pdf", ".xlsx", ".ods", ".csv"],
},
{
input: ".xlsx (MS Excel)",
output: [".pdf", ".xls", ".ods", ".csv"],
},
{
input: ".ods (OpenDocument Spreadsheet)",
output: [".pdf", ".xls", ".xlsx", ".csv"],
},
{
input: ".csv (Comma-Separated Values)",
output: [".pdf", ".xls", ".xlsx", ".ods"],
},
{
input: ".ppt (MS PowerPoint)",
output: [".pdf", ".pptx", ".odp"],
},
{
input: ".pptx (MS PowerPoint)",
output: [".pdf", ".ppt", ".odp"],
},
{
input: ".odp (OpenDocument Presentation)",
output: [".pdf", ".ppt", ".pptx"],
},
];