Compare commits
44
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e630ca5521 | ||
|
|
182eb504de | ||
|
|
98fa5dfcc1 | ||
|
|
429520d3f9 | ||
|
|
fbfe1da7da | ||
|
|
c047bdda8c | ||
|
|
a33e22559b | ||
|
|
1318604f32 | ||
|
|
43a5f72b01 | ||
|
|
d97820c232 | ||
|
|
03cd7c1456 | ||
|
|
b1b37366e8 | ||
|
|
5cd9377bba | ||
|
|
a3e1cc8393 | ||
|
|
1810a12cf3 | ||
|
|
c3cd8c48b5 | ||
|
|
2502a8def0 | ||
|
|
54cd804319 | ||
|
|
1b0a1e938e | ||
|
|
69b035c6e1 | ||
|
|
8164c56d33 | ||
|
|
098f2badec | ||
|
|
d2a4054120 | ||
|
|
7baf503d60 | ||
|
|
d9622d0fac | ||
|
|
ddba5a3eab | ||
|
|
0bfb90cfc1 | ||
|
|
c454a72f08 | ||
|
|
34fd328444 | ||
|
|
738dd0645d | ||
|
|
e997f0d4ff | ||
|
|
e137436656 | ||
|
|
1649b9bffb | ||
|
|
c990ab3216 | ||
|
|
e6d3f20c36 | ||
|
|
79d5bc942d | ||
|
|
d652fc1d1c | ||
|
|
22a1412242 | ||
|
|
0c3c0765a3 | ||
|
|
56f98dfb39 | ||
|
|
867f3bdeff | ||
|
|
11441caa30 | ||
|
|
20098a5254 | ||
|
|
a0117f9789 |
@@ -1 +1 @@
|
||||
allow-ghsas: GHSA-wrw7-89jp-8q8g
|
||||
allow-ghsas: GHSA-wrw7-89jp-8q8g
|
||||
|
||||
@@ -21,3 +21,38 @@ updates:
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
|
||||
- package-ecosystem: npm
|
||||
directory: /devTools
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
|
||||
- package-ecosystem: docker
|
||||
directory: /docker/backend
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
|
||||
- package-ecosystem: docker
|
||||
directory: /docker/embedded
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
|
||||
- package-ecosystem: docker
|
||||
directory: /docker/frontend
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
|
||||
- package-ecosystem: npm
|
||||
directory: /frontend
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
|
||||
- package-ecosystem: cargo
|
||||
directory: /frontend/src-tauri
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
|
||||
- package-ecosystem: pip
|
||||
directory: /testing/cucumber
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
|
||||
@@ -14,12 +14,10 @@ Usage:
|
||||
# Sample for Windows:
|
||||
# python .github/scripts/check_language_toml.py --reference-file frontend/public/locales/en-GB/translation.toml --branch "" --files frontend/public/locales/de-DE/translation.toml frontend/public/locales/fr-FR/translation.toml
|
||||
|
||||
import copy
|
||||
import glob
|
||||
import os
|
||||
import argparse
|
||||
import re
|
||||
import json
|
||||
import tomllib # Python 3.11+ (stdlib)
|
||||
import tomli_w # For writing TOML files
|
||||
|
||||
@@ -38,7 +36,7 @@ def find_duplicate_keys(file_path, keys=None, prefix=""):
|
||||
duplicates = []
|
||||
|
||||
# Load TOML file
|
||||
with open(file_path, 'rb') as file:
|
||||
with open(file_path, "rb") as file:
|
||||
data = tomllib.load(file)
|
||||
|
||||
def process_dict(obj, current_prefix=""):
|
||||
@@ -67,7 +65,7 @@ def parse_toml_file(file_path):
|
||||
:param file_path: Path to the TOML file.
|
||||
:return: Dictionary with flattened keys.
|
||||
"""
|
||||
with open(file_path, 'rb') as file:
|
||||
with open(file_path, "rb") as file:
|
||||
data = tomllib.load(file)
|
||||
|
||||
def flatten_dict(d, parent_key="", sep="."):
|
||||
@@ -193,13 +191,13 @@ def check_for_differences(reference_file, file_list, branch, actor):
|
||||
basename_current_file = os.path.basename(os.path.join(branch, file_normpath))
|
||||
locale_dir = os.path.basename(os.path.dirname(file_normpath))
|
||||
|
||||
if (
|
||||
basename_current_file == basename_reference_file
|
||||
and locale_dir == "en-GB"
|
||||
):
|
||||
if basename_current_file == basename_reference_file and locale_dir == "en-GB":
|
||||
continue
|
||||
|
||||
if not file_normpath.endswith(".toml") or basename_current_file != "translation.toml":
|
||||
if (
|
||||
not file_normpath.endswith(".toml")
|
||||
or basename_current_file != "translation.toml"
|
||||
):
|
||||
continue
|
||||
|
||||
only_reference_file = False
|
||||
@@ -288,7 +286,9 @@ def check_for_differences(reference_file, file_list, branch, actor):
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description="Find missing keys in TOML translation files")
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Find missing keys in TOML translation files"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--actor",
|
||||
required=False,
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
#
|
||||
# pip-compile --generate-hashes --output-file='.github\scripts\requirements_pre_commit.txt' --strip-extras '.github\scripts\requirements_pre_commit.in'
|
||||
#
|
||||
cfgv==3.4.0 \
|
||||
--hash=sha256:b7265b1f29fd3316bfcd2b330d63d024f2bfd8bcb8b0272f8e19a504856c48f9 \
|
||||
--hash=sha256:e52591d4c5f5dead8e0f673fb16db7949d2cfb3f7da4582893288f0ded8fe560
|
||||
cfgv==3.5.0 \
|
||||
--hash=sha256:a8dc6b26ad22ff227d2634a65cb388215ce6cc96bbcc5cfde7641ae87e8dacc0 \
|
||||
--hash=sha256:d5b1034354820651caa73ede66a6294d6e95c1b00acc5e9b098e917404669132
|
||||
# via pre-commit
|
||||
distlib==0.4.0 \
|
||||
--hash=sha256:9659f7d87e46584a30b5780e43ac7a2143098441670ff0a49d5f9034c54a6c16 \
|
||||
@@ -28,9 +28,9 @@ platformdirs==4.5.0 \
|
||||
--hash=sha256:70ddccdd7c99fc5942e9fc25636a8b34d04c24b335100223152c2803e4063312 \
|
||||
--hash=sha256:e578a81bb873cbb89a41fcc904c7ef523cc18284b7e3b3ccf06aca1403b7ebd3
|
||||
# via virtualenv
|
||||
pre-commit==4.3.0 \
|
||||
--hash=sha256:2b0747ad7e6e967169136edffee14c16e148a778a54e4f967921aa1ebf2308d8 \
|
||||
--hash=sha256:499fe450cc9d42e9d58e606262795ecb64dd05438943c62b66f6a8673da30b16
|
||||
pre-commit==4.5.0 \
|
||||
--hash=sha256:25e2ce09595174d9c97860a95609f9f852c0614ba602de3561e267547f2335e1 \
|
||||
--hash=sha256:dc5a065e932b19fc1d4c653c6939068fe54325af8e741e74e88db4d28a4dd66b
|
||||
# via -r .github/scripts/requirements_pre_commit.in
|
||||
pyyaml==6.0.3 \
|
||||
--hash=sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c \
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
tomlkit
|
||||
tomli-w
|
||||
|
||||
@@ -4,6 +4,10 @@
|
||||
#
|
||||
# pip-compile --generate-hashes --output-file='.github\scripts\requirements_sync_readme.txt' --strip-extras '.github\scripts\requirements_sync_readme.in'
|
||||
#
|
||||
tomli-w==1.2.0 \
|
||||
--hash=sha256:188306098d013b691fcadc011abd66727d3c414c571bb01b1a174ba8c983cf90 \
|
||||
--hash=sha256:2dd14fac5a47c27be9cd4c976af5a12d87fb1f0b4512f81d69cce3b35ae25021
|
||||
# via -r .github/scripts/requirements_sync_readme.in
|
||||
tomlkit==0.13.3 \
|
||||
--hash=sha256:430cf247ee57df2b94ee3fbe588e71d362a941ebb545dec29b53961d61add2a1 \
|
||||
--hash=sha256:c89c649d79ee40629a9fda55f8ace8c6a1b42deb912b2a8fd8d942ddadb606b0
|
||||
|
||||
@@ -37,7 +37,7 @@ jobs:
|
||||
|
||||
- name: Resolve PR info
|
||||
id: resolve
|
||||
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
with:
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
@@ -128,7 +128,7 @@ jobs:
|
||||
|
||||
- name: Add deployment started comment
|
||||
id: deployment-started
|
||||
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
with:
|
||||
github-token: ${{ steps.setup-bot.outputs.token }}
|
||||
script: |
|
||||
@@ -352,7 +352,7 @@ jobs:
|
||||
|
||||
- name: Post V2 deployment URL to PR
|
||||
if: success()
|
||||
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
with:
|
||||
github-token: ${{ steps.setup-bot.outputs.token }}
|
||||
script: |
|
||||
@@ -419,7 +419,7 @@ jobs:
|
||||
private-key: ${{ secrets.GH_APP_PRIVATE_KEY }}
|
||||
|
||||
- name: Clean up V2 deployment comments
|
||||
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
with:
|
||||
github-token: ${{ steps.setup-bot.outputs.token }}
|
||||
script: |
|
||||
|
||||
@@ -87,7 +87,7 @@ jobs:
|
||||
- name: AI PR Title Analysis
|
||||
if: steps.actor.outputs.is_repo_dev == 'true'
|
||||
id: ai-title-analysis
|
||||
uses: actions/ai-inference@b81b2afb8390ee6839b494a404766bef6493c7d9 # v1.2.8
|
||||
uses: actions/ai-inference@334892bb203895caaed82ec52d23c1ed9385151e # v2.0.4
|
||||
with:
|
||||
model: openai/gpt-4o
|
||||
system-prompt-file: ".github/config/system-prompt.txt"
|
||||
|
||||
@@ -238,7 +238,7 @@ jobs:
|
||||
sudo chmod +x /usr/local/bin/docker-compose
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@e797f83bcb11b83ae66e0230d6156d7c80228e7c # v6.0.0
|
||||
uses: actions/setup-python@83679a892e2d95755f2dac6acb0bfd1e9ac5d548 # v6.1.0
|
||||
with:
|
||||
python-version: "3.12"
|
||||
cache: 'pip' # caching pip dependencies
|
||||
|
||||
@@ -194,13 +194,13 @@ jobs:
|
||||
core.exportVariable("REFERENCE_FILE", referenceFilePath);
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@e797f83bcb11b83ae66e0230d6156d7c80228e7c # v6.0.0
|
||||
uses: actions/setup-python@83679a892e2d95755f2dac6acb0bfd1e9ac5d548 # v6.1.0
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Install Python dependencies
|
||||
run: |
|
||||
pip install tomli-w
|
||||
pip install --require-hashes tomli-w==1.2.0 --hash sha256:188306098d013b691fcadc011abd66727d3c414c571bb01b1a174ba8c983cf90
|
||||
|
||||
- name: Run Python script to check files
|
||||
id: run-check
|
||||
|
||||
@@ -23,10 +23,10 @@ jobs:
|
||||
egress-policy: audit
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1
|
||||
|
||||
- name: Get commit hashes for frontend and backend
|
||||
id: commit-hashes
|
||||
@@ -86,14 +86,14 @@ jobs:
|
||||
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@5e57cd118135c172c3672efd75eb46360885c0ef # v3.6.0
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_HUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_HUB_API }}
|
||||
|
||||
- name: Build and push frontend image
|
||||
if: steps.check-frontend.outputs.exists == 'false'
|
||||
uses: docker/build-push-action@v6
|
||||
uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||
with:
|
||||
context: .
|
||||
file: ./docker/frontend/Dockerfile
|
||||
@@ -106,7 +106,7 @@ jobs:
|
||||
|
||||
- name: Build and push backend image
|
||||
if: steps.check-backend.outputs.exists == 'false'
|
||||
uses: docker/build-push-action@v6
|
||||
uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||
with:
|
||||
context: .
|
||||
file: ./docker/backend/Dockerfile
|
||||
|
||||
@@ -253,7 +253,7 @@ jobs:
|
||||
- name: Create Pull Request (Push only)
|
||||
id: cpr
|
||||
if: github.event_name == 'push' && env.CHANGES_DETECTED == 'true'
|
||||
uses: peter-evans/create-pull-request@271a8d0340265f705b14b6d32b9829c1cb33d45e # v7.0.8
|
||||
uses: peter-evans/create-pull-request@98357b18bf14b5342f975ff684046ec3b2a07725 # v8.0.0
|
||||
with:
|
||||
token: ${{ steps.setup-bot.outputs.token }}
|
||||
commit-message: "Update Frontend 3rd Party Licenses"
|
||||
|
||||
@@ -82,7 +82,7 @@ jobs:
|
||||
- name: Create Pull Request
|
||||
id: cpr
|
||||
if: env.CHANGES_DETECTED == 'true'
|
||||
uses: peter-evans/create-pull-request@84ae59a2cdc2258d6fa0732dd66352dddae2a412 # v7.0.9
|
||||
uses: peter-evans/create-pull-request@98357b18bf14b5342f975ff684046ec3b2a07725 # v8.0.0
|
||||
with:
|
||||
token: ${{ steps.setup-bot.outputs.token }}
|
||||
commit-message: "Update 3rd Party Licenses"
|
||||
|
||||
@@ -562,7 +562,7 @@ jobs:
|
||||
run: ls -R ./artifacts
|
||||
|
||||
- name: Upload binaries to Release
|
||||
uses: softprops/action-gh-release@5be0e66d93ac7ed76da52eca8bb058f665c3a5fe # v2.4.2
|
||||
uses: softprops/action-gh-release@a06a81a03ee405af7f2048a818ed3f03bbf83c7b # v2.5.0
|
||||
with:
|
||||
tag_name: v${{ needs.determine-matrix.outputs.version }}
|
||||
generate_release_notes: true
|
||||
|
||||
@@ -38,7 +38,7 @@ jobs:
|
||||
private-key: ${{ secrets.GH_APP_PRIVATE_KEY }}
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@e797f83bcb11b83ae66e0230d6156d7c80228e7c # v6.0.0
|
||||
uses: actions/setup-python@83679a892e2d95755f2dac6acb0bfd1e9ac5d548 # v6.1.0
|
||||
with:
|
||||
python-version: 3.12
|
||||
cache: 'pip' # caching pip dependencies
|
||||
@@ -67,7 +67,7 @@ jobs:
|
||||
|
||||
- name: Create Pull Request
|
||||
if: env.CHANGES_DETECTED == 'true'
|
||||
uses: peter-evans/create-pull-request@84ae59a2cdc2258d6fa0732dd66352dddae2a412 # v7.0.9
|
||||
uses: peter-evans/create-pull-request@98357b18bf14b5342f975ff684046ec3b2a07725 # v8.0.0
|
||||
with:
|
||||
token: ${{ steps.setup-bot.outputs.token }}
|
||||
commit-message: ":file_folder: pre-commit"
|
||||
|
||||
@@ -83,7 +83,7 @@ jobs:
|
||||
|
||||
- name: Generate tags for latest (V2-master branch - production)
|
||||
id: meta
|
||||
uses: docker/metadata-action@c1e51972afc2121e065aed6d45c65596fe445f3f # v5.8.0
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
if: github.ref == 'refs/heads/V2-master'
|
||||
with:
|
||||
images: |
|
||||
@@ -97,7 +97,7 @@ jobs:
|
||||
|
||||
- name: Generate tags for latest (V1_V2_merge branch - test)
|
||||
id: meta-test
|
||||
uses: docker/metadata-action@c1e51972afc2121e065aed6d45c65596fe445f3f # v5.8.0
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
if: github.ref == 'refs/heads/V1_V2_merge'
|
||||
with:
|
||||
images: |
|
||||
@@ -139,7 +139,7 @@ jobs:
|
||||
|
||||
- name: Generate tags for latest-fat (V2-master branch - production)
|
||||
id: meta-fat
|
||||
uses: docker/metadata-action@c1e51972afc2121e065aed6d45c65596fe445f3f # v5.8.0
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
if: github.ref == 'refs/heads/V2-master'
|
||||
with:
|
||||
images: |
|
||||
@@ -153,7 +153,7 @@ jobs:
|
||||
|
||||
- name: Generate tags for latest-fat (V1_V2_merge branch - test)
|
||||
id: meta-fat-test
|
||||
uses: docker/metadata-action@c1e51972afc2121e065aed6d45c65596fe445f3f # v5.8.0
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
if: github.ref == 'refs/heads/V1_V2_merge'
|
||||
with:
|
||||
images: |
|
||||
@@ -193,7 +193,7 @@ jobs:
|
||||
|
||||
- name: Generate tags for ultra-lite (V2-master branch - production)
|
||||
id: meta-lite
|
||||
uses: docker/metadata-action@c1e51972afc2121e065aed6d45c65596fe445f3f # v5.8.0
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
if: github.ref == 'refs/heads/V2-master'
|
||||
with:
|
||||
images: |
|
||||
@@ -207,7 +207,7 @@ jobs:
|
||||
|
||||
- name: Generate tags for ultra-lite (V1_V2_merge branch - test)
|
||||
id: meta-lite-test
|
||||
uses: docker/metadata-action@c1e51972afc2121e065aed6d45c65596fe445f3f # v5.8.0
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
if: github.ref == 'refs/heads/V1_V2_merge'
|
||||
with:
|
||||
images: |
|
||||
|
||||
@@ -89,7 +89,7 @@ jobs:
|
||||
|
||||
- name: Generate tags
|
||||
id: meta
|
||||
uses: docker/metadata-action@318604b99e75e41977312d83839a89be02ca4893 # v5.9.0
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
if: github.ref != 'refs/heads/main'
|
||||
with:
|
||||
images: |
|
||||
@@ -135,7 +135,7 @@ jobs:
|
||||
|
||||
- name: Generate tags ultra-lite
|
||||
id: meta2
|
||||
uses: docker/metadata-action@318604b99e75e41977312d83839a89be02ca4893 # v5.9.0
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
if: github.ref != 'refs/heads/main'
|
||||
with:
|
||||
images: |
|
||||
@@ -166,7 +166,7 @@ jobs:
|
||||
|
||||
- name: Generate tags fat
|
||||
id: meta3
|
||||
uses: docker/metadata-action@318604b99e75e41977312d83839a89be02ca4893 # v5.9.0
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
with:
|
||||
images: |
|
||||
${{ secrets.DOCKER_HUB_USERNAME }}/s-pdf
|
||||
|
||||
@@ -526,7 +526,7 @@ jobs:
|
||||
run: ls -R ./artifacts
|
||||
|
||||
- name: Create GitHub Release
|
||||
uses: softprops/action-gh-release@5be0e66d93ac7ed76da52eca8bb058f665c3a5fe # v2.4.2
|
||||
uses: softprops/action-gh-release@a06a81a03ee405af7f2048a818ed3f03bbf83c7b # v2.5.0
|
||||
with:
|
||||
tag_name: v${{ needs.determine-matrix.outputs.version }}
|
||||
generate_release_notes: true
|
||||
|
||||
@@ -22,7 +22,7 @@ jobs:
|
||||
egress-policy: audit
|
||||
|
||||
- name: 30 days stale issues
|
||||
uses: actions/stale@5f858e3efba33a5ca4407a664cc011ad407f2008 # v10.1.0
|
||||
uses: actions/stale@997185467fa4f803885201cee163a9f38240193d # v10.1.1
|
||||
with:
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
days-before-stale: 30
|
||||
|
||||
@@ -47,14 +47,13 @@ jobs:
|
||||
private-key: ${{ secrets.GH_APP_PRIVATE_KEY }}
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@e797f83bcb11b83ae66e0230d6156d7c80228e7c # v6.0.0
|
||||
uses: actions/setup-python@83679a892e2d95755f2dac6acb0bfd1e9ac5d548 # v6.1.0
|
||||
with:
|
||||
python-version: "3.12"
|
||||
cache: "pip" # caching pip dependencies
|
||||
|
||||
- name: Install Python dependencies
|
||||
run: |
|
||||
pip install tomli-w
|
||||
run: pip install --require-hashes -r ./.github/scripts/requirements_sync_readme.txt
|
||||
|
||||
- name: Sync translation TOML files
|
||||
run: |
|
||||
@@ -65,9 +64,6 @@ jobs:
|
||||
git add frontend/public/locales/*/translation.toml
|
||||
git diff --staged --quiet || git commit -m ":memo: Sync translation files (TOML)" || echo "No changes detected"
|
||||
|
||||
- name: Install README dependencies
|
||||
run: pip install --require-hashes -r ./.github/scripts/requirements_sync_readme.txt
|
||||
|
||||
- name: Sync README.md
|
||||
run: |
|
||||
python scripts/counter_translation_v3.py
|
||||
@@ -79,7 +75,7 @@ jobs:
|
||||
|
||||
- name: Create Pull Request
|
||||
if: always()
|
||||
uses: peter-evans/create-pull-request@271a8d0340265f705b14b6d32b9829c1cb33d45e # v7.0.8
|
||||
uses: peter-evans/create-pull-request@98357b18bf14b5342f975ff684046ec3b2a07725 # v8.0.0
|
||||
with:
|
||||
token: ${{ steps.setup-bot.outputs.token }}
|
||||
commit-message: Update files
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
repos:
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
rev: v0.14.2
|
||||
rev: v0.14.8
|
||||
hooks:
|
||||
- id: ruff
|
||||
args:
|
||||
@@ -22,7 +22,7 @@ repos:
|
||||
files: \.(html|css|js|py|md)$
|
||||
exclude: (.vscode|.devcontainer|app/core/src/main/resources|app/proprietary/src/main/resources|Dockerfile|.*/pdfjs.*|.*/thirdParty.*|bootstrap.*|.*\.min\..*|.*diff\.js)
|
||||
- repo: https://github.com/gitleaks/gitleaks
|
||||
rev: v8.28.0
|
||||
rev: v8.30.0
|
||||
hooks:
|
||||
- id: gitleaks
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
|
||||
@@ -96,6 +96,22 @@
|
||||
"moduleName": ".*",
|
||||
"moduleLicense": "MPL 2.0"
|
||||
},
|
||||
{
|
||||
"moduleName": ".*",
|
||||
"moduleLicense": "Mozilla Public License, Version 2.0"
|
||||
},
|
||||
{
|
||||
"moduleName": ".*",
|
||||
"moduleLicense": "Mozilla Public License 2.0 (MPL-2.0)"
|
||||
},
|
||||
{
|
||||
"moduleName": ".*",
|
||||
"moduleLicense": "CDDL+GPL License"
|
||||
},
|
||||
{
|
||||
"moduleName": ".*",
|
||||
"moduleLicense": "BSD"
|
||||
},
|
||||
{
|
||||
"moduleName": ".*",
|
||||
"moduleLicense": "UnboundID SCIM2 SDK Free Use License"
|
||||
|
||||
@@ -156,19 +156,19 @@ public class EndpointConfiguration {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Rule 2: For tool groups, they're enabled unless explicitly disabled (handled above)
|
||||
if (isToolGroup(group)) {
|
||||
log.debug("isGroupEnabled('{}') -> true (tool group not disabled)", group);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Rule 3: For functional groups, check if all endpoints are enabled
|
||||
Set<String> endpoints = endpointGroups.get(group);
|
||||
if (endpoints == null || endpoints.isEmpty()) {
|
||||
log.debug("isGroupEnabled('{}') -> false (no endpoints)", group);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Rule 2: For functional groups, check if all endpoints are enabled
|
||||
// Rule 3: For tool groups, they're enabled unless explicitly disabled (handled above)
|
||||
if (isToolGroup(group)) {
|
||||
log.debug("isGroupEnabled('{}') -> true (tool group not disabled)", group);
|
||||
return true;
|
||||
}
|
||||
|
||||
// For functional groups, check each endpoint individually
|
||||
for (String endpoint : endpoints) {
|
||||
if (!isEndpointEnabledDirectly(endpoint)) {
|
||||
@@ -353,6 +353,7 @@ public class EndpointConfiguration {
|
||||
addEndpointToGroup("Security", "auto-redact");
|
||||
addEndpointToGroup("Security", "redact");
|
||||
addEndpointToGroup("Security", "validate-signature");
|
||||
addEndpointToGroup("Security", "verify-pdf");
|
||||
addEndpointToGroup("Security", "stamp");
|
||||
addEndpointToGroup("Security", "sign");
|
||||
|
||||
@@ -479,6 +480,8 @@ public class EndpointConfiguration {
|
||||
addEndpointToGroup("Java", "pdf-to-json");
|
||||
addEndpointToGroup("Java", "json-to-pdf");
|
||||
addEndpointToGroup("rar", "pdf-to-cbr");
|
||||
addEndpointToGroup("Java", "pdf-to-video");
|
||||
addEndpointToGroup("Java", "verify-pdf");
|
||||
|
||||
// Javascript
|
||||
addEndpointToGroup("Javascript", "pdf-organizer");
|
||||
@@ -535,6 +538,9 @@ public class EndpointConfiguration {
|
||||
addEndpointToGroup("Weasyprint", "markdown-to-pdf");
|
||||
addEndpointToGroup("Weasyprint", "eml-to-pdf");
|
||||
|
||||
// veraPDF dependent endpoints
|
||||
addEndpointToGroup("veraPDF", "verify-pdf");
|
||||
|
||||
// Pdftohtml dependent endpoints
|
||||
addEndpointToGroup("Pdftohtml", "pdf-to-html");
|
||||
addEndpointToGroup("Pdftohtml", "pdf-to-markdown");
|
||||
@@ -585,7 +591,10 @@ public class EndpointConfiguration {
|
||||
|| "Weasyprint".equals(group)
|
||||
|| "Pdftohtml".equals(group)
|
||||
|| "ImageMagick".equals(group)
|
||||
|| "rar".equals(group);
|
||||
|| "rar".equals(group)
|
||||
|| "Calibre".equals(group)
|
||||
|| "FFmpeg".equals(group)
|
||||
|| "veraPDF".equals(group);
|
||||
}
|
||||
|
||||
private boolean isEndpointEnabledDirectly(String endpoint) {
|
||||
|
||||
@@ -393,6 +393,7 @@ public class ApplicationProperties {
|
||||
private boolean googlevisibility;
|
||||
private boolean showUpdate;
|
||||
private boolean showUpdateOnlyAdmin;
|
||||
private boolean showSettingsWhenNoLogin = true;
|
||||
private boolean customHTMLFiles;
|
||||
private String tessdataDir;
|
||||
private boolean enableAlphaFunctionality;
|
||||
|
||||
+22
-3
@@ -71,6 +71,13 @@ dependencies {
|
||||
implementation "org.apache.pdfbox:preflight:$pdfboxVersion"
|
||||
implementation "org.apache.pdfbox:xmpbox:$pdfboxVersion"
|
||||
|
||||
implementation 'org.verapdf:validation-model:1.28.2'
|
||||
|
||||
// veraPDF still uses javax.xml.bind, not the new jakarta namespace
|
||||
implementation 'javax.xml.bind:jaxb-api:2.3.1'
|
||||
implementation 'com.sun.xml.bind:jaxb-impl:2.3.9'
|
||||
implementation 'com.sun.xml.bind:jaxb-core:2.3.0.1'
|
||||
|
||||
// https://mvnrepository.com/artifact/technology.tabula/tabula
|
||||
implementation ('technology.tabula:tabula:1.0.5') {
|
||||
exclude group: 'org.slf4j', module: 'slf4j-simple'
|
||||
@@ -268,6 +275,18 @@ tasks.register('cleanFrontendAssets', Delete) {
|
||||
delete generatedFrontendPaths.collect { new File(resourcesStaticDir, it) }
|
||||
}
|
||||
|
||||
tasks.register('copyApiLandingPage', Copy) {
|
||||
group = 'frontend'
|
||||
description = 'Copy API landing page to index.html for backend-only mode'
|
||||
from(new File(resourcesStaticDir, 'api-landing.html'))
|
||||
into(resourcesStaticDir)
|
||||
rename('api-landing.html', 'index.html')
|
||||
dependsOn cleanFrontendAssets
|
||||
doFirst {
|
||||
println "Copying API landing page to index.html for backend-only mode..."
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure copyFrontendAssets runs after spotless tasks
|
||||
tasks.named('copyFrontendAssets').configure {
|
||||
mustRunAfter tasks.matching { it.name.startsWith('spotless') }
|
||||
@@ -277,9 +296,9 @@ if (buildWithFrontend) {
|
||||
println "Frontend build enabled - JAR will include React frontend"
|
||||
processResources.dependsOn copyFrontendAssets
|
||||
} else {
|
||||
println "Frontend build disabled - JAR will be backend-only"
|
||||
// When not building the UI, ensure any stale frontend assets are removed
|
||||
processResources.dependsOn cleanFrontendAssets
|
||||
println "Frontend build disabled - JAR will be backend-only with API landing page"
|
||||
// When not building the UI, ensure any stale frontend assets are removed and use API landing page
|
||||
processResources.dependsOn copyApiLandingPage
|
||||
}
|
||||
|
||||
bootJar.dependsOn ':common:jar'
|
||||
|
||||
+870
-341
File diff suppressed because it is too large
Load Diff
+162
-9
@@ -1,5 +1,6 @@
|
||||
package stirling.software.SPDF.controller.api.misc;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
@@ -17,8 +18,12 @@ import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.SPDF.config.swagger.StandardPdfResponse;
|
||||
import stirling.software.SPDF.controller.api.converters.ConvertPDFToPDFA;
|
||||
import stirling.software.SPDF.model.api.misc.AddAttachmentRequest;
|
||||
import stirling.software.SPDF.model.api.misc.DeleteAttachmentRequest;
|
||||
import stirling.software.SPDF.model.api.misc.ExtractAttachmentsRequest;
|
||||
import stirling.software.SPDF.model.api.misc.ListAttachmentsRequest;
|
||||
import stirling.software.SPDF.model.api.misc.RenameAttachmentRequest;
|
||||
import stirling.software.SPDF.service.AttachmentServiceInterface;
|
||||
import stirling.software.common.annotations.AutoJobPostMapping;
|
||||
import stirling.software.common.annotations.api.MiscApi;
|
||||
@@ -36,6 +41,8 @@ public class AttachmentController {
|
||||
|
||||
private final AttachmentServiceInterface pdfAttachmentService;
|
||||
|
||||
private final ConvertPDFToPDFA convertPDFToPDFA;
|
||||
|
||||
@AutoJobPostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE, value = "/add-attachments")
|
||||
@StandardPdfResponse
|
||||
@Operation(
|
||||
@@ -43,19 +50,87 @@ public class AttachmentController {
|
||||
description =
|
||||
"This endpoint adds attachments to a PDF. Input:PDF, Output:PDF Type:MISO")
|
||||
public ResponseEntity<byte[]> addAttachments(@ModelAttribute AddAttachmentRequest request)
|
||||
throws IOException {
|
||||
throws Exception {
|
||||
MultipartFile fileInput = request.getFileInput();
|
||||
List<MultipartFile> attachments = request.getAttachments();
|
||||
boolean convertToPdfA3b = request.isConvertToPdfA3b();
|
||||
|
||||
PDDocument document =
|
||||
pdfAttachmentService.addAttachment(
|
||||
pdfDocumentFactory.load(fileInput, false), attachments);
|
||||
validateAttachmentRequest(attachments);
|
||||
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document,
|
||||
GeneralUtils.generateFilename(
|
||||
Filenames.toSimpleFileName(fileInput.getOriginalFilename()),
|
||||
"_with_attachments.pdf"));
|
||||
String originalFileName = Filenames.toSimpleFileName(fileInput.getOriginalFilename());
|
||||
if (originalFileName == null || originalFileName.isEmpty()) {
|
||||
originalFileName = "document";
|
||||
}
|
||||
String baseFileName =
|
||||
originalFileName.contains(".")
|
||||
? originalFileName.substring(0, originalFileName.lastIndexOf('.'))
|
||||
: originalFileName;
|
||||
|
||||
if (convertToPdfA3b) {
|
||||
byte[] pdfaBytes;
|
||||
try (PDDocument document = pdfDocumentFactory.load(request, false)) {
|
||||
pdfaBytes = convertPDFToPDFA.convertPDDocumentToPDFA(document, "pdfa-3b");
|
||||
}
|
||||
|
||||
try (PDDocument pdfaDocument = org.apache.pdfbox.Loader.loadPDF(pdfaBytes)) {
|
||||
pdfAttachmentService.addAttachment(pdfaDocument, attachments);
|
||||
|
||||
convertPDFToPDFA.ensureEmbeddedFileCompliance(pdfaDocument);
|
||||
|
||||
ConvertPDFToPDFA.fixType1FontCharSet(pdfaDocument);
|
||||
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
pdfaDocument.save(baos);
|
||||
byte[] resultBytes = baos.toByteArray();
|
||||
|
||||
String outputFilename = baseFileName + "_with_attachments_PDFA-3b.pdf";
|
||||
return WebResponseUtils.bytesToWebResponse(
|
||||
resultBytes, outputFilename, MediaType.APPLICATION_PDF);
|
||||
}
|
||||
} else {
|
||||
try (PDDocument document = pdfDocumentFactory.load(request, false)) {
|
||||
pdfAttachmentService.addAttachment(document, attachments);
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document,
|
||||
GeneralUtils.generateFilename(
|
||||
Filenames.toSimpleFileName(fileInput.getOriginalFilename()),
|
||||
"_with_attachments.pdf"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void validateAttachmentRequest(List<MultipartFile> attachments) {
|
||||
if (attachments == null || attachments.isEmpty()) {
|
||||
throw ExceptionUtils.createIllegalArgumentException(
|
||||
"error.attachmentsRequired", "At least one attachment is required");
|
||||
}
|
||||
|
||||
final long maxAttachmentSize = 50L * 1024 * 1024; // 50 MB per attachment
|
||||
final long maxTotalSize = 200L * 1024 * 1024; // 200 MB total
|
||||
|
||||
long totalSize = 0;
|
||||
for (MultipartFile attachment : attachments) {
|
||||
if (attachment == null || attachment.isEmpty()) {
|
||||
throw ExceptionUtils.createIllegalArgumentException(
|
||||
"error.attachmentEmpty", "Attachment files cannot be null or empty");
|
||||
}
|
||||
if (attachment.getSize() > maxAttachmentSize) {
|
||||
throw ExceptionUtils.createIllegalArgumentException(
|
||||
"error.attachmentTooLarge",
|
||||
"Attachment ''{0}'' exceeds maximum size of {1} bytes",
|
||||
attachment.getOriginalFilename(),
|
||||
maxAttachmentSize);
|
||||
}
|
||||
totalSize += attachment.getSize();
|
||||
}
|
||||
|
||||
if (totalSize > maxTotalSize) {
|
||||
throw ExceptionUtils.createIllegalArgumentException(
|
||||
"error.totalAttachmentsTooLarge",
|
||||
"Total attachment size {0} exceeds maximum of {1} bytes",
|
||||
totalSize,
|
||||
maxTotalSize);
|
||||
}
|
||||
}
|
||||
|
||||
@AutoJobPostMapping(
|
||||
@@ -88,4 +163,82 @@ public class AttachmentController {
|
||||
extracted.get(), outputName, MediaType.APPLICATION_OCTET_STREAM);
|
||||
}
|
||||
}
|
||||
|
||||
@AutoJobPostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE, value = "/list-attachments")
|
||||
@Operation(
|
||||
summary = "List attachments in PDF",
|
||||
description =
|
||||
"This endpoint lists all embedded attachments in a PDF. Input:PDF Output:JSON Type:SISO")
|
||||
public ResponseEntity<List<stirling.software.SPDF.model.api.misc.AttachmentInfo>>
|
||||
listAttachments(@ModelAttribute ListAttachmentsRequest request) throws IOException {
|
||||
try (PDDocument document = pdfDocumentFactory.load(request, true)) {
|
||||
List<stirling.software.SPDF.model.api.misc.AttachmentInfo> attachments =
|
||||
pdfAttachmentService.listAttachments(document);
|
||||
|
||||
return ResponseEntity.ok(attachments);
|
||||
}
|
||||
}
|
||||
|
||||
@AutoJobPostMapping(
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
|
||||
value = "/rename-attachment")
|
||||
@StandardPdfResponse
|
||||
@Operation(
|
||||
summary = "Rename attachment in PDF",
|
||||
description =
|
||||
"This endpoint renames an embedded attachment in a PDF. Input:PDF Output:PDF Type:MISO")
|
||||
public ResponseEntity<byte[]> renameAttachment(@ModelAttribute RenameAttachmentRequest request)
|
||||
throws Exception {
|
||||
MultipartFile fileInput = request.getFileInput();
|
||||
String attachmentName = request.getAttachmentName();
|
||||
String newName = request.getNewName();
|
||||
|
||||
if (attachmentName == null || attachmentName.isBlank()) {
|
||||
throw ExceptionUtils.createIllegalArgumentException(
|
||||
"error.attachmentNameRequired", "Attachment name cannot be null or empty");
|
||||
}
|
||||
if (newName == null || newName.isBlank()) {
|
||||
throw ExceptionUtils.createIllegalArgumentException(
|
||||
"error.newNameRequired", "New attachment name cannot be null or empty");
|
||||
}
|
||||
|
||||
try (PDDocument document = pdfDocumentFactory.load(request, false)) {
|
||||
pdfAttachmentService.renameAttachment(document, attachmentName, newName);
|
||||
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document,
|
||||
GeneralUtils.generateFilename(
|
||||
Filenames.toSimpleFileName(fileInput.getOriginalFilename()),
|
||||
"_attachment_renamed.pdf"));
|
||||
}
|
||||
}
|
||||
|
||||
@AutoJobPostMapping(
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
|
||||
value = "/delete-attachment")
|
||||
@StandardPdfResponse
|
||||
@Operation(
|
||||
summary = "Delete attachment from PDF",
|
||||
description =
|
||||
"This endpoint deletes an embedded attachment from a PDF. Input:PDF Output:PDF Type:MISO")
|
||||
public ResponseEntity<byte[]> deleteAttachment(@ModelAttribute DeleteAttachmentRequest request)
|
||||
throws Exception {
|
||||
MultipartFile fileInput = request.getFileInput();
|
||||
String attachmentName = request.getAttachmentName();
|
||||
|
||||
if (attachmentName == null || attachmentName.isBlank()) {
|
||||
throw ExceptionUtils.createIllegalArgumentException(
|
||||
"error.attachmentNameRequired", "Attachment name cannot be null or empty");
|
||||
}
|
||||
|
||||
try (PDDocument document = pdfDocumentFactory.load(request, false)) {
|
||||
pdfAttachmentService.deleteAttachment(document, attachmentName);
|
||||
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document,
|
||||
GeneralUtils.generateFilename(
|
||||
Filenames.toSimpleFileName(fileInput.getOriginalFilename()),
|
||||
"_attachment_deleted.pdf"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+3
@@ -84,6 +84,9 @@ public class ConfigController {
|
||||
boolean enableLogin =
|
||||
applicationProperties.getSecurity().isEnableLogin() && userService != null;
|
||||
configData.put("enableLogin", enableLogin);
|
||||
configData.put(
|
||||
"showSettingsWhenNoLogin",
|
||||
applicationProperties.getSystem().isShowSettingsWhenNoLogin());
|
||||
|
||||
// Mail settings - check both SMTP enabled AND invites enabled
|
||||
boolean smtpEnabled = applicationProperties.getMail().isEnabled();
|
||||
|
||||
@@ -255,6 +255,7 @@ public class OCRController {
|
||||
command.add("--force-ocr");
|
||||
}
|
||||
}
|
||||
command.add("--invalidate-digital-signatures");
|
||||
|
||||
command.addAll(
|
||||
Arrays.asList(
|
||||
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package stirling.software.SPDF.controller.api.security;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.verapdf.core.EncryptedPdfException;
|
||||
import org.verapdf.core.ModelParsingException;
|
||||
import org.verapdf.core.ValidationException;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.SPDF.model.api.security.PDFVerificationRequest;
|
||||
import stirling.software.SPDF.model.api.security.PDFVerificationResult;
|
||||
import stirling.software.SPDF.service.VeraPDFService;
|
||||
import stirling.software.common.util.ExceptionUtils;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/security")
|
||||
@Tag(name = "Security", description = "Security APIs")
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class VerifyPDFController {
|
||||
|
||||
private final VeraPDFService veraPDFService;
|
||||
|
||||
@Operation(
|
||||
summary = "Verify PDF Standards Compliance",
|
||||
description =
|
||||
"Validates PDF files against the standards declared in their metadata. "
|
||||
+ "Automatically detects PDF/A, PDF/UA-1, PDF/UA-2, and WTPDF standards "
|
||||
+ "from the document's XMP metadata and validates compliance. "
|
||||
+ "Input:PDF Output:JSON Type:SISO")
|
||||
@PostMapping(value = "/verify-pdf", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
public ResponseEntity<List<PDFVerificationResult>> verifyPDF(
|
||||
@ModelAttribute PDFVerificationRequest request) {
|
||||
|
||||
MultipartFile file = request.getFileInput();
|
||||
|
||||
if (file == null || file.isEmpty()) {
|
||||
throw ExceptionUtils.createRuntimeException(
|
||||
"error.pdfRequired", "PDF file is required", null);
|
||||
}
|
||||
|
||||
try {
|
||||
log.info("Detecting and verifying standards in PDF '{}'", file.getOriginalFilename());
|
||||
|
||||
List<PDFVerificationResult> results = veraPDFService.validatePDF(file.getInputStream());
|
||||
|
||||
log.info(
|
||||
"Verification complete for '{}': {} standard(s) checked",
|
||||
file.getOriginalFilename(),
|
||||
results.size());
|
||||
|
||||
return ResponseEntity.ok(results);
|
||||
|
||||
} catch (ValidationException e) {
|
||||
log.error("Validation exception for file: {}", file.getOriginalFilename(), e);
|
||||
throw ExceptionUtils.createRuntimeException(
|
||||
"error.validationFailed", "PDF validation failed: {0}", e, e.getMessage());
|
||||
} catch (ModelParsingException e) {
|
||||
log.error("Model parsing exception for file: {}", file.getOriginalFilename(), e);
|
||||
throw ExceptionUtils.createRuntimeException(
|
||||
"error.modelParsingFailed", "PDF model parsing failed: {0}", e, e.getMessage());
|
||||
} catch (EncryptedPdfException e) {
|
||||
log.error("Encrypted PDF exception for file: {}", file.getOriginalFilename(), e);
|
||||
throw ExceptionUtils.createRuntimeException(
|
||||
"error.encryptedPdf",
|
||||
"Cannot verify encrypted PDF. Please remove password first: {0}",
|
||||
e,
|
||||
e.getMessage());
|
||||
} catch (IOException e) {
|
||||
log.error("IO exception for file: {}", file.getOriginalFilename(), e);
|
||||
throw ExceptionUtils.createRuntimeException(
|
||||
"error.ioException",
|
||||
"IO error during PDF verification: {0}",
|
||||
e,
|
||||
e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
+57
-4
@@ -12,6 +12,7 @@ import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ProblemDetail;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.web.HttpMediaTypeNotAcceptableException;
|
||||
import org.springframework.web.HttpMediaTypeNotSupportedException;
|
||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
@@ -23,6 +24,7 @@ import org.springframework.web.multipart.support.MissingServletRequestPartExcept
|
||||
import org.springframework.web.servlet.NoHandlerFoundException;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -808,6 +810,56 @@ public class GlobalExceptionHandler {
|
||||
.body(problemDetail);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle 406 Not Acceptable errors when error responses cannot match client Accept header.
|
||||
*
|
||||
* <p>When thrown: When the client sends Accept: application/pdf but the server needs to return
|
||||
* a JSON error response (e.g., when an attachment is not found).
|
||||
*
|
||||
* <p>This handler writes directly to HttpServletResponse to bypass Spring's content negotiation
|
||||
* and ensure error responses are always delivered as JSON.
|
||||
*
|
||||
* @param ex the HttpMediaTypeNotAcceptableException
|
||||
* @param request the HTTP servlet request
|
||||
* @param response the HTTP servlet response
|
||||
*/
|
||||
@ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
|
||||
public void handleMediaTypeNotAcceptable(
|
||||
HttpMediaTypeNotAcceptableException ex,
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response)
|
||||
throws IOException {
|
||||
|
||||
log.warn(
|
||||
"Media type not acceptable at {}: client accepts {}, server supports {}",
|
||||
request.getRequestURI(),
|
||||
request.getHeader("Accept"),
|
||||
ex.getSupportedMediaTypes());
|
||||
|
||||
// Write JSON error response directly, bypassing content negotiation
|
||||
response.setStatus(HttpStatus.NOT_ACCEPTABLE.value());
|
||||
response.setContentType("application/problem+json");
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
|
||||
String errorJson =
|
||||
String.format(
|
||||
"""
|
||||
{
|
||||
"type": "about:blank",
|
||||
"title": "Not Acceptable",
|
||||
"status": 406,
|
||||
"detail": "The requested resource could not be returned in an acceptable format. Error responses are returned as JSON.",
|
||||
"instance": "%s",
|
||||
"timestamp": "%s",
|
||||
"hints": ["Error responses are always returned as application/json or application/problem+json", "Set Accept header to include application/json for proper error handling"]
|
||||
}
|
||||
""",
|
||||
request.getRequestURI(), Instant.now().toString());
|
||||
|
||||
response.getWriter().write(errorJson);
|
||||
response.getWriter().flush();
|
||||
}
|
||||
|
||||
// ===========================================================================================
|
||||
// JAVA STANDARD EXCEPTIONS
|
||||
// ===========================================================================================
|
||||
@@ -963,9 +1015,8 @@ public class GlobalExceptionHandler {
|
||||
|
||||
// Check if this RuntimeException wraps a typed exception from job execution
|
||||
Throwable cause = ex.getCause();
|
||||
if (cause instanceof BaseAppException) {
|
||||
if (cause instanceof BaseAppException appEx) {
|
||||
// Delegate to specific BaseAppException handlers
|
||||
BaseAppException appEx = (BaseAppException) cause;
|
||||
if (appEx instanceof PdfPasswordException) {
|
||||
return handlePdfPassword((PdfPasswordException) appEx, request);
|
||||
} else if (appEx instanceof PdfCorruptedException
|
||||
@@ -979,9 +1030,8 @@ public class GlobalExceptionHandler {
|
||||
} else {
|
||||
return handleBaseApp(appEx, request);
|
||||
}
|
||||
} else if (cause instanceof BaseValidationException) {
|
||||
} else if (cause instanceof BaseValidationException valEx) {
|
||||
// Delegate to validation exception handlers
|
||||
BaseValidationException valEx = (BaseValidationException) cause;
|
||||
if (valEx instanceof CbrFormatException
|
||||
|| valEx instanceof CbzFormatException
|
||||
|| valEx instanceof EmlFormatException) {
|
||||
@@ -992,6 +1042,9 @@ public class GlobalExceptionHandler {
|
||||
} else if (cause instanceof IOException) {
|
||||
// Unwrap and handle IOException (may contain PDF-specific errors)
|
||||
return handleIOException((IOException) cause, request);
|
||||
} else if (cause instanceof IllegalArgumentException) {
|
||||
// Unwrap and handle IllegalArgumentException (business logic validation errors)
|
||||
return handleIllegalArgument((IllegalArgumentException) cause, request);
|
||||
}
|
||||
|
||||
// Not a wrapped exception - treat as unexpected error
|
||||
|
||||
@@ -20,4 +20,10 @@ public class AddAttachmentRequest extends PDFFile {
|
||||
requiredMode = Schema.RequiredMode.REQUIRED,
|
||||
format = "binary")
|
||||
private List<MultipartFile> attachments;
|
||||
|
||||
@Schema(
|
||||
description = "Convert the resulting PDF to PDF/A-3b format after adding attachments",
|
||||
requiredMode = Schema.RequiredMode.NOT_REQUIRED,
|
||||
defaultValue = "false")
|
||||
private boolean convertToPdfA3b = false;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package stirling.software.SPDF.model.api.misc;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class AttachmentInfo {
|
||||
private String filename;
|
||||
private Long size;
|
||||
private String contentType;
|
||||
private String description;
|
||||
private String creationDate;
|
||||
private String modificationDate;
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package stirling.software.SPDF.model.api.misc;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import stirling.software.common.model.api.PDFFile;
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class DeleteAttachmentRequest extends PDFFile {
|
||||
|
||||
@Schema(
|
||||
description = "The name of the attachment to delete",
|
||||
requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
private String attachmentName;
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package stirling.software.SPDF.model.api.misc;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import stirling.software.common.model.api.PDFFile;
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class ListAttachmentsRequest extends PDFFile {}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package stirling.software.SPDF.model.api.misc;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import stirling.software.common.model.api.PDFFile;
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class RenameAttachmentRequest extends PDFFile {
|
||||
|
||||
@Schema(
|
||||
description = "The current name of the attachment to rename",
|
||||
requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
private String attachmentName;
|
||||
|
||||
@Schema(
|
||||
description = "The new name for the attachment",
|
||||
requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
private String newName;
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package stirling.software.SPDF.model.api.security;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import stirling.software.common.model.api.PDFFile;
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public class PDFVerificationRequest extends PDFFile {}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package stirling.software.SPDF.model.api.security;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class PDFVerificationResult {
|
||||
|
||||
private String standard;
|
||||
private String standardName;
|
||||
private String validationProfile;
|
||||
private String validationProfileName;
|
||||
private String complianceSummary;
|
||||
private boolean declaredPdfa;
|
||||
private boolean compliant;
|
||||
private int totalFailures;
|
||||
private int totalWarnings;
|
||||
private List<ValidationIssue> failures = new ArrayList<>();
|
||||
private List<ValidationIssue> warnings = new ArrayList<>();
|
||||
|
||||
public void addFailure(ValidationIssue failure) {
|
||||
this.failures.add(failure);
|
||||
this.totalFailures = this.failures.size();
|
||||
}
|
||||
|
||||
public void addWarning(ValidationIssue warning) {
|
||||
this.warnings.add(warning);
|
||||
this.totalWarnings = this.warnings.size();
|
||||
}
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class ValidationIssue {
|
||||
private String ruleId;
|
||||
private String message;
|
||||
private String location;
|
||||
private String specification;
|
||||
private String clause;
|
||||
private String testNumber;
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import java.nio.file.attribute.FileTime;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
@@ -36,6 +37,9 @@ import io.github.pixee.security.Filenames;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.SPDF.model.api.misc.AttachmentInfo;
|
||||
import stirling.software.common.util.ExceptionUtils;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class AttachmentService implements AttachmentServiceInterface {
|
||||
@@ -216,6 +220,142 @@ public class AttachmentService implements AttachmentServiceInterface {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<AttachmentInfo> listAttachments(PDDocument document) throws IOException {
|
||||
List<AttachmentInfo> attachments = new ArrayList<>();
|
||||
|
||||
PDDocumentCatalog catalog = document.getDocumentCatalog();
|
||||
if (catalog == null) {
|
||||
return attachments;
|
||||
}
|
||||
|
||||
PDDocumentNameDictionary documentNames = catalog.getNames();
|
||||
if (documentNames == null) {
|
||||
return attachments;
|
||||
}
|
||||
|
||||
PDEmbeddedFilesNameTreeNode embeddedFilesTree = documentNames.getEmbeddedFiles();
|
||||
if (embeddedFilesTree == null) {
|
||||
return attachments;
|
||||
}
|
||||
|
||||
Map<String, PDComplexFileSpecification> embeddedFiles = new LinkedHashMap<>();
|
||||
collectEmbeddedFiles(embeddedFilesTree, embeddedFiles);
|
||||
|
||||
for (Map.Entry<String, PDComplexFileSpecification> entry : embeddedFiles.entrySet()) {
|
||||
PDComplexFileSpecification fileSpecification = entry.getValue();
|
||||
PDEmbeddedFile embeddedFile = getEmbeddedFile(fileSpecification);
|
||||
|
||||
if (embeddedFile != null) {
|
||||
String filename = determineFilename(entry.getKey(), fileSpecification);
|
||||
String description = fileSpecification.getFileDescription();
|
||||
String contentType = embeddedFile.getSubtype();
|
||||
Long size = (long) embeddedFile.getSize();
|
||||
|
||||
String creationDate = null;
|
||||
if (embeddedFile.getCreationDate() != null) {
|
||||
creationDate = embeddedFile.getCreationDate().getTime().toString();
|
||||
}
|
||||
|
||||
String modificationDate = null;
|
||||
if (embeddedFile.getModDate() != null) {
|
||||
modificationDate = embeddedFile.getModDate().getTime().toString();
|
||||
}
|
||||
|
||||
AttachmentInfo attachmentInfo =
|
||||
new AttachmentInfo(
|
||||
filename,
|
||||
size,
|
||||
contentType,
|
||||
description,
|
||||
creationDate,
|
||||
modificationDate);
|
||||
|
||||
attachments.add(attachmentInfo);
|
||||
}
|
||||
}
|
||||
|
||||
return attachments;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PDDocument renameAttachment(PDDocument document, String attachmentName, String newName)
|
||||
throws IOException {
|
||||
PDEmbeddedFilesNameTreeNode embeddedFilesTree = getEmbeddedFilesTree(document);
|
||||
|
||||
Map<String, PDComplexFileSpecification> allEmbeddedFiles = new LinkedHashMap<>();
|
||||
collectEmbeddedFiles(embeddedFilesTree, allEmbeddedFiles);
|
||||
|
||||
PDComplexFileSpecification fileToRename = null;
|
||||
String keyToRename = null;
|
||||
|
||||
for (Map.Entry<String, PDComplexFileSpecification> entry : allEmbeddedFiles.entrySet()) {
|
||||
String currentName = determineFilename(entry.getKey(), entry.getValue());
|
||||
if (currentName.equals(attachmentName)) {
|
||||
fileToRename = entry.getValue();
|
||||
keyToRename = entry.getKey();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (fileToRename == null || keyToRename == null) {
|
||||
log.warn("Attachment '{}' not found for renaming", attachmentName);
|
||||
throw ExceptionUtils.createIllegalArgumentException(
|
||||
"error.attachmentNotFound",
|
||||
"Attachment ''{0}'' not found for renaming",
|
||||
attachmentName);
|
||||
}
|
||||
|
||||
fileToRename.setFile(newName);
|
||||
fileToRename.setFileUnicode(newName);
|
||||
|
||||
allEmbeddedFiles.remove(keyToRename);
|
||||
allEmbeddedFiles.put(newName, fileToRename);
|
||||
|
||||
embeddedFilesTree.setKids(null);
|
||||
|
||||
embeddedFilesTree.setNames(allEmbeddedFiles);
|
||||
log.info("Renamed attachment from '{}' to '{}'", attachmentName, newName);
|
||||
|
||||
return document;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PDDocument deleteAttachment(PDDocument document, String attachmentName)
|
||||
throws IOException {
|
||||
PDEmbeddedFilesNameTreeNode embeddedFilesTree = getEmbeddedFilesTree(document);
|
||||
|
||||
Map<String, PDComplexFileSpecification> allEmbeddedFiles = new LinkedHashMap<>();
|
||||
collectEmbeddedFiles(embeddedFilesTree, allEmbeddedFiles);
|
||||
|
||||
String keyToRemove = null;
|
||||
|
||||
for (Map.Entry<String, PDComplexFileSpecification> entry : allEmbeddedFiles.entrySet()) {
|
||||
String currentName = determineFilename(entry.getKey(), entry.getValue());
|
||||
if (currentName.equals(attachmentName)) {
|
||||
keyToRemove = entry.getKey();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (keyToRemove == null) {
|
||||
log.warn("Attachment '{}' not found for deletion", attachmentName);
|
||||
throw ExceptionUtils.createIllegalArgumentException(
|
||||
"error.attachmentNotFound",
|
||||
"Attachment ''{0}'' not found for deletion",
|
||||
attachmentName);
|
||||
}
|
||||
|
||||
allEmbeddedFiles.remove(keyToRemove);
|
||||
|
||||
embeddedFilesTree.setKids(null);
|
||||
|
||||
embeddedFilesTree.setNames(allEmbeddedFiles);
|
||||
log.info("Deleted attachment: '{}'", attachmentName);
|
||||
|
||||
return document;
|
||||
}
|
||||
|
||||
private String sanitizeFilename(String candidate) {
|
||||
String sanitized = Filenames.toSimpleFileName(candidate);
|
||||
if (StringUtils.isBlank(sanitized)) {
|
||||
|
||||
@@ -7,10 +7,19 @@ import java.util.Optional;
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import stirling.software.SPDF.model.api.misc.AttachmentInfo;
|
||||
|
||||
public interface AttachmentServiceInterface {
|
||||
|
||||
PDDocument addAttachment(PDDocument document, List<MultipartFile> attachments)
|
||||
throws IOException;
|
||||
|
||||
Optional<byte[]> extractAttachments(PDDocument document) throws IOException;
|
||||
|
||||
List<AttachmentInfo> listAttachments(PDDocument document) throws IOException;
|
||||
|
||||
PDDocument renameAttachment(PDDocument document, String attachmentName, String newName)
|
||||
throws IOException;
|
||||
|
||||
PDDocument deleteAttachment(PDDocument document, String attachmentName) throws IOException;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
package stirling.software.SPDF.service;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.verapdf.core.EncryptedPdfException;
|
||||
import org.verapdf.core.ModelParsingException;
|
||||
import org.verapdf.core.ValidationException;
|
||||
import org.verapdf.gf.foundry.VeraGreenfieldFoundryProvider;
|
||||
import org.verapdf.pdfa.Foundries;
|
||||
import org.verapdf.pdfa.PDFAParser;
|
||||
import org.verapdf.pdfa.PDFAValidator;
|
||||
import org.verapdf.pdfa.flavours.PDFAFlavour;
|
||||
import org.verapdf.pdfa.flavours.PDFFlavours;
|
||||
import org.verapdf.pdfa.results.TestAssertion;
|
||||
import org.verapdf.pdfa.results.ValidationResult;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.SPDF.model.api.security.PDFVerificationResult;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class VeraPDFService {
|
||||
|
||||
private static final String NOT_PDFA_STANDARD_ID = "not-pdfa";
|
||||
private static final String NOT_PDFA_STANDARD_NAME =
|
||||
"Not PDF/A (no PDF/A identification metadata)";
|
||||
|
||||
private static PDFVerificationResult convertToVerificationResult(
|
||||
ValidationResult result, PDFAFlavour declaredFlavour, PDFAFlavour validationFlavour) {
|
||||
PDFVerificationResult verificationResult = new PDFVerificationResult();
|
||||
|
||||
PDFAFlavour validationProfile =
|
||||
validationFlavour != null ? validationFlavour : result.getPDFAFlavour();
|
||||
boolean validationIsPdfa = isPdfaFlavour(validationProfile);
|
||||
|
||||
if (validationProfile != null) {
|
||||
verificationResult.setValidationProfile(validationProfile.getId());
|
||||
verificationResult.setValidationProfileName(getStandardName(validationProfile));
|
||||
}
|
||||
|
||||
if (declaredFlavour != null) {
|
||||
verificationResult.setStandard(declaredFlavour.getId());
|
||||
verificationResult.setDeclaredPdfa(isPdfaFlavour(declaredFlavour));
|
||||
} else if (validationProfile != null && !validationIsPdfa) {
|
||||
verificationResult.setStandard(validationProfile.getId());
|
||||
verificationResult.setDeclaredPdfa(false);
|
||||
} else {
|
||||
verificationResult.setStandard(NOT_PDFA_STANDARD_ID);
|
||||
verificationResult.setDeclaredPdfa(false);
|
||||
}
|
||||
|
||||
for (TestAssertion assertion : result.getTestAssertions()) {
|
||||
if (assertion.getStatus() == TestAssertion.Status.FAILED) {
|
||||
PDFVerificationResult.ValidationIssue issue = createValidationIssue(assertion);
|
||||
verificationResult.addFailure(issue);
|
||||
}
|
||||
}
|
||||
|
||||
verificationResult.setCompliant(result.isCompliant());
|
||||
|
||||
String baseName;
|
||||
if (declaredFlavour != null) {
|
||||
baseName = getStandardName(declaredFlavour);
|
||||
} else if (validationIsPdfa) {
|
||||
baseName = NOT_PDFA_STANDARD_NAME;
|
||||
} else if (validationProfile != null) {
|
||||
baseName = getStandardName(validationProfile);
|
||||
} else {
|
||||
baseName = "Unknown standard";
|
||||
}
|
||||
|
||||
String standardDisplay =
|
||||
formatStandardDisplay(
|
||||
baseName,
|
||||
verificationResult.getTotalFailures(),
|
||||
isPdfaFlavour(declaredFlavour),
|
||||
validationIsPdfa && declaredFlavour == null);
|
||||
verificationResult.setStandardName(standardDisplay);
|
||||
verificationResult.setComplianceSummary(standardDisplay);
|
||||
|
||||
log.debug(
|
||||
"Validation complete for profile {} (declared: {}): {} failures",
|
||||
validationProfile != null ? validationProfile.getId() : "unknown",
|
||||
declaredFlavour != null ? declaredFlavour.getId() : NOT_PDFA_STANDARD_ID,
|
||||
verificationResult.getTotalFailures());
|
||||
|
||||
return verificationResult;
|
||||
}
|
||||
|
||||
private static PDFVerificationResult.ValidationIssue createValidationIssue(
|
||||
TestAssertion assertion) {
|
||||
PDFVerificationResult.ValidationIssue issue = new PDFVerificationResult.ValidationIssue();
|
||||
|
||||
if (assertion.getRuleId() != null) {
|
||||
issue.setRuleId(assertion.getRuleId().toString());
|
||||
issue.setClause(assertion.getRuleId().getClause());
|
||||
|
||||
if (assertion.getRuleId().getSpecification() != null) {
|
||||
issue.setSpecification(assertion.getRuleId().getSpecification().toString());
|
||||
}
|
||||
|
||||
int testNumber = assertion.getRuleId().getTestNumber();
|
||||
if (testNumber > 0) {
|
||||
issue.setTestNumber(String.valueOf(testNumber));
|
||||
}
|
||||
}
|
||||
|
||||
issue.setMessage(assertion.getMessage());
|
||||
issue.setLocation(
|
||||
assertion.getLocation() != null ? assertion.getLocation().toString() : "Unknown");
|
||||
|
||||
return issue;
|
||||
}
|
||||
|
||||
private static PDFVerificationResult createNoPdfaDeclarationResult() {
|
||||
PDFVerificationResult result = new PDFVerificationResult();
|
||||
result.setStandard(NOT_PDFA_STANDARD_ID);
|
||||
result.setStandardName(NOT_PDFA_STANDARD_NAME);
|
||||
result.setComplianceSummary(NOT_PDFA_STANDARD_NAME);
|
||||
result.setCompliant(false);
|
||||
result.setDeclaredPdfa(false);
|
||||
|
||||
PDFVerificationResult.ValidationIssue issue = new PDFVerificationResult.ValidationIssue();
|
||||
issue.setMessage("Document does not declare PDF/A compliance in its XMP metadata.");
|
||||
issue.setSpecification("XMP pdfaid");
|
||||
result.addFailure(issue);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static PDFVerificationResult buildErrorResult(
|
||||
PDFAFlavour declaredFlavour, PDFAFlavour validationFlavour, String errorMessage) {
|
||||
|
||||
PDFVerificationResult errorResult = new PDFVerificationResult();
|
||||
|
||||
PDFAFlavour declaredForResult =
|
||||
isPdfaFlavour(validationFlavour) ? declaredFlavour : validationFlavour;
|
||||
|
||||
if (declaredForResult != null) {
|
||||
errorResult.setStandard(declaredForResult.getId());
|
||||
errorResult.setStandardName(getStandardName(declaredForResult) + " with errors");
|
||||
errorResult.setDeclaredPdfa(isPdfaFlavour(declaredForResult));
|
||||
} else if (isPdfaFlavour(validationFlavour)) {
|
||||
errorResult.setStandard(NOT_PDFA_STANDARD_ID);
|
||||
errorResult.setStandardName(NOT_PDFA_STANDARD_NAME);
|
||||
errorResult.setDeclaredPdfa(false);
|
||||
} else {
|
||||
errorResult.setStandard(
|
||||
validationFlavour != null ? validationFlavour.getId() : NOT_PDFA_STANDARD_ID);
|
||||
errorResult.setStandardName(
|
||||
(validationFlavour != null
|
||||
? getStandardName(validationFlavour)
|
||||
: "Unknown standard")
|
||||
+ " with errors");
|
||||
errorResult.setDeclaredPdfa(false);
|
||||
}
|
||||
|
||||
errorResult.setValidationProfile(
|
||||
validationFlavour != null ? validationFlavour.getId() : NOT_PDFA_STANDARD_ID);
|
||||
errorResult.setValidationProfileName(
|
||||
validationFlavour != null
|
||||
? getStandardName(validationFlavour)
|
||||
: "Unknown standard");
|
||||
errorResult.setComplianceSummary(errorResult.getStandardName());
|
||||
errorResult.setCompliant(false);
|
||||
|
||||
PDFVerificationResult.ValidationIssue failure = new PDFVerificationResult.ValidationIssue();
|
||||
failure.setMessage(errorMessage);
|
||||
errorResult.addFailure(failure);
|
||||
|
||||
return errorResult;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void initialize() {
|
||||
try {
|
||||
VeraGreenfieldFoundryProvider.initialise();
|
||||
log.info("VeraPDF Greenfield initialized successfully");
|
||||
} catch (Exception e) {
|
||||
log.error("Failed to initialize VeraPDF", e);
|
||||
}
|
||||
}
|
||||
|
||||
public List<PDFVerificationResult> validatePDF(InputStream pdfStream)
|
||||
throws IOException, ValidationException, ModelParsingException, EncryptedPdfException {
|
||||
|
||||
byte[] pdfBytes = pdfStream.readAllBytes();
|
||||
List<PDFVerificationResult> results = new ArrayList<>();
|
||||
|
||||
PDFAFlavour declaredFlavour;
|
||||
List<PDFAFlavour> detectedFlavours;
|
||||
|
||||
try (PDFAParser detectionParser =
|
||||
Foundries.defaultInstance().createParser(new ByteArrayInputStream(pdfBytes))) {
|
||||
declaredFlavour = detectionParser.getFlavour();
|
||||
detectedFlavours = detectionParser.getFlavours();
|
||||
}
|
||||
|
||||
List<PDFAFlavour> flavoursToValidate = new ArrayList<>();
|
||||
boolean hasPdfaDeclaration = isPdfaFlavour(declaredFlavour);
|
||||
|
||||
if (declaredFlavour != null) {
|
||||
flavoursToValidate.add(declaredFlavour);
|
||||
}
|
||||
|
||||
for (PDFAFlavour flavour : detectedFlavours) {
|
||||
if (flavour.equals(declaredFlavour)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (PDFFlavours.isFlavourFamily(flavour, PDFAFlavour.SpecificationFamily.PDF_A)) {
|
||||
if (hasPdfaDeclaration) {
|
||||
flavoursToValidate.add(flavour);
|
||||
} else {
|
||||
log.debug(
|
||||
"Ignoring detected PDF/A flavour {} because no PDF/A declaration exists in XMP",
|
||||
flavour.getId());
|
||||
}
|
||||
} else if (PDFFlavours.isFlavourFamily(flavour, PDFAFlavour.SpecificationFamily.PDF_UA)
|
||||
|| PDFFlavours.isFlavourFamily(
|
||||
flavour, PDFAFlavour.SpecificationFamily.WTPDF)) {
|
||||
flavoursToValidate.add(flavour);
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasPdfaDeclaration) {
|
||||
results.add(createNoPdfaDeclarationResult());
|
||||
}
|
||||
|
||||
if (flavoursToValidate.isEmpty()) {
|
||||
log.info("No verifiable PDF/A, PDF/UA, or WTPDF standards declared via XMP metadata");
|
||||
return results;
|
||||
}
|
||||
|
||||
for (PDFAFlavour flavour : flavoursToValidate) {
|
||||
try (PDFAParser parser =
|
||||
Foundries.defaultInstance()
|
||||
.createParser(new ByteArrayInputStream(pdfBytes), flavour)) {
|
||||
|
||||
PDFAFlavour parserDeclared = parser.getFlavour();
|
||||
PDFAValidator validator =
|
||||
Foundries.defaultInstance().createValidator(flavour, false);
|
||||
ValidationResult result = validator.validate(parser);
|
||||
|
||||
PDFAFlavour declaredForResult =
|
||||
PDFFlavours.isFlavourFamily(flavour, PDFAFlavour.SpecificationFamily.PDF_A)
|
||||
? parserDeclared
|
||||
: flavour;
|
||||
|
||||
results.add(convertToVerificationResult(result, declaredForResult, flavour));
|
||||
} catch (Exception e) {
|
||||
log.error("Error validating standard {}: {}", flavour.getId(), e.getMessage());
|
||||
results.add(
|
||||
buildErrorResult(
|
||||
declaredFlavour, flavour, "Validation error: " + e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
private static boolean isPdfaFlavour(PDFAFlavour flavour) {
|
||||
return PDFFlavours.isFlavourFamily(flavour, PDFAFlavour.SpecificationFamily.PDF_A);
|
||||
}
|
||||
|
||||
private static String formatStandardDisplay(
|
||||
String baseName,
|
||||
int errorCount,
|
||||
boolean declaredPdfa,
|
||||
boolean inferredPdfaWithoutDeclaration) {
|
||||
|
||||
if (inferredPdfaWithoutDeclaration) {
|
||||
return NOT_PDFA_STANDARD_NAME;
|
||||
}
|
||||
|
||||
if (!declaredPdfa && NOT_PDFA_STANDARD_NAME.equals(baseName)) {
|
||||
return NOT_PDFA_STANDARD_NAME;
|
||||
}
|
||||
|
||||
if (errorCount > 0) {
|
||||
return baseName + " with errors";
|
||||
}
|
||||
|
||||
return baseName + " compliant";
|
||||
}
|
||||
|
||||
private static String getStandardName(PDFAFlavour flavour) {
|
||||
String id = flavour.getId();
|
||||
String part = flavour.getPart().toString();
|
||||
String level = flavour.getLevel().toString();
|
||||
|
||||
// PDF/A standards - Fixed: proper length check and parentheses
|
||||
if (!id.isEmpty()
|
||||
&& (id.charAt(0) == '1'
|
||||
|| id.charAt(0) == '2'
|
||||
|| id.charAt(0) == '3'
|
||||
|| id.charAt(0) == '4')) {
|
||||
return "PDF/A-" + part + (level.isEmpty() ? "" : level);
|
||||
}
|
||||
// PDF/UA standards
|
||||
else if (id.contains("ua")) {
|
||||
return "PDF/UA-" + part;
|
||||
}
|
||||
// WTPDF standards
|
||||
else if (id.contains("wtpdf")) {
|
||||
return "WTPDF " + part;
|
||||
}
|
||||
|
||||
return flavour.toString();
|
||||
}
|
||||
}
|
||||
@@ -132,6 +132,7 @@ system:
|
||||
enableAlphaFunctionality: false # set to enable functionality which might need more testing before it fully goes live (this feature might make no changes)
|
||||
showUpdate: false # see when a new update is available
|
||||
showUpdateOnlyAdmin: false # only admins can see when a new update is available, depending on showUpdate it must be set to 'true'
|
||||
showSettingsWhenNoLogin: true # set to 'false' to hide settings button when login is disabled (enableLogin: false). Only applies when login is disabled.
|
||||
customHTMLFiles: false # enable to have files placed in /customFiles/templates override the existing template HTML files
|
||||
tessdataDir: "" # path to the directory containing the Tessdata files. This setting is relevant for Windows systems. For Windows users, this path should be adjusted to point to the appropriate directory where the Tessdata files are stored.
|
||||
enableAnalytics: null # Master toggle for analytics: set to 'true' to enable all analytics, 'false' to disable all analytics, or leave as 'null' to prompt admin on first launch
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="description" content="Stirling-PDF API Server">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Stirling-PDF - API Server</title>
|
||||
|
||||
<!-- Icons -->
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png">
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="favicon-32x32.png">
|
||||
<link rel="icon" type="image/png" sizes="16x16" href="favicon-16x16.png">
|
||||
<link rel="shortcut icon" href="favicon.ico">
|
||||
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
background-color: #f3f4f6;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 1.5rem 1.5rem 0;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.auth-card {
|
||||
width: min(45rem, 96vw);
|
||||
background-color: #ffffff;
|
||||
border-radius: 1.25rem;
|
||||
box-shadow: 0 1.25rem 3.75rem rgba(0, 0, 0, 0.12);
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 2rem;
|
||||
}
|
||||
|
||||
.auth-content {
|
||||
max-width: 26.25rem;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.login-header {
|
||||
margin-bottom: 1.5rem;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
.login-header-logos {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
|
||||
.login-logo-icon {
|
||||
width: 2.5rem;
|
||||
height: 2.5rem;
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
|
||||
.login-logo-text {
|
||||
height: 2rem;
|
||||
}
|
||||
|
||||
.login-title {
|
||||
font-size: 2rem;
|
||||
font-weight: 800;
|
||||
color: #111827;
|
||||
margin: 0 0 0.375rem;
|
||||
}
|
||||
|
||||
.login-subtitle {
|
||||
color: #6b7280;
|
||||
font-size: 0.875rem;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.section {
|
||||
margin: 1.5rem 0 0.75rem;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
color: #374151;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.section-text {
|
||||
font-size: 0.875rem;
|
||||
color: #6b7280;
|
||||
line-height: 1.5;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.section-list {
|
||||
font-size: 0.875rem;
|
||||
color: #6b7280;
|
||||
line-height: 1.6;
|
||||
margin-left: 1.25rem;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.section-list li {
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.section-list a,
|
||||
.section-text a {
|
||||
color: #AF3434;
|
||||
text-decoration: none;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.section-list a:hover,
|
||||
.section-text a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.code-inline {
|
||||
background-color: #f3f4f6;
|
||||
padding: 0.2rem 0.4rem;
|
||||
border-radius: 0.25rem;
|
||||
font-family: 'Courier New', monospace;
|
||||
font-size: 0.8125rem;
|
||||
color: #374151;
|
||||
}
|
||||
|
||||
.cta-button {
|
||||
width: 100%;
|
||||
padding: 0.75rem 1rem;
|
||||
background-color: #AF3434;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 0.625rem;
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
text-decoration: none;
|
||||
display: inline-block;
|
||||
text-align: center;
|
||||
transition: background-color 0.2s;
|
||||
margin: 0.75rem 0;
|
||||
}
|
||||
|
||||
.cta-button:hover {
|
||||
background-color: #9a2e2e;
|
||||
}
|
||||
|
||||
.divider {
|
||||
margin: 1.5rem 0;
|
||||
border: 0;
|
||||
border-top: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
.footer-link {
|
||||
font-size: 0.875rem;
|
||||
color: #6b7280;
|
||||
text-align: center;
|
||||
display: block;
|
||||
margin-top: 1rem;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.footer-link:hover {
|
||||
color: #374151;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.footer {
|
||||
position: fixed;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
width: 100%;
|
||||
text-align: center;
|
||||
padding: 1rem;
|
||||
font-size: 0.875rem;
|
||||
color: #6b7280;
|
||||
background-color: transparent;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.footer a {
|
||||
color: #AF3434;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.footer a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="auth-card">
|
||||
<div class="auth-content">
|
||||
<div class="login-header">
|
||||
<div class="login-header-logos">
|
||||
<img src="favicon.svg" alt="Stirling PDF" class="login-logo-icon">
|
||||
<img src="api-wordmark.svg" alt="Stirling PDF" class="login-logo-text">
|
||||
</div>
|
||||
<h1 class="login-title">API Server</h1>
|
||||
<p class="login-subtitle">Backend-only mode without web UI</p>
|
||||
</div>
|
||||
|
||||
<div class="section">
|
||||
<p class="section-text">
|
||||
This Stirling-PDF instance is running in <strong>API-only mode</strong>. The web interface has not been included in this build.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<a href="swagger-ui/index.html" class="cta-button">Open API Documentation</a>
|
||||
|
||||
<hr class="divider">
|
||||
|
||||
<div class="section">
|
||||
<h2 class="section-title">Looking for the Web UI?</h2>
|
||||
|
||||
<p class="section-text"><strong>If you're using Docker:</strong></p>
|
||||
<ul class="section-list">
|
||||
<li>You may have pulled an <strong>API-only image</strong> or there was a build configuration issue</li>
|
||||
<li>Use the standard Docker image: <code class="code-inline">stirlingtools/stirling-pdf:latest</code></li>
|
||||
</ul>
|
||||
|
||||
<p class="section-text"><strong>If you're using a JAR file:</strong></p>
|
||||
<ul class="section-list">
|
||||
<li>You downloaded <code class="code-inline">Stirling-PDF-server.jar</code> which is the <strong>API-only version without UI</strong></li>
|
||||
<li>Download the full version from <a href="https://github.com/Stirling-Tools/Stirling-PDF/releases" target="_blank">GitHub Releases</a>:</li>
|
||||
<li style="margin-left: 1.5rem;"><code class="code-inline">Stirling-PDF.jar</code> - Standard version with UI</li>
|
||||
<li style="margin-left: 1.5rem;"><code class="code-inline">Stirling-PDF-with-login.jar</code> - Version with authentication features</li>
|
||||
</ul>
|
||||
|
||||
<p class="section-text"><strong>If you built from source:</strong></p>
|
||||
<ul class="section-list">
|
||||
<li>Rebuild with: <code class="code-inline">./gradlew build -PbuildWithFrontend=true</code></li>
|
||||
<li>Or deploy the frontend separately from the <code class="code-inline">/frontend</code> directory</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<hr class="divider">
|
||||
|
||||
<div class="section">
|
||||
<h2 class="section-title">Need Help?</h2>
|
||||
<p class="section-text">Join our community for support:</p>
|
||||
<ul class="section-list">
|
||||
<li><a href="https://discord.gg/Cn8pWhQRxZ" target="_blank">Discord Community</a> - Get help from the community</li>
|
||||
<li><a href="https://github.com/Stirling-Tools/Stirling-PDF/issues" target="_blank">GitHub Issues</a> - Report bugs or request features</li>
|
||||
<li><a href="https://github.com/Stirling-Tools/Stirling-PDF" target="_blank">GitHub Repository</a> - View documentation and source code</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="footer">
|
||||
<span>Powered by </span>
|
||||
<a href="https://stirlingpdf.com">Stirling PDF</a>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 6.4 KiB |
+15
-17
@@ -67,16 +67,16 @@ class AttachmentControllerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void addAttachments_Success() throws IOException {
|
||||
void addAttachments_Success() throws Exception {
|
||||
List<MultipartFile> attachments = List.of(attachment1, attachment2);
|
||||
request.setAttachments(attachments);
|
||||
request.setFileInput(pdfFile);
|
||||
ResponseEntity<byte[]> expectedResponse =
|
||||
ResponseEntity.ok("modified PDF content".getBytes());
|
||||
|
||||
when(pdfDocumentFactory.load(pdfFile, false)).thenReturn(mockDocument);
|
||||
when(pdfDocumentFactory.load(request, false)).thenReturn(mockDocument);
|
||||
when(pdfAttachmentService.addAttachment(mockDocument, attachments))
|
||||
.thenReturn(modifiedMockDocument);
|
||||
.thenReturn(mockDocument);
|
||||
|
||||
try (MockedStatic<WebResponseUtils> mockedWebResponseUtils =
|
||||
mockStatic(WebResponseUtils.class)) {
|
||||
@@ -84,8 +84,7 @@ class AttachmentControllerTest {
|
||||
.when(
|
||||
() ->
|
||||
WebResponseUtils.pdfDocToWebResponse(
|
||||
eq(modifiedMockDocument),
|
||||
eq("test_with_attachments.pdf")))
|
||||
eq(mockDocument), eq("test_with_attachments.pdf")))
|
||||
.thenReturn(expectedResponse);
|
||||
|
||||
ResponseEntity<byte[]> response = attachmentController.addAttachments(request);
|
||||
@@ -93,22 +92,22 @@ class AttachmentControllerTest {
|
||||
assertNotNull(response);
|
||||
assertEquals(HttpStatus.OK, response.getStatusCode());
|
||||
assertNotNull(response.getBody());
|
||||
verify(pdfDocumentFactory).load(pdfFile, false);
|
||||
verify(pdfDocumentFactory).load(request, false);
|
||||
verify(pdfAttachmentService).addAttachment(mockDocument, attachments);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void addAttachments_SingleAttachment() throws IOException {
|
||||
void addAttachments_SingleAttachment() throws Exception {
|
||||
List<MultipartFile> attachments = List.of(attachment1);
|
||||
request.setAttachments(attachments);
|
||||
request.setFileInput(pdfFile);
|
||||
ResponseEntity<byte[]> expectedResponse =
|
||||
ResponseEntity.ok("modified PDF content".getBytes());
|
||||
|
||||
when(pdfDocumentFactory.load(pdfFile, false)).thenReturn(mockDocument);
|
||||
when(pdfDocumentFactory.load(request, false)).thenReturn(mockDocument);
|
||||
when(pdfAttachmentService.addAttachment(mockDocument, attachments))
|
||||
.thenReturn(modifiedMockDocument);
|
||||
.thenReturn(mockDocument);
|
||||
|
||||
try (MockedStatic<WebResponseUtils> mockedWebResponseUtils =
|
||||
mockStatic(WebResponseUtils.class)) {
|
||||
@@ -116,8 +115,7 @@ class AttachmentControllerTest {
|
||||
.when(
|
||||
() ->
|
||||
WebResponseUtils.pdfDocToWebResponse(
|
||||
eq(modifiedMockDocument),
|
||||
eq("test_with_attachments.pdf")))
|
||||
eq(mockDocument), eq("test_with_attachments.pdf")))
|
||||
.thenReturn(expectedResponse);
|
||||
|
||||
ResponseEntity<byte[]> response = attachmentController.addAttachments(request);
|
||||
@@ -125,33 +123,33 @@ class AttachmentControllerTest {
|
||||
assertNotNull(response);
|
||||
assertEquals(HttpStatus.OK, response.getStatusCode());
|
||||
assertNotNull(response.getBody());
|
||||
verify(pdfDocumentFactory).load(pdfFile, false);
|
||||
verify(pdfDocumentFactory).load(request, false);
|
||||
verify(pdfAttachmentService).addAttachment(mockDocument, attachments);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void addAttachments_IOExceptionFromPDFLoad() throws IOException {
|
||||
void addAttachments_IOExceptionFromPDFLoad() throws Exception {
|
||||
List<MultipartFile> attachments = List.of(attachment1);
|
||||
request.setAttachments(attachments);
|
||||
request.setFileInput(pdfFile);
|
||||
IOException ioException = new IOException("Failed to load PDF");
|
||||
|
||||
when(pdfDocumentFactory.load(pdfFile, false)).thenThrow(ioException);
|
||||
when(pdfDocumentFactory.load(request, false)).thenThrow(ioException);
|
||||
|
||||
assertThrows(IOException.class, () -> attachmentController.addAttachments(request));
|
||||
verify(pdfDocumentFactory).load(pdfFile, false);
|
||||
verify(pdfDocumentFactory).load(request, false);
|
||||
verifyNoInteractions(pdfAttachmentService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void addAttachments_IOExceptionFromAttachmentService() throws IOException {
|
||||
void addAttachments_IOExceptionFromAttachmentService() throws Exception {
|
||||
List<MultipartFile> attachments = List.of(attachment1);
|
||||
request.setAttachments(attachments);
|
||||
request.setFileInput(pdfFile);
|
||||
IOException ioException = new IOException("Failed to add attachment");
|
||||
|
||||
when(pdfDocumentFactory.load(pdfFile, false)).thenReturn(mockDocument);
|
||||
when(pdfDocumentFactory.load(request, false)).thenReturn(mockDocument);
|
||||
when(pdfAttachmentService.addAttachment(mockDocument, attachments)).thenThrow(ioException);
|
||||
|
||||
assertThrows(IOException.class, () -> attachmentController.addAttachments(request));
|
||||
|
||||
@@ -53,7 +53,7 @@ dependencies {
|
||||
implementation 'com.bucket4j:bucket4j_jdk17-core:8.15.0'
|
||||
|
||||
// https://mvnrepository.com/artifact/com.bucket4j/bucket4j_jdk17
|
||||
implementation 'org.bouncycastle:bcprov-jdk18on:1.82'
|
||||
implementation 'org.bouncycastle:bcprov-jdk18on:1.83'
|
||||
|
||||
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5:3.1.3.RELEASE'
|
||||
api 'io.micrometer:micrometer-registry-prometheus'
|
||||
|
||||
+6
-6
@@ -18,14 +18,14 @@ import groovy.json.JsonSlurper
|
||||
ext {
|
||||
springBootVersion = "3.5.7"
|
||||
pdfboxVersion = "3.0.6"
|
||||
imageioVersion = "3.12.0"
|
||||
imageioVersion = "3.13.0"
|
||||
lombokVersion = "1.18.42"
|
||||
bouncycastleVersion = "1.82"
|
||||
bouncycastleVersion = "1.83"
|
||||
springSecuritySamlVersion = "6.5.6"
|
||||
openSamlVersion = "4.3.2"
|
||||
commonmarkVersion = "0.27.0"
|
||||
googleJavaFormatVersion = "1.28.0"
|
||||
logback = "1.5.21"
|
||||
logback = "1.5.23"
|
||||
junitPlatformVersion = "1.12.2"
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ repositories {
|
||||
|
||||
allprojects {
|
||||
group = 'stirling.software'
|
||||
version = '2.1.5'
|
||||
version = '2.2.0'
|
||||
|
||||
configurations.configureEach {
|
||||
exclude group: 'commons-logging', module: 'commons-logging'
|
||||
@@ -172,7 +172,7 @@ subprojects {
|
||||
testRuntimeOnly 'org.mockito:mockito-inline:5.2.0'
|
||||
testRuntimeOnly "org.junit.platform:junit-platform-launcher"
|
||||
|
||||
testImplementation platform("com.squareup.okhttp3:okhttp-bom:5.3.1")
|
||||
testImplementation platform("com.squareup.okhttp3:okhttp-bom:5.3.2")
|
||||
testImplementation "com.squareup.okhttp3:mockwebserver"
|
||||
}
|
||||
|
||||
@@ -334,7 +334,7 @@ dependencies {
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
testRuntimeOnly "org.junit.platform:junit-platform-launcher:$junitPlatformVersion"
|
||||
|
||||
testImplementation platform("com.squareup.okhttp3:okhttp-bom:5.1.0")
|
||||
testImplementation platform("com.squareup.okhttp3:okhttp-bom:5.3.2")
|
||||
testImplementation "com.squareup.okhttp3:mockwebserver"
|
||||
}
|
||||
|
||||
|
||||
@@ -54,4 +54,4 @@ services:
|
||||
|
||||
networks:
|
||||
stirling-network:
|
||||
driver: bridge
|
||||
driver: bridge
|
||||
|
||||
@@ -1249,7 +1249,7 @@ includeAllRecipients = "Include CC and BCC recipients in header"
|
||||
downloadHtml = "Download HTML intermediate file instead of PDF"
|
||||
pdfaOptions = "PDF/A Options"
|
||||
outputFormat = "Output Format"
|
||||
pdfaNote = "PDF/A-1b is more compatible, PDF/A-2b supports more features."
|
||||
pdfaNote = "PDF/A-1b is more compatible, PDF/A-2b supports more features, PDF/A-3b supports embedded files."
|
||||
pdfaDigitalSignatureWarning = "The PDF contains a digital signature. This will be removed in the next step."
|
||||
fileFormat = "File Format"
|
||||
wordDoc = "Word Document"
|
||||
@@ -1278,6 +1278,21 @@ cbzOptions = "CBZ to PDF Options"
|
||||
optimizeForEbook = "Optimize PDF for ebook readers (uses Ghostscript)"
|
||||
cbzOutputOptions = "PDF to CBZ Options"
|
||||
cbzDpi = "DPI for image rendering"
|
||||
cbrOptions = "CBR Options"
|
||||
cbrOutputOptions = "PDF to CBR Options"
|
||||
cbrDpi = "DPI for image rendering"
|
||||
|
||||
[convert.ebookOptions]
|
||||
ebookOptions = "eBook to PDF Options"
|
||||
ebookOptionsDesc = "Options for converting eBooks to PDF"
|
||||
embedAllFonts = "Embed all fonts"
|
||||
embedAllFontsDesc = "Embed all fonts from the eBook into the generated PDF"
|
||||
includeTableOfContents = "Include table of contents"
|
||||
includeTableOfContentsDesc = "Add a generated table of contents to the resulting PDF"
|
||||
includePageNumbers = "Include page numbers"
|
||||
includePageNumbersDesc = "Add page numbers to the generated PDF"
|
||||
optimizeForEbookPdf = "Optimize for ebook readers"
|
||||
optimizeForEbookPdfDesc = "Optimize the PDF for eBook reading (smaller file size, better rendering on eInk devices)"
|
||||
|
||||
[imageToPdf]
|
||||
tags = "conversion,img,jpg,picture,photo"
|
||||
@@ -1394,6 +1409,11 @@ header = "Add Attachments"
|
||||
add = "Add Attachment"
|
||||
remove = "Remove Attachment"
|
||||
embed = "Embed Attachment"
|
||||
convertToPdfA3b = "Convert to PDF/A-3b"
|
||||
convertToPdfA3bDescription = "Creates an archival PDF with embedded attachments"
|
||||
convertToPdfA3bTooltip = "PDF/A-3b is an archival format ensuring long-term preservation. It allows embedding arbitrary file formats as attachments. Conversion requires Ghostscript and may take longer for large files."
|
||||
convertToPdfA3bTooltipHeader = "About PDF/A-3b Conversion"
|
||||
convertToPdfA3bTooltipTitle = "What it does"
|
||||
submit = "Add Attachments"
|
||||
|
||||
[watermark]
|
||||
@@ -2339,6 +2359,10 @@ saved = "Saved"
|
||||
label = "Upload signature image"
|
||||
placeholder = "Select image file"
|
||||
hint = "Upload a PNG or JPG image of your signature"
|
||||
removeBackground = "Remove white background (make transparent)"
|
||||
processing = "Processing image..."
|
||||
backgroundRemovalFailedTitle = "Background removal failed"
|
||||
backgroundRemovalFailedMessage = "Could not remove the background from the image. Using original image instead."
|
||||
|
||||
[sign.instructions]
|
||||
title = "How to add signature"
|
||||
@@ -2384,6 +2408,11 @@ note = "Flattening removes interactive elements from the PDF, making them non-ed
|
||||
label = "Flatten only forms"
|
||||
desc = "Only flatten form fields, leaving other interactive elements intact"
|
||||
|
||||
[flatten.renderDpi]
|
||||
label = "Rendering DPI (optional, recommended 150 DPI)"
|
||||
help = "Leave blank to use the system default. Higher DPI sharpens output but increases processing time and file size."
|
||||
placeholder = "e.g. 150"
|
||||
|
||||
[flatten.results]
|
||||
title = "Flatten Results"
|
||||
|
||||
@@ -2958,6 +2987,7 @@ header = "Crop PDF"
|
||||
submit = "Apply Crop"
|
||||
noFileSelected = "Select a PDF file to begin cropping"
|
||||
reset = "Reset to full PDF"
|
||||
autoCrop = "Auto-crop whitespace"
|
||||
|
||||
[crop.preview]
|
||||
title = "Crop Area Selection"
|
||||
@@ -3375,6 +3405,19 @@ placeholder = "Enter number of horizontal divisions"
|
||||
label = "Vertical Divisions"
|
||||
placeholder = "Enter number of vertical divisions"
|
||||
|
||||
[split-by-sections.splitMode]
|
||||
label = "Split Mode"
|
||||
description = "Choose how to split the pages"
|
||||
splitAll = "Split all pages"
|
||||
splitAllExceptFirst = "Split all except first"
|
||||
splitAllExceptLast = "Split all except last"
|
||||
splitAllExceptFirstAndLast = "Split all except first and last"
|
||||
custom = "Custom pages"
|
||||
|
||||
[split-by-sections.customPages]
|
||||
label = "Custom Page Numbers"
|
||||
placeholder = "e.g. 2,4,6"
|
||||
|
||||
[AddStampRequest]
|
||||
tags = "Stamp, Add image, center image, Watermark, PDF, Embed, Customize,Customise"
|
||||
header = "Stamp PDF"
|
||||
@@ -3736,6 +3779,9 @@ filesize = "File Size"
|
||||
[compress.grayscale]
|
||||
label = "Apply Grayscale for Compression"
|
||||
|
||||
[compress.linearize]
|
||||
label = "Linearize PDF for fast web viewing"
|
||||
|
||||
[compress.lineArt]
|
||||
label = "Convert images to line art"
|
||||
description = "Uses ImageMagick to reduce pages to high-contrast black and white for maximum size reduction."
|
||||
@@ -3779,6 +3825,11 @@ failed = "An error occurred while compressing the PDF."
|
||||
_value = "Compression Settings"
|
||||
1 = "1-3 PDF compression,</br> 4-6 lite image compression,</br> 7-9 intense image compression Will dramatically reduce image quality"
|
||||
|
||||
[compress.compressionLevel]
|
||||
range1to3 = "Lower values preserve quality but result in larger files"
|
||||
range4to6 = "Medium compression with moderate quality reduction"
|
||||
range7to9 = "Higher values reduce file size significantly but may reduce image clarity"
|
||||
|
||||
[decrypt]
|
||||
passwordPrompt = "This file is password-protected. Please enter the password:"
|
||||
cancelled = "Operation cancelled for PDF: {0}"
|
||||
@@ -6160,7 +6211,7 @@ title = "Authentication Failed"
|
||||
message = "Authentication was not successful. You can close this window and try again."
|
||||
|
||||
[pdfTextEditor]
|
||||
title = "PDF JSON Editor"
|
||||
title = "PDF Text Editor"
|
||||
viewLabel = "PDF Editor"
|
||||
converting = "Converting PDF to editable format..."
|
||||
conversionFailed = "Failed to convert PDF. Please try again."
|
||||
@@ -6189,6 +6240,8 @@ reset = "Reset Changes"
|
||||
downloadJson = "Download JSON"
|
||||
generatePdf = "Generate PDF"
|
||||
saveChanges = "Save Changes"
|
||||
applyChanges = "Apply Changes"
|
||||
downloadCopy = "Download Copy"
|
||||
|
||||
[pdfTextEditor.options.autoScaleText]
|
||||
title = "Auto-scale text to fit boxes"
|
||||
@@ -6207,6 +6260,24 @@ descriptionInline = "Tip: Hold Ctrl (Cmd) or Shift to multi-select text boxes. A
|
||||
title = "Lock edited text to a single PDF element"
|
||||
description = "When enabled, the editor exports each edited text box as one PDF text element to avoid overlapping glyphs or mixed fonts."
|
||||
|
||||
[pdfTextEditor.options.advanced]
|
||||
title = "Advanced Settings"
|
||||
|
||||
[pdfTextEditor.tooltip.header]
|
||||
title = "Preview Limitations"
|
||||
|
||||
[pdfTextEditor.tooltip.textFocus]
|
||||
title = "Text and Image Focus"
|
||||
text = "This workspace focuses on editing text and repositioning embedded images. Complex page artwork, form widgets, and layered graphics are preserved for export but are not fully editable here."
|
||||
|
||||
[pdfTextEditor.tooltip.previewVariance]
|
||||
title = "Preview Variance"
|
||||
text = "Some visuals (such as table borders, shapes, or annotation appearances) may not display exactly in the preview. The exported PDF keeps the original drawing commands whenever possible."
|
||||
|
||||
[pdfTextEditor.tooltip.alpha]
|
||||
title = "Alpha Viewer"
|
||||
text = "This alpha viewer is still evolving—certain fonts, colours, transparency effects, and layout details may shift slightly. Please double-check the generated PDF before sharing."
|
||||
|
||||
[pdfTextEditor.manual]
|
||||
mergeTooltip = "Merge selected boxes"
|
||||
merge = "Merge selection"
|
||||
@@ -6226,8 +6297,8 @@ alpha = "This alpha viewer is still evolving—certain fonts, colours, transpare
|
||||
[pdfTextEditor.empty]
|
||||
title = "No document loaded"
|
||||
subtitle = "Load a PDF or JSON file to begin editing text content."
|
||||
dropzone = "Drag and drop a PDF or JSON file here, or click to browse"
|
||||
dropzoneWithFiles = "Select a file from the Files tab, or drag and drop a PDF or JSON file here, or click to browse"
|
||||
dropzone = "Drag and drop a PDF here, or click to browse"
|
||||
dropzoneWithFiles = "Select a file from the Files tab, or drag and drop a PDF here, or click to browse"
|
||||
|
||||
[pdfTextEditor.welcomeBanner]
|
||||
title = "Welcome to PDF Text Editor (Early Access)"
|
||||
|
||||
@@ -1107,7 +1107,7 @@ title = "Dividi per conteggio"
|
||||
text = "Crea più PDF con un numero specifico di pagine o documenti ciascuno."
|
||||
bullet1 = "Conteggio pagine: numero fisso per file"
|
||||
bullet2 = "Numero documenti: numero fisso di file in output"
|
||||
bullet3 = "Utile per workflow batch"
|
||||
bullet3 = "Utile per batch di flusso di lavoro"
|
||||
|
||||
[split.tooltip.byChapters]
|
||||
title = "Dividi per capitoli"
|
||||
@@ -1696,7 +1696,7 @@ submit = "Estrai pagine"
|
||||
|
||||
[extractPages.pageNumbers]
|
||||
label = "Pagine da estrarre"
|
||||
placeholder = "es., 1,3,5-8 o odd & 1-10"
|
||||
placeholder = "es., 1,3,5-8 o dispari & 1-10"
|
||||
|
||||
[extractPages.settings]
|
||||
title = "Impostazioni"
|
||||
@@ -1711,7 +1711,7 @@ failed = "Impossibile estrarre le pagine"
|
||||
title = "Pagine estratte"
|
||||
|
||||
[pageSelection.tooltip]
|
||||
description = "Scegli quali pagine usare per l'operazione. Supporta pagine singole, intervalli, formule e la parola chiave \"all\"."
|
||||
description = "Scegli quali pagine usare per l'operazione. Supporta pagine singole, intervalli, formule e la parola chiave \"tutte\"."
|
||||
|
||||
[pageSelection.tooltip.header]
|
||||
title = "Guida Selezione Pagine"
|
||||
@@ -1721,7 +1721,7 @@ title = "Uso di base"
|
||||
text = "Seleziona pagine specifiche dal tuo PDF usando una sintassi semplice."
|
||||
bullet1 = "Pagine singole: 1,3,5"
|
||||
bullet2 = "Intervalli: 3-6 o 10-15"
|
||||
bullet3 = "Tutte le pagine: all"
|
||||
bullet3 = "Tutte le pagine: tutte"
|
||||
|
||||
[pageSelection.tooltip.advanced]
|
||||
title = "Funzionalità avanzate"
|
||||
@@ -1739,15 +1739,15 @@ text = "Usa numeri, intervalli, parole chiave e progressioni (n parte da 0). Son
|
||||
|
||||
[pageSelection.tooltip.syntax.bullets]
|
||||
numbers = "Numeri/intervalli: 5, 10-20"
|
||||
keywords = "Parole chiave: odd, even"
|
||||
keywords = "Parole chiave: dispari, pari"
|
||||
progressions = "Progressioni: 3n, 4n+1"
|
||||
|
||||
[pageSelection.tooltip.operators]
|
||||
title = "Operatori"
|
||||
text = "AND ha precedenza più alta della virgola. NOT si applica all’interno dell’intervallo del documento."
|
||||
and = "AND: & o \"and\" — richiede entrambe le condizioni (es., 1-50 & even)"
|
||||
text = "E ha precedenza più alta della virgola. NON si applica all’interno dell’intervallo del documento."
|
||||
and = "E: & o \"e\" — richiede entrambe le condizioni (es., 1-50 & pari)"
|
||||
comma = "Virgola: , o | — combina selezioni (es., 1-10, 20)"
|
||||
not = "NOT: ! o \"not\" — esclude pagine (es., 3n & not 30)"
|
||||
not = "NON: ! o \"NON\" — esclude pagine (es., 3n & non 30)"
|
||||
|
||||
[pageSelection.tooltip.examples]
|
||||
title = "Esempi"
|
||||
@@ -1795,15 +1795,15 @@ text = "Usa numeri, intervalli, parole chiave e progressioni (n parte da 0). Son
|
||||
|
||||
[bulkSelection.syntax.bullets]
|
||||
numbers = "Numeri/intervalli: 5, 10-20"
|
||||
keywords = "Parole chiave: odd, even"
|
||||
keywords = "Parole chiave: dispari, pari"
|
||||
progressions = "Progressioni: 3n, 4n+1"
|
||||
|
||||
[bulkSelection.operators]
|
||||
title = "Operatori"
|
||||
text = "AND ha precedenza più alta della virgola. NOT si applica all’interno dell’intervallo del documento."
|
||||
and = "AND: & o \"and\" — richiede entrambe le condizioni (es., 1-50 & even)"
|
||||
text = "E ha precedenza più alta della virgola. NON si applica all’interno dell’intervallo del documento."
|
||||
and = "E: & o \"e\" — richiede entrambe le condizioni (es., 1-50 & pari)"
|
||||
comma = "Virgola: , o | — combina selezioni (es., 1-10, 20)"
|
||||
not = "NOT: ! o \"not\" — esclude pagine (es., 3n & not 30)"
|
||||
not = "NON: ! o \"non\" — esclude pagine (es., 3n & non 30)"
|
||||
|
||||
[bulkSelection.examples]
|
||||
title = "Esempi"
|
||||
@@ -2163,9 +2163,9 @@ info = "Python non è installato. È necessario per l'esecuzione."
|
||||
|
||||
[ScannerImageSplit.selectText]
|
||||
1 = "Soglia angolo:"
|
||||
2 = "Imposta il minimo angolo richiesto perché l'immagine venga ruotata (default: 10)."
|
||||
2 = "Imposta il minimo angolo richiesto perché l'immagine venga ruotata (predefinito: 10)."
|
||||
3 = "Tolleranza:"
|
||||
4 = "Imposta lo spettro di colori attorno al colore di sfondo stimato (default: 30)."
|
||||
4 = "Imposta lo spettro di colori attorno al colore di sfondo stimato (predefinito: 30)."
|
||||
5 = "Area minima:"
|
||||
6 = "Imposta l'area minima di una foto (default: 10000)."
|
||||
7 = "Area di contorno minima:"
|
||||
@@ -2343,26 +2343,26 @@ placeholder = "Seleziona un file PDF nella vista principale per iniziare"
|
||||
settings = "Impostazioni"
|
||||
|
||||
[flatten.options]
|
||||
stepTitle = "Opzioni di flattening"
|
||||
title = "Opzioni di flattening"
|
||||
note = "Il flattening rimuove gli elementi interattivi dal PDF, rendendoli non modificabili."
|
||||
stepTitle = "Opzioni di appiattimento"
|
||||
title = "Opzioni di appiattimento"
|
||||
note = "L'appiattimento rimuove gli elementi interattivi dal PDF, rendendoli non modificabili."
|
||||
|
||||
[flatten.options.flattenOnlyForms]
|
||||
label = "Appiattisci solo i moduli"
|
||||
desc = "Appiattisci solo i campi modulo, lasciando intatti gli altri elementi interattivi"
|
||||
|
||||
[flatten.results]
|
||||
title = "Risultati Flatten"
|
||||
title = "Risultati di appiattimento"
|
||||
|
||||
[flatten.error]
|
||||
failed = "Si è verificato un errore durante il flattening del PDF."
|
||||
failed = "Si è verificato un errore durante l'appiattimento del PDF."
|
||||
|
||||
[flatten.tooltip.header]
|
||||
title = "Informazioni sul flattening dei PDF"
|
||||
title = "Informazioni sull'appiattimento dei PDF"
|
||||
|
||||
[flatten.tooltip.description]
|
||||
title = "Cosa fa il flattening?"
|
||||
text = "Il flattening rende il tuo PDF non modificabile trasformando moduli compilabili e pulsanti in testo e immagini normali. Il PDF avrà lo stesso aspetto, ma nessuno potrà più modificare o compilare i moduli. Perfetto per condividere moduli completati, creare documenti finali per gli archivi o garantire un aspetto uniforme ovunque."
|
||||
title = "Cosa fa l'appiattimento?"
|
||||
text = "L'appiattimento rende il tuo PDF non modificabile trasformando moduli compilabili e pulsanti in testo e immagini normali. Il PDF avrà lo stesso aspetto, ma nessuno potrà più modificare o compilare i moduli. Perfetto per condividere moduli completati, creare documenti finali per gli archivi o garantire un aspetto uniforme ovunque."
|
||||
bullet1 = "Le caselle di testo diventano testo normale (non modificabile)"
|
||||
bullet2 = "Checkbox e pulsanti diventano immagini"
|
||||
bullet3 = "Ottimo per versioni finali che non vuoi vengano modificate"
|
||||
@@ -2469,7 +2469,7 @@ title = "Compara"
|
||||
header = "Compara PDF"
|
||||
clearSelected = "Cancella selezionati"
|
||||
addFilesHint = "Aggiungi PDF nel passaggio File per abilitarne la selezione."
|
||||
noFiles = "Nessun PDF disponibile yet"
|
||||
noFiles = "Nessun PDF disponibile"
|
||||
pages = "Pagine"
|
||||
cta = "Confronta"
|
||||
loading = "Confronto in corso..."
|
||||
@@ -4168,7 +4168,7 @@ label = "Directory pipeline"
|
||||
|
||||
[admin.settings.general.customPaths.pipeline.watchedFoldersDir]
|
||||
label = "Directory cartelle monitorate"
|
||||
description = "Directory in cui la pipeline monitora i PDF in arrivo (lascia vuoto per default: /pipeline/watchedFolders)"
|
||||
description = "Directory in cui la pipeline monitora i PDF in arrivo (lascia vuoto per predefinito: /pipeline/watchedFolders)"
|
||||
|
||||
[admin.settings.general.customPaths.pipeline.finishedFoldersDir]
|
||||
label = "Directory cartelle completate"
|
||||
@@ -4179,11 +4179,11 @@ label = "Percorsi strumenti esterni"
|
||||
|
||||
[admin.settings.general.customPaths.operations.weasyprint]
|
||||
label = "Eseguibile WeasyPrint"
|
||||
description = "Percorso dell'eseguibile WeasyPrint per conversione da HTML a PDF (lascia vuoto per default: /opt/venv/bin/weasyprint)"
|
||||
description = "Percorso dell'eseguibile WeasyPrint per conversione da HTML a PDF (lascia vuoto per predefinito: /opt/venv/bin/weasyprint)"
|
||||
|
||||
[admin.settings.general.customPaths.operations.unoconvert]
|
||||
label = "Eseguibile Unoconvert"
|
||||
description = "Percorso di LibreOffice unoconvert per conversioni di documenti (lascia vuoto per default: /opt/venv/bin/unoconvert)"
|
||||
description = "Percorso di LibreOffice unoconvert per conversioni di documenti (lascia vuoto per predefinito: /opt/venv/bin/unoconvert)"
|
||||
|
||||
[admin.settings.security]
|
||||
title = "Sicurezza"
|
||||
@@ -4305,12 +4305,12 @@ label = "Blocca localhost"
|
||||
description = "Blocca localhost e indirizzi loopback (127.x.x.x, ::1)"
|
||||
|
||||
[admin.settings.security.htmlUrlSecurity.blockLinkLocal]
|
||||
label = "Blocca indirizzi link-local"
|
||||
description = "Blocca indirizzi link-local (169.254.x.x, fe80::/10)"
|
||||
label = "Blocca indirizzi link-locali"
|
||||
description = "Blocca indirizzi link-locali (169.254.x.x, fe80::/10)"
|
||||
|
||||
[admin.settings.security.htmlUrlSecurity.blockCloudMetadata]
|
||||
label = "Blocca endpoint dei metadata cloud"
|
||||
description = "Blocca gli endpoint dei metadata dei provider cloud (169.254.169.254)"
|
||||
label = "Blocca endpoint dei metadati cloud"
|
||||
description = "Blocca gli endpoint dei metadati dei provider cloud (169.254.169.254)"
|
||||
|
||||
[admin.settings.connections]
|
||||
title = "Connessioni"
|
||||
@@ -5211,7 +5211,7 @@ noSearchResults = "Nessuno strumento trovato"
|
||||
noTools = "Nessuno strumento disponibile"
|
||||
|
||||
[onboarding]
|
||||
allTools = "This is the <strong>All Tools</strong> panel, where you can browse and select from all available PDF tools."
|
||||
allTools = "Questo è il pannello <strong>Tutti gli Strumenti</strong>, dove puoi sfogliare e selezionare tutti gli strumenti PDF disponibili."
|
||||
selectCropTool = "Selezioniamo lo strumento <strong>Ritaglia</strong> per mostrare come usarne uno."
|
||||
toolInterface = "Questa è l'interfaccia dello strumento <strong>Ritaglia</strong>. Come vedi, non c'è molto perché non abbiamo ancora aggiunto file PDF su cui lavorare."
|
||||
filesButton = "Il pulsante <strong>File</strong> sulla barra di accesso rapido consente di caricare PDF su cui usare gli strumenti."
|
||||
|
||||
@@ -19,27 +19,27 @@ const debug = (message) => {
|
||||
function scanForUsedIcons() {
|
||||
const usedIcons = new Set();
|
||||
const srcDir = path.join(__dirname, '..', 'src');
|
||||
|
||||
|
||||
info('🔍 Scanning codebase for LocalIcon usage...');
|
||||
|
||||
|
||||
if (!fs.existsSync(srcDir)) {
|
||||
console.error('❌ Source directory not found:', srcDir);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
|
||||
// Recursively scan all .tsx and .ts files
|
||||
function scanDirectory(dir) {
|
||||
const files = fs.readdirSync(dir);
|
||||
|
||||
|
||||
files.forEach(file => {
|
||||
const filePath = path.join(dir, file);
|
||||
const stat = fs.statSync(filePath);
|
||||
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
scanDirectory(filePath);
|
||||
} else if (file.endsWith('.tsx') || file.endsWith('.ts')) {
|
||||
const content = fs.readFileSync(filePath, 'utf8');
|
||||
|
||||
|
||||
// Match LocalIcon usage: <LocalIcon icon="icon-name" ...>
|
||||
const localIconMatches = content.match(/<LocalIcon\s+[^>]*icon="([^"]+)"/g);
|
||||
if (localIconMatches) {
|
||||
@@ -51,7 +51,7 @@ function scanForUsedIcons() {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// Match old material-symbols-rounded spans: <span className="material-symbols-rounded">icon-name</span>
|
||||
const spanMatches = content.match(/<span[^>]*className="[^"]*material-symbols-rounded[^"]*"[^>]*>([^<]+)<\/span>/g);
|
||||
if (spanMatches) {
|
||||
@@ -64,7 +64,7 @@ function scanForUsedIcons() {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// Match Icon component usage: <Icon icon="material-symbols:icon-name" ...>
|
||||
const iconMatches = content.match(/<Icon\s+[^>]*icon="material-symbols:([^"]+)"/g);
|
||||
if (iconMatches) {
|
||||
@@ -79,12 +79,12 @@ function scanForUsedIcons() {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
scanDirectory(srcDir);
|
||||
|
||||
|
||||
const iconArray = Array.from(usedIcons).sort();
|
||||
info(`📋 Found ${iconArray.length} unique icons across codebase`);
|
||||
|
||||
|
||||
return iconArray;
|
||||
}
|
||||
|
||||
@@ -102,7 +102,7 @@ async function main() {
|
||||
const existingSet = JSON.parse(fs.readFileSync(outputPath, 'utf8'));
|
||||
const existingIcons = Object.keys(existingSet.icons || {}).sort();
|
||||
const currentIcons = [...usedIcons].sort();
|
||||
|
||||
|
||||
if (JSON.stringify(existingIcons) === JSON.stringify(currentIcons)) {
|
||||
needsRegeneration = false;
|
||||
info(`✅ Icon set already up-to-date (${usedIcons.length} icons, ${Math.round(fs.statSync(outputPath).size / 1024)}KB)`);
|
||||
@@ -122,7 +122,7 @@ async function main() {
|
||||
|
||||
// Dynamic import of ES module
|
||||
const { getIcons } = await import('@iconify/utils');
|
||||
|
||||
|
||||
// Extract only our used icons from the full set
|
||||
const extractedIcons = getIcons(icons, usedIcons);
|
||||
|
||||
@@ -183,4 +183,4 @@ export default iconSet;
|
||||
main().catch(error => {
|
||||
console.error('❌ Script failed:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
|
||||
"productName": "Stirling-PDF",
|
||||
"version": "2.1.5",
|
||||
"version": "2.2.0",
|
||||
"identifier": "stirling.pdf.dev",
|
||||
"build": {
|
||||
"frontendDist": "../dist",
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import React from 'react';
|
||||
import { FileInput, Text, Stack } from '@mantine/core';
|
||||
import React, { useState } from 'react';
|
||||
import { FileInput, Text, Stack, Checkbox } from '@mantine/core';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { PrivateContent } from '@app/components/shared/PrivateContent';
|
||||
import { removeWhiteBackground } from '@app/utils/imageTransparency';
|
||||
import { alert } from '@app/components/toast';
|
||||
|
||||
interface ImageUploaderProps {
|
||||
onImageChange: (file: File | null) => void;
|
||||
@@ -9,6 +11,8 @@ interface ImageUploaderProps {
|
||||
label?: string;
|
||||
placeholder?: string;
|
||||
hint?: string;
|
||||
allowBackgroundRemoval?: boolean;
|
||||
onProcessedImageData?: (dataUrl: string | null) => void;
|
||||
}
|
||||
|
||||
export const ImageUploader: React.FC<ImageUploaderProps> = ({
|
||||
@@ -16,26 +20,89 @@ export const ImageUploader: React.FC<ImageUploaderProps> = ({
|
||||
disabled = false,
|
||||
label,
|
||||
placeholder,
|
||||
hint
|
||||
hint,
|
||||
allowBackgroundRemoval = false,
|
||||
onProcessedImageData
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [removeBackground, setRemoveBackground] = useState(false);
|
||||
const [currentFile, setCurrentFile] = useState<File | null>(null);
|
||||
const [originalImageData, setOriginalImageData] = useState<string | null>(null);
|
||||
const [isProcessing, setIsProcessing] = useState(false);
|
||||
|
||||
const processImage = async (imageSource: File | string, shouldRemoveBackground: boolean): Promise<void> => {
|
||||
if (shouldRemoveBackground && allowBackgroundRemoval) {
|
||||
setIsProcessing(true);
|
||||
try {
|
||||
const transparentImageDataUrl = await removeWhiteBackground(imageSource, {
|
||||
autoDetectCorner: true,
|
||||
tolerance: 15
|
||||
});
|
||||
onProcessedImageData?.(transparentImageDataUrl);
|
||||
} catch (error) {
|
||||
console.error('Error removing background:', error);
|
||||
alert({
|
||||
title: t('sign.image.backgroundRemovalFailedTitle', 'Background removal failed'),
|
||||
body: t('sign.image.backgroundRemovalFailedMessage', 'Could not remove the background from the image. Using original image instead.'),
|
||||
alertType: 'error'
|
||||
});
|
||||
onProcessedImageData?.(null);
|
||||
} finally {
|
||||
setIsProcessing(false);
|
||||
}
|
||||
} else {
|
||||
// When background removal is disabled, return the original image data
|
||||
if (typeof imageSource === 'string') {
|
||||
onProcessedImageData?.(imageSource);
|
||||
} else {
|
||||
// Convert File to data URL if needed
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => {
|
||||
onProcessedImageData?.(e.target?.result as string);
|
||||
};
|
||||
reader.readAsDataURL(imageSource);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleImageChange = async (file: File | null) => {
|
||||
if (file && !disabled) {
|
||||
try {
|
||||
// Validate that it's actually an image file
|
||||
if (!file.type.startsWith('image/')) {
|
||||
console.error('Selected file is not an image');
|
||||
// Validate that it's actually an image file or SVG
|
||||
if (!file.type.startsWith('image/') && !file.name.toLowerCase().endsWith('.svg')) {
|
||||
console.error('Selected file is not an image or SVG');
|
||||
return;
|
||||
}
|
||||
|
||||
setCurrentFile(file);
|
||||
onImageChange(file);
|
||||
|
||||
const originalDataUrl = await new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => resolve(e.target?.result as string);
|
||||
reader.onerror = () => reject(reader.error);
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
|
||||
setOriginalImageData(originalDataUrl);
|
||||
await processImage(file, removeBackground);
|
||||
} catch (error) {
|
||||
console.error('Error processing image file:', error);
|
||||
}
|
||||
} else if (!file) {
|
||||
// Clear image data when no file is selected
|
||||
setCurrentFile(null);
|
||||
setOriginalImageData(null);
|
||||
onImageChange(null);
|
||||
onProcessedImageData?.(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleBackgroundRemovalChange = async (checked: boolean) => {
|
||||
if (isProcessing) return; // Prevent race conditions
|
||||
setRemoveBackground(checked);
|
||||
if (originalImageData) {
|
||||
await processImage(originalImageData, checked);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -45,16 +112,29 @@ export const ImageUploader: React.FC<ImageUploaderProps> = ({
|
||||
<FileInput
|
||||
label={label}
|
||||
placeholder={placeholder || t('sign.image.placeholder', 'Select image file')}
|
||||
accept="image/*"
|
||||
accept="image/*,.svg"
|
||||
onChange={handleImageChange}
|
||||
disabled={disabled}
|
||||
disabled={disabled || isProcessing}
|
||||
/>
|
||||
</PrivateContent>
|
||||
{allowBackgroundRemoval && (
|
||||
<Checkbox
|
||||
label={t('sign.image.removeBackground', 'Remove white background (make transparent)')}
|
||||
checked={removeBackground}
|
||||
onChange={(event) => handleBackgroundRemovalChange(event.currentTarget.checked)}
|
||||
disabled={disabled || !currentFile || isProcessing}
|
||||
/>
|
||||
)}
|
||||
{hint && (
|
||||
<Text size="sm" c="dimmed">
|
||||
{hint}
|
||||
</Text>
|
||||
)}
|
||||
{isProcessing && (
|
||||
<Text size="sm" c="dimmed">
|
||||
{t('sign.image.processing', 'Processing image...')}
|
||||
</Text>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -112,6 +112,7 @@ const FileEditorThumbnail = ({
|
||||
}, [file.name]);
|
||||
|
||||
const isCBZ = extLower === 'cbz';
|
||||
const isCBR = extLower === 'cbr';
|
||||
|
||||
const pageLabel = useMemo(
|
||||
() =>
|
||||
@@ -226,7 +227,7 @@ const FileEditorThumbnail = ({
|
||||
alert({ alertType: 'success', title: `Unzipping ${file.name}`, expandable: false, durationMs: 2500 });
|
||||
}
|
||||
},
|
||||
hidden: !isZipFile || !onUnzipFile || isCBZ,
|
||||
hidden: !isZipFile || !onUnzipFile || isCBZ || isCBR,
|
||||
},
|
||||
{
|
||||
id: 'close',
|
||||
@@ -238,7 +239,7 @@ const FileEditorThumbnail = ({
|
||||
},
|
||||
color: 'red',
|
||||
}
|
||||
], [t, file.id, file.name, isZipFile, onViewFile, onDownloadFile, onUnzipFile, handleCloseWithConfirmation]);
|
||||
], [t, file.id, file.name, isZipFile, isCBR, onViewFile, onDownloadFile, onUnzipFile, handleCloseWithConfirmation]);
|
||||
|
||||
// ---- Card interactions ----
|
||||
const handleCardClick = () => {
|
||||
|
||||
@@ -52,6 +52,11 @@ const FileListItem: React.FC<FileListItemProps> = ({
|
||||
// Check if this is a ZIP file
|
||||
const isZipFile = zipFileService.isZipFileStub(file);
|
||||
|
||||
// Check file extension
|
||||
const extLower = (file.name?.match(/\.([a-z0-9]+)$/i)?.[1] || '').toLowerCase();
|
||||
const isCBZ = extLower === 'cbz';
|
||||
const isCBR = extLower === 'cbr';
|
||||
|
||||
// Keep item in hovered state if menu is open
|
||||
const shouldShowHovered = isHovered || isMenuOpen;
|
||||
|
||||
@@ -240,7 +245,7 @@ const FileListItem: React.FC<FileListItemProps> = ({
|
||||
)}
|
||||
|
||||
{/* Unzip option for ZIP files */}
|
||||
{isZipFile && !isHistoryFile && (
|
||||
{isZipFile && !isHistoryFile && !isCBZ && !isCBR && (
|
||||
<>
|
||||
<Menu.Item
|
||||
leftSection={<UnarchiveIcon style={{ fontSize: 16 }} />}
|
||||
|
||||
@@ -173,6 +173,12 @@ const QuickAccessBar = forwardRef<HTMLDivElement>((_, ref) => {
|
||||
// onClick: () => setActiveButton('activity')
|
||||
//},
|
||||
|
||||
// Determine if settings button should be hidden
|
||||
// Hide when login is disabled AND showSettingsWhenNoLogin is false
|
||||
const shouldHideSettingsButton =
|
||||
config?.enableLogin === false &&
|
||||
config?.showSettingsWhenNoLogin === false;
|
||||
|
||||
const bottomButtons: ButtonConfig[] = [
|
||||
{
|
||||
id: 'help',
|
||||
@@ -185,17 +191,17 @@ const QuickAccessBar = forwardRef<HTMLDivElement>((_, ref) => {
|
||||
// This will be overridden by the wrapper logic
|
||||
},
|
||||
},
|
||||
{
|
||||
...(shouldHideSettingsButton ? [] : [{
|
||||
id: 'config',
|
||||
name: t("quickAccess.settings", "Settings"),
|
||||
icon: <LocalIcon icon="settings-rounded" width="1.25rem" height="1.25rem" />,
|
||||
size: 'md',
|
||||
type: 'modal',
|
||||
size: 'md' as const,
|
||||
type: 'modal' as const,
|
||||
onClick: () => {
|
||||
navigate('/settings/overview');
|
||||
setConfigModalOpen(true);
|
||||
}
|
||||
}
|
||||
} as ButtonConfig])
|
||||
];
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Paper, Group, Text, Button, Collapse, Stack, TextInput, Textarea, Switch, PasswordInput } from '@mantine/core';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import LocalIcon from '@app/components/shared/LocalIcon';
|
||||
@@ -25,14 +25,22 @@ export default function ProviderCard({
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [localSettings, setLocalSettings] = useState<Record<string, any>>(settings);
|
||||
|
||||
// Keep local settings in sync with incoming settings (values loaded from settings.yml)
|
||||
useEffect(() => {
|
||||
if (!expanded) {
|
||||
setLocalSettings(settings);
|
||||
}
|
||||
}, [settings, expanded]);
|
||||
|
||||
// Initialize local settings with defaults when opening an unconfigured provider
|
||||
const handleConnectToggle = () => {
|
||||
if (!isConfigured && !expanded) {
|
||||
// First time opening an unconfigured provider - initialize with defaults
|
||||
const defaultSettings: Record<string, any> = {};
|
||||
// while preserving any values already present (from settings.yml)
|
||||
const defaultSettings: Record<string, any> = { ...settings };
|
||||
provider.fields.forEach((field) => {
|
||||
if (field.defaultValue !== undefined) {
|
||||
defaultSettings[field.key] = field.defaultValue;
|
||||
defaultSettings[field.key] = defaultSettings[field.key] ?? field.defaultValue;
|
||||
}
|
||||
});
|
||||
setLocalSettings(defaultSettings);
|
||||
|
||||
@@ -8,6 +8,7 @@ interface Props {
|
||||
min?: number;
|
||||
max?: number;
|
||||
step?: number;
|
||||
suffix?: string;
|
||||
}
|
||||
|
||||
export default function SliderWithInput({
|
||||
@@ -18,11 +19,12 @@ export default function SliderWithInput({
|
||||
min = 0,
|
||||
max = 200,
|
||||
step = 1,
|
||||
suffix = '%',
|
||||
}: Props) {
|
||||
return (
|
||||
<div>
|
||||
<Text size="sm" fw={600} mb={4}>{label}: {Math.round(value)}%</Text>
|
||||
<Group gap="sm" align="center">
|
||||
<Text size="sm" fw={500} mb={8}>{label}</Text>
|
||||
<Group gap="md" align="center">
|
||||
<div style={{ flex: 1 }}>
|
||||
<Slider min={min} max={max} step={step} value={value} onChange={onChange} disabled={disabled} />
|
||||
</div>
|
||||
@@ -33,6 +35,7 @@ export default function SliderWithInput({
|
||||
max={max}
|
||||
step={step}
|
||||
disabled={disabled}
|
||||
suffix={suffix}
|
||||
style={{ width: 90 }}
|
||||
/>
|
||||
</Group>
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
/**
|
||||
* AddAttachmentsSettings - Shared settings component for both tool UI and automation
|
||||
*
|
||||
* Allows selecting files to attach to PDFs.
|
||||
* Allows selecting files to attach to PDFs with optional PDF/A-3b conversion support.
|
||||
*/
|
||||
|
||||
import { Stack, Text, Group, ActionIcon, ScrollArea, Button } from "@mantine/core";
|
||||
import { Stack, Text, Group, ActionIcon, ScrollArea, Button, Checkbox } from "@mantine/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { AddAttachmentsParameters } from "@app/hooks/tools/addAttachments/useAddAttachmentsParameters";
|
||||
import LocalIcon from "@app/components/shared/LocalIcon";
|
||||
import { Tooltip } from "@app/components/shared/Tooltip";
|
||||
|
||||
interface AddAttachmentsSettingsProps {
|
||||
parameters: AddAttachmentsParameters;
|
||||
@@ -103,6 +104,40 @@ const AddAttachmentsSettings = ({ parameters, onParameterChange, disabled = fals
|
||||
</ScrollArea.Autosize>
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
{/* PDF/A-3b conversion option with informative tooltip */}
|
||||
<Group gap="xs" align="flex-start">
|
||||
<Checkbox
|
||||
label={
|
||||
<Group gap={4}>
|
||||
<Text size="sm">{t("attachments.convertToPdfA3b", "Convert to PDF/A-3b")}</Text>
|
||||
<Tooltip
|
||||
header={{
|
||||
title: t("attachments.convertToPdfA3bTooltipHeader", "About PDF/A-3b Conversion")
|
||||
}}
|
||||
tips={[
|
||||
{
|
||||
title: t("attachments.convertToPdfA3bTooltipTitle", "What it does"),
|
||||
description: t(
|
||||
"attachments.convertToPdfA3bTooltip",
|
||||
"PDF/A-3b is an archival format ensuring long-term preservation. It allows embedding arbitrary file formats as attachments. Conversion requires Ghostscript and may take longer for large files."
|
||||
)
|
||||
}
|
||||
]}
|
||||
sidebarTooltip={true}
|
||||
pinOnClick={true}
|
||||
>
|
||||
<LocalIcon icon="info-outline-rounded" width="1.25rem" height="1.25rem" style={{ color: 'var(--icon-files-color)', cursor: 'help' }} />
|
||||
</Tooltip>
|
||||
</Group>
|
||||
}
|
||||
description={t("attachments.convertToPdfA3bDescription", "Creates an archival PDF with embedded attachments")}
|
||||
checked={parameters.convertToPdfA3b}
|
||||
onChange={(event) => onParameterChange('convertToPdfA3b', event.currentTarget.checked)}
|
||||
disabled={disabled}
|
||||
styles={{ root: { flex: 1 } }}
|
||||
/>
|
||||
</Group>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Stack, Text, NumberInput, Select, Divider, Checkbox, Slider, SegmentedControl } from "@mantine/core";
|
||||
import SliderWithInput from '@app/components/shared/sliderWithInput/SliderWithInput';
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { CompressParameters } from "@app/hooks/tools/compress/useCompressParameters";
|
||||
import ButtonSelector from "@app/components/shared/ButtonSelector";
|
||||
@@ -13,7 +14,6 @@ interface CompressSettingsProps {
|
||||
|
||||
const CompressSettings = ({ parameters, onParameterChange, disabled = false }: CompressSettingsProps) => {
|
||||
const { t } = useTranslation();
|
||||
const [isSliding, setIsSliding] = useState(false);
|
||||
const [imageMagickAvailable, setImageMagickAvailable] = useState<boolean | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -47,57 +47,22 @@ const CompressSettings = ({ parameters, onParameterChange, disabled = false }: C
|
||||
|
||||
{/* Quality Adjustment */}
|
||||
{parameters.compressionMethod === 'quality' && (
|
||||
<Stack gap="sm">
|
||||
<Stack gap="md">
|
||||
<Divider />
|
||||
<Text size="sm" fw={500}>Compression Level</Text>
|
||||
<div style={{ position: 'relative' }}>
|
||||
<input
|
||||
type="range"
|
||||
min="1"
|
||||
max="9"
|
||||
step="1"
|
||||
value={parameters.compressionLevel}
|
||||
onChange={(e) => onParameterChange('compressionLevel', parseInt(e.target.value))}
|
||||
onMouseDown={() => setIsSliding(true)}
|
||||
onMouseUp={() => setIsSliding(false)}
|
||||
onTouchStart={() => setIsSliding(true)}
|
||||
onTouchEnd={() => setIsSliding(false)}
|
||||
disabled={disabled}
|
||||
style={{
|
||||
width: '100%',
|
||||
height: '6px',
|
||||
borderRadius: '3px',
|
||||
background: `linear-gradient(to right, #228be6 0%, #228be6 ${(parameters.compressionLevel - 1) / 8 * 100}%, #e9ecef ${(parameters.compressionLevel - 1) / 8 * 100}%, #e9ecef 100%)`,
|
||||
outline: 'none',
|
||||
WebkitAppearance: 'none'
|
||||
}}
|
||||
/>
|
||||
{isSliding && (
|
||||
<div style={{
|
||||
position: 'absolute',
|
||||
top: '-25px',
|
||||
left: `${(parameters.compressionLevel - 1) / 8 * 100}%`,
|
||||
transform: 'translateX(-50%)',
|
||||
background: '#f8f9fa',
|
||||
border: '1px solid #dee2e6',
|
||||
borderRadius: '4px',
|
||||
padding: '2px 6px',
|
||||
fontSize: '12px',
|
||||
color: '#228be6',
|
||||
whiteSpace: 'nowrap'
|
||||
}}>
|
||||
{parameters.compressionLevel}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', color: '#6c757d' }}>
|
||||
<span>Min 1</span>
|
||||
<span>Max 9</span>
|
||||
</div>
|
||||
<Text size="xs" c="dimmed" style={{ marginTop: '8px' }}>
|
||||
{parameters.compressionLevel <= 3 && "1-3 PDF compression"}
|
||||
{parameters.compressionLevel >= 4 && parameters.compressionLevel <= 6 && "4-6 lite image compression"}
|
||||
{parameters.compressionLevel >= 7 && "7-9 intense image compression Will dramatically reduce image quality"}
|
||||
<SliderWithInput
|
||||
label={t('compress.tooltip.qualityAdjustment.title', 'Compression Level')}
|
||||
value={parameters.compressionLevel}
|
||||
onChange={(value) => onParameterChange('compressionLevel', value)}
|
||||
disabled={disabled}
|
||||
min={1}
|
||||
max={9}
|
||||
step={1}
|
||||
suffix=""
|
||||
/>
|
||||
<Text size="xs" c="dimmed" mt={-4}>
|
||||
{parameters.compressionLevel <= 3 && t('compress.compressionLevel.range1to3', 'Lower values preserve quality but result in larger files')}
|
||||
{parameters.compressionLevel >= 4 && parameters.compressionLevel <= 6 && t('compress.compressionLevel.range4to6', 'Medium compression with moderate quality reduction')}
|
||||
{parameters.compressionLevel >= 7 && t('compress.compressionLevel.range7to9', 'Higher values reduce file size significantly but may reduce image clarity')}
|
||||
</Text>
|
||||
</Stack>
|
||||
)}
|
||||
@@ -144,6 +109,17 @@ const CompressSettings = ({ parameters, onParameterChange, disabled = false }: C
|
||||
disabled={disabled}
|
||||
label={t("compress.grayscale.label", "Apply Grayscale for compression")}
|
||||
/>
|
||||
|
||||
{/* Linearize Option */}
|
||||
<Stack gap="sm">
|
||||
<Checkbox
|
||||
checked={parameters.linearize}
|
||||
onChange={(event) => onParameterChange('linearize', event.currentTarget.checked)}
|
||||
disabled={disabled}
|
||||
label={t("compress.linearize.label", "Linearize PDF for fast web viewing")}
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
<Checkbox
|
||||
checked={parameters.lineArt}
|
||||
onChange={(event) => onParameterChange('lineArt', event.currentTarget.checked)}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Stack, Text, Checkbox } from '@mantine/core';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ConvertParameters } from "@app/hooks/tools/convert/useConvertParameters";
|
||||
|
||||
interface ConvertFromCbrSettingsProps {
|
||||
parameters: ConvertParameters;
|
||||
onParameterChange: <K extends keyof ConvertParameters>(key: K, value: ConvertParameters[K]) => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
const ConvertFromCbrSettings = ({
|
||||
parameters,
|
||||
onParameterChange,
|
||||
disabled = false
|
||||
}: ConvertFromCbrSettingsProps) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Stack gap="sm" data-testid="cbr-settings">
|
||||
<Text size="sm" fw={500}>{t("convert.cbrOptions", "CBR Options")}:</Text>
|
||||
|
||||
<Checkbox
|
||||
label={t('convert.optimizeForEbook', 'Optimize PDF for ebook readers (uses Ghostscript)')}
|
||||
checked={parameters.cbrOptions.optimizeForEbook}
|
||||
onChange={(event) => onParameterChange('cbrOptions', {
|
||||
...parameters.cbrOptions,
|
||||
optimizeForEbook: event.currentTarget.checked
|
||||
})}
|
||||
disabled={disabled}
|
||||
data-testid="optimize-ebook-checkbox"
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
export default ConvertFromCbrSettings;
|
||||
@@ -0,0 +1,96 @@
|
||||
import { Stack, Checkbox } from "@mantine/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ConvertParameters } from "@app/hooks/tools/convert/useConvertParameters";
|
||||
|
||||
interface ConvertFromEbookSettingsProps {
|
||||
parameters: ConvertParameters;
|
||||
onParameterChange: <K extends keyof ConvertParameters>(key: K, value: ConvertParameters[K]) => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
const ConvertFromEbookSettings = ({
|
||||
parameters,
|
||||
onParameterChange,
|
||||
disabled = false
|
||||
}: ConvertFromEbookSettingsProps) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const handleEmbedAllFontsChange = (value: boolean) => {
|
||||
onParameterChange('ebookOptions', {
|
||||
embedAllFonts: value,
|
||||
includeTableOfContents: parameters.ebookOptions?.includeTableOfContents ?? false,
|
||||
includePageNumbers: parameters.ebookOptions?.includePageNumbers ?? false,
|
||||
optimizeForEbook: parameters.ebookOptions?.optimizeForEbook ?? false,
|
||||
});
|
||||
};
|
||||
|
||||
const handleIncludeTableOfContentsChange = (value: boolean) => {
|
||||
onParameterChange('ebookOptions', {
|
||||
embedAllFonts: parameters.ebookOptions?.embedAllFonts ?? false,
|
||||
includeTableOfContents: value,
|
||||
includePageNumbers: parameters.ebookOptions?.includePageNumbers ?? false,
|
||||
optimizeForEbook: parameters.ebookOptions?.optimizeForEbook ?? false,
|
||||
});
|
||||
};
|
||||
|
||||
const handleIncludePageNumbersChange = (value: boolean) => {
|
||||
onParameterChange('ebookOptions', {
|
||||
embedAllFonts: parameters.ebookOptions?.embedAllFonts ?? false,
|
||||
includeTableOfContents: parameters.ebookOptions?.includeTableOfContents ?? false,
|
||||
includePageNumbers: value,
|
||||
optimizeForEbook: parameters.ebookOptions?.optimizeForEbook ?? false,
|
||||
});
|
||||
};
|
||||
|
||||
const handleOptimizeForEbookChange = (value: boolean) => {
|
||||
onParameterChange('ebookOptions', {
|
||||
embedAllFonts: parameters.ebookOptions?.embedAllFonts ?? false,
|
||||
includeTableOfContents: parameters.ebookOptions?.includeTableOfContents ?? false,
|
||||
includePageNumbers: parameters.ebookOptions?.includePageNumbers ?? false,
|
||||
optimizeForEbook: value,
|
||||
});
|
||||
};
|
||||
|
||||
// Initialize ebookOptions if not present
|
||||
const ebookOptions = parameters.ebookOptions || {
|
||||
embedAllFonts: false,
|
||||
includeTableOfContents: false,
|
||||
includePageNumbers: false,
|
||||
optimizeForEbook: false,
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack gap="sm">
|
||||
<Checkbox
|
||||
label={t("convert.ebookOptions.embedAllFonts", "Embed all fonts")}
|
||||
description={t("convert.ebookOptions.embedAllFontsDesc", "Embed all fonts from the eBook into the generated PDF")}
|
||||
checked={ebookOptions.embedAllFonts}
|
||||
onChange={(event) => handleEmbedAllFontsChange(event.currentTarget.checked)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
<Checkbox
|
||||
label={t("convert.ebookOptions.includeTableOfContents", "Include table of contents")}
|
||||
description={t("convert.ebookOptions.includeTableOfContentsDesc", "Add a generated table of contents to the resulting PDF")}
|
||||
checked={ebookOptions.includeTableOfContents}
|
||||
onChange={(event) => handleIncludeTableOfContentsChange(event.currentTarget.checked)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
<Checkbox
|
||||
label={t("convert.ebookOptions.includePageNumbers", "Include page numbers")}
|
||||
description={t("convert.ebookOptions.includePageNumbersDesc", "Add page numbers to the generated PDF")}
|
||||
checked={ebookOptions.includePageNumbers}
|
||||
onChange={(event) => handleIncludePageNumbersChange(event.currentTarget.checked)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
<Checkbox
|
||||
label={t("convert.ebookOptions.optimizeForEbookPdf", "Optimize for ebook readers")}
|
||||
description={t("convert.ebookOptions.optimizeForEbookPdfDesc", "Optimize the PDF for eBook reading (smaller file size, better rendering on eInk devices)")}
|
||||
checked={ebookOptions.optimizeForEbook}
|
||||
onChange={(event) => handleOptimizeForEbookChange(event.currentTarget.checked)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
export default ConvertFromEbookSettings;
|
||||
@@ -17,6 +17,9 @@ import ConvertFromEmailSettings from "@app/components/tools/convert/ConvertFromE
|
||||
import ConvertFromCbzSettings from "@app/components/tools/convert/ConvertFromCbzSettings";
|
||||
import ConvertToCbzSettings from "@app/components/tools/convert/ConvertToCbzSettings";
|
||||
import ConvertToPdfaSettings from "@app/components/tools/convert/ConvertToPdfaSettings";
|
||||
import ConvertFromCbrSettings from "@app/components/tools/convert/ConvertFromCbrSettings";
|
||||
import ConvertToCbrSettings from "@app/components/tools/convert/ConvertToCbrSettings";
|
||||
import ConvertFromEbookSettings from "@app/components/tools/convert/ConvertFromEbookSettings";
|
||||
import { ConvertParameters } from "@app/hooks/tools/convert/useConvertParameters";
|
||||
import {
|
||||
FROM_FORMAT_OPTIONS,
|
||||
@@ -142,12 +145,24 @@ const ConvertSettings = ({
|
||||
onParameterChange('pdfaOptions', {
|
||||
outputFormat: 'pdfa-1',
|
||||
});
|
||||
onParameterChange('cbrOptions', {
|
||||
optimizeForEbook: false,
|
||||
});
|
||||
onParameterChange('pdfToCbrOptions', {
|
||||
dpi: 150,
|
||||
});
|
||||
onParameterChange('cbzOptions', {
|
||||
optimizeForEbook: false,
|
||||
});
|
||||
onParameterChange('cbzOutputOptions', {
|
||||
dpi: 150,
|
||||
});
|
||||
onParameterChange('ebookOptions', {
|
||||
embedAllFonts: false,
|
||||
includeTableOfContents: false,
|
||||
includePageNumbers: false,
|
||||
optimizeForEbook: false,
|
||||
});
|
||||
onParameterChange('isSmartDetection', false);
|
||||
onParameterChange('smartDetectionType', 'none');
|
||||
};
|
||||
@@ -210,6 +225,12 @@ const ConvertSettings = ({
|
||||
onParameterChange('pdfaOptions', {
|
||||
outputFormat: 'pdfa-1',
|
||||
});
|
||||
onParameterChange('cbrOptions', {
|
||||
optimizeForEbook: false,
|
||||
});
|
||||
onParameterChange('pdfToCbrOptions', {
|
||||
dpi: 150,
|
||||
});
|
||||
onParameterChange('cbzOptions', {
|
||||
optimizeForEbook: false,
|
||||
});
|
||||
@@ -366,6 +387,42 @@ const ConvertSettings = ({
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* eBook to PDF options */}
|
||||
{['epub', 'mobi', 'azw3', 'fb2'].includes(parameters.fromExtension) && parameters.toExtension === 'pdf' && (
|
||||
<>
|
||||
<Divider />
|
||||
<ConvertFromEbookSettings
|
||||
parameters={parameters}
|
||||
onParameterChange={onParameterChange}
|
||||
disabled={disabled}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* CBR to PDF options */}
|
||||
{parameters.fromExtension === 'cbr' && parameters.toExtension === 'pdf' && (
|
||||
<>
|
||||
<Divider />
|
||||
<ConvertFromCbrSettings
|
||||
parameters={parameters}
|
||||
onParameterChange={onParameterChange}
|
||||
disabled={disabled}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* PDF to CBR options */}
|
||||
{parameters.fromExtension === 'pdf' && parameters.toExtension === 'cbr' && (
|
||||
<>
|
||||
<Divider />
|
||||
<ConvertToCbrSettings
|
||||
parameters={parameters}
|
||||
onParameterChange={onParameterChange}
|
||||
disabled={disabled}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Stack, Text, NumberInput } from "@mantine/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ConvertParameters } from "@app/hooks/tools/convert/useConvertParameters";
|
||||
|
||||
interface ConvertToCbrSettingsProps {
|
||||
parameters: ConvertParameters;
|
||||
onParameterChange: <K extends keyof ConvertParameters>(key: K, value: ConvertParameters[K]) => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
const ConvertToCbrSettings = ({
|
||||
parameters,
|
||||
onParameterChange,
|
||||
disabled = false
|
||||
}: ConvertToCbrSettingsProps) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Stack gap="sm" data-testid="cbr-output-settings">
|
||||
<Text size="sm" fw={500}>{t("convert.cbrOutputOptions", "PDF to CBR Options")}:</Text>
|
||||
|
||||
<NumberInput
|
||||
data-testid="cbr-dpi-input"
|
||||
label={t("convert.cbrDpi", "DPI for image rendering")}
|
||||
value={parameters.pdfToCbrOptions.dpi}
|
||||
onChange={(val) =>
|
||||
typeof val === 'number' &&
|
||||
onParameterChange('pdfToCbrOptions', { ...parameters.pdfToCbrOptions, dpi: val })
|
||||
}
|
||||
min={72}
|
||||
max={600}
|
||||
step={50}
|
||||
disabled={disabled}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
export default ConvertToCbrSettings;
|
||||
@@ -22,7 +22,8 @@ const ConvertToPdfaSettings = ({
|
||||
|
||||
const pdfaFormatOptions = [
|
||||
{ value: 'pdfa-1', label: 'PDF/A-1b' },
|
||||
{ value: 'pdfa', label: 'PDF/A-2b' }
|
||||
{ value: 'pdfa', label: 'PDF/A-2b' },
|
||||
{ value: 'pdfa-3', label: 'PDF/A-3b' }
|
||||
];
|
||||
|
||||
return (
|
||||
@@ -50,7 +51,7 @@ const ConvertToPdfaSettings = ({
|
||||
data-testid="pdfa-output-format-select"
|
||||
/>
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("convert.pdfaNote", "PDF/A-1b is more compatible, PDF/A-2b supports more features.")}
|
||||
{t("convert.pdfaNote", "PDF/A-1b is more compatible, PDF/A-2b supports more features, PDF/A-3b supports embedded files.")}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Stack>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useMemo, useState, useEffect } from "react";
|
||||
import { Stack, Text, Box, Group, ActionIcon, Center, Alert } from "@mantine/core";
|
||||
import { Stack, Text, Box, Group, ActionIcon, Center, Alert, Checkbox } from "@mantine/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import RestartAltIcon from "@mui/icons-material/RestartAlt";
|
||||
import { CropParametersHook } from "@app/hooks/tools/crop/useCropParameters";
|
||||
@@ -151,69 +151,81 @@ const CropSettings = ({ parameters, disabled = false }: CropSettingsProps) => {
|
||||
|
||||
return (
|
||||
<Stack gap="md" data-tour="crop-settings">
|
||||
{/* PDF Preview with Crop Selector */}
|
||||
<Stack gap="xs">
|
||||
<Group justify="space-between" align="center">
|
||||
<Text size="sm" fw={500}>
|
||||
{t("crop.preview.title", "Crop Area Selection")}
|
||||
</Text>
|
||||
<ActionIcon
|
||||
variant="outline"
|
||||
onClick={handleReset}
|
||||
disabled={disabled || isFullCrop}
|
||||
title={t("crop.reset", "Reset to full PDF")}
|
||||
aria-label={t("crop.reset", "Reset to full PDF")}
|
||||
>
|
||||
<RestartAltIcon style={{ fontSize: '1rem' }} />
|
||||
</ActionIcon>
|
||||
</Group>
|
||||
|
||||
<Center>
|
||||
<Box
|
||||
style={{
|
||||
width: CONTAINER_SIZE,
|
||||
height: CONTAINER_SIZE,
|
||||
border: '1px solid var(--mantine-color-gray-3)',
|
||||
borderRadius: '8px',
|
||||
backgroundColor: 'var(--mantine-color-gray-0)',
|
||||
overflow: 'hidden',
|
||||
position: 'relative'
|
||||
}}
|
||||
>
|
||||
<CropAreaSelector
|
||||
pdfBounds={pdfBounds}
|
||||
cropArea={cropArea}
|
||||
onCropAreaChange={handleCropAreaChange}
|
||||
disabled={disabled}
|
||||
>
|
||||
<DocumentThumbnail
|
||||
file={selectedStub}
|
||||
thumbnail={thumbnail}
|
||||
style={{
|
||||
width: pdfBounds.thumbnailWidth,
|
||||
height: pdfBounds.thumbnailHeight,
|
||||
position: 'absolute',
|
||||
left: pdfBounds.offsetX,
|
||||
top: pdfBounds.offsetY
|
||||
}}
|
||||
/>
|
||||
</CropAreaSelector>
|
||||
</Box>
|
||||
</Center>
|
||||
|
||||
</Stack>
|
||||
|
||||
{/* Manual Coordinate Input */}
|
||||
<CropCoordinateInputs
|
||||
cropArea={cropArea}
|
||||
onCoordinateChange={handleCoordinateChange}
|
||||
{/* Auto-Crop Checkbox */}
|
||||
<Checkbox
|
||||
label={t("crop.autoCrop", "Auto-crop whitespace")}
|
||||
checked={parameters.parameters.autoCrop}
|
||||
onChange={(e) => parameters.updateParameter('autoCrop', e.currentTarget.checked)}
|
||||
disabled={disabled}
|
||||
pdfBounds={pdfBounds}
|
||||
showAutomationInfo={false}
|
||||
/>
|
||||
|
||||
{/* Validation Alert */}
|
||||
{!isCropValid && (
|
||||
{/* PDF Preview with Crop Selector - Only show when autoCrop is false */}
|
||||
{!parameters.parameters.autoCrop && (
|
||||
<Stack gap="xs">
|
||||
<Group justify="space-between" align="center">
|
||||
<Text size="sm" fw={500}>
|
||||
{t("crop.preview.title", "Crop Area Selection")}
|
||||
</Text>
|
||||
<ActionIcon
|
||||
variant="outline"
|
||||
onClick={handleReset}
|
||||
disabled={disabled || isFullCrop}
|
||||
title={t("crop.reset", "Reset to full PDF")}
|
||||
aria-label={t("crop.reset", "Reset to full PDF")}
|
||||
>
|
||||
<RestartAltIcon style={{ fontSize: '1rem' }} />
|
||||
</ActionIcon>
|
||||
</Group>
|
||||
|
||||
<Center>
|
||||
<Box
|
||||
style={{
|
||||
width: CONTAINER_SIZE,
|
||||
height: CONTAINER_SIZE,
|
||||
border: '1px solid var(--mantine-color-gray-3)',
|
||||
borderRadius: '8px',
|
||||
backgroundColor: 'var(--mantine-color-gray-0)',
|
||||
overflow: 'hidden',
|
||||
position: 'relative'
|
||||
}}
|
||||
>
|
||||
<CropAreaSelector
|
||||
pdfBounds={pdfBounds}
|
||||
cropArea={cropArea}
|
||||
onCropAreaChange={handleCropAreaChange}
|
||||
disabled={disabled}
|
||||
>
|
||||
<DocumentThumbnail
|
||||
file={selectedStub}
|
||||
thumbnail={thumbnail}
|
||||
style={{
|
||||
width: pdfBounds.thumbnailWidth,
|
||||
height: pdfBounds.thumbnailHeight,
|
||||
position: 'absolute',
|
||||
left: pdfBounds.offsetX,
|
||||
top: pdfBounds.offsetY
|
||||
}}
|
||||
/>
|
||||
</CropAreaSelector>
|
||||
</Box>
|
||||
</Center>
|
||||
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
{/* Manual Coordinate Input - Only show when autoCrop is false */}
|
||||
{!parameters.parameters.autoCrop && (
|
||||
<CropCoordinateInputs
|
||||
cropArea={cropArea}
|
||||
onCoordinateChange={handleCoordinateChange}
|
||||
disabled={disabled}
|
||||
pdfBounds={pdfBounds}
|
||||
showAutomationInfo={false}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Validation Alert - Only show when autoCrop is false */}
|
||||
{!parameters.parameters.autoCrop && !isCropValid && (
|
||||
<Alert color="red" variant="light">
|
||||
<Text size="xs">
|
||||
{t("crop.error.invalidArea", "Crop area extends beyond PDF boundaries")}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Stack, Text, Checkbox } from "@mantine/core";
|
||||
import { Stack, Text, Checkbox, NumberInput } from "@mantine/core";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { FlattenParameters } from "@app/hooks/tools/flatten/useFlattenParameters";
|
||||
|
||||
@@ -28,6 +28,20 @@ const FlattenSettings = ({ parameters, onParameterChange, disabled = false }: Fl
|
||||
}
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
{!parameters.flattenOnlyForms && (
|
||||
<NumberInput
|
||||
label={t('flatten.renderDpi.label', 'Rendering DPI')}
|
||||
description={t('flatten.renderDpi.help', 'Leave blank to use the system default. Higher DPI sharpens output but increases processing time and file size.')}
|
||||
placeholder={t('flatten.renderDpi.placeholder', 'e.g. 150')}
|
||||
value={parameters.renderDpi ?? undefined}
|
||||
onChange={(value) => onParameterChange('renderDpi', value != null && value !== '' ? Number(value) : undefined)}
|
||||
disabled={disabled}
|
||||
min={72}
|
||||
max={2400}
|
||||
step={50}
|
||||
/>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React from 'react';
|
||||
import { Accordion, Stack, Text } from '@mantine/core';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { PdfOtherInfo } from '@app/types/getPdfInfo';
|
||||
import type { PdfOtherInfo, PdfAttachmentInfo, PdfEmbeddedFileInfo } from '@app/types/getPdfInfo';
|
||||
import SectionBlock from '@app/components/tools/getPdfInfo/shared/SectionBlock';
|
||||
import ScrollableCodeBlock from '@app/components/tools/getPdfInfo/shared/ScrollableCodeBlock';
|
||||
import { pdfInfoAccordionStyles } from '@app/components/tools/getPdfInfo/shared/accordionStyles';
|
||||
@@ -11,6 +11,42 @@ interface OtherSectionProps {
|
||||
other?: PdfOtherInfo | null;
|
||||
}
|
||||
|
||||
const renderAttachmentsList = (attachments: PdfAttachmentInfo[] | undefined, emptyText: string) => {
|
||||
if (!attachments || attachments.length === 0) return <Text size="sm" c="dimmed">{emptyText}</Text>;
|
||||
return (
|
||||
<Stack gap={4}>
|
||||
{attachments.map((attachment, idx) => (
|
||||
<div key={idx} style={{ wordBreak: 'break-word', overflowWrap: 'break-word' }}>
|
||||
<Text size="sm" c="dimmed">
|
||||
<strong>{attachment.Name || 'Unnamed attachment'}</strong>
|
||||
{attachment.Description && ` - ${attachment.Description}`}
|
||||
{attachment.FileSize != null && ` (${attachment.FileSize} bytes)`}
|
||||
</Text>
|
||||
</div>
|
||||
))}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
const renderEmbeddedFilesList = (embeddedFiles: PdfEmbeddedFileInfo[] | undefined, emptyText: string) => {
|
||||
if (!embeddedFiles || embeddedFiles.length === 0) return <Text size="sm" c="dimmed">{emptyText}</Text>;
|
||||
return (
|
||||
<Stack gap={4}>
|
||||
{embeddedFiles.map((file, idx) => (
|
||||
<div key={idx} style={{ wordBreak: 'break-word', overflowWrap: 'break-word' }}>
|
||||
<Text size="sm" c="dimmed">
|
||||
<strong>{file.Name || 'Unnamed file'}</strong>
|
||||
{file.FileSize != null && ` (${file.FileSize} bytes)`}
|
||||
{file.MimeType && ` - ${file.MimeType}`}
|
||||
{file.CreationDate && ` - Created: ${file.CreationDate}`}
|
||||
{file.ModificationDate && ` - Modified: ${file.ModificationDate}`}
|
||||
</Text>
|
||||
</div>
|
||||
))}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
const renderList = (arr: unknown[] | undefined, emptyText: string) => {
|
||||
if (!arr || arr.length === 0) return <Text size="sm" c="dimmed">{emptyText}</Text>;
|
||||
return (
|
||||
@@ -37,11 +73,11 @@ const OtherSection: React.FC<OtherSectionProps> = ({ anchorId, other }) => {
|
||||
<Stack gap="sm">
|
||||
<Stack gap={6}>
|
||||
<Text fw={600} size="sm">{t('getPdfInfo.other.attachments', 'Attachments')}</Text>
|
||||
{renderList(other?.Attachments, noneDetected)}
|
||||
{renderAttachmentsList(other?.Attachments, noneDetected)}
|
||||
</Stack>
|
||||
<Stack gap={6}>
|
||||
<Text fw={600} size="sm">{t('getPdfInfo.other.embeddedFiles', 'Embedded Files')}</Text>
|
||||
{renderList(other?.EmbeddedFiles, noneDetected)}
|
||||
{renderEmbeddedFilesList(other?.EmbeddedFiles, noneDetected)}
|
||||
</Stack>
|
||||
<Stack gap={6}>
|
||||
<Text fw={600} size="sm">{t('getPdfInfo.other.javaScript', 'JavaScript')}</Text>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React from 'react';
|
||||
import { Accordion, Stack, Text } from '@mantine/core';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { PdfPerPageInfo, PdfPageInfo, PdfFontInfo } from '@app/types/getPdfInfo';
|
||||
import type { PdfPerPageInfo, PdfPageInfo, PdfFontInfo, PdfImageInfo } from '@app/types/getPdfInfo';
|
||||
import SectionBlock from '@app/components/tools/getPdfInfo/shared/SectionBlock';
|
||||
import KeyValueList from '@app/components/tools/getPdfInfo/shared/KeyValueList';
|
||||
import { pdfInfoAccordionStyles } from '@app/components/tools/getPdfInfo/shared/accordionStyles';
|
||||
@@ -11,6 +11,23 @@ interface PerPageSectionProps {
|
||||
perPage?: PdfPerPageInfo | null;
|
||||
}
|
||||
|
||||
const renderImagesList = (images: PdfImageInfo[] | undefined, emptyText: string) => {
|
||||
if (!images || images.length === 0) return <Text size="sm" c="dimmed">{emptyText}</Text>;
|
||||
return (
|
||||
<Stack gap={4}>
|
||||
{images.map((image, idx) => (
|
||||
<div key={idx} style={{ wordBreak: 'break-word', overflowWrap: 'break-word' }}>
|
||||
<Text size="sm" c="dimmed">
|
||||
{image.Name ? `${image.Name} ` : 'Image '}
|
||||
({image.Width}×{image.Height}px
|
||||
{image.ColorSpace ? `, ${image.ColorSpace}` : ''})
|
||||
</Text>
|
||||
</div>
|
||||
))}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
const renderList = (arr: unknown[] | undefined, emptyText: string) => {
|
||||
if (!arr || arr.length === 0) return <Text size="sm" c="dimmed">{emptyText}</Text>;
|
||||
return (
|
||||
@@ -84,7 +101,7 @@ const PerPageSection: React.FC<PerPageSectionProps> = ({ anchorId, perPage }) =>
|
||||
)}
|
||||
<Stack gap={4}>
|
||||
<Text fw={600} size="sm">{t('getPdfInfo.perPage.images', 'Images')}</Text>
|
||||
{renderList(pageInfo?.Images, noneDetected)}
|
||||
{renderImagesList(pageInfo?.Images, noneDetected)}
|
||||
</Stack>
|
||||
<Stack gap={4}>
|
||||
<Text fw={600} size="sm">{t('getPdfInfo.perPage.links', 'Links')}</Text>
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import React, { useMemo, useState } from 'react';
|
||||
import {
|
||||
Accordion,
|
||||
Badge,
|
||||
Box,
|
||||
Code,
|
||||
Collapse,
|
||||
Divider,
|
||||
Flex,
|
||||
Group,
|
||||
List,
|
||||
Paper,
|
||||
@@ -29,10 +30,14 @@ import {
|
||||
getFontStatusColor,
|
||||
getFontStatusDescription,
|
||||
} from '@app/tools/pdfTextEditor/fontAnalysis';
|
||||
import LocalIcon from '@app/components/shared/LocalIcon';
|
||||
import { Tooltip as CustomTooltip } from '@app/components/shared/Tooltip';
|
||||
|
||||
interface FontStatusPanelProps {
|
||||
document: PdfJsonDocument | null;
|
||||
pageIndex?: number;
|
||||
isCollapsed?: boolean;
|
||||
onCollapsedChange?: (collapsed: boolean) => void;
|
||||
}
|
||||
|
||||
const FontStatusBadge = ({ analysis }: { analysis: FontAnalysis }) => {
|
||||
@@ -74,25 +79,31 @@ const FontDetailItem = ({ analysis }: { analysis: FontAnalysis }) => {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
|
||||
return (
|
||||
<Paper withBorder p="xs" style={{ cursor: 'pointer' }} onClick={() => setExpanded(!expanded)}>
|
||||
<Paper withBorder px="sm" py="md" style={{ cursor: 'pointer' }} onClick={() => setExpanded(!expanded)}>
|
||||
<Stack gap={4}>
|
||||
<Group justify="space-between">
|
||||
<Group gap={4}>
|
||||
<FontDownloadIcon sx={{ fontSize: 16 }} />
|
||||
<Text size="xs" fw={500} lineClamp={1}>
|
||||
{analysis.baseName}
|
||||
</Text>
|
||||
<Flex align="center" justify="space-between" wrap="nowrap">
|
||||
<Group gap={4} wrap="nowrap" style={{ flex: 1, minWidth: 0 }}>
|
||||
<FontDownloadIcon sx={{ fontSize: 16, flexShrink: 0 }} />
|
||||
<CustomTooltip
|
||||
sidebarTooltip={false}
|
||||
content={analysis.baseName}
|
||||
position="top"
|
||||
>
|
||||
<Text size="xs" fw={500} lineClamp={1} style={{ flex: 1, minWidth: 0 }}>
|
||||
{analysis.baseName}
|
||||
</Text>
|
||||
</CustomTooltip>
|
||||
{analysis.isSubset && (
|
||||
<Badge size="xs" color="gray" variant="outline">
|
||||
<Badge size="xs" color="gray" variant="outline" style={{ flexShrink: 0 }}>
|
||||
subset
|
||||
</Badge>
|
||||
)}
|
||||
</Group>
|
||||
<Group gap={4}>
|
||||
<Group gap={4} wrap="nowrap" style={{ flexShrink: 0 }}>
|
||||
<FontStatusBadge analysis={analysis} />
|
||||
{expanded ? <ExpandLessIcon sx={{ fontSize: 16 }} /> : <ExpandMoreIcon sx={{ fontSize: 16 }} />}
|
||||
</Group>
|
||||
</Group>
|
||||
</Flex>
|
||||
|
||||
<Collapse in={expanded}>
|
||||
<Stack gap={4} mt={4}>
|
||||
@@ -165,7 +176,12 @@ const FontDetailItem = ({ analysis }: { analysis: FontAnalysis }) => {
|
||||
);
|
||||
};
|
||||
|
||||
const FontStatusPanel: React.FC<FontStatusPanelProps> = ({ document, pageIndex }) => {
|
||||
const FontStatusPanel: React.FC<FontStatusPanelProps> = ({
|
||||
document,
|
||||
pageIndex,
|
||||
isCollapsed = false,
|
||||
onCollapsedChange
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const fontAnalysis: DocumentFontAnalysis = useMemo(
|
||||
@@ -175,16 +191,6 @@ const FontStatusPanel: React.FC<FontStatusPanelProps> = ({ document, pageIndex }
|
||||
|
||||
const { canReproducePerfectly, hasWarnings, summary, fonts } = fontAnalysis;
|
||||
|
||||
const statusIcon = useMemo(() => {
|
||||
if (canReproducePerfectly) {
|
||||
return <CheckCircleIcon sx={{ fontSize: 16 }} />;
|
||||
}
|
||||
if (hasWarnings) {
|
||||
return <WarningIcon sx={{ fontSize: 16 }} />;
|
||||
}
|
||||
return <InfoIcon sx={{ fontSize: 16 }} />;
|
||||
}, [canReproducePerfectly, hasWarnings]);
|
||||
|
||||
// Early return AFTER all hooks are declared
|
||||
if (!document || fontAnalysis.fonts.length === 0) {
|
||||
return null;
|
||||
@@ -197,37 +203,46 @@ const FontStatusPanel: React.FC<FontStatusPanelProps> = ({ document, pageIndex }
|
||||
: t('pdfTextEditor.fontAnalysis.allFonts', 'All fonts');
|
||||
|
||||
return (
|
||||
<Accordion variant="contained" defaultValue={hasWarnings ? 'fonts' : undefined}>
|
||||
<Accordion.Item value="fonts">
|
||||
<Accordion.Control>
|
||||
<Group gap="xs" wrap="wrap" style={{ flex: 1 }}>
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
{statusIcon}
|
||||
<Text size="sm" fw={500}>
|
||||
{pageLabel}
|
||||
</Text>
|
||||
<Badge size="xs" color={statusColor} variant="dot">
|
||||
{fonts.length}
|
||||
</Badge>
|
||||
</Group>
|
||||
<div>
|
||||
<div
|
||||
style={{
|
||||
padding: '0.5rem',
|
||||
opacity: isCollapsed ? 0.8 : 1,
|
||||
color: isCollapsed ? 'var(--mantine-color-dimmed)' : 'inherit',
|
||||
transition: 'opacity 0.2s ease, color 0.2s ease'
|
||||
}}
|
||||
>
|
||||
{/* Header - matches ToolStep style */}
|
||||
<Flex
|
||||
align="center"
|
||||
justify="space-between"
|
||||
mb={isCollapsed ? 0 : 'sm'}
|
||||
style={{ cursor: 'pointer' }}
|
||||
onClick={() => onCollapsedChange?.(!isCollapsed)}
|
||||
>
|
||||
<Flex align="center" gap="xs">
|
||||
<Text fw={500} size="sm">
|
||||
{pageLabel}
|
||||
</Text>
|
||||
<Badge size="xs" color={statusColor} variant="dot">
|
||||
{fonts.length}
|
||||
</Badge>
|
||||
</Flex>
|
||||
|
||||
{/* Warning badges BEFORE expansion */}
|
||||
<Group gap={4} wrap="wrap">
|
||||
{summary.systemFallback > 0 && (
|
||||
<Badge size="xs" color="yellow" variant="filled" leftSection={<WarningIcon sx={{ fontSize: 12 }} />}>
|
||||
{summary.systemFallback} {t('pdfTextEditor.fontAnalysis.fallback', 'fallback')}
|
||||
</Badge>
|
||||
)}
|
||||
{summary.missing > 0 && (
|
||||
<Badge size="xs" color="red" variant="filled" leftSection={<ErrorIcon sx={{ fontSize: 12 }} />}>
|
||||
{summary.missing} {t('pdfTextEditor.fontAnalysis.missing', 'missing')}
|
||||
</Badge>
|
||||
)}
|
||||
</Group>
|
||||
</Group>
|
||||
</Accordion.Control>
|
||||
<Accordion.Panel>
|
||||
<Stack gap="xs">
|
||||
{isCollapsed ? (
|
||||
<LocalIcon icon="chevron-right-rounded" width="1.2rem" height="1.2rem" style={{
|
||||
color: 'var(--mantine-color-dimmed)'
|
||||
}} />
|
||||
) : (
|
||||
<LocalIcon icon="expand-more-rounded" width="1.2rem" height="1.2rem" style={{
|
||||
color: 'var(--mantine-color-dimmed)'
|
||||
}} />
|
||||
)}
|
||||
</Flex>
|
||||
|
||||
{/* Content */}
|
||||
{!isCollapsed && (
|
||||
<Stack gap="xs" pl="sm">
|
||||
{/* Overall Status Message */}
|
||||
<Text size="xs" c="dimmed">
|
||||
{canReproducePerfectly
|
||||
@@ -277,9 +292,10 @@ const FontStatusPanel: React.FC<FontStatusPanelProps> = ({ document, pageIndex }
|
||||
))}
|
||||
</Stack>
|
||||
</Stack>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
</Accordion>
|
||||
)}
|
||||
</div>
|
||||
<Divider style={{ color: '#E2E8F0', marginLeft: '1rem', marginRight: '-0.5rem' }} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,340 @@
|
||||
import React, { useCallback, useMemo, useState } from 'react';
|
||||
import {
|
||||
ActionIcon,
|
||||
Badge,
|
||||
Button,
|
||||
Divider,
|
||||
Flex,
|
||||
Group,
|
||||
Menu,
|
||||
Modal,
|
||||
ScrollArea,
|
||||
SegmentedControl,
|
||||
Stack,
|
||||
Switch,
|
||||
Text,
|
||||
} from '@mantine/core';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import AutorenewIcon from '@mui/icons-material/Autorenew';
|
||||
import InfoOutlinedIcon from '@mui/icons-material/InfoOutlined';
|
||||
import MoreHorizIcon from '@mui/icons-material/MoreHoriz';
|
||||
import FileDownloadIcon from '@mui/icons-material/FileDownloadOutlined';
|
||||
|
||||
import { PdfTextEditorViewData, TextGroup } from '@app/tools/pdfTextEditor/pdfTextEditorTypes';
|
||||
import { pageDimensions } from '@app/tools/pdfTextEditor/pdfTextEditorUtils';
|
||||
import FontStatusPanel from '@app/components/tools/pdfTextEditor/FontStatusPanel';
|
||||
import ToolStep from '@app/components/tools/shared/ToolStep';
|
||||
import { usePdfTextEditorTips } from '@app/components/tooltips/usePdfTextEditorTips';
|
||||
import { Tooltip } from '@app/components/shared/Tooltip';
|
||||
import LocalIcon from '@app/components/shared/LocalIcon';
|
||||
|
||||
type GroupingMode = 'auto' | 'paragraph' | 'singleLine';
|
||||
|
||||
interface PdfTextEditorSidebarProps {
|
||||
data: PdfTextEditorViewData;
|
||||
}
|
||||
|
||||
// Analyze page content to determine if it's paragraph-heavy
|
||||
const analyzePageContentType = (
|
||||
groups: TextGroup[],
|
||||
pageWidth: number,
|
||||
): boolean => {
|
||||
if (groups.length < 3) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const widths = groups.map((g) => Math.max(g.bounds.right - g.bounds.left, 1));
|
||||
const avgWidth = widths.reduce((sum, w) => sum + w, 0) / widths.length;
|
||||
const stdDev = Math.sqrt(
|
||||
widths.reduce((sum, w) => sum + Math.pow(w - avgWidth, 2), 0) / widths.length,
|
||||
);
|
||||
const coefficientOfVariation = avgWidth > 0 ? stdDev / avgWidth : 0;
|
||||
const fullWidthRatio = widths.filter((w) => w > pageWidth * 0.65).length / widths.length;
|
||||
|
||||
const criterion1 = groups.length >= 3;
|
||||
const criterion2 = avgWidth > pageWidth * 0.3;
|
||||
const criterion3 = coefficientOfVariation > 0.5 || fullWidthRatio > 0.6;
|
||||
|
||||
return criterion1 && criterion2 && criterion3;
|
||||
};
|
||||
|
||||
const PdfTextEditorSidebar = ({ data }: PdfTextEditorSidebarProps) => {
|
||||
const { t } = useTranslation();
|
||||
const [pendingModeChange, setPendingModeChange] = useState<GroupingMode | null>(null);
|
||||
const [advancedSettingsCollapsed, setAdvancedSettingsCollapsed] = useState(false);
|
||||
const [fontsCollapsed, setFontsCollapsed] = useState(false);
|
||||
const pdfTextEditorTips = usePdfTextEditorTips();
|
||||
|
||||
const {
|
||||
document: pdfDocument,
|
||||
groupsByPage,
|
||||
hasDocument,
|
||||
hasChanges,
|
||||
fileName,
|
||||
isGeneratingPdf,
|
||||
isSavingToWorkbench,
|
||||
isConverting,
|
||||
forceSingleTextElement,
|
||||
groupingMode: externalGroupingMode,
|
||||
autoScaleText,
|
||||
selectedPage,
|
||||
onReset,
|
||||
onGeneratePdf,
|
||||
onSaveToWorkbench,
|
||||
onForceSingleTextElementChange,
|
||||
onGroupingModeChange,
|
||||
onAutoScaleTextChange,
|
||||
} = data;
|
||||
|
||||
// Get page dimensions
|
||||
const pages = pdfDocument?.pages ?? [];
|
||||
const currentPage = pages[selectedPage] ?? null;
|
||||
const { width: pageWidth } = pageDimensions(currentPage);
|
||||
const pageGroups = groupsByPage[selectedPage] ?? [];
|
||||
|
||||
// Detect if current page contains paragraph-heavy content
|
||||
const isParagraphPage = useMemo(() => {
|
||||
return analyzePageContentType(pageGroups, pageWidth);
|
||||
}, [pageGroups, pageWidth]);
|
||||
|
||||
const handleModeChangeRequest = useCallback((newMode: GroupingMode) => {
|
||||
if (hasChanges && newMode !== externalGroupingMode) {
|
||||
setPendingModeChange(newMode);
|
||||
} else {
|
||||
onGroupingModeChange(newMode);
|
||||
}
|
||||
}, [hasChanges, externalGroupingMode, onGroupingModeChange]);
|
||||
|
||||
const handleConfirmModeChange = useCallback(() => {
|
||||
if (pendingModeChange) {
|
||||
onGroupingModeChange(pendingModeChange);
|
||||
setPendingModeChange(null);
|
||||
}
|
||||
}, [pendingModeChange, onGroupingModeChange]);
|
||||
|
||||
const handleCancelModeChange = useCallback(() => {
|
||||
setPendingModeChange(null);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack style={{ height: '100%', display: 'flex' }} gap={0}>
|
||||
<ScrollArea style={{ flex: 1 }} offsetScrollbars>
|
||||
<Stack gap="md">
|
||||
<Stack gap="xs" pl="md" pr={0} pt="md">
|
||||
{/* Title row with ALPHA badge and info tooltip */}
|
||||
<Flex align="center" justify="space-between">
|
||||
<Flex align="center" gap="xs">
|
||||
<Text fw={600} size="sm">
|
||||
{t('pdfTextEditor.title', 'PDF Text Editor')}
|
||||
</Text>
|
||||
<Badge size="xs" variant="light" color="orange">
|
||||
{t('toolPanel.alpha', 'Alpha')}
|
||||
</Badge>
|
||||
</Flex>
|
||||
<Tooltip
|
||||
sidebarTooltip={true}
|
||||
tips={pdfTextEditorTips.tips}
|
||||
header={pdfTextEditorTips.header}
|
||||
pinOnClick
|
||||
>
|
||||
<ActionIcon variant="subtle" color="blue" size="sm">
|
||||
<LocalIcon icon="info-outline-rounded" width="1.25rem" height="1.25rem" />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Flex>
|
||||
|
||||
{fileName && (
|
||||
<Text size="sm" c="dimmed">
|
||||
{t('pdfTextEditor.currentFile', 'Current file: {{name}}', { name: fileName })}
|
||||
</Text>
|
||||
)}
|
||||
</Stack>
|
||||
|
||||
<ToolStep
|
||||
title={t('pdfTextEditor.options.advanced.title', 'Advanced Settings')}
|
||||
isCollapsed={advancedSettingsCollapsed}
|
||||
onCollapsedClick={() => setAdvancedSettingsCollapsed(!advancedSettingsCollapsed)}
|
||||
>
|
||||
<Stack gap="md">
|
||||
<Divider />
|
||||
<Group justify="space-between" align="center">
|
||||
<Group gap={4} align="center" style={{ flex: 1, minWidth: 0 }}>
|
||||
<Tooltip
|
||||
sidebarTooltip={false}
|
||||
content={t(
|
||||
'pdfTextEditor.options.autoScaleText.description',
|
||||
'Automatically scales text horizontally to fit within its original bounding box when font rendering differs from PDF.'
|
||||
)}
|
||||
position="top"
|
||||
>
|
||||
<ActionIcon variant="subtle" color="gray" size="sm" style={{ flexShrink: 0 }}>
|
||||
<InfoOutlinedIcon fontSize="small" />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
<Text fw={500} size="sm" style={{ flex: 1 }}>
|
||||
{t('pdfTextEditor.options.autoScaleText.title', 'Auto-scale text to fit boxes')}
|
||||
</Text>
|
||||
</Group>
|
||||
<Switch
|
||||
size="md"
|
||||
checked={autoScaleText}
|
||||
onChange={(event) => onAutoScaleTextChange(event.currentTarget.checked)}
|
||||
/>
|
||||
</Group>
|
||||
|
||||
<Divider />
|
||||
|
||||
<Stack gap="xs">
|
||||
<Group gap={4} align="center">
|
||||
<Text fw={500} size="sm">
|
||||
{t('pdfTextEditor.options.groupingMode.title', 'Text Grouping Mode')}
|
||||
</Text>
|
||||
{externalGroupingMode === 'auto' && isParagraphPage && (
|
||||
<Badge size="xs" color="blue" variant="light" key={`para-${selectedPage}`}>
|
||||
{t('pdfTextEditor.pageType.paragraph', 'Paragraph page')}
|
||||
</Badge>
|
||||
)}
|
||||
{externalGroupingMode === 'auto' && !isParagraphPage && hasDocument && (
|
||||
<Badge size="xs" color="gray" variant="light" key={`sparse-${selectedPage}`}>
|
||||
{t('pdfTextEditor.pageType.sparse', 'Sparse text')}
|
||||
</Badge>
|
||||
)}
|
||||
</Group>
|
||||
<Text size="xs" c="dimmed">
|
||||
{externalGroupingMode === 'auto'
|
||||
? t(
|
||||
'pdfTextEditor.options.groupingMode.autoDescription',
|
||||
'Automatically detects page type and groups text appropriately.'
|
||||
)
|
||||
: externalGroupingMode === 'paragraph'
|
||||
? t(
|
||||
'pdfTextEditor.options.groupingMode.paragraphDescription',
|
||||
'Groups aligned lines into multi-line paragraph text boxes.'
|
||||
)
|
||||
: t(
|
||||
'pdfTextEditor.options.groupingMode.singleLineDescription',
|
||||
'Keeps each PDF text line as a separate text box.'
|
||||
)}
|
||||
</Text>
|
||||
<SegmentedControl
|
||||
value={externalGroupingMode}
|
||||
onChange={(value) => handleModeChangeRequest(value as GroupingMode)}
|
||||
data={[
|
||||
{ label: t('pdfTextEditor.groupingMode.auto', 'Auto'), value: 'auto' },
|
||||
{ label: t('pdfTextEditor.groupingMode.paragraph', 'Paragraph'), value: 'paragraph' },
|
||||
{ label: t('pdfTextEditor.groupingMode.singleLine', 'Single Line'), value: 'singleLine' },
|
||||
]}
|
||||
fullWidth
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
<Divider />
|
||||
|
||||
<Group justify="space-between" align="center">
|
||||
<Group gap={4} align="center" style={{ flex: 1, minWidth: 0 }}>
|
||||
<Tooltip
|
||||
sidebarTooltip={false}
|
||||
content={t(
|
||||
'pdfTextEditor.options.forceSingleElement.description',
|
||||
'When enabled, the editor exports each edited text box as one PDF text element to avoid overlapping glyphs or mixed fonts.'
|
||||
)}
|
||||
position="top"
|
||||
>
|
||||
<ActionIcon variant="subtle" color="gray" size="sm" style={{ flexShrink: 0 }}>
|
||||
<InfoOutlinedIcon fontSize="small" />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
<Text fw={500} size="sm" style={{ flex: 1 }}>
|
||||
{t('pdfTextEditor.options.forceSingleElement.title', 'Lock edited text to a single PDF element')}
|
||||
</Text>
|
||||
</Group>
|
||||
<Switch
|
||||
size="md"
|
||||
checked={forceSingleTextElement}
|
||||
onChange={(event) => onForceSingleTextElementChange(event.currentTarget.checked)}
|
||||
/>
|
||||
</Group>
|
||||
</Stack>
|
||||
</ToolStep>
|
||||
|
||||
{hasDocument && (
|
||||
<FontStatusPanel
|
||||
document={pdfDocument}
|
||||
pageIndex={selectedPage}
|
||||
isCollapsed={fontsCollapsed}
|
||||
onCollapsedChange={setFontsCollapsed}
|
||||
/>
|
||||
)}
|
||||
</Stack>
|
||||
</ScrollArea>
|
||||
|
||||
<Group gap="xs" wrap="nowrap" p="md">
|
||||
<Button
|
||||
variant="filled"
|
||||
onClick={onSaveToWorkbench}
|
||||
loading={isSavingToWorkbench}
|
||||
disabled={!hasDocument || !hasChanges || isConverting}
|
||||
style={{ flex: 1 }}
|
||||
>
|
||||
{t('pdfTextEditor.actions.applyChanges', 'Apply Changes')}
|
||||
</Button>
|
||||
<Menu position="bottom-end" withinPortal>
|
||||
<Menu.Target>
|
||||
<ActionIcon
|
||||
variant="default"
|
||||
size="lg"
|
||||
disabled={!hasDocument || isConverting}
|
||||
>
|
||||
<MoreHorizIcon fontSize="small" />
|
||||
</ActionIcon>
|
||||
</Menu.Target>
|
||||
<Menu.Dropdown>
|
||||
<Menu.Item
|
||||
leftSection={<FileDownloadIcon fontSize="small" />}
|
||||
onClick={() => onGeneratePdf()}
|
||||
disabled={!hasChanges || isGeneratingPdf}
|
||||
>
|
||||
{t('pdfTextEditor.actions.downloadCopy', 'Download Copy')}
|
||||
</Menu.Item>
|
||||
<Menu.Item
|
||||
leftSection={<AutorenewIcon fontSize="small" />}
|
||||
onClick={onReset}
|
||||
color="red"
|
||||
>
|
||||
{t('pdfTextEditor.actions.reset', 'Reset Changes')}
|
||||
</Menu.Item>
|
||||
</Menu.Dropdown>
|
||||
</Menu>
|
||||
</Group>
|
||||
</Stack>
|
||||
|
||||
{/* Mode Change Confirmation Modal */}
|
||||
<Modal
|
||||
opened={pendingModeChange !== null}
|
||||
onClose={handleCancelModeChange}
|
||||
title={t('pdfTextEditor.modeChange.title', 'Confirm Mode Change')}
|
||||
centered
|
||||
>
|
||||
<Stack gap="md">
|
||||
<Text>
|
||||
{t(
|
||||
'pdfTextEditor.modeChange.warning',
|
||||
'Changing the text grouping mode will reset all unsaved changes. Are you sure you want to continue?'
|
||||
)}
|
||||
</Text>
|
||||
<Group justify="flex-end" gap="sm">
|
||||
<Button variant="default" onClick={handleCancelModeChange}>
|
||||
{t('pdfTextEditor.modeChange.cancel', 'Cancel')}
|
||||
</Button>
|
||||
<Button color="red" onClick={handleConfirmModeChange}>
|
||||
{t('pdfTextEditor.modeChange.confirm', 'Reset and Change Mode')}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default PdfTextEditorSidebar;
|
||||
@@ -1,6 +1,5 @@
|
||||
import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
Accordion,
|
||||
ActionIcon,
|
||||
Alert,
|
||||
Badge,
|
||||
@@ -14,18 +13,12 @@ import {
|
||||
Pagination,
|
||||
Progress,
|
||||
ScrollArea,
|
||||
SegmentedControl,
|
||||
Stack,
|
||||
Switch,
|
||||
Text,
|
||||
Title,
|
||||
Tooltip,
|
||||
} from '@mantine/core';
|
||||
import { Dropzone } from '@mantine/dropzone';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import DescriptionIcon from '@mui/icons-material/DescriptionOutlined';
|
||||
import FileDownloadIcon from '@mui/icons-material/FileDownloadOutlined';
|
||||
import PictureAsPdfIcon from '@mui/icons-material/PictureAsPdfOutlined';
|
||||
import AutorenewIcon from '@mui/icons-material/Autorenew';
|
||||
import WarningAmberIcon from '@mui/icons-material/WarningAmber';
|
||||
import InfoOutlinedIcon from '@mui/icons-material/InfoOutlined';
|
||||
@@ -34,7 +27,6 @@ import MergeTypeIcon from '@mui/icons-material/MergeType';
|
||||
import CallSplitIcon from '@mui/icons-material/CallSplit';
|
||||
import MoreVertIcon from '@mui/icons-material/MoreVert';
|
||||
import UploadFileIcon from '@mui/icons-material/UploadFileOutlined';
|
||||
import SaveIcon from '@mui/icons-material/SaveOutlined';
|
||||
import { Rnd } from 'react-rnd';
|
||||
import NavigationWarningModal from '@app/components/shared/NavigationWarningModal';
|
||||
|
||||
@@ -46,7 +38,6 @@ import {
|
||||
TextGroup,
|
||||
} from '@app/tools/pdfTextEditor/pdfTextEditorTypes';
|
||||
import { getImageBounds, pageDimensions } from '@app/tools/pdfTextEditor/pdfTextEditorUtils';
|
||||
import FontStatusPanel from '@app/components/tools/pdfTextEditor/FontStatusPanel';
|
||||
|
||||
const MAX_RENDER_WIDTH = 820;
|
||||
const MIN_BOX_SIZE = 18;
|
||||
@@ -313,8 +304,6 @@ const analyzePageContentType = (groups: TextGroup[], pageWidth: number): boolean
|
||||
return isParagraphPage;
|
||||
};
|
||||
|
||||
type GroupingMode = 'auto' | 'paragraph' | 'singleLine';
|
||||
|
||||
const PdfTextEditorView = ({ data }: PdfTextEditorViewProps) => {
|
||||
const { t } = useTranslation();
|
||||
const { activeFiles } = useFileContext();
|
||||
@@ -327,9 +316,7 @@ const PdfTextEditorView = ({ data }: PdfTextEditorViewProps) => {
|
||||
const rndRefs = useRef<Map<string, any>>(new Map());
|
||||
const pendingDragUpdateRef = useRef<number | null>(null);
|
||||
const [fontFamilies, setFontFamilies] = useState<Map<string, string>>(new Map());
|
||||
const [autoScaleText, setAutoScaleText] = useState(true);
|
||||
const [textScales, setTextScales] = useState<Map<string, number>>(new Map());
|
||||
const [pendingModeChange, setPendingModeChange] = useState<GroupingMode | null>(null);
|
||||
const measurementKeyRef = useRef<string>('');
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
const editorRefs = useRef<Map<string, HTMLDivElement>>(new Map());
|
||||
@@ -378,27 +365,27 @@ const PdfTextEditorView = ({ data }: PdfTextEditorViewProps) => {
|
||||
dirtyPages,
|
||||
hasDocument,
|
||||
hasVectorPreview,
|
||||
fileName,
|
||||
fileName: _fileName,
|
||||
errorMessage,
|
||||
isGeneratingPdf,
|
||||
isSavingToWorkbench,
|
||||
isGeneratingPdf: _isGeneratingPdf,
|
||||
isSavingToWorkbench: _isSavingToWorkbench,
|
||||
isConverting,
|
||||
conversionProgress,
|
||||
hasChanges,
|
||||
forceSingleTextElement,
|
||||
hasChanges: _hasChanges,
|
||||
forceSingleTextElement: _forceSingleTextElement,
|
||||
groupingMode: externalGroupingMode,
|
||||
autoScaleText,
|
||||
requestPagePreview,
|
||||
onSelectPage,
|
||||
onGroupEdit,
|
||||
onGroupDelete,
|
||||
onImageTransform,
|
||||
onImageReset,
|
||||
onReset,
|
||||
onDownloadJson,
|
||||
onGeneratePdf,
|
||||
onReset: _onReset,
|
||||
onGeneratePdf: _onGeneratePdf,
|
||||
onSaveToWorkbench,
|
||||
onForceSingleTextElementChange,
|
||||
onGroupingModeChange,
|
||||
onForceSingleTextElementChange: _onForceSingleTextElementChange,
|
||||
onGroupingModeChange: _onGroupingModeChange,
|
||||
onMergeGroups,
|
||||
onUngroupGroup,
|
||||
onLoadFile,
|
||||
@@ -428,27 +415,6 @@ const PdfTextEditorView = ({ data }: PdfTextEditorViewProps) => {
|
||||
} : null,
|
||||
});
|
||||
|
||||
const handleModeChangeRequest = useCallback((newMode: GroupingMode) => {
|
||||
if (hasChanges && newMode !== externalGroupingMode) {
|
||||
// Show confirmation dialog
|
||||
setPendingModeChange(newMode);
|
||||
} else {
|
||||
// No changes, switch immediately
|
||||
onGroupingModeChange(newMode);
|
||||
}
|
||||
}, [hasChanges, externalGroupingMode, onGroupingModeChange]);
|
||||
|
||||
const handleConfirmModeChange = useCallback(() => {
|
||||
if (pendingModeChange) {
|
||||
onGroupingModeChange(pendingModeChange);
|
||||
setPendingModeChange(null);
|
||||
}
|
||||
}, [pendingModeChange, onGroupingModeChange]);
|
||||
|
||||
const handleCancelModeChange = useCallback(() => {
|
||||
setPendingModeChange(null);
|
||||
}, []);
|
||||
|
||||
const clearSelection = useCallback(() => {
|
||||
setSelectedGroupIds(new Set());
|
||||
lastSelectedGroupIdRef.current = null;
|
||||
@@ -1448,223 +1414,16 @@ const selectionToolbarPosition = useMemo(() => {
|
||||
padding: '1.5rem',
|
||||
overflow: 'hidden',
|
||||
height: '100%',
|
||||
display: 'grid',
|
||||
gridTemplateColumns: 'minmax(0, 1fr) 320px',
|
||||
gridTemplateRows: '1fr',
|
||||
alignItems: hasDocument ? 'start' : 'stretch',
|
||||
gap: '1.5rem',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
}}
|
||||
>
|
||||
<Card
|
||||
withBorder
|
||||
radius="md"
|
||||
shadow="xs"
|
||||
padding="md"
|
||||
style={{
|
||||
gridColumn: '2 / 3',
|
||||
gridRow: 1,
|
||||
maxHeight: 'calc(100vh - 3rem)',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
overflow: 'hidden'
|
||||
}}
|
||||
>
|
||||
<ScrollArea style={{ flex: 1 }} offsetScrollbars>
|
||||
<Stack gap="sm" pb="md">
|
||||
<Group justify="space-between" align="center">
|
||||
<Group gap="xs" align="center">
|
||||
<DescriptionIcon fontSize="small" />
|
||||
<Title order={3}>{t('pdfTextEditor.title', 'PDF JSON Editor')}</Title>
|
||||
{hasChanges && <Badge color="orange" variant="light" size="sm">{t('pdfTextEditor.badges.unsaved', 'Edited')}</Badge>}
|
||||
</Group>
|
||||
</Group>
|
||||
|
||||
<Stack gap="xs">
|
||||
<Button
|
||||
variant="subtle"
|
||||
leftSection={<AutorenewIcon fontSize="small" />}
|
||||
onClick={onReset}
|
||||
disabled={!hasDocument || isConverting}
|
||||
fullWidth
|
||||
>
|
||||
{t('pdfTextEditor.actions.reset', 'Reset Changes')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="default"
|
||||
leftSection={<FileDownloadIcon fontSize="small" />}
|
||||
onClick={onDownloadJson}
|
||||
disabled={!hasDocument || isConverting}
|
||||
fullWidth
|
||||
>
|
||||
{t('pdfTextEditor.actions.downloadJson', 'Download JSON')}
|
||||
</Button>
|
||||
<Button
|
||||
leftSection={<PictureAsPdfIcon fontSize="small" />}
|
||||
onClick={onGeneratePdf}
|
||||
loading={isGeneratingPdf}
|
||||
disabled={!hasDocument || !hasChanges || isConverting}
|
||||
fullWidth
|
||||
>
|
||||
{t('pdfTextEditor.actions.generatePdf', 'Generate PDF')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="filled"
|
||||
color="green"
|
||||
leftSection={<SaveIcon fontSize="small" />}
|
||||
onClick={onSaveToWorkbench}
|
||||
loading={isSavingToWorkbench}
|
||||
disabled={!hasDocument || !hasChanges || isConverting}
|
||||
fullWidth
|
||||
>
|
||||
{t('pdfTextEditor.actions.saveChanges', 'Save Changes')}
|
||||
</Button>
|
||||
</Stack>
|
||||
|
||||
{fileName && (
|
||||
<Text size="sm" c="dimmed">
|
||||
{t('pdfTextEditor.currentFile', 'Current file: {{name}}', { name: fileName })}
|
||||
</Text>
|
||||
)}
|
||||
|
||||
<Divider my="xs" />
|
||||
|
||||
<Group justify="space-between" align="center">
|
||||
<div>
|
||||
<Text fw={500} size="sm">
|
||||
{t('pdfTextEditor.options.autoScaleText.title', 'Auto-scale text to fit boxes')}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed" mt={4}>
|
||||
{t(
|
||||
'pdfTextEditor.options.autoScaleText.description',
|
||||
'Automatically scales text horizontally to fit within its original bounding box when font rendering differs from PDF.'
|
||||
)}
|
||||
</Text>
|
||||
</div>
|
||||
<Switch
|
||||
size="md"
|
||||
checked={autoScaleText}
|
||||
onChange={(event) => setAutoScaleText(event.currentTarget.checked)}
|
||||
/>
|
||||
</Group>
|
||||
|
||||
<Stack gap="xs">
|
||||
<Group gap={4} align="center">
|
||||
<Text fw={500} size="sm">
|
||||
{t('pdfTextEditor.options.groupingMode.title', 'Text Grouping Mode')}
|
||||
</Text>
|
||||
{externalGroupingMode === 'auto' && isParagraphPage && (
|
||||
<Badge size="xs" color="blue" variant="light" key={`para-${selectedPage}`}>
|
||||
{t('pdfTextEditor.pageType.paragraph', 'Paragraph page')}
|
||||
</Badge>
|
||||
)}
|
||||
{externalGroupingMode === 'auto' && !isParagraphPage && hasDocument && (
|
||||
<Badge size="xs" color="gray" variant="light" key={`sparse-${selectedPage}`}>
|
||||
{t('pdfTextEditor.pageType.sparse', 'Sparse text')}
|
||||
</Badge>
|
||||
)}
|
||||
</Group>
|
||||
<Text size="xs" c="dimmed">
|
||||
{externalGroupingMode === 'auto'
|
||||
? t(
|
||||
'pdfTextEditor.options.groupingMode.autoDescription',
|
||||
'Automatically detects page type and groups text appropriately.'
|
||||
)
|
||||
: externalGroupingMode === 'paragraph'
|
||||
? t(
|
||||
'pdfTextEditor.options.groupingMode.paragraphDescription',
|
||||
'Groups aligned lines into multi-line paragraph text boxes.'
|
||||
)
|
||||
: t(
|
||||
'pdfTextEditor.options.groupingMode.singleLineDescription',
|
||||
'Keeps each PDF text line as a separate text box.'
|
||||
)}
|
||||
</Text>
|
||||
<SegmentedControl
|
||||
value={externalGroupingMode}
|
||||
onChange={(value) => handleModeChangeRequest(value as GroupingMode)}
|
||||
data={[
|
||||
{ label: t('pdfTextEditor.groupingMode.auto', 'Auto'), value: 'auto' },
|
||||
{ label: t('pdfTextEditor.groupingMode.paragraph', 'Paragraph'), value: 'paragraph' },
|
||||
{ label: t('pdfTextEditor.groupingMode.singleLine', 'Single Line'), value: 'singleLine' },
|
||||
]}
|
||||
fullWidth
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
<Text size="xs" c="dimmed">
|
||||
{t(
|
||||
'pdfTextEditor.options.manualGrouping.descriptionInline',
|
||||
'Tip: Hold Ctrl (Cmd) or Shift to multi-select text boxes. A floating toolbar will appear above the selection so you can merge, ungroup, or adjust widths.',
|
||||
)}
|
||||
</Text>
|
||||
|
||||
<Group justify="space-between" align="center">
|
||||
<div>
|
||||
<Text fw={500} size="sm">
|
||||
{t('pdfTextEditor.options.forceSingleElement.title', 'Lock edited text to a single PDF element')}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed" mt={4}>
|
||||
{t(
|
||||
'pdfTextEditor.options.forceSingleElement.description',
|
||||
'When enabled, the editor exports each edited text box as one PDF text element to avoid overlapping glyphs or mixed fonts.'
|
||||
)}
|
||||
</Text>
|
||||
</div>
|
||||
<Switch
|
||||
size="md"
|
||||
checked={forceSingleTextElement}
|
||||
onChange={(event) => onForceSingleTextElementChange(event.currentTarget.checked)}
|
||||
/>
|
||||
</Group>
|
||||
|
||||
<Divider my="xs" />
|
||||
|
||||
<Accordion variant="contained">
|
||||
<Accordion.Item value="disclaimer">
|
||||
<Accordion.Control>
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<InfoOutlinedIcon fontSize="small" />
|
||||
<Text size="sm" fw={500}>
|
||||
{t('pdfTextEditor.disclaimer.heading', 'Preview Limitations')}
|
||||
</Text>
|
||||
</Group>
|
||||
</Accordion.Control>
|
||||
<Accordion.Panel>
|
||||
<Stack gap={4}>
|
||||
<Text size="xs">
|
||||
{t(
|
||||
'pdfTextEditor.disclaimer.textFocus',
|
||||
'This workspace focuses on editing text and repositioning embedded images. Complex page artwork, form widgets, and layered graphics are preserved for export but are not fully editable here.'
|
||||
)}
|
||||
</Text>
|
||||
<Text size="xs">
|
||||
{t(
|
||||
'pdfTextEditor.disclaimer.previewVariance',
|
||||
'Some visuals (such as table borders, shapes, or annotation appearances) may not display exactly in the preview. The exported PDF keeps the original drawing commands whenever possible.'
|
||||
)}
|
||||
</Text>
|
||||
<Text size="xs">
|
||||
{t(
|
||||
'pdfTextEditor.disclaimer.alpha',
|
||||
'This alpha viewer is still evolving—certain fonts, colours, transparency effects, and layout details may shift slightly. Please double-check the generated PDF before sharing.'
|
||||
)}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
</Accordion>
|
||||
|
||||
{hasDocument && <FontStatusPanel document={pdfDocument} pageIndex={selectedPage} />}
|
||||
</Stack>
|
||||
</ScrollArea>
|
||||
</Card>
|
||||
|
||||
{errorMessage && (
|
||||
<Alert
|
||||
icon={<WarningAmberIcon fontSize="small" />}
|
||||
color="red"
|
||||
radius="md"
|
||||
style={{ gridColumn: '2 / 3' }}
|
||||
mb="md"
|
||||
>
|
||||
{errorMessage}
|
||||
</Alert>
|
||||
@@ -1674,7 +1433,7 @@ const selectionToolbarPosition = useMemo(() => {
|
||||
<Stack
|
||||
align="center"
|
||||
justify="center"
|
||||
style={{ gridColumn: '1 / 2', gridRow: 1, height: '100%' }}
|
||||
style={{ flex: 1, height: '100%' }}
|
||||
>
|
||||
<Dropzone
|
||||
onDrop={(files) => {
|
||||
@@ -1704,8 +1463,8 @@ const selectionToolbarPosition = useMemo(() => {
|
||||
</Text>
|
||||
<Text size="sm" c="dimmed" ta="center" maw={420}>
|
||||
{activeFiles.length > 0
|
||||
? t('pdfTextEditor.empty.dropzoneWithFiles', 'Select a file from the Files tab, or drag and drop a PDF or JSON file here, or click to browse')
|
||||
: t('pdfTextEditor.empty.dropzone', 'Drag and drop a PDF or JSON file here, or click to browse')}
|
||||
? t('pdfTextEditor.empty.dropzoneWithFiles', 'Select a file from the Files tab, or drag and drop a PDF here, or click to browse')
|
||||
: t('pdfTextEditor.empty.dropzone', 'Drag and drop a PDF here, or click to browse')}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Dropzone>
|
||||
@@ -1713,7 +1472,7 @@ const selectionToolbarPosition = useMemo(() => {
|
||||
)}
|
||||
|
||||
{isConverting && (
|
||||
<Card withBorder radius="md" padding="xl" style={{ gridColumn: '1 / 2', gridRow: 1 }}>
|
||||
<Card withBorder radius="md" padding="xl" style={{ flex: 1 }}>
|
||||
<Stack gap="md">
|
||||
<Group justify="space-between" align="flex-start">
|
||||
<div style={{ flex: 1 }}>
|
||||
@@ -1748,10 +1507,8 @@ const selectionToolbarPosition = useMemo(() => {
|
||||
gap="lg"
|
||||
className="flex-1"
|
||||
style={{
|
||||
gridColumn: '1 / 2',
|
||||
gridRow: 1,
|
||||
minHeight: 0,
|
||||
height: 'calc(100vh - 3rem)',
|
||||
flex: 1,
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
@@ -1788,65 +1545,208 @@ const selectionToolbarPosition = useMemo(() => {
|
||||
title={
|
||||
<Group gap="xs">
|
||||
<InfoOutlinedIcon fontSize="small" />
|
||||
<Text fw={600}>{t('pdfTextEditor.welcomeBanner.title', 'Welcome to PDF Text Editor (Early Access)')}</Text>
|
||||
<Text fw={600}>
|
||||
{t(
|
||||
'pdfTextEditor.welcomeBanner.title',
|
||||
'Welcome to PDF Text Editor (Early Access)',
|
||||
)}
|
||||
</Text>
|
||||
</Group>
|
||||
}
|
||||
centered
|
||||
size="lg"
|
||||
scrollAreaComponent={Box}
|
||||
>
|
||||
<ScrollArea style={{ maxHeight: '70vh' }} offsetScrollbars>
|
||||
<Stack gap="sm">
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
maxHeight: '70vh',
|
||||
width: '100%',
|
||||
}}
|
||||
>
|
||||
{/* Header (fixed) */}
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: '0.5rem',
|
||||
marginBottom: '0.75rem',
|
||||
}}
|
||||
>
|
||||
<Alert color="orange" variant="light" radius="md">
|
||||
<Text size="sm" fw={500}>
|
||||
{t('pdfTextEditor.welcomeBanner.experimental', 'This is an experimental feature in active development. Expect some instability and issues during use.')}
|
||||
{t(
|
||||
'pdfTextEditor.welcomeBanner.experimental',
|
||||
'This is an experimental feature in active development. Expect some instability and issues during use.',
|
||||
)}
|
||||
</Text>
|
||||
</Alert>
|
||||
<Text size="sm">
|
||||
{t('pdfTextEditor.welcomeBanner.howItWorks', 'This tool converts your PDF to an editable format where you can modify text content and reposition images. Changes are saved back as a new PDF.')}
|
||||
{t(
|
||||
'pdfTextEditor.welcomeBanner.howItWorks',
|
||||
'This tool converts your PDF to an editable format where you can modify text content and reposition images. Changes are saved back as a new PDF.',
|
||||
)}
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
{/* Body (scrollable) */}
|
||||
<div
|
||||
style={{
|
||||
flex: 1,
|
||||
minHeight: 0,
|
||||
overflowY: 'auto',
|
||||
paddingRight: '0.25rem',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
gap: '0.5rem',
|
||||
}}
|
||||
>
|
||||
<Divider />
|
||||
<Text size="sm" fw={500} c="green.7">
|
||||
{t('pdfTextEditor.welcomeBanner.bestFor', 'Works Best With:')}
|
||||
</Text>
|
||||
<Text
|
||||
size="sm"
|
||||
component="ul"
|
||||
style={{ marginLeft: '1rem', marginTop: '0.25rem' }}
|
||||
>
|
||||
<li>
|
||||
{t(
|
||||
'pdfTextEditor.welcomeBanner.bestFor1',
|
||||
'Simple PDFs containing primarily text and images',
|
||||
)}
|
||||
</li>
|
||||
<li>
|
||||
{t(
|
||||
'pdfTextEditor.welcomeBanner.bestFor2',
|
||||
'Documents with standard paragraph formatting',
|
||||
)}
|
||||
</li>
|
||||
<li>
|
||||
{t(
|
||||
'pdfTextEditor.welcomeBanner.bestFor3',
|
||||
'Letters, essays, reports, and basic documents',
|
||||
)}
|
||||
</li>
|
||||
</Text>
|
||||
<Divider />
|
||||
<Text size="sm" fw={500} c="orange.7">
|
||||
{t('pdfTextEditor.welcomeBanner.notIdealFor', 'Not Ideal For:')}
|
||||
</Text>
|
||||
<Text
|
||||
size="sm"
|
||||
component="ul"
|
||||
style={{ marginLeft: '1rem', marginTop: '0.25rem' }}
|
||||
>
|
||||
<li>
|
||||
{t(
|
||||
'pdfTextEditor.welcomeBanner.notIdealFor1',
|
||||
'PDFs with special formatting like bullet points, tables, or multi-column layouts',
|
||||
)}
|
||||
</li>
|
||||
<li>
|
||||
{t(
|
||||
'pdfTextEditor.welcomeBanner.notIdealFor2',
|
||||
'Magazines, brochures, or heavily designed documents',
|
||||
)}
|
||||
</li>
|
||||
<li>
|
||||
{t(
|
||||
'pdfTextEditor.welcomeBanner.notIdealFor3',
|
||||
'Instruction manuals with complex layouts',
|
||||
)}
|
||||
</li>
|
||||
</Text>
|
||||
<Divider />
|
||||
<Text size="sm" fw={500}>
|
||||
{t('pdfTextEditor.welcomeBanner.limitations', 'Current Limitations:')}
|
||||
</Text>
|
||||
<Text
|
||||
size="sm"
|
||||
component="ul"
|
||||
style={{ marginLeft: '1rem', marginTop: '0.25rem' }}
|
||||
>
|
||||
<li>
|
||||
{t(
|
||||
'pdfTextEditor.welcomeBanner.limitation1',
|
||||
'Font rendering may differ slightly from the original PDF',
|
||||
)}
|
||||
</li>
|
||||
<li>
|
||||
{t(
|
||||
'pdfTextEditor.welcomeBanner.limitation2',
|
||||
'Complex graphics, form fields, and annotations are preserved but not editable',
|
||||
)}
|
||||
</li>
|
||||
<li>
|
||||
{t(
|
||||
'pdfTextEditor.welcomeBanner.limitation3',
|
||||
'Large files may take time to convert and process',
|
||||
)}
|
||||
</li>
|
||||
</Text>
|
||||
<Divider />
|
||||
<Text size="sm" fw={500}>
|
||||
{t('pdfTextEditor.welcomeBanner.knownIssues', 'Known Issues (Being Fixed):')}
|
||||
</Text>
|
||||
<Text
|
||||
size="sm"
|
||||
component="ul"
|
||||
style={{ marginLeft: '1rem', marginTop: '0.25rem' }}
|
||||
>
|
||||
<li>
|
||||
{t(
|
||||
'pdfTextEditor.welcomeBanner.issue1',
|
||||
'Text colour is not currently preserved (will be added soon)',
|
||||
)}
|
||||
</li>
|
||||
<li>
|
||||
{t(
|
||||
'pdfTextEditor.welcomeBanner.issue2',
|
||||
'Paragraph mode has more alignment and spacing issues - Single Line mode recommended',
|
||||
)}
|
||||
</li>
|
||||
<li>
|
||||
{t(
|
||||
'pdfTextEditor.welcomeBanner.issue3',
|
||||
'The preview display differs from the exported PDF - exported PDFs are closer to the original',
|
||||
)}
|
||||
</li>
|
||||
<li>
|
||||
{t(
|
||||
'pdfTextEditor.welcomeBanner.issue4',
|
||||
'Rotated text alignment may need manual adjustment',
|
||||
)}
|
||||
</li>
|
||||
<li>
|
||||
{t(
|
||||
'pdfTextEditor.welcomeBanner.issue5',
|
||||
'Transparency and layering effects may vary from original',
|
||||
)}
|
||||
</li>
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer (fixed) */}
|
||||
<div
|
||||
style={{
|
||||
marginTop: '0.75rem',
|
||||
}}
|
||||
>
|
||||
<Divider />
|
||||
<Text size="sm" fw={500} c="green.7">
|
||||
{t('pdfTextEditor.welcomeBanner.bestFor', 'Works Best With:')}
|
||||
<Text size="xs" c="dimmed" mt="xs">
|
||||
{t(
|
||||
'pdfTextEditor.welcomeBanner.feedback',
|
||||
'This is an early access feature. Please report any issues you encounter to help us improve!',
|
||||
)}
|
||||
</Text>
|
||||
<Text size="sm" component="ul" style={{ marginLeft: '1rem', marginTop: '0.25rem' }}>
|
||||
<li>{t('pdfTextEditor.welcomeBanner.bestFor1', 'Simple PDFs containing primarily text and images')}</li>
|
||||
<li>{t('pdfTextEditor.welcomeBanner.bestFor2', 'Documents with standard paragraph formatting')}</li>
|
||||
<li>{t('pdfTextEditor.welcomeBanner.bestFor3', 'Letters, essays, reports, and basic documents')}</li>
|
||||
</Text>
|
||||
<Divider />
|
||||
<Text size="sm" fw={500} c="orange.7">
|
||||
{t('pdfTextEditor.welcomeBanner.notIdealFor', 'Not Ideal For:')}
|
||||
</Text>
|
||||
<Text size="sm" component="ul" style={{ marginLeft: '1rem', marginTop: '0.25rem' }}>
|
||||
<li>{t('pdfTextEditor.welcomeBanner.notIdealFor1', 'PDFs with special formatting like bullet points, tables, or multi-column layouts')}</li>
|
||||
<li>{t('pdfTextEditor.welcomeBanner.notIdealFor2', 'Magazines, brochures, or heavily designed documents')}</li>
|
||||
<li>{t('pdfTextEditor.welcomeBanner.notIdealFor3', 'Instruction manuals with complex layouts')}</li>
|
||||
</Text>
|
||||
<Divider />
|
||||
<Text size="sm" fw={500}>
|
||||
{t('pdfTextEditor.welcomeBanner.limitations', 'Current Limitations:')}
|
||||
</Text>
|
||||
<Text size="sm" component="ul" style={{ marginLeft: '1rem', marginTop: '0.25rem' }}>
|
||||
<li>{t('pdfTextEditor.welcomeBanner.limitation1', 'Font rendering may differ slightly from the original PDF')}</li>
|
||||
<li>{t('pdfTextEditor.welcomeBanner.limitation2', 'Complex graphics, form fields, and annotations are preserved but not editable')}</li>
|
||||
<li>{t('pdfTextEditor.welcomeBanner.limitation3', 'Large files may take time to convert and process')}</li>
|
||||
</Text>
|
||||
<Divider />
|
||||
<Text size="sm" fw={500}>
|
||||
{t('pdfTextEditor.welcomeBanner.knownIssues', 'Known Issues (Being Fixed):')}
|
||||
</Text>
|
||||
<Text size="sm" component="ul" style={{ marginLeft: '1rem', marginTop: '0.25rem' }}>
|
||||
<li>{t('pdfTextEditor.welcomeBanner.issue1', 'Text colour is not currently preserved (will be added soon)')}</li>
|
||||
<li>{t('pdfTextEditor.welcomeBanner.issue2', 'Paragraph mode has more alignment and spacing issues - Single Line mode recommended')}</li>
|
||||
<li>{t('pdfTextEditor.welcomeBanner.issue3', 'The preview display differs from the exported PDF - exported PDFs are closer to the original')}</li>
|
||||
<li>{t('pdfTextEditor.welcomeBanner.issue4', 'Rotated text alignment may need manual adjustment')}</li>
|
||||
<li>{t('pdfTextEditor.welcomeBanner.issue5', 'Transparency and layering effects may vary from original')}</li>
|
||||
</Text>
|
||||
<Divider />
|
||||
<Text size="xs" c="dimmed">
|
||||
{t('pdfTextEditor.welcomeBanner.feedback', 'This is an early access feature. Please report any issues you encounter to help us improve!')}
|
||||
</Text>
|
||||
<Group justify="flex-end" gap="sm" mt="md">
|
||||
<Group justify="flex-end" gap="sm" mt="xs">
|
||||
<Button variant="default" onClick={handleDismissWelcomeBanner}>
|
||||
{t('pdfTextEditor.welcomeBanner.gotIt', 'Got it')}
|
||||
</Button>
|
||||
@@ -1854,8 +1754,8 @@ const selectionToolbarPosition = useMemo(() => {
|
||||
{t('pdfTextEditor.welcomeBanner.dontShowAgain', "Don't show again")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
<Card
|
||||
@@ -2485,31 +2385,6 @@ const selectionToolbarPosition = useMemo(() => {
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
{/* Mode Change Confirmation Modal */}
|
||||
<Modal
|
||||
opened={pendingModeChange !== null}
|
||||
onClose={handleCancelModeChange}
|
||||
title={t('pdfTextEditor.modeChange.title', 'Confirm Mode Change')}
|
||||
centered
|
||||
>
|
||||
<Stack gap="md">
|
||||
<Text>
|
||||
{t(
|
||||
'pdfTextEditor.modeChange.warning',
|
||||
'Changing the text grouping mode will reset all unsaved changes. Are you sure you want to continue?'
|
||||
)}
|
||||
</Text>
|
||||
<Group justify="flex-end" gap="sm">
|
||||
<Button variant="default" onClick={handleCancelModeChange}>
|
||||
{t('pdfTextEditor.modeChange.cancel', 'Cancel')}
|
||||
</Button>
|
||||
<Button color="red" onClick={handleConfirmModeChange}>
|
||||
{t('pdfTextEditor.modeChange.confirm', 'Reset and Change Mode')}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</Modal>
|
||||
|
||||
{/* Navigation Warning Modal */}
|
||||
<NavigationWarningModal
|
||||
onApplyAndContinue={onSaveToWorkbench}
|
||||
|
||||
@@ -31,6 +31,24 @@ const RotateSettings = ({ parameters, disabled = false }: RotateSettingsProps) =
|
||||
// Calculate current angle display
|
||||
const currentAngle = parameters.parameters.angle;
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'ArrowLeft') {
|
||||
event.preventDefault();
|
||||
parameters.rotateAnticlockwise();
|
||||
} else if (event.key === 'ArrowRight') {
|
||||
event.preventDefault();
|
||||
parameters.rotateClockwise();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('keydown', handleKeyDown);
|
||||
};
|
||||
}, [parameters]);
|
||||
|
||||
return (
|
||||
<Stack gap="md">
|
||||
{/* Thumbnail Preview Section */}
|
||||
|
||||
@@ -461,23 +461,13 @@ const SignSettings = ({
|
||||
const handleImageChange = async (file: File | null) => {
|
||||
if (file && !disabled) {
|
||||
try {
|
||||
const result = await new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => {
|
||||
if (e.target?.result) {
|
||||
resolve(e.target.result as string);
|
||||
} else {
|
||||
reject(new Error('Failed to read file'));
|
||||
}
|
||||
};
|
||||
reader.onerror = () => reject(reader.error);
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
|
||||
// Reset pause state and directly activate placement
|
||||
setPlacementManuallyPaused(false);
|
||||
lastAppliedPlacementKey.current = null;
|
||||
setImageSignatureData(result);
|
||||
|
||||
// Image data will be set by onProcessedImageData callback in ImageUploader
|
||||
// This avoids the race condition where both handleImageChange and onProcessedImageData
|
||||
// try to set the image data, potentially with the wrong version
|
||||
|
||||
// Directly activate placement on image upload
|
||||
if (typeof window !== 'undefined') {
|
||||
@@ -491,8 +481,6 @@ const SignSettings = ({
|
||||
} else if (!file) {
|
||||
setImageSignatureData(undefined);
|
||||
onDeactivateSignature?.();
|
||||
setImageSignatureData(undefined);
|
||||
onDeactivateSignature?.();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -835,6 +823,12 @@ const SignSettings = ({
|
||||
<ImageUploader
|
||||
onImageChange={handleImageChange}
|
||||
disabled={disabled}
|
||||
allowBackgroundRemoval={true}
|
||||
onProcessedImageData={(dataUrl) => {
|
||||
if (dataUrl) {
|
||||
setImageSignatureData(dataUrl);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{renderSaveButtonRow('image', hasImageSignature, handleSaveImageSignature)}
|
||||
</Stack>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Stack, TextInput, Checkbox, Anchor, Text } from '@mantine/core';
|
||||
import { Stack, TextInput, Checkbox, Anchor, Text, Select } from '@mantine/core';
|
||||
import LocalIcon from '@app/components/shared/LocalIcon';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { SPLIT_METHODS } from '@app/constants/splitConstants';
|
||||
@@ -49,6 +49,29 @@ const SplitSettings = ({
|
||||
placeholder={t("split-by-sections.vertical.placeholder", "Enter number of vertical divisions")}
|
||||
disabled={disabled}
|
||||
/>
|
||||
<Select
|
||||
label={t("split-by-sections.splitMode.label", "Split Mode")}
|
||||
value={parameters.splitMode || 'SPLIT_ALL'}
|
||||
onChange={(value) => onParameterChange('splitMode', value || 'SPLIT_ALL')}
|
||||
description={t("split-by-sections.splitMode.description", "Choose how to split the pages")}
|
||||
data={[
|
||||
{ value: 'SPLIT_ALL', label: t("split-by-sections.splitMode.splitAll", "Split all pages") },
|
||||
{ value: 'SPLIT_ALL_EXCEPT_FIRST', label: t("split-by-sections.splitMode.splitAllExceptFirst", "Split all except first") },
|
||||
{ value: 'SPLIT_ALL_EXCEPT_LAST', label: t("split-by-sections.splitMode.splitAllExceptLast", "Split all except last") },
|
||||
{ value: 'SPLIT_ALL_EXCEPT_FIRST_AND_LAST', label: t("split-by-sections.splitMode.splitAllExceptFirstAndLast", "Split all except first and last") },
|
||||
{ value: 'CUSTOM', label: t("split-by-sections.splitMode.custom", "Custom pages") },
|
||||
]}
|
||||
disabled={disabled}
|
||||
/>
|
||||
{parameters.splitMode === 'CUSTOM' && (
|
||||
<TextInput
|
||||
label={t("split-by-sections.customPages.label", "Custom Page Numbers")}
|
||||
placeholder={t("split-by-sections.customPages.placeholder", "e.g. 2,4,6")}
|
||||
value={parameters.customPages || ''}
|
||||
onChange={(e) => onParameterChange('customPages', e.target.value)}
|
||||
disabled={disabled}
|
||||
/>
|
||||
)}
|
||||
<Checkbox
|
||||
label={t("split-by-sections.merge", "Merge sections into one PDF")}
|
||||
checked={parameters.merge}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { TooltipContent } from '@app/types/tips';
|
||||
|
||||
export const usePdfTextEditorTips = (): TooltipContent => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return {
|
||||
header: {
|
||||
title: t('pdfTextEditor.tooltip.header.title', 'Preview Limitations'),
|
||||
},
|
||||
tips: [
|
||||
{
|
||||
title: t('pdfTextEditor.tooltip.textFocus.title', 'Text and Image Focus'),
|
||||
description: t(
|
||||
'pdfTextEditor.tooltip.textFocus.text',
|
||||
'This workspace focuses on editing text and repositioning embedded images. Complex page artwork, form widgets, and layered graphics are preserved for export but are not fully editable here.'
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('pdfTextEditor.tooltip.previewVariance.title', 'Preview Variance'),
|
||||
description: t(
|
||||
'pdfTextEditor.tooltip.previewVariance.text',
|
||||
'Some visuals (such as table borders, shapes, or annotation appearances) may not display exactly in the preview. The exported PDF keeps the original drawing commands whenever possible.'
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('pdfTextEditor.tooltip.alpha.title', 'Alpha Viewer'),
|
||||
description: t(
|
||||
'pdfTextEditor.tooltip.alpha.text',
|
||||
'This alpha viewer is still evolving—certain fonts, colours, transparency effects, and layout details may shift slightly. Please double-check the generated PDF before sharing.'
|
||||
),
|
||||
},
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
@@ -34,6 +34,9 @@ export const CONVERSION_ENDPOINTS = {
|
||||
'html-pdf': '/api/v1/convert/html/pdf',
|
||||
'markdown-pdf': '/api/v1/convert/markdown/pdf',
|
||||
'eml-pdf': '/api/v1/convert/eml/pdf',
|
||||
'cbr-pdf': '/api/v1/convert/cbr/pdf',
|
||||
'pdf-cbr': '/api/v1/convert/pdf/cbr',
|
||||
'ebook-pdf': '/api/v1/convert/ebook/pdf',
|
||||
'pdf-text-editor': '/api/v1/convert/pdf/text-editor',
|
||||
'text-editor-pdf': '/api/v1/convert/text-editor/pdf'
|
||||
} as const;
|
||||
@@ -55,6 +58,9 @@ export const ENDPOINT_NAMES = {
|
||||
'html-pdf': 'html-to-pdf',
|
||||
'markdown-pdf': 'markdown-to-pdf',
|
||||
'eml-pdf': 'eml-to-pdf',
|
||||
'ebook-pdf': 'ebook-to-pdf',
|
||||
'cbr-pdf': 'cbr-to-pdf',
|
||||
'pdf-cbr': 'pdf-to-cbr',
|
||||
'pdf-text-editor': 'pdf-to-text-editor',
|
||||
'text-editor-pdf': 'text-editor-to-pdf'
|
||||
} as const;
|
||||
@@ -66,6 +72,7 @@ export const FROM_FORMAT_OPTIONS = [
|
||||
{ value: 'image', label: 'Images', group: 'Multiple Files' },
|
||||
{ value: 'pdf', label: 'PDF', group: 'Document' },
|
||||
{ value: 'cbz', label: 'CBZ', group: 'Archive' },
|
||||
{ value: 'cbr', label: 'CBR', group: 'Archive' },
|
||||
{ value: 'docx', label: 'DOCX', group: 'Document' },
|
||||
{ value: 'doc', label: 'DOC', group: 'Document' },
|
||||
{ value: 'odt', label: 'ODT', group: 'Document' },
|
||||
@@ -89,6 +96,10 @@ export const FROM_FORMAT_OPTIONS = [
|
||||
{ value: 'txt', label: 'TXT', group: 'Text' },
|
||||
{ value: 'rtf', label: 'RTF', group: 'Text' },
|
||||
{ value: 'eml', label: 'EML', group: 'Email' },
|
||||
{ value: 'epub', label: 'EPUB', group: 'eBook' },
|
||||
{ value: 'mobi', label: 'MOBI', group: 'eBook' },
|
||||
{ value: 'azw3', label: 'AZW3', group: 'eBook' },
|
||||
{ value: 'fb2', label: 'FB2', group: 'eBook' },
|
||||
];
|
||||
|
||||
export const TO_FORMAT_OPTIONS = [
|
||||
@@ -97,6 +108,7 @@ export const TO_FORMAT_OPTIONS = [
|
||||
{ value: 'docx', label: 'DOCX', group: 'Document' },
|
||||
{ value: 'odt', label: 'ODT', group: 'Document' },
|
||||
{ value: 'cbz', label: 'CBZ', group: 'Archive' },
|
||||
{ value: 'cbr', label: 'CBR', group: 'Archive' },
|
||||
{ value: 'csv', label: 'CSV', group: 'Spreadsheet' },
|
||||
{ value: 'pptx', label: 'PPTX', group: 'Presentation' },
|
||||
{ value: 'odp', label: 'ODP', group: 'Presentation' },
|
||||
@@ -117,7 +129,7 @@ export const TO_FORMAT_OPTIONS = [
|
||||
export const CONVERSION_MATRIX: Record<string, string[]> = {
|
||||
'any': ['pdf'], // Mixed files always convert to PDF
|
||||
'image': ['pdf'], // Multiple images always convert to PDF
|
||||
'pdf': ['png', 'jpg', 'gif', 'tiff', 'bmp', 'webp', 'docx', 'odt', 'pptx', 'odp', 'csv', 'txt', 'rtf', 'md', 'html', 'xml', 'pdfa', 'cbz'],
|
||||
'pdf': ['png', 'jpg', 'gif', 'tiff', 'bmp', 'webp', 'docx', 'odt', 'pptx', 'odp', 'csv', 'txt', 'rtf', 'md', 'html', 'xml', 'pdfa', 'cbz', 'cbr'],
|
||||
'cbz': ['pdf'],
|
||||
'docx': ['pdf'], 'doc': ['pdf'], 'odt': ['pdf'],
|
||||
'xlsx': ['pdf'], 'xls': ['pdf'], 'ods': ['pdf'],
|
||||
@@ -127,7 +139,9 @@ export const CONVERSION_MATRIX: Record<string, string[]> = {
|
||||
'zip': ['pdf'],
|
||||
'md': ['pdf'],
|
||||
'txt': ['pdf'], 'rtf': ['pdf'],
|
||||
'eml': ['pdf']
|
||||
'eml': ['pdf'],
|
||||
'cbr': ['pdf'],
|
||||
'epub': ['pdf'], 'mobi': ['pdf'], 'azw3': ['pdf'], 'fb2': ['pdf']
|
||||
};
|
||||
|
||||
// Map extensions to endpoint keys
|
||||
@@ -142,6 +156,7 @@ export const EXTENSION_TO_ENDPOINT: Record<string, Record<string, string>> = {
|
||||
'txt': 'pdf-to-text', 'rtf': 'pdf-to-text', 'md': 'pdf-to-markdown',
|
||||
'html': 'pdf-to-html', 'xml': 'pdf-to-xml',
|
||||
'pdfa': 'pdf-to-pdfa',
|
||||
'cbr': 'pdf-to-cbr',
|
||||
'cbz': 'pdf-to-cbz'
|
||||
},
|
||||
'cbz': { 'pdf': 'cbz-to-pdf' },
|
||||
@@ -154,7 +169,9 @@ export const EXTENSION_TO_ENDPOINT: Record<string, Record<string, string>> = {
|
||||
'zip': { 'pdf': 'html-to-pdf' },
|
||||
'md': { 'pdf': 'markdown-to-pdf' },
|
||||
'txt': { 'pdf': 'file-to-pdf' }, 'rtf': { 'pdf': 'file-to-pdf' },
|
||||
'eml': { 'pdf': 'eml-to-pdf' }
|
||||
'cbr': { 'pdf': 'cbr-to-pdf' },
|
||||
'eml': { 'pdf': 'eml-to-pdf' },
|
||||
'epub': { 'pdf': 'ebook-to-pdf' }, 'mobi': { 'pdf': 'ebook-to-pdf' }, 'azw3': { 'pdf': 'ebook-to-pdf' }, 'fb2': { 'pdf': 'ebook-to-pdf' }
|
||||
};
|
||||
|
||||
export type ColorType = typeof COLOR_TYPES[keyof typeof COLOR_TYPES];
|
||||
|
||||
@@ -12,10 +12,10 @@ export const CONVERT_SUPPORTED_FORMATS = [
|
||||
'sda', 'sdc', 'sdd', 'sdw', 'stc', 'std', 'sti', 'stw', 'sxd', 'sxg', 'sxi', 'sxw',
|
||||
// Email formats
|
||||
'eml',
|
||||
// Ebook formats
|
||||
'epub', 'mobi', 'azw3', 'fb2',
|
||||
// Archive formats
|
||||
'zip', 'cbz',
|
||||
'zip', 'cbr', 'cbz',
|
||||
// Other
|
||||
'dbf', 'fods', 'vsd', 'vor', 'vor3', 'vor4', 'uop', 'pct', 'ps', 'pdf',
|
||||
];
|
||||
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ export interface AppConfig {
|
||||
defaultLocale?: string;
|
||||
logoStyle?: 'modern' | 'classic';
|
||||
enableLogin?: boolean;
|
||||
showSettingsWhenNoLogin?: boolean;
|
||||
enableEmailInvites?: boolean;
|
||||
isAdmin?: boolean;
|
||||
enableAlphaFunctionality?: boolean;
|
||||
|
||||
@@ -16,6 +16,8 @@ const buildFormData = (parameters: AddAttachmentsParameters, file: File): FormDa
|
||||
if (attachment) formData.append("attachments", attachment);
|
||||
});
|
||||
|
||||
formData.append("convertToPdfA3b", String(parameters.convertToPdfA3b));
|
||||
|
||||
return formData;
|
||||
};
|
||||
|
||||
|
||||
@@ -2,10 +2,12 @@ import { useState } from 'react';
|
||||
|
||||
export interface AddAttachmentsParameters {
|
||||
attachments: File[];
|
||||
convertToPdfA3b: boolean;
|
||||
}
|
||||
|
||||
const defaultParameters: AddAttachmentsParameters = {
|
||||
attachments: []
|
||||
attachments: [],
|
||||
convertToPdfA3b: false
|
||||
};
|
||||
|
||||
export const useAddAttachmentsParameters = () => {
|
||||
@@ -33,3 +35,5 @@ export const useAddAttachmentsParameters = () => {
|
||||
validateParameters
|
||||
};
|
||||
};
|
||||
|
||||
export const DEFAULT_ADD_ATTACHMENTS_PARAMETERS: AddAttachmentsParameters = defaultParameters;
|
||||
|
||||
@@ -20,6 +20,7 @@ export const buildCompressFormData = (parameters: CompressParameters, file: File
|
||||
|
||||
formData.append("grayscale", parameters.grayscale.toString());
|
||||
formData.append("lineArt", parameters.lineArt.toString());
|
||||
formData.append("linearize", parameters.linearize.toString());
|
||||
if (parameters.lineArt) {
|
||||
formData.append("lineArtThreshold", parameters.lineArtThreshold.toString());
|
||||
formData.append("lineArtEdgeLevel", parameters.lineArtEdgeLevel.toString());
|
||||
|
||||
@@ -11,6 +11,7 @@ export interface CompressParameters extends BaseParameters {
|
||||
compressionMethod: 'quality' | 'filesize';
|
||||
fileSizeValue: string;
|
||||
fileSizeUnit: 'KB' | 'MB';
|
||||
linearize: boolean;
|
||||
}
|
||||
|
||||
export const defaultParameters: CompressParameters = {
|
||||
@@ -23,6 +24,7 @@ export const defaultParameters: CompressParameters = {
|
||||
compressionMethod: 'quality',
|
||||
fileSizeValue: '',
|
||||
fileSizeUnit: 'MB',
|
||||
linearize: false,
|
||||
};
|
||||
|
||||
export type CompressParametersHook = BaseParametersHook<CompressParameters>;
|
||||
|
||||
@@ -21,6 +21,8 @@ export const shouldProcessFilesSeparately = (
|
||||
(parameters.fromExtension === 'pdf' && parameters.toExtension === 'pdfa') ||
|
||||
// PDF to text-like formats should be one output per input
|
||||
(parameters.fromExtension === 'pdf' && ['txt', 'rtf', 'csv'].includes(parameters.toExtension)) ||
|
||||
// PDF to CBR conversions (each PDF should generate its own archive)
|
||||
(parameters.fromExtension === 'pdf' && parameters.toExtension === 'cbr') ||
|
||||
// PDF to office format conversions (each PDF should generate its own office file)
|
||||
(parameters.fromExtension === 'pdf' && isOfficeFormat(parameters.toExtension)) ||
|
||||
// Office files to PDF conversions (each file should be processed separately via LibreOffice)
|
||||
@@ -28,6 +30,8 @@ export const shouldProcessFilesSeparately = (
|
||||
// Web files to PDF conversions (each web file should generate its own PDF)
|
||||
((isWebFormat(parameters.fromExtension) || parameters.fromExtension === 'web') &&
|
||||
parameters.toExtension === 'pdf') ||
|
||||
// eBook files to PDF conversions (each file should be processed separately via Calibre)
|
||||
(['epub', 'mobi', 'azw3', 'fb2'].includes(parameters.fromExtension) && parameters.toExtension === 'pdf') ||
|
||||
// Web files smart detection
|
||||
(parameters.isSmartDetection && parameters.smartDetectionType === 'web') ||
|
||||
// Mixed file types (smart detection)
|
||||
@@ -38,12 +42,12 @@ export const shouldProcessFilesSeparately = (
|
||||
// Static function that can be used by both the hook and automation executor
|
||||
export const buildConvertFormData = (parameters: ConvertParameters, selectedFiles: File[]): FormData => {
|
||||
const formData = new FormData();
|
||||
const { fromExtension, toExtension, imageOptions, htmlOptions, emailOptions, pdfaOptions, cbrOptions, pdfToCbrOptions, cbzOptions, cbzOutputOptions, ebookOptions } = parameters;
|
||||
|
||||
selectedFiles.forEach(file => {
|
||||
formData.append("fileInput", file);
|
||||
});
|
||||
|
||||
const { fromExtension, toExtension, imageOptions, htmlOptions, emailOptions, pdfaOptions, cbzOptions, cbzOutputOptions } = parameters;
|
||||
|
||||
if (isImageFormat(toExtension)) {
|
||||
formData.append("imageFormat", toExtension);
|
||||
@@ -71,10 +75,19 @@ export const buildConvertFormData = (parameters: ConvertParameters, selectedFile
|
||||
formData.append("outputFormat", pdfaOptions.outputFormat);
|
||||
} else if (fromExtension === 'pdf' && toExtension === 'csv') {
|
||||
formData.append("pageNumbers", "all");
|
||||
} else if (fromExtension === 'cbr' && toExtension === 'pdf') {
|
||||
formData.append("optimizeForEbook", cbrOptions.optimizeForEbook.toString());
|
||||
} else if (fromExtension === 'pdf' && toExtension === 'cbr') {
|
||||
formData.append("dpi", pdfToCbrOptions.dpi.toString());
|
||||
} else if (fromExtension === 'cbz' && toExtension === 'pdf') {
|
||||
formData.append("optimizeForEbook", (cbzOptions?.optimizeForEbook ?? false).toString());
|
||||
} else if (fromExtension === 'pdf' && toExtension === 'cbz') {
|
||||
formData.append("dpi", (cbzOutputOptions?.dpi ?? 150).toString());
|
||||
} else if (['epub', 'mobi', 'azw3', 'fb2'].includes(fromExtension) && toExtension === 'pdf') {
|
||||
formData.append("embedAllFonts", (ebookOptions?.embedAllFonts ?? false).toString());
|
||||
formData.append("includeTableOfContents", (ebookOptions?.includeTableOfContents ?? false).toString());
|
||||
formData.append("includePageNumbers", (ebookOptions?.includePageNumbers ?? false).toString());
|
||||
formData.append("optimizeForEbook", (ebookOptions?.optimizeForEbook ?? false).toString());
|
||||
}
|
||||
|
||||
return formData;
|
||||
|
||||
@@ -36,12 +36,24 @@ export interface ConvertParameters extends BaseParameters {
|
||||
pdfaOptions: {
|
||||
outputFormat: string;
|
||||
};
|
||||
cbrOptions: {
|
||||
optimizeForEbook: boolean;
|
||||
};
|
||||
pdfToCbrOptions: {
|
||||
dpi: number;
|
||||
};
|
||||
cbzOptions: {
|
||||
optimizeForEbook: boolean;
|
||||
};
|
||||
cbzOutputOptions: {
|
||||
dpi: number;
|
||||
};
|
||||
ebookOptions?: {
|
||||
embedAllFonts: boolean;
|
||||
includeTableOfContents: boolean;
|
||||
includePageNumbers: boolean;
|
||||
optimizeForEbook: boolean;
|
||||
};
|
||||
isSmartDetection: boolean;
|
||||
smartDetectionType: 'mixed' | 'images' | 'web' | 'none';
|
||||
}
|
||||
@@ -75,12 +87,24 @@ export const defaultParameters: ConvertParameters = {
|
||||
pdfaOptions: {
|
||||
outputFormat: 'pdfa-1',
|
||||
},
|
||||
cbrOptions: {
|
||||
optimizeForEbook: false,
|
||||
},
|
||||
pdfToCbrOptions: {
|
||||
dpi: 150,
|
||||
},
|
||||
cbzOptions: {
|
||||
optimizeForEbook: false,
|
||||
},
|
||||
cbzOutputOptions: {
|
||||
dpi: 150,
|
||||
},
|
||||
ebookOptions: {
|
||||
embedAllFonts: false,
|
||||
includeTableOfContents: false,
|
||||
includePageNumbers: false,
|
||||
optimizeForEbook: false,
|
||||
},
|
||||
isSmartDetection: false,
|
||||
smartDetectionType: 'none',
|
||||
};
|
||||
|
||||
@@ -7,13 +7,17 @@ import { CropParameters, defaultParameters } from '@app/hooks/tools/crop/useCrop
|
||||
export const buildCropFormData = (parameters: CropParameters, file: File): FormData => {
|
||||
const formData = new FormData();
|
||||
formData.append("fileInput", file);
|
||||
const cropArea = parameters.cropArea;
|
||||
|
||||
// Backend expects precise float values for PDF coordinates
|
||||
formData.append("x", cropArea.x.toString());
|
||||
formData.append("y", cropArea.y.toString());
|
||||
formData.append("width", cropArea.width.toString());
|
||||
formData.append("height", cropArea.height.toString());
|
||||
if (!parameters.autoCrop) {
|
||||
const cropArea = parameters.cropArea;
|
||||
|
||||
formData.append("x", cropArea.x.toString());
|
||||
formData.append("y", cropArea.y.toString());
|
||||
formData.append("width", cropArea.width.toString());
|
||||
formData.append("height", cropArea.height.toString());
|
||||
}
|
||||
|
||||
formData.append("autoCrop", parameters.autoCrop.toString());
|
||||
|
||||
return formData;
|
||||
};
|
||||
|
||||
@@ -6,10 +6,12 @@ import { DEFAULT_CROP_AREA } from '@app/constants/cropConstants';
|
||||
|
||||
export interface CropParameters extends BaseParameters {
|
||||
cropArea: Rectangle;
|
||||
autoCrop: boolean;
|
||||
}
|
||||
|
||||
export const defaultParameters: CropParameters = {
|
||||
cropArea: DEFAULT_CROP_AREA,
|
||||
autoCrop: false,
|
||||
};
|
||||
|
||||
export type CropParametersHook = BaseParametersHook<CropParameters> & {
|
||||
|
||||
@@ -8,6 +8,9 @@ export const buildFlattenFormData = (parameters: FlattenParameters, file: File):
|
||||
const formData = new FormData();
|
||||
formData.append('fileInput', file);
|
||||
formData.append('flattenOnlyForms', parameters.flattenOnlyForms.toString());
|
||||
if (parameters.renderDpi != null) {
|
||||
formData.append('renderDpi', parameters.renderDpi.toString());
|
||||
}
|
||||
return formData;
|
||||
};
|
||||
|
||||
|
||||
@@ -3,10 +3,12 @@ import { useBaseParameters, BaseParametersHook } from '@app/hooks/tools/shared/u
|
||||
|
||||
export interface FlattenParameters extends BaseParameters {
|
||||
flattenOnlyForms: boolean;
|
||||
renderDpi?: number;
|
||||
}
|
||||
|
||||
export const defaultParameters: FlattenParameters = {
|
||||
flattenOnlyForms: false,
|
||||
renderDpi: undefined,
|
||||
};
|
||||
|
||||
export type FlattenParametersHook = BaseParametersHook<FlattenParameters>;
|
||||
|
||||
@@ -20,6 +20,10 @@ export const buildSplitFormData = (parameters: SplitParameters, file: File): For
|
||||
formData.append("horizontalDivisions", parameters.hDiv);
|
||||
formData.append("verticalDivisions", parameters.vDiv);
|
||||
formData.append("merge", parameters.merge.toString());
|
||||
formData.append("splitMode", parameters.splitMode || 'SPLIT_ALL');
|
||||
if (parameters.splitMode === 'CUSTOM' && parameters.customPages) {
|
||||
formData.append("pageNumbers", parameters.customPages);
|
||||
}
|
||||
break;
|
||||
case SPLIT_METHODS.BY_SIZE:
|
||||
formData.append("splitType", "0");
|
||||
|
||||
@@ -13,6 +13,8 @@ export interface SplitParameters extends BaseParameters {
|
||||
includeMetadata: boolean;
|
||||
allowDuplicates: boolean;
|
||||
duplexMode: boolean;
|
||||
splitMode?: string;
|
||||
customPages?: string;
|
||||
}
|
||||
|
||||
export type SplitParametersHook = BaseParametersHook<SplitParameters>;
|
||||
@@ -28,6 +30,8 @@ export const defaultParameters: SplitParameters = {
|
||||
includeMetadata: false,
|
||||
allowDuplicates: false,
|
||||
duplexMode: false,
|
||||
splitMode: 'SPLIT_ALL',
|
||||
customPages: '',
|
||||
};
|
||||
|
||||
export const useSplitParameters = (): SplitParametersHook => {
|
||||
@@ -44,7 +48,11 @@ export const useSplitParameters = (): SplitParametersHook => {
|
||||
case SPLIT_METHODS.BY_PAGES:
|
||||
return params.pages.trim() !== "";
|
||||
case SPLIT_METHODS.BY_SECTIONS:
|
||||
return params.hDiv !== "" && params.vDiv !== "";
|
||||
if (params.hDiv === "" || params.vDiv === "") return false;
|
||||
if (params.splitMode === 'CUSTOM') {
|
||||
return (params.customPages || '').trim() !== "";
|
||||
}
|
||||
return true;
|
||||
case SPLIT_METHODS.BY_SIZE:
|
||||
case SPLIT_METHODS.BY_PAGE_COUNT:
|
||||
case SPLIT_METHODS.BY_DOC_COUNT:
|
||||
|
||||
@@ -28,6 +28,10 @@ i18n
|
||||
'convert.dpi': 'DPI',
|
||||
'convert.singleOrMultiple': 'Output',
|
||||
'convert.emailNote': 'Email attachments and embedded images will be included',
|
||||
'convert.pdfaOptions': 'PDF/A Options',
|
||||
'convert.outputFormat': 'Output Format',
|
||||
'convert.pdfaNote': 'PDF/A-1b is more compatible, PDF/A-2b supports more features, PDF/A-3b supports embedded files.',
|
||||
'convert.pdfaDigitalSignatureWarning': 'The PDF contains a digital signature. This will be removed in the next step.',
|
||||
'common.color': 'Color',
|
||||
'common.grayscale': 'Grayscale',
|
||||
'common.blackWhite': 'Black & White',
|
||||
|
||||
@@ -38,7 +38,7 @@ const FREE_LICENSE_INFO: LicenseInfo = {
|
||||
|
||||
const BASE_NO_LOGIN_CONFIG: AppConfig = {
|
||||
enableAnalytics: true,
|
||||
appVersion: '2.1.5',
|
||||
appVersion: '2.2.0',
|
||||
serverCertificateEnabled: false,
|
||||
enableAlphaFunctionality: false,
|
||||
serverPort: 8080,
|
||||
|
||||
@@ -152,6 +152,12 @@ describe('Convert Tool Integration Tests', () => {
|
||||
pdfaOptions: {
|
||||
outputFormat: ''
|
||||
},
|
||||
cbrOptions: {
|
||||
optimizeForEbook: false
|
||||
},
|
||||
pdfToCbrOptions: {
|
||||
dpi: 150
|
||||
},
|
||||
cbzOptions: {
|
||||
optimizeForEbook: false
|
||||
},
|
||||
@@ -225,6 +231,12 @@ describe('Convert Tool Integration Tests', () => {
|
||||
pdfaOptions: {
|
||||
outputFormat: ''
|
||||
},
|
||||
cbrOptions: {
|
||||
optimizeForEbook: false
|
||||
},
|
||||
pdfToCbrOptions: {
|
||||
dpi: 150
|
||||
},
|
||||
cbzOptions: {
|
||||
optimizeForEbook: false
|
||||
},
|
||||
@@ -276,6 +288,12 @@ describe('Convert Tool Integration Tests', () => {
|
||||
pdfaOptions: {
|
||||
outputFormat: ''
|
||||
},
|
||||
cbrOptions: {
|
||||
optimizeForEbook: false
|
||||
},
|
||||
pdfToCbrOptions: {
|
||||
dpi: 150
|
||||
},
|
||||
cbzOptions: {
|
||||
optimizeForEbook: false
|
||||
},
|
||||
@@ -336,6 +354,12 @@ describe('Convert Tool Integration Tests', () => {
|
||||
pdfaOptions: {
|
||||
outputFormat: ''
|
||||
},
|
||||
cbrOptions: {
|
||||
optimizeForEbook: false
|
||||
},
|
||||
pdfToCbrOptions: {
|
||||
dpi: 150
|
||||
},
|
||||
cbzOptions: {
|
||||
optimizeForEbook: false
|
||||
},
|
||||
@@ -400,6 +424,12 @@ describe('Convert Tool Integration Tests', () => {
|
||||
pdfaOptions: {
|
||||
outputFormat: ''
|
||||
},
|
||||
cbrOptions: {
|
||||
optimizeForEbook: false
|
||||
},
|
||||
pdfToCbrOptions: {
|
||||
dpi: 150
|
||||
},
|
||||
cbzOptions: {
|
||||
optimizeForEbook: false
|
||||
},
|
||||
@@ -462,6 +492,12 @@ describe('Convert Tool Integration Tests', () => {
|
||||
pdfaOptions: {
|
||||
outputFormat: ''
|
||||
},
|
||||
cbrOptions: {
|
||||
optimizeForEbook: false
|
||||
},
|
||||
pdfToCbrOptions: {
|
||||
dpi: 150
|
||||
},
|
||||
cbzOptions: {
|
||||
optimizeForEbook: false
|
||||
},
|
||||
@@ -520,6 +556,12 @@ describe('Convert Tool Integration Tests', () => {
|
||||
pdfaOptions: {
|
||||
outputFormat: ''
|
||||
},
|
||||
cbrOptions: {
|
||||
optimizeForEbook: false
|
||||
},
|
||||
pdfToCbrOptions: {
|
||||
dpi: 150
|
||||
},
|
||||
cbzOptions: {
|
||||
optimizeForEbook: false
|
||||
},
|
||||
@@ -575,6 +617,12 @@ describe('Convert Tool Integration Tests', () => {
|
||||
pdfaOptions: {
|
||||
outputFormat: ''
|
||||
},
|
||||
cbrOptions: {
|
||||
optimizeForEbook: false
|
||||
},
|
||||
pdfToCbrOptions: {
|
||||
dpi: 150
|
||||
},
|
||||
cbzOptions: {
|
||||
optimizeForEbook: false
|
||||
},
|
||||
@@ -632,6 +680,12 @@ describe('Convert Tool Integration Tests', () => {
|
||||
pdfaOptions: {
|
||||
outputFormat: ''
|
||||
},
|
||||
cbrOptions: {
|
||||
optimizeForEbook: false
|
||||
},
|
||||
pdfToCbrOptions: {
|
||||
dpi: 150
|
||||
},
|
||||
cbzOptions: {
|
||||
optimizeForEbook: false
|
||||
},
|
||||
@@ -686,6 +740,12 @@ describe('Convert Tool Integration Tests', () => {
|
||||
pdfaOptions: {
|
||||
outputFormat: ''
|
||||
},
|
||||
cbrOptions: {
|
||||
optimizeForEbook: false
|
||||
},
|
||||
pdfToCbrOptions: {
|
||||
dpi: 150
|
||||
},
|
||||
cbzOptions: {
|
||||
optimizeForEbook: false
|
||||
},
|
||||
@@ -746,6 +806,12 @@ describe('Convert Tool Integration Tests', () => {
|
||||
pdfaOptions: {
|
||||
outputFormat: ''
|
||||
},
|
||||
cbrOptions: {
|
||||
optimizeForEbook: false
|
||||
},
|
||||
pdfToCbrOptions: {
|
||||
dpi: 150
|
||||
},
|
||||
cbzOptions: {
|
||||
optimizeForEbook: false
|
||||
},
|
||||
@@ -805,6 +871,12 @@ describe('Convert Tool Integration Tests', () => {
|
||||
pdfaOptions: {
|
||||
outputFormat: ''
|
||||
},
|
||||
cbrOptions: {
|
||||
optimizeForEbook: false
|
||||
},
|
||||
pdfToCbrOptions: {
|
||||
dpi: 150
|
||||
},
|
||||
cbzOptions: {
|
||||
optimizeForEbook: false
|
||||
},
|
||||
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
valueOr,
|
||||
} from '@app/tools/pdfTextEditor/pdfTextEditorUtils';
|
||||
import PdfTextEditorView from '@app/components/tools/pdfTextEditor/PdfTextEditorView';
|
||||
import PdfTextEditorSidebar from '@app/components/tools/pdfTextEditor/PdfTextEditorSidebar';
|
||||
import type { PDFDocumentProxy } from 'pdfjs-dist';
|
||||
|
||||
const WORKBENCH_VIEW_ID = 'pdfTextEditorWorkbench';
|
||||
@@ -228,6 +229,7 @@ const PdfTextEditor = ({ onComplete, onError }: BaseToolProps) => {
|
||||
const [groupingMode, setGroupingMode] = useState<'auto' | 'paragraph' | 'singleLine'>('auto');
|
||||
const [hasVectorPreview, setHasVectorPreview] = useState(false);
|
||||
const [pagePreviews, setPagePreviews] = useState<Map<number, string>>(new Map());
|
||||
const [autoScaleText, setAutoScaleText] = useState(true);
|
||||
|
||||
// Lazy loading state
|
||||
const [isLazyMode, setIsLazyMode] = useState(false);
|
||||
@@ -1565,6 +1567,8 @@ const PdfTextEditor = ({ onComplete, onError }: BaseToolProps) => {
|
||||
hasChanges,
|
||||
forceSingleTextElement,
|
||||
groupingMode,
|
||||
autoScaleText,
|
||||
onAutoScaleTextChange: setAutoScaleText,
|
||||
requestPagePreview,
|
||||
onSelectPage: handleSelectPage,
|
||||
onGroupEdit: handleGroupTextChange,
|
||||
@@ -1613,6 +1617,7 @@ const PdfTextEditor = ({ onComplete, onError }: BaseToolProps) => {
|
||||
selectedPage,
|
||||
forceSingleTextElement,
|
||||
groupingMode,
|
||||
autoScaleText,
|
||||
requestPagePreview,
|
||||
setForceSingleTextElement,
|
||||
handleLoadFileFromDropzone,
|
||||
@@ -1683,12 +1688,17 @@ const PdfTextEditor = ({ onComplete, onError }: BaseToolProps) => {
|
||||
icon: <DescriptionIcon fontSize="small" />,
|
||||
component: PdfTextEditorView,
|
||||
});
|
||||
setLeftPanelView('hidden');
|
||||
setCustomWorkbenchViewData(WORKBENCH_VIEW_ID, latestViewDataRef.current);
|
||||
|
||||
return () => {
|
||||
// Clear backend cache if we were using lazy loading
|
||||
clearCachedJob(cachedJobIdRef.current);
|
||||
clearCustomWorkbenchViewData(WORKBENCH_VIEW_ID);
|
||||
unregisterCustomWorkbenchView(WORKBENCH_VIEW_ID);
|
||||
};
|
||||
}, [
|
||||
registerCustomWorkbenchView,
|
||||
setCustomWorkbenchViewData,
|
||||
setLeftPanelView,
|
||||
viewLabel,
|
||||
]);
|
||||
|
||||
@@ -1723,12 +1733,12 @@ const PdfTextEditor = ({ onComplete, onError }: BaseToolProps) => {
|
||||
setCustomWorkbenchViewData(WORKBENCH_VIEW_ID, viewData);
|
||||
}, [setCustomWorkbenchViewData, viewData]);
|
||||
|
||||
// All editing happens in the custom workbench view.
|
||||
return null;
|
||||
// Render the sidebar with settings while editing happens in the custom workbench view.
|
||||
return <PdfTextEditorSidebar data={viewData} />;
|
||||
};
|
||||
|
||||
(PdfTextEditor as ToolComponent).tool = () => {
|
||||
throw new Error('PDF JSON Editor does not support automation operations.');
|
||||
throw new Error('PDF Text Editor does not support automation operations.');
|
||||
};
|
||||
|
||||
(PdfTextEditor as ToolComponent).getDefaultParameters = () => ({
|
||||
|
||||
@@ -201,6 +201,8 @@ export interface PdfTextEditorViewData {
|
||||
hasChanges: boolean;
|
||||
forceSingleTextElement: boolean;
|
||||
groupingMode: 'auto' | 'paragraph' | 'singleLine';
|
||||
autoScaleText: boolean;
|
||||
onAutoScaleTextChange: (value: boolean) => void;
|
||||
requestPagePreview: (pageIndex: number, scale: number) => void;
|
||||
onSelectPage: (pageIndex: number) => void;
|
||||
onGroupEdit: (pageIndex: number, groupId: string, value: string) => void;
|
||||
|
||||
@@ -160,12 +160,16 @@ export interface PdfPerPageInfo {
|
||||
export interface PdfEmbeddedFileInfo {
|
||||
Name?: string;
|
||||
FileSize?: number;
|
||||
MimeType?: string;
|
||||
CreationDate?: string;
|
||||
ModificationDate?: string;
|
||||
}
|
||||
|
||||
/** Attachment info */
|
||||
export interface PdfAttachmentInfo {
|
||||
Name?: string;
|
||||
Description?: string;
|
||||
FileSize?: number;
|
||||
}
|
||||
|
||||
/** JavaScript info */
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
export interface TransparencyOptions {
|
||||
lowerBound?: { r: number; g: number; b: number };
|
||||
upperBound?: { r: number; g: number; b: number };
|
||||
autoDetectCorner?: boolean;
|
||||
tolerance?: number;
|
||||
}
|
||||
|
||||
const DEFAULT_LOWER_BOUND = { r: 200, g: 200, b: 200 };
|
||||
const DEFAULT_UPPER_BOUND = { r: 255, g: 255, b: 255 }; // #FFFFFF
|
||||
|
||||
export async function removeWhiteBackground(
|
||||
imageFile: File | string,
|
||||
options: TransparencyOptions = {}
|
||||
): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const img = new Image();
|
||||
|
||||
img.onload = () => {
|
||||
try {
|
||||
const result = processImageTransparency(img, options);
|
||||
resolve(result);
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
};
|
||||
|
||||
img.onerror = () => {
|
||||
reject(new Error('Failed to load image'));
|
||||
};
|
||||
|
||||
if (typeof imageFile === 'string') {
|
||||
img.src = imageFile;
|
||||
} else {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => {
|
||||
img.src = e.target?.result as string;
|
||||
};
|
||||
reader.onerror = () => {
|
||||
reject(new Error('Failed to read image file'));
|
||||
};
|
||||
reader.readAsDataURL(imageFile);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function processImageTransparency(
|
||||
img: HTMLImageElement,
|
||||
options: TransparencyOptions
|
||||
): string {
|
||||
const canvas = document.createElement('canvas');
|
||||
const ctx = canvas.getContext('2d');
|
||||
|
||||
if (!ctx) {
|
||||
throw new Error('Failed to get canvas context');
|
||||
}
|
||||
|
||||
canvas.width = img.width;
|
||||
canvas.height = img.height;
|
||||
|
||||
ctx.drawImage(img, 0, 0);
|
||||
|
||||
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
||||
const data = imageData.data;
|
||||
|
||||
let lowerBound = options.lowerBound || DEFAULT_LOWER_BOUND;
|
||||
let upperBound = options.upperBound || DEFAULT_UPPER_BOUND;
|
||||
|
||||
if (options.autoDetectCorner) {
|
||||
const cornerColor = detectCornerColor(imageData);
|
||||
const tolerance = options.tolerance || 10;
|
||||
lowerBound = {
|
||||
r: Math.max(0, cornerColor.r - tolerance),
|
||||
g: Math.max(0, cornerColor.g - tolerance),
|
||||
b: Math.max(0, cornerColor.b - tolerance)
|
||||
};
|
||||
upperBound = {
|
||||
r: Math.min(255, cornerColor.r + tolerance),
|
||||
g: Math.min(255, cornerColor.g + tolerance),
|
||||
b: Math.min(255, cornerColor.b + tolerance)
|
||||
};
|
||||
}
|
||||
|
||||
for (let i = 0; i < data.length; i += 4) {
|
||||
const r = data[i];
|
||||
const g = data[i + 1];
|
||||
const b = data[i + 2];
|
||||
|
||||
if (
|
||||
r >= lowerBound.r && r <= upperBound.r &&
|
||||
g >= lowerBound.g && g <= upperBound.g &&
|
||||
b >= lowerBound.b && b <= upperBound.b
|
||||
) {
|
||||
data[i + 3] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
ctx.putImageData(imageData, 0, 0);
|
||||
|
||||
return canvas.toDataURL('image/png');
|
||||
}
|
||||
|
||||
|
||||
function detectCornerColor(imageData: ImageData): { r: number; g: number; b: number } {
|
||||
const { width, height, data } = imageData;
|
||||
|
||||
const sampleSize = 5;
|
||||
const corners = [
|
||||
{ x: 0, y: 0 }, // top-left
|
||||
{ x: width - sampleSize, y: 0 }, // top-right
|
||||
{ x: 0, y: height - sampleSize }, // bottom-left
|
||||
{ x: width - sampleSize, y: height - sampleSize } // bottom-right
|
||||
];
|
||||
|
||||
let totalR = 0, totalG = 0, totalB = 0;
|
||||
let samples = 0;
|
||||
|
||||
corners.forEach(corner => {
|
||||
for (let dy = 0; dy < sampleSize; dy++) {
|
||||
for (let dx = 0; dx < sampleSize; dx++) {
|
||||
const x = Math.min(width - 1, Math.max(0, corner.x + dx));
|
||||
const y = Math.min(height - 1, Math.max(0, corner.y + dy));
|
||||
const i = (y * width + x) * 4;
|
||||
|
||||
totalR += data[i];
|
||||
totalG += data[i + 1];
|
||||
totalB += data[i + 2];
|
||||
samples++;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
r: Math.round(totalR / samples),
|
||||
g: Math.round(totalG / samples),
|
||||
b: Math.round(totalB / samples)
|
||||
};
|
||||
}
|
||||
@@ -28,6 +28,8 @@ export const URL_TO_TOOL_MAP: Record<string, ToolId> = {
|
||||
'/pdf-to-pdfa': 'convert',
|
||||
'/pdf-to-word': 'convert',
|
||||
'/pdf-to-xml': 'convert',
|
||||
'/cbr-to-pdf': 'convert',
|
||||
'/pdf-to-cbr': 'convert',
|
||||
'/cbz-to-pdf': 'convert',
|
||||
'/pdf-to-cbz': 'convert',
|
||||
|
||||
|
||||
+1
@@ -422,6 +422,7 @@ export default function AdminConnectionsSection() {
|
||||
key={provider.id}
|
||||
provider={provider}
|
||||
isConfigured={false}
|
||||
settings={getProviderSettings(provider)}
|
||||
onSave={(providerSettings) => handleProviderSave(provider, providerSettings)}
|
||||
disabled={!loginEnabled}
|
||||
/>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user