Merge branch 'Stirling-2.0' of https://github.com/reecebrowne/Stirling-PDF into Stirling-2.0

This commit is contained in:
Reece 2025-05-19 13:14:58 +01:00
commit 5f7a4e1664
36 changed files with 79294 additions and 70 deletions

23
frontend/.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

70
frontend/README.md Normal file
View File

@ -0,0 +1,70 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
The page will reload when you make changes.\
You may also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you can't go back!**
If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
### Analyzing the Bundle Size
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
### Making a Progressive Web App
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
### Advanced Configuration
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
### Deployment
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
### `npm run build` fails to minify
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)

19253
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

56
frontend/package.json Normal file
View File

@ -0,0 +1,56 @@
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"proxy": "http://localhost:8080",
"dependencies": {
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.0",
"@mantine/core": "^8.0.1",
"@mantine/dropzone": "^8.0.1",
"@mantine/hooks": "^8.0.1",
"@mui/icons-material": "^7.1.0",
"@mui/material": "^7.1.0",
"@testing-library/dom": "^10.4.0",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.9.0",
"pdfjs-dist": "^3.11.174",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-router-dom": "^7.6.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"postcss": "^8.5.3",
"postcss-cli": "^11.0.1",
"postcss-preset-mantine": "^1.17.0",
"postcss-simple-vars": "^7.0.1"
}
}

View File

@ -0,0 +1,7 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

BIN
frontend/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>

BIN
frontend/public/logo192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

BIN
frontend/public/logo512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

View File

@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

58353
frontend/public/pdf.worker.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

38
frontend/src/App.css Normal file
View File

@ -0,0 +1,38 @@
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

31
frontend/src/App.js Normal file
View File

@ -0,0 +1,31 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { ColorSchemeScript, MantineProvider } from '@mantine/core';
import './index.css';
import HomePage from './pages/HomePage';
import SplitPdfPanel from './tools/Split';
import reportWebVitals from './reportWebVitals';
export default function App() {
return (
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/split" element={<SplitPdfPanel />} />
</Routes>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<ColorSchemeScript />
<MantineProvider withGlobalStyles withNormalizeCSS>
<BrowserRouter>
<App />
</BrowserRouter>
</MantineProvider>
</React.StrictMode>
);
reportWebVitals();

8
frontend/src/App.test.js Normal file
View File

@ -0,0 +1,8 @@
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});

View File

