Merge branch 'main' of https://github.com/iib0011/omni-tools into fork/m5lk3n/feature/base64

# Conflicts:
#	package-lock.json
This commit is contained in:
Ibrahima G. Coulibaly
2025-06-05 18:46:51 +01:00
8 changed files with 651 additions and 141 deletions

View File

@@ -38,25 +38,25 @@ const FormikListenerComponent = <T,>({
return null; // This component doesn't render anything
};
interface ToolContentProps<T, I> extends ToolComponentProps {
interface ToolContentProps<Options, Input> extends ToolComponentProps {
inputComponent?: ReactNode;
resultComponent?: ReactNode;
renderCustomInput?: (
values: T,
values: Options,
setFieldValue: (fieldName: string, value: any) => void
) => ReactNode;
initialValues: T;
getGroups: GetGroupsType<T> | null;
compute: (optionsValues: T, input: I) => void;
initialValues: Options;
getGroups: GetGroupsType<Options> | null;
compute: (optionsValues: Options, input: Input) => void;
toolInfo?: {
title: string;
description?: string;
};
input?: I;
exampleCards?: CardExampleType<T>[];
setInput?: React.Dispatch<React.SetStateAction<I>>;
input?: Input;
exampleCards?: CardExampleType<Options>[];
setInput?: React.Dispatch<React.SetStateAction<Input>>;
validationSchema?: any;
onValuesChange?: (values: T) => void;
onValuesChange?: (values: Options) => void;
verticalGroups?: boolean;
}

View File

@@ -4,11 +4,13 @@ import { meta as mergePdf } from './merge-pdf/meta';
import { DefinedTool } from '@tools/defineTool';
import { tool as compressPdfTool } from './compress-pdf/meta';
import { tool as protectPdfTool } from './protect-pdf/meta';
import { meta as pdfToEpub } from './pdf-to-epub/meta';
export const pdfTools: DefinedTool[] = [
splitPdfMeta,
pdfRotatePdf,
compressPdfTool,
protectPdfTool,
mergePdf
mergePdf,
pdfToEpub
];

View File

@@ -0,0 +1,58 @@
import { useState, useEffect } from 'react';
import ToolFileResult from '@components/result/ToolFileResult';
import ToolContent from '@components/ToolContent';
import { ToolComponentProps } from '@tools/defineTool';
import ToolPdfInput from '@components/input/ToolPdfInput';
import { convertPdfToEpub } from './service';
export default function PdfToEpub({ title }: ToolComponentProps) {
const [input, setInput] = useState<File | null>(null);
const [result, setResult] = useState<File | null>(null);
const [isProcessing, setIsProcessing] = useState<boolean>(false);
const compute = async (options: {}, input: File | null) => {
if (!input) return;
try {
setIsProcessing(true);
setResult(null);
const epub = await convertPdfToEpub(input);
setResult(epub);
} catch (error) {
console.error('Failed to convert PDF to EPUB:', error);
} finally {
setIsProcessing(false);
}
};
return (
<ToolContent
title={title}
input={input}
setInput={setInput}
initialValues={{}}
compute={compute}
inputComponent={
<ToolPdfInput
value={input}
onChange={(file) => setInput(file)}
accept={['application/pdf']}
title={'Input PDF'}
/>
}
getGroups={null}
resultComponent={
<ToolFileResult
title={'EPUB Output'}
value={result}
extension={'epub'}
loading={isProcessing}
loadingText={'Converting PDF to EPUB...'}
/>
}
toolInfo={{
title: 'How to Use PDF to EPUB?',
description: `Upload a PDF file and this tool will convert it into an EPUB format, suitable for most e-reader devices.`
}}
/>
);
}

View File

@@ -0,0 +1,13 @@
import { defineTool } from '@tools/defineTool';
import { lazy } from 'react';
export const meta = defineTool('pdf', {
name: 'PDF to EPUB',
shortDescription: 'Convert PDF files to EPUB format',
description:
'Transform PDF documents into EPUB files for better e-reader compatibility.',
icon: 'material-symbols:import-contacts',
component: lazy(() => import('./index')),
keywords: ['pdf', 'epub', 'convert', 'ebook'],
path: 'pdf-to-epub'
});

View File

@@ -0,0 +1,144 @@
import * as pdfjsLib from 'pdfjs-dist';
import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.min?url';
import JSZip from 'jszip';
// Set worker source for PDF.js
pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsWorker;
function formatTextToParagraphs(raw: string): string {
return raw
.split(/\n{2,}|\r{2,}/g) // Split on double line breaks
.map((p) => p.trim())
.filter((p) => p.length > 0)
.map((p) => `<p>${p.replace(/\n/g, ' ')}</p>`)
.join('\n');
}
export async function convertPdfToEpub(pdfFile: File): Promise<File> {
const arrayBuffer = await pdfFile.arrayBuffer();
const loadingTask = pdfjsLib.getDocument({ data: arrayBuffer });
const pdfDoc = await loadingTask.promise;
const numPages = pdfDoc.numPages;
// Extracting text
const pages: string[] = [];
for (let i = 1; i <= numPages; i++) {
const page = await pdfDoc.getPage(i);
const textContent = await page.getTextContent();
const pageText = textContent.items.map((item: any) => item.str).join('\n'); // Preserve line breaks better
pages.push(pageText);
}
const zip = new JSZip();
zip.file('mimetype', 'application/epub+zip', { compression: 'STORE' });
const metaInf = zip.folder('META-INF');
metaInf!.file(
'container.xml',
`<?xml version="1.0" encoding="UTF-8"?>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
<rootfiles>
<rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
</rootfiles>
</container>`
);
const oebps = zip.folder('OEBPS');
const bookTitle = pdfFile.name.replace(/\.pdf$/i, '');
const contentOpf = `<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://www.idpf.org/2007/opf" unique-identifier="bookid" version="2.0">
<metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
<dc:title>${bookTitle}</dc:title>
<dc:creator>Converted by omni-tools</dc:creator>
<dc:identifier id="bookid">${Date.now()}</dc:identifier>
<dc:language>en</dc:language>
</metadata>
<manifest>
<item id="ncx" href="toc.ncx" media-type="application/x-dtbncx+xml"/>
${pages
.map(
(_, index) =>
`<item id="chapter${index + 1}" href="chapter${
index + 1
}.xhtml" media-type="application/xhtml+xml"/>`
)
.join('\n ')}
</manifest>
<spine toc="ncx">
${pages
.map((_, index) => `<itemref idref="chapter${index + 1}"/>`)
.join('\n ')}
</spine>
</package>`;
oebps!.file('content.opf', contentOpf);
const tocNcx = `<?xml version="1.0" encoding="UTF-8"?>
<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1">
<head>
<meta name="dtb:uid" content="${Date.now()}"/>
<meta name="dtb:depth" content="1"/>
<meta name="dtb:totalPageCount" content="0"/>
<meta name="dtb:maxPageNumber" content="0"/>
</head>
<docTitle>
<text>${bookTitle}</text>
</docTitle>
<navMap>
${pages
.map(
(_, index) =>
`<navPoint id="navpoint-${index + 1}" playOrder="${index + 1}">
<navLabel>
<text>Page ${index + 1}</text>
</navLabel>
<content src="chapter${index + 1}.xhtml"/>
</navPoint>`
)
.join('\n ')}
</navMap>
</ncx>`;
oebps!.file('toc.ncx', tocNcx);
pages.forEach((pageText, index) => {
const formattedBody = formatTextToParagraphs(pageText);
const chapterXhtml = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Page ${index + 1}</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
body {
font-family: serif;
line-height: 1.6;
margin: 1em;
}
p {
margin-bottom: 1em;
text-align: justify;
}
</style>
</head>
<body>
<h1>Page ${index + 1}</h1>
${formattedBody}
</body>
</html>`;
oebps!.file(`chapter${index + 1}.xhtml`, chapterXhtml);
});
const epubBuffer = await zip.generateAsync({ type: 'arraybuffer' });
return new File([epubBuffer], pdfFile.name.replace(/\.pdf$/i, '.epub'), {
type: 'application/epub+zip'
});
}