Compare commits
30
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
15a7f10dec | ||
|
|
65a5d05713 | ||
|
|
8632ed9875 | ||
|
|
3af5970424 | ||
|
|
3c8fb8ac96 | ||
|
|
251ad63ea6 | ||
|
|
c7b713ac80 | ||
|
|
d4d4538630 | ||
|
|
d2677e64dd | ||
|
|
0ae108ca11 | ||
|
|
5236c1ccf6 | ||
|
|
72389f5872 | ||
|
|
a284dbfc15 | ||
|
|
ff078b9d88 | ||
|
|
18be8f4692 | ||
|
|
dd09f7b7cf | ||
|
|
8394b71014 | ||
|
|
b4dd7afe03 | ||
|
|
ef7a3fa933 | ||
|
|
772ed6f52b | ||
|
|
4a1039fa97 | ||
|
|
c158664d2c | ||
|
|
d9caa3482c | ||
|
|
c44b7e229c | ||
|
|
f38e3d2b2c | ||
|
|
b6e675fab3 | ||
|
|
91bf9abbaa | ||
|
|
faf0a3555e | ||
|
|
fbc5d91c2c | ||
|
|
0c96133544 |
+5
-8
@@ -2,20 +2,17 @@
|
||||
* @Frooodle @Ludy87 @jbrunton96 @ConnorYoh
|
||||
|
||||
# Backend
|
||||
/app/** @DarioGii @Frooodle @Ludy87 @jbrunton96 @ConnorYoh
|
||||
|
||||
#V1 frontend
|
||||
/app/core/src/main/resources/static/** @reecebrowne @ConnorYoh @EthanHealy01 @jbrunton96 @Frooodle @Ludy87
|
||||
/app/core/src/main/resources/templates/** @reecebrowne @ConnorYoh @EthanHealy01 @jbrunton96 @Frooodle @Ludy87
|
||||
/app/** @DarioGii @Frooodle @Ludy87 @jbrunton96 @ConnorYoh @balazs-szucs
|
||||
|
||||
#V2 frontend
|
||||
/frontend/** @reecebrowne @ConnorYoh @EthanHealy01 @jbrunton96 @Frooodle
|
||||
/frontend/** @reecebrowne @ConnorYoh @EthanHealy01 @jbrunton96 @Frooodle @balazs-szucs
|
||||
/app/core/src/main/resources/static/** @reecebrowne @ConnorYoh @EthanHealy01 @jbrunton96 @Frooodle @Ludy87 @balazs-szucs
|
||||
|
||||
#V2 docker
|
||||
/docker/backend/** @Frooodle @Ludy87 @DarioGii @Ludy87
|
||||
/docker/backend/** @Frooodle @Ludy87 @DarioGii
|
||||
/docker/frontend/** @reecebrowne @ConnorYoh @EthanHealy01 @jbrunton96 @Frooodle @Ludy87
|
||||
/docker/compose/** @reecebrowne @ConnorYoh @EthanHealy01 @DarioGii @jbrunton96 @Frooodle @Ludy87
|
||||
|
||||
|
||||
#GHA (All users)
|
||||
/.github/** @reecebrowne @ConnorYoh @EthanHealy01 @DarioGii @jbrunton96 @Frooodle @Ludy87
|
||||
/.github/** @reecebrowne @ConnorYoh @EthanHealy01 @DarioGii @jbrunton96 @Frooodle @Ludy87 @balazs-szucs
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
"reecebrowne",
|
||||
"DarioGii",
|
||||
"ConnorYoh",
|
||||
"EthanHealy01"
|
||||
"EthanHealy01",
|
||||
"balazs-szucs"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "gradle" # See documentation for possible values
|
||||
directories:
|
||||
directories:
|
||||
- "/" # Location of package manifests
|
||||
- "/app/common"
|
||||
- "/app/core"
|
||||
|
||||
+1
-1
@@ -200,4 +200,4 @@
|
||||
from_name: "tauri"
|
||||
- name: "license-review-required"
|
||||
color: "EDEDED"
|
||||
description: "This PR requires a license review"
|
||||
description: "This PR requires a license review"
|
||||
|
||||
@@ -271,7 +271,7 @@ jobs:
|
||||
- name: Set up SSH
|
||||
run: |
|
||||
mkdir -p ~/.ssh/
|
||||
echo "${{ secrets.VPS_SSH_KEY }}" > ../private.key
|
||||
echo "${{ secrets.NEW_VPS_SSH_KEY }}" > ../private.key
|
||||
sudo chmod 600 ../private.key
|
||||
|
||||
- name: Deploy V2 to VPS
|
||||
@@ -316,16 +316,16 @@ jobs:
|
||||
ports:
|
||||
- "${V2_PORT}:80" # Frontend port (same as regular PRs)
|
||||
environment:
|
||||
VITE_API_BASE_URL: "http://${{ secrets.VPS_HOST }}:${BACKEND_PORT}"
|
||||
VITE_API_BASE_URL: "http://${{ secrets.NEW_VPS_HOST }}:${BACKEND_PORT}"
|
||||
depends_on:
|
||||
- stirling-pdf-v2-backend
|
||||
restart: on-failure:5
|
||||
EOF
|
||||
|
||||
# Deploy to VPS
|
||||
scp -i ../private.key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null docker-compose.yml ${{ secrets.VPS_USERNAME }}@${{ secrets.VPS_HOST }}:/tmp/docker-compose-v2.yml
|
||||
scp -i ../private.key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null docker-compose.yml ${{ secrets.NEW_VPS_USERNAME }}@${{ secrets.NEW_VPS_HOST }}:/tmp/docker-compose-v2.yml
|
||||
|
||||
ssh -i ../private.key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -T ${{ secrets.VPS_USERNAME }}@${{ secrets.VPS_HOST }} << ENDSSH
|
||||
ssh -i ../private.key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -T ${{ secrets.NEW_VPS_USERNAME }}@${{ secrets.NEW_VPS_HOST }} << ENDSSH
|
||||
# Create V2 PR-specific directories
|
||||
mkdir -p /stirling/V2-PR-${{ needs.check-pr.outputs.pr_number }}/{data,config,logs}
|
||||
|
||||
@@ -375,7 +375,7 @@ jobs:
|
||||
}
|
||||
}
|
||||
|
||||
const deploymentUrl = `http://${{ secrets.VPS_HOST }}:${v2Port}`;
|
||||
const deploymentUrl = `http://${{ secrets.NEW_VPS_HOST }}:${v2Port}`;
|
||||
const httpsUrl = `https://${v2Port}.ssl.stirlingpdf.cloud`;
|
||||
|
||||
const commentBody = `## 🚀 V2 Auto-Deployment Complete!\n\n` +
|
||||
@@ -450,12 +450,12 @@ jobs:
|
||||
- name: Set up SSH
|
||||
run: |
|
||||
mkdir -p ~/.ssh/
|
||||
echo "${{ secrets.VPS_SSH_KEY }}" > ../private.key
|
||||
echo "${{ secrets.NEW_VPS_SSH_KEY }}" > ../private.key
|
||||
sudo chmod 600 ../private.key
|
||||
|
||||
- name: Cleanup V2 deployment
|
||||
run: |
|
||||
ssh -i ../private.key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -T ${{ secrets.VPS_USERNAME }}@${{ secrets.VPS_HOST }} << 'ENDSSH'
|
||||
ssh -i ../private.key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -T ${{ secrets.NEW_VPS_USERNAME }}@${{ secrets.NEW_VPS_HOST }} << 'ENDSSH'
|
||||
if [ -d "/stirling/V2-PR-${{ github.event.pull_request.number }}" ]; then
|
||||
echo "Found V2 PR directory, proceeding with cleanup..."
|
||||
|
||||
|
||||
@@ -190,7 +190,7 @@ jobs:
|
||||
- name: Set up SSH
|
||||
run: |
|
||||
mkdir -p ~/.ssh/
|
||||
echo "${{ secrets.VPS_SSH_KEY }}" > ../private.key
|
||||
echo "${{ secrets.NEW_VPS_SSH_KEY }}" > ../private.key
|
||||
sudo chmod 600 ../private.key
|
||||
|
||||
- name: Deploy to VPS
|
||||
@@ -252,9 +252,9 @@ jobs:
|
||||
EOF
|
||||
|
||||
# Then copy the file and execute commands
|
||||
scp -i ../private.key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null docker-compose.yml ${{ secrets.VPS_USERNAME }}@${{ secrets.VPS_HOST }}:/tmp/docker-compose.yml
|
||||
scp -i ../private.key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null docker-compose.yml ${{ secrets.NEW_VPS_USERNAME }}@${{ secrets.NEW_VPS_HOST }}:/tmp/docker-compose.yml
|
||||
|
||||
ssh -i ../private.key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -T ${{ secrets.VPS_USERNAME }}@${{ secrets.VPS_HOST }} << ENDSSH
|
||||
ssh -i ../private.key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -T ${{ secrets.NEW_VPS_USERNAME }}@${{ secrets.NEW_VPS_HOST }} << ENDSSH
|
||||
# Create PR-specific directories
|
||||
mkdir -p /stirling/PR-${{ needs.check-comment.outputs.pr_number }}/{data,config,logs}
|
||||
|
||||
@@ -336,7 +336,7 @@ jobs:
|
||||
const prNumber = ${{ needs.check-comment.outputs.pr_number }};
|
||||
const securityStatus = process.env.security_status || "Security Disabled";
|
||||
|
||||
const deploymentUrl = `http://${{ secrets.VPS_HOST }}:${prNumber}`;
|
||||
const deploymentUrl = `http://${{ secrets.NEW_VPS_HOST }}:${prNumber}`;
|
||||
const commentBody = `## 🚀 PR Test Deployment\n\n` +
|
||||
`Your PR has been deployed for testing!\n\n` +
|
||||
`🔗 **Test URL:** [${deploymentUrl}](${deploymentUrl})\n` +
|
||||
|
||||
@@ -8,7 +8,7 @@ permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
SERVER_IP: ${{ secrets.VPS_IP }} # Add this to your GitHub secrets
|
||||
SERVER_IP: ${{ secrets.NEW_VPS_IP }} # Add this to your GitHub secrets
|
||||
CLEANUP_PERFORMED: "false" # Add flag to track if cleanup occurred
|
||||
|
||||
jobs:
|
||||
@@ -100,14 +100,14 @@ jobs:
|
||||
if: steps.remove-label-comment.outputs.present == 'true'
|
||||
run: |
|
||||
mkdir -p ~/.ssh/
|
||||
echo "${{ secrets.VPS_SSH_KEY }}" > ../private.key
|
||||
echo "${{ secrets.NEW_VPS_SSH_KEY }}" > ../private.key
|
||||
sudo chmod 600 ../private.key
|
||||
|
||||
- name: Cleanup PR deployment
|
||||
if: steps.remove-label-comment.outputs.present == 'true'
|
||||
id: cleanup
|
||||
run: |
|
||||
ssh -i ../private.key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -T ${{ secrets.VPS_USERNAME }}@${{ secrets.VPS_HOST }} << 'ENDSSH'
|
||||
ssh -i ../private.key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -T ${{ secrets.NEW_VPS_USERNAME }}@${{ secrets.NEW_VPS_HOST }} << 'ENDSSH'
|
||||
if [ -d "/stirling/PR-${{ github.event.pull_request.number }}" ]; then
|
||||
echo "Found PR directory, proceeding with cleanup..."
|
||||
|
||||
|
||||
@@ -97,6 +97,7 @@ jobs:
|
||||
with:
|
||||
name: test-reports-jdk-${{ matrix.jdk-version }}-spring-security-${{ matrix.spring-security }}
|
||||
path: |
|
||||
app/**/build/reports/jacoco/test
|
||||
app/**/build/reports/tests/
|
||||
app/**/build/test-results/
|
||||
app/**/build/reports/problems/
|
||||
@@ -104,6 +105,17 @@ jobs:
|
||||
retention-days: 3
|
||||
if-no-files-found: warn
|
||||
|
||||
- name: Add coverage to PR with spring security ${{ matrix.spring-security }} and JDK ${{ matrix.jdk-version }}
|
||||
id: jacoco
|
||||
uses: madrapps/jacoco-report@50d3aff4548aa991e6753342d9ba291084e63848 # v1.7.2
|
||||
with:
|
||||
paths: |
|
||||
${{ github.workspace }}/**/build/reports/jacoco/test/jacocoTestReport.xml
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
min-coverage-overall: 10
|
||||
min-coverage-changed-files: 0
|
||||
comment-type: summary
|
||||
|
||||
check-generateOpenApiDocs:
|
||||
if: needs.files-changed.outputs.openapi == 'true'
|
||||
needs: [files-changed]
|
||||
|
||||
@@ -119,7 +119,7 @@ jobs:
|
||||
- name: Set up SSH
|
||||
run: |
|
||||
mkdir -p ~/.ssh/
|
||||
echo "${{ secrets.VPS_SSH_KEY }}" > ../private.key
|
||||
echo "${{ secrets.NEW_VPS_SSH_KEY }}" > ../private.key
|
||||
chmod 600 ../private.key
|
||||
|
||||
- name: Deploy to VPS on port 3000
|
||||
@@ -158,17 +158,17 @@ jobs:
|
||||
ports:
|
||||
- "3000:80"
|
||||
environment:
|
||||
VITE_API_BASE_URL: "http://${{ secrets.VPS_HOST }}:13000"
|
||||
VITE_API_BASE_URL: "http://${{ secrets.NEW_VPS_HOST }}:13000"
|
||||
depends_on:
|
||||
- backend
|
||||
restart: on-failure:5
|
||||
EOF
|
||||
|
||||
# Copy to remote with unique name
|
||||
scp -i ../private.key -o StrictHostKeyChecking=no $UNIQUE_NAME ${{ secrets.VPS_USERNAME }}@${{ secrets.VPS_HOST }}:/tmp/$UNIQUE_NAME
|
||||
scp -i ../private.key -o StrictHostKeyChecking=no $UNIQUE_NAME ${{ secrets.NEW_VPS_USERNAME }}@${{ secrets.NEW_VPS_HOST }}:/tmp/$UNIQUE_NAME
|
||||
|
||||
# SSH and rename/move atomically to avoid interference
|
||||
ssh -i ../private.key -o StrictHostKeyChecking=no ${{ secrets.VPS_USERNAME }}@${{ secrets.VPS_HOST }} << ENDSSH
|
||||
ssh -i ../private.key -o StrictHostKeyChecking=no ${{ secrets.NEW_VPS_USERNAME }}@${{ secrets.NEW_VPS_HOST }} << ENDSSH
|
||||
mkdir -p /stirling/V2/{data,config,logs}
|
||||
mv /tmp/$UNIQUE_NAME /stirling/V2/docker-compose.yml
|
||||
cd /stirling/V2
|
||||
|
||||
@@ -268,7 +268,7 @@ jobs:
|
||||
|
||||
- name: Install frontend dependencies
|
||||
working-directory: ./frontend
|
||||
run: npm install
|
||||
run: npm ci
|
||||
|
||||
# DigiCert KeyLocker Setup (Cloud HSM)
|
||||
- name: Setup DigiCert KeyLocker
|
||||
|
||||
@@ -1,245 +0,0 @@
|
||||
name: Push Docker Image - V2 Branch
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- V2-master
|
||||
|
||||
# cancel in-progress jobs if a new job is triggered
|
||||
# This is useful to avoid running multiple builds for the same branch if a new commit is pushed
|
||||
# or a pull request is updated.
|
||||
# It helps to save resources and time by ensuring that only the latest commit is built and tested
|
||||
# This is particularly useful for long-running jobs that may take a while to complete.
|
||||
# The `group` is set to a combination of the workflow name, event name, and branch name.
|
||||
# This ensures that jobs are grouped by the workflow and branch, allowing for cancellation of
|
||||
# in-progress jobs when a new commit is pushed to the same branch or a new pull request is opened.
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.ref_name || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
push:
|
||||
if: ${{ vars.CI_PROFILE != 'lite' }}
|
||||
runs-on: ubuntu-24.04-8core
|
||||
permissions:
|
||||
packages: write
|
||||
id-token: write
|
||||
steps:
|
||||
- name: Harden Runner
|
||||
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
|
||||
with:
|
||||
egress-policy: audit
|
||||
|
||||
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||
|
||||
- name: Set up JDK 21
|
||||
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
|
||||
with:
|
||||
java-version: "21"
|
||||
distribution: "temurin"
|
||||
|
||||
- uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
|
||||
with:
|
||||
gradle-version: 8.14
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
id: buildx
|
||||
uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1
|
||||
|
||||
- name: Get version number
|
||||
id: versionNumber
|
||||
run: echo "versionNumber=$(./gradlew printVersion --quiet | tail -1)" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Install cosign
|
||||
if: github.ref == 'refs/heads/V2-master'
|
||||
uses: sigstore/cosign-installer@d7543c93d881b35a8faa02e8e3605f69b7a1ce62 # v3.10.0
|
||||
with:
|
||||
cosign-release: "v2.4.1"
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@9780b0c442fbb1117ed29e0efdff1e18412f7567 # v3.3.0
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_HUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_HUB_API }}
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@9780b0c442fbb1117ed29e0efdff1e18412f7567 # v3.3.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ github.token }}
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@29109295f81e9208d7d86ff1c6c12d2833863392 # v3.6.0
|
||||
|
||||
- name: Convert repository owner to lowercase
|
||||
id: repoowner
|
||||
run: echo "lowercase=$(echo ${{ github.repository_owner }} | awk '{print tolower($0)}')" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Generate tags for latest (V2-master branch - production)
|
||||
id: meta
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
if: github.ref == 'refs/heads/V2-master'
|
||||
with:
|
||||
images: |
|
||||
${{ secrets.DOCKER_HUB_USERNAME }}/s-pdf
|
||||
ghcr.io/${{ steps.repoowner.outputs.lowercase }}/s-pdf
|
||||
ghcr.io/${{ steps.repoowner.outputs.lowercase }}/stirling-pdf
|
||||
${{ secrets.DOCKER_HUB_ORG_USERNAME }}/stirling-pdf
|
||||
tags: |
|
||||
type=raw,value=${{ steps.versionNumber.outputs.versionNumber }}
|
||||
type=raw,value=latest
|
||||
|
||||
- name: Generate tags for latest (V1_V2_merge branch - test)
|
||||
id: meta-test
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
if: github.ref == 'refs/heads/V1_V2_merge'
|
||||
with:
|
||||
images: |
|
||||
ghcr.io/stirling-tools/stirling-pdf-test
|
||||
tags: |
|
||||
type=raw,value=${{ steps.versionNumber.outputs.versionNumber }}
|
||||
type=raw,value=latest
|
||||
|
||||
- name: Build and push Unified Dockerfile (latest variant)
|
||||
id: build-push-latest
|
||||
uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||
with:
|
||||
builder: ${{ steps.buildx.outputs.name }}
|
||||
context: .
|
||||
file: ./docker/embedded/Dockerfile
|
||||
push: true
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
tags: ${{ github.ref == 'refs/heads/V2-master' && steps.meta.outputs.tags || steps.meta-test.outputs.tags }}
|
||||
labels: ${{ github.ref == 'refs/heads/V2-master' && steps.meta.outputs.labels || steps.meta-test.outputs.labels }}
|
||||
build-args: VERSION_TAG=${{ steps.versionNumber.outputs.versionNumber }}
|
||||
platforms: linux/amd64,linux/arm64/v8
|
||||
provenance: true
|
||||
sbom: true
|
||||
|
||||
- name: Sign regular images
|
||||
if: github.ref == 'refs/heads/V2-master'
|
||||
env:
|
||||
DIGEST: ${{ steps.build-push-latest.outputs.digest }}
|
||||
TAGS: ${{ steps.meta.outputs.tags }}
|
||||
COSIGN_PRIVATE_KEY: ${{ secrets.COSIGN_PRIVATE_KEY }}
|
||||
COSIGN_PASSWORD: ${{ secrets.COSIGN_PASSWORD }}
|
||||
run: |
|
||||
echo "$TAGS" | tr ',' '\n' | while read -r tag; do
|
||||
cosign sign --yes \
|
||||
--key env://COSIGN_PRIVATE_KEY \
|
||||
"${tag}@${DIGEST}"
|
||||
done
|
||||
|
||||
- name: Generate tags for latest-fat (V2-master branch - production)
|
||||
id: meta-fat
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
if: github.ref == 'refs/heads/V2-master'
|
||||
with:
|
||||
images: |
|
||||
${{ secrets.DOCKER_HUB_USERNAME }}/s-pdf
|
||||
ghcr.io/${{ steps.repoowner.outputs.lowercase }}/s-pdf
|
||||
ghcr.io/${{ steps.repoowner.outputs.lowercase }}/stirling-pdf
|
||||
${{ secrets.DOCKER_HUB_ORG_USERNAME }}/stirling-pdf
|
||||
tags: |
|
||||
type=raw,value=${{ steps.versionNumber.outputs.versionNumber }}-fat
|
||||
type=raw,value=latest-fat
|
||||
|
||||
- name: Generate tags for latest-fat (V1_V2_merge branch - test)
|
||||
id: meta-fat-test
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
if: github.ref == 'refs/heads/V1_V2_merge'
|
||||
with:
|
||||
images: |
|
||||
ghcr.io/stirling-tools/stirling-pdf-test
|
||||
tags: |
|
||||
type=raw,value=${{ steps.versionNumber.outputs.versionNumber }}-fat
|
||||
type=raw,value=latest-fat
|
||||
|
||||
- name: Build and push Unified Dockerfile (fat variant)
|
||||
id: build-push-fat
|
||||
uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||
with:
|
||||
builder: ${{ steps.buildx.outputs.name }}
|
||||
context: .
|
||||
file: ./docker/embedded/Dockerfile.fat
|
||||
push: true
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
tags: ${{ github.ref == 'refs/heads/V2-master' && steps.meta-fat.outputs.tags || steps.meta-fat-test.outputs.tags }}
|
||||
labels: ${{ github.ref == 'refs/heads/V2-master' && steps.meta-fat.outputs.labels || steps.meta-fat-test.outputs.labels }}
|
||||
build-args: VERSION_TAG=${{ steps.versionNumber.outputs.versionNumber }}
|
||||
platforms: linux/amd64,linux/arm64/v8
|
||||
provenance: true
|
||||
sbom: true
|
||||
|
||||
- name: Sign fat images
|
||||
if: github.ref == 'refs/heads/V2-master'
|
||||
env:
|
||||
DIGEST: ${{ steps.build-push-fat.outputs.digest }}
|
||||
TAGS: ${{ steps.meta-fat.outputs.tags }}
|
||||
COSIGN_PRIVATE_KEY: ${{ secrets.COSIGN_PRIVATE_KEY }}
|
||||
COSIGN_PASSWORD: ${{ secrets.COSIGN_PASSWORD }}
|
||||
run: |
|
||||
echo "$TAGS" | tr ',' '\n' | while read -r tag; do
|
||||
cosign sign --key env://COSIGN_PRIVATE_KEY --yes "${tag}@${DIGEST}"
|
||||
done
|
||||
|
||||
- name: Generate tags for ultra-lite (V2-master branch - production)
|
||||
id: meta-lite
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
if: github.ref == 'refs/heads/V2-master'
|
||||
with:
|
||||
images: |
|
||||
${{ secrets.DOCKER_HUB_USERNAME }}/s-pdf
|
||||
ghcr.io/${{ steps.repoowner.outputs.lowercase }}/s-pdf
|
||||
ghcr.io/${{ steps.repoowner.outputs.lowercase }}/stirling-pdf
|
||||
${{ secrets.DOCKER_HUB_ORG_USERNAME }}/stirling-pdf
|
||||
tags: |
|
||||
type=raw,value=${{ steps.versionNumber.outputs.versionNumber }}-ultra-lite
|
||||
type=raw,value=latest-ultra-lite
|
||||
|
||||
- name: Generate tags for ultra-lite (V1_V2_merge branch - test)
|
||||
id: meta-lite-test
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
if: github.ref == 'refs/heads/V1_V2_merge'
|
||||
with:
|
||||
images: |
|
||||
ghcr.io/stirling-tools/stirling-pdf-test
|
||||
tags: |
|
||||
type=raw,value=${{ steps.versionNumber.outputs.versionNumber }}-ultra-lite
|
||||
type=raw,value=latest-ultra-lite
|
||||
|
||||
- name: Build and push Unified Dockerfile (ultra-lite variant)
|
||||
id: build-push-lite
|
||||
uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||
with:
|
||||
builder: ${{ steps.buildx.outputs.name }}
|
||||
context: .
|
||||
file: ./docker/embedded/Dockerfile.ultra-lite
|
||||
push: true
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
tags: ${{ github.ref == 'refs/heads/V2-master' && steps.meta-lite.outputs.tags || steps.meta-lite-test.outputs.tags }}
|
||||
labels: ${{ github.ref == 'refs/heads/V2-master' && steps.meta-lite.outputs.labels || steps.meta-lite-test.outputs.labels }}
|
||||
build-args: VERSION_TAG=${{ steps.versionNumber.outputs.versionNumber }}
|
||||
platforms: linux/amd64,linux/arm64/v8
|
||||
provenance: true
|
||||
sbom: true
|
||||
|
||||
- name: Sign ultra-lite images
|
||||
if: github.ref == 'refs/heads/V2-master'
|
||||
env:
|
||||
DIGEST: ${{ steps.build-push-lite.outputs.digest }}
|
||||
TAGS: ${{ steps.meta-lite.outputs.tags }}
|
||||
COSIGN_PRIVATE_KEY: ${{ secrets.COSIGN_PRIVATE_KEY }}
|
||||
COSIGN_PASSWORD: ${{ secrets.COSIGN_PASSWORD }}
|
||||
run: |
|
||||
echo "$TAGS" | tr ',' '\n' | while read -r tag; do
|
||||
cosign sign --key env://COSIGN_PRIVATE_KEY --yes "${tag}@${DIGEST}"
|
||||
done
|
||||
@@ -6,6 +6,8 @@ on:
|
||||
branches:
|
||||
- master
|
||||
- main
|
||||
- V2-master
|
||||
- testMain
|
||||
|
||||
# cancel in-progress jobs if a new job is triggered
|
||||
# This is useful to avoid running multiple builds for the same branch if a new commit is pushed
|
||||
@@ -25,7 +27,7 @@ permissions:
|
||||
jobs:
|
||||
push:
|
||||
if: ${{ vars.CI_PROFILE != 'lite' }}
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04-8core
|
||||
permissions:
|
||||
packages: write
|
||||
id-token: write
|
||||
@@ -47,18 +49,6 @@ jobs:
|
||||
with:
|
||||
gradle-version: 8.14
|
||||
|
||||
- name: Run Gradle Command
|
||||
run: ./gradlew clean build
|
||||
env:
|
||||
DISABLE_ADDITIONAL_FEATURES: true
|
||||
STIRLING_PDF_DESKTOP_UI: false
|
||||
|
||||
- name: Install cosign
|
||||
if: github.ref == 'refs/heads/master'
|
||||
uses: sigstore/cosign-installer@faadad0cce49287aee09b3a48701e75088a2c6ad # v4.0.0
|
||||
with:
|
||||
cosign-release: "v2.4.1"
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
id: buildx
|
||||
uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1
|
||||
@@ -67,6 +57,12 @@ jobs:
|
||||
id: versionNumber
|
||||
run: echo "versionNumber=$(./gradlew printVersion --quiet | tail -1)" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Install cosign
|
||||
if: github.ref == 'refs/heads/master' || github.ref == 'refs/heads/V2-master'
|
||||
uses: sigstore/cosign-installer@faadad0cce49287aee09b3a48701e75088a2c6ad # v4.0.0
|
||||
with:
|
||||
cosign-release: "v2.4.1"
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@5e57cd118135c172c3672efd75eb46360885c0ef # v3.6.0
|
||||
with:
|
||||
@@ -87,10 +83,9 @@ jobs:
|
||||
id: repoowner
|
||||
run: echo "lowercase=$(echo ${{ github.repository_owner }} | awk '{print tolower($0)}')" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Generate tags
|
||||
- name: Generate tags for latest
|
||||
id: meta
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
if: github.ref != 'refs/heads/main'
|
||||
with:
|
||||
images: |
|
||||
${{ secrets.DOCKER_HUB_USERNAME }}/s-pdf
|
||||
@@ -98,13 +93,13 @@ jobs:
|
||||
ghcr.io/${{ steps.repoowner.outputs.lowercase }}/stirling-pdf
|
||||
${{ secrets.DOCKER_HUB_ORG_USERNAME }}/stirling-pdf
|
||||
tags: |
|
||||
type=raw,value=${{ steps.versionNumber.outputs.versionNumber }},enable=${{ github.ref == 'refs/heads/master' }}
|
||||
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/master' }}
|
||||
type=raw,value=${{ steps.versionNumber.outputs.versionNumber }},enable=${{ github.ref == 'refs/heads/master' || github.ref == 'refs/heads/V2-master' }}
|
||||
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/master' || github.ref == 'refs/heads/V2-master' }}
|
||||
type=raw,value=alpha,enable=${{ github.ref == 'refs/heads/main' || github.ref == 'refs/heads/testMain' }}
|
||||
|
||||
- name: Build and push main Dockerfile
|
||||
id: build-push-regular
|
||||
- name: Build and push Unified Dockerfile (latest variant)
|
||||
id: build-push-latest
|
||||
uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||
if: github.ref != 'refs/heads/main'
|
||||
with:
|
||||
builder: ${{ steps.buildx.outputs.name }}
|
||||
context: .
|
||||
@@ -120,9 +115,9 @@ jobs:
|
||||
sbom: true
|
||||
|
||||
- name: Sign regular images
|
||||
if: github.ref == 'refs/heads/master'
|
||||
if: github.ref == 'refs/heads/master' || github.ref == 'refs/heads/V2-master'
|
||||
env:
|
||||
DIGEST: ${{ steps.build-push-regular.outputs.digest }}
|
||||
DIGEST: ${{ steps.build-push-latest.outputs.digest }}
|
||||
TAGS: ${{ steps.meta.outputs.tags }}
|
||||
COSIGN_PRIVATE_KEY: ${{ secrets.COSIGN_PRIVATE_KEY }}
|
||||
COSIGN_PASSWORD: ${{ secrets.COSIGN_PASSWORD }}
|
||||
@@ -133,10 +128,10 @@ jobs:
|
||||
"${tag}@${DIGEST}"
|
||||
done
|
||||
|
||||
- name: Generate tags ultra-lite
|
||||
id: meta2
|
||||
- name: Generate tags for latest-fat
|
||||
id: meta-fat
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
if: github.ref != 'refs/heads/main'
|
||||
if: github.ref != 'refs/heads/main' && github.ref != 'refs/heads/testMain'
|
||||
with:
|
||||
images: |
|
||||
${{ secrets.DOCKER_HUB_USERNAME }}/s-pdf
|
||||
@@ -144,43 +139,13 @@ jobs:
|
||||
ghcr.io/${{ steps.repoowner.outputs.lowercase }}/stirling-pdf
|
||||
${{ secrets.DOCKER_HUB_ORG_USERNAME }}/stirling-pdf
|
||||
tags: |
|
||||
type=raw,value=${{ steps.versionNumber.outputs.versionNumber }}-ultra-lite,enable=${{ github.ref == 'refs/heads/master' }}
|
||||
type=raw,value=latest-ultra-lite,enable=${{ github.ref == 'refs/heads/master' }}
|
||||
type=raw,value=${{ steps.versionNumber.outputs.versionNumber }}-fat,enable=${{ github.ref == 'refs/heads/master' || github.ref == 'refs/heads/V2-master' }}
|
||||
type=raw,value=latest-fat,enable=${{ github.ref == 'refs/heads/master' || github.ref == 'refs/heads/V2-master' }}
|
||||
|
||||
- name: Build and push Dockerfile-ultra-lite
|
||||
id: build-push-lite
|
||||
uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||
if: github.ref != 'refs/heads/main'
|
||||
with:
|
||||
context: .
|
||||
file: ./docker/embedded/Dockerfile.ultra-lite
|
||||
push: true
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
tags: ${{ steps.meta2.outputs.tags }}
|
||||
labels: ${{ steps.meta2.outputs.labels }}
|
||||
build-args: VERSION_TAG=${{ steps.versionNumber.outputs.versionNumber }}
|
||||
platforms: linux/amd64,linux/arm64/v8
|
||||
provenance: true
|
||||
sbom: true
|
||||
|
||||
- name: Generate tags fat
|
||||
id: meta3
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
with:
|
||||
images: |
|
||||
${{ secrets.DOCKER_HUB_USERNAME }}/s-pdf
|
||||
ghcr.io/${{ steps.repoowner.outputs.lowercase }}/s-pdf
|
||||
ghcr.io/${{ steps.repoowner.outputs.lowercase }}/stirling-pdf
|
||||
${{ secrets.DOCKER_HUB_ORG_USERNAME }}/stirling-pdf
|
||||
tags: |
|
||||
type=raw,value=${{ steps.versionNumber.outputs.versionNumber }}-fat,enable=${{ github.ref == 'refs/heads/master' }}
|
||||
type=raw,value=latest-fat,enable=${{ github.ref == 'refs/heads/master' }}
|
||||
type=raw,value=alpha,enable=${{ github.ref == 'refs/heads/main' }}
|
||||
|
||||
- name: Build and push main Dockerfile fat
|
||||
- name: Build and push Unified Dockerfile (fat variant)
|
||||
id: build-push-fat
|
||||
uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||
if: github.ref != 'refs/heads/main' && github.ref != 'refs/heads/testMain'
|
||||
with:
|
||||
builder: ${{ steps.buildx.outputs.name }}
|
||||
context: .
|
||||
@@ -188,18 +153,62 @@ jobs:
|
||||
push: true
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
tags: ${{ steps.meta3.outputs.tags }}
|
||||
labels: ${{ steps.meta3.outputs.labels }}
|
||||
tags: ${{ steps.meta-fat.outputs.tags }}
|
||||
labels: ${{ steps.meta-fat.outputs.labels }}
|
||||
build-args: VERSION_TAG=${{ steps.versionNumber.outputs.versionNumber }}
|
||||
platforms: linux/amd64,linux/arm64/v8
|
||||
provenance: true
|
||||
sbom: true
|
||||
|
||||
- name: Sign fat images
|
||||
if: github.ref == 'refs/heads/master'
|
||||
if: github.ref == 'refs/heads/master' || github.ref == 'refs/heads/V2-master'
|
||||
env:
|
||||
DIGEST: ${{ steps.build-push-fat.outputs.digest }}
|
||||
TAGS: ${{ steps.meta3.outputs.tags }}
|
||||
TAGS: ${{ steps.meta-fat.outputs.tags }}
|
||||
COSIGN_PRIVATE_KEY: ${{ secrets.COSIGN_PRIVATE_KEY }}
|
||||
COSIGN_PASSWORD: ${{ secrets.COSIGN_PASSWORD }}
|
||||
run: |
|
||||
echo "$TAGS" | tr ',' '\n' | while read -r tag; do
|
||||
cosign sign --key env://COSIGN_PRIVATE_KEY --yes "${tag}@${DIGEST}"
|
||||
done
|
||||
|
||||
- name: Generate tags for ultra-lite
|
||||
id: meta-lite
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
if: github.ref != 'refs/heads/main' && github.ref != 'refs/heads/testMain'
|
||||
with:
|
||||
images: |
|
||||
${{ secrets.DOCKER_HUB_USERNAME }}/s-pdf
|
||||
ghcr.io/${{ steps.repoowner.outputs.lowercase }}/s-pdf
|
||||
ghcr.io/${{ steps.repoowner.outputs.lowercase }}/stirling-pdf
|
||||
${{ secrets.DOCKER_HUB_ORG_USERNAME }}/stirling-pdf
|
||||
tags: |
|
||||
type=raw,value=${{ steps.versionNumber.outputs.versionNumber }}-ultra-lite,enable=${{ github.ref == 'refs/heads/master' || github.ref == 'refs/heads/V2-master' }}
|
||||
type=raw,value=latest-ultra-lite,enable=${{ github.ref == 'refs/heads/master' || github.ref == 'refs/heads/V2-master' }}
|
||||
|
||||
- name: Build and push Unified Dockerfile (ultra-lite variant)
|
||||
id: build-push-lite
|
||||
uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||
if: github.ref != 'refs/heads/main' && github.ref != 'refs/heads/testMain'
|
||||
with:
|
||||
builder: ${{ steps.buildx.outputs.name }}
|
||||
context: .
|
||||
file: ./docker/embedded/Dockerfile.ultra-lite
|
||||
push: true
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
tags: ${{ steps.meta-lite.outputs.tags }}
|
||||
labels: ${{ steps.meta-lite.outputs.labels }}
|
||||
build-args: VERSION_TAG=${{ steps.versionNumber.outputs.versionNumber }}
|
||||
platforms: linux/amd64,linux/arm64/v8
|
||||
provenance: true
|
||||
sbom: true
|
||||
|
||||
- name: Sign ultra-lite images
|
||||
if: github.ref == 'refs/heads/master' || github.ref == 'refs/heads/V2-master'
|
||||
env:
|
||||
DIGEST: ${{ steps.build-push-lite.outputs.digest }}
|
||||
TAGS: ${{ steps.meta-lite.outputs.tags }}
|
||||
COSIGN_PRIVATE_KEY: ${{ secrets.COSIGN_PRIVATE_KEY }}
|
||||
COSIGN_PASSWORD: ${{ secrets.COSIGN_PASSWORD }}
|
||||
run: |
|
||||
|
||||
@@ -174,7 +174,7 @@ jobs:
|
||||
|
||||
- name: Install frontend dependencies
|
||||
working-directory: ./frontend
|
||||
run: npm install
|
||||
run: npm ci
|
||||
|
||||
# DigiCert KeyLocker Setup (Cloud HSM)
|
||||
- name: Setup DigiCert KeyLocker
|
||||
@@ -507,7 +507,6 @@ jobs:
|
||||
find . -name "*.msi" -exec cp {} "../../../dist/Stirling-PDF-${{ matrix.name }}.msi" \;
|
||||
elif [ "${{ matrix.platform }}" = "macos-15" ] || [ "${{ matrix.platform }}" = "macos-15-intel" ]; then
|
||||
find . -name "*.dmg" -exec cp {} "../../../dist/Stirling-PDF-${{ matrix.name }}.dmg" \;
|
||||
find . -name "*.app" -exec cp -r {} "../../../dist/Stirling-PDF-${{ matrix.name }}.app" \;
|
||||
else
|
||||
find . -name "*.deb" -exec cp {} "../../../dist/Stirling-PDF-${{ matrix.name }}.deb" \;
|
||||
find . -name "*.AppImage" -exec cp {} "../../../dist/Stirling-PDF-${{ matrix.name }}.AppImage" \;
|
||||
@@ -595,8 +594,8 @@ jobs:
|
||||
fi
|
||||
elif [ "${{ matrix.platform }}" = "macos-15" ] || [ "${{ matrix.platform }}" = "macos-15-intel" ]; then
|
||||
echo "Checking for macOS artifacts..."
|
||||
find . -name "*.dmg" -o -name "*.app" | head -5
|
||||
if [ $(find . -name "*.dmg" -o -name "*.app" | wc -l) -eq 0 ]; then
|
||||
find . -name "*.dmg" | head -5
|
||||
if [ $(find . -name "*.dmg" | wc -l) -eq 0 ]; then
|
||||
echo "❌ No macOS artifacts found"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -76,7 +76,7 @@ jobs:
|
||||
- name: Set up SSH
|
||||
run: |
|
||||
mkdir -p ~/.ssh/
|
||||
echo "${{ secrets.VPS_SSH_KEY }}" > ../private.key
|
||||
echo "${{ secrets.NEW_VPS_SSH_KEY }}" > ../private.key
|
||||
sudo chmod 600 ../private.key
|
||||
|
||||
- name: Deploy to VPS
|
||||
@@ -107,9 +107,9 @@ jobs:
|
||||
restart: on-failure:5
|
||||
EOF
|
||||
|
||||
scp -i ../private.key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null docker-compose.yml ${{ secrets.VPS_USERNAME }}@${{ secrets.VPS_HOST }}:/tmp/docker-compose.yml
|
||||
scp -i ../private.key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null docker-compose.yml ${{ secrets.NEW_VPS_USERNAME }}@${{ secrets.NEW_VPS_HOST }}:/tmp/docker-compose.yml
|
||||
|
||||
ssh -i ../private.key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null ${{ secrets.VPS_USERNAME }}@${{ secrets.VPS_HOST }} << EOF
|
||||
ssh -i ../private.key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null ${{ secrets.NEW_VPS_USERNAME }}@${{ secrets.NEW_VPS_HOST }} << EOF
|
||||
mkdir -p /stirling/test-${{ github.sha }}/{data,config,logs}
|
||||
mv /tmp/docker-compose.yml /stirling/test-${{ github.sha }}/docker-compose.yml
|
||||
cd /stirling/test-${{ github.sha }}
|
||||
@@ -161,7 +161,7 @@ jobs:
|
||||
npm install
|
||||
npm run build
|
||||
npm install dashcam-chrome --save
|
||||
Start-Process "C:/Program Files/Google/Chrome/Application/chrome.exe" -ArgumentList "--start-maximized", "--load-extension=$(pwd)/node_modules/dashcam-chrome/build", "http://${{ secrets.VPS_HOST }}:1337"
|
||||
Start-Process "C:/Program Files/Google/Chrome/Application/chrome.exe" -ArgumentList "--start-maximized", "--load-extension=$(pwd)/node_modules/dashcam-chrome/build", "http://${{ secrets.NEW_VPS_HOST }}:1337"
|
||||
Start-Sleep -Seconds 20
|
||||
prompt: |
|
||||
1. /run testing/testdriver/test.yml
|
||||
@@ -183,13 +183,13 @@ jobs:
|
||||
- name: Set up SSH
|
||||
run: |
|
||||
mkdir -p ~/.ssh/
|
||||
echo "${{ secrets.VPS_SSH_KEY }}" > ../private.key
|
||||
echo "${{ secrets.NEW_VPS_SSH_KEY }}" > ../private.key
|
||||
sudo chmod 600 ../private.key
|
||||
|
||||
- name: Cleanup deployment
|
||||
if: always()
|
||||
run: |
|
||||
ssh -i ../private.key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null ${{ secrets.VPS_USERNAME }}@${{ secrets.VPS_HOST }} << EOF
|
||||
ssh -i ../private.key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null ${{ secrets.NEW_VPS_USERNAME }}@${{ secrets.NEW_VPS_HOST }} << EOF
|
||||
cd /stirling/test-${{ github.sha }}
|
||||
docker-compose down
|
||||
cd /stirling
|
||||
|
||||
@@ -37,6 +37,7 @@ dependencies {
|
||||
api 'com.drewnoakes:metadata-extractor:2.19.0' // Image metadata extractor
|
||||
api 'com.vladsch.flexmark:flexmark-html2md-converter:0.64.8'
|
||||
api "org.apache.pdfbox:pdfbox:$pdfboxVersion"
|
||||
api "org.apache.pdfbox:pdfbox-io:$pdfboxVersion"
|
||||
api "org.apache.pdfbox:xmpbox:$pdfboxVersion"
|
||||
api "org.apache.pdfbox:preflight:$pdfboxVersion"
|
||||
api 'com.github.junrar:junrar:7.5.7' // RAR archive support for CBR files
|
||||
|
||||
+11
-8
@@ -94,16 +94,19 @@ public class RuntimePathConfig {
|
||||
defaultSOfficePath, operations != null ? operations.getSoffice() : null);
|
||||
|
||||
// Initialize Tesseract data path
|
||||
String defaultTessDataPath =
|
||||
isDocker ? "/usr/share/tesseract-ocr/5/tessdata" : "/usr/share/tessdata";
|
||||
|
||||
// Priority: config setting > TESSDATA_PREFIX env var > default path
|
||||
String tessPath = system.getTessdataDir();
|
||||
String tessdataDir = java.lang.System.getenv("TESSDATA_PREFIX");
|
||||
String tessdataPrefix = java.lang.System.getenv("TESSDATA_PREFIX");
|
||||
String defaultPath = "/usr/share/tesseract-ocr/5/tessdata";
|
||||
|
||||
if (tessPath != null && !tessPath.isEmpty()) {
|
||||
this.tessDataPath = tessPath;
|
||||
} else if (tessdataPrefix != null && !tessdataPrefix.isEmpty()) {
|
||||
this.tessDataPath = tessdataPrefix;
|
||||
} else {
|
||||
this.tessDataPath = defaultPath;
|
||||
}
|
||||
|
||||
this.tessDataPath =
|
||||
resolvePath(
|
||||
defaultTessDataPath,
|
||||
(tessPath != null && !tessPath.isEmpty()) ? tessPath : tessdataDir);
|
||||
log.info("Using Tesseract data path: {}", this.tessDataPath);
|
||||
}
|
||||
|
||||
|
||||
@@ -418,6 +418,15 @@ public class ApplicationProperties {
|
||||
|
||||
// 'https://app.example.com'). If not set, falls back to backendUrl.
|
||||
private boolean enableMobileScanner = false; // Enable mobile phone QR code upload feature
|
||||
private MobileScannerSettings mobileScannerSettings = new MobileScannerSettings();
|
||||
|
||||
@Data
|
||||
public static class MobileScannerSettings {
|
||||
private boolean convertToPdf = true; // Whether to automatically convert images to PDF
|
||||
private String imageResolution = "full"; // Options: "full", "reduced"
|
||||
private String pageFormat = "A4"; // Options: "keep", "A4", "letter"
|
||||
private boolean stretchToFit = false; // Whether to stretch image to fill page
|
||||
}
|
||||
|
||||
public boolean isAnalyticsEnabled() {
|
||||
return this.getEnableAnalytics() != null && this.getEnableAnalytics();
|
||||
|
||||
@@ -129,7 +129,12 @@ public class CbrUtils {
|
||||
new PDRectangle(pdImage.getWidth(), pdImage.getHeight()));
|
||||
document.addPage(page);
|
||||
try (PDPageContentStream contentStream =
|
||||
new PDPageContentStream(document, page)) {
|
||||
new PDPageContentStream(
|
||||
document,
|
||||
page,
|
||||
PDPageContentStream.AppendMode.OVERWRITE,
|
||||
true,
|
||||
true)) {
|
||||
contentStream.drawImage(pdImage, 0, 0);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
|
||||
@@ -97,7 +97,12 @@ public class CbzUtils {
|
||||
new PDRectangle(pdImage.getWidth(), pdImage.getHeight()));
|
||||
document.addPage(page);
|
||||
try (PDPageContentStream contentStream =
|
||||
new PDPageContentStream(document, page)) {
|
||||
new PDPageContentStream(
|
||||
document,
|
||||
page,
|
||||
PDPageContentStream.AppendMode.OVERWRITE,
|
||||
true,
|
||||
true)) {
|
||||
contentStream.drawImage(pdImage, 0, 0);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
|
||||
@@ -41,7 +41,7 @@ import lombok.extern.slf4j.Slf4j;
|
||||
* <pre>{@code
|
||||
* // In service layer - create exception with ExceptionUtils
|
||||
* try {
|
||||
* PDDocument doc = PDDocument.load(file);
|
||||
* PDDocument doc = Loader.loadPDF(file);
|
||||
* } catch (IOException e) {
|
||||
* throw ExceptionUtils.createPdfCorruptedException("during load", e);
|
||||
* }
|
||||
|
||||
@@ -60,6 +60,7 @@ public class PdfToCbrUtils {
|
||||
|
||||
private static byte[] createCbrFromPdf(PDDocument document, int dpi) throws IOException {
|
||||
PDFRenderer pdfRenderer = new PDFRenderer(document);
|
||||
pdfRenderer.setSubsamplingAllowed(true); // Enable subsampling to reduce memory usage
|
||||
|
||||
Path tempDir = Files.createTempDirectory("stirling-pdf-cbr-");
|
||||
List<Path> generatedImages = new ArrayList<>();
|
||||
|
||||
@@ -55,6 +55,7 @@ public class PdfToCbzUtils {
|
||||
|
||||
private static byte[] createCbzFromPdf(PDDocument document, int dpi) throws IOException {
|
||||
PDFRenderer pdfRenderer = new PDFRenderer(document);
|
||||
pdfRenderer.setSubsamplingAllowed(true); // Enable subsampling to reduce memory usage
|
||||
|
||||
try (ByteArrayOutputStream cbzOutputStream = new ByteArrayOutputStream();
|
||||
ZipOutputStream zipOut = new ZipOutputStream(cbzOutputStream)) {
|
||||
|
||||
@@ -119,11 +119,11 @@ public class PdfUtils {
|
||||
|
||||
public boolean hasTextOnPage(PDPage page, String phrase) throws IOException {
|
||||
PDFTextStripper textStripper = new PDFTextStripper();
|
||||
PDDocument tempDoc = new PDDocument();
|
||||
tempDoc.addPage(page);
|
||||
String pageText = textStripper.getText(tempDoc);
|
||||
tempDoc.close();
|
||||
return pageText.contains(phrase);
|
||||
try (PDDocument tempDoc = new PDDocument()) {
|
||||
tempDoc.addPage(page);
|
||||
String pageText = textStripper.getText(tempDoc);
|
||||
return pageText.contains(phrase);
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] convertFromPdf(
|
||||
@@ -153,7 +153,8 @@ public class PdfUtils {
|
||||
maxSafeDpi);
|
||||
}
|
||||
|
||||
try (PDDocument document = pdfDocumentFactory.load(inputStream)) {
|
||||
try (PDDocument document = pdfDocumentFactory.load(inputStream);
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
|
||||
PDFRenderer pdfRenderer = new PDFRenderer(document);
|
||||
pdfRenderer.setSubsamplingAllowed(true);
|
||||
if (!includeAnnotations) {
|
||||
@@ -161,9 +162,6 @@ public class PdfUtils {
|
||||
}
|
||||
int pageCount = document.getNumberOfPages();
|
||||
|
||||
// Create a ByteArrayOutputStream to save the image(s) to
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
|
||||
if (singleImage) {
|
||||
if ("tiff".equals(imageType.toLowerCase(Locale.ROOT))
|
||||
|| "tif".equals(imageType.toLowerCase(Locale.ROOT))) {
|
||||
@@ -400,55 +398,61 @@ public class PdfUtils {
|
||||
*/
|
||||
public PDDocument convertPdfToPdfImage(PDDocument document) throws IOException {
|
||||
PDDocument imageDocument = new PDDocument();
|
||||
PDFRenderer pdfRenderer = new PDFRenderer(document);
|
||||
pdfRenderer.setSubsamplingAllowed(true);
|
||||
for (int page = 0; page < document.getNumberOfPages(); ++page) {
|
||||
final int pageIndex = page;
|
||||
BufferedImage bim;
|
||||
try {
|
||||
PDFRenderer pdfRenderer = new PDFRenderer(document);
|
||||
pdfRenderer.setSubsamplingAllowed(true);
|
||||
for (int page = 0; page < document.getNumberOfPages(); ++page) {
|
||||
final int pageIndex = page;
|
||||
BufferedImage bim;
|
||||
|
||||
// Use global maximum DPI setting, fallback to 300 if not set
|
||||
int renderDpi = 300; // Default fallback
|
||||
ApplicationProperties properties =
|
||||
ApplicationContextProvider.getBean(ApplicationProperties.class);
|
||||
if (properties != null && properties.getSystem() != null) {
|
||||
renderDpi = properties.getSystem().getMaxDPI();
|
||||
}
|
||||
final int dpi = renderDpi;
|
||||
|
||||
try {
|
||||
bim =
|
||||
ExceptionUtils.handleOomRendering(
|
||||
pageIndex + 1,
|
||||
dpi,
|
||||
() ->
|
||||
pdfRenderer.renderImageWithDPI(
|
||||
pageIndex, dpi, ImageType.RGB));
|
||||
} catch (IllegalArgumentException e) {
|
||||
if (e.getMessage() != null
|
||||
&& e.getMessage().contains("Maximum size of image exceeded")) {
|
||||
throw ExceptionUtils.createIllegalArgumentException(
|
||||
"error.pageTooBigFor300Dpi",
|
||||
"PDF page {0} is too large to render at 300 DPI. The resulting image"
|
||||
+ " would exceed Java's maximum array size. Please use a lower DPI"
|
||||
+ " value for PDF-to-image conversion.",
|
||||
pageIndex + 1);
|
||||
// Use global maximum DPI setting, fallback to 300 if not set
|
||||
int renderDpi = 300; // Default fallback
|
||||
ApplicationProperties properties =
|
||||
ApplicationContextProvider.getBean(ApplicationProperties.class);
|
||||
if (properties != null && properties.getSystem() != null) {
|
||||
renderDpi = properties.getSystem().getMaxDPI();
|
||||
}
|
||||
throw e;
|
||||
final int dpi = renderDpi;
|
||||
|
||||
try {
|
||||
bim =
|
||||
ExceptionUtils.handleOomRendering(
|
||||
pageIndex + 1,
|
||||
dpi,
|
||||
() ->
|
||||
pdfRenderer.renderImageWithDPI(
|
||||
pageIndex, dpi, ImageType.RGB));
|
||||
} catch (IllegalArgumentException e) {
|
||||
if (e.getMessage() != null
|
||||
&& e.getMessage().contains("Maximum size of image exceeded")) {
|
||||
throw ExceptionUtils.createIllegalArgumentException(
|
||||
"error.pageTooBigFor300Dpi",
|
||||
"PDF page {0} is too large to render at 300 DPI. The resulting image"
|
||||
+ " would exceed Java's maximum array size. Please use a lower DPI"
|
||||
+ " value for PDF-to-image conversion.",
|
||||
pageIndex + 1);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
PDPage originalPage = document.getPage(page);
|
||||
|
||||
float width = originalPage.getMediaBox().getWidth();
|
||||
float height = originalPage.getMediaBox().getHeight();
|
||||
|
||||
PDPage newPage = new PDPage(new PDRectangle(width, height));
|
||||
imageDocument.addPage(newPage);
|
||||
PDImageXObject pdImage = LosslessFactory.createFromImage(imageDocument, bim);
|
||||
try (PDPageContentStream contentStream =
|
||||
new PDPageContentStream(
|
||||
imageDocument, newPage, AppendMode.APPEND, true, true)) {
|
||||
contentStream.drawImage(pdImage, 0, 0, width, height);
|
||||
}
|
||||
bim.flush();
|
||||
}
|
||||
PDPage originalPage = document.getPage(page);
|
||||
|
||||
float width = originalPage.getMediaBox().getWidth();
|
||||
float height = originalPage.getMediaBox().getHeight();
|
||||
|
||||
PDPage newPage = new PDPage(new PDRectangle(width, height));
|
||||
imageDocument.addPage(newPage);
|
||||
PDImageXObject pdImage = LosslessFactory.createFromImage(imageDocument, bim);
|
||||
PDPageContentStream contentStream =
|
||||
new PDPageContentStream(imageDocument, newPage, AppendMode.APPEND, true, true);
|
||||
contentStream.drawImage(pdImage, 0, 0, width, height);
|
||||
contentStream.close();
|
||||
return imageDocument;
|
||||
} catch (Exception e) {
|
||||
throw e;
|
||||
}
|
||||
return imageDocument;
|
||||
}
|
||||
|
||||
private BufferedImage prepareImageForPdfToImage(int maxWidth, int height, String imageType) {
|
||||
|
||||
@@ -69,7 +69,6 @@ public class WebResponseUtils {
|
||||
// Open Byte Array and save document to it
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
document.save(baos);
|
||||
document.close();
|
||||
|
||||
return baosToWebResponse(baos, docName);
|
||||
}
|
||||
|
||||
+6
-1
@@ -146,13 +146,18 @@ public class CustomColorReplaceStrategy extends ReplaceAndInvertColorStrategy {
|
||||
// Save the modified PDF to a ByteArrayOutputStream
|
||||
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
|
||||
document.save(byteArrayOutputStream);
|
||||
document.close();
|
||||
|
||||
// Prepare the modified PDF for download
|
||||
ByteArrayInputStream inputStream =
|
||||
new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
|
||||
InputStreamResource resource = new InputStreamResource(inputStream);
|
||||
return resource;
|
||||
} finally {
|
||||
try {
|
||||
Files.deleteIfExists(file.toPath());
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to delete temporary file: {}", file.getAbsolutePath(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+35
-3
@@ -7,6 +7,7 @@ import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
@@ -19,11 +20,14 @@ import org.apache.pdfbox.rendering.PDFRenderer;
|
||||
import org.springframework.core.io.InputStreamResource;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.model.api.misc.ReplaceAndInvert;
|
||||
import stirling.software.common.util.ApplicationContextProvider;
|
||||
import stirling.software.common.util.ExceptionUtils;
|
||||
|
||||
@Slf4j
|
||||
public class InvertFullColorStrategy extends ReplaceAndInvertColorStrategy {
|
||||
|
||||
public InvertFullColorStrategy(MultipartFile file, ReplaceAndInvert replaceAndInvert) {
|
||||
@@ -43,6 +47,8 @@ public class InvertFullColorStrategy extends ReplaceAndInvertColorStrategy {
|
||||
try (PDDocument document = Loader.loadPDF(tempFile.getFile())) {
|
||||
// Render each page and invert colors
|
||||
PDFRenderer pdfRenderer = new PDFRenderer(document);
|
||||
pdfRenderer.setSubsamplingAllowed(
|
||||
true); // Enable subsampling to reduce memory usage
|
||||
for (int page = 0; page < document.getNumberOfPages(); page++) {
|
||||
BufferedImage image;
|
||||
|
||||
@@ -73,12 +79,27 @@ public class InvertFullColorStrategy extends ReplaceAndInvertColorStrategy {
|
||||
PDImageXObject pdImage =
|
||||
PDImageXObject.createFromFileByContent(tempImageFile, document);
|
||||
|
||||
// Delete temp file immediately after loading into memory to prevent disk
|
||||
// exhaustion
|
||||
// The file content is now in the PDImageXObject, so the file is no longer
|
||||
// needed
|
||||
try {
|
||||
Files.deleteIfExists(tempImageFile.toPath());
|
||||
tempImageFile = null; // Mark as deleted to avoid double deletion
|
||||
} catch (IOException e) {
|
||||
log.warn(
|
||||
"Failed to delete temporary image file: {}",
|
||||
tempImageFile.getAbsolutePath(),
|
||||
e);
|
||||
}
|
||||
|
||||
try (PDPageContentStream contentStream =
|
||||
new PDPageContentStream(
|
||||
document,
|
||||
pdPage,
|
||||
PDPageContentStream.AppendMode.OVERWRITE,
|
||||
true)) {
|
||||
true,
|
||||
true)) { // resetContext=true ensures clean graphics state
|
||||
contentStream.drawImage(
|
||||
pdImage,
|
||||
0,
|
||||
@@ -87,8 +108,16 @@ public class InvertFullColorStrategy extends ReplaceAndInvertColorStrategy {
|
||||
pdPage.getMediaBox().getHeight());
|
||||
}
|
||||
} finally {
|
||||
// Safety net: ensure temp file is deleted even if an exception occurred
|
||||
if (tempImageFile != null && tempImageFile.exists()) {
|
||||
Files.delete(tempImageFile.toPath());
|
||||
try {
|
||||
Files.deleteIfExists(tempImageFile.toPath());
|
||||
} catch (IOException e) {
|
||||
log.warn(
|
||||
"Failed to delete temporary image file: {}",
|
||||
tempImageFile.getAbsolutePath(),
|
||||
e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -128,7 +157,10 @@ public class InvertFullColorStrategy extends ReplaceAndInvertColorStrategy {
|
||||
|
||||
// Helper method to convert BufferedImage to InputStream
|
||||
private File convertToBufferedImageTpFile(BufferedImage image) throws IOException {
|
||||
File file = File.createTempFile("image", ".png");
|
||||
// Use Files.createTempFile instead of File.createTempFile for better security and modern
|
||||
// Java practices
|
||||
Path tempPath = Files.createTempFile("image", ".png");
|
||||
File file = tempPath.toFile();
|
||||
ImageIO.write(image, "png", file);
|
||||
return file;
|
||||
}
|
||||
|
||||
@@ -92,8 +92,7 @@ public class WebResponseUtilsTest {
|
||||
|
||||
@Test
|
||||
public void testPdfDocToWebResponse() {
|
||||
try {
|
||||
PDDocument document = new PDDocument();
|
||||
try (PDDocument document = new PDDocument()) {
|
||||
document.addPage(new org.apache.pdfbox.pdmodel.PDPage());
|
||||
String docName = "sample.pdf";
|
||||
|
||||
|
||||
@@ -141,10 +141,10 @@ public class SPDFApplication {
|
||||
String backendUrl = appConfig.getBackendUrl();
|
||||
String contextPath = appConfig.getContextPath();
|
||||
String serverPort = appConfig.getServerPort();
|
||||
baseUrlStatic = backendUrl;
|
||||
baseUrlStatic = normalizeBackendUrl(backendUrl, serverPort);
|
||||
contextPathStatic = contextPath;
|
||||
serverPortStatic = serverPort;
|
||||
String url = backendUrl + ":" + getStaticPort() + contextPath;
|
||||
String url = buildFullUrl(baseUrlStatic, getStaticPort(), contextPathStatic);
|
||||
|
||||
// Log Tauri mode information
|
||||
if (Boolean.parseBoolean(System.getProperty("STIRLING_PDF_TAURI_MODE", "false"))) {
|
||||
@@ -210,7 +210,7 @@ public class SPDFApplication {
|
||||
|
||||
private static void printStartupLogs() {
|
||||
log.info("Stirling-PDF Started.");
|
||||
String url = baseUrlStatic + ":" + getStaticPort() + contextPathStatic;
|
||||
String url = buildFullUrl(baseUrlStatic, getStaticPort(), contextPathStatic);
|
||||
log.info("Navigate to {}", url);
|
||||
}
|
||||
|
||||
@@ -258,4 +258,79 @@ public class SPDFApplication {
|
||||
public static String getStaticContextPath() {
|
||||
return contextPathStatic;
|
||||
}
|
||||
|
||||
private static String buildFullUrl(String backendUrl, String port, String contextPath) {
|
||||
String normalizedBase = normalizeBackendUrl(backendUrl, port);
|
||||
|
||||
String normalizedContextPath =
|
||||
(contextPath == null || contextPath.isBlank() || "/".equals(contextPath))
|
||||
? "/"
|
||||
: (contextPath.startsWith("/") ? contextPath : "/" + contextPath);
|
||||
|
||||
return normalizedBase + normalizedContextPath;
|
||||
}
|
||||
|
||||
private static String normalizeBackendUrl(String backendUrl, String port) {
|
||||
String trimmedBase =
|
||||
(backendUrl == null || backendUrl.isBlank())
|
||||
? "http://localhost"
|
||||
: backendUrl.trim().replaceAll("/+$", "");
|
||||
boolean hasScheme = trimmedBase.matches("^[a-zA-Z][a-zA-Z0-9+.-]*://.*");
|
||||
String baseForParsing = hasScheme ? trimmedBase : "http://" + trimmedBase;
|
||||
Integer parsedPort = parsePort(port);
|
||||
|
||||
try {
|
||||
java.net.URI uri = new java.net.URI(baseForParsing);
|
||||
String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
|
||||
String host = uri.getHost();
|
||||
if (host == null) {
|
||||
return appendPortFallback(trimmedBase, parsedPort);
|
||||
}
|
||||
|
||||
boolean defaultHttp =
|
||||
"http".equalsIgnoreCase(scheme) && Integer.valueOf(80).equals(parsedPort);
|
||||
boolean defaultHttps =
|
||||
"https".equalsIgnoreCase(scheme) && Integer.valueOf(443).equals(parsedPort);
|
||||
|
||||
int effectivePort = uri.getPort();
|
||||
if (effectivePort == -1 && parsedPort != null && !defaultHttp && !defaultHttps) {
|
||||
effectivePort = parsedPort;
|
||||
}
|
||||
|
||||
java.net.URI rebuilt =
|
||||
new java.net.URI(
|
||||
scheme,
|
||||
uri.getUserInfo(),
|
||||
host,
|
||||
effectivePort,
|
||||
uri.getPath(),
|
||||
uri.getQuery(),
|
||||
uri.getFragment());
|
||||
return rebuilt.toString();
|
||||
} catch (java.net.URISyntaxException e) {
|
||||
return appendPortFallback(trimmedBase, parsedPort);
|
||||
}
|
||||
}
|
||||
|
||||
private static Integer parsePort(String port) {
|
||||
if (port == null || port.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
int parsed = Integer.parseInt(port);
|
||||
return parsed > 0 ? parsed : null;
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String appendPortFallback(String trimmedBase, Integer port) {
|
||||
if (port == null) {
|
||||
return trimmedBase;
|
||||
}
|
||||
if (trimmedBase.matches(".+:\\d+$")) {
|
||||
return trimmedBase;
|
||||
}
|
||||
return trimmedBase + ":" + port;
|
||||
}
|
||||
}
|
||||
|
||||
+25
-24
@@ -29,6 +29,7 @@ import lombok.RequiredArgsConstructor;
|
||||
import stirling.software.SPDF.model.api.general.BookletImpositionRequest;
|
||||
import stirling.software.common.annotations.AutoJobPostMapping;
|
||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||
import stirling.software.common.util.GeneralUtils;
|
||||
import stirling.software.common.util.WebResponseUtils;
|
||||
|
||||
@RestController
|
||||
@@ -68,33 +69,33 @@ public class BookletImpositionController {
|
||||
"Booklet printing uses 2 pages per side (landscape). For 4-up, use the N-up feature.");
|
||||
}
|
||||
|
||||
PDDocument sourceDocument = pdfDocumentFactory.load(file);
|
||||
int totalPages = sourceDocument.getNumberOfPages();
|
||||
try (PDDocument sourceDocument = pdfDocumentFactory.load(file)) {
|
||||
int totalPages = sourceDocument.getNumberOfPages();
|
||||
|
||||
// Create proper booklet with signature-based page ordering
|
||||
PDDocument newDocument =
|
||||
createSaddleBooklet(
|
||||
sourceDocument,
|
||||
totalPages,
|
||||
addBorder,
|
||||
spineLocation,
|
||||
addGutter,
|
||||
gutterSize,
|
||||
doubleSided,
|
||||
duplexPass,
|
||||
flipOnShortEdge);
|
||||
// Create proper booklet with signature-based page ordering
|
||||
try (PDDocument newDocument =
|
||||
createSaddleBooklet(
|
||||
sourceDocument,
|
||||
totalPages,
|
||||
addBorder,
|
||||
spineLocation,
|
||||
addGutter,
|
||||
gutterSize,
|
||||
doubleSided,
|
||||
duplexPass,
|
||||
flipOnShortEdge)) {
|
||||
|
||||
sourceDocument.close();
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
newDocument.save(baos);
|
||||
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
newDocument.save(baos);
|
||||
newDocument.close();
|
||||
|
||||
byte[] result = baos.toByteArray();
|
||||
return WebResponseUtils.bytesToWebResponse(
|
||||
result,
|
||||
Filenames.toSimpleFileName(file.getOriginalFilename()).replaceFirst("[.][^.]+$", "")
|
||||
+ "_booklet.pdf");
|
||||
byte[] result = baos.toByteArray();
|
||||
return WebResponseUtils.bytesToWebResponse(
|
||||
result,
|
||||
GeneralUtils.generateFilename(
|
||||
Filenames.toSimpleFileName(file.getOriginalFilename()),
|
||||
"_booklet.pdf"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int padToMultipleOf4(int n) {
|
||||
|
||||
@@ -155,6 +155,7 @@ public class CropController {
|
||||
try (PDDocument newDocument =
|
||||
pdfDocumentFactory.createNewDocumentBasedOnOldDocument(sourceDocument)) {
|
||||
PDFRenderer renderer = new PDFRenderer(sourceDocument);
|
||||
renderer.setSubsamplingAllowed(true); // Enable subsampling to reduce memory usage
|
||||
LayerUtility layerUtility = new LayerUtility(newDocument);
|
||||
|
||||
for (int i = 0; i < sourceDocument.getNumberOfPages(); i++) {
|
||||
|
||||
@@ -3,6 +3,7 @@ package stirling.software.SPDF.controller.api;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
@@ -27,7 +28,6 @@ import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
|
||||
@@ -277,7 +277,7 @@ public class MergeController {
|
||||
"This endpoint merges multiple PDF files into a single PDF file. The merged"
|
||||
+ " file will contain all pages from the input files in the order they were"
|
||||
+ " provided. Input:PDF Output:PDF Type:MISO")
|
||||
public ResponseEntity<StreamingResponseBody> mergePdfs(
|
||||
public ResponseEntity<byte[]> mergePdfs(
|
||||
@ModelAttribute MergePdfsRequest request,
|
||||
@RequestParam(value = "fileOrder", required = false) String fileOrder)
|
||||
throws IOException {
|
||||
@@ -304,8 +304,6 @@ public class MergeController {
|
||||
request.getSortType())); // Sort files based on requested sort type
|
||||
}
|
||||
|
||||
ResponseEntity<StreamingResponseBody> response;
|
||||
|
||||
try (TempFile mt = new TempFile(tempFileManager, ".pdf")) {
|
||||
|
||||
PDFMergerUtility mergerUtility = new PDFMergerUtility();
|
||||
@@ -399,7 +397,7 @@ public class MergeController {
|
||||
String mergedFileName =
|
||||
GeneralUtils.generateFilename(firstFilename, "_merged_unsigned.pdf");
|
||||
|
||||
response = WebResponseUtils.pdfFileToWebResponse(outputTempFile, mergedFileName);
|
||||
return response;
|
||||
byte[] pdfBytes = Files.readAllBytes(outputTempFile.getPath());
|
||||
return WebResponseUtils.bytesToWebResponse(pdfBytes, mergedFileName);
|
||||
}
|
||||
}
|
||||
|
||||
+98
-97
@@ -70,108 +70,109 @@ public class MultiPageLayoutController {
|
||||
: (int) Math.sqrt(pagesPerSheet);
|
||||
int rows = pagesPerSheet == 2 || pagesPerSheet == 3 ? 1 : (int) Math.sqrt(pagesPerSheet);
|
||||
|
||||
PDDocument sourceDocument = pdfDocumentFactory.load(file);
|
||||
PDDocument newDocument =
|
||||
pdfDocumentFactory.createNewDocumentBasedOnOldDocument(sourceDocument);
|
||||
PDPage newPage = new PDPage(PDRectangle.A4);
|
||||
newDocument.addPage(newPage);
|
||||
try (PDDocument sourceDocument = pdfDocumentFactory.load(file)) {
|
||||
try (PDDocument newDocument =
|
||||
pdfDocumentFactory.createNewDocumentBasedOnOldDocument(sourceDocument)) {
|
||||
int totalPages = sourceDocument.getNumberOfPages();
|
||||
LayerUtility layerUtility = new LayerUtility(newDocument);
|
||||
|
||||
int totalPages = sourceDocument.getNumberOfPages();
|
||||
float cellWidth = newPage.getMediaBox().getWidth() / cols;
|
||||
float cellHeight = newPage.getMediaBox().getHeight() / rows;
|
||||
// Calculate cell dimensions once (all output pages are A4) - declare outside try
|
||||
// blocks
|
||||
float cellWidth = PDRectangle.A4.getWidth() / cols;
|
||||
float cellHeight = PDRectangle.A4.getHeight() / rows;
|
||||
|
||||
PDPageContentStream contentStream =
|
||||
new PDPageContentStream(
|
||||
newDocument, newPage, PDPageContentStream.AppendMode.APPEND, true, true);
|
||||
LayerUtility layerUtility = new LayerUtility(newDocument);
|
||||
// Process pages in groups of pagesPerSheet, creating a new page and content stream
|
||||
// for each group
|
||||
for (int i = 0; i < totalPages; i += pagesPerSheet) {
|
||||
// Create a new output page for each group of pagesPerSheet
|
||||
PDPage newPage = new PDPage(PDRectangle.A4);
|
||||
newDocument.addPage(newPage);
|
||||
|
||||
float borderThickness = 1.5f; // Specify border thickness as required
|
||||
contentStream.setLineWidth(borderThickness);
|
||||
contentStream.setStrokingColor(Color.BLACK);
|
||||
// Use try-with-resources for each content stream to ensure proper cleanup
|
||||
// resetContext=true: Start with a clean graphics state for new content
|
||||
try (PDPageContentStream contentStream =
|
||||
new PDPageContentStream(
|
||||
newDocument,
|
||||
newPage,
|
||||
PDPageContentStream.AppendMode.APPEND,
|
||||
true,
|
||||
true)) {
|
||||
float borderThickness = 1.5f; // Specify border thickness as required
|
||||
contentStream.setLineWidth(borderThickness);
|
||||
contentStream.setStrokingColor(Color.BLACK);
|
||||
|
||||
for (int i = 0; i < totalPages; i++) {
|
||||
if (i != 0 && i % pagesPerSheet == 0) {
|
||||
// Close the current content stream and create a new page and content stream
|
||||
contentStream.close();
|
||||
newPage = new PDPage(PDRectangle.A4);
|
||||
newDocument.addPage(newPage);
|
||||
contentStream =
|
||||
new PDPageContentStream(
|
||||
// Process all pages in this group
|
||||
for (int j = 0; j < pagesPerSheet && (i + j) < totalPages; j++) {
|
||||
int pageIndex = i + j;
|
||||
PDPage sourcePage = sourceDocument.getPage(pageIndex);
|
||||
PDRectangle rect = sourcePage.getMediaBox();
|
||||
float scaleWidth = cellWidth / rect.getWidth();
|
||||
float scaleHeight = cellHeight / rect.getHeight();
|
||||
float scale = Math.min(scaleWidth, scaleHeight);
|
||||
|
||||
int adjustedPageIndex = j % pagesPerSheet;
|
||||
int rowIndex = adjustedPageIndex / cols;
|
||||
int colIndex = adjustedPageIndex % cols;
|
||||
|
||||
float x =
|
||||
colIndex * cellWidth
|
||||
+ (cellWidth - rect.getWidth() * scale) / 2;
|
||||
float y =
|
||||
newPage.getMediaBox().getHeight()
|
||||
- ((rowIndex + 1) * cellHeight
|
||||
- (cellHeight - rect.getHeight() * scale) / 2);
|
||||
|
||||
contentStream.saveGraphicsState();
|
||||
contentStream.transform(Matrix.getTranslateInstance(x, y));
|
||||
contentStream.transform(Matrix.getScaleInstance(scale, scale));
|
||||
|
||||
PDFormXObject formXObject =
|
||||
layerUtility.importPageAsForm(sourceDocument, pageIndex);
|
||||
contentStream.drawForm(formXObject);
|
||||
|
||||
contentStream.restoreGraphicsState();
|
||||
|
||||
if (addBorder) {
|
||||
// Draw border around each page
|
||||
float borderX = colIndex * cellWidth;
|
||||
float borderY =
|
||||
newPage.getMediaBox().getHeight()
|
||||
- (rowIndex + 1) * cellHeight;
|
||||
contentStream.addRect(borderX, borderY, cellWidth, cellHeight);
|
||||
contentStream.stroke();
|
||||
}
|
||||
}
|
||||
} // contentStream is automatically closed here
|
||||
}
|
||||
|
||||
// If any source page is rotated, skip form copying/transformation entirely
|
||||
boolean hasRotation = GeneralFormCopyUtils.hasAnyRotatedPage(sourceDocument);
|
||||
if (hasRotation) {
|
||||
log.info("Source document has rotated pages; skipping form field copying.");
|
||||
} else {
|
||||
try {
|
||||
GeneralFormCopyUtils.copyAndTransformFormFields(
|
||||
sourceDocument,
|
||||
newDocument,
|
||||
newPage,
|
||||
PDPageContentStream.AppendMode.APPEND,
|
||||
true,
|
||||
true);
|
||||
}
|
||||
totalPages,
|
||||
pagesPerSheet,
|
||||
cols,
|
||||
rows,
|
||||
cellWidth,
|
||||
cellHeight);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to copy and transform form fields: {}", e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
PDPage sourcePage = sourceDocument.getPage(i);
|
||||
PDRectangle rect = sourcePage.getMediaBox();
|
||||
float scaleWidth = cellWidth / rect.getWidth();
|
||||
float scaleHeight = cellHeight / rect.getHeight();
|
||||
float scale = Math.min(scaleWidth, scaleHeight);
|
||||
|
||||
int adjustedPageIndex =
|
||||
i % pagesPerSheet; // Close the current content stream and create a new
|
||||
// page and content stream
|
||||
int rowIndex = adjustedPageIndex / cols;
|
||||
int colIndex = adjustedPageIndex % cols;
|
||||
|
||||
float x = colIndex * cellWidth + (cellWidth - rect.getWidth() * scale) / 2;
|
||||
float y =
|
||||
newPage.getMediaBox().getHeight()
|
||||
- ((rowIndex + 1) * cellHeight
|
||||
- (cellHeight - rect.getHeight() * scale) / 2);
|
||||
|
||||
contentStream.saveGraphicsState();
|
||||
contentStream.transform(Matrix.getTranslateInstance(x, y));
|
||||
contentStream.transform(Matrix.getScaleInstance(scale, scale));
|
||||
|
||||
PDFormXObject formXObject = layerUtility.importPageAsForm(sourceDocument, i);
|
||||
contentStream.drawForm(formXObject);
|
||||
|
||||
contentStream.restoreGraphicsState();
|
||||
|
||||
if (addBorder) {
|
||||
// Draw border around each page
|
||||
float borderX = colIndex * cellWidth;
|
||||
float borderY = newPage.getMediaBox().getHeight() - (rowIndex + 1) * cellHeight;
|
||||
contentStream.addRect(borderX, borderY, cellWidth, cellHeight);
|
||||
contentStream.stroke();
|
||||
}
|
||||
}
|
||||
|
||||
contentStream.close();
|
||||
|
||||
// If any source page is rotated, skip form copying/transformation entirely
|
||||
boolean hasRotation = GeneralFormCopyUtils.hasAnyRotatedPage(sourceDocument);
|
||||
if (hasRotation) {
|
||||
log.info("Source document has rotated pages; skipping form field copying.");
|
||||
} else {
|
||||
try {
|
||||
GeneralFormCopyUtils.copyAndTransformFormFields(
|
||||
sourceDocument,
|
||||
newDocument,
|
||||
totalPages,
|
||||
pagesPerSheet,
|
||||
cols,
|
||||
rows,
|
||||
cellWidth,
|
||||
cellHeight);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to copy and transform form fields: {}", e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
sourceDocument.close();
|
||||
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
newDocument.save(baos);
|
||||
newDocument.close();
|
||||
|
||||
byte[] result = baos.toByteArray();
|
||||
return WebResponseUtils.bytesToWebResponse(
|
||||
result,
|
||||
GeneralUtils.generateFilename(
|
||||
file.getOriginalFilename(), "_multi_page_layout.pdf"));
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
newDocument.save(baos);
|
||||
byte[] result = baos.toByteArray();
|
||||
return WebResponseUtils.bytesToWebResponse(
|
||||
result,
|
||||
GeneralUtils.generateFilename(
|
||||
file.getOriginalFilename(), "_multi_page_layout.pdf"));
|
||||
} // newDocument is closed here
|
||||
} // sourceDocument is closed here
|
||||
}
|
||||
}
|
||||
|
||||
+18
-15
@@ -53,25 +53,28 @@ public class PdfImageRemovalController {
|
||||
"This endpoint remove images from file to reduce the file size.Input:PDF"
|
||||
+ " Output:PDF Type:SISO")
|
||||
public ResponseEntity<byte[]> removeImages(@ModelAttribute PDFFile file) throws IOException {
|
||||
// Load the PDF document
|
||||
PDDocument document = pdfDocumentFactory.load(file);
|
||||
// Load the PDF document with proper resource management
|
||||
try (PDDocument document = pdfDocumentFactory.load(file)) {
|
||||
|
||||
// Remove images from the PDF document using the service
|
||||
PDDocument modifiedDocument = pdfImageRemovalService.removeImagesFromPdf(document);
|
||||
// Remove images from the PDF document using the service
|
||||
try (PDDocument modifiedDocument =
|
||||
pdfImageRemovalService.removeImagesFromPdf(document)) {
|
||||
|
||||
// Create a ByteArrayOutputStream to hold the modified PDF data
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
// Create a ByteArrayOutputStream to hold the modified PDF data
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
|
||||
// Save the modified PDF document to the output stream
|
||||
modifiedDocument.save(outputStream);
|
||||
modifiedDocument.close();
|
||||
// Save the modified PDF document to the output stream
|
||||
modifiedDocument.save(outputStream);
|
||||
|
||||
// Generate a new filename for the modified PDF
|
||||
String mergedFileName =
|
||||
GeneralUtils.generateFilename(
|
||||
file.getFileInput().getOriginalFilename(), "_images_removed.pdf");
|
||||
// Generate a new filename for the modified PDF
|
||||
String mergedFileName =
|
||||
GeneralUtils.generateFilename(
|
||||
file.getFileInput().getOriginalFilename(), "_images_removed.pdf");
|
||||
|
||||
// Convert the byte array to a web response and return it
|
||||
return WebResponseUtils.bytesToWebResponse(outputStream.toByteArray(), mergedFileName);
|
||||
// Convert the byte array to a web response and return it
|
||||
return WebResponseUtils.bytesToWebResponse(
|
||||
outputStream.toByteArray(), mergedFileName);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+49
-45
@@ -50,23 +50,25 @@ public class RearrangePagesPDFController {
|
||||
MultipartFile pdfFile = request.getFileInput();
|
||||
String pagesToDelete = request.getPageNumbers();
|
||||
|
||||
PDDocument document = pdfDocumentFactory.load(pdfFile);
|
||||
try (PDDocument document = pdfDocumentFactory.load(pdfFile)) {
|
||||
|
||||
// Split the page order string into an array of page numbers or range of numbers
|
||||
String[] pageOrderArr = pagesToDelete.split(",");
|
||||
// Split the page order string into an array of page numbers or range of numbers
|
||||
String[] pageOrderArr = pagesToDelete.split(",");
|
||||
|
||||
List<Integer> pagesToRemove =
|
||||
GeneralUtils.parsePageList(pageOrderArr, document.getNumberOfPages(), false);
|
||||
List<Integer> pagesToRemove =
|
||||
GeneralUtils.parsePageList(pageOrderArr, document.getNumberOfPages(), false);
|
||||
|
||||
Collections.sort(pagesToRemove);
|
||||
Collections.sort(pagesToRemove);
|
||||
|
||||
for (int i = pagesToRemove.size() - 1; i >= 0; i--) {
|
||||
int pageIndex = pagesToRemove.get(i);
|
||||
document.removePage(pageIndex);
|
||||
for (int i = pagesToRemove.size() - 1; i >= 0; i--) {
|
||||
int pageIndex = pagesToRemove.get(i);
|
||||
document.removePage(pageIndex);
|
||||
}
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document,
|
||||
GeneralUtils.generateFilename(
|
||||
pdfFile.getOriginalFilename(), "_removed_pages.pdf"));
|
||||
}
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document,
|
||||
GeneralUtils.generateFilename(pdfFile.getOriginalFilename(), "_removed_pages.pdf"));
|
||||
}
|
||||
|
||||
private List<Integer> removeFirst(int totalPages) {
|
||||
@@ -243,41 +245,43 @@ public class RearrangePagesPDFController {
|
||||
String pageOrder = request.getPageNumbers();
|
||||
String sortType = request.getCustomMode();
|
||||
try {
|
||||
// Load the input PDF
|
||||
PDDocument document = pdfDocumentFactory.load(pdfFile);
|
||||
// Load the input PDF with proper resource management
|
||||
try (PDDocument document = pdfDocumentFactory.load(pdfFile)) {
|
||||
|
||||
// Split the page order string into an array of page numbers or range of numbers
|
||||
String[] pageOrderArr = pageOrder != null ? pageOrder.split(",") : new String[0];
|
||||
int totalPages = document.getNumberOfPages();
|
||||
List<Integer> newPageOrder;
|
||||
if (sortType != null
|
||||
&& !sortType.isEmpty()
|
||||
&& !"custom".equals(sortType.toLowerCase(Locale.ROOT))) {
|
||||
newPageOrder = processSortTypes(sortType, totalPages, pageOrder);
|
||||
} else {
|
||||
newPageOrder = GeneralUtils.parsePageList(pageOrderArr, totalPages, false);
|
||||
// Split the page order string into an array of page numbers or range of numbers
|
||||
String[] pageOrderArr = pageOrder != null ? pageOrder.split(",") : new String[0];
|
||||
int totalPages = document.getNumberOfPages();
|
||||
List<Integer> newPageOrder;
|
||||
if (sortType != null
|
||||
&& !sortType.isEmpty()
|
||||
&& !"custom".equals(sortType.toLowerCase(Locale.ROOT))) {
|
||||
newPageOrder = processSortTypes(sortType, totalPages, pageOrder);
|
||||
} else {
|
||||
newPageOrder = GeneralUtils.parsePageList(pageOrderArr, totalPages, false);
|
||||
}
|
||||
log.info("newPageOrder = {}", newPageOrder);
|
||||
log.info("totalPages = {}", totalPages);
|
||||
// Create a new list to hold the pages in the new order
|
||||
List<PDPage> newPages = new ArrayList<>();
|
||||
for (int i = 0; i < newPageOrder.size(); i++) {
|
||||
newPages.add(document.getPage(newPageOrder.get(i)));
|
||||
}
|
||||
|
||||
// Create a new document based on the original one
|
||||
try (PDDocument rearrangedDocument =
|
||||
pdfDocumentFactory.createNewDocumentBasedOnOldDocument(document)) {
|
||||
|
||||
// Add the pages in the new order
|
||||
for (PDPage page : newPages) {
|
||||
rearrangedDocument.addPage(page);
|
||||
}
|
||||
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
rearrangedDocument,
|
||||
GeneralUtils.generateFilename(
|
||||
pdfFile.getOriginalFilename(), "_rearranged.pdf"));
|
||||
}
|
||||
}
|
||||
log.info("newPageOrder = {}", newPageOrder);
|
||||
log.info("totalPages = {}", totalPages);
|
||||
// Create a new list to hold the pages in the new order
|
||||
List<PDPage> newPages = new ArrayList<>();
|
||||
for (int i = 0; i < newPageOrder.size(); i++) {
|
||||
newPages.add(document.getPage(newPageOrder.get(i)));
|
||||
}
|
||||
|
||||
// Create a new document based on the original one
|
||||
PDDocument rearrangedDocument =
|
||||
pdfDocumentFactory.createNewDocumentBasedOnOldDocument(document);
|
||||
|
||||
// Add the pages in the new order
|
||||
for (PDPage page : newPages) {
|
||||
rearrangedDocument.addPage(page);
|
||||
}
|
||||
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
rearrangedDocument,
|
||||
GeneralUtils.generateFilename(
|
||||
pdfFile.getOriginalFilename(), "_rearranged.pdf"));
|
||||
} catch (IOException e) {
|
||||
ExceptionUtils.logException("document rearrangement", e);
|
||||
throw e;
|
||||
|
||||
+12
-11
@@ -47,19 +47,20 @@ public class RotationController {
|
||||
"error.angleNotMultipleOf90", "Angle must be a multiple of 90");
|
||||
}
|
||||
|
||||
// Load the PDF document
|
||||
PDDocument document = pdfDocumentFactory.load(request);
|
||||
// Load the PDF document with proper resource management
|
||||
try (PDDocument document = pdfDocumentFactory.load(request)) {
|
||||
|
||||
// Get the list of pages in the document
|
||||
PDPageTree pages = document.getPages();
|
||||
// Get the list of pages in the document
|
||||
PDPageTree pages = document.getPages();
|
||||
|
||||
for (PDPage page : pages) {
|
||||
page.setRotation(page.getRotation() + angle);
|
||||
for (PDPage page : pages) {
|
||||
page.setRotation(page.getRotation() + angle);
|
||||
}
|
||||
|
||||
// Return the rotated PDF as a response
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document,
|
||||
GeneralUtils.generateFilename(pdfFile.getOriginalFilename(), "_rotated.pdf"));
|
||||
}
|
||||
|
||||
// Return the rotated PDF as a response
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document,
|
||||
GeneralUtils.generateFilename(pdfFile.getOriginalFilename(), "_rotated.pdf"));
|
||||
}
|
||||
}
|
||||
|
||||
+58
-32
@@ -1,9 +1,10 @@
|
||||
package stirling.software.SPDF.controller.api;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.util.*;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
@@ -18,38 +19,37 @@ import org.apache.pdfbox.util.Matrix;
|
||||
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.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
|
||||
|
||||
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.config.swagger.MultiFileResponse;
|
||||
import stirling.software.SPDF.model.SplitTypes;
|
||||
import stirling.software.SPDF.model.api.SplitPdfBySectionsRequest;
|
||||
import stirling.software.common.annotations.AutoJobPostMapping;
|
||||
import stirling.software.common.annotations.api.GeneralApi;
|
||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||
import stirling.software.common.util.ExceptionUtils;
|
||||
import stirling.software.common.util.GeneralUtils;
|
||||
import stirling.software.common.util.PDFService;
|
||||
import stirling.software.common.util.TempFile;
|
||||
import stirling.software.common.util.TempFileManager;
|
||||
import stirling.software.common.util.WebResponseUtils;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/general")
|
||||
@Tag(name = "General", description = "General APIs")
|
||||
@GeneralApi
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class SplitPdfBySectionsController {
|
||||
|
||||
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
||||
private final TempFileManager tempFileManager;
|
||||
private final PDFService pdfService;
|
||||
|
||||
@PostMapping(value = "/split-pdf-by-sections", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
@AutoJobPostMapping(
|
||||
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
|
||||
value = "/split-pdf-by-sections")
|
||||
@MultiFileResponse
|
||||
@Operation(
|
||||
summary = "Split PDF pages into smaller sections",
|
||||
description =
|
||||
@@ -57,8 +57,8 @@ public class SplitPdfBySectionsController {
|
||||
+ " which page to split, and how to split"
|
||||
+ " ( halves, thirds, quarters, etc.), both vertically and horizontally."
|
||||
+ " Input:PDF Output:ZIP-PDF Type:SISO")
|
||||
public ResponseEntity<StreamingResponseBody> splitPdf(
|
||||
@ModelAttribute SplitPdfBySectionsRequest request) throws Exception {
|
||||
public ResponseEntity<byte[]> splitPdf(@ModelAttribute SplitPdfBySectionsRequest request)
|
||||
throws Exception {
|
||||
MultipartFile file = request.getFileInput();
|
||||
String pageNumbers = request.getPageNumbers();
|
||||
SplitTypes splitMode =
|
||||
@@ -77,9 +77,10 @@ public class SplitPdfBySectionsController {
|
||||
String filename = GeneralUtils.generateFilename(file.getOriginalFilename(), "_split");
|
||||
|
||||
if (merge) {
|
||||
TempFile tempFile = new TempFile(tempFileManager, ".pdf");
|
||||
try (PDDocument mergedDoc = pdfDocumentFactory.createNewDocument();
|
||||
OutputStream out = Files.newOutputStream(tempFile.getPath())) {
|
||||
try (PDDocument mergedDoc =
|
||||
pdfDocumentFactory.createNewDocumentBasedOnOldDocument(
|
||||
sourceDocument);
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
|
||||
LayerUtility layerUtility = new LayerUtility(mergedDoc);
|
||||
for (int pageIndex = 0;
|
||||
pageIndex < sourceDocument.getNumberOfPages();
|
||||
@@ -96,9 +97,9 @@ public class SplitPdfBySectionsController {
|
||||
addPageToTarget(sourceDocument, pageIndex, mergedDoc, layerUtility);
|
||||
}
|
||||
}
|
||||
mergedDoc.save(out);
|
||||
mergedDoc.save(baos);
|
||||
return WebResponseUtils.baosToWebResponse(baos, filename + ".pdf");
|
||||
}
|
||||
return WebResponseUtils.pdfFileToWebResponse(tempFile, filename + ".pdf");
|
||||
} else {
|
||||
TempFile zipTempFile = new TempFile(tempFileManager, ".zip");
|
||||
try (ZipOutputStream zipOut =
|
||||
@@ -131,6 +132,13 @@ public class SplitPdfBySectionsController {
|
||||
+ sectionNum
|
||||
+ ".pdf";
|
||||
saveDocToZip(subDoc, zipOut, entryName);
|
||||
} catch (IOException e) {
|
||||
log.error(
|
||||
"Error creating section {} for page {}",
|
||||
(i * verti + j + 1),
|
||||
pageNum,
|
||||
e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -140,12 +148,23 @@ public class SplitPdfBySectionsController {
|
||||
addPageToTarget(sourceDocument, pageIndex, subDoc, subLayerUtility);
|
||||
String entryName = filename + "_" + pageNum + "_1.pdf";
|
||||
saveDocToZip(subDoc, zipOut, entryName);
|
||||
} catch (IOException e) {
|
||||
log.error("Error processing unsplit page {}", pageNum, e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("Error creating ZIP file with split PDF sections", e);
|
||||
throw e;
|
||||
}
|
||||
return WebResponseUtils.zipFileToWebResponse(zipTempFile, filename + ".zip");
|
||||
byte[] zipBytes = Files.readAllBytes(zipTempFile.getPath());
|
||||
return WebResponseUtils.bytesToWebResponse(
|
||||
zipBytes, filename + ".zip", MediaType.APPLICATION_OCTET_STREAM);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Error splitting PDF file: {}", file.getOriginalFilename(), e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,6 +179,9 @@ public class SplitPdfBySectionsController {
|
||||
try (PDPageContentStream contentStream =
|
||||
new PDPageContentStream(targetDoc, newPage, AppendMode.APPEND, true, true)) {
|
||||
contentStream.drawForm(form);
|
||||
} catch (IOException e) {
|
||||
log.error("Error adding page {} to target document", pageIndex, e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,6 +219,10 @@ public class SplitPdfBySectionsController {
|
||||
contentStream.transform(new Matrix(1, 0, 0, 1, translateX, translateY));
|
||||
contentStream.drawForm(form);
|
||||
contentStream.restoreGraphicsState();
|
||||
} catch (IOException e) {
|
||||
log.error(
|
||||
"Error adding split section ({}, {}) for page {}", i, j, pageIndex, e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -233,6 +259,14 @@ public class SplitPdfBySectionsController {
|
||||
contentStream.transform(new Matrix(1, 0, 0, 1, translateX, translateY));
|
||||
contentStream.drawForm(form);
|
||||
contentStream.restoreGraphicsState();
|
||||
} catch (IOException e) {
|
||||
log.error(
|
||||
"Error adding single section ({}, {}) for page {} to target",
|
||||
horizIndex,
|
||||
vertIndex,
|
||||
pageIndex,
|
||||
e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -264,27 +298,19 @@ public class SplitPdfBySectionsController {
|
||||
break;
|
||||
|
||||
case SPLIT_ALL:
|
||||
for (int i = 0; i < totalPages; i++) {
|
||||
pagesToSplit.add(i);
|
||||
}
|
||||
pagesToSplit.addAll(IntStream.range(0, totalPages).boxed().toList());
|
||||
break;
|
||||
|
||||
case SPLIT_ALL_EXCEPT_FIRST:
|
||||
for (int i = 1; i < totalPages; i++) {
|
||||
pagesToSplit.add(i);
|
||||
}
|
||||
pagesToSplit.addAll(IntStream.range(1, totalPages).boxed().toList());
|
||||
break;
|
||||
|
||||
case SPLIT_ALL_EXCEPT_LAST:
|
||||
for (int i = 0; i < totalPages - 1; i++) {
|
||||
pagesToSplit.add(i);
|
||||
}
|
||||
pagesToSplit.addAll(IntStream.range(0, totalPages - 1).boxed().toList());
|
||||
break;
|
||||
|
||||
case SPLIT_ALL_EXCEPT_FIRST_AND_LAST:
|
||||
for (int i = 1; i < totalPages - 1; i++) {
|
||||
pagesToSplit.add(i);
|
||||
}
|
||||
pagesToSplit.addAll(IntStream.range(1, totalPages - 1).boxed().toList());
|
||||
break;
|
||||
|
||||
default:
|
||||
|
||||
+26
-24
@@ -473,34 +473,36 @@ public class SplitPdfBySizeController {
|
||||
PDDocument document, ZipOutputStream zipOut, String baseFilename, int index)
|
||||
throws IOException {
|
||||
log.debug("Starting saveDocumentToZip for document part {}", index);
|
||||
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
|
||||
try (ByteArrayOutputStream outStream = new ByteArrayOutputStream()) {
|
||||
|
||||
try (PDDocument doc = document) {
|
||||
log.debug("Saving document part {} to byte array", index);
|
||||
doc.save(outStream);
|
||||
log.debug("Successfully saved document part {} ({} bytes)", index, outStream.size());
|
||||
} catch (Exception e) {
|
||||
log.error("Error saving document part {} to byte array", index, e);
|
||||
throw ExceptionUtils.createFileProcessingException("split", e);
|
||||
}
|
||||
try (PDDocument doc = document) {
|
||||
log.debug("Saving document part {} to byte array", index);
|
||||
doc.save(outStream);
|
||||
log.debug(
|
||||
"Successfully saved document part {} ({} bytes)", index, outStream.size());
|
||||
} catch (Exception e) {
|
||||
log.error("Error saving document part {} to byte array", index, e);
|
||||
throw ExceptionUtils.createFileProcessingException("split", e);
|
||||
}
|
||||
|
||||
try {
|
||||
// Create a new zip entry
|
||||
String entryName = baseFilename + "_" + index + ".pdf";
|
||||
log.debug("Creating ZIP entry: {}", entryName);
|
||||
ZipEntry zipEntry = new ZipEntry(entryName);
|
||||
zipOut.putNextEntry(zipEntry);
|
||||
try {
|
||||
// Create a new zip entry
|
||||
String entryName = baseFilename + "_" + index + ".pdf";
|
||||
log.debug("Creating ZIP entry: {}", entryName);
|
||||
ZipEntry zipEntry = new ZipEntry(entryName);
|
||||
zipOut.putNextEntry(zipEntry);
|
||||
|
||||
byte[] bytes = outStream.toByteArray();
|
||||
log.debug("Writing {} bytes to ZIP entry", bytes.length);
|
||||
zipOut.write(bytes);
|
||||
byte[] bytes = outStream.toByteArray();
|
||||
log.debug("Writing {} bytes to ZIP entry", bytes.length);
|
||||
zipOut.write(bytes);
|
||||
|
||||
log.debug("Closing ZIP entry");
|
||||
zipOut.closeEntry();
|
||||
log.debug("Successfully added document part {} to ZIP", index);
|
||||
} catch (Exception e) {
|
||||
log.error("Error adding document part {} to ZIP", index, e);
|
||||
throw ExceptionUtils.createFileProcessingException("split", e);
|
||||
log.debug("Closing ZIP entry");
|
||||
zipOut.closeEntry();
|
||||
log.debug("Successfully added document part {} to ZIP", index);
|
||||
} catch (Exception e) {
|
||||
log.error("Error adding document part {} to ZIP", index, e);
|
||||
throw ExceptionUtils.createFileProcessingException("split", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,7 +191,7 @@ public class UIDataController {
|
||||
}
|
||||
|
||||
private List<String> getAvailableTesseractLanguages() {
|
||||
String tessdataDir = applicationProperties.getSystem().getTessdataDir();
|
||||
String tessdataDir = runtimePathConfig.getTessDataPath();
|
||||
java.io.File[] files = new java.io.File(tessdataDir).listFiles();
|
||||
if (files == null) {
|
||||
return Collections.emptyList();
|
||||
|
||||
+10
-5
@@ -10,6 +10,7 @@ import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.util.HtmlUtils;
|
||||
|
||||
import io.github.pixee.security.Filenames;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
@@ -152,20 +153,24 @@ public class ConvertEmlToPDF {
|
||||
}
|
||||
|
||||
private static @NotNull String buildErrorMessage(Exception e, String originalFilename) {
|
||||
String safeFilename = HtmlUtils.htmlEscape(originalFilename);
|
||||
String exceptionMessage = e.getMessage();
|
||||
String safeExceptionMessage =
|
||||
exceptionMessage == null ? "Unknown error" : HtmlUtils.htmlEscape(exceptionMessage);
|
||||
String errorMessage;
|
||||
if (e.getMessage() != null && e.getMessage().contains("Invalid EML")) {
|
||||
if (exceptionMessage != null && exceptionMessage.contains("Invalid EML")) {
|
||||
errorMessage =
|
||||
"Invalid EML file format. Please ensure you've uploaded a valid email"
|
||||
+ " file ("
|
||||
+ originalFilename
|
||||
+ safeFilename
|
||||
+ ").";
|
||||
} else if (e.getMessage() != null && e.getMessage().contains("WeasyPrint")) {
|
||||
} else if (exceptionMessage != null && exceptionMessage.contains("WeasyPrint")) {
|
||||
errorMessage =
|
||||
"PDF generation failed for "
|
||||
+ originalFilename
|
||||
+ safeFilename
|
||||
+ ". This may be due to complex email formatting.";
|
||||
} else {
|
||||
errorMessage = "Conversion failed for " + originalFilename + ": " + e.getMessage();
|
||||
errorMessage = "Conversion failed for " + safeFilename + ": " + safeExceptionMessage;
|
||||
}
|
||||
return errorMessage;
|
||||
}
|
||||
|
||||
+3
-3
@@ -188,15 +188,15 @@ public class ConvertImgPDFController {
|
||||
bodyBytes = Files.readAllBytes(webpFilePath);
|
||||
} else {
|
||||
// Create a ZIP file containing all WebP images
|
||||
ByteArrayOutputStream zipOutputStream = new ByteArrayOutputStream();
|
||||
try (ZipOutputStream zos = new ZipOutputStream(zipOutputStream)) {
|
||||
try (ByteArrayOutputStream zipOutputStream = new ByteArrayOutputStream();
|
||||
ZipOutputStream zos = new ZipOutputStream(zipOutputStream)) {
|
||||
for (Path webpFile : webpFiles) {
|
||||
zos.putNextEntry(new ZipEntry(webpFile.getFileName().toString()));
|
||||
Files.copy(webpFile, zos);
|
||||
zos.closeEntry();
|
||||
}
|
||||
bodyBytes = zipOutputStream.toByteArray();
|
||||
}
|
||||
bodyBytes = zipOutputStream.toByteArray();
|
||||
}
|
||||
// Clean up the temporary files
|
||||
Files.deleteIfExists(tempFile);
|
||||
|
||||
+6
-5
@@ -196,11 +196,12 @@ public class ConvertOfficeController {
|
||||
try {
|
||||
file = convertToPdf(inputFile);
|
||||
|
||||
PDDocument doc = pdfDocumentFactory.load(file);
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
doc,
|
||||
GeneralUtils.generateFilename(
|
||||
inputFile.getOriginalFilename(), "_convertedToPDF.pdf"));
|
||||
try (PDDocument doc = pdfDocumentFactory.load(file)) {
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
doc,
|
||||
GeneralUtils.generateFilename(
|
||||
inputFile.getOriginalFilename(), "_convertedToPDF.pdf"));
|
||||
}
|
||||
} finally {
|
||||
if (file != null && file.getParent() != null) {
|
||||
FileUtils.deleteDirectory(file.getParentFile());
|
||||
|
||||
+267
-28
@@ -21,6 +21,7 @@ import org.apache.pdfbox.cos.COSArray;
|
||||
import org.apache.pdfbox.cos.COSBase;
|
||||
import org.apache.pdfbox.cos.COSDictionary;
|
||||
import org.apache.pdfbox.cos.COSName;
|
||||
import org.apache.pdfbox.cos.COSStream;
|
||||
import org.apache.pdfbox.io.RandomAccessRead;
|
||||
import org.apache.pdfbox.io.RandomAccessReadBufferedFile;
|
||||
import org.apache.pdfbox.pdfwriter.compress.CompressParameters;
|
||||
@@ -51,7 +52,7 @@ import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;
|
||||
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
|
||||
import org.apache.pdfbox.pdmodel.graphics.optionalcontent.PDOptionalContentProperties;
|
||||
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
|
||||
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationTextMarkup;
|
||||
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationHighlight;
|
||||
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget;
|
||||
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceDictionary;
|
||||
import org.apache.pdfbox.pdmodel.interactive.viewerpreferences.PDViewerPreferences;
|
||||
@@ -378,7 +379,6 @@ public class ConvertPDFToPDFA {
|
||||
command.add("-sOutputICCProfile=" + colorProfiles.rgb().toAbsolutePath());
|
||||
command.add("-sDefaultRGBProfile=" + colorProfiles.rgb().toAbsolutePath());
|
||||
command.add("-sDefaultGrayProfile=" + colorProfiles.gray().toAbsolutePath());
|
||||
command.add("-sDefaultCMYKProfile=" + colorProfiles.rgb().toAbsolutePath());
|
||||
|
||||
// Font handling optimized for PDF/A CIDSet compliance
|
||||
command.add("-dEmbedAllFonts=true");
|
||||
@@ -673,25 +673,55 @@ public class ConvertPDFToPDFA {
|
||||
if (descriptor == null) continue;
|
||||
|
||||
// Check if this is a Type1 font
|
||||
if (fontNameStr.contains("Type1")
|
||||
|| descriptor.getFontFile() != null
|
||||
|| (descriptor.getFontFile2() == null
|
||||
&& descriptor.getFontFile3() == null)) {
|
||||
boolean isType1 =
|
||||
isType1Font(font)
|
||||
|| descriptor.getFontFile() != null
|
||||
|| (descriptor.getFontFile2() == null
|
||||
&& descriptor.getFontFile3() == null);
|
||||
|
||||
String existingCharSet =
|
||||
descriptor.getCOSObject().getString(COSName.CHAR_SET);
|
||||
if (isType1) {
|
||||
COSDictionary descDict = descriptor.getCOSObject();
|
||||
String existingCharSet = descDict.getString(COSName.CHAR_SET);
|
||||
|
||||
String glyphSet = buildStandardType1GlyphSet();
|
||||
if (!glyphSet.isEmpty()) {
|
||||
if (existingCharSet == null
|
||||
|| existingCharSet.trim().isEmpty()
|
||||
|| countGlyphs(existingCharSet) < countGlyphs(glyphSet)) {
|
||||
descriptor.getCOSObject().setString(COSName.CHAR_SET, glyphSet);
|
||||
// Check if font is embedded and if CharSet might be invalid
|
||||
boolean fontEmbedded = font.isEmbedded();
|
||||
boolean hasFontFile =
|
||||
descriptor.getFontFile() != null
|
||||
|| descriptor.getFontFile2() != null
|
||||
|| descriptor.getFontFile3() != null;
|
||||
|
||||
// For PDF/A compliance: if CharSet exists but font is subsetted or
|
||||
// we can't verify it matches the font file, remove it to avoid validation
|
||||
// errors
|
||||
if (existingCharSet != null && !existingCharSet.trim().isEmpty()) {
|
||||
// If the font appears to be subsetted (indicated by subset prefix in
|
||||
// name)
|
||||
// or if we can't verify the CharSet is correct, remove it
|
||||
if (fontNameStr.contains("+") || fontNameStr.contains("Subset")) {
|
||||
descDict.removeItem(COSName.CHAR_SET);
|
||||
log.debug(
|
||||
"Fixed CharSet for Type1 font {} with {} glyphs (was: {})",
|
||||
fontNameStr,
|
||||
countGlyphs(glyphSet),
|
||||
existingCharSet != null ? countGlyphs(existingCharSet) : 0);
|
||||
"Removed potentially invalid CharSet from subsetted Type1 font: {}",
|
||||
fontNameStr);
|
||||
} else if (!hasFontFile && fontEmbedded) {
|
||||
// Font is embedded but we can't verify CharSet, remove it
|
||||
descDict.removeItem(COSName.CHAR_SET);
|
||||
log.debug(
|
||||
"Removed unverifiable CharSet from embedded Type1 font: {}",
|
||||
fontNameStr);
|
||||
}
|
||||
} else if (existingCharSet == null || existingCharSet.trim().isEmpty()) {
|
||||
// Only add CharSet if font is not subsetted and we can verify it
|
||||
if (!fontNameStr.contains("+")
|
||||
&& !fontNameStr.contains("Subset")
|
||||
&& hasFontFile) {
|
||||
String glyphSet = buildStandardType1GlyphSet();
|
||||
if (!glyphSet.isEmpty()) {
|
||||
descDict.setString(COSName.CHAR_SET, glyphSet);
|
||||
log.debug(
|
||||
"Added missing CharSet for Type1 font {} with {} glyphs",
|
||||
fontNameStr,
|
||||
countGlyphs(glyphSet));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1211,7 +1241,7 @@ public class ConvertPDFToPDFA {
|
||||
List<PDAnnotation> annotations = page.getAnnotations();
|
||||
for (PDAnnotation annot : annotations) {
|
||||
if (ANNOTATION_HIGHLIGHT.equals(annot.getSubtype())
|
||||
&& annot instanceof PDAnnotationTextMarkup highlight) {
|
||||
&& annot instanceof PDAnnotationHighlight highlight) {
|
||||
float[] colorComponents =
|
||||
highlight.getColor() != null
|
||||
? highlight.getColor().getComponents()
|
||||
@@ -1349,13 +1379,22 @@ public class ConvertPDFToPDFA {
|
||||
|
||||
for (COSBase base : ocgArray) {
|
||||
if (base instanceof COSDictionary ocgDict) {
|
||||
if (!ocgDict.containsKey(COSName.NAME)) {
|
||||
// Ensure Name entry exists and is not empty
|
||||
String nameValue = ocgDict.getString(COSName.NAME);
|
||||
if (nameValue == null || nameValue.trim().isEmpty()) {
|
||||
String newName = "Layer " + unnamedCount++;
|
||||
ocgDict.setString(COSName.NAME, newName);
|
||||
log.debug("Fixed OCG missing name, set to: {}", newName);
|
||||
log.debug("Fixed OCG missing or empty name, set to: {}", newName);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (ocgs instanceof COSDictionary ocgDict) {
|
||||
// Handle case where OCGS is a single dictionary instead of array
|
||||
String nameValue = ocgDict.getString(COSName.NAME);
|
||||
if (nameValue == null || nameValue.trim().isEmpty()) {
|
||||
ocgDict.setString(COSName.NAME, "Layer 1");
|
||||
log.debug("Fixed single OCG missing or empty name");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1479,7 +1518,9 @@ public class ConvertPDFToPDFA {
|
||||
Path pdfaDefFile = createPdfaDefFile(workingDir, colorProfiles, profile);
|
||||
|
||||
// Preprocess PDF for PDF/A compliance using the sanitizer
|
||||
Path sanitizedInputPdf = sanitizePdfWithPdfBox(inputPdf);
|
||||
// We add a white background to ensure transparency is flattened correctly against white
|
||||
// instead of black, addressing common PDF/A conversion issues.
|
||||
Path sanitizedInputPdf = sanitizePdfWithPdfBox(inputPdf, true);
|
||||
Path preprocessedPdf = sanitizedInputPdf != null ? sanitizedInputPdf : inputPdf;
|
||||
|
||||
// For PDF/A-1, clean CIDSet issues that may cause validation failures
|
||||
@@ -1500,11 +1541,14 @@ public class ConvertPDFToPDFA {
|
||||
buildGhostscriptCommand(
|
||||
inputForGs, outputPdf, colorProfiles, workingDir, profile, pdfaDefFile);
|
||||
|
||||
log.info("Running Ghostscript command: {}", String.join(" ", command));
|
||||
|
||||
ProcessExecutorResult result =
|
||||
ProcessExecutor.getInstance(ProcessExecutor.Processes.GHOSTSCRIPT)
|
||||
.runCommandWithOutputHandling(command);
|
||||
|
||||
if (result.getRc() != 0) {
|
||||
log.error("Ghostscript failed with output: {}", result.getMessages());
|
||||
throw new IOException("Ghostscript exited with code " + result.getRc());
|
||||
}
|
||||
|
||||
@@ -1665,6 +1709,7 @@ public class ConvertPDFToPDFA {
|
||||
}
|
||||
|
||||
private byte[] convertWithPdfBoxMethod(Path inputPath, PdfaProfile profile) throws Exception {
|
||||
log.info("Starting PDFBox/LibreOffice conversion for PDF/A-{}", profile.getPart());
|
||||
Path tempInputFile = null;
|
||||
byte[] fileBytes;
|
||||
Path loPdfPath = null;
|
||||
@@ -1720,17 +1765,20 @@ public class ConvertPDFToPDFA {
|
||||
ColorProfiles colorProfiles = prepareColorProfiles(workingDir);
|
||||
|
||||
// Sanitize the PDF before PDF/X conversion for better Ghostscript compatibility
|
||||
Path sanitizedInputPdf = sanitizePdfWithPdfBox(inputPdf);
|
||||
Path sanitizedInputPdf = sanitizePdfWithPdfBox(inputPdf, true);
|
||||
Path inputForGs = sanitizedInputPdf != null ? sanitizedInputPdf : inputPdf;
|
||||
|
||||
List<String> command =
|
||||
buildGhostscriptCommandX(inputForGs, outputPdf, colorProfiles, workingDir, profile);
|
||||
|
||||
log.info("Running Ghostscript PDF/X command: {}", String.join(" ", command));
|
||||
|
||||
ProcessExecutorResult result =
|
||||
ProcessExecutor.getInstance(ProcessExecutor.Processes.GHOSTSCRIPT)
|
||||
.runCommandWithOutputHandling(command);
|
||||
|
||||
if (result.getRc() != 0) {
|
||||
log.error("Ghostscript PDF/X failed with output: {}", result.getMessages());
|
||||
throw new IOException("Ghostscript exited with code " + result.getRc());
|
||||
}
|
||||
|
||||
@@ -1796,12 +1844,12 @@ public class ConvertPDFToPDFA {
|
||||
}
|
||||
}
|
||||
|
||||
private Path sanitizePdfWithPdfBox(Path inputPdf) {
|
||||
private Path sanitizePdfWithPdfBox(Path inputPdf, boolean addWhiteBackground) {
|
||||
try {
|
||||
Path sanitizedPath =
|
||||
inputPdf.getParent().resolve("sanitized_" + inputPdf.getFileName().toString());
|
||||
|
||||
sanitizeDocument(inputPdf, sanitizedPath);
|
||||
sanitizeDocument(inputPdf, sanitizedPath, addWhiteBackground);
|
||||
|
||||
log.info("PDF sanitized with PDFBox for better Ghostscript compatibility");
|
||||
return sanitizedPath;
|
||||
@@ -1813,7 +1861,8 @@ public class ConvertPDFToPDFA {
|
||||
}
|
||||
}
|
||||
|
||||
private void sanitizeDocument(Path inputPath, Path outputPath) throws IOException {
|
||||
private void sanitizeDocument(Path inputPath, Path outputPath, boolean addWhiteBackground)
|
||||
throws IOException {
|
||||
try (PDDocument doc = Loader.loadPDF(inputPath.toFile())) {
|
||||
Map<String, DocumentSanitizer> sanitizers = new LinkedHashMap<>();
|
||||
sanitizers.put("Flatten highlight annotations", this::flattenHighlightsToContent);
|
||||
@@ -1824,6 +1873,11 @@ public class ConvertPDFToPDFA {
|
||||
sanitizers.put("Ensure embedded file compliance", this::ensureEmbeddedFileCompliance);
|
||||
sanitizers.put(
|
||||
"Fix optional content groups", ConvertPDFToPDFA::fixOptionalContentGroups);
|
||||
sanitizers.put("Fix separation color spaces", this::fixSeparationColorSpaces);
|
||||
|
||||
if (addWhiteBackground) {
|
||||
sanitizers.put("Add white background", this::addWhiteBackground);
|
||||
}
|
||||
|
||||
for (Map.Entry<String, DocumentSanitizer> entry : sanitizers.entrySet()) {
|
||||
try {
|
||||
@@ -1841,6 +1895,191 @@ public class ConvertPDFToPDFA {
|
||||
}
|
||||
}
|
||||
|
||||
private void fixSeparationColorSpaces(PDDocument doc) throws IOException {
|
||||
Map<String, COSBase> knownTintTransforms = new HashMap<>();
|
||||
Set<COSBase> visitedResources = new HashSet<>();
|
||||
|
||||
// Process all pages first to collect all separation color spaces
|
||||
for (PDPage page : doc.getPages()) {
|
||||
PDResources resources = page.getResources();
|
||||
processResourcesForSeparation(resources, knownTintTransforms, visitedResources);
|
||||
}
|
||||
|
||||
// Process document-level resources if they exist
|
||||
PDDocumentCatalog catalog = doc.getDocumentCatalog();
|
||||
if (catalog != null) {
|
||||
PDResources docResources =
|
||||
catalog.getAcroForm() != null
|
||||
? catalog.getAcroForm().getDefaultResources()
|
||||
: null;
|
||||
if (docResources != null) {
|
||||
processResourcesForSeparation(docResources, knownTintTransforms, visitedResources);
|
||||
}
|
||||
}
|
||||
|
||||
// Second pass: ensure all separations with the same name use the same tintTransform
|
||||
visitedResources.clear();
|
||||
for (PDPage page : doc.getPages()) {
|
||||
PDResources resources = page.getResources();
|
||||
enforceSeparationConsistency(resources, knownTintTransforms, visitedResources);
|
||||
}
|
||||
}
|
||||
|
||||
private void processResourcesForSeparation(
|
||||
PDResources resources,
|
||||
Map<String, COSBase> knownTintTransforms,
|
||||
Set<COSBase> visitedResources) {
|
||||
if (resources == null) return;
|
||||
|
||||
// Prevent infinite recursion if resources are shared or cyclic
|
||||
if (!visitedResources.add(resources.getCOSObject())) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check defined ColorSpaces
|
||||
COSDictionary csDict =
|
||||
(COSDictionary) resources.getCOSObject().getDictionaryObject(COSName.COLORSPACE);
|
||||
if (csDict != null) {
|
||||
for (COSName name : csDict.keySet()) {
|
||||
COSBase csVal = csDict.getDictionaryObject(name);
|
||||
checkAndFixSeparation(csVal, knownTintTransforms);
|
||||
}
|
||||
}
|
||||
|
||||
// Recursively check XObjects (Forms)
|
||||
COSDictionary xObjDict =
|
||||
(COSDictionary) resources.getCOSObject().getDictionaryObject(COSName.XOBJECT);
|
||||
if (xObjDict != null) {
|
||||
for (COSName name : xObjDict.keySet()) {
|
||||
COSBase xObj = xObjDict.getDictionaryObject(name);
|
||||
if (xObj instanceof COSStream stream) {
|
||||
COSName type = (COSName) stream.getDictionaryObject(COSName.SUBTYPE);
|
||||
if (COSName.FORM.equals(type)) {
|
||||
COSBase formRes = stream.getDictionaryObject(COSName.RESOURCES);
|
||||
if (formRes instanceof COSDictionary formResDict) {
|
||||
processResourcesForSeparation(
|
||||
new PDResources(formResDict),
|
||||
knownTintTransforms,
|
||||
visitedResources);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void checkAndFixSeparation(COSBase cs, Map<String, COSBase> knownTintTransforms) {
|
||||
if (cs instanceof COSArray arr && arr.size() >= 4) {
|
||||
COSBase type = arr.getObject(0);
|
||||
if (COSName.SEPARATION.equals(type)) {
|
||||
// Separation: [/Separation name altSpace tintTransform]
|
||||
COSBase nameBase = arr.getObject(1);
|
||||
if (nameBase instanceof COSName colorName) {
|
||||
String name = colorName.getName();
|
||||
COSBase tintTransform = arr.getObject(3);
|
||||
|
||||
if (knownTintTransforms.containsKey(name)) {
|
||||
COSBase known = knownTintTransforms.get(name);
|
||||
// If objects are not identical (same reference), unify them
|
||||
if (known != tintTransform) {
|
||||
arr.set(3, known);
|
||||
log.debug("Unified TintTransform for Separation color: {}", name);
|
||||
}
|
||||
} else {
|
||||
// Store the first encountered tintTransform for this color name
|
||||
knownTintTransforms.put(name, tintTransform);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void enforceSeparationConsistency(
|
||||
PDResources resources,
|
||||
Map<String, COSBase> knownTintTransforms,
|
||||
Set<COSBase> visitedResources) {
|
||||
if (resources == null) return;
|
||||
|
||||
// Prevent infinite recursion
|
||||
if (!visitedResources.add(resources.getCOSObject())) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check defined ColorSpaces
|
||||
COSDictionary csDict =
|
||||
(COSDictionary) resources.getCOSObject().getDictionaryObject(COSName.COLORSPACE);
|
||||
if (csDict != null) {
|
||||
for (COSName name : csDict.keySet()) {
|
||||
COSBase csVal = csDict.getDictionaryObject(name);
|
||||
enforceSeparationTintTransform(csVal, knownTintTransforms);
|
||||
}
|
||||
}
|
||||
|
||||
// Recursively check XObjects (Forms)
|
||||
COSDictionary xObjDict =
|
||||
(COSDictionary) resources.getCOSObject().getDictionaryObject(COSName.XOBJECT);
|
||||
if (xObjDict != null) {
|
||||
for (COSName name : xObjDict.keySet()) {
|
||||
COSBase xObj = xObjDict.getDictionaryObject(name);
|
||||
if (xObj instanceof COSStream stream) {
|
||||
COSName type = (COSName) stream.getDictionaryObject(COSName.SUBTYPE);
|
||||
if (COSName.FORM.equals(type)) {
|
||||
COSBase formRes = stream.getDictionaryObject(COSName.RESOURCES);
|
||||
if (formRes instanceof COSDictionary formResDict) {
|
||||
enforceSeparationConsistency(
|
||||
new PDResources(formResDict),
|
||||
knownTintTransforms,
|
||||
visitedResources);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void enforceSeparationTintTransform(
|
||||
COSBase cs, Map<String, COSBase> knownTintTransforms) {
|
||||
if (cs instanceof COSArray arr && arr.size() >= 4) {
|
||||
COSBase type = arr.getObject(0);
|
||||
if (COSName.SEPARATION.equals(type)) {
|
||||
COSBase nameBase = arr.getObject(1);
|
||||
if (nameBase instanceof COSName colorName) {
|
||||
String name = colorName.getName();
|
||||
COSBase tintTransform = arr.getObject(3);
|
||||
|
||||
// Ensure all separations with the same name use the same tintTransform
|
||||
// reference
|
||||
if (knownTintTransforms.containsKey(name)) {
|
||||
COSBase known = knownTintTransforms.get(name);
|
||||
if (known != tintTransform) {
|
||||
arr.set(3, known);
|
||||
log.debug(
|
||||
"Enforced consistent TintTransform for Separation color: {}",
|
||||
name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void addWhiteBackground(PDDocument doc) throws IOException {
|
||||
for (PDPage page : doc.getPages()) {
|
||||
PDRectangle mediaBox = page.getMediaBox();
|
||||
try (PDPageContentStream cs =
|
||||
new PDPageContentStream(
|
||||
doc, page, PDPageContentStream.AppendMode.PREPEND, true, true)) {
|
||||
cs.setNonStrokingColor(Color.WHITE);
|
||||
cs.addRect(
|
||||
mediaBox.getLowerLeftX(),
|
||||
mediaBox.getLowerLeftY(),
|
||||
mediaBox.getWidth(),
|
||||
mediaBox.getHeight());
|
||||
cs.fill();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void flattenHighlightsToContent(PDDocument doc) throws IOException {
|
||||
for (PDPage page : doc.getPages()) {
|
||||
List<PDAnnotation> annotations = new ArrayList<>(page.getAnnotations());
|
||||
@@ -1851,7 +2090,7 @@ public class ConvertPDFToPDFA {
|
||||
doc, page, PDPageContentStream.AppendMode.PREPEND, true, true)) {
|
||||
|
||||
for (PDAnnotation annot : annotations) {
|
||||
if (annot instanceof PDAnnotationTextMarkup highlight
|
||||
if (annot instanceof PDAnnotationHighlight highlight
|
||||
&& ANNOTATION_HIGHLIGHT.equals(annot.getSubtype())) {
|
||||
|
||||
PDColor color = highlight.getColor();
|
||||
@@ -1973,7 +2212,7 @@ public class ConvertPDFToPDFA {
|
||||
return annot.getAppearance() != null;
|
||||
}
|
||||
|
||||
if (annot instanceof PDAnnotationTextMarkup) {
|
||||
if (annot instanceof PDAnnotationHighlight) {
|
||||
return false; // Will be handled by flattening
|
||||
}
|
||||
|
||||
|
||||
+85
-82
@@ -47,102 +47,105 @@ public class AutoRenameController {
|
||||
MultipartFile file = request.getFileInput();
|
||||
boolean useFirstTextAsFallback = Boolean.TRUE.equals(request.getUseFirstTextAsFallback());
|
||||
|
||||
PDDocument document = pdfDocumentFactory.load(file);
|
||||
PDFTextStripper reader =
|
||||
new PDFTextStripper() {
|
||||
List<LineInfo> lineInfos = new ArrayList<>();
|
||||
StringBuilder lineBuilder = new StringBuilder();
|
||||
float lastY = -1;
|
||||
float maxFontSizeInLine = 0.0f;
|
||||
int lineCount = 0;
|
||||
try (PDDocument document = pdfDocumentFactory.load(file)) {
|
||||
PDFTextStripper reader =
|
||||
new PDFTextStripper() {
|
||||
List<LineInfo> lineInfos = new ArrayList<>();
|
||||
StringBuilder lineBuilder = new StringBuilder();
|
||||
float lastY = -1;
|
||||
float maxFontSizeInLine = 0.0f;
|
||||
int lineCount = 0;
|
||||
|
||||
@Override
|
||||
protected void processTextPosition(TextPosition text) {
|
||||
if (lastY != text.getY() && lineCount < LINE_LIMIT) {
|
||||
processLine();
|
||||
lineBuilder = new StringBuilder(text.getUnicode());
|
||||
maxFontSizeInLine = text.getFontSizeInPt();
|
||||
lastY = text.getY();
|
||||
lineCount++;
|
||||
} else if (lineCount < LINE_LIMIT) {
|
||||
lineBuilder.append(text.getUnicode());
|
||||
if (text.getFontSizeInPt() > maxFontSizeInLine) {
|
||||
@Override
|
||||
protected void processTextPosition(TextPosition text) {
|
||||
if (lastY != text.getY() && lineCount < LINE_LIMIT) {
|
||||
processLine();
|
||||
lineBuilder = new StringBuilder(text.getUnicode());
|
||||
maxFontSizeInLine = text.getFontSizeInPt();
|
||||
lastY = text.getY();
|
||||
lineCount++;
|
||||
} else if (lineCount < LINE_LIMIT) {
|
||||
lineBuilder.append(text.getUnicode());
|
||||
if (text.getFontSizeInPt() > maxFontSizeInLine) {
|
||||
maxFontSizeInLine = text.getFontSizeInPt();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void processLine() {
|
||||
if (!lineBuilder.isEmpty() && lineCount < LINE_LIMIT) {
|
||||
lineInfos.add(new LineInfo(lineBuilder.toString(), maxFontSizeInLine));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getText(PDDocument doc) throws IOException {
|
||||
this.lineInfos.clear();
|
||||
this.lineBuilder = new StringBuilder();
|
||||
this.lastY = -1;
|
||||
this.maxFontSizeInLine = 0.0f;
|
||||
this.lineCount = 0;
|
||||
super.getText(doc);
|
||||
processLine(); // Process the last line
|
||||
|
||||
// Merge lines with same font size
|
||||
List<LineInfo> mergedLineInfos = new ArrayList<>();
|
||||
for (int i = 0; i < lineInfos.size(); i++) {
|
||||
StringBuilder mergedText = new StringBuilder(lineInfos.get(i).text);
|
||||
float fontSize = lineInfos.get(i).fontSize;
|
||||
while (i + 1 < lineInfos.size()
|
||||
&& lineInfos.get(i + 1).fontSize == fontSize) {
|
||||
mergedText.append(" ").append(lineInfos.get(i + 1).text);
|
||||
i++;
|
||||
private void processLine() {
|
||||
if (!lineBuilder.isEmpty() && lineCount < LINE_LIMIT) {
|
||||
lineInfos.add(
|
||||
new LineInfo(lineBuilder.toString(), maxFontSizeInLine));
|
||||
}
|
||||
mergedLineInfos.add(new LineInfo(mergedText.toString(), fontSize));
|
||||
}
|
||||
|
||||
// Sort lines by font size in descending order and get the first one
|
||||
mergedLineInfos.sort(
|
||||
Comparator.comparing((LineInfo li) -> li.fontSize).reversed());
|
||||
String title =
|
||||
mergedLineInfos.isEmpty() ? null : mergedLineInfos.get(0).text;
|
||||
@Override
|
||||
public String getText(PDDocument doc) throws IOException {
|
||||
this.lineInfos.clear();
|
||||
this.lineBuilder = new StringBuilder();
|
||||
this.lastY = -1;
|
||||
this.maxFontSizeInLine = 0.0f;
|
||||
this.lineCount = 0;
|
||||
super.getText(doc);
|
||||
processLine(); // Process the last line
|
||||
|
||||
return title != null
|
||||
? title
|
||||
: (useFirstTextAsFallback
|
||||
? (mergedLineInfos.isEmpty()
|
||||
? null
|
||||
: mergedLineInfos.get(mergedLineInfos.size() - 1)
|
||||
.text)
|
||||
: null);
|
||||
}
|
||||
// Merge lines with same font size
|
||||
List<LineInfo> mergedLineInfos = new ArrayList<>();
|
||||
for (int i = 0; i < lineInfos.size(); i++) {
|
||||
StringBuilder mergedText = new StringBuilder(lineInfos.get(i).text);
|
||||
float fontSize = lineInfos.get(i).fontSize;
|
||||
while (i + 1 < lineInfos.size()
|
||||
&& lineInfos.get(i + 1).fontSize == fontSize) {
|
||||
mergedText.append(" ").append(lineInfos.get(i + 1).text);
|
||||
i++;
|
||||
}
|
||||
mergedLineInfos.add(new LineInfo(mergedText.toString(), fontSize));
|
||||
}
|
||||
|
||||
class LineInfo {
|
||||
String text;
|
||||
float fontSize;
|
||||
// Sort lines by font size in descending order and get the first one
|
||||
mergedLineInfos.sort(
|
||||
Comparator.comparing((LineInfo li) -> li.fontSize).reversed());
|
||||
String title =
|
||||
mergedLineInfos.isEmpty() ? null : mergedLineInfos.get(0).text;
|
||||
|
||||
LineInfo(String text, float fontSize) {
|
||||
this.text = text;
|
||||
this.fontSize = fontSize;
|
||||
return title != null
|
||||
? title
|
||||
: (useFirstTextAsFallback
|
||||
? (mergedLineInfos.isEmpty()
|
||||
? null
|
||||
: mergedLineInfos.get(
|
||||
mergedLineInfos.size() - 1)
|
||||
.text)
|
||||
: null);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
String header = reader.getText(document);
|
||||
class LineInfo {
|
||||
String text;
|
||||
float fontSize;
|
||||
|
||||
// Sanitize the header string by removing characters not allowed in a filename.
|
||||
if (header != null && header.length() < 255) {
|
||||
header =
|
||||
RegexPatternUtils.getInstance()
|
||||
.getSafeFilenamePattern()
|
||||
.matcher(header)
|
||||
.replaceAll("")
|
||||
.trim();
|
||||
return WebResponseUtils.pdfDocToWebResponse(document, header + ".pdf");
|
||||
} else {
|
||||
log.info("File has no good title to be found");
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document, Filenames.toSimpleFileName(file.getOriginalFilename()));
|
||||
LineInfo(String text, float fontSize) {
|
||||
this.text = text;
|
||||
this.fontSize = fontSize;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
String header = reader.getText(document);
|
||||
|
||||
// Sanitize the header string by removing characters not allowed in a filename.
|
||||
if (header != null && header.length() < 255) {
|
||||
header =
|
||||
RegexPatternUtils.getInstance()
|
||||
.getSafeFilenamePattern()
|
||||
.matcher(header)
|
||||
.replaceAll("")
|
||||
.trim();
|
||||
return WebResponseUtils.pdfDocToWebResponse(document, header + ".pdf");
|
||||
} else {
|
||||
log.info("File has no good title to be found");
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document, Filenames.toSimpleFileName(file.getOriginalFilename()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+3
-2
@@ -1100,8 +1100,9 @@ public class CompressController {
|
||||
inputFile.getOriginalFilename(), "_Optimized.pdf");
|
||||
|
||||
try {
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
pdfDocumentFactory.load(currentFile.toFile()), outputFilename);
|
||||
try (PDDocument document = pdfDocumentFactory.load(currentFile.toFile())) {
|
||||
return WebResponseUtils.pdfDocToWebResponse(document, outputFilename);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw ExceptionUtils.handlePdfException(e, "PDF optimization");
|
||||
}
|
||||
|
||||
+16
-1
@@ -75,10 +75,25 @@ public class ConfigController {
|
||||
String frontendUrl = applicationProperties.getSystem().getFrontendUrl();
|
||||
configData.put("frontendUrl", frontendUrl != null ? frontendUrl : "");
|
||||
|
||||
// Add mobile scanner setting
|
||||
// Add mobile scanner settings
|
||||
configData.put(
|
||||
"enableMobileScanner",
|
||||
applicationProperties.getSystem().isEnableMobileScanner());
|
||||
configData.put(
|
||||
"mobileScannerConvertToPdf",
|
||||
applicationProperties.getSystem().getMobileScannerSettings().isConvertToPdf());
|
||||
configData.put(
|
||||
"mobileScannerImageResolution",
|
||||
applicationProperties
|
||||
.getSystem()
|
||||
.getMobileScannerSettings()
|
||||
.getImageResolution());
|
||||
configData.put(
|
||||
"mobileScannerPageFormat",
|
||||
applicationProperties.getSystem().getMobileScannerSettings().getPageFormat());
|
||||
configData.put(
|
||||
"mobileScannerStretchToFit",
|
||||
applicationProperties.getSystem().getMobileScannerSettings().isStretchToFit());
|
||||
|
||||
// Extract values from ApplicationProperties
|
||||
configData.put("appNameNavbar", applicationProperties.getUi().getAppNameNavbar());
|
||||
|
||||
+91
-81
@@ -49,93 +49,103 @@ public class FlattenController {
|
||||
public ResponseEntity<byte[]> flatten(@ModelAttribute FlattenRequest request) throws Exception {
|
||||
MultipartFile file = request.getFileInput();
|
||||
|
||||
PDDocument document = pdfDocumentFactory.load(file);
|
||||
Boolean flattenOnlyForms = request.getFlattenOnlyForms();
|
||||
try (PDDocument document = pdfDocumentFactory.load(file)) {
|
||||
Boolean flattenOnlyForms = request.getFlattenOnlyForms();
|
||||
|
||||
if (Boolean.TRUE.equals(flattenOnlyForms)) {
|
||||
PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();
|
||||
if (acroForm != null) {
|
||||
acroForm.flatten();
|
||||
}
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document, Filenames.toSimpleFileName(file.getOriginalFilename()));
|
||||
} else {
|
||||
// flatten whole page aka convert each page to image and re-add it (making text
|
||||
// unselectable)
|
||||
PDFRenderer pdfRenderer = new PDFRenderer(document);
|
||||
PDDocument newDocument =
|
||||
pdfDocumentFactory.createNewDocumentBasedOnOldDocument(document);
|
||||
if (Boolean.TRUE.equals(flattenOnlyForms)) {
|
||||
PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();
|
||||
if (acroForm != null) {
|
||||
acroForm.flatten();
|
||||
}
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document, Filenames.toSimpleFileName(file.getOriginalFilename()));
|
||||
} else {
|
||||
// flatten whole page aka convert each page to image and re-add it (making text
|
||||
// unselectable)
|
||||
PDFRenderer pdfRenderer = new PDFRenderer(document);
|
||||
pdfRenderer.setSubsamplingAllowed(
|
||||
true); // Enable subsampling to reduce memory usage
|
||||
|
||||
int defaultRenderDpi = 100; // Default fallback
|
||||
ApplicationProperties properties =
|
||||
ApplicationContextProvider.getBean(ApplicationProperties.class);
|
||||
Integer configuredMaxDpi = null;
|
||||
if (properties != null && properties.getSystem() != null) {
|
||||
configuredMaxDpi = properties.getSystem().getMaxDPI();
|
||||
}
|
||||
try (PDDocument newDocument =
|
||||
pdfDocumentFactory.createNewDocumentBasedOnOldDocument(document)) {
|
||||
|
||||
int maxDpi =
|
||||
(configuredMaxDpi != null && configuredMaxDpi > 0)
|
||||
? configuredMaxDpi
|
||||
: defaultRenderDpi;
|
||||
|
||||
Integer requestedDpi = request.getRenderDpi();
|
||||
int renderDpiTemp = maxDpi;
|
||||
if (requestedDpi != null) {
|
||||
renderDpiTemp = Math.min(requestedDpi, maxDpi);
|
||||
renderDpiTemp = Math.max(renderDpiTemp, 72);
|
||||
}
|
||||
final int renderDpi = renderDpiTemp;
|
||||
|
||||
int numPages = document.getNumberOfPages();
|
||||
for (int i = 0; i < numPages; i++) {
|
||||
final int pageIndex = i;
|
||||
BufferedImage image = null;
|
||||
try {
|
||||
// Validate dimensions BEFORE rendering to prevent OOM
|
||||
ExceptionUtils.validateRenderingDimensions(
|
||||
document.getPage(pageIndex), pageIndex + 1, renderDpi);
|
||||
|
||||
// Wrap entire rendering operation to catch OutOfMemoryError from any depth
|
||||
image =
|
||||
ExceptionUtils.handleOomRendering(
|
||||
pageIndex + 1,
|
||||
renderDpi,
|
||||
() ->
|
||||
pdfRenderer.renderImageWithDPI(
|
||||
pageIndex, renderDpi, ImageType.RGB));
|
||||
|
||||
PDPage page = new PDPage();
|
||||
page.setMediaBox(document.getPage(i).getMediaBox());
|
||||
newDocument.addPage(page);
|
||||
try (PDPageContentStream contentStream =
|
||||
new PDPageContentStream(newDocument, page)) {
|
||||
PDImageXObject pdImage = JPEGFactory.createFromImage(newDocument, image);
|
||||
float pageWidth = page.getMediaBox().getWidth();
|
||||
float pageHeight = page.getMediaBox().getHeight();
|
||||
|
||||
contentStream.drawImage(pdImage, 0, 0, pageWidth, pageHeight);
|
||||
int defaultRenderDpi = 100; // Default fallback
|
||||
ApplicationProperties properties =
|
||||
ApplicationContextProvider.getBean(ApplicationProperties.class);
|
||||
Integer configuredMaxDpi = null;
|
||||
if (properties != null && properties.getSystem() != null) {
|
||||
configuredMaxDpi = properties.getSystem().getMaxDPI();
|
||||
}
|
||||
} catch (ExceptionUtils.OutOfMemoryDpiException e) {
|
||||
// Re-throw OutOfMemoryDpiException to be handled by GlobalExceptionHandler
|
||||
newDocument.close();
|
||||
document.close();
|
||||
throw e;
|
||||
} catch (IOException e) {
|
||||
log.error("IOException during page processing: ", e);
|
||||
// Continue processing other pages
|
||||
} catch (OutOfMemoryError e) {
|
||||
// Catch any OutOfMemoryError that escaped the inner try block
|
||||
newDocument.close();
|
||||
document.close();
|
||||
throw ExceptionUtils.createOutOfMemoryDpiException(i + 1, renderDpi, e);
|
||||
} finally {
|
||||
// Help GC by clearing the image reference
|
||||
image = null;
|
||||
|
||||
int maxDpi =
|
||||
(configuredMaxDpi != null && configuredMaxDpi > 0)
|
||||
? configuredMaxDpi
|
||||
: defaultRenderDpi;
|
||||
|
||||
Integer requestedDpi = request.getRenderDpi();
|
||||
int renderDpiTemp = maxDpi;
|
||||
if (requestedDpi != null) {
|
||||
renderDpiTemp = Math.min(requestedDpi, maxDpi);
|
||||
renderDpiTemp = Math.max(renderDpiTemp, 72);
|
||||
}
|
||||
final int renderDpi = renderDpiTemp;
|
||||
|
||||
int numPages = document.getNumberOfPages();
|
||||
for (int i = 0; i < numPages; i++) {
|
||||
final int pageIndex = i;
|
||||
BufferedImage image = null;
|
||||
try {
|
||||
// Validate dimensions BEFORE rendering to prevent OOM
|
||||
ExceptionUtils.validateRenderingDimensions(
|
||||
document.getPage(pageIndex), pageIndex + 1, renderDpi);
|
||||
|
||||
// Wrap entire rendering operation to catch OutOfMemoryError from any
|
||||
// depth
|
||||
image =
|
||||
ExceptionUtils.handleOomRendering(
|
||||
pageIndex + 1,
|
||||
renderDpi,
|
||||
() ->
|
||||
pdfRenderer.renderImageWithDPI(
|
||||
pageIndex, renderDpi, ImageType.RGB));
|
||||
|
||||
PDPage page = new PDPage();
|
||||
page.setMediaBox(document.getPage(i).getMediaBox());
|
||||
newDocument.addPage(page);
|
||||
// resetContext=true: Ensure clean graphics state when overwriting.
|
||||
try (PDPageContentStream contentStream =
|
||||
new PDPageContentStream(
|
||||
newDocument,
|
||||
page,
|
||||
PDPageContentStream.AppendMode.OVERWRITE,
|
||||
true,
|
||||
true)) {
|
||||
PDImageXObject pdImage =
|
||||
JPEGFactory.createFromImage(newDocument, image);
|
||||
float pageWidth = page.getMediaBox().getWidth();
|
||||
float pageHeight = page.getMediaBox().getHeight();
|
||||
|
||||
contentStream.drawImage(pdImage, 0, 0, pageWidth, pageHeight);
|
||||
}
|
||||
} catch (ExceptionUtils.OutOfMemoryDpiException e) {
|
||||
// Re-throw OutOfMemoryDpiException to be handled by
|
||||
// GlobalExceptionHandler
|
||||
throw e;
|
||||
} catch (IOException e) {
|
||||
log.error("IOException during page processing: ", e);
|
||||
// Continue processing other pages
|
||||
} catch (OutOfMemoryError e) {
|
||||
// Catch any OutOfMemoryError that escaped the inner try block
|
||||
throw ExceptionUtils.createOutOfMemoryDpiException(i + 1, renderDpi, e);
|
||||
} finally {
|
||||
// Help GC by clearing the image reference
|
||||
image = null;
|
||||
}
|
||||
}
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
newDocument, Filenames.toSimpleFileName(file.getOriginalFilename()));
|
||||
}
|
||||
}
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
newDocument, Filenames.toSimpleFileName(file.getOriginalFilename()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+91
-82
@@ -84,93 +84,102 @@ public class MetadataController {
|
||||
if (allRequestParams == null) {
|
||||
allRequestParams = new java.util.HashMap<String, String>();
|
||||
}
|
||||
// Load the PDF file into a PDDocument
|
||||
PDDocument document = pdfDocumentFactory.load(pdfFile, true);
|
||||
// Load the PDF file into a PDDocument with proper resource management
|
||||
try (PDDocument document = pdfDocumentFactory.load(pdfFile, true)) {
|
||||
|
||||
// Get the document information from the PDF
|
||||
PDDocumentInformation info = document.getDocumentInformation();
|
||||
// Get the document information from the PDF
|
||||
PDDocumentInformation info = document.getDocumentInformation();
|
||||
|
||||
// Check if each metadata value is "undefined" and set it to null if it is
|
||||
author = checkUndefined(author);
|
||||
creationDate = checkUndefined(creationDate);
|
||||
creator = checkUndefined(creator);
|
||||
keywords = checkUndefined(keywords);
|
||||
modificationDate = checkUndefined(modificationDate);
|
||||
producer = checkUndefined(producer);
|
||||
subject = checkUndefined(subject);
|
||||
title = checkUndefined(title);
|
||||
trapped = checkUndefined(trapped);
|
||||
// Check if each metadata value is "undefined" and set it to null if it is
|
||||
author = checkUndefined(author);
|
||||
creationDate = checkUndefined(creationDate);
|
||||
creator = checkUndefined(creator);
|
||||
keywords = checkUndefined(keywords);
|
||||
modificationDate = checkUndefined(modificationDate);
|
||||
producer = checkUndefined(producer);
|
||||
subject = checkUndefined(subject);
|
||||
title = checkUndefined(title);
|
||||
trapped = checkUndefined(trapped);
|
||||
|
||||
// If the "deleteAll" flag is set, remove all metadata from the document
|
||||
// information
|
||||
if (deleteAll) {
|
||||
for (String key : info.getMetadataKeys()) {
|
||||
info.setCustomMetadataValue(key, null);
|
||||
}
|
||||
// Remove metadata from the PDF history
|
||||
document.getDocumentCatalog().getCOSObject().removeItem(COSName.getPDFName("Metadata"));
|
||||
document.getDocumentCatalog()
|
||||
.getCOSObject()
|
||||
.removeItem(COSName.getPDFName("PieceInfo"));
|
||||
author = null;
|
||||
creationDate = null;
|
||||
creator = null;
|
||||
keywords = null;
|
||||
modificationDate = null;
|
||||
producer = null;
|
||||
subject = null;
|
||||
title = null;
|
||||
trapped = null;
|
||||
} else {
|
||||
// Iterate through the request parameters and set the metadata values
|
||||
for (Entry<String, String> entry : allRequestParams.entrySet()) {
|
||||
String key = entry.getKey();
|
||||
// Check if the key is a standard metadata key
|
||||
if (!"Author".equalsIgnoreCase(key)
|
||||
&& !"CreationDate".equalsIgnoreCase(key)
|
||||
&& !"Creator".equalsIgnoreCase(key)
|
||||
&& !"Keywords".equalsIgnoreCase(key)
|
||||
&& !"modificationDate".equalsIgnoreCase(key)
|
||||
&& !"Producer".equalsIgnoreCase(key)
|
||||
&& !"Subject".equalsIgnoreCase(key)
|
||||
&& !"Title".equalsIgnoreCase(key)
|
||||
&& !"Trapped".equalsIgnoreCase(key)
|
||||
&& !key.contains("customKey")
|
||||
&& !key.contains("customValue")) {
|
||||
info.setCustomMetadataValue(key, entry.getValue());
|
||||
} else if (key.contains("customKey")) {
|
||||
int number =
|
||||
Integer.parseInt(
|
||||
RegexPatternUtils.getInstance()
|
||||
.getNumericExtractionPattern()
|
||||
.matcher(key)
|
||||
.replaceAll(""));
|
||||
String customKey = entry.getValue();
|
||||
String customValue = allRequestParams.get("customValue" + number);
|
||||
info.setCustomMetadataValue(customKey, customValue);
|
||||
// If the "deleteAll" flag is set, remove all metadata from the document
|
||||
// information
|
||||
if (deleteAll) {
|
||||
for (String key : info.getMetadataKeys()) {
|
||||
info.setCustomMetadataValue(key, null);
|
||||
}
|
||||
// Remove metadata from the PDF history
|
||||
document.getDocumentCatalog()
|
||||
.getCOSObject()
|
||||
.removeItem(COSName.getPDFName("Metadata"));
|
||||
document.getDocumentCatalog()
|
||||
.getCOSObject()
|
||||
.removeItem(COSName.getPDFName("PieceInfo"));
|
||||
author = null;
|
||||
creationDate = null;
|
||||
creator = null;
|
||||
keywords = null;
|
||||
modificationDate = null;
|
||||
producer = null;
|
||||
subject = null;
|
||||
title = null;
|
||||
trapped = null;
|
||||
} else {
|
||||
// Iterate through the request parameters and set the metadata values
|
||||
for (Entry<String, String> entry : allRequestParams.entrySet()) {
|
||||
String key = entry.getKey();
|
||||
// Check if the key is a standard metadata key
|
||||
if (!"Author".equalsIgnoreCase(key)
|
||||
&& !"CreationDate".equalsIgnoreCase(key)
|
||||
&& !"Creator".equalsIgnoreCase(key)
|
||||
&& !"Keywords".equalsIgnoreCase(key)
|
||||
&& !"modificationDate".equalsIgnoreCase(key)
|
||||
&& !"Producer".equalsIgnoreCase(key)
|
||||
&& !"Subject".equalsIgnoreCase(key)
|
||||
&& !"Title".equalsIgnoreCase(key)
|
||||
&& !"Trapped".equalsIgnoreCase(key)
|
||||
&& !key.contains("customKey")
|
||||
&& !key.contains("customValue")) {
|
||||
info.setCustomMetadataValue(key, entry.getValue());
|
||||
} else if (key.contains("customKey")) {
|
||||
try {
|
||||
int number =
|
||||
Integer.parseInt(
|
||||
RegexPatternUtils.getInstance()
|
||||
.getNumericExtractionPattern()
|
||||
.matcher(key)
|
||||
.replaceAll(""));
|
||||
String customKey = entry.getValue();
|
||||
String customValue = allRequestParams.get("customValue" + number);
|
||||
info.setCustomMetadataValue(customKey, customValue);
|
||||
} catch (NumberFormatException e) {
|
||||
// Skip invalid custom key entries that don't have valid numeric
|
||||
// suffixes
|
||||
log.warn("Skipping invalid custom key '{}': {}", key, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Set creation date using utility method
|
||||
Calendar creationDateCal = PdfMetadataService.parseToCalendar(creationDate);
|
||||
info.setCreationDate(creationDateCal);
|
||||
|
||||
// Set modification date using utility method
|
||||
Calendar modificationDateCal = PdfMetadataService.parseToCalendar(modificationDate);
|
||||
info.setModificationDate(modificationDateCal);
|
||||
info.setCreator(creator);
|
||||
info.setKeywords(keywords);
|
||||
info.setAuthor(author);
|
||||
info.setProducer(producer);
|
||||
info.setSubject(subject);
|
||||
info.setTitle(title);
|
||||
info.setTrapped(trapped);
|
||||
|
||||
document.setDocumentInformation(info);
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document,
|
||||
GeneralUtils.removeExtension(
|
||||
Filenames.toSimpleFileName(pdfFile.getOriginalFilename()))
|
||||
+ "_metadata.pdf");
|
||||
}
|
||||
// Set creation date using utility method
|
||||
Calendar creationDateCal = PdfMetadataService.parseToCalendar(creationDate);
|
||||
info.setCreationDate(creationDateCal);
|
||||
|
||||
// Set modification date using utility method
|
||||
Calendar modificationDateCal = PdfMetadataService.parseToCalendar(modificationDate);
|
||||
info.setModificationDate(modificationDateCal);
|
||||
info.setCreator(creator);
|
||||
info.setKeywords(keywords);
|
||||
info.setAuthor(author);
|
||||
info.setProducer(producer);
|
||||
info.setSubject(subject);
|
||||
info.setTitle(title);
|
||||
info.setTrapped(trapped);
|
||||
|
||||
document.setDocumentInformation(info);
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document,
|
||||
GeneralUtils.removeExtension(
|
||||
Filenames.toSimpleFileName(pdfFile.getOriginalFilename()))
|
||||
+ "_metadata.pdf");
|
||||
}
|
||||
}
|
||||
|
||||
+59
-1
@@ -31,6 +31,7 @@ import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.common.service.MobileScannerService;
|
||||
import stirling.software.common.service.MobileScannerService.FileMetadata;
|
||||
|
||||
@@ -51,9 +52,31 @@ import stirling.software.common.service.MobileScannerService.FileMetadata;
|
||||
public class MobileScannerController {
|
||||
|
||||
private final MobileScannerService mobileScannerService;
|
||||
private final ApplicationProperties applicationProperties;
|
||||
|
||||
public MobileScannerController(MobileScannerService mobileScannerService) {
|
||||
public MobileScannerController(
|
||||
MobileScannerService mobileScannerService,
|
||||
ApplicationProperties applicationProperties) {
|
||||
this.mobileScannerService = mobileScannerService;
|
||||
this.applicationProperties = applicationProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if mobile scanner feature is enabled
|
||||
*
|
||||
* @return Error response if disabled, null if enabled
|
||||
*/
|
||||
private ResponseEntity<Map<String, Object>> checkFeatureEnabled() {
|
||||
if (!applicationProperties.getSystem().isEnableMobileScanner()) {
|
||||
return ResponseEntity.status(HttpStatus.FORBIDDEN)
|
||||
.body(
|
||||
Map.of(
|
||||
"error",
|
||||
"Mobile scanner feature is not enabled",
|
||||
"enabled",
|
||||
false));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -71,10 +94,16 @@ public class MobileScannerController {
|
||||
description = "Session created successfully",
|
||||
content = @Content(schema = @Schema(implementation = SessionInfoResponse.class)))
|
||||
@ApiResponse(responseCode = "400", description = "Invalid session ID")
|
||||
@ApiResponse(responseCode = "403", description = "Mobile scanner feature not enabled")
|
||||
public ResponseEntity<Map<String, Object>> createSession(
|
||||
@Parameter(description = "Session ID for QR code", required = true) @PathVariable
|
||||
String sessionId) {
|
||||
|
||||
ResponseEntity<Map<String, Object>> featureCheck = checkFeatureEnabled();
|
||||
if (featureCheck != null) {
|
||||
return featureCheck;
|
||||
}
|
||||
|
||||
try {
|
||||
MobileScannerService.SessionInfo sessionInfo =
|
||||
mobileScannerService.createSession(sessionId);
|
||||
@@ -109,10 +138,16 @@ public class MobileScannerController {
|
||||
description = "Session is valid",
|
||||
content = @Content(schema = @Schema(implementation = SessionInfoResponse.class)))
|
||||
@ApiResponse(responseCode = "404", description = "Session not found or expired")
|
||||
@ApiResponse(responseCode = "403", description = "Mobile scanner feature not enabled")
|
||||
public ResponseEntity<Map<String, Object>> validateSession(
|
||||
@Parameter(description = "Session ID to validate", required = true) @PathVariable
|
||||
String sessionId) {
|
||||
|
||||
ResponseEntity<Map<String, Object>> featureCheck = checkFeatureEnabled();
|
||||
if (featureCheck != null) {
|
||||
return featureCheck;
|
||||
}
|
||||
|
||||
MobileScannerService.SessionInfo sessionInfo =
|
||||
mobileScannerService.validateSession(sessionId);
|
||||
|
||||
@@ -147,6 +182,7 @@ public class MobileScannerController {
|
||||
description = "Files uploaded successfully",
|
||||
content = @Content(schema = @Schema(implementation = UploadResponse.class)))
|
||||
@ApiResponse(responseCode = "400", description = "Invalid session ID or files")
|
||||
@ApiResponse(responseCode = "403", description = "Mobile scanner feature not enabled")
|
||||
@ApiResponse(responseCode = "500", description = "Upload failed")
|
||||
public ResponseEntity<Map<String, Object>> uploadFiles(
|
||||
@Parameter(description = "Session ID from QR code", required = true) @PathVariable
|
||||
@@ -154,6 +190,11 @@ public class MobileScannerController {
|
||||
@Parameter(description = "Files to upload", required = true) @RequestParam("files")
|
||||
List<MultipartFile> files) {
|
||||
|
||||
ResponseEntity<Map<String, Object>> featureCheck = checkFeatureEnabled();
|
||||
if (featureCheck != null) {
|
||||
return featureCheck;
|
||||
}
|
||||
|
||||
try {
|
||||
if (files == null || files.isEmpty()) {
|
||||
return ResponseEntity.badRequest().body(Map.of("error", "No files provided"));
|
||||
@@ -194,10 +235,16 @@ public class MobileScannerController {
|
||||
responseCode = "200",
|
||||
description = "File list retrieved",
|
||||
content = @Content(schema = @Schema(implementation = FileListResponse.class)))
|
||||
@ApiResponse(responseCode = "403", description = "Mobile scanner feature not enabled")
|
||||
public ResponseEntity<Map<String, Object>> getSessionFiles(
|
||||
@Parameter(description = "Session ID", required = true) @PathVariable
|
||||
String sessionId) {
|
||||
|
||||
ResponseEntity<Map<String, Object>> featureCheck = checkFeatureEnabled();
|
||||
if (featureCheck != null) {
|
||||
return featureCheck;
|
||||
}
|
||||
|
||||
List<FileMetadata> files = mobileScannerService.getSessionFiles(sessionId);
|
||||
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
@@ -221,12 +268,17 @@ public class MobileScannerController {
|
||||
description =
|
||||
"Download a file that was uploaded to a session. File is automatically deleted after download.")
|
||||
@ApiResponse(responseCode = "200", description = "File downloaded successfully")
|
||||
@ApiResponse(responseCode = "403", description = "Mobile scanner feature not enabled")
|
||||
@ApiResponse(responseCode = "404", description = "File or session not found")
|
||||
public ResponseEntity<Resource> downloadFile(
|
||||
@Parameter(description = "Session ID", required = true) @PathVariable String sessionId,
|
||||
@Parameter(description = "Filename to download", required = true) @PathVariable
|
||||
String filename) {
|
||||
|
||||
if (!applicationProperties.getSystem().isEnableMobileScanner()) {
|
||||
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
|
||||
}
|
||||
|
||||
try {
|
||||
Path filePath = mobileScannerService.getFile(sessionId, filename);
|
||||
|
||||
@@ -268,10 +320,16 @@ public class MobileScannerController {
|
||||
summary = "Delete a session",
|
||||
description = "Manually delete a session and all its uploaded files")
|
||||
@ApiResponse(responseCode = "200", description = "Session deleted successfully")
|
||||
@ApiResponse(responseCode = "403", description = "Mobile scanner feature not enabled")
|
||||
public ResponseEntity<Map<String, Object>> deleteSession(
|
||||
@Parameter(description = "Session ID to delete", required = true) @PathVariable
|
||||
String sessionId) {
|
||||
|
||||
ResponseEntity<Map<String, Object>> featureCheck = checkFeatureEnabled();
|
||||
if (featureCheck != null) {
|
||||
return featureCheck;
|
||||
}
|
||||
|
||||
mobileScannerService.deleteSession(sessionId);
|
||||
|
||||
return ResponseEntity.ok(
|
||||
|
||||
+4
-1
@@ -15,6 +15,7 @@ import java.util.zip.ZipOutputStream;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
import org.apache.pdfbox.io.IOUtils;
|
||||
import org.apache.pdfbox.multipdf.PDFMergerUtility;
|
||||
import org.apache.pdfbox.pdmodel.PDDocument;
|
||||
import org.apache.pdfbox.pdmodel.PDPage;
|
||||
@@ -326,6 +327,8 @@ public class OCRController {
|
||||
|
||||
try (PDDocument document = pdfDocumentFactory.load(tempInputFile.toFile())) {
|
||||
PDFRenderer pdfRenderer = new PDFRenderer(document);
|
||||
pdfRenderer.setSubsamplingAllowed(
|
||||
true); // Enable subsampling to reduce memory usage
|
||||
int pageCount = document.getNumberOfPages();
|
||||
|
||||
for (int pageNum = 0; pageNum < pageCount; pageNum++) {
|
||||
@@ -415,7 +418,7 @@ public class OCRController {
|
||||
}
|
||||
|
||||
// Merge all pages into final PDF
|
||||
merger.mergeDocuments(null);
|
||||
merger.mergeDocuments(IOUtils.createTempFileOnlyStreamCache());
|
||||
|
||||
// Copy final output to the expected location
|
||||
Files.copy(
|
||||
|
||||
+104
-103
@@ -65,113 +65,114 @@ public class PageNumbersController {
|
||||
}
|
||||
}
|
||||
|
||||
PDDocument document = pdfDocumentFactory.load(file);
|
||||
|
||||
float marginFactor =
|
||||
switch (customMargin == null ? "" : customMargin.toLowerCase(Locale.ROOT)) {
|
||||
case "small" -> 0.02f;
|
||||
case "large" -> 0.05f;
|
||||
case "x-large" -> 0.075f;
|
||||
case "medium" -> 0.035f;
|
||||
default -> 0.035f;
|
||||
};
|
||||
|
||||
if (pagesToNumber == null || pagesToNumber.isEmpty()) {
|
||||
pagesToNumber = "all";
|
||||
}
|
||||
if (customText == null || customText.isEmpty()) {
|
||||
customText = "{n}";
|
||||
}
|
||||
|
||||
final String baseFilename =
|
||||
Filenames.toSimpleFileName(file.getOriginalFilename())
|
||||
.replaceFirst("[.][^.]+$", "");
|
||||
|
||||
List<Integer> pagesToNumberList =
|
||||
GeneralUtils.parsePageList(pagesToNumber.split(","), document.getNumberOfPages());
|
||||
|
||||
// Clamp position to 1..9 (1 = top-left, 9 = bottom-right)
|
||||
int pos = Math.max(1, Math.min(9, position));
|
||||
|
||||
for (int i : pagesToNumberList) {
|
||||
PDPage page = document.getPage(i);
|
||||
PDRectangle pageSize = page.getMediaBox();
|
||||
|
||||
String text =
|
||||
customText
|
||||
.replace("{n}", String.valueOf(pageNumber))
|
||||
.replace("{total}", String.valueOf(document.getNumberOfPages()))
|
||||
.replace(
|
||||
"{filename}",
|
||||
GeneralUtils.removeExtension(
|
||||
Filenames.toSimpleFileName(
|
||||
file.getOriginalFilename())));
|
||||
|
||||
PDType1Font currentFont =
|
||||
switch (fontType == null ? "" : fontType.toLowerCase(Locale.ROOT)) {
|
||||
case "courier" -> new PDType1Font(Standard14Fonts.FontName.COURIER);
|
||||
case "times" -> new PDType1Font(Standard14Fonts.FontName.TIMES_ROMAN);
|
||||
default -> new PDType1Font(Standard14Fonts.FontName.HELVETICA);
|
||||
try (PDDocument document = pdfDocumentFactory.load(file)) {
|
||||
float marginFactor =
|
||||
switch (customMargin == null ? "" : customMargin.toLowerCase(Locale.ROOT)) {
|
||||
case "small" -> 0.02f;
|
||||
case "large" -> 0.05f;
|
||||
case "x-large" -> 0.075f;
|
||||
case "medium" -> 0.035f;
|
||||
default -> 0.035f;
|
||||
};
|
||||
|
||||
// Text dimensions and font metrics
|
||||
float textWidth = currentFont.getStringWidth(text) / 1000f * fontSize;
|
||||
float ascent = currentFont.getFontDescriptor().getAscent() / 1000f * fontSize;
|
||||
float descent = currentFont.getFontDescriptor().getDescent() / 1000f * fontSize;
|
||||
|
||||
// Derive column/row in range 1..3 (1 = left/top, 2 = center/middle, 3 = right/bottom)
|
||||
int col = ((pos - 1) % 3) + 1; // 1 = left, 2 = center, 3 = right
|
||||
int row = ((pos - 1) / 3) + 1; // 1 = top, 2 = middle, 3 = bottom
|
||||
|
||||
// Anchor coordinates with margin
|
||||
float leftX = pageSize.getLowerLeftX() + marginFactor * pageSize.getWidth();
|
||||
float midX = pageSize.getLowerLeftX() + pageSize.getWidth() / 2f;
|
||||
float rightX = pageSize.getUpperRightX() - marginFactor * pageSize.getWidth();
|
||||
|
||||
float botY = pageSize.getLowerLeftY() + marginFactor * pageSize.getHeight();
|
||||
float midY = pageSize.getLowerLeftY() + pageSize.getHeight() / 2f;
|
||||
float topY = pageSize.getUpperRightY() - marginFactor * pageSize.getHeight();
|
||||
|
||||
// Horizontal alignment: left = anchor, center = centered, right = right-aligned
|
||||
float x =
|
||||
switch (col) {
|
||||
case 1 -> leftX;
|
||||
case 2 -> midX - textWidth / 2f;
|
||||
default -> rightX - textWidth;
|
||||
};
|
||||
|
||||
// Vertical alignment (baseline!):
|
||||
// top = align text top at topY,
|
||||
// middle = optical middle using ascent/descent,
|
||||
// bottom = baseline at botY
|
||||
float y =
|
||||
switch (row) {
|
||||
case 1 -> topY - ascent;
|
||||
case 2 -> midY - (ascent + descent) / 2f;
|
||||
default -> botY;
|
||||
};
|
||||
|
||||
try (PDPageContentStream contentStream =
|
||||
new PDPageContentStream(
|
||||
document, page, PDPageContentStream.AppendMode.APPEND, true, true)) {
|
||||
contentStream.beginText();
|
||||
contentStream.setFont(currentFont, fontSize);
|
||||
contentStream.setNonStrokingColor(color);
|
||||
contentStream.newLineAtOffset(x, y);
|
||||
contentStream.showText(text);
|
||||
contentStream.endText();
|
||||
if (pagesToNumber == null || pagesToNumber.isEmpty()) {
|
||||
pagesToNumber = "all";
|
||||
}
|
||||
if (customText == null || customText.isEmpty()) {
|
||||
customText = "{n}";
|
||||
}
|
||||
|
||||
pageNumber++;
|
||||
List<Integer> pagesToNumberList =
|
||||
GeneralUtils.parsePageList(
|
||||
pagesToNumber.split(","), document.getNumberOfPages());
|
||||
|
||||
// Clamp position to 1..9 (1 = top-left, 9 = bottom-right)
|
||||
int pos = Math.max(1, Math.min(9, position));
|
||||
|
||||
for (int i : pagesToNumberList) {
|
||||
PDPage page = document.getPage(i);
|
||||
PDRectangle pageSize = page.getMediaBox();
|
||||
|
||||
String text =
|
||||
customText
|
||||
.replace("{n}", String.valueOf(pageNumber))
|
||||
.replace("{total}", String.valueOf(document.getNumberOfPages()))
|
||||
.replace(
|
||||
"{filename}",
|
||||
GeneralUtils.removeExtension(
|
||||
Filenames.toSimpleFileName(
|
||||
file.getOriginalFilename())));
|
||||
|
||||
PDType1Font currentFont =
|
||||
switch (fontType == null ? "" : fontType.toLowerCase(Locale.ROOT)) {
|
||||
case "courier" -> new PDType1Font(Standard14Fonts.FontName.COURIER);
|
||||
case "times" -> new PDType1Font(Standard14Fonts.FontName.TIMES_ROMAN);
|
||||
default -> new PDType1Font(Standard14Fonts.FontName.HELVETICA);
|
||||
};
|
||||
|
||||
// Text dimensions and font metrics
|
||||
float textWidth = currentFont.getStringWidth(text) / 1000f * fontSize;
|
||||
float ascent = currentFont.getFontDescriptor().getAscent() / 1000f * fontSize;
|
||||
float descent = currentFont.getFontDescriptor().getDescent() / 1000f * fontSize;
|
||||
|
||||
// Derive column/row in range 1..3 (1 = left/top, 2 = center/middle, 3 =
|
||||
// right/bottom)
|
||||
int col = ((pos - 1) % 3) + 1; // 1 = left, 2 = center, 3 = right
|
||||
int row = ((pos - 1) / 3) + 1; // 1 = top, 2 = middle, 3 = bottom
|
||||
|
||||
// Anchor coordinates with margin
|
||||
float leftX = pageSize.getLowerLeftX() + marginFactor * pageSize.getWidth();
|
||||
float midX = pageSize.getLowerLeftX() + pageSize.getWidth() / 2f;
|
||||
float rightX = pageSize.getUpperRightX() - marginFactor * pageSize.getWidth();
|
||||
|
||||
float botY = pageSize.getLowerLeftY() + marginFactor * pageSize.getHeight();
|
||||
float midY = pageSize.getLowerLeftY() + pageSize.getHeight() / 2f;
|
||||
float topY = pageSize.getUpperRightY() - marginFactor * pageSize.getHeight();
|
||||
|
||||
// Horizontal alignment: left = anchor, center = centered, right = right-aligned
|
||||
float x =
|
||||
switch (col) {
|
||||
case 1 -> leftX;
|
||||
case 2 -> midX - textWidth / 2f;
|
||||
default -> rightX - textWidth;
|
||||
};
|
||||
|
||||
// Vertical alignment (baseline!):
|
||||
// top = align text top at topY,
|
||||
// middle = optical middle using ascent/descent,
|
||||
// bottom = baseline at botY
|
||||
float y =
|
||||
switch (row) {
|
||||
case 1 -> topY - ascent;
|
||||
case 2 -> midY - (ascent + descent) / 2f;
|
||||
default -> botY;
|
||||
};
|
||||
|
||||
try (PDPageContentStream contentStream =
|
||||
new PDPageContentStream(
|
||||
document,
|
||||
page,
|
||||
PDPageContentStream.AppendMode.APPEND,
|
||||
true,
|
||||
true)) {
|
||||
contentStream.beginText();
|
||||
contentStream.setFont(currentFont, fontSize);
|
||||
contentStream.setNonStrokingColor(color);
|
||||
contentStream.newLineAtOffset(x, y);
|
||||
contentStream.showText(text);
|
||||
contentStream.endText();
|
||||
}
|
||||
|
||||
pageNumber++;
|
||||
}
|
||||
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
document.save(baos);
|
||||
|
||||
return WebResponseUtils.bytesToWebResponse(
|
||||
baos.toByteArray(),
|
||||
GeneralUtils.generateFilename(
|
||||
file.getOriginalFilename(), "_page_numbers_added.pdf"));
|
||||
}
|
||||
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
document.save(baos);
|
||||
document.close();
|
||||
|
||||
return WebResponseUtils.bytesToWebResponse(
|
||||
baos.toByteArray(),
|
||||
GeneralUtils.generateFilename(
|
||||
file.getOriginalFilename(), "_page_numbers_added.pdf"));
|
||||
}
|
||||
}
|
||||
|
||||
+16
-5
@@ -7,7 +7,10 @@ import java.awt.print.Printable;
|
||||
import java.awt.print.PrinterException;
|
||||
import java.awt.print.PrinterJob;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
|
||||
@@ -77,11 +80,19 @@ public class PrintFileController {
|
||||
log.info("Selected Printer: {}", selectedService.getName());
|
||||
|
||||
if (MediaType.APPLICATION_PDF_VALUE.equals(contentType)) {
|
||||
try (PDDocument document = Loader.loadPDF(file.getBytes())) {
|
||||
PrinterJob job = PrinterJob.getPrinterJob();
|
||||
job.setPrintService(selectedService);
|
||||
job.setPageable(new PDFPageable(document));
|
||||
job.print();
|
||||
// Use Stream-to-File pattern: write to temp file first, then load from file
|
||||
Path tempFile = Files.createTempFile("print-", ".pdf");
|
||||
try {
|
||||
Files.copy(
|
||||
file.getInputStream(), tempFile, StandardCopyOption.REPLACE_EXISTING);
|
||||
try (PDDocument document = Loader.loadPDF(tempFile.toFile())) {
|
||||
PrinterJob job = PrinterJob.getPrinterJob();
|
||||
job.setPrintService(selectedService);
|
||||
job.setPageable(new PDFPageable(document));
|
||||
job.print();
|
||||
}
|
||||
} finally {
|
||||
Files.deleteIfExists(tempFile);
|
||||
}
|
||||
} else if (contentType.startsWith("image/")) {
|
||||
try (var inputStream = file.getInputStream()) {
|
||||
|
||||
+7
-1
@@ -463,7 +463,13 @@ public class ScannerEffectController {
|
||||
PDPage newPage = new PDPage(new PDRectangle(page.origW, page.origH));
|
||||
document.addPage(newPage);
|
||||
|
||||
try (PDPageContentStream contentStream = new PDPageContentStream(document, newPage)) {
|
||||
try (PDPageContentStream contentStream =
|
||||
new PDPageContentStream(
|
||||
document,
|
||||
newPage,
|
||||
PDPageContentStream.AppendMode.OVERWRITE,
|
||||
true,
|
||||
true)) {
|
||||
PDImageXObject pdImage = LosslessFactory.createFromImage(document, page.image);
|
||||
contentStream.drawImage(
|
||||
pdImage, page.offsetX, page.offsetY, page.drawW, page.drawH);
|
||||
|
||||
+51
-46
@@ -134,60 +134,65 @@ public class StampController {
|
||||
};
|
||||
|
||||
// Load the input PDF
|
||||
PDDocument document = pdfDocumentFactory.load(pdfFile);
|
||||
try (PDDocument document = pdfDocumentFactory.load(pdfFile)) {
|
||||
|
||||
List<Integer> pageNumbers = request.getPageNumbersList(document, true);
|
||||
List<Integer> pageNumbers = request.getPageNumbersList(document, true);
|
||||
|
||||
for (int pageIndex : pageNumbers) {
|
||||
int zeroBasedIndex = pageIndex - 1;
|
||||
if (zeroBasedIndex >= 0 && zeroBasedIndex < document.getNumberOfPages()) {
|
||||
PDPage page = document.getPage(zeroBasedIndex);
|
||||
PDRectangle pageSize = page.getMediaBox();
|
||||
float margin = marginFactor * (pageSize.getWidth() + pageSize.getHeight()) / 2;
|
||||
for (int pageIndex : pageNumbers) {
|
||||
int zeroBasedIndex = pageIndex - 1;
|
||||
if (zeroBasedIndex >= 0 && zeroBasedIndex < document.getNumberOfPages()) {
|
||||
PDPage page = document.getPage(zeroBasedIndex);
|
||||
PDRectangle pageSize = page.getMediaBox();
|
||||
float margin = marginFactor * (pageSize.getWidth() + pageSize.getHeight()) / 2;
|
||||
|
||||
PDPageContentStream contentStream =
|
||||
new PDPageContentStream(
|
||||
document, page, PDPageContentStream.AppendMode.APPEND, true, true);
|
||||
PDPageContentStream contentStream =
|
||||
new PDPageContentStream(
|
||||
document,
|
||||
page,
|
||||
PDPageContentStream.AppendMode.APPEND,
|
||||
true,
|
||||
true);
|
||||
|
||||
PDExtendedGraphicsState graphicsState = new PDExtendedGraphicsState();
|
||||
graphicsState.setNonStrokingAlphaConstant(opacity);
|
||||
contentStream.setGraphicsStateParameters(graphicsState);
|
||||
PDExtendedGraphicsState graphicsState = new PDExtendedGraphicsState();
|
||||
graphicsState.setNonStrokingAlphaConstant(opacity);
|
||||
contentStream.setGraphicsStateParameters(graphicsState);
|
||||
|
||||
if ("text".equalsIgnoreCase(stampType)) {
|
||||
addTextStamp(
|
||||
contentStream,
|
||||
stampText,
|
||||
document,
|
||||
page,
|
||||
rotation,
|
||||
position,
|
||||
fontSize,
|
||||
alphabet,
|
||||
overrideX,
|
||||
overrideY,
|
||||
margin,
|
||||
customColor);
|
||||
} else if ("image".equalsIgnoreCase(stampType)) {
|
||||
addImageStamp(
|
||||
contentStream,
|
||||
stampImage,
|
||||
document,
|
||||
page,
|
||||
rotation,
|
||||
position,
|
||||
fontSize,
|
||||
overrideX,
|
||||
overrideY,
|
||||
margin);
|
||||
if ("text".equalsIgnoreCase(stampType)) {
|
||||
addTextStamp(
|
||||
contentStream,
|
||||
stampText,
|
||||
document,
|
||||
page,
|
||||
rotation,
|
||||
position,
|
||||
fontSize,
|
||||
alphabet,
|
||||
overrideX,
|
||||
overrideY,
|
||||
margin,
|
||||
customColor);
|
||||
} else if ("image".equalsIgnoreCase(stampType)) {
|
||||
addImageStamp(
|
||||
contentStream,
|
||||
stampImage,
|
||||
document,
|
||||
page,
|
||||
rotation,
|
||||
position,
|
||||
fontSize,
|
||||
overrideX,
|
||||
overrideY,
|
||||
margin);
|
||||
}
|
||||
|
||||
contentStream.close();
|
||||
}
|
||||
|
||||
contentStream.close();
|
||||
}
|
||||
// Return the stamped PDF as a response
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document,
|
||||
GeneralUtils.generateFilename(pdfFile.getOriginalFilename(), "_stamped.pdf"));
|
||||
}
|
||||
// Return the stamped PDF as a response
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document,
|
||||
GeneralUtils.generateFilename(pdfFile.getOriginalFilename(), "_stamped.pdf"));
|
||||
}
|
||||
|
||||
private void addTextStamp(
|
||||
|
||||
+2
-1
@@ -139,11 +139,12 @@ public class CertSignController {
|
||||
signatureOptions.setPage(pageNumber);
|
||||
|
||||
doc.addSignature(signature, instance, signatureOptions);
|
||||
doc.saveIncremental(output);
|
||||
}
|
||||
} else {
|
||||
doc.addSignature(signature, instance);
|
||||
doc.saveIncremental(output);
|
||||
}
|
||||
doc.saveIncremental(output);
|
||||
} catch (Exception e) {
|
||||
ExceptionUtils.logException("PDF signing", e);
|
||||
}
|
||||
|
||||
+30
-4
@@ -3,6 +3,8 @@ package stirling.software.SPDF.controller.api.security;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
@@ -14,7 +16,8 @@ import java.util.regex.Pattern;
|
||||
import org.apache.pdfbox.cos.COSInputStream;
|
||||
import org.apache.pdfbox.cos.COSName;
|
||||
import org.apache.pdfbox.cos.COSString;
|
||||
import org.apache.pdfbox.io.RandomAccessReadBuffer;
|
||||
import org.apache.pdfbox.io.RandomAccessRead;
|
||||
import org.apache.pdfbox.io.RandomAccessReadBufferedFile;
|
||||
import org.apache.pdfbox.pdmodel.*;
|
||||
import org.apache.pdfbox.pdmodel.common.PDMetadata;
|
||||
import org.apache.pdfbox.pdmodel.common.PDRectangle;
|
||||
@@ -198,10 +201,20 @@ public class GetInfoOnPDF {
|
||||
return false;
|
||||
}
|
||||
|
||||
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
|
||||
document.save(baos);
|
||||
// Use Stream-to-File pattern: save to temp file instead of loading into memory
|
||||
// This prevents OutOfMemoryError on large PDFs
|
||||
Path tempFile = null;
|
||||
try {
|
||||
tempFile = Files.createTempFile("preflight-", ".pdf");
|
||||
|
||||
try (RandomAccessReadBuffer source = new RandomAccessReadBuffer(baos.toByteArray())) {
|
||||
// Save document to temp file (avoids loading entire document into memory)
|
||||
try (var outputStream = Files.newOutputStream(tempFile)) {
|
||||
document.save(outputStream);
|
||||
}
|
||||
|
||||
// Use RandomAccessReadBufferedFile for efficient file-based reading
|
||||
// This avoids Windows file locking issues that occur with memory-mapped files
|
||||
try (RandomAccessRead source = new RandomAccessReadBufferedFile(tempFile.toFile())) {
|
||||
PreflightParser parser = new PreflightParser(source);
|
||||
|
||||
try (PDDocument parsedDocument = parser.parse()) {
|
||||
@@ -243,6 +256,19 @@ public class GetInfoOnPDF {
|
||||
log.debug("IOException during PDF/A validation: {}", e.getMessage());
|
||||
} catch (Exception e) {
|
||||
log.debug("Unexpected error during PDF/A validation: {}", e.getMessage());
|
||||
} finally {
|
||||
// Explicitly clean up temp file to prevent disk exhaustion
|
||||
// This must be in finally block to ensure cleanup even on exceptions
|
||||
if (tempFile != null) {
|
||||
try {
|
||||
Files.deleteIfExists(tempFile);
|
||||
} catch (IOException e) {
|
||||
log.warn(
|
||||
"Failed to delete temp file during PDF/A validation cleanup: {}",
|
||||
tempFile,
|
||||
e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
|
||||
+31
-34
@@ -42,25 +42,17 @@ public class PasswordController {
|
||||
MultipartFile fileInput = request.getFileInput();
|
||||
String password = request.getPassword();
|
||||
|
||||
PDDocument document;
|
||||
try {
|
||||
document = pdfDocumentFactory.load(fileInput, password);
|
||||
} catch (IOException e) {
|
||||
// Handle password errors specifically
|
||||
if (ExceptionUtils.isPasswordError(e)) {
|
||||
throw ExceptionUtils.createPdfPasswordException(e);
|
||||
}
|
||||
throw ExceptionUtils.handlePdfException(e);
|
||||
}
|
||||
|
||||
try {
|
||||
try (PDDocument document = pdfDocumentFactory.load(fileInput, password)) {
|
||||
document.setAllSecurityToBeRemoved(true);
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document,
|
||||
GeneralUtils.generateFilename(
|
||||
fileInput.getOriginalFilename(), "_password_removed.pdf"));
|
||||
} catch (IOException e) {
|
||||
document.close();
|
||||
// Handle password errors specifically
|
||||
if (ExceptionUtils.isPasswordError(e)) {
|
||||
throw ExceptionUtils.createPdfPasswordException(e);
|
||||
}
|
||||
ExceptionUtils.logException("password removal", e);
|
||||
throw ExceptionUtils.handlePdfException(e);
|
||||
}
|
||||
@@ -91,31 +83,36 @@ public class PasswordController {
|
||||
boolean preventPrinting = Boolean.TRUE.equals(request.getPreventPrinting());
|
||||
boolean preventPrintingFaithful = Boolean.TRUE.equals(request.getPreventPrintingFaithful());
|
||||
|
||||
PDDocument document = pdfDocumentFactory.load(fileInput);
|
||||
AccessPermission ap = new AccessPermission();
|
||||
ap.setCanAssembleDocument(!preventAssembly);
|
||||
ap.setCanExtractContent(!preventExtractContent);
|
||||
ap.setCanExtractForAccessibility(!preventExtractForAccessibility);
|
||||
ap.setCanFillInForm(!preventFillInForm);
|
||||
ap.setCanModify(!preventModify);
|
||||
ap.setCanModifyAnnotations(!preventModifyAnnotations);
|
||||
ap.setCanPrint(!preventPrinting);
|
||||
ap.setCanPrintFaithful(!preventPrintingFaithful);
|
||||
StandardProtectionPolicy spp = new StandardProtectionPolicy(ownerPassword, password, ap);
|
||||
try (PDDocument document = pdfDocumentFactory.load(fileInput)) {
|
||||
AccessPermission ap = new AccessPermission();
|
||||
ap.setCanAssembleDocument(!preventAssembly);
|
||||
ap.setCanExtractContent(!preventExtractContent);
|
||||
ap.setCanExtractForAccessibility(!preventExtractForAccessibility);
|
||||
ap.setCanFillInForm(!preventFillInForm);
|
||||
ap.setCanModify(!preventModify);
|
||||
ap.setCanModifyAnnotations(!preventModifyAnnotations);
|
||||
ap.setCanPrint(!preventPrinting);
|
||||
ap.setCanPrintFaithful(!preventPrintingFaithful);
|
||||
StandardProtectionPolicy spp =
|
||||
new StandardProtectionPolicy(ownerPassword, password, ap);
|
||||
|
||||
if (!"".equals(ownerPassword) || !"".equals(password)) {
|
||||
spp.setEncryptionKeyLength(keyLength);
|
||||
}
|
||||
spp.setPermissions(ap);
|
||||
document.protect(spp);
|
||||
if ((ownerPassword != null && ownerPassword.length() > 0)
|
||||
|| (password != null && password.length() > 0)) {
|
||||
spp.setEncryptionKeyLength(keyLength);
|
||||
}
|
||||
spp.setPermissions(ap);
|
||||
document.protect(spp);
|
||||
|
||||
if ("".equals(ownerPassword) && "".equals(password))
|
||||
if ((ownerPassword == null || ownerPassword.length() == 0)
|
||||
&& (password == null || password.length() == 0))
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document,
|
||||
GeneralUtils.generateFilename(
|
||||
fileInput.getOriginalFilename(), "_permissions.pdf"));
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document,
|
||||
GeneralUtils.generateFilename(
|
||||
fileInput.getOriginalFilename(), "_permissions.pdf"));
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document,
|
||||
GeneralUtils.generateFilename(fileInput.getOriginalFilename(), "_passworded.pdf"));
|
||||
fileInput.getOriginalFilename(), "_passworded.pdf"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+19
-18
@@ -41,28 +41,29 @@ public class RemoveCertSignController {
|
||||
throws Exception {
|
||||
MultipartFile pdf = request.getFileInput();
|
||||
|
||||
// Load the PDF document
|
||||
PDDocument document = pdfDocumentFactory.load(pdf);
|
||||
// Load the PDF document with proper resource management
|
||||
try (PDDocument document = pdfDocumentFactory.load(pdf)) {
|
||||
|
||||
// Get the document catalog
|
||||
PDDocumentCatalog catalog = document.getDocumentCatalog();
|
||||
// Get the document catalog
|
||||
PDDocumentCatalog catalog = document.getDocumentCatalog();
|
||||
|
||||
// Get the AcroForm
|
||||
PDAcroForm acroForm = catalog.getAcroForm();
|
||||
if (acroForm != null) {
|
||||
// Remove signature fields safely
|
||||
List<PDField> fieldsToRemove =
|
||||
acroForm.getFields().stream()
|
||||
.filter(field -> field instanceof PDSignatureField)
|
||||
.toList();
|
||||
// Get the AcroForm
|
||||
PDAcroForm acroForm = catalog.getAcroForm();
|
||||
if (acroForm != null) {
|
||||
// Remove signature fields safely
|
||||
List<PDField> fieldsToRemove =
|
||||
acroForm.getFields().stream()
|
||||
.filter(field -> field instanceof PDSignatureField)
|
||||
.toList();
|
||||
|
||||
if (!fieldsToRemove.isEmpty()) {
|
||||
acroForm.flatten(fieldsToRemove, false);
|
||||
if (!fieldsToRemove.isEmpty()) {
|
||||
acroForm.flatten(fieldsToRemove, false);
|
||||
}
|
||||
}
|
||||
// Return the modified PDF as a response
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document,
|
||||
GeneralUtils.generateFilename(pdf.getOriginalFilename(), "_unsigned.pdf"));
|
||||
}
|
||||
// Return the modified PDF as a response
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document,
|
||||
GeneralUtils.generateFilename(pdf.getOriginalFilename(), "_unsigned.pdf"));
|
||||
}
|
||||
}
|
||||
|
||||
+33
-32
@@ -67,39 +67,40 @@ public class SanitizeController {
|
||||
boolean removeLinks = Boolean.TRUE.equals(request.getRemoveLinks());
|
||||
boolean removeFonts = Boolean.TRUE.equals(request.getRemoveFonts());
|
||||
|
||||
PDDocument document = pdfDocumentFactory.load(inputFile, true);
|
||||
if (removeJavaScript) {
|
||||
sanitizeJavaScript(document);
|
||||
try (PDDocument document = pdfDocumentFactory.load(inputFile, true)) {
|
||||
if (removeJavaScript) {
|
||||
sanitizeJavaScript(document);
|
||||
}
|
||||
|
||||
if (removeEmbeddedFiles) {
|
||||
sanitizeEmbeddedFiles(document);
|
||||
}
|
||||
|
||||
if (removeXMPMetadata) {
|
||||
sanitizeXMPMetadata(document);
|
||||
}
|
||||
|
||||
if (removeMetadata) {
|
||||
sanitizeDocumentInfoMetadata(document);
|
||||
}
|
||||
|
||||
if (removeLinks) {
|
||||
sanitizeLinks(document);
|
||||
}
|
||||
|
||||
if (removeFonts) {
|
||||
sanitizeFonts(document);
|
||||
}
|
||||
|
||||
// Save the sanitized document to output stream
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
document.save(outputStream);
|
||||
|
||||
return WebResponseUtils.bytesToWebResponse(
|
||||
outputStream.toByteArray(),
|
||||
GeneralUtils.generateFilename(
|
||||
inputFile.getOriginalFilename(), "_sanitized.pdf"));
|
||||
}
|
||||
|
||||
if (removeEmbeddedFiles) {
|
||||
sanitizeEmbeddedFiles(document);
|
||||
}
|
||||
|
||||
if (removeXMPMetadata) {
|
||||
sanitizeXMPMetadata(document);
|
||||
}
|
||||
|
||||
if (removeMetadata) {
|
||||
sanitizeDocumentInfoMetadata(document);
|
||||
}
|
||||
|
||||
if (removeLinks) {
|
||||
sanitizeLinks(document);
|
||||
}
|
||||
|
||||
if (removeFonts) {
|
||||
sanitizeFonts(document);
|
||||
}
|
||||
|
||||
// Save the sanitized document to output stream
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
document.save(outputStream);
|
||||
document.close();
|
||||
|
||||
return WebResponseUtils.bytesToWebResponse(
|
||||
outputStream.toByteArray(),
|
||||
GeneralUtils.generateFilename(inputFile.getOriginalFilename(), "_sanitized.pdf"));
|
||||
}
|
||||
|
||||
private static void sanitizeJavaScript(PDDocument document) throws IOException {
|
||||
|
||||
+55
-48
@@ -98,60 +98,67 @@ public class WatermarkController {
|
||||
String customColor = request.getCustomColor();
|
||||
boolean convertPdfToImage = Boolean.TRUE.equals(request.getConvertPDFToImage());
|
||||
|
||||
// Load the input PDF
|
||||
PDDocument document = pdfDocumentFactory.load(pdfFile);
|
||||
// Load the input PDF with proper resource management
|
||||
try (PDDocument document = pdfDocumentFactory.load(pdfFile)) {
|
||||
|
||||
// Create a page in the document
|
||||
for (PDPage page : document.getPages()) {
|
||||
// Create a page in the document
|
||||
for (PDPage page : document.getPages()) {
|
||||
// Get the page's content stream
|
||||
try (PDPageContentStream contentStream =
|
||||
new PDPageContentStream(
|
||||
document,
|
||||
page,
|
||||
PDPageContentStream.AppendMode.APPEND,
|
||||
true,
|
||||
true)) {
|
||||
|
||||
// Get the page's content stream
|
||||
PDPageContentStream contentStream =
|
||||
new PDPageContentStream(
|
||||
document, page, PDPageContentStream.AppendMode.APPEND, true, true);
|
||||
// Set transparency
|
||||
PDExtendedGraphicsState graphicsState = new PDExtendedGraphicsState();
|
||||
graphicsState.setNonStrokingAlphaConstant(opacity);
|
||||
contentStream.setGraphicsStateParameters(graphicsState);
|
||||
|
||||
// Set transparency
|
||||
PDExtendedGraphicsState graphicsState = new PDExtendedGraphicsState();
|
||||
graphicsState.setNonStrokingAlphaConstant(opacity);
|
||||
contentStream.setGraphicsStateParameters(graphicsState);
|
||||
|
||||
if ("text".equalsIgnoreCase(watermarkType)) {
|
||||
addTextWatermark(
|
||||
contentStream,
|
||||
watermarkText,
|
||||
document,
|
||||
page,
|
||||
rotation,
|
||||
widthSpacer,
|
||||
heightSpacer,
|
||||
fontSize,
|
||||
alphabet,
|
||||
customColor);
|
||||
} else if ("image".equalsIgnoreCase(watermarkType)) {
|
||||
addImageWatermark(
|
||||
contentStream,
|
||||
watermarkImage,
|
||||
document,
|
||||
page,
|
||||
rotation,
|
||||
widthSpacer,
|
||||
heightSpacer,
|
||||
fontSize);
|
||||
if ("text".equalsIgnoreCase(watermarkType)) {
|
||||
addTextWatermark(
|
||||
contentStream,
|
||||
watermarkText,
|
||||
document,
|
||||
page,
|
||||
rotation,
|
||||
widthSpacer,
|
||||
heightSpacer,
|
||||
fontSize,
|
||||
alphabet,
|
||||
customColor);
|
||||
} else if ("image".equalsIgnoreCase(watermarkType)) {
|
||||
addImageWatermark(
|
||||
contentStream,
|
||||
watermarkImage,
|
||||
document,
|
||||
page,
|
||||
rotation,
|
||||
widthSpacer,
|
||||
heightSpacer,
|
||||
fontSize);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Close the content stream
|
||||
contentStream.close();
|
||||
if (convertPdfToImage) {
|
||||
try (PDDocument convertedPdf = PdfUtils.convertPdfToPdfImage(document)) {
|
||||
// Return the watermarked PDF as a response
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
convertedPdf,
|
||||
GeneralUtils.generateFilename(
|
||||
pdfFile.getOriginalFilename(), "_watermarked.pdf"));
|
||||
}
|
||||
} else {
|
||||
// Return the watermarked PDF as a response
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document,
|
||||
GeneralUtils.generateFilename(
|
||||
pdfFile.getOriginalFilename(), "_watermarked.pdf"));
|
||||
}
|
||||
}
|
||||
|
||||
if (convertPdfToImage) {
|
||||
PDDocument convertedPdf = PdfUtils.convertPdfToPdfImage(document);
|
||||
document.close();
|
||||
document = convertedPdf;
|
||||
}
|
||||
|
||||
// Return the watermarked PDF as a response
|
||||
return WebResponseUtils.pdfDocToWebResponse(
|
||||
document,
|
||||
GeneralUtils.generateFilename(pdfFile.getOriginalFilename(), "_watermarked.pdf"));
|
||||
}
|
||||
|
||||
private void addTextWatermark(
|
||||
|
||||
+392
-49
@@ -15,84 +15,106 @@ import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.util.HtmlUtils;
|
||||
import org.springframework.web.util.JavaScriptUtils;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.configuration.InstallationPathConfig;
|
||||
|
||||
@Slf4j
|
||||
@Controller
|
||||
public class ReactRoutingController {
|
||||
|
||||
private static final org.slf4j.Logger log =
|
||||
org.slf4j.LoggerFactory.getLogger(ReactRoutingController.class);
|
||||
|
||||
@Value("${server.servlet.context-path:/}")
|
||||
private String contextPath;
|
||||
|
||||
private String cachedIndexHtml;
|
||||
private String cachedCallbackHtml;
|
||||
private boolean indexHtmlExists = false;
|
||||
private boolean useExternalIndexHtml = false;
|
||||
private boolean loggedMissingIndex = false;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
log.info("Static files custom path: {}", InstallationPathConfig.getStaticPath());
|
||||
|
||||
// Always initialize callback HTML (used for OAuth desktop flow)
|
||||
this.cachedCallbackHtml = buildCallbackHtml();
|
||||
|
||||
// Check for external index.html first (customFiles/static/)
|
||||
Path externalIndexPath = Paths.get(InstallationPathConfig.getStaticPath(), "index.html");
|
||||
log.debug("Checking for custom index.html at: {}", externalIndexPath);
|
||||
if (Files.exists(externalIndexPath) && Files.isReadable(externalIndexPath)) {
|
||||
log.info("Using custom index.html from: {}", externalIndexPath);
|
||||
try {
|
||||
this.cachedIndexHtml = processIndexHtml();
|
||||
this.indexHtmlExists = true;
|
||||
this.useExternalIndexHtml = true;
|
||||
return;
|
||||
} catch (IOException e) {
|
||||
log.warn("Failed to load custom index.html, falling back to classpath", e);
|
||||
}
|
||||
this.cachedIndexHtml = processIndexHtml();
|
||||
this.indexHtmlExists = true;
|
||||
this.useExternalIndexHtml = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// Fall back to classpath index.html
|
||||
ClassPathResource resource = new ClassPathResource("static/index.html");
|
||||
if (resource.exists()) {
|
||||
try {
|
||||
this.cachedIndexHtml = processIndexHtml();
|
||||
this.indexHtmlExists = true;
|
||||
this.useExternalIndexHtml = false;
|
||||
} catch (IOException e) {
|
||||
// Failed to cache, will process on each request
|
||||
log.warn("Failed to cache index.html", e);
|
||||
this.indexHtmlExists = false;
|
||||
this.cachedIndexHtml = processIndexHtml();
|
||||
this.indexHtmlExists = true;
|
||||
this.useExternalIndexHtml = false;
|
||||
return;
|
||||
}
|
||||
|
||||
// Neither external nor classpath index.html exists - cache fallback once
|
||||
this.cachedIndexHtml = buildFallbackHtml();
|
||||
this.indexHtmlExists = true;
|
||||
this.useExternalIndexHtml = false;
|
||||
this.loggedMissingIndex = true;
|
||||
log.warn(
|
||||
"index.html not found in classpath or custom path; using lightweight fallback page");
|
||||
}
|
||||
|
||||
private String processIndexHtml() {
|
||||
try {
|
||||
Resource resource = getIndexHtmlResource();
|
||||
|
||||
if (!resource.exists()) {
|
||||
if (!loggedMissingIndex) {
|
||||
log.warn("index.html not found, using lightweight fallback page");
|
||||
loggedMissingIndex = true;
|
||||
}
|
||||
return buildFallbackHtml();
|
||||
}
|
||||
|
||||
try (InputStream inputStream = resource.getInputStream()) {
|
||||
String html = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
|
||||
|
||||
// Replace %BASE_URL% with the actual context path for base href
|
||||
String baseUrl = contextPath.endsWith("/") ? contextPath : contextPath + "/";
|
||||
html = html.replace("%BASE_URL%", baseUrl);
|
||||
// Also rewrite any existing <base> tag (Vite may have baked one in)
|
||||
html =
|
||||
html.replaceFirst(
|
||||
"<base href=\\\"[^\\\"]*\\\"\\s*/?>",
|
||||
"<base href=\\\"" + baseUrl + "\\\" />");
|
||||
|
||||
// Inject context path as a global variable for API calls
|
||||
String contextPathScript =
|
||||
"<script>window.STIRLING_PDF_API_BASE_URL = '" + baseUrl + "';</script>";
|
||||
html = html.replace("</head>", contextPathScript + "</head>");
|
||||
|
||||
return html;
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
if (!loggedMissingIndex) {
|
||||
log.warn("index.html not found, using lightweight fallback page", ex);
|
||||
loggedMissingIndex = true;
|
||||
}
|
||||
return buildFallbackHtml();
|
||||
}
|
||||
}
|
||||
|
||||
private String processIndexHtml() throws IOException {
|
||||
Resource resource = getIndexHtmlResource();
|
||||
|
||||
try (InputStream inputStream = resource.getInputStream()) {
|
||||
String html = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
|
||||
|
||||
// Replace %BASE_URL% with the actual context path for base href
|
||||
String baseUrl = contextPath.endsWith("/") ? contextPath : contextPath + "/";
|
||||
html = html.replace("%BASE_URL%", baseUrl);
|
||||
// Also rewrite any existing <base> tag (Vite may have baked one in)
|
||||
html =
|
||||
html.replaceFirst(
|
||||
"<base href=\\\"[^\\\"]*\\\"\\s*/?>",
|
||||
"<base href=\\\"" + baseUrl + "\\\" />");
|
||||
|
||||
// Inject context path as a global variable for API calls
|
||||
String contextPathScript =
|
||||
"<script>window.STIRLING_PDF_API_BASE_URL = '" + baseUrl + "';</script>";
|
||||
html = html.replace("</head>", contextPathScript + "</head>");
|
||||
|
||||
return html;
|
||||
}
|
||||
}
|
||||
|
||||
private Resource getIndexHtmlResource() throws IOException {
|
||||
private Resource getIndexHtmlResource() {
|
||||
// Check external location first
|
||||
Path externalIndexPath = Paths.get(InstallationPathConfig.getStaticPath(), "index.html");
|
||||
if (Files.exists(externalIndexPath) && Files.isReadable(externalIndexPath)) {
|
||||
@@ -106,12 +128,28 @@ public class ReactRoutingController {
|
||||
@GetMapping(
|
||||
value = {"/", "/index.html"},
|
||||
produces = MediaType.TEXT_HTML_VALUE)
|
||||
public ResponseEntity<String> serveIndexHtml(HttpServletRequest request) throws IOException {
|
||||
if (indexHtmlExists && cachedIndexHtml != null) {
|
||||
return ResponseEntity.ok().contentType(MediaType.TEXT_HTML).body(cachedIndexHtml);
|
||||
public ResponseEntity<String> serveIndexHtml(HttpServletRequest request) {
|
||||
try {
|
||||
if (indexHtmlExists && cachedIndexHtml != null) {
|
||||
return ResponseEntity.ok().contentType(MediaType.TEXT_HTML).body(cachedIndexHtml);
|
||||
}
|
||||
// Fallback: process on each request (dev mode or cache failed)
|
||||
return ResponseEntity.ok().contentType(MediaType.TEXT_HTML).body(processIndexHtml());
|
||||
} catch (Exception ex) {
|
||||
log.error("Failed to serve index.html, returning fallback", ex);
|
||||
return ResponseEntity.ok().contentType(MediaType.TEXT_HTML).body(buildFallbackHtml());
|
||||
}
|
||||
// Fallback: process on each request (dev mode or cache failed)
|
||||
return ResponseEntity.ok().contentType(MediaType.TEXT_HTML).body(processIndexHtml());
|
||||
}
|
||||
|
||||
@GetMapping(value = "/auth/callback", produces = MediaType.TEXT_HTML_VALUE)
|
||||
public ResponseEntity<String> serveAuthCallback(HttpServletRequest request) {
|
||||
return serveIndexHtml(request);
|
||||
}
|
||||
|
||||
@GetMapping(value = "/auth/callback/tauri", produces = MediaType.TEXT_HTML_VALUE)
|
||||
public ResponseEntity<String> serveTauriAuthCallback(HttpServletRequest request) {
|
||||
// cachedCallbackHtml is always initialized in @PostConstruct
|
||||
return ResponseEntity.ok().contentType(MediaType.TEXT_HTML).body(cachedCallbackHtml);
|
||||
}
|
||||
|
||||
@GetMapping(
|
||||
@@ -126,4 +164,309 @@ public class ReactRoutingController {
|
||||
throws IOException {
|
||||
return serveIndexHtml(request);
|
||||
}
|
||||
|
||||
private String buildFallbackHtml() {
|
||||
String baseUrl = contextPath.endsWith("/") ? contextPath : contextPath + "/";
|
||||
|
||||
// Escape for HTML attribute context
|
||||
String escapedBaseUrlHtml = HtmlUtils.htmlEscape(baseUrl);
|
||||
|
||||
// Escape for JavaScript string context
|
||||
String escapedBaseUrlJs = JavaScriptUtils.javaScriptEscape(baseUrl);
|
||||
|
||||
String serverUrl = "(window.location.origin + '" + escapedBaseUrlJs + "')";
|
||||
return """
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<base href="%s" />
|
||||
<title>Stirling PDF</title>
|
||||
<script>
|
||||
// Minimal handler for SSO callback when index.html is missing (desktop fallback)
|
||||
(function() {
|
||||
const baseUrl = '%s';
|
||||
window.STIRLING_PDF_API_BASE_URL = baseUrl;
|
||||
const hashParams = new URLSearchParams(window.location.hash.replace(/^#/, ''));
|
||||
const searchParams = new URLSearchParams(window.location.search);
|
||||
const token = hashParams.get('access_token') || hashParams.get('token') || searchParams.get('access_token');
|
||||
const serverUrl = %s;
|
||||
|
||||
if (token) {
|
||||
// Extract nonce from URL to send back to desktop app for validation
|
||||
const nonceFromUrl = hashParams.get('nonce') || searchParams.get('nonce');
|
||||
|
||||
console.log('[Fallback Auth] Token received, sending to desktop app via deep link');
|
||||
|
||||
// Send token + nonce via deep link to desktop app
|
||||
// Desktop app will validate nonce before accepting token
|
||||
try {
|
||||
const encodedToken = encodeURIComponent(token);
|
||||
const encodedServer = encodeURIComponent(serverUrl);
|
||||
const encodedNonce = nonceFromUrl ? encodeURIComponent(nonceFromUrl) : '';
|
||||
const deepLink = `stirlingpdf://auth/sso-complete?server=${encodedServer}#access_token=${encodedToken}&nonce=${encodedNonce}&type=sso-selfhosted`;
|
||||
window.location.href = deepLink;
|
||||
return;
|
||||
} catch (_) {
|
||||
// ignore deep link errors
|
||||
}
|
||||
}
|
||||
|
||||
// No redirect to avoid loops when index.html is missing
|
||||
})();
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<p>Stirling PDF is running.</p>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
.formatted(escapedBaseUrlHtml, escapedBaseUrlJs, serverUrl);
|
||||
}
|
||||
|
||||
private String buildCallbackHtml() {
|
||||
String baseUrl = contextPath.endsWith("/") ? contextPath : contextPath + "/";
|
||||
|
||||
// Escape for HTML attribute context
|
||||
String escapedBaseUrlHtml = HtmlUtils.htmlEscape(baseUrl);
|
||||
|
||||
// Escape for JavaScript string context
|
||||
String escapedBaseUrlJs = JavaScriptUtils.javaScriptEscape(baseUrl);
|
||||
|
||||
String serverUrl = "(window.location.origin + '" + escapedBaseUrlJs + "')";
|
||||
return """
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<base href="%s" />
|
||||
<title>Authentication Complete</title>
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
text-align: center;
|
||||
padding: 50px 20px;
|
||||
background: #f5f5f5;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.container {
|
||||
background: #ffffff;
|
||||
border-radius: 12px;
|
||||
padding: 40px;
|
||||
max-width: 420px;
|
||||
width: 100%%;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
||||
border: 1px solid #e5e7eb;
|
||||
color: #1a1a1a;
|
||||
}
|
||||
|
||||
.icon {
|
||||
font-size: 48px;
|
||||
margin-bottom: 16px;
|
||||
color: #2e7d32;
|
||||
}
|
||||
|
||||
.icon.error {
|
||||
color: #d32f2f;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 24px;
|
||||
font-weight: 600;
|
||||
margin-bottom: 12px;
|
||||
color: #1a1a1a;
|
||||
}
|
||||
|
||||
p {
|
||||
color: #666;
|
||||
line-height: 1.6;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.error-details {
|
||||
background: #ffebee;
|
||||
border: 1px solid #ffcdd2;
|
||||
padding: 16px;
|
||||
border-radius: 8px;
|
||||
margin-top: 20px;
|
||||
font-size: 14px;
|
||||
color: #c62828;
|
||||
word-break: break-word;
|
||||
text-align: left;
|
||||
line-height: 1.5;
|
||||
display: none;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
body {
|
||||
background: #1a1a1a;
|
||||
color: #e0e0e0;
|
||||
}
|
||||
|
||||
.container {
|
||||
background: #2d2d2d;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
|
||||
border-color: #374151;
|
||||
color: #e5e7eb;
|
||||
}
|
||||
|
||||
.icon {
|
||||
color: #66bb6a;
|
||||
}
|
||||
|
||||
.icon.error {
|
||||
color: #ef5350;
|
||||
}
|
||||
|
||||
h1 {
|
||||
color: #f5f5f5;
|
||||
}
|
||||
|
||||
p {
|
||||
color: #b0b0b0;
|
||||
}
|
||||
|
||||
.error-details {
|
||||
background: #3d2020;
|
||||
border: 1px solid #5d3030;
|
||||
color: #ef9a9a;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
body {
|
||||
padding: 20px 16px;
|
||||
}
|
||||
|
||||
.container {
|
||||
padding: 32px 24px;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.icon {
|
||||
font-size: 40px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<script>
|
||||
(function() {
|
||||
const run = () => {
|
||||
const hashParams = new URLSearchParams(window.location.hash.replace(/^#/, ''));
|
||||
const searchParams = new URLSearchParams(window.location.search);
|
||||
const token = hashParams.get('access_token') || hashParams.get('token') || searchParams.get('access_token');
|
||||
const errorCode = searchParams.get('errorOAuth')
|
||||
|| searchParams.get('error')
|
||||
|| hashParams.get('error')
|
||||
|| searchParams.get('error_description')
|
||||
|| hashParams.get('error_description');
|
||||
const serverUrl = %s;
|
||||
const iconEl = document.getElementById('auth-icon');
|
||||
const titleEl = document.getElementById('auth-title');
|
||||
const messageEl = document.getElementById('auth-message');
|
||||
const detailsEl = document.getElementById('auth-error-details');
|
||||
|
||||
const sendDeepLink = (type, value, key) => {
|
||||
try {
|
||||
const encodedValue = encodeURIComponent(value || '');
|
||||
const encodedServer = encodeURIComponent(serverUrl);
|
||||
const hashKey = key || 'access_token';
|
||||
const deepLink = `stirlingpdf://auth/sso-complete?server=${encodedServer}#${hashKey}=${encodedValue}&type=${type}`;
|
||||
window.location.href = deepLink;
|
||||
} catch (_) {
|
||||
// ignore deep link errors
|
||||
}
|
||||
};
|
||||
|
||||
const showError = (message, details) => {
|
||||
if (iconEl) {
|
||||
iconEl.textContent = '✗';
|
||||
iconEl.classList.add('error');
|
||||
}
|
||||
if (titleEl) {
|
||||
titleEl.textContent = 'Authentication failed';
|
||||
}
|
||||
if (messageEl) {
|
||||
messageEl.textContent = message;
|
||||
}
|
||||
if (detailsEl && details) {
|
||||
detailsEl.textContent = details;
|
||||
detailsEl.style.display = 'block';
|
||||
}
|
||||
};
|
||||
|
||||
if (token) {
|
||||
// Extract nonce from URL to send back to desktop app for validation
|
||||
// (System browser doesn't have access to desktop app's sessionStorage)
|
||||
const nonceFromUrl = hashParams.get('nonce') || searchParams.get('nonce');
|
||||
|
||||
console.log('[Auth Callback] Token received, sending to desktop app via deep link');
|
||||
|
||||
// Send token + nonce via deep link to desktop app
|
||||
// Desktop app will validate nonce before accepting token
|
||||
setTimeout(() => {
|
||||
try {
|
||||
const encodedToken = encodeURIComponent(token);
|
||||
const encodedServer = encodeURIComponent(serverUrl);
|
||||
const encodedNonce = nonceFromUrl ? encodeURIComponent(nonceFromUrl) : '';
|
||||
const deepLink = `stirlingpdf://auth/sso-complete?server=${encodedServer}#access_token=${encodedToken}&nonce=${encodedNonce}&type=sso-selfhosted`;
|
||||
window.location.href = deepLink;
|
||||
} catch (err) {
|
||||
console.error('[Auth Callback] Failed to trigger deep link:', err);
|
||||
}
|
||||
}, 200);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (errorCode) {
|
||||
const isCancelled = errorCode === 'access_denied';
|
||||
sendDeepLink('sso-error', errorCode, 'error');
|
||||
showError(
|
||||
isCancelled
|
||||
? 'Authentication was cancelled. You can close this window and return to the app.'
|
||||
: 'Authentication was not successful. You can close this window and return to the app.',
|
||||
errorCode
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
showError(
|
||||
'Authentication did not complete. You can close this window and try again.',
|
||||
'missing_token'
|
||||
);
|
||||
};
|
||||
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', run);
|
||||
} else {
|
||||
run();
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="icon" id="auth-icon">✓</div>
|
||||
<h1 id="auth-title">Authentication complete</h1>
|
||||
<p id="auth-message">You can close this window and return to Stirling PDF.</p>
|
||||
<div class="error-details" id="auth-error-details"></div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
.formatted(escapedBaseUrlHtml, serverUrl);
|
||||
}
|
||||
}
|
||||
|
||||
+40
-2
@@ -80,7 +80,7 @@ import stirling.software.common.util.RegexPatternUtils;
|
||||
* <pre>{@code
|
||||
* // In controllers/services - use ExceptionUtils to create typed exceptions:
|
||||
* try {
|
||||
* PDDocument doc = PDDocument.load(file);
|
||||
* PDDocument doc = Loader.loadPDF(file);
|
||||
* } catch (IOException e) {
|
||||
* throw ExceptionUtils.createPdfCorruptedException("during load", e);
|
||||
* }
|
||||
@@ -1117,6 +1117,34 @@ public class GlobalExceptionHandler {
|
||||
return handleBaseApp((BaseAppException) processedException, request);
|
||||
}
|
||||
|
||||
// Check if this is a NoSuchFileException (temp file was deleted prematurely)
|
||||
if (ex instanceof java.nio.file.NoSuchFileException) {
|
||||
log.error(
|
||||
"Temporary file not found at {}: {}",
|
||||
request.getRequestURI(),
|
||||
ex.getMessage(),
|
||||
ex);
|
||||
|
||||
String message =
|
||||
getLocalizedMessage(
|
||||
"error.tempFileNotFound.detail",
|
||||
"The temporary file was not found. This may indicate a processing error or cleanup issue. Please try again.");
|
||||
String title =
|
||||
getLocalizedMessage("error.tempFileNotFound.title", "Temporary File Not Found");
|
||||
|
||||
ProblemDetail problemDetail =
|
||||
createBaseProblemDetail(HttpStatus.INTERNAL_SERVER_ERROR, message, request);
|
||||
problemDetail.setType(URI.create("https://stirlingpdf.com/errors/temp-file-not-found"));
|
||||
problemDetail.setTitle(title);
|
||||
problemDetail.setProperty("title", title);
|
||||
problemDetail.setProperty("errorCode", "E999");
|
||||
problemDetail.setProperty(
|
||||
"hint.1",
|
||||
"This error usually occurs when temporary files are cleaned up before processing completes.");
|
||||
problemDetail.setProperty("hint.2", "Try submitting your request again.");
|
||||
return new ResponseEntity<>(problemDetail, HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
log.error("IO error at {}: {}", request.getRequestURI(), ex.getMessage(), ex);
|
||||
|
||||
String message =
|
||||
@@ -1161,9 +1189,19 @@ public class GlobalExceptionHandler {
|
||||
*/
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ProblemDetail> handleGenericException(
|
||||
Exception ex, HttpServletRequest request) {
|
||||
Exception ex, HttpServletRequest request, HttpServletResponse response) {
|
||||
log.error("Unexpected error at {}: {}", request.getRequestURI(), ex.getMessage(), ex);
|
||||
|
||||
// If response is already committed (e.g., during streaming), we can't send an error
|
||||
// response
|
||||
// Log the error and return null to let Spring handle it gracefully
|
||||
if (response.isCommitted()) {
|
||||
log.warn(
|
||||
"Cannot send error response because response is already committed for URI: {}",
|
||||
request.getRequestURI());
|
||||
return null; // Spring will handle gracefully
|
||||
}
|
||||
|
||||
String userMessage =
|
||||
getLocalizedMessage(
|
||||
"error.unexpected",
|
||||
|
||||
@@ -204,11 +204,65 @@ public class VeraPDFService {
|
||||
detectedFlavours = detectionParser.getFlavours();
|
||||
}
|
||||
|
||||
// For PDF/A flavours, we need to validate first to check if PDF/A identification exists in
|
||||
// XMP
|
||||
// If declaredFlavour is PDF/A, do a quick validation to check for PDF/A identification
|
||||
// schema
|
||||
boolean hasValidPdfaMetadata = false;
|
||||
if (isPdfaFlavour(declaredFlavour)) {
|
||||
try (PDFAParser quickParser =
|
||||
Foundries.defaultInstance()
|
||||
.createParser(new ByteArrayInputStream(pdfBytes), declaredFlavour)) {
|
||||
PDFAValidator quickValidator =
|
||||
Foundries.defaultInstance().createValidator(declaredFlavour, false);
|
||||
ValidationResult quickResult = quickValidator.validate(quickParser);
|
||||
|
||||
// Check if the document has the PDF/A Identification extension schema (clause
|
||||
// 6.7.11, test 1)
|
||||
// OR if it lacks XMP metadata entirely (clause 6.7.2, test 1)
|
||||
// If either of these errors is present, the document is NOT a declared PDF/A
|
||||
hasValidPdfaMetadata = true;
|
||||
for (TestAssertion assertion : quickResult.getTestAssertions()) {
|
||||
if (assertion.getStatus() == TestAssertion.Status.FAILED
|
||||
&& assertion.getRuleId() != null) {
|
||||
String clause = assertion.getRuleId().getClause();
|
||||
int testNumber = assertion.getRuleId().getTestNumber();
|
||||
|
||||
// Missing XMP metadata entirely (clause 6.7.2, test 1)
|
||||
if ("6.7.2".equals(clause) && testNumber == 1) {
|
||||
hasValidPdfaMetadata = false;
|
||||
log.debug(
|
||||
"Document lacks XMP metadata (6.7.2): {}",
|
||||
assertion.getMessage());
|
||||
break;
|
||||
}
|
||||
|
||||
// Missing PDF/A identification schema in XMP (clause 6.7.11, test 1)
|
||||
if ("6.7.11".equals(clause) && testNumber == 1) {
|
||||
hasValidPdfaMetadata = false;
|
||||
log.debug(
|
||||
"Document lacks PDF/A identification in XMP (6.7.11): {}",
|
||||
assertion.getMessage());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.debug("Error checking for PDF/A identification: {}", e.getMessage());
|
||||
hasValidPdfaMetadata = false;
|
||||
}
|
||||
}
|
||||
|
||||
List<PDFAFlavour> flavoursToValidate = new ArrayList<>();
|
||||
boolean hasPdfaDeclaration = isPdfaFlavour(declaredFlavour);
|
||||
boolean hasPdfaDeclaration = isPdfaFlavour(declaredFlavour) && hasValidPdfaMetadata;
|
||||
|
||||
if (declaredFlavour != null) {
|
||||
flavoursToValidate.add(declaredFlavour);
|
||||
boolean isDeclaredPdfa = isPdfaFlavour(declaredFlavour);
|
||||
if (isDeclaredPdfa && hasPdfaDeclaration) {
|
||||
flavoursToValidate.add(declaredFlavour);
|
||||
} else if (!isDeclaredPdfa) {
|
||||
flavoursToValidate.add(declaredFlavour);
|
||||
}
|
||||
}
|
||||
|
||||
for (PDFAFlavour flavour : detectedFlavours) {
|
||||
|
||||
+3
@@ -220,6 +220,9 @@ public class Type3FontLibrary {
|
||||
}
|
||||
|
||||
private byte[] loadResourceBytes(String location) throws IOException {
|
||||
if (location == null || location.isBlank()) {
|
||||
throw new IOException("Resource location is null or blank");
|
||||
}
|
||||
String resolved = resolveLocation(location);
|
||||
Resource resource = resourceLoader.getResource(resolved);
|
||||
if (!resource.exists()) {
|
||||
|
||||
@@ -146,6 +146,11 @@ system:
|
||||
backendUrl: '' # Backend base URL for SAML/OAuth/API callbacks (e.g. 'http://localhost:8080' for dev, 'https://api.example.com' for production). REQUIRED for SSO authentication to work correctly. This is where your IdP will send SAML responses and OAuth callbacks. Leave empty to default to 'http://localhost:8080' in development.
|
||||
frontendUrl: '' # Frontend URL for invite email links (e.g. 'https://app.example.com'). Optional - if not set, will use backendUrl. This is the URL users click in invite emails.
|
||||
enableMobileScanner: false # Enable mobile phone QR code upload feature. Requires frontendUrl to be configured.
|
||||
mobileScannerSettings:
|
||||
convertToPdf: true # Automatically convert uploaded images to PDF format. If false, images are kept as-is.
|
||||
imageResolution: full # Image resolution for mobile uploads: 'full' (original size) or 'reduced' (max 1200px on longest side). Only applies when convertToPdf is true.
|
||||
pageFormat: A4 # Page format for converted PDFs: 'keep' (original image dimensions), 'A4' (A4 page size), or 'letter' (US Letter page size). Only applies when convertToPdf is true.
|
||||
stretchToFit: false # Whether to stretch images to fill the entire page (may distort aspect ratio). If false, images are centered with preserved aspect ratio. Only applies when convertToPdf is true.
|
||||
serverCertificate:
|
||||
enabled: true # Enable server-side certificate for "Sign with Stirling-PDF" option
|
||||
organizationName: Stirling-PDF # Organization name for generated certificates
|
||||
|
||||
@@ -55,7 +55,7 @@ public class SPDFApplicationTest {
|
||||
|
||||
sPDFApplication.init();
|
||||
|
||||
assertEquals("http://localhost", SPDFApplication.getStaticBaseUrl());
|
||||
assertEquals("http://localhost:8080", SPDFApplication.getStaticBaseUrl());
|
||||
assertEquals("/app", SPDFApplication.getStaticContextPath());
|
||||
assertEquals("8080", SPDFApplication.getStaticPort());
|
||||
}
|
||||
|
||||
+5
-1
@@ -169,7 +169,10 @@ public class ProprietaryUIDataController {
|
||||
|
||||
OAUTH2 oauth = securityProps.getOauth2();
|
||||
|
||||
if (oauth != null && oauth.getEnabled()) {
|
||||
// Only add OAuth2 providers if loginMethod allows it
|
||||
if (oauth != null
|
||||
&& oauth.getEnabled()
|
||||
&& securityProps.isOauth2Active()) { // This checks loginMethod
|
||||
if (oauth.isSettingsValid()) {
|
||||
String firstChar = String.valueOf(oauth.getProvider().charAt(0));
|
||||
String clientName =
|
||||
@@ -201,6 +204,7 @@ public class ProprietaryUIDataController {
|
||||
}
|
||||
|
||||
SAML2 saml2 = securityProps.getSaml2();
|
||||
// Only add SAML2 providers if loginMethod allows it
|
||||
if (securityProps.isSaml2Active() && applicationProperties.getPremium().isEnabled()) {
|
||||
String samlIdp = saml2.getProvider();
|
||||
String saml2AuthenticationPath = "/saml2/authenticate/" + saml2.getRegistrationId();
|
||||
|
||||
+14
@@ -18,6 +18,7 @@ import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
|
||||
import org.springframework.security.saml2.provider.service.authentication.OpenSaml4AuthenticationProvider;
|
||||
import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository;
|
||||
import org.springframework.security.saml2.provider.service.web.authentication.OpenSaml4AuthenticationRequestResolver;
|
||||
@@ -46,6 +47,7 @@ import stirling.software.proprietary.security.filter.JwtAuthenticationFilter;
|
||||
import stirling.software.proprietary.security.filter.UserAuthenticationFilter;
|
||||
import stirling.software.proprietary.security.oauth2.CustomOAuth2AuthenticationFailureHandler;
|
||||
import stirling.software.proprietary.security.oauth2.CustomOAuth2AuthenticationSuccessHandler;
|
||||
import stirling.software.proprietary.security.oauth2.TauriAuthorizationRequestResolver;
|
||||
import stirling.software.proprietary.security.saml2.CustomSaml2AuthenticationFailureHandler;
|
||||
import stirling.software.proprietary.security.saml2.CustomSaml2AuthenticationSuccessHandler;
|
||||
import stirling.software.proprietary.security.saml2.CustomSaml2ResponseAuthenticationConverter;
|
||||
@@ -82,6 +84,7 @@ public class SecurityConfiguration {
|
||||
private final OpenSaml4AuthenticationRequestResolver saml2AuthenticationRequestResolver;
|
||||
private final stirling.software.proprietary.service.UserLicenseSettingsService
|
||||
licenseSettingsService;
|
||||
private final ClientRegistrationRepository clientRegistrationRepository;
|
||||
|
||||
public SecurityConfiguration(
|
||||
PersistentLoginRepository persistentLoginRepository,
|
||||
@@ -102,6 +105,7 @@ public class SecurityConfiguration {
|
||||
RelyingPartyRegistrationRepository saml2RelyingPartyRegistrations,
|
||||
@Autowired(required = false)
|
||||
OpenSaml4AuthenticationRequestResolver saml2AuthenticationRequestResolver,
|
||||
@Autowired(required = false) ClientRegistrationRepository clientRegistrationRepository,
|
||||
stirling.software.proprietary.service.UserLicenseSettingsService
|
||||
licenseSettingsService) {
|
||||
this.userDetailsService = userDetailsService;
|
||||
@@ -120,6 +124,7 @@ public class SecurityConfiguration {
|
||||
this.oAuth2userAuthoritiesMapper = oAuth2userAuthoritiesMapper;
|
||||
this.saml2RelyingPartyRegistrations = saml2RelyingPartyRegistrations;
|
||||
this.saml2AuthenticationRequestResolver = saml2AuthenticationRequestResolver;
|
||||
this.clientRegistrationRepository = clientRegistrationRepository;
|
||||
this.licenseSettingsService = licenseSettingsService;
|
||||
}
|
||||
|
||||
@@ -290,6 +295,15 @@ public class SecurityConfiguration {
|
||||
http.oauth2Login(
|
||||
oauth2 -> {
|
||||
oauth2.loginPage("/login")
|
||||
.authorizationEndpoint(
|
||||
authorizationEndpoint -> {
|
||||
if (clientRegistrationRepository != null) {
|
||||
authorizationEndpoint
|
||||
.authorizationRequestResolver(
|
||||
new TauriAuthorizationRequestResolver(
|
||||
clientRegistrationRepository));
|
||||
}
|
||||
})
|
||||
.successHandler(
|
||||
new CustomOAuth2AuthenticationSuccessHandler(
|
||||
loginAttemptService,
|
||||
|
||||
+13
@@ -21,6 +21,7 @@ import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.proprietary.audit.AuditEventType;
|
||||
import stirling.software.proprietary.audit.AuditLevel;
|
||||
import stirling.software.proprietary.audit.Audited;
|
||||
@@ -44,6 +45,7 @@ public class AuthController {
|
||||
private final JwtServiceInterface jwtService;
|
||||
private final CustomUserDetailsService userDetailsService;
|
||||
private final LoginAttemptService loginAttemptService;
|
||||
private final ApplicationProperties.Security securityProperties;
|
||||
|
||||
/**
|
||||
* Login endpoint - replaces Supabase signInWithPassword
|
||||
@@ -60,6 +62,17 @@ public class AuthController {
|
||||
HttpServletRequest httpRequest,
|
||||
HttpServletResponse response) {
|
||||
try {
|
||||
// Check if username/password authentication is allowed
|
||||
if (!securityProperties.isUserPass()) {
|
||||
log.warn(
|
||||
"Username/password login attempted but not allowed by current login method configuration");
|
||||
return ResponseEntity.status(HttpStatus.FORBIDDEN)
|
||||
.body(
|
||||
Map.of(
|
||||
"error",
|
||||
"Username/password authentication is not enabled. Please use the configured authentication method."));
|
||||
}
|
||||
|
||||
// Validate input parameters
|
||||
if (request.getUsername() == null || request.getUsername().trim().isEmpty()) {
|
||||
log.warn("Login attempt with null or empty username");
|
||||
|
||||
+62
-1
@@ -1,7 +1,11 @@
|
||||
package stirling.software.proprietary.security.oauth2;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.ResponseCookie;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.security.authentication.DisabledException;
|
||||
import org.springframework.security.authentication.LockedException;
|
||||
@@ -60,9 +64,66 @@ public class CustomOAuth2AuthenticationFailureHandler
|
||||
"OAuth2 Authentication error: {}",
|
||||
errorCode != null ? errorCode : exception.getMessage(),
|
||||
exception);
|
||||
getRedirectStrategy().sendRedirect(request, response, "/login?errorOAuth=" + errorCode);
|
||||
String errorValue = errorCode != null ? errorCode : "oauth2AuthenticationError";
|
||||
clearRedirectCookie(response);
|
||||
boolean tauriState = TauriOAuthUtils.isTauriState(request);
|
||||
String redirectUrl;
|
||||
if (tauriState) {
|
||||
String basePath =
|
||||
TauriOAuthUtils.defaultTauriCallbackPath(request.getContextPath());
|
||||
redirectUrl = basePath;
|
||||
String stateParam = request.getParameter("state");
|
||||
if (stateParam != null && !stateParam.isBlank()) {
|
||||
redirectUrl = appendQueryParam(redirectUrl, "state", stateParam);
|
||||
// Extract and pass nonce for CSRF validation
|
||||
String nonce = TauriOAuthUtils.extractNonceFromState(stateParam);
|
||||
if (nonce != null) {
|
||||
redirectUrl = appendQueryParam(redirectUrl, "nonce", nonce);
|
||||
}
|
||||
}
|
||||
redirectUrl = appendQueryParam(redirectUrl, "errorOAuth", errorValue);
|
||||
} else {
|
||||
redirectUrl = buildFailureRedirectUrl(request, errorValue);
|
||||
}
|
||||
getRedirectStrategy().sendRedirect(request, response, redirectUrl);
|
||||
return;
|
||||
}
|
||||
log.error("Unhandled authentication exception", exception);
|
||||
super.onAuthenticationFailure(request, response, exception);
|
||||
}
|
||||
|
||||
private String buildFailureRedirectUrl(HttpServletRequest request, String errorValue) {
|
||||
String contextPath = request.getContextPath();
|
||||
String cookiePath = TauriOAuthUtils.extractRedirectPathFromCookie(request);
|
||||
String redirectPath =
|
||||
cookiePath != null ? cookiePath : TauriOAuthUtils.defaultCallbackPath(contextPath);
|
||||
if (TauriOAuthUtils.isTauriState(request)) {
|
||||
redirectPath = appendQueryParam(redirectPath, "tauri", "1");
|
||||
}
|
||||
String resolvedPath =
|
||||
redirectPath.startsWith("/")
|
||||
? TauriOAuthUtils.normalizeContextPath(contextPath) + redirectPath
|
||||
: TauriOAuthUtils.normalizeContextPath(contextPath) + "/" + redirectPath;
|
||||
return appendQueryParam(resolvedPath, "errorOAuth", errorValue);
|
||||
}
|
||||
|
||||
private void clearRedirectCookie(HttpServletResponse response) {
|
||||
ResponseCookie cookie =
|
||||
ResponseCookie.from(TauriOAuthUtils.SPA_REDIRECT_COOKIE, "")
|
||||
.path("/")
|
||||
.sameSite("Lax")
|
||||
.maxAge(0)
|
||||
.build();
|
||||
response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());
|
||||
}
|
||||
|
||||
private String appendQueryParam(String path, String key, String value) {
|
||||
if (path == null || path.isBlank()) {
|
||||
return path;
|
||||
}
|
||||
String separator = path.contains("?") ? "&" : "?";
|
||||
String encodedKey = URLEncoder.encode(key, StandardCharsets.UTF_8);
|
||||
String encodedValue = value == null ? "" : URLEncoder.encode(value, StandardCharsets.UTF_8);
|
||||
return path + separator + encodedKey + "=" + encodedValue;
|
||||
}
|
||||
}
|
||||
|
||||
+18
-35
@@ -4,8 +4,6 @@ import static stirling.software.proprietary.security.model.AuthenticationType.OA
|
||||
import static stirling.software.proprietary.security.model.AuthenticationType.SSO;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -21,7 +19,6 @@ import org.springframework.security.web.authentication.SavedRequestAwareAuthenti
|
||||
import org.springframework.security.web.savedrequest.SavedRequest;
|
||||
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import jakarta.servlet.http.HttpSession;
|
||||
@@ -45,9 +42,6 @@ import stirling.software.proprietary.security.service.UserService;
|
||||
public class CustomOAuth2AuthenticationSuccessHandler
|
||||
extends SavedRequestAwareAuthenticationSuccessHandler {
|
||||
|
||||
private static final String SPA_REDIRECT_COOKIE = "stirling_redirect_path";
|
||||
private static final String DEFAULT_CALLBACK_PATH = "/auth/callback";
|
||||
|
||||
private final LoginAttemptService loginAttemptService;
|
||||
private final ApplicationProperties.Security.OAUTH2 oauth2Properties;
|
||||
private final UserService userService;
|
||||
@@ -210,39 +204,28 @@ public class CustomOAuth2AuthenticationSuccessHandler
|
||||
resolveOriginFromReferer(request)
|
||||
.orElseGet(() -> buildOriginFromRequest(request)));
|
||||
clearRedirectCookie(response);
|
||||
return origin + redirectPath + "#access_token=" + jwt;
|
||||
|
||||
// Extract nonce from state for CSRF validation in callback
|
||||
String nonce = TauriOAuthUtils.extractNonceFromRequest(request);
|
||||
String url = origin + redirectPath + "#access_token=" + jwt;
|
||||
if (nonce != null) {
|
||||
url +=
|
||||
"&nonce="
|
||||
+ java.net.URLEncoder.encode(
|
||||
nonce, java.nio.charset.StandardCharsets.UTF_8);
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
private String resolveRedirectPath(HttpServletRequest request, String contextPath) {
|
||||
return extractRedirectPathFromCookie(request)
|
||||
.filter(path -> path.startsWith("/"))
|
||||
.orElseGet(() -> defaultCallbackPath(contextPath));
|
||||
}
|
||||
|
||||
private Optional<String> extractRedirectPathFromCookie(HttpServletRequest request) {
|
||||
Cookie[] cookies = request.getCookies();
|
||||
if (cookies == null) {
|
||||
return Optional.empty();
|
||||
if (TauriOAuthUtils.isTauriState(request)) {
|
||||
return TauriOAuthUtils.defaultTauriCallbackPath(contextPath);
|
||||
}
|
||||
for (Cookie cookie : cookies) {
|
||||
if (SPA_REDIRECT_COOKIE.equals(cookie.getName())) {
|
||||
String value = URLDecoder.decode(cookie.getValue(), StandardCharsets.UTF_8).trim();
|
||||
if (!value.isEmpty()) {
|
||||
return Optional.of(value);
|
||||
}
|
||||
}
|
||||
String cookiePath = TauriOAuthUtils.extractRedirectPathFromCookie(request);
|
||||
if (cookiePath != null && cookiePath.startsWith("/")) {
|
||||
return cookiePath;
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private String defaultCallbackPath(String contextPath) {
|
||||
if (contextPath == null
|
||||
|| contextPath.isBlank()
|
||||
|| "/".equals(contextPath)
|
||||
|| "\\".equals(contextPath)) {
|
||||
return DEFAULT_CALLBACK_PATH;
|
||||
}
|
||||
return contextPath + DEFAULT_CALLBACK_PATH;
|
||||
return TauriOAuthUtils.defaultCallbackPath(contextPath);
|
||||
}
|
||||
|
||||
private Optional<String> resolveForwardedOrigin(HttpServletRequest request) {
|
||||
@@ -326,7 +309,7 @@ public class CustomOAuth2AuthenticationSuccessHandler
|
||||
|
||||
private void clearRedirectCookie(HttpServletResponse response) {
|
||||
ResponseCookie cookie =
|
||||
ResponseCookie.from(SPA_REDIRECT_COOKIE, "")
|
||||
ResponseCookie.from(TauriOAuthUtils.SPA_REDIRECT_COOKIE, "")
|
||||
.path("/")
|
||||
.sameSite("Lax")
|
||||
.maxAge(0)
|
||||
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package stirling.software.proprietary.security.oauth2;
|
||||
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
|
||||
import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizationRequestResolver;
|
||||
import org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestResolver;
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
public class TauriAuthorizationRequestResolver implements OAuth2AuthorizationRequestResolver {
|
||||
|
||||
private static final String TAURI_STATE_PREFIX = "tauri:";
|
||||
|
||||
private final OAuth2AuthorizationRequestResolver delegate;
|
||||
|
||||
public TauriAuthorizationRequestResolver(
|
||||
ClientRegistrationRepository clientRegistrationRepository) {
|
||||
this.delegate =
|
||||
new DefaultOAuth2AuthorizationRequestResolver(
|
||||
clientRegistrationRepository, "/oauth2/authorization");
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuth2AuthorizationRequest resolve(HttpServletRequest request) {
|
||||
return customize(request, delegate.resolve(request));
|
||||
}
|
||||
|
||||
@Override
|
||||
public OAuth2AuthorizationRequest resolve(
|
||||
HttpServletRequest request, String clientRegistrationId) {
|
||||
return customize(request, delegate.resolve(request, clientRegistrationId));
|
||||
}
|
||||
|
||||
private OAuth2AuthorizationRequest customize(
|
||||
HttpServletRequest request, OAuth2AuthorizationRequest authorizationRequest) {
|
||||
if (authorizationRequest == null) {
|
||||
return null;
|
||||
}
|
||||
String tauriParam = request.getParameter("tauri");
|
||||
if (!"1".equals(tauriParam)) {
|
||||
return authorizationRequest;
|
||||
}
|
||||
|
||||
String state = authorizationRequest.getState();
|
||||
if (state == null || state.startsWith(TAURI_STATE_PREFIX)) {
|
||||
return authorizationRequest;
|
||||
}
|
||||
|
||||
// Extract nonce from request for CSRF protection
|
||||
String nonce = request.getParameter("nonce");
|
||||
String customState = TAURI_STATE_PREFIX + state;
|
||||
if (nonce != null && !nonce.isBlank()) {
|
||||
customState = customState + ":" + nonce;
|
||||
}
|
||||
|
||||
return OAuth2AuthorizationRequest.from(authorizationRequest).state(customState).build();
|
||||
}
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
package stirling.software.proprietary.security.oauth2;
|
||||
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* Utility class for Tauri desktop OAuth flow handling. Centralizes common logic for OAuth state
|
||||
* management, nonce validation, and callback path construction.
|
||||
*/
|
||||
public final class TauriOAuthUtils {
|
||||
|
||||
public static final String TAURI_STATE_PREFIX = "tauri:";
|
||||
public static final String SPA_REDIRECT_COOKIE = "stirling_redirect_path";
|
||||
public static final String DEFAULT_CALLBACK_PATH = "/auth/callback";
|
||||
public static final String TAURI_CALLBACK_SUFFIX = "/tauri";
|
||||
|
||||
private TauriOAuthUtils() {
|
||||
// Utility class - prevent instantiation
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts nonce from OAuth state parameter for CSRF validation. State format:
|
||||
* tauri:<original-state>:<nonce>
|
||||
*
|
||||
* @param state The state parameter value
|
||||
* @return The nonce if present, null otherwise
|
||||
*/
|
||||
public static String extractNonceFromState(String state) {
|
||||
if (state == null || !state.startsWith(TAURI_STATE_PREFIX)) {
|
||||
return null;
|
||||
}
|
||||
// Split by ':' and get the last part (nonce)
|
||||
String[] parts = state.split(":");
|
||||
if (parts.length >= 3) {
|
||||
return parts[parts.length - 1];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts nonce from request's state parameter.
|
||||
*
|
||||
* @param request The HTTP request
|
||||
* @return The nonce if present, null otherwise
|
||||
*/
|
||||
public static String extractNonceFromRequest(HttpServletRequest request) {
|
||||
String state = request.getParameter("state");
|
||||
return extractNonceFromState(state);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the request has a Tauri state parameter (desktop OAuth flow).
|
||||
*
|
||||
* @param request The HTTP request
|
||||
* @return true if this is a Tauri desktop OAuth flow, false otherwise
|
||||
*/
|
||||
public static boolean isTauriState(HttpServletRequest request) {
|
||||
String state = request.getParameter("state");
|
||||
return state != null && state.startsWith(TAURI_STATE_PREFIX);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the default callback path for the given context path.
|
||||
*
|
||||
* @param contextPath The application context path
|
||||
* @return The full callback path
|
||||
*/
|
||||
public static String defaultCallbackPath(String contextPath) {
|
||||
if (contextPath == null
|
||||
|| contextPath.isBlank()
|
||||
|| "/".equals(contextPath)
|
||||
|| "\\".equals(contextPath)) {
|
||||
return DEFAULT_CALLBACK_PATH;
|
||||
}
|
||||
return contextPath + DEFAULT_CALLBACK_PATH;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the Tauri-specific callback path (includes /tauri suffix).
|
||||
*
|
||||
* @param contextPath The application context path
|
||||
* @return The full Tauri callback path
|
||||
*/
|
||||
public static String defaultTauriCallbackPath(String contextPath) {
|
||||
return defaultCallbackPath(contextPath) + TAURI_CALLBACK_SUFFIX;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes context path by removing trailing slashes and handling empty/root paths.
|
||||
*
|
||||
* @param contextPath The context path to normalize
|
||||
* @return Normalized context path (empty string for root)
|
||||
*/
|
||||
public static String normalizeContextPath(String contextPath) {
|
||||
if (contextPath == null || contextPath.isBlank() || "/".equals(contextPath)) {
|
||||
return "";
|
||||
}
|
||||
return contextPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the SPA redirect cookie value from the request.
|
||||
*
|
||||
* @param request The HTTP request
|
||||
* @return The redirect path from cookie, or null if not found
|
||||
*/
|
||||
public static String extractRedirectPathFromCookie(HttpServletRequest request) {
|
||||
Cookie[] cookies = request.getCookies();
|
||||
if (cookies == null) {
|
||||
return null;
|
||||
}
|
||||
for (Cookie cookie : cookies) {
|
||||
if (SPA_REDIRECT_COOKIE.equals(cookie.getName())) {
|
||||
String value =
|
||||
java.net.URLDecoder.decode(
|
||||
cookie.getValue(), java.nio.charset.StandardCharsets.UTF_8);
|
||||
return value.trim().isEmpty() ? null : value.trim();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -292,6 +292,7 @@ public class FormUtils {
|
||||
}
|
||||
|
||||
PDFRenderer renderer = new PDFRenderer(document);
|
||||
renderer.setSubsamplingAllowed(true); // Enable subsampling to reduce memory usage
|
||||
ApplicationProperties properties =
|
||||
ApplicationContextProvider.getBean(ApplicationProperties.class);
|
||||
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package stirling.software.proprietary.security.oauth2;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
|
||||
import org.springframework.security.oauth2.core.OAuth2Error;
|
||||
|
||||
class CustomOAuth2AuthenticationFailureHandlerTest {
|
||||
|
||||
@Test
|
||||
void redirectsToTauriCallbackWhenStateMarked() throws Exception {
|
||||
CustomOAuth2AuthenticationFailureHandler handler =
|
||||
new CustomOAuth2AuthenticationFailureHandler();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setContextPath("");
|
||||
request.setParameter("state", "tauri:abc");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
handler.onAuthenticationFailure(
|
||||
request,
|
||||
response,
|
||||
new OAuth2AuthenticationException(new OAuth2Error("access_denied")));
|
||||
|
||||
assertEquals(
|
||||
"/auth/callback/tauri?state=tauri%3Aabc&errorOAuth=access_denied",
|
||||
response.getRedirectedUrl());
|
||||
}
|
||||
|
||||
@Test
|
||||
void redirectsToDefaultCallbackWithoutTauriState() throws Exception {
|
||||
CustomOAuth2AuthenticationFailureHandler handler =
|
||||
new CustomOAuth2AuthenticationFailureHandler();
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setContextPath("");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
handler.onAuthenticationFailure(
|
||||
request,
|
||||
response,
|
||||
new OAuth2AuthenticationException(new OAuth2Error("access_denied")));
|
||||
|
||||
assertEquals("/auth/callback?errorOAuth=access_denied", response.getRedirectedUrl());
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package stirling.software.proprietary.security.oauth2;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
|
||||
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
|
||||
|
||||
import stirling.software.common.model.ApplicationProperties;
|
||||
import stirling.software.proprietary.security.service.JwtServiceInterface;
|
||||
import stirling.software.proprietary.security.service.LoginAttemptService;
|
||||
import stirling.software.proprietary.security.service.UserService;
|
||||
import stirling.software.proprietary.service.UserLicenseSettingsService;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class CustomOAuth2AuthenticationSuccessHandlerTest {
|
||||
|
||||
@Test
|
||||
void redirectsToTauriCallbackWhenStateMarked() throws Exception {
|
||||
LoginAttemptService loginAttemptService = mock(LoginAttemptService.class);
|
||||
UserService userService = mock(UserService.class);
|
||||
JwtServiceInterface jwtService = mock(JwtServiceInterface.class);
|
||||
UserLicenseSettingsService licenseSettingsService = mock(UserLicenseSettingsService.class);
|
||||
|
||||
ApplicationProperties.Security.OAUTH2 oauth2Props =
|
||||
new ApplicationProperties.Security.OAUTH2();
|
||||
oauth2Props.setAutoCreateUser(true);
|
||||
oauth2Props.setBlockRegistration(false);
|
||||
|
||||
CustomOAuth2AuthenticationSuccessHandler handler =
|
||||
new CustomOAuth2AuthenticationSuccessHandler(
|
||||
loginAttemptService,
|
||||
oauth2Props,
|
||||
userService,
|
||||
jwtService,
|
||||
licenseSettingsService);
|
||||
|
||||
when(userService.usernameExistsIgnoreCase("user")).thenReturn(false);
|
||||
when(licenseSettingsService.isOAuthEligible(null)).thenReturn(true);
|
||||
when(userService.isUserDisabled("user")).thenReturn(false);
|
||||
when(jwtService.isJwtEnabled()).thenReturn(true);
|
||||
when(jwtService.generateToken(
|
||||
org.mockito.Mockito.any(
|
||||
org.springframework.security.core.Authentication.class),
|
||||
org.mockito.Mockito.anyMap()))
|
||||
.thenReturn("jwt");
|
||||
|
||||
Map<String, Object> attributes = Map.of("sub", "provider-sub", "name", "user");
|
||||
DefaultOAuth2User oauthUser =
|
||||
new DefaultOAuth2User(
|
||||
List.of(new SimpleGrantedAuthority("ROLE_USER")), attributes, "name");
|
||||
OAuth2AuthenticationToken authentication =
|
||||
new OAuth2AuthenticationToken(oauthUser, oauthUser.getAuthorities(), "google");
|
||||
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setContextPath("");
|
||||
request.setScheme("http");
|
||||
request.setServerName("localhost");
|
||||
request.setServerPort(8080);
|
||||
request.setParameter("state", "tauri:abc");
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
|
||||
handler.onAuthenticationSuccess(request, response, authentication);
|
||||
|
||||
assertEquals(
|
||||
"http://localhost:8080/auth/callback/tauri#access_token=jwt",
|
||||
response.getRedirectedUrl());
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package stirling.software.proprietary.security.oauth2;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.security.oauth2.client.registration.ClientRegistration;
|
||||
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
|
||||
import org.springframework.security.oauth2.core.AuthorizationGrantType;
|
||||
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
|
||||
|
||||
class TauriAuthorizationRequestResolverTest {
|
||||
|
||||
private TauriAuthorizationRequestResolver buildResolver() {
|
||||
ClientRegistration registration =
|
||||
ClientRegistration.withRegistrationId("google")
|
||||
.clientId("client-id")
|
||||
.clientSecret("client-secret")
|
||||
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
|
||||
.authorizationUri("https://accounts.example.com/o/oauth2/auth")
|
||||
.tokenUri("https://accounts.example.com/o/oauth2/token")
|
||||
.redirectUri("http://localhost:8080/login/oauth2/code/google")
|
||||
.userInfoUri("https://accounts.example.com/userinfo")
|
||||
.userNameAttributeName("sub")
|
||||
.clientName("Google")
|
||||
.scope("email")
|
||||
.build();
|
||||
|
||||
return new TauriAuthorizationRequestResolver(
|
||||
new InMemoryClientRegistrationRepository(registration));
|
||||
}
|
||||
|
||||
private MockHttpServletRequest buildRequest(boolean tauri) {
|
||||
MockHttpServletRequest request =
|
||||
new MockHttpServletRequest("GET", "/oauth2/authorization/google");
|
||||
request.setServletPath("/oauth2/authorization/google");
|
||||
if (tauri) {
|
||||
request.setParameter("tauri", "1");
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolve_prefixesStateWhenTauriParamPresent() {
|
||||
TauriAuthorizationRequestResolver resolver = buildResolver();
|
||||
OAuth2AuthorizationRequest authRequest = resolver.resolve(buildRequest(true));
|
||||
assertNotNull(authRequest);
|
||||
assertNotNull(authRequest.getState());
|
||||
assertTrue(authRequest.getState().startsWith("tauri:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolve_doesNotPrefixStateWithoutTauriParam() {
|
||||
TauriAuthorizationRequestResolver resolver = buildResolver();
|
||||
OAuth2AuthorizationRequest authRequest = resolver.resolve(buildRequest(false));
|
||||
assertNotNull(authRequest);
|
||||
assertNotNull(authRequest.getState());
|
||||
assertFalse(authRequest.getState().startsWith("tauri:"));
|
||||
}
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
package stirling.software.proprietary.security.oauth2;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
|
||||
class TauriOAuthUtilsTest {
|
||||
|
||||
@Test
|
||||
void extractNonceFromState_validState() {
|
||||
String state = "tauri:original-state-12345:test-nonce-uuid";
|
||||
String nonce = TauriOAuthUtils.extractNonceFromState(state);
|
||||
assertEquals("test-nonce-uuid", nonce);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractNonceFromState_stateWithColonInNonce() {
|
||||
String state = "tauri:original:complex:nonce-with-colon";
|
||||
String nonce = TauriOAuthUtils.extractNonceFromState(state);
|
||||
assertEquals("nonce-with-colon", nonce);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractNonceFromState_noNonce() {
|
||||
String state = "tauri:original-state";
|
||||
String nonce = TauriOAuthUtils.extractNonceFromState(state);
|
||||
assertNull(nonce);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractNonceFromState_notTauriState() {
|
||||
String state = "regular-state:with-colons";
|
||||
String nonce = TauriOAuthUtils.extractNonceFromState(state);
|
||||
assertNull(nonce);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractNonceFromState_nullState() {
|
||||
String nonce = TauriOAuthUtils.extractNonceFromState(null);
|
||||
assertNull(nonce);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractNonceFromRequest_validRequest() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setParameter("state", "tauri:abc:nonce-123");
|
||||
|
||||
String nonce = TauriOAuthUtils.extractNonceFromRequest(request);
|
||||
assertEquals("nonce-123", nonce);
|
||||
}
|
||||
|
||||
@Test
|
||||
void isTauriState_validTauriState() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setParameter("state", "tauri:original-state");
|
||||
|
||||
assertTrue(TauriOAuthUtils.isTauriState(request));
|
||||
}
|
||||
|
||||
@Test
|
||||
void isTauriState_notTauriState() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setParameter("state", "regular-state");
|
||||
|
||||
assertFalse(TauriOAuthUtils.isTauriState(request));
|
||||
}
|
||||
|
||||
@Test
|
||||
void isTauriState_noState() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
|
||||
assertFalse(TauriOAuthUtils.isTauriState(request));
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultCallbackPath_rootContext() {
|
||||
assertEquals("/auth/callback", TauriOAuthUtils.defaultCallbackPath("/"));
|
||||
assertEquals("/auth/callback", TauriOAuthUtils.defaultCallbackPath(""));
|
||||
assertEquals("/auth/callback", TauriOAuthUtils.defaultCallbackPath(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultCallbackPath_withContext() {
|
||||
assertEquals("/myapp/auth/callback", TauriOAuthUtils.defaultCallbackPath("/myapp"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultTauriCallbackPath_rootContext() {
|
||||
assertEquals("/auth/callback/tauri", TauriOAuthUtils.defaultTauriCallbackPath("/"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultTauriCallbackPath_withContext() {
|
||||
assertEquals(
|
||||
"/myapp/auth/callback/tauri", TauriOAuthUtils.defaultTauriCallbackPath("/myapp"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void normalizeContextPath_rootPaths() {
|
||||
assertEquals("", TauriOAuthUtils.normalizeContextPath("/"));
|
||||
assertEquals("", TauriOAuthUtils.normalizeContextPath(""));
|
||||
assertEquals("", TauriOAuthUtils.normalizeContextPath(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void normalizeContextPath_withPath() {
|
||||
assertEquals("/myapp", TauriOAuthUtils.normalizeContextPath("/myapp"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractRedirectPathFromCookie_noCookies() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
assertNull(TauriOAuthUtils.extractRedirectPathFromCookie(request));
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractRedirectPathFromCookie_withCookie() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setCookies(
|
||||
new jakarta.servlet.http.Cookie(
|
||||
TauriOAuthUtils.SPA_REDIRECT_COOKIE, "/auth/callback"));
|
||||
|
||||
assertEquals("/auth/callback", TauriOAuthUtils.extractRedirectPathFromCookie(request));
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractRedirectPathFromCookie_emptyCookie() {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setCookies(
|
||||
new jakarta.servlet.http.Cookie(TauriOAuthUtils.SPA_REDIRECT_COOKIE, ""));
|
||||
|
||||
assertNull(TauriOAuthUtils.extractRedirectPathFromCookie(request));
|
||||
}
|
||||
}
|
||||
+123
-9
@@ -14,6 +14,8 @@ plugins {
|
||||
import com.github.jk1.license.render.*
|
||||
import groovy.json.JsonOutput
|
||||
import groovy.json.JsonSlurper
|
||||
import groovy.xml.XmlSlurper
|
||||
import org.gradle.api.tasks.testing.Test
|
||||
|
||||
ext {
|
||||
springBootVersion = "3.5.7"
|
||||
@@ -60,7 +62,7 @@ repositories {
|
||||
|
||||
allprojects {
|
||||
group = 'stirling.software'
|
||||
version = '2.2.0'
|
||||
version = '2.2.1'
|
||||
|
||||
configurations.configureEach {
|
||||
exclude group: 'commons-logging', module: 'commons-logging'
|
||||
@@ -183,30 +185,142 @@ subprojects {
|
||||
}
|
||||
}
|
||||
|
||||
compileJava {
|
||||
options.compilerArgs << "-parameters"
|
||||
tasks.named("compileJava", JavaCompile).configure {
|
||||
options.compilerArgs.add("-parameters")
|
||||
}
|
||||
|
||||
test {
|
||||
def jacocoReport = tasks.named("jacocoTestReport")
|
||||
|
||||
tasks.withType(Test).configureEach {
|
||||
useJUnitPlatform()
|
||||
finalizedBy jacocoTestReport
|
||||
finalizedBy(jacocoReport)
|
||||
}
|
||||
|
||||
jacocoTestReport {
|
||||
dependsOn test
|
||||
jacocoReport.configure {
|
||||
dependsOn(tasks.named("test"))
|
||||
reports {
|
||||
xml.required.set(true)
|
||||
csv.required.set(false)
|
||||
html.required.set(true)
|
||||
}
|
||||
doLast {
|
||||
def xmlReport = reports.xml.outputLocation.get().asFile
|
||||
if (!xmlReport.exists()) {
|
||||
logger.lifecycle("Jacoco coverage report not found at ${xmlReport}")
|
||||
return
|
||||
}
|
||||
|
||||
def xmlContent = xmlReport.getText("UTF-8")
|
||||
xmlContent = xmlContent.replaceFirst('(?s)<!DOCTYPE.*?>', '')
|
||||
def report = new XmlSlurper(false, false).parseText(xmlContent)
|
||||
def counters = report.counter.collectEntries { counter ->
|
||||
def type = counter.@type.text()
|
||||
def covered = counter.@covered.text() as BigDecimal
|
||||
def missed = counter.@missed.text() as BigDecimal
|
||||
[(type): [covered: covered, missed: missed]]
|
||||
}
|
||||
|
||||
def thresholds = [
|
||||
LINE : 0.16,
|
||||
INSTRUCTION: 0.14,
|
||||
BRANCH : 0.09
|
||||
]
|
||||
|
||||
def types = ["LINE", "INSTRUCTION", "BRANCH"]
|
||||
def headers = ["Metric", "Coverage", "Covered/Total", "Status", "Target"]
|
||||
|
||||
def rows = types.collect { String type ->
|
||||
def data = counters[type]
|
||||
if (!data) {
|
||||
return [type, "—", "—", "No data", ""]
|
||||
}
|
||||
|
||||
def total = data.covered + data.missed
|
||||
if (total == 0) {
|
||||
return [type, "—", "0/${total.toBigInteger()}", "No executions", ""]
|
||||
}
|
||||
|
||||
def ratio = data.covered / total * 100
|
||||
def coverageText = String.format(Locale.ROOT, "%.2f%%", ratio)
|
||||
def coveredText = String.format(Locale.ROOT, "%d/%d",
|
||||
data.covered.toBigInteger(),
|
||||
total.toBigInteger())
|
||||
|
||||
def threshold = thresholds[type]
|
||||
def thresholdPercent = threshold != null ? threshold * 100 : null
|
||||
def targetText = thresholdPercent != null ?
|
||||
String.format(Locale.ROOT, ">= %.2f%%", thresholdPercent) : ""
|
||||
def passed = thresholdPercent != null ? ratio >= thresholdPercent : null
|
||||
def statusText = passed == null ? "" : (passed ? "PASS" : "FAIL")
|
||||
|
||||
return [type, coverageText, coveredText, statusText, targetText]
|
||||
}
|
||||
|
||||
def columnIndexes = (0..<headers.size())
|
||||
def columnWidths = columnIndexes.collect { idx ->
|
||||
Math.max(headers[idx].length(), rows.collect { row ->
|
||||
row[idx] != null ? row[idx].toString().length() : 0
|
||||
}.max() ?: 0)
|
||||
}
|
||||
|
||||
def formatRow = { List<String> values ->
|
||||
columnIndexes.collect { idx ->
|
||||
def value = values[idx] ?: ""
|
||||
value.padRight(columnWidths[idx])
|
||||
}.join(" | ")
|
||||
}
|
||||
|
||||
def separator = columnIndexes.collect { idx ->
|
||||
''.padRight(columnWidths[idx], '-')
|
||||
}.join("-+-")
|
||||
|
||||
logger.lifecycle("")
|
||||
logger.lifecycle("==== JaCoCo Coverage Summary ====")
|
||||
logger.lifecycle(formatRow(headers))
|
||||
logger.lifecycle(separator)
|
||||
rows.each { row ->
|
||||
logger.lifecycle(formatRow(row))
|
||||
}
|
||||
logger.lifecycle(separator)
|
||||
|
||||
def htmlReport = reports.html.outputLocation.get().asFile
|
||||
logger.lifecycle("Detailed HTML report available at: ${htmlReport}")
|
||||
if (rows.any { it[3] == "FAIL" }) {
|
||||
logger.lifecycle("Some coverage targets were missed. Please review the detailed report above.")
|
||||
} else if (rows.any { it[3] == "PASS" }) {
|
||||
logger.lifecycle("Great job! All tracked coverage metrics meet their targets.")
|
||||
}
|
||||
logger.lifecycle("=================================\n")
|
||||
}
|
||||
}
|
||||
|
||||
tasks.named("build") {
|
||||
dependsOn jacocoReport
|
||||
}
|
||||
|
||||
jacocoTestCoverageVerification {
|
||||
dependsOn jacocoTestReport
|
||||
dependsOn jacocoReport
|
||||
violationRules {
|
||||
rule {
|
||||
enabled = true
|
||||
element = 'BUNDLE'
|
||||
// Bytecode-Anweisungen abgedeckt
|
||||
limit {
|
||||
minimum = 0.0
|
||||
counter = 'INSTRUCTION'
|
||||
value = 'COVEREDRATIO'
|
||||
minimum = 0.14
|
||||
}
|
||||
// wie viele Quellcode-Zeilen abgedeckt
|
||||
limit {
|
||||
counter = 'LINE'
|
||||
value = 'COVEREDRATIO'
|
||||
minimum = 0.16
|
||||
}
|
||||
// Verzweigungen (if/else, switch) abgedeckt; misst Logik-Abdeckung
|
||||
limit {
|
||||
counter = 'BRANCH'
|
||||
value = 'COVEREDRATIO'
|
||||
minimum = 0.09
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# Supports MODE parameter: BOTH (default), FRONTEND, BACKEND
|
||||
|
||||
# Stage 1: Build Frontend
|
||||
FROM node:20-alpine AS frontend-build
|
||||
FROM node:20-alpine@sha256:658d0f63e501824d6c23e06d4bb95c71e7d704537c9d9272f488ac03a370d448 AS frontend-build
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
@@ -15,7 +15,7 @@ COPY frontend .
|
||||
RUN DISABLE_ADDITIONAL_FEATURES=false VITE_API_BASE_URL=/ npm run build
|
||||
|
||||
# Stage 2: Build Backend (server-only JAR - no UI)
|
||||
FROM gradle:8.14-jdk21 AS backend-build
|
||||
FROM gradle:8.14-jdk21@sha256:051d9a116793bdc5175a3f97a545718b750489eee85a7da20913c8a53f722a72 AS backend-build
|
||||
|
||||
COPY build.gradle .
|
||||
COPY settings.gradle .
|
||||
@@ -35,7 +35,7 @@ RUN DISABLE_ADDITIONAL_FEATURES=false \
|
||||
./gradlew clean build -x spotlessApply -x spotlessCheck -x test -x sonarqube
|
||||
|
||||
# Stage 3: Final unified image
|
||||
FROM alpine:3.22.1
|
||||
FROM alpine:3.22.1@sha256:4bcff63911fcb4448bd4fdacec207030997caf25e9bea4045fa6c8c44de311d1
|
||||
|
||||
ARG VERSION_TAG
|
||||
|
||||
@@ -66,7 +66,7 @@ COPY docker/unified/entrypoint.sh /entrypoint.sh
|
||||
|
||||
# Environment Variables
|
||||
ENV VERSION_TAG=$VERSION_TAG \
|
||||
JAVA_BASE_OPTS="-XX:+UnlockExperimentalVMOptions -XX:MaxRAMPercentage=75 -XX:InitiatingHeapOccupancyPercent=20 -XX:+G1PeriodicGCInvokesConcurrent -XX:G1PeriodicGCInterval=10000 -XX:+UseStringDeduplication -XX:G1PeriodicGCSystemLoadThreshold=70" \
|
||||
JAVA_BASE_OPTS="-XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/configs/heap_dumps -XX:+UnlockExperimentalVMOptions -XX:MaxRAMPercentage=75 -XX:InitiatingHeapOccupancyPercent=20 -XX:+G1PeriodicGCInvokesConcurrent -XX:G1PeriodicGCInterval=10000 -XX:+UseStringDeduplication -XX:G1PeriodicGCSystemLoadThreshold=70" \
|
||||
JAVA_CUSTOM_OPTS="" \
|
||||
HOME=/home/stirlingpdfuser \
|
||||
PUID=1000 \
|
||||
@@ -129,7 +129,7 @@ RUN echo "@main https://dl-cdn.alpinelinux.org/alpine/edge/main" | tee -a /etc/a
|
||||
ln -s /usr/lib/libreoffice/program/unohelper.py /opt/venv/lib/python3.12/site-packages/ && \
|
||||
ln -s /usr/lib/libreoffice/program /opt/venv/lib/python3.12/site-packages/LibreOffice && \
|
||||
mv /usr/share/tessdata /usr/share/tessdata-original && \
|
||||
mkdir -p $HOME /configs /logs /customFiles /pipeline/watchedFolders /pipeline/finishedFolders /tmp/stirling-pdf /pipeline/watchedFolders /pipeline/finishedFolders && \
|
||||
mkdir -p $HOME /configs /configs/heap_dumps /logs /customFiles /pipeline/watchedFolders /pipeline/finishedFolders /tmp/stirling-pdf /pipeline/watchedFolders /pipeline/finishedFolders && \
|
||||
mkdir -p /var/lib/nginx/tmp /var/log/nginx && \
|
||||
fc-cache -f -v && \
|
||||
chmod +x /scripts/* && \
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# Supports MODE parameter: BOTH (default), FRONTEND, BACKEND
|
||||
|
||||
# Stage 1: Build Frontend
|
||||
FROM node:20-alpine AS frontend-build
|
||||
FROM node:20-alpine@sha256:658d0f63e501824d6c23e06d4bb95c71e7d704537c9d9272f488ac03a370d448 AS frontend-build
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
@@ -15,7 +15,7 @@ COPY frontend .
|
||||
RUN DISABLE_ADDITIONAL_FEATURES=true VITE_API_BASE_URL=/ npm run build
|
||||
|
||||
# Stage 2: Build Backend
|
||||
FROM gradle:8.14-jdk21 AS backend-build
|
||||
FROM gradle:8.14-jdk21@sha256:051d9a116793bdc5175a3f97a545718b750489eee85a7da20913c8a53f722a72 AS backend-build
|
||||
|
||||
COPY build.gradle .
|
||||
COPY settings.gradle .
|
||||
@@ -34,7 +34,7 @@ RUN DISABLE_ADDITIONAL_FEATURES=true \
|
||||
./gradlew clean build -x spotlessApply -x spotlessCheck -x test -x sonarqube
|
||||
|
||||
# Stage 3: Final unified ultra-lite image
|
||||
FROM alpine:3.22.1
|
||||
FROM alpine:3.22.1@sha256:4bcff63911fcb4448bd4fdacec207030997caf25e9bea4045fa6c8c44de311d1
|
||||
|
||||
ARG VERSION_TAG
|
||||
|
||||
@@ -66,7 +66,7 @@ COPY docker/unified/entrypoint.sh /entrypoint.sh
|
||||
# Environment Variables
|
||||
ENV DISABLE_ADDITIONAL_FEATURES=false \
|
||||
VERSION_TAG=$VERSION_TAG \
|
||||
JAVA_BASE_OPTS="-XX:+UnlockExperimentalVMOptions -XX:MaxRAMPercentage=75 -XX:InitiatingHeapOccupancyPercent=20 -XX:+G1PeriodicGCInvokesConcurrent -XX:G1PeriodicGCInterval=10000 -XX:+UseStringDeduplication -XX:G1PeriodicGCSystemLoadThreshold=70" \
|
||||
JAVA_BASE_OPTS="-XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/configs/heap_dumps -XX:+UnlockExperimentalVMOptions -XX:MaxRAMPercentage=75 -XX:InitiatingHeapOccupancyPercent=20 -XX:+G1PeriodicGCInvokesConcurrent -XX:G1PeriodicGCInterval=10000 -XX:+UseStringDeduplication -XX:G1PeriodicGCSystemLoadThreshold=70" \
|
||||
JAVA_CUSTOM_OPTS="" \
|
||||
HOME=/home/stirlingpdfuser \
|
||||
PUID=1000 \
|
||||
@@ -95,7 +95,7 @@ RUN echo "@main https://dl-cdn.alpinelinux.org/alpine/edge/main" | tee -a /etc/a
|
||||
su-exec \
|
||||
openjdk21-jre \
|
||||
nginx && \
|
||||
mkdir -p $HOME /configs /logs /customFiles /pipeline/watchedFolders /pipeline/finishedFolders /tmp/stirling-pdf /pipeline/watchedFolders /pipeline/finishedFolders && \
|
||||
mkdir -p $HOME /configs /configs/heap_dumps /logs /customFiles /pipeline/watchedFolders /pipeline/finishedFolders /tmp/stirling-pdf /pipeline/watchedFolders /pipeline/finishedFolders && \
|
||||
mkdir -p /usr/share/fonts/opentype/noto /var/lib/nginx/tmp /var/log/nginx && \
|
||||
chmod +x /scripts/*.sh && \
|
||||
chmod +x /entrypoint.sh && \
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
# ========================================
|
||||
# STAGE 1: Build stage - Alpine with Gradle
|
||||
# ========================================
|
||||
FROM gradle:8.14-jdk21 AS build
|
||||
FROM gradle:8.14-jdk21@sha256:051d9a116793bdc5175a3f97a545718b750489eee85a7da20913c8a53f722a72 AS build
|
||||
|
||||
COPY build.gradle .
|
||||
COPY settings.gradle .
|
||||
@@ -128,7 +128,8 @@ LABEL org.opencontainers.image.keywords="PDF, manipulation, backend, API, Spring
|
||||
# ==============================================================================
|
||||
ENV VERSION_TAG=$VERSION_TAG \
|
||||
DISABLE_ADDITIONAL_FEATURES=true \
|
||||
JAVA_BASE_OPTS="-XX:+UnlockExperimentalVMOptions -XX:MaxRAMPercentage=75 -XX:InitiatingHeapOccupancyPercent=20 \
|
||||
JAVA_BASE_OPTS="-XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/configs/heap_dumps \
|
||||
-XX:+UnlockExperimentalVMOptions -XX:MaxRAMPercentage=75 -XX:InitiatingHeapOccupancyPercent=20 \
|
||||
-XX:+G1PeriodicGCInvokesConcurrent -XX:G1PeriodicGCInterval=10000 \
|
||||
-XX:+UseStringDeduplication -XX:G1PeriodicGCSystemLoadThreshold=70 \
|
||||
-Djava.awt.headless=true" \
|
||||
@@ -166,7 +167,7 @@ ENV PATH="/opt/venv/bin:/opt/unoserver-venv/bin:${PATH}"
|
||||
# ==============================================================================
|
||||
RUN set -eux; \
|
||||
chmod +x /scripts/*; \
|
||||
mkdir -p /configs /logs /customFiles /pipeline/watchedFolders /pipeline/finishedFolders /tmp/stirling-pdf; \
|
||||
mkdir -p /configs /configs/heap_dumps /logs /customFiles /pipeline/watchedFolders /pipeline/finishedFolders /tmp/stirling-pdf; \
|
||||
chown -R stirlingpdfuser:stirlingpdfgroup \
|
||||
/home/stirlingpdfuser /configs /logs /customFiles /pipeline /tmp/stirling-pdf \
|
||||
/app.jar /restart-helper.jar /usr/share/fonts/truetype /scripts; \
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
# ========================================
|
||||
# STAGE 1: Build stage - Gradle
|
||||
# ========================================
|
||||
FROM gradle:8.14-jdk21 AS build
|
||||
FROM gradle:8.14-jdk21@sha256:051d9a116793bdc5175a3f97a545718b750489eee85a7da20913c8a53f722a72 AS build
|
||||
|
||||
COPY build.gradle .
|
||||
COPY settings.gradle .
|
||||
@@ -127,7 +127,8 @@ LABEL org.opencontainers.image.keywords="PDF, manipulation, merge, split, conver
|
||||
# ==============================================================================
|
||||
ENV VERSION_TAG=$VERSION_TAG \
|
||||
DISABLE_ADDITIONAL_FEATURES=true \
|
||||
JAVA_BASE_OPTS="-XX:+UnlockExperimentalVMOptions -XX:MaxRAMPercentage=75 -XX:InitiatingHeapOccupancyPercent=20 \
|
||||
JAVA_BASE_OPTS="-XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/configs/heap_dumps \
|
||||
-XX:+UnlockExperimentalVMOptions -XX:MaxRAMPercentage=75 -XX:InitiatingHeapOccupancyPercent=20 \
|
||||
-XX:+G1PeriodicGCInvokesConcurrent -XX:G1PeriodicGCInterval=10000 \
|
||||
-XX:+UseStringDeduplication -XX:G1PeriodicGCSystemLoadThreshold=70 \
|
||||
-Djava.awt.headless=true" \
|
||||
@@ -167,7 +168,7 @@ ENV PATH="/opt/venv/bin:/opt/unoserver-venv/bin:${PATH}"
|
||||
# ==============================================================================
|
||||
RUN set -eux; \
|
||||
chmod +x /scripts/*; \
|
||||
mkdir -p /configs /logs /customFiles /pipeline/watchedFolders /pipeline/finishedFolders /tmp/stirling-pdf; \
|
||||
mkdir -p /configs /configs/heap_dumps /logs /customFiles /pipeline/watchedFolders /pipeline/finishedFolders /tmp/stirling-pdf; \
|
||||
chown -R stirlingpdfuser:stirlingpdfgroup \
|
||||
/home/stirlingpdfuser /configs /logs /customFiles /pipeline /tmp/stirling-pdf \
|
||||
/app.jar /restart-helper.jar /usr/share/fonts/truetype /scripts; \
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# ========================================
|
||||
# STAGE 1: Build stage - Gradle
|
||||
# ========================================
|
||||
FROM gradle:8.14-jdk21 AS build
|
||||
FROM gradle:8.14-jdk21@sha256:051d9a116793bdc5175a3f97a545718b750489eee85a7da20913c8a53f722a72 AS build
|
||||
|
||||
COPY build.gradle .
|
||||
COPY settings.gradle .
|
||||
@@ -34,7 +34,7 @@ ARG VERSION_TAG
|
||||
# Set Environment Variables
|
||||
ENV HOME=/home/stirlingpdfuser \
|
||||
VERSION_TAG=$VERSION_TAG \
|
||||
JAVA_BASE_OPTS="-XX:+UnlockExperimentalVMOptions -XX:MaxRAMPercentage=75 -XX:InitiatingHeapOccupancyPercent=20 -XX:+G1PeriodicGCInvokesConcurrent -XX:G1PeriodicGCInterval=10000 -XX:+UseStringDeduplication -XX:G1PeriodicGCSystemLoadThreshold=70" \
|
||||
JAVA_BASE_OPTS="-XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/configs/heap_dumps -XX:+UnlockExperimentalVMOptions -XX:MaxRAMPercentage=75 -XX:InitiatingHeapOccupancyPercent=20 -XX:+G1PeriodicGCInvokesConcurrent -XX:G1PeriodicGCInterval=10000 -XX:+UseStringDeduplication -XX:G1PeriodicGCSystemLoadThreshold=70" \
|
||||
JAVA_CUSTOM_OPTS="" \
|
||||
PUID=1000 \
|
||||
PGID=1000 \
|
||||
@@ -71,7 +71,7 @@ RUN apk add --no-cache bash \
|
||||
ghostscript \
|
||||
fontforge && \
|
||||
# User permissions
|
||||
mkdir -p /configs /logs /customFiles /usr/share/fonts/opentype/noto /tmp/stirling-pdf /pipeline/watchedFolders /pipeline/finishedFolders && \
|
||||
mkdir -p /configs /configs/heap_dumps /logs /customFiles /usr/share/fonts/opentype/noto /tmp/stirling-pdf /pipeline/watchedFolders /pipeline/finishedFolders && \
|
||||
chmod +x /scripts/*.sh && \
|
||||
addgroup -S stirlingpdfgroup && adduser -S stirlingpdfuser -G stirlingpdfgroup && \
|
||||
chown -R stirlingpdfuser:stirlingpdfgroup $HOME /scripts /pipeline /configs /customFiles /pipeline /tmp/stirling-pdf && \
|
||||
|
||||
@@ -4,7 +4,7 @@ services:
|
||||
context: ../..
|
||||
dockerfile: docker/backend/Dockerfile.fat
|
||||
container_name: stirling-pdf-backend-fat
|
||||
restart: on-failure:5
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
@@ -42,7 +42,7 @@ services:
|
||||
context: ../..
|
||||
dockerfile: docker/frontend/Dockerfile
|
||||
container_name: stirling-pdf-frontend-fat
|
||||
restart: on-failure:5
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "3000:80"
|
||||
environment:
|
||||
|
||||
@@ -4,7 +4,7 @@ services:
|
||||
context: ../..
|
||||
dockerfile: docker/backend/Dockerfile.ultra-lite
|
||||
container_name: stirling-pdf-backend-ultra-lite
|
||||
restart: on-failure:5
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
@@ -39,7 +39,7 @@ services:
|
||||
context: ../..
|
||||
dockerfile: docker/frontend/Dockerfile
|
||||
container_name: stirling-pdf-frontend-ultra-lite
|
||||
restart: on-failure:5
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "3000:80"
|
||||
environment:
|
||||
|
||||
@@ -4,7 +4,7 @@ services:
|
||||
context: ../..
|
||||
dockerfile: docker/backend/Dockerfile
|
||||
container_name: stirling-pdf-backend
|
||||
restart: on-failure:5
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "curl -f http://localhost:8080/api/v1/info/status | grep -q 'UP'"]
|
||||
interval: 5s
|
||||
@@ -37,7 +37,7 @@ services:
|
||||
context: ../..
|
||||
dockerfile: docker/frontend/Dockerfile
|
||||
container_name: stirling-pdf-frontend
|
||||
restart: on-failure:5
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "3000:80"
|
||||
environment:
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# Single JAR contains both frontend and backend
|
||||
|
||||
# Stage 1: Build application with embedded frontend
|
||||
FROM gradle:8.14-jdk21 AS build
|
||||
FROM gradle:8.14-jdk21@sha256:051d9a116793bdc5175a3f97a545718b750489eee85a7da20913c8a53f722a72 AS build
|
||||
|
||||
# Install Node.js and npm for frontend build
|
||||
RUN apt-get update && apt-get install -y \
|
||||
@@ -54,7 +54,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
tesseract-ocr tesseract-ocr-eng tesseract-ocr-deu tesseract-ocr-fra \
|
||||
tesseract-ocr-por tesseract-ocr-chi-sim \
|
||||
libcairo2 libpango-1.0-0 libpangoft2-1.0-0 libgdk-pixbuf-2.0-0 \
|
||||
gosu unpaper \
|
||||
gosu unpaper qpdf \
|
||||
# AWT headless support (required for some Java graphics operations)
|
||||
libfreetype6 libfontconfig1 libx11-6 libxt6 libxext6 libxrender1 libxtst6 libxi6 \
|
||||
libxinerama1 libxkbcommon0 libxkbfile1 libsm6 libice6 \
|
||||
@@ -133,7 +133,7 @@ LABEL org.opencontainers.image.keywords="PDF, manipulation, API, Spring Boot, Re
|
||||
# Runtime environment variables
|
||||
# ==============================================================================
|
||||
ENV VERSION_TAG=$VERSION_TAG \
|
||||
JAVA_BASE_OPTS="-XX:+UnlockExperimentalVMOptions -XX:MaxRAMPercentage=75 -XX:InitiatingHeapOccupancyPercent=20 -XX:+G1PeriodicGCInvokesConcurrent -XX:G1PeriodicGCInterval=10000 -XX:+UseStringDeduplication -XX:G1PeriodicGCSystemLoadThreshold=70 -Djava.awt.headless=true" \
|
||||
JAVA_BASE_OPTS="-XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/configs/heap_dumps -XX:+UnlockExperimentalVMOptions -XX:MaxRAMPercentage=75 -XX:InitiatingHeapOccupancyPercent=20 -XX:+G1PeriodicGCInvokesConcurrent -XX:G1PeriodicGCInterval=10000 -XX:+UseStringDeduplication -XX:G1PeriodicGCSystemLoadThreshold=70 -Djava.awt.headless=true" \
|
||||
JAVA_CUSTOM_OPTS="" \
|
||||
HOME=/home/stirlingpdfuser \
|
||||
PUID=${PUID} \
|
||||
@@ -168,7 +168,7 @@ ENV PATH="/opt/venv/bin:/opt/unoserver-venv/bin:${PATH}"
|
||||
# ==============================================================================
|
||||
RUN set -eux; \
|
||||
chmod +x /scripts/*; \
|
||||
mkdir -p /configs /logs /customFiles /pipeline/watchedFolders /pipeline/finishedFolders /tmp/stirling-pdf; \
|
||||
mkdir -p /configs /configs/heap_dumps /logs /customFiles /pipeline/watchedFolders /pipeline/finishedFolders /tmp/stirling-pdf; \
|
||||
chown -R stirlingpdfuser:stirlingpdfgroup \
|
||||
/home/stirlingpdfuser /configs /logs /customFiles /pipeline /tmp/stirling-pdf \
|
||||
/app.jar /restart-helper.jar /usr/share/fonts/truetype /scripts; \
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# Single JAR contains both frontend and backend with extra fonts for air-gapped environments
|
||||
|
||||
# Stage 1: Build application with embedded frontend
|
||||
FROM gradle:8.14-jdk21 AS build
|
||||
FROM gradle:8.14-jdk21@sha256:051d9a116793bdc5175a3f97a545718b750489eee85a7da20913c8a53f722a72 AS build
|
||||
|
||||
# Install Node.js and npm for frontend build
|
||||
RUN apt-get update && apt-get install -y \
|
||||
@@ -54,7 +54,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
tesseract-ocr tesseract-ocr-eng tesseract-ocr-deu tesseract-ocr-fra \
|
||||
tesseract-ocr-por tesseract-ocr-chi-sim \
|
||||
libcairo2 libpango-1.0-0 libpangoft2-1.0-0 libgdk-pixbuf-2.0-0 \
|
||||
gosu unpaper \
|
||||
gosu unpaper qpdf \
|
||||
# Extra fonts for fat/air-gapped version
|
||||
fonts-dejavu fonts-liberation fonts-noto fonts-noto-cjk fonts-noto-color-emoji \
|
||||
fonts-freefont-ttf fonts-terminus fonts-linuxlibertine \
|
||||
@@ -136,7 +136,7 @@ LABEL org.opencontainers.image.keywords="PDF, manipulation, fat, air-gapped, API
|
||||
# Runtime environment variables
|
||||
# ==============================================================================
|
||||
ENV VERSION_TAG=$VERSION_TAG \
|
||||
JAVA_BASE_OPTS="-XX:+UnlockExperimentalVMOptions -XX:MaxRAMPercentage=75 -XX:InitiatingHeapOccupancyPercent=20 -XX:+G1PeriodicGCInvokesConcurrent -XX:G1PeriodicGCInterval=10000 -XX:+UseStringDeduplication -XX:G1PeriodicGCSystemLoadThreshold=70 -Djava.awt.headless=true" \
|
||||
JAVA_BASE_OPTS="-XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/configs/heap_dumps -XX:+UnlockExperimentalVMOptions -XX:MaxRAMPercentage=75 -XX:InitiatingHeapOccupancyPercent=20 -XX:+G1PeriodicGCInvokesConcurrent -XX:G1PeriodicGCInterval=10000 -XX:+UseStringDeduplication -XX:G1PeriodicGCSystemLoadThreshold=70 -Djava.awt.headless=true" \
|
||||
JAVA_CUSTOM_OPTS="" \
|
||||
HOME=/home/stirlingpdfuser \
|
||||
PUID=${PUID} \
|
||||
@@ -173,7 +173,7 @@ ENV PATH="/opt/venv/bin:/opt/unoserver-venv/bin:${PATH}"
|
||||
# ==============================================================================
|
||||
RUN set -eux; \
|
||||
chmod +x /scripts/*; \
|
||||
mkdir -p /configs /logs /customFiles /pipeline/watchedFolders /pipeline/finishedFolders /tmp/stirling-pdf; \
|
||||
mkdir -p /configs /configs/heap_dumps /logs /customFiles /pipeline/watchedFolders /pipeline/finishedFolders /tmp/stirling-pdf; \
|
||||
chown -R stirlingpdfuser:stirlingpdfgroup \
|
||||
/home/stirlingpdfuser /configs /logs /customFiles /pipeline /tmp/stirling-pdf \
|
||||
/app.jar /restart-helper.jar /usr/share/fonts/truetype /scripts; \
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# Single JAR contains both frontend and backend with minimal dependencies
|
||||
|
||||
# Stage 1: Build application with embedded frontend
|
||||
FROM gradle:8.14-jdk21 AS build
|
||||
FROM gradle:8.14-jdk21@sha256:051d9a116793bdc5175a3f97a545718b750489eee85a7da20913c8a53f722a72 AS build
|
||||
|
||||
# Install Node.js and npm for frontend build
|
||||
RUN apt-get update && apt-get install -y \
|
||||
@@ -36,7 +36,7 @@ RUN DISABLE_ADDITIONAL_FEATURES=true \
|
||||
./gradlew clean build -PbuildWithFrontend=true -x spotlessApply -x spotlessCheck -x test -x sonarqube
|
||||
|
||||
# Stage 2: Runtime image
|
||||
FROM alpine:3.22.1
|
||||
FROM alpine:3.22.1@sha256:4bcff63911fcb4448bd4fdacec207030997caf25e9bea4045fa6c8c44de311d1
|
||||
|
||||
ARG VERSION_TAG
|
||||
|
||||
@@ -63,7 +63,7 @@ COPY --from=build /app/build/libs/restart-helper.jar /restart-helper.jar
|
||||
|
||||
# Environment Variables
|
||||
ENV VERSION_TAG=$VERSION_TAG \
|
||||
JAVA_BASE_OPTS="-XX:+UnlockExperimentalVMOptions -XX:MaxRAMPercentage=75 -XX:InitiatingHeapOccupancyPercent=20 -XX:+G1PeriodicGCInvokesConcurrent -XX:G1PeriodicGCInterval=10000 -XX:+UseStringDeduplication -XX:G1PeriodicGCSystemLoadThreshold=70" \
|
||||
JAVA_BASE_OPTS="-XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/configs/heap_dumps -XX:+UnlockExperimentalVMOptions -XX:MaxRAMPercentage=75 -XX:InitiatingHeapOccupancyPercent=20 -XX:+G1PeriodicGCInvokesConcurrent -XX:G1PeriodicGCInterval=10000 -XX:+UseStringDeduplication -XX:G1PeriodicGCSystemLoadThreshold=70" \
|
||||
JAVA_CUSTOM_OPTS="" \
|
||||
HOME=/home/stirlingpdfuser \
|
||||
PUID=1000 \
|
||||
@@ -89,7 +89,7 @@ RUN echo "@main https://dl-cdn.alpinelinux.org/alpine/edge/main" | tee -a /etc/a
|
||||
shadow \
|
||||
su-exec \
|
||||
openjdk21-jre && \
|
||||
mkdir -p $HOME /configs /logs /customFiles /pipeline/watchedFolders /pipeline/finishedFolders /tmp/stirling-pdf && \
|
||||
mkdir -p $HOME /configs /configs/heap_dumps /logs /customFiles /pipeline/watchedFolders /pipeline/finishedFolders /tmp/stirling-pdf && \
|
||||
mkdir -p /usr/share/fonts/opentype/noto && \
|
||||
chmod +x /scripts/*.sh && \
|
||||
# User permissions
|
||||
|
||||
@@ -33,4 +33,4 @@ services:
|
||||
METRICS_ENABLED: "true"
|
||||
SYSTEM_GOOGLEVISIBILITY: "true"
|
||||
SHOW_SURVEY: "true"
|
||||
restart: on-failure:5
|
||||
restart: unless-stopped
|
||||
|
||||
@@ -31,4 +31,4 @@ services:
|
||||
METRICS_ENABLED: "true"
|
||||
SYSTEM_GOOGLEVISIBILITY: "true"
|
||||
SHOW_SURVEY: "true"
|
||||
restart: on-failure:5
|
||||
restart: unless-stopped
|
||||
|
||||
@@ -26,4 +26,4 @@ services:
|
||||
METRICS_ENABLED: "true"
|
||||
SYSTEM_GOOGLEVISIBILITY: "true"
|
||||
SHOW_SURVEY: "true"
|
||||
restart: on-failure:5
|
||||
restart: unless-stopped
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# Frontend Dockerfile - React/Vite application
|
||||
FROM node:20-alpine AS build
|
||||
FROM node:20-alpine@sha256:658d0f63e501824d6c23e06d4bb95c71e7d704537c9d9272f488ac03a370d448 AS build
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
@@ -16,7 +16,7 @@ COPY frontend .
|
||||
RUN npm run build
|
||||
|
||||
# Production stage
|
||||
FROM nginx:alpine
|
||||
FROM nginx:alpine@sha256:8491795299c8e739b7fcc6285d531d9812ce2666e07bd3dd8db00020ad132295
|
||||
|
||||
# Copy built files from build stage
|
||||
COPY --from=build /app/dist /usr/share/nginx/html
|
||||
|
||||
@@ -14,17 +14,20 @@ echo "==================================="
|
||||
setup_ocr() {
|
||||
echo "Setting up OCR languages..."
|
||||
|
||||
# Copy tessdata
|
||||
mkdir -p /usr/share/tessdata
|
||||
cp -rn /usr/share/tessdata-original/* /usr/share/tessdata 2>/dev/null || true
|
||||
# In Alpine, tesseract uses /usr/share/tessdata
|
||||
TESSDATA_DIR="/usr/share/tessdata"
|
||||
|
||||
if [ -d /usr/share/tesseract-ocr/4.00/tessdata ]; then
|
||||
cp -r /usr/share/tesseract-ocr/4.00/tessdata/* /usr/share/tessdata 2>/dev/null || true
|
||||
# Create tessdata directory
|
||||
mkdir -p "$TESSDATA_DIR"
|
||||
|
||||
# Restore system languages from backup (Dockerfile moved them to tessdata-original)
|
||||
if [ -d /usr/share/tessdata-original ]; then
|
||||
echo "Restoring system tessdata from backup..."
|
||||
cp -rn /usr/share/tessdata-original/* "$TESSDATA_DIR"/ 2>/dev/null || true
|
||||
fi
|
||||
|
||||
if [ -d /usr/share/tesseract-ocr/5/tessdata ]; then
|
||||
cp -r /usr/share/tesseract-ocr/5/tessdata/* /usr/share/tessdata 2>/dev/null || true
|
||||
fi
|
||||
# Note: If user mounted custom languages to /usr/share/tessdata, they'll be overlaid here.
|
||||
# The cp -rn above won't overwrite user files, just adds missing system files.
|
||||
|
||||
# Install additional languages if specified
|
||||
if [[ -n "$TESSERACT_LANGS" ]]; then
|
||||
@@ -32,10 +35,15 @@ setup_ocr() {
|
||||
pattern='^[a-zA-Z]{2,4}(_[a-zA-Z]{2,4})?$'
|
||||
for LANG in $SPACE_SEPARATED_LANGS; do
|
||||
if [[ $LANG =~ $pattern ]]; then
|
||||
echo "Installing tesseract language: $LANG"
|
||||
apk add --no-cache "tesseract-ocr-data-$LANG" 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
# Point to the consolidated location
|
||||
export TESSDATA_PREFIX="$TESSDATA_DIR"
|
||||
echo "Using TESSDATA_PREFIX=$TESSDATA_PREFIX"
|
||||
}
|
||||
|
||||
# Function to setup user permissions (from init-without-ocr.sh)
|
||||
|
||||
Generated
+1976
-784
File diff suppressed because it is too large
Load Diff
@@ -17,6 +17,7 @@
|
||||
"@embedpdf/plugin-loader": "^1.5.0",
|
||||
"@embedpdf/plugin-pan": "^1.5.0",
|
||||
"@embedpdf/plugin-print": "^1.5.0",
|
||||
"@embedpdf/plugin-redaction": "^1.5.0",
|
||||
"@embedpdf/plugin-render": "^1.5.0",
|
||||
"@embedpdf/plugin-rotate": "^1.5.0",
|
||||
"@embedpdf/plugin-scroll": "^1.5.0",
|
||||
@@ -45,6 +46,7 @@
|
||||
"@tauri-apps/api": "^2.5.0",
|
||||
"@tauri-apps/plugin-fs": "^2.4.0",
|
||||
"@tauri-apps/plugin-http": "^2.5.4",
|
||||
"@tauri-apps/plugin-shell": "^2.3.3",
|
||||
"autoprefixer": "^10.4.21",
|
||||
"axios": "^1.12.2",
|
||||
"globals": "^16.4.0",
|
||||
@@ -76,6 +78,10 @@
|
||||
"preview": "vite preview",
|
||||
"tauri-dev": "tauri dev --no-watch",
|
||||
"tauri-build": "tauri build",
|
||||
"tauri-build-dev": "tauri build --no-bundle",
|
||||
"tauri-build-dev-mac": "tauri build --bundles app",
|
||||
"tauri-build-dev-windows": "tauri build --bundles nsis",
|
||||
"tauri-build-dev-linux": "tauri build --bundles appimage",
|
||||
"tauri-clean": "cd src-tauri && cargo clean && cd .. && rm -rf dist build",
|
||||
"typecheck": "npm run typecheck:proprietary",
|
||||
"typecheck:core": "tsc --noEmit --project tsconfig.core.json",
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
unsavedChanges = "You have unsaved changes to your PDF."
|
||||
pendingRedactionsTitle = "Unapplied Redactions"
|
||||
pendingRedactions = "You have unapplied redactions that will be lost."
|
||||
areYouSure = "Are you sure you want to leave?"
|
||||
unsavedChangesTitle = "Unsaved Changes"
|
||||
keepWorking = "Keep Working"
|
||||
discardChanges = "Discard & Leave"
|
||||
discardRedactions = "Discard & Leave"
|
||||
applyAndContinue = "Save & Leave"
|
||||
exportAndContinue = "Export & Continue"
|
||||
cancel = "Cancel"
|
||||
@@ -438,6 +441,13 @@ currentVersion = "Current Version"
|
||||
latestVersion = "Latest Version"
|
||||
checkForUpdates = "Check for Updates"
|
||||
viewDetails = "View Details"
|
||||
serverNeedsUpdate = "Server needs to be updated by administrator"
|
||||
|
||||
[settings.general.versionInfo]
|
||||
title = "Version Information"
|
||||
description = "Desktop and server version details"
|
||||
desktop = "Desktop Version"
|
||||
server = "Server Version"
|
||||
|
||||
[settings.security]
|
||||
title = "Security"
|
||||
@@ -528,6 +538,8 @@ accountSettings = "Account Settings"
|
||||
adminSettings = "Admin Settings - View and Add Users"
|
||||
userControlSettings = "User Control Settings"
|
||||
changeUsername = "Change Username"
|
||||
changeUsernameDescription = "Update your username. You will be logged out after updating."
|
||||
newUsernamePlaceholder = "Enter your new username"
|
||||
newUsername = "New Username"
|
||||
password = "Confirmation Password"
|
||||
oldPassword = "Old password"
|
||||
@@ -3219,6 +3231,7 @@ title = "Redaction Method"
|
||||
mode = "Mode"
|
||||
automatic = "Automatic"
|
||||
automaticDesc = "Redact text based on search terms"
|
||||
automaticDisabledTooltip = "Select files in the file manager to redact multiple files at once"
|
||||
manual = "Manual"
|
||||
manualDesc = "Click and drag to redact specific areas"
|
||||
manualComingSoon = "Manual redaction coming soon"
|
||||
@@ -3289,8 +3302,35 @@ text = "Only match complete words, not partial matches. 'John' won't match 'John
|
||||
title = "Convert to PDF-Image"
|
||||
text = "Converts the PDF to an image-based PDF after redaction. This ensures text behind redaction boxes is completely removed and unrecoverable."
|
||||
|
||||
[redact.tooltip.manual.header]
|
||||
title = "Manual Redaction Controls"
|
||||
|
||||
[redact.tooltip.manual.markText]
|
||||
title = "Mark Text Tool"
|
||||
text = "Select text directly on the PDF to mark it for redaction. Click and drag to highlight specific text that you want to redact."
|
||||
|
||||
[redact.tooltip.manual.markArea]
|
||||
title = "Mark Area Tool"
|
||||
text = "Draw rectangular areas on the PDF to mark regions for redaction. Useful for redacting images, signatures, or irregular shapes."
|
||||
|
||||
[redact.tooltip.manual.apply]
|
||||
title = "Apply Redactions"
|
||||
text = "After marking content, click 'Apply' to permanently redact all marked areas. The pending count shows how many redactions are ready to be applied."
|
||||
bullet1 = "Mark as many areas as needed before applying"
|
||||
bullet2 = "All pending redactions are applied at once"
|
||||
bullet3 = "Redactions cannot be undone after applying"
|
||||
|
||||
[redact.manual]
|
||||
title = "Redaction Tools"
|
||||
instructions = "Select text or draw areas on the PDF to mark content for redaction."
|
||||
markText = "Mark Text"
|
||||
markArea = "Mark Area"
|
||||
pendingLabel = "Pending:"
|
||||
applyWarning = "⚠️ Permanent application, cannot be undone and the data underneath will be deleted"
|
||||
apply = "Apply"
|
||||
noMarks = "No redaction marks. Use the tools above to mark content for redaction."
|
||||
header = "Manual Redaction"
|
||||
controlsTitle = "Manual Redaction Controls"
|
||||
textBasedRedaction = "Text-based Redaction"
|
||||
pageBasedRedaction = "Page-based Redaction"
|
||||
convertPDFToImageLabel = "Convert PDF to PDF-Image (Used to remove text behind the box)"
|
||||
@@ -4078,11 +4118,16 @@ language = "Language"
|
||||
toggleAnnotations = "Toggle Annotations Visibility"
|
||||
search = "Search PDF"
|
||||
panMode = "Pan Mode"
|
||||
applyRedactionsFirst = "Apply redactions first"
|
||||
rotateLeft = "Rotate Left"
|
||||
rotateRight = "Rotate Right"
|
||||
toggleSidebar = "Toggle Sidebar"
|
||||
toggleBookmarks = "Toggle Bookmarks"
|
||||
print = "Print PDF"
|
||||
draw = "Draw"
|
||||
redact = "Redact"
|
||||
exitRedaction = "Exit Redaction Mode"
|
||||
save = "Save"
|
||||
downloadAll = "Download All"
|
||||
saveAll = "Save All"
|
||||
|
||||
@@ -4156,6 +4201,7 @@ editSwitchToSelect = "Switch to Select & Edit to edit this annotation."
|
||||
undo = "Undo"
|
||||
redo = "Redo"
|
||||
applyChanges = "Apply Changes"
|
||||
saveChanges = "Save Changes"
|
||||
|
||||
[search]
|
||||
title = "Search PDF"
|
||||
@@ -4238,6 +4284,8 @@ fetchError = "Failed to load settings"
|
||||
saveError = "Failed to save settings"
|
||||
saved = "Settings saved successfully"
|
||||
saveSuccess = "Settings saved successfully"
|
||||
success = "Settings saved successfully"
|
||||
error = "Failed to save settings"
|
||||
save = "Save Changes"
|
||||
discard = "Discard"
|
||||
restartRequired = "Restart Required"
|
||||
@@ -4504,6 +4552,19 @@ connect = "Connect"
|
||||
disconnect = "Disconnect"
|
||||
disconnected = "Provider disconnected successfully"
|
||||
disconnectError = "Failed to disconnect provider"
|
||||
mobileScannerConvertToPdf = "Convert Images to PDF"
|
||||
mobileScannerConvertToPdfDesc = "Automatically convert uploaded images to PDF format. If disabled, images will be kept as-is."
|
||||
mobileScannerImageResolution = "Image Resolution"
|
||||
mobileScannerImageResolutionDesc = "Resolution of uploaded images. \"Reduced\" scales images to max 1200px to reduce file size."
|
||||
imageResolutionFull = "Full (Original Size)"
|
||||
imageResolutionReduced = "Reduced (Max 1200px)"
|
||||
mobileScannerPageFormat = "Page Format"
|
||||
mobileScannerPageFormatDesc = "PDF page size for converted images. \"Keep\" uses original image dimensions."
|
||||
pageFormatKeep = "Keep (Original Dimensions)"
|
||||
pageFormatA4 = "A4 (210×297mm)"
|
||||
pageFormatLetter = "Letter (8.5×11in)"
|
||||
mobileScannerStretchToFit = "Stretch to Fit"
|
||||
mobileScannerStretchToFitDesc = "Stretch images to fill the entire page. If disabled, images are centered with preserved aspect ratio."
|
||||
|
||||
[admin.settings.connections.ssoAutoLogin]
|
||||
label = "SSO Auto Login"
|
||||
@@ -4578,6 +4639,19 @@ enable = "Enable QR Code Upload"
|
||||
description = "Allow users to upload files from mobile devices by scanning a QR code"
|
||||
note = "Note: Requires Frontend URL to be configured. "
|
||||
link = "Configure in System Settings"
|
||||
mobileScannerConvertToPdf = "Convert Images to PDF"
|
||||
mobileScannerConvertToPdfDesc = "Automatically convert uploaded images to PDF format. If disabled, images will be kept as-is."
|
||||
mobileScannerImageResolution = "Image Resolution"
|
||||
mobileScannerImageResolutionDesc = "Resolution of uploaded images. \"Reduced\" scales images to max 1200px to reduce file size."
|
||||
imageResolutionFull = "Full (Original Size)"
|
||||
imageResolutionReduced = "Reduced (Max 1200px)"
|
||||
mobileScannerPageFormat = "Page Format"
|
||||
mobileScannerPageFormatDesc = "PDF page size for converted images. \"Keep\" uses original image dimensions."
|
||||
pageFormatKeep = "Keep (Original Dimensions)"
|
||||
pageFormatA4 = "A4 (210×297mm)"
|
||||
pageFormatLetter = "Letter (8.5×11in)"
|
||||
mobileScannerStretchToFit = "Stretch to Fit"
|
||||
mobileScannerStretchToFitDesc = "Stretch images to fill the entire page. If disabled, images are centered with preserved aspect ratio."
|
||||
|
||||
[admin.settings.database]
|
||||
title = "Database"
|
||||
@@ -4951,6 +5025,7 @@ noRecentFiles = "No recent files found"
|
||||
googleDriveNotAvailable = "Google Drive integration not available"
|
||||
mobileUpload = "Mobile Upload"
|
||||
mobileShort = "Mobile"
|
||||
mobileUploadNotAvailable = "Mobile upload not enabled"
|
||||
downloadSelected = "Download Selected"
|
||||
saveSelected = "Save Selected"
|
||||
openFiles = "Open Files"
|
||||
@@ -6178,6 +6253,7 @@ description = "Enter the full URL of your self-hosted Stirling PDF server"
|
||||
|
||||
[setup.server.error]
|
||||
emptyUrl = "Please enter a server URL"
|
||||
invalidUrl = "Invalid URL format. Please enter a valid URL like https://your-server.com"
|
||||
unreachable = "Could not connect to server"
|
||||
testFailed = "Connection test failed"
|
||||
configFetch = "Failed to fetch server configuration. Please check the URL and try again."
|
||||
@@ -6196,6 +6272,7 @@ connectingTo = "Connecting to:"
|
||||
submit = "Login"
|
||||
signInWith = "Sign in with"
|
||||
oauthPending = "Opening browser for authentication..."
|
||||
sso = "Single Sign-On"
|
||||
orContinueWith = "Or continue with email"
|
||||
serverRequirement = "Note: The server must have login enabled."
|
||||
showInstructions = "How to enable?"
|
||||
@@ -6423,7 +6500,8 @@ failed = "An error occurred while adding text to the PDF."
|
||||
|
||||
[mobileUpload]
|
||||
title = "Upload from Mobile"
|
||||
description = "Scan this QR code with your mobile device to upload photos directly to this page."
|
||||
description = "Scan to upload photos. Images auto-convert to PDF."
|
||||
descriptionNoConvert = "Scan to upload photos from your mobile device."
|
||||
error = "Connection Error"
|
||||
pollingError = "Error checking for files"
|
||||
sessionId = "Session ID"
|
||||
@@ -6432,7 +6510,8 @@ expiryWarning = "Session Expiring Soon"
|
||||
expiryWarningMessage = "This QR code will expire in {{seconds}} seconds. A new code will be generated automatically."
|
||||
filesReceived = "{{count}} file(s) received"
|
||||
connected = "Mobile device connected"
|
||||
instructions = "Open the camera app on your phone and scan this code. Files will be transferred directly between devices."
|
||||
instructions = "Scan with your phone camera. Images convert to PDF automatically."
|
||||
instructionsNoConvert = "Scan with your phone camera to upload files."
|
||||
|
||||
[mobileScanner]
|
||||
title = "Mobile Scanner"
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
unsavedChanges = "Tá athruithe gan sábháil agat ar do PDF."
|
||||
pendingRedactionsTitle = "Eagarthóireacht Neamhfheidhmithe"
|
||||
pendingRedactions = "Tá eagarthóireachtaí neamhfheidhmithe agat a chaillfear."
|
||||
areYouSure = "An bhfuil tú cinnte gur mian leat imeacht?"
|
||||
unsavedChangesTitle = "Athruithe Gan Sábháil"
|
||||
keepWorking = "Lean ort ag obair"
|
||||
discardChanges = "Caith uait & Fág"
|
||||
discardRedactions = "Scrios & Fág"
|
||||
applyAndContinue = "Sábháil & Fág"
|
||||
exportAndContinue = "Easpórtáil & Lean ar aghaidh"
|
||||
cancel = "Cealaigh"
|
||||
@@ -124,14 +127,14 @@ submit = "Cuir isteach"
|
||||
success = "D’éirigh leis"
|
||||
undoDataMismatch = "Ní féidir a chealú: tá sonraí na hoibríochta truaillithe"
|
||||
undoFailed = "Theip ar chealú na hoibríochta"
|
||||
undoQuotaError = "Ní féidir a chealú: níl dóthain spáis stórála ann"
|
||||
undoStorageError = "Críochnaíodh an cealú ach níorbh fhéidir roinnt comhad a shábháil sa stóras"
|
||||
undoSuccess = "Cealaíodh an oibríocht go rathúil"
|
||||
unsupported = "Ní thacaítear leis"
|
||||
undoQuotaError = "Ní féidir é a chealú: easpa spáis stórála"
|
||||
undoStorageError = "Cealú críochnaithe ach níorbh fhéidir roinnt comhad a shábháil chuig an stóras"
|
||||
undoSuccess = "Oibríocht cealaithe go rathúil"
|
||||
unsupported = "Gan tacaíocht"
|
||||
|
||||
[toolPanel]
|
||||
placeholder = "Roghnaigh uirlis chun tosú"
|
||||
alpha = "Alpha"
|
||||
alpha = "Alfa"
|
||||
premiumFeature = "Gné Préimhe:"
|
||||
comingSoon = "Ag teacht go luath:"
|
||||
|
||||
@@ -340,6 +343,10 @@ advance = "Casta"
|
||||
edit = "Féach ar & Cuir in Eagar"
|
||||
popular = "Coitianta"
|
||||
|
||||
[footer]
|
||||
discord = "Discord"
|
||||
issues = "GitHub"
|
||||
|
||||
[settings.preferences]
|
||||
title = "Sainroghanna"
|
||||
|
||||
@@ -435,6 +442,25 @@ latestVersion = "Leagan is Déanaí"
|
||||
checkForUpdates = "Seiceáil le haghaidh Nuashonruithe"
|
||||
viewDetails = "Féach Sonraí"
|
||||
|
||||
[settings.security]
|
||||
title = "Slándáil"
|
||||
description = "Nuashonraigh do phasfhocal chun do chuntas a choinneáil slán."
|
||||
|
||||
[settings.security.password]
|
||||
subtitle = "Athraigh do phasfhocal. Logálfar amach thú tar éis an nuashonraithe."
|
||||
required = "Tá gach réimse riachtanach."
|
||||
mismatch = "Ní hionann na pasfhocail nua."
|
||||
error = "Ní féidir an focal faire a nuashonrú. Fíoraigh do phasfhocal reatha agus déan iarracht arís."
|
||||
success = "Nuashonraíodh an focal faire go rathúil. Sínigh isteach arís le do thoil."
|
||||
ssoDisabled = "Déanann do sholáthraí aitheantais athruithe ar phasfhocail a bhainistiú."
|
||||
current = "Focal faire reatha"
|
||||
currentPlaceholder = "Cuir isteach do phasfhocal reatha"
|
||||
new = "Pasfhocal nua"
|
||||
newPlaceholder = "Cuir isteach focal faire nua"
|
||||
confirm = "Deimhnigh an focal faire nua"
|
||||
confirmPlaceholder = "Ath-iontráil do phasfhocal nua"
|
||||
update = "Nuashonraigh an focal faire"
|
||||
|
||||
[settings.hotkeys]
|
||||
title = "Aicearraí Méarchláir"
|
||||
description = "Saincheap aicearraí méarchláir chun rochtain thapa ar uirlisí. Cliceáil \"Athraigh aicearra\" agus brúigh teaglaim eochracha nua. Brúigh Esc chun cealú."
|
||||
@@ -488,11 +514,16 @@ low = "Íseal"
|
||||
title = "Athraigh Dintiúir"
|
||||
header = "Nuashonraigh Sonraí do Chuntais"
|
||||
changePassword = "Tá dintiúir réamhshocraithe logáil isteach á úsáid agat. Cuir isteach pasfhocal nua le do thoil"
|
||||
ssoManaged = "Déanann do sholáthraí aitheantais bainistíocht ar do chuntas."
|
||||
newUsername = "Ainm Úsáideora Nua"
|
||||
oldPassword = "Pasfhocal reatha"
|
||||
newPassword = "Focal Faire Nua"
|
||||
confirmNewPassword = "Deimhnigh Pasfhocal Nua"
|
||||
submit = "Cuir Athruithe isteach"
|
||||
credsUpdated = "Cuntas nuashonraithe"
|
||||
description = "Athruithe sábháilte. Logáil isteach arís le do thoil."
|
||||
error = "Ní féidir an t-ainm úsáideora a nuashonrú. Fíoraigh do phasfhocal agus déan iarracht arís."
|
||||
changeUsername = "Nuashonraigh d'ainm úsáideora. Logálfar amach thú tar éis an nuashonraithe."
|
||||
|
||||
[account]
|
||||
title = "Socruithe cuntas"
|
||||
@@ -704,7 +735,12 @@ title = "Braith & Roinn Grianghraif Scanta"
|
||||
desc = "Braith agus roinn grianghraif scanta ina leathanaigh ar leith"
|
||||
|
||||
[home.sign]
|
||||
tags = "síniú,uathshíniú"
|
||||
tags = "síniú, uathghraf"
|
||||
title = "Sínigh"
|
||||
desc = "Cuireann síniú le PDF trí líníocht, téacs nó íomhá"
|
||||
|
||||
[home.annotate]
|
||||
tags = "anótáil, aibhsigh, tarraing"
|
||||
title = "Comhartha"
|
||||
desc = "Cuireann síniú le PDF trí líníocht, téacs nó íomhá"
|
||||
|
||||
@@ -922,14 +958,15 @@ title = "Eagarthóir Téacs PDF"
|
||||
desc = "Cuir téacs agus íomhánna atá ann cheana in eagar laistigh de PDFanna"
|
||||
|
||||
[home.addText]
|
||||
tags = "téacs,anótáil,lipéad"
|
||||
title = "Cuir Téacs Leis"
|
||||
tags = "annotate,highlight,draw"
|
||||
title = "Annotate"
|
||||
desc = "Cuir téacs saincheaptha in áit ar bith i do PDF"
|
||||
|
||||
[landing]
|
||||
addFiles = "Cuir Comhaid Leis"
|
||||
uploadFromComputer = "Uaslódáil ón ríomhaire"
|
||||
openFromComputer = "Oscail ón ríomhaire"
|
||||
mobileUpload = "Uaslódáil ó Shoghluaiste"
|
||||
|
||||
[viewPdf]
|
||||
tags = "amharc, léamh, anótáil, téacs, íomhá"
|
||||
@@ -1104,10 +1141,10 @@ bullet3 = "Scoilfidh an córas ag teorainneacha leathanaigh"
|
||||
|
||||
[split.tooltip.byCount]
|
||||
title = "Scoilt de réir Líon"
|
||||
text = "Cruthaigh il‑PDFanna le líon sonrach leathanach nó cáipéisí an ceann."
|
||||
text = "Cruthaigh il-PDFanna le líon sonrach leathanach nó doiciméad an ceann."
|
||||
bullet1 = "Líon Leathanach: Líon seasta leathanach in aghaidh an chomhaid"
|
||||
bullet2 = "Líon Cáipéisí: Líon seasta comhad aschuir"
|
||||
bullet3 = "Úsáideach do shreafaí oibre baisc‑phróiseála"
|
||||
bullet2 = "Líon na nDoiciméad: Líon socraithe comhad aschuir"
|
||||
bullet3 = "Úsáideach le haghaidh sreafaí oibre próiseála baisce"
|
||||
|
||||
[split.tooltip.byChapters]
|
||||
title = "Scoilt de réir Caibidlí"
|
||||
@@ -1244,7 +1281,22 @@ errorConversion = "Tharla earráid agus an comhad á thiontú."
|
||||
cbzOptions = "Roghanna CBZ go PDF"
|
||||
optimizeForEbook = "Optamaigh PDF do léitheoirí ríomhleabhar (úsáideann Ghostscript)"
|
||||
cbzOutputOptions = "Roghanna PDF go CBZ"
|
||||
cbzDpi = "DPI do rindreáil íomhá"
|
||||
cbzDpi = "DPI le haghaidh rindreáil íomhá"
|
||||
cbrOptions = "CRoghanna BR"
|
||||
cbrOutputOptions = "Roghanna PDF go CBR"
|
||||
cbrDpi = "DPI le haghaidh rindreáil íomhá"
|
||||
|
||||
[convert.ebookOptions]
|
||||
ebookOptions = "Roghanna ríomhleabhar go PDF"
|
||||
ebookOptionsDesc = "Roghanna chun ríomhleabhair a thiontú go PDF"
|
||||
embedAllFonts = "Leabaigh gach cló"
|
||||
embedAllFontsDesc = "Cuir na clónna uile ón ríomhleabhar isteach sa PDF a ghintear"
|
||||
includeTableOfContents = "Cuir clár ábhair san áireamh"
|
||||
includeTableOfContentsDesc = "Cuir clár ábhair ginte leis an PDF a eascraíonn as"
|
||||
includePageNumbers = "Cuir uimhreacha leathanach san áireamh"
|
||||
includePageNumbersDesc = "Cuir uimhreacha leathanach leis an PDF ginte"
|
||||
optimizeForEbookPdf = "Optamaigh do léitheoirí ríomhleabhar"
|
||||
optimizeForEbookPdfDesc = "An PDF a bharrfheabhsú le haghaidh léamh ríomhleabhar (méid comhaid níos lú, rindreáil níos fearr ar ghléasanna eInk)"
|
||||
|
||||
[imageToPdf]
|
||||
tags = "comhshó, img, jpg, pictiúr, grianghraf"
|
||||
@@ -1356,12 +1408,17 @@ defaultImageLabel = "Íomhá uaslódáilte"
|
||||
|
||||
[attachments]
|
||||
tags = "embed,attach,file,attachment,attachments"
|
||||
title = "Add attachments"
|
||||
header = "Add attachments"
|
||||
title = "Cuir Ceangaltáin leis"
|
||||
header = "Cuir Ceangaltáin leis"
|
||||
add = "Cuir Iatán Leis"
|
||||
remove = "Bain Iatán"
|
||||
embed = "Leabaigh Iatán"
|
||||
submit = "Add attachments"
|
||||
embed = "Leabaigh an Ceangaltán"
|
||||
convertToPdfA3b = "Tiontaigh go PDF/A-3b"
|
||||
convertToPdfA3bDescription = "Cruthaíonn sé PDF cartlannaithe le ceangaltáin leabaithe"
|
||||
convertToPdfA3bTooltip = "Is formáid chartlainne í PDF/A-3b a chinntíonn caomhnú fadtéarmach. Ceadaíonn sí formáidí comhaid treallacha a leabú mar cheangaltáin. Éilíonn an comhshó Ghostscript agus d’fhéadfadh sé go dtógfadh sé níos faide i gcás comhad mór."
|
||||
convertToPdfA3bTooltipHeader = "Maidir le Comhshó PDF/A-3b"
|
||||
convertToPdfA3bTooltipTitle = "Cad a dhéanann sé"
|
||||
submit = "Cuir Ceangaltáin leis"
|
||||
|
||||
[watermark]
|
||||
title = "Cuir Uisce leis"
|
||||
@@ -1496,9 +1553,9 @@ bullet3 = "Coinníonn íomhánna ar ardtaifeach an cháilíocht níos fearr"
|
||||
[watermark.tooltip.file.recommendations]
|
||||
title = "Cleachtais is Fearr"
|
||||
text = "Leideanna le haghaidh torthaí optamacha i gcomharthaí uisce íomhá."
|
||||
bullet1 = "Úsáid lógónna nó stampaí le cúlraí trédhearcacha"
|
||||
bullet1 = "Bain úsáid as lógónna nó stampaí le cúlraí trédhearcacha"
|
||||
bullet2 = "Oibríonn dearaí simplí níos fearr ná íomhánna casta"
|
||||
bullet3 = "Smaoinigh ar mhéid deiridh an doiciméid agus taifeach á roghnú"
|
||||
bullet3 = "Smaoinigh ar mhéid deiridh an doiciméid agus tú ag roghnú taifeach"
|
||||
|
||||
[watermark.tooltip.formatting.header]
|
||||
title = "Formáidiú agus Leagan Amach"
|
||||
@@ -1517,8 +1574,8 @@ bullet3 = "Cruthaíonn teimhneacht níos ísle comharthaí uisce níos míne"
|
||||
|
||||
[watermark.tooltip.formatting.spacing]
|
||||
title = "Rialú Spásála"
|
||||
text = "Coigeartaigh an spásáil idir comharthaí uisce athchleachtaithe ar fud an leathanaigh."
|
||||
bullet1 = "Spásáil chothrománach: Fad idir comharthaí uisce ó chlé go deas"
|
||||
text = "Coigeartaigh an spásáil idir uiscemharcanna athuair ar fud an leathanaigh."
|
||||
bullet1 = "Spásáil chothrománach: An fad idir na huiscemharcanna ó chlé go deas"
|
||||
bullet2 = "Spásáil ingearach: Fad idir comharthaí uisce ó bharr go bun"
|
||||
bullet3 = "Cruthaíonn luachanna níos airde patrúin níos scaipthe"
|
||||
|
||||
@@ -1526,9 +1583,9 @@ bullet3 = "Cruthaíonn luachanna níos airde patrúin níos scaipthe"
|
||||
title = "Rogha Slándála"
|
||||
text = "Tiontaigh an PDF deiridh go formáid bunaithe ar íomhánna ar mhaithe le slándáil fheabhsaithe."
|
||||
bullet1 = "Coscann sé roghnú téacs agus cóipeáil"
|
||||
bullet2 = "Déanann sé comharthaí uisce níos deacra a bhaint"
|
||||
bullet3 = "Mar thoradh air sin tá méideanna comhaid níos mó"
|
||||
bullet4 = "Is fearr d’ábhar íogair nó faoi chóipcheart"
|
||||
bullet2 = "Déanann sé níos deacra uiscemharcanna a bhaint"
|
||||
bullet3 = "Torthaí i méideanna comhaid níos mó"
|
||||
bullet4 = "Is fearr le haghaidh ábhar íogair nó cóipchirt"
|
||||
|
||||
[watermark.type]
|
||||
1 = "Téacs"
|
||||
@@ -2190,11 +2247,11 @@ useCase2 = "Roinn baisceanna leaba chothrom ina gcomhaid ar leith"
|
||||
useCase3 = "Bris colláisí ina ngrianghraif aonair"
|
||||
useCase4 = "Tarraing grianghraif ó dhoiciméid"
|
||||
quickFixes = "Deisiúcháin thapa"
|
||||
problem1 = "Ní braitheadh grianghraif → méadaigh Tolerance go 30-50"
|
||||
problem2 = "An iomarca braiteanna bréagacha → méadaigh Minimum Area go 15,000-20,000"
|
||||
problem3 = "Tá barróga rómhall → méadaigh Border Size go 5-10"
|
||||
problem4 = "Ní dhírítear grianghraif claonta → ísligh Angle Threshold go ~5°"
|
||||
problem5 = "Boscaí deannaigh/torainn → méadaigh Minimum Contour Area go 1000-2000"
|
||||
problem1 = "Grianghraif gan bhrath → méadaigh an Lamháltas go 30-50"
|
||||
problem2 = "An iomarca braite bréagacha → méadaigh an Limistéar Íosta go 15,000-20,000"
|
||||
problem3 = "Tá na bearrtha ró-dhlúth → méadaigh Méid na Teorann go 5-10"
|
||||
problem4 = "Grianghraif chlaonta gan a bheith díreach → ísligh an Tairseach Uillinne go ~5°"
|
||||
problem5 = "Boscaí deannaigh/torainn → méadaigh an Limistéar Comhrian Íosta go 1000-2000"
|
||||
setupTips = "Leideanna socraithe"
|
||||
tip1 = "Úsáid cúlra éadrom, simplí"
|
||||
tip2 = "Fág bearna bheag (≈1 cm) idir grianghraif"
|
||||
@@ -2306,6 +2363,10 @@ saved = "Sábháilte"
|
||||
label = "Uaslódáil íomhá sínithe"
|
||||
placeholder = "Roghnaigh comhad íomhá"
|
||||
hint = "Uaslódáil íomhá PNG nó JPG de do shíniú"
|
||||
backgroundRemovalFailedMessage = "Níorbh fhéidir an cúlra a bhaint den íomhá. Íomhá bhunaidh á húsáid ina ionad."
|
||||
backgroundRemovalFailedTitle = "Theip ar bhaint an chúlra"
|
||||
processing = "Íomhá á phróiseáil..."
|
||||
removeBackground = "Bain an cúlra bán (déan trédhearcach)"
|
||||
|
||||
[sign.instructions]
|
||||
title = "Conas síniú a chur leis"
|
||||
@@ -2351,6 +2412,11 @@ note = "Baineann maolú eilimintí idirghníomhacha ón PDF, rud a fhágann nach
|
||||
label = "Flatten foirmeacha amháin"
|
||||
desc = "Maolaigh réimsí foirme amháin, fág eilimintí idirghníomhacha eile slán"
|
||||
|
||||
[flatten.renderDpi]
|
||||
label = "DPI rindreála (roghnach, molta 150 DPI)"
|
||||
help = "Fág bán chun réamhshocrú an chórais a úsáid. Géaraíonn DPI níos airde an t-aschur ach méadaíonn sé an t-am próiseála agus méid an chomhaid."
|
||||
placeholder = "m.sh. 150"
|
||||
|
||||
[flatten.results]
|
||||
title = "Torthaí Maolaithe"
|
||||
|
||||
@@ -2376,6 +2442,8 @@ bullet2 = "Oibríonn naisc fós nuair a chliceáiltear orthu"
|
||||
bullet3 = "Fanann nótaí agus tráchtanna le feiceáil"
|
||||
bullet4 = "Cabhraíonn leabharmharcanna leat nascleanúint a dhéanamh fós"
|
||||
|
||||
|
||||
|
||||
[repair]
|
||||
tags = "deisiú, athchóiriú, ceartú, aisghabháil"
|
||||
title = "Deisiúchán"
|
||||
@@ -2813,10 +2881,10 @@ bullet3 = "Nuair a fhilltear & a chairnítear: Léamh 1→2→3→4→5→6→7
|
||||
[bookletImposition.tooltip.printing]
|
||||
title = "Conas a Chlódófar & a Chruaifear"
|
||||
text = "Lean na céimeanna seo le haghaidh leabhrán foirfe:"
|
||||
bullet1 = "Clóigh dhá thaobh le 'Flip on long edge'"
|
||||
bullet1 = "Priontáil déthaobhach le 'Flip ar an imeall fada'"
|
||||
bullet2 = "Carn na bileoga in ord, fill ina leath"
|
||||
bullet3 = "Grádaigh nó ceangail feadh an droma fhillte"
|
||||
bullet4 = "Do phrintéirí imeall gearr: Cumasaigh an rogha 'Flip on short edge'"
|
||||
bullet4 = "I gcás printéirí imeall gearr: Cumasaigh an rogha 'Flip ar an imeall gearr'"
|
||||
|
||||
[bookletImposition.tooltip.manualDuplex]
|
||||
title = "Dúphléacs Láimhe (Printéirí Aon-taobh)"
|
||||
@@ -2857,8 +2925,8 @@ label = "Fachtóir Scála"
|
||||
[adjustPageScale.pageSize]
|
||||
label = "Spriocmhéid Leathanaigh"
|
||||
keep = "Coinnigh an méid bunaidh"
|
||||
letter = "Letter"
|
||||
legal = "Legal"
|
||||
letter = "Litir"
|
||||
legal = "Dlíthiúil"
|
||||
|
||||
[adjustPageScale.error]
|
||||
failed = "Tharla earráid agus scála na leathanach á choigeartú."
|
||||
@@ -2925,6 +2993,7 @@ header = "PDF a ghearradh"
|
||||
submit = "Cuir isteach"
|
||||
noFileSelected = "Roghnaigh comhad PDF chun tosú ar bhearradh"
|
||||
reset = "Athshocraigh go PDF iomlán"
|
||||
autoCrop = "Spás bán a bhearradh go huathoibríoch"
|
||||
|
||||
[crop.preview]
|
||||
title = "Roghnú Limistéir Bhearrtha"
|
||||
@@ -3158,6 +3227,7 @@ automaticDesc = "Ceil téacs bunaithe ar théarmaí cuardaigh"
|
||||
manual = "Láimhe"
|
||||
manualDesc = "Cliceáil agus tarraing chun limistéir shonracha a cheilt"
|
||||
manualComingSoon = "Ceilt láimhe ag teacht go luath"
|
||||
automaticDisabledTooltip = "Roghnaigh comhaid sa bhainisteoir comhad chun comhaid iolracha a cheilt ag an am céanna"
|
||||
|
||||
[redact.auto]
|
||||
header = "Ceilt Uathoibríoch"
|
||||
@@ -3223,13 +3293,40 @@ text = "Ní mheaitseálfar ach focail iomlána, ní meaitseálacha páirteacha.
|
||||
|
||||
[redact.tooltip.advanced.convert]
|
||||
title = "Tiontaigh go PDF-Image"
|
||||
text = "Tiontaíonn sé an PDF go PDF bunaithe ar íomhá tar éis ceilte. Cinntíonn sé seo go mbaintear téacs taobh thiar de bhoscaí ceilte go hiomlán agus nach féidir é a ghnóthú."
|
||||
text = "Athraíonn sé an PDF go PDF bunaithe ar íomhá tar éis eagarthóireachta. Cinntíonn sé seo go mbaintear téacs taobh thiar de bhoscaí eagarthóireachta go hiomlán agus nach féidir é a aisghabháil."
|
||||
|
||||
[redact.tooltip.manual.header]
|
||||
title = "Rialuithe Eagarthóireachta Láimhe"
|
||||
|
||||
[redact.tooltip.manual.markText]
|
||||
title = "Uirlis Téacs Marcála"
|
||||
text = "Roghnaigh téacs go díreach ar an PDF chun é a mharcáil le haghaidh eagarthóireachta. Cliceáil agus tarraing chun téacs ar leith ar mhaith leat a chealú a aibhsiú."
|
||||
|
||||
[redact.tooltip.manual.markArea]
|
||||
title = "Uirlis Limistéir Mharcáilte"
|
||||
text = "Tarraing limistéir dhronuilleogacha ar an PDF chun réigiúin a mharcáil le haghaidh eagarthóireachta. Úsáideach chun íomhánna, sínithe, nó cruthanna neamhrialta a cheilt."
|
||||
|
||||
[redact.tooltip.manual.apply]
|
||||
title = "Cuir Eagarthóireacht i bhFeidhm"
|
||||
text = "Tar éis duit ábhar a mharcáil, cliceáil 'Cuir i bhFeidhm' chun na réimsí marcáilte go léir a cheilt go buan. Taispeánann an comhaireamh atá ar feitheamh cé mhéad cheilt atá réidh le cur i bhfeidhm."
|
||||
bullet1 = "Marcáil an oiread limistéar agus is gá sula gcuirtear i bhfeidhm é"
|
||||
bullet2 = "Cuirtear gach eagarthóireacht atá ar feitheamh i bhfeidhm ag an am céanna"
|
||||
bullet3 = "Ní féidir eagarthóireachtaí a chealú tar éis iad a chur i bhfeidhm"
|
||||
|
||||
[redact.manual]
|
||||
header = "Ceilt Láimhe"
|
||||
textBasedRedaction = "Ceilt bunaithe ar théacs"
|
||||
pageBasedRedaction = "Ceilt bunaithe ar leathanach"
|
||||
convertPDFToImageLabel = "Tiontaigh PDF go PDF-Image (Úsáidtear chun téacs taobh thiar den bhosca a bhaint)"
|
||||
title = "Uirlisí Eagarthóireachta"
|
||||
instructions = "Roghnaigh téacs nó tarraing limistéir ar an PDF chun ábhar a mharcáil le haghaidh eagarthóireachta."
|
||||
markText = "Marcáil Téacs"
|
||||
markArea = "Marcáil Limistéar"
|
||||
pendingLabel = "Ar feitheamh:"
|
||||
applyWarning = "⚠️ Feidhmchlár buan, ní féidir é a chealú agus scriosfar na sonraí faoi."
|
||||
apply = "Cuir isteach"
|
||||
noMarks = "Gan aon mharcanna eagarthóireachta. Bain úsáid as na huirlisí thuas chun ábhar a mharcáil le haghaidh eagarthóireachta."
|
||||
header = "Eagarthóireacht Láimhe"
|
||||
controlsTitle = "Rialuithe Eagarthóireachta Láimhe"
|
||||
textBasedRedaction = "Eagarthóireacht Téacsbhunaithe"
|
||||
pageBasedRedaction = "Eagarthóireacht Leathanachbhunaithe"
|
||||
convertPDFToImageLabel = "Tiontaigh PDF go PDF-Íomhá (Úsáidtear é chun téacs taobh thiar den bhosca a bhaint)"
|
||||
export = "Easpórtáil"
|
||||
upload = "Uaslódáil"
|
||||
boxRedaction = "Ceilt trí bhosca a tharraingt"
|
||||
@@ -3342,6 +3439,19 @@ placeholder = "Cuir isteach líon na rannán cothrománach"
|
||||
label = "Rannáin Ingearach"
|
||||
placeholder = "Cuir isteach líon na rannáin ingearacha"
|
||||
|
||||
[split-by-sections.splitMode]
|
||||
label = "Mód Scoilte"
|
||||
description = "Roghnaigh conas na leathanaigh a roinnt"
|
||||
splitAll = "Scoilt na leathanaigh uile"
|
||||
splitAllExceptFirst = "Roinn gach rud seachas an chéad cheann"
|
||||
splitAllExceptLast = "Roinn gach rud seachas an ceann deireanach"
|
||||
splitAllExceptFirstAndLast = "Roinn gach rud seachas an chéad cheann agus an ceann deireanach"
|
||||
custom = "Leathanaigh saincheaptha"
|
||||
|
||||
[split-by-sections.customPages]
|
||||
label = "Uimhreacha Leathanaigh Saincheaptha"
|
||||
placeholder = "m.sh. 2,4,6"
|
||||
|
||||
[AddStampRequest]
|
||||
tags = "Stampa, Cuir íomhá, íomhá lár, Uisce, PDF, Leabú, Saincheap"
|
||||
header = "Stampa PDF"
|
||||
@@ -3481,7 +3591,7 @@ certHint = "Uaslódáil teastas X.509 iontaofa le bailíochtú i gcoinne foinse
|
||||
title = "Socruithe Bailíochtaithe"
|
||||
|
||||
[replaceColor]
|
||||
tags = "Ionadaigh Dath,Oibríochtaí Leathanaigh,Back end,server side"
|
||||
tags = "Athsholáthar Dath, Oibríochtaí Leathanaigh, Cúlchríoch, Taobh an Fhreastalaí"
|
||||
|
||||
[replaceColor.labels]
|
||||
settings = "Socruithe"
|
||||
@@ -3520,7 +3630,7 @@ bullet2 = "Dath cúlra - Socraigh dath cúlra an doiciméid"
|
||||
|
||||
[replaceColor.tooltip.cmyk]
|
||||
title = "Tiontaigh go CMYK"
|
||||
text = "Tiontaigh an PDF ó spás datha RGB go spás datha CMYK, optamaithe le haghaidh priontála gairmiúla. Tiontaíonn an próiseas seo dathanna go samhail Cyan, Magenta, Yellow, Black a úsáideann printéirí."
|
||||
text = "Tiontaigh an PDF ó spás dathanna RGB go spás dathanna CMYK, atá optamaithe le haghaidh priontála gairmiúla. Tiontaíonn an próiseas seo dathanna go dtí an tsamhail Cian, Magenta, Buí, Dubh a úsáideann printéirí."
|
||||
|
||||
[replaceColor.error]
|
||||
failed = "Tharla earráid agus ionadú datha á phróiseáil."
|
||||
@@ -3539,8 +3649,8 @@ signinTitle = "Sínigh isteach le do thoil"
|
||||
ssoSignIn = "Logáil isteach trí Chlárú Aonair"
|
||||
oAuth2AutoCreateDisabled = "OAUTH2 Uath-Chruthaigh Úsáideoir faoi Mhíchumas"
|
||||
oAuth2AdminBlockedUser = "Tá bac faoi láthair ar chlárú nó logáil isteach úsáideoirí neamhchláraithe. Déan teagmháil leis an riarthóir le do thoil."
|
||||
oAuth2RequiresLicense = "Teastaíonn ceadúnas íoctha (Server nó Enterprise) chun logáil isteach le OAuth/SSO. Déan teagmháil leis an riarthóir chun do phlean a uasghrádú."
|
||||
saml2RequiresLicense = "Teastaíonn ceadúnas íoctha (Server nó Enterprise) chun logáil isteach le SAML. Déan teagmháil leis an riarthóir chun do phlean a uasghrádú."
|
||||
oAuth2RequiresLicense = "Éilíonn logáil isteach OAuth/SSO ceadúnas Freastalaí nó Fiontraíochta. Téigh i dteagmháil leis an riarthóir le do phlean a uasghrádú."
|
||||
saml2RequiresLicense = "Éilíonn logáil isteach SAML ceadúnas Fiontraíochta. Téigh i dteagmháil leis an riarthóir le do phlean a uasghrádú."
|
||||
maxUsersReached = "Sroicheadh an líon uasta úsáideoirí do do cheadúnas reatha. Déan teagmháil leis an riarthóir chun do phlean a uasghrádú nó suíocháin bhreise a chur leis."
|
||||
oauth2RequestNotFound = "Níor aimsíodh iarratas údaraithe"
|
||||
oauth2InvalidUserInfoResponse = "Freagra Neamhbhailí Faisnéise Úsáideora"
|
||||
@@ -3692,7 +3802,7 @@ title = "PDF Coigeartaithe"
|
||||
title = "Comhbhrúigh"
|
||||
desc = "Comhbhrúigh PDFanna chun a méid comhaid a laghdú."
|
||||
header = "Comhbhrúigh PDF"
|
||||
credit = "Úsáideann an tseirbhís seo qpdf le haghaidh Comhbhrú/Optimization PDF."
|
||||
credit = "Úsáideann an tseirbhís seo qpdf le haghaidh Comhbhrú/Optamú PDF."
|
||||
submit = "Comhbhrúigh"
|
||||
|
||||
[compress.method]
|
||||
@@ -3703,6 +3813,19 @@ filesize = "Méid an Chomhaid"
|
||||
[compress.grayscale]
|
||||
label = "Cuir Scála Liath i bhFeidhm le Comhbhrú"
|
||||
|
||||
[compress.linearize]
|
||||
label = "Líneáil PDF le haghaidh féachana gréasáin thapa"
|
||||
|
||||
[compress.lineArt]
|
||||
label = "Íomhánna a thiontú go healaín líne"
|
||||
description = "Úsáideann sé ImageMagick chun leathanaigh a laghdú go dubh agus bán ardchodarsnachta chun an laghdú méide is mó is féidir a bhaint amach."
|
||||
unavailable = "Níl ImageMagick suiteáilte ná cumasaithe ar an bhfreastalaí seo"
|
||||
detailLevel = "Leibhéal mionsonraí"
|
||||
edgeEmphasis = "Béim imeall"
|
||||
edgeLow = "Séimh"
|
||||
edgeMedium = "Cothromaithe"
|
||||
edgeHigh = "Láidir"
|
||||
|
||||
[compress.tooltip.header]
|
||||
title = "Forbhreathnú ar Shocruithe Comhbhrúite"
|
||||
|
||||
@@ -3720,6 +3843,10 @@ bullet2 = "Laghdaíonn luachanna níos airde an méid comhaid"
|
||||
title = "Liathscála"
|
||||
text = "Roghnaigh an rogha seo chun gach íomhá a thiontú go dubh agus bán, rud a d'fhéadfadh méid an chomhaid a laghdú go mór, go háirithe do PDFanna scanta nó do dhoiciméid lán d’íomhánna."
|
||||
|
||||
[compress.tooltip.lineArt]
|
||||
text = "Tiontaigh leathanaigh go dubh agus bán ardchodarsnachta ag baint úsáide as ImageMagick. Bain úsáid as leibhéal mionsonraí chun rialú a dhéanamh ar cé mhéad ábhair a thagann chun bheith dubh, agus béim imeall chun rialú a dhéanamh ar cé chomh ionsaitheach agus a bhraitear imill."
|
||||
title = "Ealaín Líne"
|
||||
|
||||
[compress.error]
|
||||
failed = "Tharla earráid agus an PDF á chomhbhrú."
|
||||
|
||||
@@ -3732,6 +3859,11 @@ failed = "Tharla earráid agus an PDF á chomhbhrú."
|
||||
_value = "Socruithe Comhbhrúite"
|
||||
1 = "1-3 comhbhrú PDF,</br> 4-6 comhbhrú éadrom íomhá,</br> 7-9 comhbhrú dian íomhá Laghdóidh sé cáilíocht na n-íomhánna go mór"
|
||||
|
||||
[compress.compressionLevel]
|
||||
range1to3 = "Coinníonn luachanna níos ísle cáilíocht ach bíonn comhaid níos mó mar thoradh orthu"
|
||||
range4to6 = "Comhbhrú meánach le laghdú measartha ar cháilíocht"
|
||||
range7to9 = "Laghdaíonn luachanna níos airde méid an chomhaid go suntasach ach d’fhéadfadh soiléireacht na híomhá a laghdú"
|
||||
|
||||
[decrypt]
|
||||
passwordPrompt = "Tá an comhad seo cosanta ag pasfhocal. Cuir isteach an pasfhocal le do thoil:"
|
||||
cancelled = "Cealaíodh an oibríocht le haghaidh PDF: {0}"
|
||||
@@ -3885,7 +4017,7 @@ showPreferencesBtn = "Bainistigh sainroghanna"
|
||||
|
||||
[cookieBanner.popUp.description]
|
||||
1 = "Úsáidimid fianáin agus teicneolaíochtaí eile chun Stirling PDF a dhéanamh níos fearr duit—ag cabhrú linn ár n-uirlisí a fheabhsú agus gnéithe a thógáil a thaitneoidh leat."
|
||||
2 = "If you’d rather not, clicking 'No Thanks' will only enable the essential cookies needed to keep things running smoothly."
|
||||
2 = "Mura mian leat, ní chuirfear ar chumas ach na fianáin riachtanacha atá riachtanach chun go n-oibreoidh rudaí go réidh má chliceálann tú ar 'Níl Go raibh maith agat'."
|
||||
|
||||
[cookieBanner.preferencesModal]
|
||||
title = "Lárionad Sainroghanna Toilithe"
|
||||
@@ -3902,7 +4034,7 @@ subtitle = "Úsáid Fianáin"
|
||||
3 = "Tá do phríobháideachas agus do mhuinín i gcroílár ár gcuid oibre."
|
||||
|
||||
[cookieBanner.preferencesModal.necessary]
|
||||
description = "These cookies are essential for the website to function properly. They enable core features like setting your privacy preferences, logging in, and filling out forms—which is why they can’t be turned off."
|
||||
description = "Tá na fianáin seo riachtanach chun go bhfeidhmeoidh an suíomh Gréasáin i gceart. Cuireann siad gnéithe lárnacha ar chumas amhail do chuid roghanna príobháideachais a shocrú, logáil isteach agus foirmeacha a líonadh—agus is é sin an fáth nach féidir iad a mhúchadh."
|
||||
|
||||
[cookieBanner.preferencesModal.necessary.title]
|
||||
1 = "Fianáin Riachtanacha go Docht"
|
||||
@@ -3913,8 +4045,8 @@ title = "Anailísíocht"
|
||||
description = "Cuidíonn na fianáin seo linn a thuiscint conas a úsáidtear ár n-uirlisí, ionas gur féidir linn díriú ar na gnéithe is tábhachtaí dár bpobal a thógáil. Bí cinnte—ní féidir le Stirling PDF agus ní dhéanfaidh sé riamh ábhar na ndoiciméad a n-oibríonn tú leo a rianú."
|
||||
|
||||
[cookieBanner.services]
|
||||
posthog = "PostHog Analytics"
|
||||
scarf = "Scarf Pixel"
|
||||
posthog = "Anailísíocht PostHog"
|
||||
scarf = "Scairf Picteilín"
|
||||
|
||||
[removeMetadata]
|
||||
submit = "Bain Meiteashonraí"
|
||||
@@ -3970,23 +4102,98 @@ selectByNumber = "Roghnaigh de réir Uimhreacha Leathanaigh"
|
||||
deleteSelected = "Scrios na Leathanaigh Roghnaithe"
|
||||
closePdf = "Dún an PDF"
|
||||
exportAll = "Easpórtáil an PDF"
|
||||
downloadSelected = "Íoslódáil na Comhaid Roghnaithe"
|
||||
downloadAll = "Íoslódáil Uile"
|
||||
saveAll = "Sábháil Uile"
|
||||
toggleTheme = "Athraigh an Téama"
|
||||
toggleBookmarks = "Scoránaigh Leabharmharcanna"
|
||||
downloadSelected = "Íoslódáil Comhaid Roghnaithe"
|
||||
annotations = "Anótálacha"
|
||||
exportSelected = "Easpórtáil Leathanaigh Roghnaithe"
|
||||
saveChanges = "Sábháil Athruithe"
|
||||
toggleTheme = "Téama a Athsholáthar"
|
||||
language = "Teanga"
|
||||
search = "Cuardaigh an PDF"
|
||||
panMode = "Mód Pánála"
|
||||
toggleAnnotations = "Infheictheacht Anótálacha a Athrú"
|
||||
search = "Cuardaigh PDF"
|
||||
panMode = "Mód Pan"
|
||||
applyRedactionsFirst = "Cuir eagarthóireachtaí i bhfeidhm ar dtús"
|
||||
rotateLeft = "Rothlaigh ar Chlé"
|
||||
rotateRight = "Rothlaigh ar Dheis"
|
||||
toggleSidebar = "Athraigh an Barra Taoibh"
|
||||
exportSelected = "Easpórtáil na Leathanaigh Roghnaithe"
|
||||
toggleAnnotations = "Athraigh Infheictheacht Anótálacha"
|
||||
annotationMode = "Athraigh Mód Anótála"
|
||||
toggleSidebar = "Barra Taobh a Athraigh"
|
||||
toggleBookmarks = "Leabharmharcanna a Athsholáthar"
|
||||
print = "Priontáil PDF"
|
||||
draw = "Tarraing"
|
||||
redact = "Leasaigh"
|
||||
exitRedaction = "Scoir Mód Eagarthóireachta"
|
||||
save = "Sábháil"
|
||||
downloadAll = "Íoslódáil Gach Rud"
|
||||
saveAll = "Sábháil Uile"
|
||||
|
||||
[textAlign]
|
||||
left = "Ar chlé"
|
||||
center = "Lár"
|
||||
right = "Ar dheis"
|
||||
|
||||
[annotation]
|
||||
title = "Anótáil"
|
||||
desc = "Bain úsáid as aird a tharraingt, peann, téacs agus nótaí. Fanann athruithe beo—níl gá le leacú."
|
||||
highlight = "Aibhsigh"
|
||||
pen = "Peann"
|
||||
text = "Bosca téacs"
|
||||
note = "Nóta"
|
||||
rectangle = "Dronuilleog"
|
||||
ellipse = "Éilips"
|
||||
select = "Roghnaigh"
|
||||
exit = "Scoir mód anótála"
|
||||
strokeWidth = "Leithead"
|
||||
opacity = "Teimhneacht"
|
||||
strokeOpacity = "Teimhneacht Stróc"
|
||||
fillOpacity = "Teimhneacht Líonadh"
|
||||
fontSize = "Méid an chló"
|
||||
chooseColor = "Roghnaigh dath"
|
||||
color = "Dath"
|
||||
strokeColor = "Dath Stróc"
|
||||
fillColor = "Dath Líonta"
|
||||
underline = "Folínigh"
|
||||
strikeout = "Stailc amach"
|
||||
squiggly = "Scriobláil"
|
||||
inkHighlighter = "Aibhseoir Saorláimhe"
|
||||
freehandHighlighter = "Aibhseoir Saorláimhe"
|
||||
square = "Cearnóg"
|
||||
circle = "Ciorcal"
|
||||
polygon = "Polagán"
|
||||
line = "Líne"
|
||||
stamp = "Cuir Íomhá leis"
|
||||
textMarkup = "Marcáil Téacs"
|
||||
drawing = "Líníocht"
|
||||
shapes = "Cruthanna"
|
||||
notesStamps = "Nótaí & Stampaí"
|
||||
settings = "Socruithe"
|
||||
borderOn = "Teorainn: Ar"
|
||||
borderOff = "Teorainn: As"
|
||||
editInk = "Peann a Chur in Eagar"
|
||||
editLine = "Líne a Chur in Eagar"
|
||||
editNote = "Cuir Nóta in Eagar"
|
||||
editText = "Cuir Bosca Téacs in Eagar"
|
||||
editTextMarkup = "Cuir Marcáil Téacs in Eagar"
|
||||
editSelected = "Cuir an nóta in Eagar"
|
||||
editSquare = "Cuir Cearnóg in Eagar"
|
||||
editCircle = "Cuir Ciorcal in Eagar"
|
||||
editPolygon = "Cuir Polagán in Eagar"
|
||||
unsupportedType = "Ní thacaítear go hiomlán leis an gcineál seo anótála le haghaidh eagarthóireachta."
|
||||
textAlignment = "Ailíniú Téacs"
|
||||
noteIcon = "Deilbhín Nóta"
|
||||
imagePreview = "Réamhamharc"
|
||||
contents = "Téacs"
|
||||
backgroundColor = "Dath an chúlra"
|
||||
clearBackground = "Bain an cúlra"
|
||||
noBackground = "Gan chúlra"
|
||||
stampSettings = "Socruithe Stampa"
|
||||
savingCopy = "Ag ullmhú íoslódáil..."
|
||||
saveFailed = "Ní féidir cóip a shábháil"
|
||||
saveReady = "Íoslódáil réidh"
|
||||
selectAndMove = "Roghnaigh agus Cuir in Eagar"
|
||||
editSelectDescription = "Cliceáil ar nóta atá ann cheana féin chun a dhath, a theimhneacht, a théacs nó a mhéid a chur in eagar."
|
||||
editStampHint = "Chun an íomhá a athrú, scrios an stampa seo agus cuir ceann nua leis."
|
||||
editSwitchToSelect = "Athraigh go Roghnaigh agus Cuir in Eagar chun an nóta seo a chur in eagar."
|
||||
undo = "Cealaigh"
|
||||
redo = "Athdhéan"
|
||||
applyChanges = "Cuir Athruithe i bhFeidhm"
|
||||
saveChanges = "Sábháil Athruithe"
|
||||
|
||||
[search]
|
||||
@@ -4038,12 +4245,20 @@ settings = "Socruí"
|
||||
adminSettings = "Socruí riar."
|
||||
allTools = "All Tools"
|
||||
reader = "Léamh"
|
||||
tours = "Turais"
|
||||
showMeAround = "Taispeáin dom timpeall"
|
||||
|
||||
[quickAccess.toursTooltip]
|
||||
admin = "Féach ar na treoracha anseo: Turas uirlisí, turas leagan amach nua V2, agus turas an Riarthóra."
|
||||
user = "Féach ar na treoracha anseo: Turas uirlisí agus turas leagan amach an V2 nua."
|
||||
|
||||
[quickAccess.helpMenu]
|
||||
toolsTour = "Turas na nUirlisí"
|
||||
toolsTourDesc = "Faigh amach cad is féidir leis na huirlisí a dhéanamh"
|
||||
adminTour = "Turas an Riarthóra"
|
||||
adminTourDesc = "Déan iniúchadh ar shocruithe agus gnéithe an riarthóra"
|
||||
whatsNewTour = "Féach cad atá nua i V2"
|
||||
whatsNewTourDesc = "Tabhair cuairt ar an leagan amach nuashonraithe"
|
||||
|
||||
[admin]
|
||||
error = "Earráid"
|
||||
@@ -4185,6 +4400,13 @@ description = "Conair chuig inrite WeasyPrint le haghaidh tiontaithe HTML go PDF
|
||||
label = "Inrite Unoconvert"
|
||||
description = "Conair chuig LibreOffice unoconvert le haghaidh tiontaithe doiciméad (fág folamh don réamhshocrú: /opt/venv/bin/unoconvert)"
|
||||
|
||||
[admin.settings.general.frontendUrl]
|
||||
label = "URL tosaigh"
|
||||
description = "URL bunúsach don tosaigh (m.sh., https://pdf.example.com). Úsáidtear é le haghaidh naisc cuireadh ríomhphoist agus uaslódálacha cóid QR soghluaiste. Fág folamh chun URL cúil a úsáid."
|
||||
|
||||
[admin.settings.badge]
|
||||
clickToUpgrade = "Cliceáil chun sonraí an phlean a fheiceáil"
|
||||
|
||||
[admin.settings.security]
|
||||
title = "Slándáil"
|
||||
description = "Cumraigh fíordheimhniú, iompar logála isteach, agus polasaithe slándála."
|
||||
@@ -4192,7 +4414,7 @@ authentication = "Fíordheimhniú"
|
||||
|
||||
[admin.settings.security.ssoNotice]
|
||||
title = "An bhfuil tú ag lorg socruithe SSO/SAML?"
|
||||
message = "Aistríodh soláthraithe fíordheimhnithe OAuth2 agus SAML2 go dtí an roghchlár Connections ar mhaithe le bainistíocht níos éasca."
|
||||
message = "Tá soláthraithe fíordheimhnithe OAuth2 agus SAML2 bogtha go dtí an roghchlár Naisc le haghaidh bainistíocht níos éasca."
|
||||
|
||||
[admin.settings.security.enableLogin]
|
||||
label = "Cumasaigh Logáil Isteach"
|
||||
@@ -4364,7 +4586,7 @@ description = "Cosc ar chlárú úsáideoirí nua trí OAuth2"
|
||||
|
||||
[admin.settings.connections.oauth2.scopes]
|
||||
label = "Scóipeanna OAuth2"
|
||||
description = "Liosta scartha le camóga de scóipeanna OAuth2 le hiarraidh (m.sh., openid, profile, email)"
|
||||
description = "Liosta scartha le camóga de raonta OAuth2 le hiarraidh (m.sh., openid, próifíl, ríomhphost)"
|
||||
|
||||
[admin.settings.connections.saml2]
|
||||
label = "SAML2"
|
||||
@@ -4389,6 +4611,13 @@ description = "Cruthaigh cuntais úsáideora go huathoibríoch ar an gcéad log
|
||||
label = "Cuir Clárú ar Chosc"
|
||||
description = "Cosc ar chlárú úsáideoirí nua trí SAML2"
|
||||
|
||||
[admin.settings.connections.mobileScanner]
|
||||
description = "Ceadaigh d’úsáideoirí comhaid a uaslódáil ó ghléasanna soghluaiste trí chód QR a scanadh"
|
||||
enable = "Cumasaigh Uaslódáil Cód QR"
|
||||
label = "Uaslódáil Fón Póca"
|
||||
link = "Cumraigh i Socruithe an Chórais"
|
||||
note = "Nóta: Éilíonn sé go mbeidh URL an Tosaigh cumraithe."
|
||||
|
||||
[admin.settings.database]
|
||||
title = "Bunachar Sonraí"
|
||||
description = "Cumraigh socruithe ceangail bunachair shonraí saincheaptha le haghaidh imscaradh fiontraíochta."
|
||||
@@ -4517,10 +4746,10 @@ description = "Cumraigh teorainneacha seisiúin agus teorainneacha ama do gach f
|
||||
libreOffice = "LibreOffice"
|
||||
pdfToHtml = "PDF go HTML"
|
||||
qpdf = "QPDF"
|
||||
tesseract = "Tesseract OCR"
|
||||
tesseract = "OCR Tesseract"
|
||||
pythonOpenCv = "Python OpenCV"
|
||||
weasyPrint = "WeasyPrint"
|
||||
installApp = "Suiteáil App"
|
||||
installApp = "Suiteáil Aop"
|
||||
calibre = "Calibre"
|
||||
ghostscript = "Ghostscript"
|
||||
ocrMyPdf = "OCRmyPDF"
|
||||
@@ -4570,6 +4799,10 @@ description = "Ceadaigh do riarthóirí úsáideoirí a thabhairt cuireadh trí
|
||||
label = "URL an Tosaigh"
|
||||
description = "Bun‑URL don tosaigh (m.sh. https://pdf.example.com). Úsáidtear é chun naisc chuireadh a ghiniúint i ríomhphoist. Fág folamh chun URL an chúlchórais a úsáid."
|
||||
|
||||
[admin.settings.mail.frontendUrlNote]
|
||||
link = "Cumraigh i Socruithe an Chórais"
|
||||
note = "Nóta: Éilíonn sé go mbeidh URL an Tosaigh cumraithe. "
|
||||
|
||||
[admin.settings.legal]
|
||||
title = "Doiciméid Dhlíthiúla"
|
||||
description = "Cumraigh naisc le doiciméid agus polasaithe dlíthiúla."
|
||||
@@ -4636,6 +4869,7 @@ title = "Ceadúnas Gníomhach"
|
||||
file = "Foinse: Comhad ceadúnais ({{path}})"
|
||||
key = "Foinse: Eochair ceadúnais"
|
||||
type = "Cineál: {{type}}"
|
||||
|
||||
noInput = "Tabhair eochair ceadúnais nó uaslódáil comhad teastais, le do thoil"
|
||||
success = "Rath"
|
||||
|
||||
@@ -4653,11 +4887,11 @@ description = "Cumraigh gnéithe roghnacha agus feidhmiúlacht."
|
||||
|
||||
[admin.settings.features.serverCertificate]
|
||||
label = "Deimhniú Freastalaí"
|
||||
description = "Cumraigh giniúint deimhnithe ar thaobh an fhreastalaí don fheidhmiúlacht \"Sign with Stirling-PDF\""
|
||||
description = "Cumraigh giniúint deimhnithe ar thaobh an fhreastalaí don fheidhmiúlacht \"Sínigh le Stirling-PDF\""
|
||||
|
||||
[admin.settings.features.serverCertificate.enabled]
|
||||
label = "Cumasaigh Deimhniú Freastalaí"
|
||||
description = "Cumasaigh deimhniú taobh an fhreastalaí don rogha \"Sign with Stirling-PDF\""
|
||||
description = "Cumasaigh deimhniú taobh an fhreastalaí don rogha \"Sínigh le Stirling-PDF\""
|
||||
|
||||
[admin.settings.features.serverCertificate.organizationName]
|
||||
label = "Ainm Eagraíochta"
|
||||
@@ -4682,8 +4916,8 @@ label = "Críochphointí Díchumasaithe"
|
||||
description = "Roghnaigh críochphointí aonair le díchumasú"
|
||||
|
||||
[admin.settings.endpoints.groupsToRemove]
|
||||
label = "Grúpaí Críochphointí Díchumasaithe"
|
||||
description = "Roghnaigh grúpaí críochphointí le díchumasú"
|
||||
label = "Grúpaí Deireadhphointe Díchumasaithe"
|
||||
description = "Roghnaigh grúpaí críochphointe le díchumasú"
|
||||
|
||||
[fileUpload]
|
||||
selectFile = "Roghnaigh comhad"
|
||||
@@ -4696,7 +4930,7 @@ loadFromStorage = "Luchtaigh ón Stóráil"
|
||||
filesAvailable = "comhaid ar fáil"
|
||||
loading = "Á lódáil..."
|
||||
or = "nó"
|
||||
dropFileHere = "Scaoil an comhad anseo nó cliceáil chun uaslódáil"
|
||||
dropFileHere = "Scaoil comhad anseo nó cliceáil chun é a uaslódáil"
|
||||
dropFilesHere = "Scaoil comhaid anseo nó cliceáil an cnaipe uaslódála"
|
||||
dropFilesHereOpen = "Scaoil comhaid anseo nó cliceáil an cnaipe Oscail"
|
||||
pdfFilesOnly = "Comhaid PDF amháin"
|
||||
@@ -4750,10 +4984,12 @@ searchFiles = "Cuardaigh comhaid..."
|
||||
recent = "Le Déanaí"
|
||||
localFiles = "Comhaid Logánta"
|
||||
googleDrive = "Google Drive"
|
||||
googleDriveShort = "Drive"
|
||||
googleDriveShort = "Tiomáint"
|
||||
myFiles = "Mo Chomhaid"
|
||||
noRecentFiles = "Níor aimsíodh comhaid le déanaí"
|
||||
googleDriveNotAvailable = "Níl comhtháthú Google Drive ar fáil"
|
||||
mobileUpload = "Uaslódáil Soghluaiste"
|
||||
mobileShort = "Soghluaiste"
|
||||
downloadSelected = "Íoslódáil Roghnaithe"
|
||||
saveSelected = "Sábháil Roghnaithe"
|
||||
openFiles = "Oscail Comhaid"
|
||||
@@ -5069,6 +5305,7 @@ loading = "Á lódáil..."
|
||||
back = "Siar"
|
||||
continue = "Lean ar aghaidh"
|
||||
error = "Earráid"
|
||||
save = "Sábháil"
|
||||
|
||||
[config.overview]
|
||||
title = "Cumraíocht an Fheidhmchláir"
|
||||
@@ -5211,7 +5448,7 @@ noSearchResults = "Níor aimsíodh uirlisí"
|
||||
noTools = "Níl aon uirlisí ar fáil"
|
||||
|
||||
[onboarding]
|
||||
allTools = "This is the <strong>All Tools</strong> panel, where you can browse and select from all available PDF tools."
|
||||
allTools = "Seo é an painéal <strong>Gach Uirlis</strong>, áit ar féidir leat brabhsáil agus roghnú astu na huirlisí PDF uile atá ar fáil."
|
||||
selectCropTool = "Roghnaímis an uirlis <strong>Bearradh</strong> chun a léiriú conas ceann de na huirlisí a úsáid."
|
||||
toolInterface = "Seo comhéadan na huirlise <strong>Bearradh</strong>. Mar a fheiceann tú, níl mórán ann fós mar nár chuir muid aon chomhaid PDF leis le hoibriú leo go fóill."
|
||||
filesButton = "Ligeann an cnaipe <strong>Comhaid</strong> ar an mBarra Rochtana Thapa duit PDFanna a uaslódáil chun na huirlisí a úsáid orthu."
|
||||
@@ -5235,6 +5472,16 @@ finish = "Críochnaigh"
|
||||
startTour = "Tosaigh an Turas"
|
||||
startTourDescription = "Téigh ar thuras treoraithe de phríomhghnéithe Stirling PDF"
|
||||
|
||||
[onboarding.whatsNew]
|
||||
quickAccess = "Tosaigh ag an ráille <strong>Rochtain Thapa</strong> chun léim idir Léitheoir, Uathoibriú, do chuid comhad, agus na turais go léir."
|
||||
leftPanel = "Liostaítear gach rud is féidir leat a dhéanamh sa phainéal <strong>Uirlisí</strong> ar chlé. Brabhsáil catagóirí nó déan cuardach chun uirlis a aimsiú go tapa."
|
||||
fileUpload = "Úsáid an cnaipe <strong>Comhaid</strong> chun PDF le déanaí a uaslódáil nó a roghnú. Lódálfaimid sampla ionas gur féidir leat an spás oibre a fheiceáil."
|
||||
rightRail = "Tá gníomhartha tapa ar an <strong>Ráille Deas</strong> chun comhaid a roghnú, téama nó teanga a athrú, agus torthaí a íoslódáil."
|
||||
topBar = "Ligeann an barra uachtarach duit malartú idir <strong>Amharcóir</strong>, <strong>Eagarthóir Leathanaigh</strong>, agus <strong>Comhaid Ghníomhacha</strong>."
|
||||
pageEditorView = "Téigh go dtí an tEagarthóir Leathanach chun leathanaigh a athordú, a rothlú nó a scriosadh."
|
||||
activeFilesView = "Bain úsáid as Comhaid Ghníomhacha chun gach rud atá oscailte agat a fheiceáil agus chun a roghnú cad atá le hoibriú air."
|
||||
wrapUp = "Sin atá nua i V2. Oscail an roghchlár <strong>Turais</strong> am ar bith chun é seo, an turas Uirlisí, nó an turas Riarthóra a athsheinm."
|
||||
|
||||
[onboarding.welcomeModal]
|
||||
title = "Fáilte go Stirling PDF!"
|
||||
description = "Ar mhaith leat turas gasta 1 nóiméad a dhéanamh chun na príomhghnéithe agus conas tosú a fhoghlaim?"
|
||||
@@ -5255,6 +5502,10 @@ download = "Íoslódáil →"
|
||||
showMeAround = "Taispeáin timpeall dom"
|
||||
skipTheTour = "Scipeáil an turas"
|
||||
|
||||
[onboarding.tourOverview]
|
||||
title = "Forbhreathnú ar an Turas"
|
||||
body = "Tagann Stirling PDF V2 le mórán uirlisí agus leagan amach athnuaite. Tabhair cuairt ghearr chun a fheiceáil cad a d'athraigh agus cá háit le fáil na gnéithe atá uait."
|
||||
|
||||
[onboarding.serverLicense]
|
||||
skip = "Scipeáil faoi láthair"
|
||||
seePlans = "Féach ar Phleananna →"
|
||||
@@ -5277,17 +5528,17 @@ adminBodyLoginDisabled = "Nuair a chumasaíonn tú mód logála isteach, is féi
|
||||
userBody = "Tabhair cuireadh do chomhoibrithe, sann róil, agus coinnigh do dhoiciméid eagraithe in aon spás oibre slán amháin. Cumasaigh mód logála isteach aon uair is mian leat dul thar úsáid aonair."
|
||||
|
||||
[onboarding.securityCheck]
|
||||
message = "Rinneadh athruithe suntasacha ar an bhfeidhmchlár le déanaí. D’fhéadfadh aird do riarthóra freastalaí a bheith de dhíth. Deimhnigh do ról le do thoil chun leanúint ar aghaidh."
|
||||
message = "Tá athruithe suntasacha déanta ar an bhfeidhmchlár le déanaí. B’fhéidir go mbeidh aird riarthóir do fhreastalaí ag teastáil. Deimhnigh do ról le leanúint ar aghaidh."
|
||||
|
||||
[adminOnboarding]
|
||||
welcome = "Fáilte go dtí an <strong>Admin Tour</strong>! Déanaimis iniúchadh ar na gnéithe agus na socruithe fiontraíochta cumhachtacha atá ar fáil do riarthóirí córais."
|
||||
configButton = "Cliceáil an cnaipe <strong>Config</strong> chun rochtain a fháil ar gach socrú córais agus rialú riaracháin."
|
||||
welcome = "Fáilte go dtí an <strong>Turas Riaracháin</strong>! Déanaimis iniúchadh ar na gnéithe agus na socruithe cumhachtacha fiontraíochta atá ar fáil do riarthóirí córais."
|
||||
configButton = "Cliceáil an cnaipe <strong>Cumraíocht</strong> chun rochtain a fháil ar shocruithe an chórais agus ar rialuithe riaracháin go léir."
|
||||
settingsOverview = "Seo é an <strong>Painéal Socruithe</strong>. Tá socruithe riaracháin eagraithe de réir catagóire le haghaidh nascleanúna éasca."
|
||||
teamsAndUsers = "Bainistigh <strong>Foirne</strong> agus úsáideoirí aonair anseo. Is féidir leat úsáideoirí nua a thabhairt isteach trí r-phost, naisc inroinnte, nó cuntais shaincheaptha a chruthú dóibh tú féin."
|
||||
systemCustomization = "Tá bealaí fairsinge againn chun an UI a shaincheapadh: ligeann <strong>System Settings</strong> duit ainm agus teangacha an aipe a athrú, cuireann <strong>Features</strong> bainistíocht teastais freastalaí ar fáil, agus ligeann <strong>Endpoints</strong> duit uirlisí áirithe a chumasú nó a dhíchumasú do d’úsáideoirí."
|
||||
systemCustomization = "Tá bealaí fairsinge againn chun an comhéadan úsáideora a shaincheapadh: Ligeann <strong>Socruithe Córais</strong> duit ainm agus teangacha an aip a athrú, ceadaíonn <strong>Gnéithe</strong> bainistíocht teastais freastalaí, agus ligeann <strong>Deireadhphointí</strong> duit uirlisí sonracha a chumasú nó a dhíchumasú do d'úsáideoirí."
|
||||
databaseSection = "Le haghaidh timpeallachtaí táirgthe ardleibhéil, tá socruithe againn chun <strong>nascanna le bunachair shonraí sheachtracha</strong> a chumasú ionas gur féidir leat comhtháthú le d’infreastruchtúr atá ann cheana."
|
||||
connectionsSection = "Tacaíonn an rannán <strong>Connections</strong> le modhanna logála isteach éagsúla lena n-áirítear SSO saincheaptha agus soláthraithe SAML ar nós Google agus GitHub, móide comhtháthuithe ríomhphoist le haghaidh fógraí agus cumarsáide."
|
||||
adminTools = "Ar deireadh, tá uirlisí riaracháin ardleibhéil againn mar <strong>Auditing</strong> chun gníomhaíocht chórais a rianú agus <strong>Usage Analytics</strong> chun monatóireacht a dhéanamh ar conas a idirghníomhaíonn d’úsáideoirí leis an ardán."
|
||||
adminTools = "Ar deireadh, tá uirlisí riaracháin ardleibhéil againn ar nós <strong>Iniúchadh</strong> chun gníomhaíocht chórais a rianú agus <strong>Anailísíocht Úsáide</strong> chun monatóireacht a dhéanamh ar an gcaoi a n-idirghníomhaíonn d'úsáideoirí leis an ardán."
|
||||
wrapUp = "Sin é an turas riaracháin! Chonaic tú na gnéithe fiontraíochta a dhéanann Stirling PDF ina réiteach cumhachtach, saincheaptha d’eagraíochtaí. Is féidir an turas seo a rochtain am ar bith ón roghchlár <strong>Cabhair</strong>."
|
||||
|
||||
[workspace]
|
||||
@@ -5334,7 +5585,7 @@ user = "Úsáideoir"
|
||||
[workspace.people.addMember]
|
||||
title = "Cuir Ball Leis"
|
||||
username = "Ainm Úsáideora (R-phost)"
|
||||
usernamePlaceholder = "user@example.com"
|
||||
usernamePlaceholder = "úsáideoir@sampla.com"
|
||||
password = "Focal Faire"
|
||||
passwordPlaceholder = "Cuir isteach focal faire"
|
||||
role = "Ról"
|
||||
@@ -5396,7 +5647,7 @@ error = "Níor éirigh le focal faire a nuashonrú"
|
||||
tab = "Cuireadh Ríomhphoist"
|
||||
description = "Clóscríobh nó greamaigh seoltaí ríomhphoist thíos, scartha le camóga. Gheobhaidh úsáideoirí dintiúir logála isteach trí r-phost."
|
||||
emails = "Seoltaí Ríomhphoist"
|
||||
emailsPlaceholder = "user1@example.com, user2@example.com"
|
||||
emailsPlaceholder = "úsáideoir1@sampla.com, úsáideoir2@sampla.com"
|
||||
emailsRequired = "Tá ar a laghad seoladh ríomhphoist amháin de dhíth"
|
||||
submit = "Seol Cuirí"
|
||||
success = "Tugadh cuireadh d’úsáideoir(í) go rathúil"
|
||||
@@ -5568,6 +5819,28 @@ contactSales = "Déan Teagmháil le Díolacháin"
|
||||
contactToUpgrade = "Déan teagmháil linn chun do phlean a uasghrádú nó a shaincheapadh"
|
||||
maxUsers = "Uaslíon Úsáideoirí"
|
||||
upTo = "Suas le"
|
||||
getLicense = "Faigh Ceadúnas Freastalaí"
|
||||
upgradeToEnterprise = "Uasghrádú go Fiontar"
|
||||
selectPeriod = "Roghnaigh Tréimhse Billeála"
|
||||
monthlyBilling = "Billeáil Mhíosúil"
|
||||
yearlyBilling = "Billeáil Bhliantúil"
|
||||
checkoutOpened = "Seiceáil Oscailte"
|
||||
checkoutInstructions = "Críochnaigh do cheannachán sa chluaisín Stripe. Tar éis íocaíochta, fill ar ais anseo agus athnuachan an leathanach chun do cheadúnas a ghníomhachtú. Gheobhaidh tú ríomhphost le d’eochair cheadúnais freisin."
|
||||
activateLicense = "Gníomhachtaigh Do Cheadúnas"
|
||||
|
||||
[plan.static.licenseActivation]
|
||||
checkoutOpened = "Seiceáil Oscailte i gCluaisín Nua"
|
||||
instructions = "Comhlánaigh do cheannachán sa chluaisín Stripe. Nuair a bheidh d’íocaíocht críochnaithe, gheobhaidh tú ríomhphost le d’eochair cheadúnais."
|
||||
enterKey = "Cuir isteach d’eochair cheadúnais thíos chun do phlean a ghníomhachtú:"
|
||||
keyDescription = "Greamaigh an eochair cheadúnais ó do ríomhphost"
|
||||
activate = "Gníomhachtaigh an Ceadúnas"
|
||||
doLater = "Déanfaidh mé é seo níos déanaí"
|
||||
success = "Ceadúnas Gníomhachtaithe!"
|
||||
successMessage = "Tá do cheadúnas gníomhachtaithe go rathúil. Is féidir leat an fhuinneog seo a dhúnadh anois."
|
||||
|
||||
[plan.static.billingPortal]
|
||||
title = "Fíorú Ríomhphoist Riachtanach"
|
||||
message = "Beidh ort do sheoladh ríomhphoist a fhíorú i dtairseach billeála Stripe. Seiceáil do ríomhphost le haghaidh nasc logála isteach."
|
||||
|
||||
[plan.period]
|
||||
month = "mí"
|
||||
@@ -5588,12 +5861,12 @@ highlight2 = "Uirlisí PDF Casta"
|
||||
highlight3 = "Gan comharthaí uisce"
|
||||
|
||||
[plan.enterprise]
|
||||
name = "Enterprise"
|
||||
name = "Fiontar"
|
||||
highlight1 = "Praghsáil shaincheaptha"
|
||||
highlight2 = "Tacaíocht thiomnaithe"
|
||||
highlight3 = "Na gnéithe is déanaí"
|
||||
requiresServer = "Teastaíonn Freastalaí"
|
||||
requiresServerMessage = "Uasghrádaigh go dtí an plean Freastalaí ar dtús sula n-uasghrádaíonn tú go Enterprise."
|
||||
requiresServerMessage = "Uasghrádaigh go dtí an plean Freastalaí ar dtús sula n-uasghrádaíonn tú go Fiontraíochta."
|
||||
|
||||
[plan.feature]
|
||||
title = "Gné"
|
||||
@@ -5625,7 +5898,7 @@ none = "Gan Síntiús"
|
||||
[billing]
|
||||
manageBilling = "Bainistigh Billeáil"
|
||||
updateSeats = "Nuashonraigh Suíocháin"
|
||||
updateEnterpriseSeats = "Nuashonraigh Suíocháin Enterprise"
|
||||
updateEnterpriseSeats = "Nuashonraigh Suíocháin Fiontraíochta"
|
||||
currentSeats = "Suíocháin Reatha"
|
||||
minimumSeats = "Íosmhéid Suíochán"
|
||||
basedOnUsers = "(úsáideoirí reatha)"
|
||||
@@ -5657,7 +5930,7 @@ seeInfo = "Féach eolas"
|
||||
|
||||
[payment]
|
||||
preparing = "Do sheiceáil amach á ullmhú..."
|
||||
redirecting = "Ag atreorú chuig checkout slán..."
|
||||
redirecting = "Ag atreorú chuig an tseiceáil amach slán..."
|
||||
upgradeTitle = "Uasghrádaigh go {{planName}}"
|
||||
success = "D’éirigh leis an Íocaíocht!"
|
||||
successMessage = "Gníomhachtaíodh do shíntiús go rathúil. Gheobhaidh tú ríomhphost dearbhaithe go luath."
|
||||
@@ -5696,7 +5969,7 @@ emailInvalid = "Cuir isteach seoladh ríomhphoist bailí"
|
||||
title = "Cuir isteach do Ríomhphost"
|
||||
description = "Úsáidfimid é seo chun d’eochair cheadúnais agus admhálacha a sheoladh."
|
||||
emailLabel = "Seoladh Ríomhphoist"
|
||||
emailPlaceholder = "your@email.com"
|
||||
emailPlaceholder = "do@ríomhphost.com"
|
||||
continue = "Lean ar aghaidh"
|
||||
modalTitle = "Tosaigh - {{planName}}"
|
||||
|
||||
@@ -5771,6 +6044,8 @@ notAvailable = "Níl an córas iniúchta ar fáil"
|
||||
notAvailableMessage = "Níl an córas iniúchta cumraithe nó níl sé ar fáil."
|
||||
disabled = "Tá logáil iniúchta díchumasaithe"
|
||||
disabledMessage = "Cumasaigh logáil iniúchta i gcumraíocht d’fheidhmchláir chun imeachtaí an chórais a rianú."
|
||||
enterpriseRequired = "Ceadúnas Fiontraíochta Riachtanach"
|
||||
enterpriseRequiredMessage = "Is gné fiontraíochta é an córas logála iniúchóireachta. Uasghrádaigh go ceadúnas fiontraíochta le rochtain a fháil ar logaí iniúchóireachta agus anailísíocht."
|
||||
|
||||
[audit.error]
|
||||
title = "Earráid agus an córas iniúchta á lódáil"
|
||||
@@ -6025,6 +6300,8 @@ reset = "Athshocraigh Athruithe"
|
||||
downloadJson = "Íoslódáil JSON"
|
||||
generatePdf = "Gin PDF"
|
||||
saveChanges = "Sábháil Athruithe"
|
||||
applyChanges = "Cuir Athruithe i bhFeidhm"
|
||||
downloadCopy = "Íoslódáil Cóip"
|
||||
|
||||
[pdfTextEditor.options.autoScaleText]
|
||||
title = "Scálaigh téacs go huathoibríoch chun boscaí a fheistiú"
|
||||
@@ -6043,6 +6320,24 @@ descriptionInline = "Leid: Coinnigh Ctrl (Cmd) nó Shift chun boscaí téacs a r
|
||||
title = "Glasáil téacs curtha in eagar le heilimint PDF aonair"
|
||||
description = "Nuair atá cumasaithe, easpórtálann an t-eagarthóir gach bosca téacs curtha in eagar mar eilimint téacs PDF amháin chun glifaí forluiteacha nó clónna measctha a sheachaint."
|
||||
|
||||
[pdfTextEditor.options.advanced]
|
||||
title = "Socruithe Ardleibhéil"
|
||||
|
||||
[pdfTextEditor.tooltip.header]
|
||||
title = "Teorainneacha Réamhamhairc"
|
||||
|
||||
[pdfTextEditor.tooltip.textFocus]
|
||||
title = "Fócas Téacs agus Íomhá"
|
||||
text = "Díríonn an spás oibre seo ar théacs a chur in eagar agus íomhánna leabaithe a athshuíomh. Coinnítear saothar ealaíne leathanaigh casta, giuirléidí foirmeacha, agus grafaicí srathacha le haghaidh onnmhairithe ach ní féidir iad a chur in eagar go hiomlán anseo."
|
||||
|
||||
[pdfTextEditor.tooltip.previewVariance]
|
||||
title = "Réamhamharc ar an Éagsúlacht"
|
||||
text = "B’fhéidir nach dtaispeánfar roinnt amharcléirithe (amhail teorainneacha tábla, cruthanna, nó cuma anótála) go díreach sa réamhamharc. Coinníonn an PDF easpórtáilte na horduithe líníochta bunaidh aon uair is féidir."
|
||||
|
||||
[pdfTextEditor.tooltip.alpha]
|
||||
title = "Amharcóir Alfa"
|
||||
text = "Tá an breathnóir alfa seo fós ag forbairt—d’fhéadfadh clónna, dathanna, éifeachtaí trédhearcachta agus sonraí leagan amach áirithe athrú beagán. Déan seiceáil dhúbailte ar an PDF ginte sula roinneann tú é."
|
||||
|
||||
[pdfTextEditor.manual]
|
||||
mergeTooltip = "Cumaisc na boscaí roghnaithe"
|
||||
merge = "Cumaisc an roghnú"
|
||||
@@ -6079,10 +6374,10 @@ notIdealFor2 = "Irisí, bróisiúir, nó doiciméid le dearadh trom"
|
||||
notIdealFor3 = "Lámhleabhair treoracha le leagan amach casta"
|
||||
limitations = "Teorainneacha Reatha:"
|
||||
limitation1 = "Féadfaidh rindreáil cló a bheith beagán difriúil ón PDF bunaidh"
|
||||
limitation2 = "Caomhnaítear grafaicí casta, réimsí foirme agus anótálacha ach ní féidir iad a chur in eagar"
|
||||
limitation3 = "D’fhéadfadh go dtógfadh tiontú agus próiseáil comhaid mhóra tamall"
|
||||
knownIssues = "Fadhbanna Aitheanta (Á Socrú):"
|
||||
issue1 = "Ní chaomhnaítear dath téacs faoi láthair (cuirfear leis go luath)"
|
||||
limitation2 = "Coinnítear grafaicí casta, réimsí foirme agus nótaí ach ní féidir iad a chur in eagar"
|
||||
limitation3 = "D’fhéadfadh sé go dtógfadh sé tamall comhaid mhóra a thiontú agus a phróiseáil"
|
||||
knownIssues = "Fadhbanna Aitheanta (Á Réiteach):"
|
||||
issue1 = "Níl dath an téacs caomhnaithe faoi láthair (cuirfear leis go luath é)"
|
||||
issue2 = "Tá níos mó saincheisteanna ailínithe agus spásála i Mód Míre — moltar Mód Líne Aonair"
|
||||
issue3 = "Tá an réamhamharc difriúil ón PDF easpórtáilte — tá PDFanna easpórtáilte níos gaire don bhunleagan"
|
||||
issue4 = "D’fhéadfadh go mbeadh coigeartú láimhe de dhíth ar ailíniú téacs rothlaithe"
|
||||
@@ -6164,3 +6459,56 @@ title = "Torthaí Cur Téacs"
|
||||
|
||||
[addText.error]
|
||||
failed = "Tharla earráid agus téacs á chur leis an PDF."
|
||||
|
||||
[mobileUpload]
|
||||
title = "Uaslódáil ó Shoghluaiste"
|
||||
description = "Scan an cód QR seo le do ghléas soghluaiste chun grianghraif a uaslódáil go díreach chuig an leathanach seo."
|
||||
error = "Earráid Ceangail"
|
||||
pollingError = "Earráid ag seiceáil comhad"
|
||||
sessionId = "Aitheantas Seisiúin"
|
||||
sessionCreateError = "Theip ar chruthú seisiúin"
|
||||
expiryWarning = "Seisiún ag Dul in Éag go Luath"
|
||||
expiryWarningMessage = "Rachaidh an cód QR seo in éag i {{seconds}} soicind. Ginfear cód nua go huathoibríoch."
|
||||
filesReceived = "{{count}} comhad(anna) faighte"
|
||||
connected = "Gléas soghluaiste ceangailte"
|
||||
instructions = "Oscail an aip ceamara ar do ghuthán agus scan an cód seo. Aistreofar comhaid go díreach idir gléasanna."
|
||||
|
||||
[mobileScanner]
|
||||
title = "Scanóir Soghluaiste"
|
||||
noSession = "Seisiún Neamhbhailí"
|
||||
noSessionMessage = "Scanáil cód QR bailí le do thoil chun rochtain a fháil ar an leathanach seo."
|
||||
validating = "Ag bailíochtú an tseisiúin..."
|
||||
sessionInvalid = "Earráid Seisiúin"
|
||||
sessionExpired = "Tá an seisiún seo imithe in éag. Athnuachan agus déan iarracht arís."
|
||||
sessionNotFound = "Níor aimsíodh an seisiún. Athnuachan agus déan iarracht arís."
|
||||
sessionValidationError = "Ní féidir an seisiún a fhíorú. Déan iarracht arís."
|
||||
uploadSuccess = "Uaslódáil Rathúil!"
|
||||
uploadSuccessMessage = "Tá do chuid íomhánna aistrithe."
|
||||
httpsRequired = "Éilíonn rochtain ceamara HTTPS nó localhost. Bain úsáid as HTTPS nó rochtain trí localhost."
|
||||
uploadFailed = "Theip ar an uaslódáil. Déan iarracht arís."
|
||||
uploading = "Ag uaslódáil..."
|
||||
connected = "Ceangailte"
|
||||
connecting = "Ag ceangal..."
|
||||
chooseMethod = "Roghnaigh Modh Uaslódála"
|
||||
chooseMethodDescription = "Roghnaigh conas is mian leat doiciméid a scanadh agus a uaslódáil"
|
||||
camera = "Ceamara"
|
||||
cameraDescription = "Scan doiciméid ag baint úsáide as ceamara do ghléis le braiteadh imeall uathoibríoch"
|
||||
fileUpload = "Uaslódáil Comhad"
|
||||
fileDescription = "Uaslódáil grianghraif nó doiciméid atá ann cheana féin ó do ghléas"
|
||||
cameraAccessDenied = "Diúltaíodh rochtain ceamara. Cumasaigh rochtain ceamara le do thoil."
|
||||
back= "Ar ais"
|
||||
settings = "Socruithe"
|
||||
edgeDetection = "Braith Imeall"
|
||||
flashlight = "Splanc"
|
||||
flash = "Splanc"
|
||||
processing = "Ag Próiseáil..."
|
||||
capture = "Gabh Grianghraf"
|
||||
selectFilesPrompt = "Roghnaigh comhaid le huaslódáil"
|
||||
selectImage = "Roghnaigh Íomhá"
|
||||
preview = "Réamhamharc"
|
||||
retake = "Athghlac"
|
||||
addToBatch = "Cuir le Baisc"
|
||||
upload = "Uaslódáil"
|
||||
batchImages = "Baisc"
|
||||
clearBatch = "Glan"
|
||||
uploadAll = "Uaslódáil Gach Rud"
|
||||
|
||||
+2
-2
@@ -132,9 +132,9 @@
|
||||
|
||||
/**
|
||||
* Extracts and undistorts the image detected within the frame.
|
||||
*
|
||||
*
|
||||
* Returns `null` if no paper is detected.
|
||||
*
|
||||
*
|
||||
* @param {*} image image to process
|
||||
* @param {*} resultWidth desired result paper width
|
||||
* @param {*} resultHeight desired result paper height
|
||||
|
||||
+2
-3
@@ -20,7 +20,7 @@
|
||||
root.cv = factory();
|
||||
}
|
||||
}(this, function () {
|
||||
|
||||
|
||||
var cv = (function() {
|
||||
var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined;
|
||||
return (
|
||||
@@ -40,9 +40,8 @@ if (typeof exports === 'object' && typeof module === 'object')
|
||||
define([], function() { return cv; });
|
||||
else if (typeof exports === 'object')
|
||||
exports["cv"] = cv;
|
||||
|
||||
|
||||
if (typeof Module === 'undefined')
|
||||
Module = {};
|
||||
return cv(Module);
|
||||
}));
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user