@ -0,0 +1,172 @@
import React, { useState, useEffect } from "react";
import { Card, Group, Text, Stack, Image, Badge, Button, Box, Flex } from "@mantine/core";
import { Dropzone, MIME_TYPES } from "@mantine/dropzone";
import { GlobalWorkerOptions, getDocument, version as pdfjsVersion } from "pdfjs-dist";
GlobalWorkerOptions.workerSrc = `${process.env.PUBLIC_URL}/pdf.worker.js`;
function getFileDate(file) {
if (file.lastModified) {
return new Date(file.lastModified).toLocaleString();
}
return "Unknown";
}
function getFileSize(file) {
if (!file.size) return "Unknown";
if (file.size < 1024) return `${file.size} B`;
if (file.size < 1024 * 1024) return `${(file.size / 1024).toFixed(1)} KB`;
return `${(file.size / (1024 * 1024)).toFixed(2)} MB`;
}
function usePdfThumbnail(file) {
const [thumb, setThumb] = useState(null);
useEffect(() => {
let cancelled = false;
async function generate() {
if (!file) return;
try {
const arrayBuffer = await file.arrayBuffer();
const pdf = await getDocument({ data: arrayBuffer }).promise;
const page = await pdf.getPage(1);
const viewport = page.getViewport({ scale: 0.5 });
const canvas = document.createElement("canvas");
canvas.width = viewport.width;
canvas.height = viewport.height;
const context = canvas.getContext("2d");
await page.render({ canvasContext: context, viewport }).promise;
if (!cancelled) setThumb(canvas.toDataURL());
} catch {
if (!cancelled) setThumb(null);
}
}
generate();
return () => { cancelled = true; };
}, [file]);
return thumb;
}
function FileCard({ file, onRemove, onDoubleClick }) {
const thumb = usePdfThumbnail(file);
return (
<Card
shadow="xs"
radius="md"
withBorder
p="xs"
style={{ width: 225, minWidth: 180, maxWidth: 260, cursor: onDoubleClick ? "pointer" : undefined }}
onDoubleClick={onDoubleClick}
>
<Stack spacing={6} align="center">
<Box
style={{
border: "2px solid #e0e0e0",
borderRadius: 8,
width: 90,
height: 120,
display: "flex",
alignItems: "center",
justifyContent: "center",
margin: "0 auto",
background: "#fafbfc",
}}
>
{thumb ? (
<Image src={thumb} alt="PDF thumbnail" height={110} width={80} fit="contain" radius="sm" />
) : (
<Image src="/images/pdf-placeholder.svg" alt="PDF" height={60} width={60} fit="contain" radius="sm" withPlaceholder />
)}
</Box>
<Text weight={500} size="sm" lineClamp={1} align="center">
{file.name}
</Text>
<Group spacing="xs" position="center">
<Badge color="gray" variant="light" size="sm">
{getFileSize(file)}
</Badge>
<Badge color="blue" variant="light" size="sm">
{getFileDate(file)}
</Badge>
</Group>
<Button
color="red"
size="xs"
variant="light"
onClick={onRemove}
mt={4}
>
Remove
</Button>
</Stack>
</Card>
);
}
export default function FileManager({ files = [], setFiles, allowMultiple = true, setPdfFile, setCurrentView }) {
const handleDrop = (uploadedFiles) => {
setFiles((prevFiles) => (allowMultiple ? [...prevFiles, ...uploadedFiles] : uploadedFiles));
};
const handleRemoveFile = (index) => {
setFiles((prevFiles) => prevFiles.filter((_, i) => i !== index));
};
return (
<div style={{ width: "100%", margin: "0 auto" }}>
<Dropzone
onDrop={handleDrop}
accept={[MIME_TYPES.pdf]}
multiple={allowMultiple}
maxSize={20 * 1024 * 1024}
style={{
marginBottom: 16,
border: "2px dashed rgb(202, 202, 202)",
background: "#f8fafc",
borderRadius: 8,
minHeight: 120,
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
>
<Group position="center" spacing="xl" style={{ pointerEvents: "none" }}>
<Text size="md">
Drag PDF files here or click to select
</Text>
</Group>
</Dropzone>
{files.length === 0 ? (
<Text c="dimmed" align="center">
No files uploaded yet.
</Text>
) : (
<Box>
<Flex
wrap="wrap"
gap="lg"
justify="flex-start"
style={{ width: "fit-content", margin: "0 auto" }}
>
{files.map((file, idx) => (
<FileCard
key={file.name + idx}
file={file}
onRemove={() => handleRemoveFile(idx)}
onDoubleClick={() => {
const fileObj = file.file || file; // handle wrapped or raw File
setPdfFile && setPdfFile({
file: fileObj,
url: URL.createObjectURL(fileObj),
});
setCurrentView && setCurrentView("viewer");
}}
/>
))}
</Flex>
</Box>
)}
</div>
);
}

View File

@ -0,0 +1,9 @@
import React from "react";
export default function PageEditor({ pdfFile }) {
return (
<div className="w-full h-full flex items-center justify-center">
<p className="text-gray-500">Page Editor is under construction.</p>
</div>
);
}

View File

@ -0,0 +1,112 @@
import React, { useEffect, useState } from "react";
import { Paper, Stack, Text, ScrollArea, Loader, Center, Button, Group } from "@mantine/core";
import { getDocument, GlobalWorkerOptions, version as pdfjsVersion } from "pdfjs-dist";
GlobalWorkerOptions.workerSrc = `${process.env.PUBLIC_URL}/pdf.worker.js`;
export default function Viewer({ pdfFile, setPdfFile }) {
const [numPages, setNumPages] = useState(0);
const [pageImages, setPageImages] = useState([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
let cancelled = false;
async function renderPages() {
if (!pdfFile || !pdfFile.url) {
setNumPages(0);
setPageImages([]);
return;
}
setLoading(true);
try {
const pdf = await getDocument(pdfFile.url).promise;
setNumPages(pdf.numPages);
const images = [];
for (let i = 1; i <= pdf.numPages; i++) {
const page = await pdf.getPage(i);
const viewport = page.getViewport({ scale: 1.2 });
const canvas = document.createElement("canvas");
canvas.width = viewport.width;
canvas.height = viewport.height;
const ctx = canvas.getContext("2d");
await page.render({ canvasContext: ctx, viewport }).promise;
images.push(canvas.toDataURL());
}
if (!cancelled) setPageImages(images);
} catch {
if (!cancelled) setPageImages([]);
}
if (!cancelled) setLoading(false);
}
renderPages();
return () => { cancelled = true; };
}, [pdfFile]);
return (
<Paper shadow="xs" radius="md" p="md" style={{ height: "100%", minHeight: 400, display: "flex", flexDirection: "column" }}>
{!pdfFile ? (
<Center style={{ flex: 1 }}>
<Stack align="center">
<Text color="dimmed">No PDF loaded. Click to upload a PDF.</Text>
<Button
component="label"
variant="outline"
color="blue"
>
Choose PDF
<input
type="file"
accept="application/pdf"
hidden
onChange={(e) => {
const file = e.target.files[0];
if (file && file.type === "application/pdf") {
const fileUrl = URL.createObjectURL(file);
setPdfFile({ file, url: fileUrl });
}
}}
/>
</Button>
</Stack>
</Center>
) : loading ? (
<Center style={{ flex: 1 }}>
<Loader size="lg" />
</Center>
) : (
<ScrollArea style={{ flex: 1, height: "100%" }}>
<Stack spacing="xl" align="center">
{pageImages.length === 0 && (
<Text color="dimmed">No pages to display.</Text>
)}
{pageImages.map((img, idx) => (
<img
key={idx}
src={img}
alt={`Page ${idx + 1}`}
style={{
width: "100%",
maxWidth: 700,
boxShadow: "0 2px 8px rgba(0,0,0,0.08)",
borderRadius: 8,
background: "#fff"
}}
/>
))}
</Stack>
</ScrollArea>
)}
{pdfFile && (
<Group position="right" mt="md">
<Button
variant="light"
color="red"
onClick={() => setPdfFile(null)}
>
Close PDF
</Button>
</Group>
)}
</Paper>
);
}

17
frontend/src/index.css Normal file
View File

@ -0,0 +1,17 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}

22
frontend/src/index.js Normal file
View File

@ -0,0 +1,22 @@
import '@mantine/core/styles.css';
import React from 'react';
import ReactDOM from 'react-dom/client';
import { ColorSchemeScript, MantineProvider, mantineHtmlProps } from '@mantine/core';
import { BrowserRouter } from 'react-router-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root')); // Finds the root DOM element
root.render(
<React.StrictMode>
<ColorSchemeScript />
<MantineProvider withGlobalStyles withNormalizeCSS>
<BrowserRouter>
<App />
</BrowserRouter>
</MantineProvider>
</React.StrictMode>
);
reportWebVitals();

