Замена wordpdf-cli на Spring Boot REST API: wordpdf-app, SPA wordpdf-web, docker-compose

This commit is contained in:
Pjandro
2026-10-13 16:38:18 +00:00
parent aec4dbffe7
commit 8c390104d2
44 changed files with 3439 additions and 337 deletions
+32
View File
@@ -0,0 +1,32 @@
/** Ошибка API: сервер ответил не 2xx — текст из JSON `{"error": …}`. */
export class ApiError extends Error {}
export interface ConvertResult {
blob: Blob
filename: string
}
/**
* Единственная сетевая точка приложения: POST /api/v1/convert (multipart,
* поле `file`) → PDF-blob + имя файла из Content-Disposition.
* Таймаут на фронте не ставим: конвертация долгая — это ожидаемо.
*/
export async function convertDocx(
file: File,
signal: AbortSignal,
): Promise<ConvertResult> {
const fd = new FormData()
fd.append('file', file, file.name)
const resp = await fetch('/api/v1/convert', { method: 'POST', body: fd, signal })
if (!resp.ok) {
const json = (await resp.json().catch(() => null)) as { error?: string } | null
throw new ApiError(json?.error ?? `HTTP ${resp.status}`)
}
// Framework 7 отдаёт `filename*=UTF-8''…` (charset в верхнем регистре) —
// флаг i обязателен; фолбэк — имя исходника с заменой расширения
const cd = resp.headers.get('Content-Disposition') ?? ''
const m = /filename\*=utf-8''([^;]+)/i.exec(cd)
const filename = m ? decodeURIComponent(m[1]) : file.name.replace(/\.docx$/i, '') + '.pdf'
const blob = await resp.blob()
return { blob, filename }
}
+137
View File
@@ -0,0 +1,137 @@
import { useEffect, useRef, useState } from 'react'
import { ApiError, convertDocx } from '../api'
import DropZone from './DropZone'
import Logo from './Logo'
import PdfPreview from './PdfPreview'
import StatusMessage from './StatusMessage'
type Status = 'idle' | 'converting' | 'done' | 'error'
interface Result {
url: string
filename: string
size: number
}
export default function App() {
const [file, setFile] = useState<File | null>(null)
const [status, setStatus] = useState<Status>('idle')
const [result, setResult] = useState<Result | null>(null)
const [error, setError] = useState<string | null>(null)
const abortRef = useRef<AbortController | null>(null)
const urlRef = useRef<string | null>(null)
// снимаем blob-URL предыдущего результата — иначе он течёт до закрытия вкладки
const resetResult = () => {
if (urlRef.current) {
URL.revokeObjectURL(urlRef.current)
urlRef.current = null
}
setResult(null)
setError(null)
}
const selectFile = (picked: File) => {
resetResult()
setStatus('idle')
setFile(picked)
}
const convert = () => {
if (!file || status === 'converting') return
resetResult()
setStatus('converting')
const ac = new AbortController()
abortRef.current = ac
convertDocx(file, ac.signal)
.then(({ blob, filename }) => {
const url = URL.createObjectURL(blob)
urlRef.current = url
setResult({ url, filename, size: blob.size })
setStatus('done')
})
.catch((e: unknown) => {
if (e instanceof DOMException && e.name === 'AbortError') return
// ApiError — осмысленный текст из JSON; всё остальное — нет связи
setError(e instanceof ApiError ? e.message : 'Сервер недоступен')
setStatus('error')
})
.finally(() => {
abortRef.current = null
})
}
useEffect(
() => () => {
abortRef.current?.abort()
if (urlRef.current) URL.revokeObjectURL(urlRef.current)
},
[],
)
return (
<div className="min-h-screen bg-bg">
<div className="mx-auto max-w-[760px] px-5 py-12">
<header className="mb-8 flex items-center gap-3">
<Logo className="h-10 w-10 shrink-0 text-accent" />
<div>
<h1 className="text-2xl font-semibold">Word → PDF</h1>
<p className="mt-1 text-sm text-muted">
docx → PDF на docx4j + Apache FOP. Лимиты: файл ≤ 5 МБ, документ ≤ 100
страниц.
</p>
</div>
</header>
<section className="rounded-2xl border border-border bg-surface p-6 shadow-sm">
<DropZone file={file} disabled={status === 'converting'} onSelect={selectFile} />
<div className="mt-5">
<button
type="button"
onClick={convert}
disabled={!file || status === 'converting'}
className={`flex items-center gap-2 rounded-lg bg-accent px-6 py-3 font-medium text-white ${
!file || status === 'converting' ? 'cursor-default opacity-60' : 'hover:bg-accent/90'
}`}
>
{status === 'converting' ? (
<>
<span
className="h-4 w-4 animate-spin rounded-full border-2 border-white/40 border-t-white"
aria-hidden="true"
/>
Конвертация…
</>
) : (
'Конвертировать'
)}
</button>
</div>
{status === 'done' && result && (
<StatusMessage
kind="success"
text={`Готово · ${result.filename} · ${(result.size / 1024).toFixed(0)} КБ`}
/>
)}
{status === 'error' && error && <StatusMessage kind="error" text={error} />}
{status === 'done' && result && (
<PdfPreview url={result.url} filename={result.filename} />
)}
</section>
<footer className="mt-8 text-sm text-muted">
<a href="/swagger-ui.html" className="underline-offset-2 hover:text-accent hover:underline">
Swagger UI
</a>
{' · '}
<a href="/v3/api-docs" className="underline-offset-2 hover:text-accent hover:underline">
OpenAPI
</a>
</footer>
</div>
</div>
)
}
+77
View File
@@ -0,0 +1,77 @@
import { useRef, useState } from 'react'
import type { DragEvent } from 'react'
interface Props {
file: File | null
disabled: boolean
onSelect: (file: File) => void
}
/**
* Зона drag&drop + клик для выбора .docx. Скрытый input[type=file] —
* единственный источник выбора; drop берёт первый файл.
*/
export default function DropZone({ file, disabled, onSelect }: Props) {
const inputRef = useRef<HTMLInputElement>(null)
const [dragging, setDragging] = useState(false)
const onDrop = (e: DragEvent<HTMLLabelElement>) => {
e.preventDefault()
setDragging(false)
if (disabled) return
const dropped = e.dataTransfer.files[0]
if (dropped) onSelect(dropped)
}
return (
<label
onDragOver={(e) => {
e.preventDefault()
if (!disabled) setDragging(true)
}}
onDragLeave={(e) => {
e.preventDefault()
setDragging(false)
}}
onDrop={onDrop}
className={`flex cursor-pointer flex-col items-center gap-3 rounded-xl border-2 border-dashed p-9 text-center transition-colors ${
dragging
? 'border-accent bg-accent/6'
: 'border-border hover:border-accent hover:bg-accent/6'
}`}
>
<svg
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.8"
strokeLinecap="round"
strokeLinejoin="round"
className="h-9 w-9 text-accent"
aria-hidden="true"
>
<path d="M12 16V4m0 0-4 4m4-4 4 4" />
<path d="M4 16v3a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-3" />
</svg>
<span>Перетащите .docx сюда или нажмите для выбора</span>
{file && (
<span className="text-sm text-muted">
{file.name} · {(file.size / 1024).toFixed(0)} КБ
</span>
)}
<input
ref={inputRef}
type="file"
accept=".docx"
className="sr-only"
disabled={disabled}
onChange={(e) => {
const picked = e.target.files?.[0]
if (picked) onSelect(picked)
// сбрасываем value — иначе повторный выбор того же файла не событие
e.target.value = ''
}}
/>
</label>
)
}
+21
View File
@@ -0,0 +1,21 @@
/** Логотип: лист A4 → стрелка → лист PDF. Красится currentColor. */
export default function Logo({ className }: { className?: string }) {
return (
<svg
viewBox="0 0 40 40"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className={className}
aria-hidden="true"
>
<rect x="2.5" y="8" width="15" height="24" rx="2" />
<path d="M6.5 14.5h7M6.5 19h7M6.5 23.5h4" />
<path d="M20 20h7m0 0-2.5-2.5M27 20l-2.5 2.5" />
<rect x="29.5" y="8" width="8" height="24" rx="2" />
<path d="M31.5 26.5h4M31.5 14h4v5h-4z" />
</svg>
)
}
+34
View File
@@ -0,0 +1,34 @@
interface Props {
url: string
filename: string
}
/** Предпросмотр PDF (blob-URL в iframe) + кнопки скачивания. */
export default function PdfPreview({ url, filename }: Props) {
return (
<section className="mt-6">
<iframe
src={url}
title="Предпросмотр PDF"
className="h-[65vh] w-full rounded-xl border-0 shadow-sm"
/>
<div className="mt-4 flex gap-3">
<a
href={url}
download={filename}
className="rounded-lg bg-accent px-6 py-3 font-medium text-white hover:bg-accent/90"
>
Скачать PDF
</a>
<a
href={url}
target="_blank"
rel="noopener"
className="rounded-lg border border-border px-6 py-3 font-medium hover:border-accent"
>
Открыть в новой вкладке
</a>
</div>
</section>
)
}
@@ -0,0 +1,33 @@
interface Props {
kind: 'success' | 'error'
/** Для success: «Готово · имя · КБ»; для error: текст ошибки. */
text: string
}
/** Строка результата над/под кнопкой: успех (зелёный) или ошибка (красный). */
export default function StatusMessage({ kind, text }: Props) {
const ok = kind === 'success'
return (
<p
role="status"
aria-live="polite"
className={`mt-5 flex items-center gap-2 text-sm font-medium ${
ok ? 'text-ok' : 'text-err'
}`}
>
<svg
viewBox="0 0 20 20"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="h-4.5 w-4.5 shrink-0"
aria-hidden="true"
>
{ok ? <path d="M4 10.5l4 4 8-9" /> : <path d="M5 5l10 10M15 5 5 15" />}
</svg>
{text}
</p>
)
}
+29
View File
@@ -0,0 +1,29 @@
@import "tailwindcss";
@theme {
--color-bg: #f6f7f9;
--color-surface: #ffffff;
--color-border: #e3e6ea;
--color-text: #1c2333;
--color-muted: #667085;
--color-accent: #2f6fed;
--color-ok: #1a7f37;
--color-err: #d1242f;
}
@media (prefers-color-scheme: dark) {
:root {
--color-bg: #0f1420;
--color-surface: #171e2e;
--color-border: #2a3348;
--color-text: #e6e9f0;
--color-muted: #98a2b3;
--color-accent: #4f83f1;
--color-ok: #3fb950;
--color-err: #f85149;
}
}
body {
@apply bg-bg text-text antialiased;
}
+10
View File
@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './components/App'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)