1
frontend/src/logo.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

362
frontend/src/output.css Normal file
View File

@ -0,0 +1,362 @@
*, ::before, ::after {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-rotate: 0;
--tw-skew-x: 0;
--tw-skew-y: 0;
--tw-scale-x: 1;
--tw-scale-y: 1;
--tw-pan-x: ;
--tw-pan-y: ;
--tw-pinch-zoom: ;
--tw-scroll-snap-strictness: proximity;
--tw-gradient-from-position: ;
--tw-gradient-via-position: ;
--tw-gradient-to-position: ;
--tw-ordinal: ;
--tw-slashed-zero: ;
--tw-numeric-figure: ;
--tw-numeric-spacing: ;
--tw-numeric-fraction: ;
--tw-ring-inset: ;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgb(59 130 246 / 0.5);
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
--tw-shadow: 0 0 #0000;
--tw-shadow-colored: 0 0 #0000;
--tw-blur: ;
--tw-brightness: ;
--tw-contrast: ;
--tw-grayscale: ;
--tw-hue-rotate: ;
--tw-invert: ;
--tw-saturate: ;
--tw-sepia: ;
--tw-drop-shadow: ;
--tw-backdrop-blur: ;
--tw-backdrop-brightness: ;
--tw-backdrop-contrast: ;
--tw-backdrop-grayscale: ;
--tw-backdrop-hue-rotate: ;
--tw-backdrop-invert: ;
--tw-backdrop-opacity: ;
--tw-backdrop-saturate: ;
--tw-backdrop-sepia: ;
--tw-contain-size: ;
--tw-contain-layout: ;
--tw-contain-paint: ;
--tw-contain-style:
}
::backdrop {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-rotate: 0;
--tw-skew-x: 0;
--tw-skew-y: 0;
--tw-scale-x: 1;
--tw-scale-y: 1;
--tw-pan-x: ;
--tw-pan-y: ;
--tw-pinch-zoom: ;
--tw-scroll-snap-strictness: proximity;
--tw-gradient-from-position: ;
--tw-gradient-via-position: ;
--tw-gradient-to-position: ;
--tw-ordinal: ;
--tw-slashed-zero: ;
--tw-numeric-figure: ;
--tw-numeric-spacing: ;
--tw-numeric-fraction: ;
--tw-ring-inset: ;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgb(59 130 246 / 0.5);
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
--tw-shadow: 0 0 #0000;
--tw-shadow-colored: 0 0 #0000;
--tw-blur: ;
--tw-brightness: ;
--tw-contrast: ;
--tw-grayscale: ;
--tw-hue-rotate: ;
--tw-invert: ;
--tw-saturate: ;
--tw-sepia: ;
--tw-drop-shadow: ;
--tw-backdrop-blur: ;
--tw-backdrop-brightness: ;
--tw-backdrop-contrast: ;
--tw-backdrop-grayscale: ;
--tw-backdrop-hue-rotate: ;
--tw-backdrop-invert: ;
--tw-backdrop-opacity: ;
--tw-backdrop-saturate: ;
--tw-backdrop-sepia: ;
--tw-contain-size: ;
--tw-contain-layout: ;
--tw-contain-paint: ;
--tw-contain-style:
}
.mb-3 {
margin-bottom: 0.75rem
}
.mb-4 {
margin-bottom: 1rem
}
.mr-2 {
margin-right: 0.5rem
}
.mt-2 {
margin-top: 0.5rem
}
.mt-4 {
margin-top: 1rem
}
.block {
display: block
}
.flex {
display: flex
}
.hidden {
display: none
}
.h-6 {
height: 1.5rem
}
.h-full {
height: 100%
}
.h-screen {
height: 100vh
}
.w-6 {
width: 1.5rem
}
.w-64 {
width: 16rem
}
.w-72 {
width: 18rem
}
.w-full {
width: 100%
}
.max-w-3xl {
max-width: 48rem
}
.flex-1 {
flex: 1 1 0%
}
.cursor-pointer {
cursor: pointer
}
.list-disc {
list-style-type: disc
}
.flex-col {
flex-direction: column
}
.items-center {
align-items: center
}
.justify-center {
justify-content: center
}
.justify-between {
justify-content: space-between
}
.space-x-2 > :not([hidden]) ~ :not([hidden]) {
--tw-space-x-reverse: 0;
margin-right: calc(0.5rem * var(--tw-space-x-reverse));
margin-left: calc(0.5rem * calc(1 - var(--tw-space-x-reverse)))
}
.space-x-3 > :not([hidden]) ~ :not([hidden]) {
--tw-space-x-reverse: 0;
margin-right: calc(0.75rem * var(--tw-space-x-reverse));
margin-left: calc(0.75rem * calc(1 - var(--tw-space-x-reverse)))
}
.space-y-2 > :not([hidden]) ~ :not([hidden]) {
--tw-space-y-reverse: 0;
margin-top: calc(0.5rem * calc(1 - var(--tw-space-y-reverse)));
margin-bottom: calc(0.5rem * var(--tw-space-y-reverse))
}
.space-y-3 > :not([hidden]) ~ :not([hidden]) {
--tw-space-y-reverse: 0;
margin-top: calc(0.75rem * calc(1 - var(--tw-space-y-reverse)));
margin-bottom: calc(0.75rem * var(--tw-space-y-reverse))
}
.space-y-4 > :not([hidden]) ~ :not([hidden]) {
--tw-space-y-reverse: 0;
margin-top: calc(1rem * calc(1 - var(--tw-space-y-reverse)));
margin-bottom: calc(1rem * var(--tw-space-y-reverse))
}
.overflow-hidden {
overflow: hidden
}
.overflow-y-auto {
overflow-y: auto
}
.rounded {
border-radius: 0.25rem
}
.rounded-md {
border-radius: 0.375rem
}
.border {
border-width: 1px
}
.border-b {
border-bottom-width: 1px
}
.border-l {
border-left-width: 1px
}
.border-r {
border-right-width: 1px
}
.border-none {
border-style: none
}
.bg-blue-600 {
--tw-bg-opacity: 1;
background-color: rgb(37 99 235 / var(--tw-bg-opacity, 1))
}
.bg-gray-100 {
--tw-bg-opacity: 1;
background-color: rgb(243 244 246 / var(--tw-bg-opacity, 1))
}
.bg-gray-50 {
--tw-bg-opacity: 1;
background-color: rgb(249 250 251 / var(--tw-bg-opacity, 1))
}
.bg-green-600 {
--tw-bg-opacity: 1;
background-color: rgb(22 163 74 / var(--tw-bg-opacity, 1))
}
.bg-white {
--tw-bg-opacity: 1;
background-color: rgb(255 255 255 / var(--tw-bg-opacity, 1))
}
.p-2 {
padding: 0.5rem
}
.p-4 {
padding: 1rem
}
.px-2 {
padding-left: 0.5rem;
padding-right: 0.5rem
}
.px-4 {
padding-left: 1rem;
padding-right: 1rem
}
.py-1 {
padding-top: 0.25rem;
padding-bottom: 0.25rem
}
.py-2 {
padding-top: 0.5rem;
padding-bottom: 0.5rem
}
.pl-5 {
padding-left: 1.25rem
}
.text-left {
text-align: left
}
.text-center {
text-align: center
}
.text-lg {
font-size: 1.125rem;
line-height: 1.75rem
}
.text-sm {
font-size: 0.875rem;
line-height: 1.25rem
}
.text-xl {
font-size: 1.25rem;
line-height: 1.75rem
}
.text-xs {
font-size: 0.75rem;
line-height: 1rem
}
.font-medium {
font-weight: 500
}
.font-semibold {
font-weight: 600
}
.leading-none {
line-height: 1
}
.text-blue-600 {
--tw-text-opacity: 1;
color: rgb(37 99 235 / var(--tw-text-opacity, 1))
}
.text-gray-500 {
--tw-text-opacity: 1;
color: rgb(107 114 128 / var(--tw-text-opacity, 1))
}
.text-gray-600 {
--tw-text-opacity: 1;
color: rgb(75 85 99 / var(--tw-text-opacity, 1))
}
.text-red-500 {
--tw-text-opacity: 1;
color: rgb(239 68 68 / var(--tw-text-opacity, 1))
}
.text-red-600 {
--tw-text-opacity: 1;
color: rgb(220 38 38 / var(--tw-text-opacity, 1))
}
.text-white {
--tw-text-opacity: 1;
color: rgb(255 255 255 / var(--tw-text-opacity, 1))
}
.underline {
text-decoration-line: underline
}
.shadow {
--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);
--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);
box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow)
}
.shadow-sm {
--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05);
--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);
box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow)
}
.grayscale {
--tw-grayscale: grayscale(100%);
filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)
}
.filter {
filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)
}
.hover\:bg-blue-700:hover {
--tw-bg-opacity: 1;
background-color: rgb(29 78 216 / var(--tw-bg-opacity, 1))
}
.hover\:bg-gray-200:hover {
--tw-bg-opacity: 1;
background-color: rgb(229 231 235 / var(--tw-bg-opacity, 1))
}
.hover\:bg-green-700:hover {
--tw-bg-opacity: 1;
background-color: rgb(21 128 61 / var(--tw-bg-opacity, 1))
}
.hover\:underline:hover {
text-decoration-line: underline
}

View File

@ -0,0 +1,201 @@
import React, { useState } from "react";
import AddToPhotosIcon from "@mui/icons-material/AddToPhotos";
import ContentCutIcon from "@mui/icons-material/ContentCut";
import ZoomInMapIcon from "@mui/icons-material/ZoomInMap";
import InsertDriveFileIcon from "@mui/icons-material/InsertDriveFile";
import VisibilityIcon from "@mui/icons-material/Visibility";
import EditNoteIcon from "@mui/icons-material/EditNote";
import { Group, SegmentedControl, Paper, Center, Stack, Button, Text, Box } from "@mantine/core";
import FileManager from "../components/FileManager";
import SplitPdfPanel from "../tools/Split";
import CompressPdfPanel from "../tools/Compress";
import MergePdfPanel from "../tools/Merge";
import PageEditor from "../components/PageEditor";
import Viewer from "../components/Viewer";
const toolRegistry = {
split: { icon: <ContentCutIcon />, name: "Split PDF", component: SplitPdfPanel, view: "viewer" },
compress: { icon: <ZoomInMapIcon />, name: "Compress PDF", component: CompressPdfPanel, view: "viewer" },
merge: { icon: <AddToPhotosIcon />, name: "Merge PDFs", component: MergePdfPanel, view: "fileManager" },
};
const VIEW_OPTIONS = [
{
label: (
<Group gap={4}>
<VisibilityIcon fontSize="small" />
</Group>
),
value: "viewer",
},
{
label: (
<Group gap={4}>
<EditNoteIcon fontSize="small" />
</Group>
),
value: "pageEditor",
},
{
label: (
<Group gap={4}>
<InsertDriveFileIcon fontSize="small" />
</Group>
),
value: "fileManager",
},
];
export default function HomePage() {
const [selectedToolKey, setSelectedToolKey] = useState("split");
const [currentView, setCurrentView] = useState("viewer");
const [pdfFile, setPdfFile] = useState(null);
const [files, setFiles] = useState([]);
const [downloadUrl, setDownloadUrl] = useState(null);
const selectedTool = toolRegistry[selectedToolKey];
return (
<Group align="flex-start" spacing={0} style={{ minHeight: "100vh" }}>
{/* Left: Tool Picker */}
<Box
style={{
width: 220,
background: "#f8f9fa",
borderRight: "1px solid #e9ecef",
minHeight: "100vh",
padding: 16,
position: "fixed",
left: 0,
top: 0,
bottom: 0,
zIndex: 100,
overflowY: "auto",
}}
>
<Text size="lg" weight={500} mb="md">
Tools
</Text>
<Stack spacing="sm">
{Object.entries(toolRegistry).map(([id, { icon, name }]) => (
<Button
key={id}
variant={selectedToolKey === id ? "filled" : "subtle"}
leftIcon={icon}
onClick={() => {
setSelectedToolKey(id);
if (toolRegistry[id].view) setCurrentView(toolRegistry[id].view);
}}
fullWidth
size="md"
radius="md"
>
{name}
</Button>
))}
</Stack>
</Box>
{/* Middle: Main View (Viewer, Editor, Manager) */}
<Box
style={{
width: "calc(100vw - 220px - 380px)",
marginLeft: 220,
marginRight: 380,
padding: 24,
background: "#fff",
position: "relative",
minHeight: "100vh",
height: "100vh",
overflowY: "auto",
}}
>
<Center>
<Paper
radius="xl"
shadow="sm"
p={4}
style={{
display: "inline-block",
marginTop: 8,
marginBottom: 24,
background: "#f8f9fa",
zIndex: 10,
}}
>
<SegmentedControl
data={VIEW_OPTIONS}
value={currentView}
onChange={setCurrentView}
color="blue"
radius="xl"
size="md"
/>
</Paper>
</Center>
<Box>
{(currentView === "viewer" || currentView === "pageEditor") && !pdfFile ? (
<FileManager
files={files}
setFiles={setFiles}
setPdfFile={setPdfFile}
setCurrentView={setCurrentView}
/>
) : currentView === "viewer" ? (
<Viewer
pdfFile={pdfFile}
setPDFFile={setPdfFile}
downloadUrl={downloadUrl}
setDownloadUrl={setDownloadUrl}
/>
) : currentView === "pageEditor" ? (
<PageEditor
file={pdfFile}
setFile={setPdfFile}
downloadUrl={downloadUrl}
setDownloadUrl={setDownloadUrl}
/>
) : (
<FileManager
files={files}
setFiles={setFiles}
setPdfFile={setPdfFile}
setCurrentView={setCurrentView}
/>
)}
</Box>
</Box>
{/* Right: Tool Interaction */}
<Box
style={{
width: 380,
background: "#f8f9fa",
borderLeft: "1px solid #e9ecef",
minHeight: "100vh",
padding: 24,
gap: 16,
position: "fixed",
right: 0,
top: 0,
bottom: 0,
zIndex: 100,
overflowY: "auto",
}}
>
{selectedTool && selectedTool.component && (
<>
{React.createElement(selectedTool.component, {
file: pdfFile,
setPdfFile,
files,
setFiles,
downloadUrl,
setDownloadUrl,
})}
</>
)}
</Box>
</Group>
);
}

View File

@ -0,0 +1,13 @@
const reportWebVitals = onPerfEntry => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;

View File

@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';

View File

@ -0,0 +1,113 @@
import React, { useState } from "react";
import { Stack, Slider, Group, Text, Button, Checkbox, TextInput, Paper } from "@mantine/core";
export default function CompressPdfPanel({ files = [], setDownloadUrl, setLoading }) {
const [selected, setSelected] = useState(files.map(() => false));
const [compressionLevel, setCompressionLevel] = useState(5); // 1-9, default 5
const [grayscale, setGrayscale] = useState(false);
const [removeMetadata, setRemoveMetadata] = useState(false);
const [expectedSize, setExpectedSize] = useState("");
const [aggressive, setAggressive] = useState(false);
const [localLoading, setLocalLoading] = useState(false);
// Update selection state if files prop changes
React.useEffect(() => {
setSelected(files.map(() => false));
}, [files]);
const handleCheckbox = idx => {
setSelected(sel => sel.map((v, i) => (i === idx ? !v : v)));
};
const handleCompress = async () => {
const selectedFiles = files.filter((_, i) => selected[i]);
if (selectedFiles.length === 0) return;
setLocalLoading(true);
setLoading?.(true);
const formData = new FormData();
selectedFiles.forEach(file => formData.append("fileInput", file));
formData.append("compressionLevel", compressionLevel);
formData.append("grayscale", grayscale);
formData.append("removeMetadata", removeMetadata);
formData.append("aggressive", aggressive);
if (expectedSize) formData.append("expectedSize", expectedSize);
try {
const res = await fetch("/api/v1/general/compress-pdf", {
method: "POST",
body: formData,
});
const blob = await res.blob();
setDownloadUrl(URL.createObjectURL(blob));
} finally {
setLocalLoading(false);
setLoading?.(false);
}
};
return (
<Paper shadow="xs" p="md" radius="md" withBorder>
<Stack>
<Text weight={500} mb={4}>Select files to compress:</Text>
<Stack spacing={4}>
{files.length === 0 && <Text color="dimmed" size="sm">No files loaded.</Text>}
{files.map((file, idx) => (
<Checkbox
key={file.name + idx}
label={file.name}
checked={selected[idx] || false}
onChange={() => handleCheckbox(idx)}
/>
))}
</Stack>
<Stack spacing={4} mb={14}>
<Text size="sm" style={{ minWidth: 140 }}>Compression Level</Text>
<Slider
min={1}
max={9}
step={1}
value={compressionLevel}
onChange={setCompressionLevel}
marks={[
{ value: 1, label: "1" },
{ value: 5, label: "5" },
{ value: 9, label: "9" },
]}
style={{ flex: 1 }}
/>
</Stack >
<Checkbox
label="Convert images to grayscale"
checked={grayscale}
onChange={e => setGrayscale(e.currentTarget.checked)}
/>
<Checkbox
label="Remove PDF metadata"
checked={removeMetadata}
onChange={e => setRemoveMetadata(e.currentTarget.checked)}
/>
<Checkbox
label="Aggressive compression (may reduce quality)"
checked={aggressive}
onChange={e => setAggressive(e.currentTarget.checked)}
/>
<TextInput
label="Expected output size (e.g. 2MB, 500KB)"
placeholder="Optional"
value={expectedSize}
onChange={e => setExpectedSize(e.currentTarget.value)}
/>
<Button
onClick={handleCompress}
loading={localLoading}
disabled={selected.every(v => !v)}
fullWidth
mt="md"
>
Compress Selected PDF{selected.filter(Boolean).length > 1 ? "s" : ""}
</Button>
</Stack>
</Paper>
);
}

101
frontend/src/tools/Merge.js Normal file
View File

@ -0,0 +1,101 @@
import React, { useState, useEffect } from "react";
export default function MergePdfPanel({ files, setDownloadUrl }) {
const [selectedFiles, setSelectedFiles] = useState([]);
const [downloadUrl, setLocalDownloadUrl] = useState(null); // Local state for download URL
const [isLoading, setIsLoading] = useState(false); // Loading state
const [errorMessage, setErrorMessage] = useState(null); // Error message state
// Sync selectedFiles with files whenever files change
useEffect(() => {
setSelectedFiles(files.map(() => true)); // Select all files by default
}, [files]);
const handleMerge = async () => {
const filesToMerge = files.filter((_, index) => selectedFiles[index]);
if (filesToMerge.length < 2) {
alert("Please select at least two PDFs to merge.");
return;
}
const formData = new FormData();
filesToMerge.forEach((file) => formData.append("fileInput", file)); // Use "fileInput" as the key
setIsLoading(true); // Start loading
setErrorMessage(null); // Clear previous errors
try {
const response = await fetch("/api/v1/general/merge-pdfs", {
method: "POST",
body: formData,
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to merge PDFs: ${errorText}`);
}
const blob = await response.blob();
const downloadUrl = URL.createObjectURL(blob);
setDownloadUrl(downloadUrl); // Pass to parent component
setLocalDownloadUrl(downloadUrl); // Store locally for download button
} catch (error) {
console.error("Error merging PDFs:", error);
setErrorMessage(error.message); // Set error message
} finally {
setIsLoading(false); // Stop loading
}
};
const handleCheckboxChange = (index) => {
setSelectedFiles((prevSelectedFiles) =>
prevSelectedFiles.map((selected, i) => (i === index ? !selected : selected))
);
};
return (
<div className="space-y-4">
<h3 className="font-semibold text-lg">Merge PDFs</h3>
<ul className="list-disc pl-5 text-sm">
{files.map((file, index) => (
<li key={index} className="flex items-center space-x-2">
<input
type="checkbox"
checked={selectedFiles[index]}
onChange={() => handleCheckboxChange(index)}
className="form-checkbox"
/>
<span>{file.name}</span>
</li>
))}
</ul>
{files.filter((_, index) => selectedFiles[index]).length < 2 && (
<p className="text-sm text-red-500">
Please select at least two PDFs to merge.
</p>
)}
<button
onClick={handleMerge}
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
disabled={files.filter((_, index) => selectedFiles[index]).length < 2 || isLoading}
>
{isLoading ? "Merging..." : "Merge PDFs"}
</button>
{errorMessage && (
<p className="text-sm text-red-500 mt-2">
{errorMessage}
</p>
)}
{downloadUrl && (
<a
href={downloadUrl}
download="merged.pdf"
className="block mt-4 px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700 text-center"
>
Download Merged PDF
</a>
)}
</div>
);
}

208
frontend/src/tools/Split.js Normal file
View File

@ -0,0 +1,208 @@
import React, { useState } from "react";
import axios from "axios";
import {
Button,
Select,
TextInput,
Checkbox,
Notification,
Stack,
} from "@mantine/core";
import DownloadIcon from "@mui/icons-material/Download";
export default function SplitPdfPanel({ file, downloadUrl, setDownloadUrl }) {
const [mode, setMode] = useState("byPages");
const [pageNumbers, setPageNumbers] = useState("");
const [horizontalDivisions, setHorizontalDivisions] = useState("0");
const [verticalDivisions, setVerticalDivisions] = useState("1");
const [mergeSections, setMergeSections] = useState(false);
const [splitType, setSplitType] = useState("size");
const [splitValue, setSplitValue] = useState("");
const [bookmarkLevel, setBookmarkLevel] = useState("0");
const [includeMetadata, setIncludeMetadata] = useState(false);
const [allowDuplicates, setAllowDuplicates] = useState(false);
const [status, setStatus] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState(null);
const handleSubmit = async (e) => {
e.preventDefault();
if (!file) {
setStatus("Please upload a PDF first.");
return;
}
const formData = new FormData();
formData.append("fileInput", file.file);
let endpoint = "";
switch (mode) {
case "byPages":
formData.append("pageNumbers", pageNumbers);
endpoint = "/api/v1/general/split-pages";
break;
case "bySections":
formData.append("horizontalDivisions", horizontalDivisions);
formData.append("verticalDivisions", verticalDivisions);
formData.append("merge", mergeSections);
endpoint = "/api/v1/general/split-pdf-by-sections";
break;
case "bySizeOrCount":
formData.append("splitType", splitType === "size" ? 0 : splitType === "pages" ? 1 : 2);
formData.append("splitValue", splitValue);
endpoint = "/api/v1/general/split-by-size-or-count";
break;
case "byChapters":
formData.append("bookmarkLevel", bookmarkLevel);
formData.append("includeMetadata", includeMetadata);
formData.append("allowDuplicates", allowDuplicates);
endpoint = "/api/v1/general/split-pdf-by-chapters";
break;
default:
return;
}
setStatus("Processing split...");
setIsLoading(true);
setErrorMessage(null);
try {
const response = await axios.post(endpoint, formData, { responseType: "blob" });
const blob = new Blob([response.data], { type: "application/zip" });
const url = window.URL.createObjectURL(blob);
setDownloadUrl(url);
setStatus("Download ready.");
} catch (error) {
console.error(error);
setErrorMessage(error.response?.data || "An error occurred while splitting the PDF.");
setStatus("Split failed.");
} finally {
setIsLoading(false);
}
};
return (
<form onSubmit={handleSubmit} >
<h3 className="font-semibold">Split PDF</h3>
<Stack spacing="sm" mb={16}>
<Select
label="Split Mode"
value={mode}
onChange={setMode}
data={[
{ value: "byPages", label: "Split by Pages (e.g. 1,3,5-10)" },
{ value: "bySections", label: "Split by Grid Sections" },
{ value: "bySizeOrCount", label: "Split by Size or Count" },
{ value: "byChapters", label: "Split by Chapters" },
]}
/>
{mode === "byPages" && (
<TextInput
label="Pages"
placeholder="e.g. 1,3,5-10"
value={pageNumbers}
onChange={(e) => setPageNumbers(e.target.value)}
/>
)}
{mode === "bySections" && (
<Stack spacing="sm" gap={16}>
<TextInput
label="Horizontal Divisions"
type="number"
min="0"
max="300"
value={horizontalDivisions}
onChange={(e) => setHorizontalDivisions(e.target.value)}
/>
<TextInput
label="Vertical Divisions"
type="number"
min="0"
max="300"
value={verticalDivisions}
onChange={(e) => setVerticalDivisions(e.target.value)}
/>
<Checkbox
label="Merge sections into one PDF"
checked={mergeSections}
onChange={(e) => setMergeSections(e.currentTarget.checked)}
/>
</Stack>
)}
{mode === "bySizeOrCount" && (
<Stack spacing="sm" gap={16}>
<Select
label="Split Type"
value={splitType}
onChange={setSplitType}
data={[
{ value: "size", label: "By Size" },
{ value: "pages", label: "By Page Count" },
{ value: "docs", label: "By Document Count" },
]}
/>
<TextInput
label="Split Value"
placeholder="e.g. 10MB or 5 pages"
value={splitValue}
onChange={(e) => setSplitValue(e.target.value)}
/>
</Stack>
)}
{mode === "byChapters" && (
<Stack spacing="sm">
<TextInput
label="Bookmark Level"
type="number"
value={bookmarkLevel}
onChange={(e) => setBookmarkLevel(e.target.value)}
/>
<Checkbox
label="Include Metadata"
checked={includeMetadata}
onChange={(e) => setIncludeMetadata(e.currentTarget.checked)}
/>
<Checkbox
label="Allow Duplicate Bookmarks"
checked={allowDuplicates}
onChange={(e) => setAllowDuplicates(e.currentTarget.checked)}
/>
</Stack>
)}
<Button type="submit" loading={isLoading} fullWidth>
{isLoading ? "Processing..." : "Split PDF"}
</Button>
{status && <p className="text-xs text-gray-600">{status}</p>}
{errorMessage && (
<Notification color="red" title="Error" onClose={() => setErrorMessage(null)}>
{errorMessage}
</Notification>
)}
{status === "Download ready." && downloadUrl && (
<Button
component="a"
href={downloadUrl}
download="split_output.zip"
leftIcon={<DownloadIcon />}
color="green"
fullWidth
>
Download Split PDF
</Button>
)}
</Stack>
</form>
);
}

View File

@ -0,0 +1,12 @@
module.exports = {
corePlugins: {
preflight: false,
},
content: [
"./src/**/*.{js,jsx,ts,tsx}"
],
theme: {
extend: {},
},
plugins: [],
}

View File

@ -59,7 +59,8 @@ public class AnalysisController {
description = "Returns title, author, subject, etc. Input:PDF Output:JSON Type:SISO")
public Map<String, String> getDocumentProperties(@ModelAttribute PDFFile file)
throws IOException {
// Load the document in read-only mode to prevent modifications and ensure the integrity of the original file.
// Load the document in read-only mode to prevent modifications and ensure the integrity of
// the original file.
try (PDDocument document = pdfDocumentFactory.load(file.getFileInput(), true)) {
PDDocumentInformation info = document.getDocumentInformation();
Map<String, String> properties = new HashMap<>();

View File

@ -146,8 +146,8 @@ public class CertSignController {
summary = "Sign PDF with a Digital Certificate",
description =
"This endpoint accepts a PDF file, a digital certificate and related"
+ " information to sign the PDF. It then returns the digitally signed PDF"
+ " file. Input:PDF Output:PDF Type:SISO")
+ " information to sign the PDF. It then returns the digitally signed PDF"
+ " file. Input:PDF Output:PDF Type:SISO")
public ResponseEntity<byte[]> signPDFWithCert(@ModelAttribute SignPDFWithCertRequest request)
throws Exception {
MultipartFile pdf = request.getFileInput();

View File

@ -1,4 +1,4 @@
package stirling.software.SPDF.controller.web;
package stirling.software.SPDF.controller.api;
import java.io.IOException;
import java.io.InputStream;
@ -9,10 +9,7 @@ import java.util.Map;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.*;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
@ -25,65 +22,39 @@ import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.model.ApplicationProperties;
import stirling.software.SPDF.model.Dependency;
@Controller
@Slf4j
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
@Slf4j
public class HomeWebController {
private final ApplicationProperties applicationProperties;
@GetMapping("/about")
@Hidden
public String gameForm(Model model) {
model.addAttribute("currentPage", "about");
return "about";
}
@GetMapping("/licenses")
@Hidden
public String licensesForm(Model model) {
model.addAttribute("currentPage", "licenses");
Resource resource = new ClassPathResource("static/3rdPartyLicenses.json");
try {
InputStream is = resource.getInputStream();
String json = new String(is.readAllBytes(), StandardCharsets.UTF_8);
ObjectMapper mapper = new ObjectMapper();
Map<String, List<Dependency>> data =
mapper.readValue(json, new TypeReference<Map<String, List<Dependency>>>() {});
model.addAttribute("dependencies", data.get("dependencies"));
} catch (IOException e) {
log.error("exception", e);
}
return "licenses";
}
@GetMapping("/releases")
public String getReleaseNotes(Model model) {
return "releases";
}
@GetMapping("/")
public String home(Model model) {
model.addAttribute("currentPage", "home");
/** Returns the visibility settings for things like surveys. */
@GetMapping("/env")
public Map<String, Object> getEnvironmentFlags() {
String showSurvey = System.getenv("SHOW_SURVEY");
boolean showSurveyValue = showSurvey == null || "true".equalsIgnoreCase(showSurvey);
model.addAttribute("showSurveyFromDocker", showSurveyValue);
return "home";
return Map.of("showSurvey", showSurveyValue);
}
@GetMapping("/home")
public String root(Model model) {
return "redirect:/";
}
@GetMapping("/home-legacy")
public String homeLegacy(Model model) {
model.addAttribute("currentPage", "home-legacy");
return "home-legacy";
/** Returns the third-party licenses as a JSON list. */
@GetMapping("/licenses")
public List<Dependency> getLicenses() {
Resource resource = new ClassPathResource("static/3rdPartyLicenses.json");
try (InputStream is = resource.getInputStream()) {
String json = new String(is.readAllBytes(), StandardCharsets.UTF_8);
ObjectMapper mapper = new ObjectMapper();
Map<String, List<Dependency>> data = mapper.readValue(json, new TypeReference<>() {});
return data.get("dependencies");
} catch (IOException e) {
log.error("Failed to read licenses JSON", e);
throw new RuntimeException("Could not load license data", e);
}
}
/** Dynamic generation of robots.txt based on configuration. */
@GetMapping(value = "/robots.txt", produces = MediaType.TEXT_PLAIN_VALUE)
@ResponseBody
@Hidden
public String getRobotsTxt() {
Boolean allowGoogle = applicationProperties.getSystem().getGooglevisibility();

View File

@ -0,0 +1,18 @@
package stirling.software.SPDF.controller.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class ReactRoutingController {
@GetMapping("/{path:^(?!api|static|robots\\.txt|favicon\\.ico)[^\\.]*$}")
public String forwardRootPaths() {
return "forward:/index.html";
}
@GetMapping("/{path:^(?!api|static)[^\\.]*}/{subpath:^(?!.*\\.).*$}")
public String forwardNestedPaths() {
return "forward:/index.html";
}
}

View File

@ -4,7 +4,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

View File

@ -2,36 +2,32 @@ package stirling.software.SPDF.config.security.mail;
import static org.mockito.Mockito.*;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.multipart.MultipartFile;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import stirling.software.SPDF.model.ApplicationProperties;
import stirling.software.SPDF.model.api.Email;
@ExtendWith(MockitoExtension.class)
public class EmailServiceTest {
@Mock
private JavaMailSender mailSender;
@Mock private JavaMailSender mailSender;
@Mock
private ApplicationProperties applicationProperties;
@Mock private ApplicationProperties applicationProperties;
@Mock
private ApplicationProperties.Mail mailProperties;
@Mock private ApplicationProperties.Mail mailProperties;
@Mock
private MultipartFile fileInput;
@Mock private MultipartFile fileInput;
@InjectMocks
private EmailService emailService;
@InjectMocks private EmailService emailService;
@Test
void testSendEmailWithAttachment() throws MessagingException {

View File

@ -4,7 +4,6 @@ import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import jakarta.mail.MessagingException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -14,6 +13,9 @@ import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.multipart.MultipartFile;
import jakarta.mail.MessagingException;
import stirling.software.SPDF.config.security.mail.EmailService;
import stirling.software.SPDF.model.api.Email;