diff --git a/.gitattributes b/.gitattributes
deleted file mode 100644
index a51c0517..00000000
--- a/.gitattributes
+++ /dev/null
@@ -1,5 +0,0 @@
-# Ignore all JavaScript files in a directory
-src/main/resources/static/pdfjs/* linguist-vendored
-src/main/resources/static/css/bootstrap-icons.css linguist-vendored
-src/main/resources/static/css/bootstrap.min.css linguist-vendored
-src/main/resources/static/css/fonts/* linguist-vendored
diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml
deleted file mode 100644
index 30a5ce23..00000000
--- a/.github/FUNDING.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-# These are supported funding model platforms
-
-github: Frooodle # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
-patreon: # Replace with a single Patreon username
-open_collective: # Replace with a single Open Collective username
-ko_fi: # Replace with a single Ko-fi username
-tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
-community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
-liberapay: # Replace with a single Liberapay username
-issuehunt: # Replace with a single IssueHunt username
-otechie: # Replace with a single Otechie username
-lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
-custom: ['https://paypal.me/froodleplex?country.x=GB&locale.x=en_GB'] # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
deleted file mode 100644
index a35c2aa1..00000000
--- a/.github/dependabot.yml
+++ /dev/null
@@ -1,11 +0,0 @@
-# To get started with Dependabot version updates, you'll need to specify which
-# package ecosystems to update and where the package manifests are located.
-# Please see the documentation for all configuration options:
-# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
-
-version: 2
-updates:
- - package-ecosystem: "gradle" # See documentation for possible values
- directory: "/" # Location of package manifests
- schedule:
- interval: "weekly"
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
deleted file mode 100644
index e73caa3f..00000000
--- a/.github/pull_request_template.md
+++ /dev/null
@@ -1,4 +0,0 @@
-# License Agreement for Contributions
-By submitting this pull request, I acknowledge and agree that my contributions will be included in Stirling-PDF and that they can be relicensed in the future under MPL 2.0 (Mozilla Public License Version 2.0) license.
-
-(This does not change the general open-source nature of Stirling-PDF, simply moving from one license to another license)
diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml
deleted file mode 100644
index 55500892..00000000
--- a/.github/workflows/codeql.yml
+++ /dev/null
@@ -1,55 +0,0 @@
-# For most projects, this workflow file will not need changing; you simply need
-# to commit it to your repository.
-#
-# You may wish to alter this file to override the set of languages analyzed,
-# or to provide custom queries or build logic.
-#
-# ******** NOTE ********
-# We have attempted to detect the languages in your repository. Please check
-# the `language` matrix defined below to confirm you have the correct set of
-
-name: "Build repo"
-
-on:
- push:
- branches: [ "main" ]
- pull_request:
- # The branches below must be a subset of the branches above
- branches: [ "main" ]
- schedule:
- - cron: '15 12 * * 1'
-
-jobs:
- analyze:
- name: Analyze
- runs-on: ubuntu-latest
- permissions:
- actions: read
- contents: read
- security-events: write
-
- strategy:
- fail-fast: false
-
- steps:
- - name: Checkout repository
- uses: actions/checkout@v3
-
- - name: Set up JDK 17
- uses: actions/setup-java@v3
- with:
- java-version: '17'
- distribution: 'temurin'
-
- # - name: Initialize CodeQL
- # uses: github/codeql-action/init@v2
- # with:
- # languages: java
-
- - uses: gradle/gradle-build-action@v2.4.2
- with:
- gradle-version: 7.6
- arguments: assemble --no-build-cache
-
- #- name: Perform CodeQL analysis
- # uses: github/codeql-action/analyze@v2
diff --git a/.github/workflows/pull_request_template.md b/.github/workflows/pull_request_template.md
deleted file mode 100644
index bc8f5d04..00000000
--- a/.github/workflows/pull_request_template.md
+++ /dev/null
@@ -1,3 +0,0 @@
-# License Agreement for Contributions
-By submitting this pull request, I acknowledge and agree that my contributions will be included in Stirling-PDF and that they can be relicensed in the future under MPL 2.0 (Mozilla Public License Version 2.0) license.
-(This does not change the open-source nature of Stirling-PDF, simply moving from one license to another license)
diff --git a/.github/workflows/push-docker.yml b/.github/workflows/push-docker.yml
deleted file mode 100644
index 50d03bcc..00000000
--- a/.github/workflows/push-docker.yml
+++ /dev/null
@@ -1,142 +0,0 @@
-name: Push Docker Image with VersionNumber
-
-on:
- workflow_dispatch:
- push:
- branches:
- - master
- - main
-jobs:
- push:
- runs-on: ubuntu-latest
- steps:
-
- - uses: actions/checkout@v3.5.2
-
- - name: Set up JDK 17
- uses: actions/setup-java@v3.11.0
- with:
- java-version: '17'
- distribution: 'temurin'
-
-
- - uses: gradle/gradle-build-action@v2.4.2
- env:
- DOCKER_ENABLE_SECURITY: false
- with:
- gradle-version: 7.6
- arguments: clean build
-
- - name: Make Gradle wrapper executable
- run: chmod +x gradlew
-
- - name: Get version number
- id: versionNumber
- run: echo "::set-output name=versionNumber::$(./gradlew printVersion --quiet | tail -1)"
-
- - name: Login to Docker Hub
- uses: docker/login-action@v2.1.0
- with:
- username: ${{ secrets.DOCKER_HUB_USERNAME }}
- password: ${{ secrets.DOCKER_HUB_API }}
-
- - name: Login to GitHub Container Registry
- uses: docker/login-action@v2.1.0
- with:
- registry: ghcr.io
- username: ${{ github.actor }}
- password: ${{ github.token }}
-
- - name: Convert repository owner to lowercase
- id: repoowner
- run: echo "::set-output name=lowercase::$(echo ${{ github.repository_owner }} | awk '{print tolower($0)}')"
-
- - name: Generate tags
- id: meta
- uses: docker/metadata-action@v4.4.0
- with:
- images: |
- ${{ secrets.DOCKER_HUB_USERNAME }}/s-pdf
- ghcr.io/${{ steps.repoowner.outputs.lowercase }}/s-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=alpha,enable=${{ github.ref == 'refs/heads/main' }}
-
- - name: Set up QEMU
- uses: docker/setup-qemu-action@v2.1.0
-
- - name: Set up Docker Buildx
- uses: docker/setup-buildx-action@v2.5.0
-
- - name: Build and push main Dockerfile
- uses: docker/build-push-action@v4.0.0
- with:
- context: .
- dockerfile: ./Dockerfile
- push: true
- cache-from: type=gha
- cache-to: type=gha,mode=max
- tags: ${{ steps.meta.outputs.tags }}
- labels: ${{ steps.meta.outputs.labels }}
- build-args:
- VERSION_TAG=${{ steps.versionNumber.outputs.versionNumber }}
- platforms: linux/amd64,linux/arm64/v8
-
-
-
- - name: Generate tags ultra-lite
- id: meta2
- uses: docker/metadata-action@v4.4.0
- if: github.ref != 'refs/heads/main'
- with:
- images: |
- ${{ secrets.DOCKER_HUB_USERNAME }}/s-pdf
- ghcr.io/${{ steps.repoowner.outputs.lowercase }}/s-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' }}
-
-
- - name: Build and push Dockerfile-ultra-lite
- uses: docker/build-push-action@v4.0.0
- if: github.ref != 'refs/heads/main'
- with:
- context: .
- file: ./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
-
-
-
- - name: Generate tags lite
- id: meta3
- uses: docker/metadata-action@v4.4.0
- if: github.ref != 'refs/heads/main'
- with:
- images: |
- ${{ secrets.DOCKER_HUB_USERNAME }}/s-pdf
- ghcr.io/${{ steps.repoowner.outputs.lowercase }}/s-pdf
- tags: |
- type=raw,value=${{ steps.versionNumber.outputs.versionNumber }}-lite,enable=${{ github.ref == 'refs/heads/master' }}
- type=raw,value=latest-lite,enable=${{ github.ref == 'refs/heads/master' }}
-
-
- - name: Build and push Dockerfile-lite
- uses: docker/build-push-action@v4.0.0
- if: github.ref != 'refs/heads/main'
- with:
- context: .
- file: ./Dockerfile-lite
- push: true
- cache-from: type=gha
- cache-to: type=gha,mode=max
- tags: ${{ steps.meta3.outputs.tags }}
- labels: ${{ steps.meta3.outputs.labels }}
- platforms: linux/amd64,linux/arm64/v8
diff --git a/.github/workflows/releaseArtifacts.yml b/.github/workflows/releaseArtifacts.yml
deleted file mode 100644
index f57aacd4..00000000
--- a/.github/workflows/releaseArtifacts.yml
+++ /dev/null
@@ -1,55 +0,0 @@
-name: Release Artifacts
-
-on:
- release:
- types: [created]
-
-jobs:
- push:
- runs-on: ubuntu-latest
- strategy:
- matrix:
- enable_security: [true, false]
- include:
- - enable_security: true
- file_suffix: '-with-login'
- - enable_security: false
- file_suffix: ''
- steps:
- - uses: actions/checkout@v3.5.2
-
- - name: Set up JDK 17
- uses: actions/setup-java@v3.11.0
- with:
- java-version: '17'
- distribution: 'temurin'
-
- - name: Grant execute permission for gradlew
- run: chmod +x gradlew
-
- - name: Generate jar (With Security=${{ matrix.enable_security }})
- run: ./gradlew clean createExe
- env:
- DOCKER_ENABLE_SECURITY: ${{ matrix.enable_security }}
-
- - name: Upload binaries to release
- uses: svenstaro/upload-release-action@v2
- with:
- repo_token: ${{ secrets.GITHUB_TOKEN }}
- file: ./build/launch4j/Stirling-PDF.exe
- asset_name: Stirling-PDF${{ matrix.file_suffix }}.exe
- tag: ${{ github.ref }}
- overwrite: true
-
- - name: Get version number
- id: versionNumber
- run: echo "::set-output name=versionNumber::$(./gradlew printVersion --quiet | tail -1)"
-
- - name: Upload jar binaries to release
- uses: svenstaro/upload-release-action@v2
- with:
- repo_token: ${{ secrets.GITHUB_TOKEN }}
- file: ./build/libs/Stirling-PDF-${{ steps.versionNumber.outputs.versionNumber }}.jar
- asset_name: Stirling-PDF${{ matrix.file_suffix }}.jar
- tag: ${{ github.ref }}
- overwrite: true
diff --git a/.github/workflows/swagger.yml b/.github/workflows/swagger.yml
deleted file mode 100644
index c1e6774e..00000000
--- a/.github/workflows/swagger.yml
+++ /dev/null
@@ -1,37 +0,0 @@
-name: Update Swagger
-
-on:
- workflow_dispatch:
- push:
- branches:
- - master
-jobs:
- push:
-
- runs-on: ubuntu-latest
- steps:
-
- - uses: actions/checkout@v3.5.2
-
- - name: Set up JDK 17
- uses: actions/setup-java@v3.11.0
- with:
- java-version: '17'
- distribution: 'temurin'
-
- - name: Grant execute permission for gradlew
- run: chmod +x gradlew
-
- - name: Generate Swagger documentation
- run: ./gradlew generateOpenApiDocs
-
- - name: Upload Swagger Documentation to SwaggerHub
- run: ./gradlew swaggerhubUpload
- env:
- SWAGGERHUB_API_KEY: ${{ secrets.SWAGGERHUB_API_KEY }}
-
- - name: Set API version as published and default on SwaggerHub
- run: |
- curl -X PUT -H "Authorization: ${SWAGGERHUB_API_KEY}" "https://api.swaggerhub.com/apis/Frooodle/Stirling-PDF/${{ steps.versionNumber.outputs.versionNumber }}/settings/lifecycle" -H "accept: application/json" -H "Content-Type: application/json" -d "{\"published\":true,\"default\":true}"
- env:
- SWAGGERHUB_API_KEY: ${{ secrets.SWAGGERHUB_API_KEY }}
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
deleted file mode 100644
index ff9a3bc5..00000000
--- a/.gitignore
+++ /dev/null
@@ -1,122 +0,0 @@
-
-
-### Eclipse ###
-.metadata
-bin/
-tmp/
-*.tmp
-*.bak
-*.swp
-*~.nib
-local.properties
-.settings/
-.loadpath
-.recommenders
-.classpath
-.project
-version.properties
-pipeline/
-
-#### Stirling-PDF Files ###
-customFiles/
-configs/
-watchedFolders/
-
-
-# Gradle
-.gradle
-.lock
-
-# External tool builders
-.externalToolBuilders/
-
-# Locally stored "Eclipse launch configurations"
-*.launch
-
-# PyDev specific (Python IDE for Eclipse)
-*.pydevproject
-
-# CDT-specific (C/C++ Development Tooling)
-.cproject
-
-# CDT- autotools
-.autotools
-
-# Java annotation processor (APT)
-.factorypath
-
-# PDT-specific (PHP Development Tools)
-.buildpath
-
-# sbteclipse plugin
-.target
-
-# Tern plugin
-.tern-project
-
-# TeXlipse plugin
-.texlipse
-
-# STS (Spring Tool Suite)
-.springBeans
-
-# Code Recommenders
-.recommenders/
-
-# Annotation Processing
-.apt_generated/
-.apt_generated_test/
-
-# Scala IDE specific (Scala & Java development for Eclipse)
-.cache-main
-.scala_dependencies
-.worksheet
-
-# Uncomment this line if you wish to ignore the project description file.
-# Typically, this file would be tracked if it contains build/dependency configurations:
-#.project
-
-### Eclipse Patch ###
-# Spring Boot Tooling
-.sts4-cache/
-
-### Git ###
-# Created by git for backups. To disable backups in Git:
-# $ git config --global mergetool.keepBackup false
-*.orig
-
-# Created by git when using merge tools for conflicts
-*.BACKUP.*
-*.BASE.*
-*.LOCAL.*
-*.REMOTE.*
-*_BACKUP_*.txt
-*_BASE_*.txt
-*_LOCAL_*.txt
-*_REMOTE_*.txt
-
-### Java ###
-# Compiled class file
-*.class
-
-# Log file
-*.log
-
-# BlueJ files
-*.ctxt
-
-# Mobile Tools for Java (J2ME)
-.mtj.tmp/
-
-# Package Files #
-*.jar
-*.war
-*.nar
-*.ear
-*.zip
-*.tar.gz
-*.rar
-*.db
-/build
-
-/.vscode
\ No newline at end of file
diff --git a/.idea/.gitignore b/.idea/.gitignore
deleted file mode 100644
index 13566b81..00000000
--- a/.idea/.gitignore
+++ /dev/null
@@ -1,8 +0,0 @@
-# Default ignored files
-/shelf/
-/workspace.xml
-# Editor-based HTTP Client requests
-/httpRequests/
-# Datasource local storage ignored files
-/dataSources/
-/dataSources.local.xml
diff --git a/CNAME b/CNAME
deleted file mode 100644
index 736e5893..00000000
--- a/CNAME
+++ /dev/null
@@ -1 +0,0 @@
-stirlingtools.com
\ No newline at end of file
diff --git a/Dockerfile b/Dockerfile
deleted file mode 100644
index e4bd868c..00000000
--- a/Dockerfile
+++ /dev/null
@@ -1,45 +0,0 @@
-# Use the base image
-FROM frooodle/stirling-pdf-base:beta4
-
-ARG VERSION_TAG
-
-# Set Environment Variables
-ENV DOCKER_ENABLE_SECURITY=false \
- HOME=/home/stirlingpdfuser \
- VERSION_TAG=$VERSION_TAG
-# PUID=1000 \
-# PGID=1000 \
-# UMASK=022 \
-
-
-# Create user and group
-##RUN groupadd -g $PGID stirlingpdfgroup && \
-## useradd -u $PUID -g stirlingpdfgroup -s /bin/sh stirlingpdfuser && \
-## mkdir -p $HOME && chown stirlingpdfuser:stirlingpdfgroup $HOME
-
-# Set up necessary directories and permissions
-RUN mkdir -p /scripts /usr/share/fonts/opentype/noto /usr/share/tesseract-ocr /configs /customFiles
-##&& \
-## chown -R stirlingpdfuser:stirlingpdfgroup /scripts /usr/share/fonts/opentype/noto /usr/share/tesseract-ocr /configs /customFiles && \
-## chown -R stirlingpdfuser:stirlingpdfgroup /usr/share/tesseract-ocr-original
-
-# Copy necessary files
-COPY ./scripts/* /scripts/
-COPY src/main/resources/static/fonts/*.ttf /usr/share/fonts/opentype/noto/
-COPY src/main/resources/static/fonts/*.otf /usr/share/fonts/opentype/noto/
-COPY build/libs/*.jar app.jar
-
-# Set font cache and permissions
-RUN fc-cache -f -v && chmod +x /scripts/init.sh
-
-##&& \
-## chown stirlingpdfuser:stirlingpdfgroup /app.jar && \
-## chmod +x /scripts/init.sh
-
-# Expose necessary ports
-EXPOSE 8080
-
-# Set user and run command
-##USER stirlingpdfuser
-ENTRYPOINT ["/scripts/init.sh"]
-CMD ["java", "-jar", "/app.jar"]
diff --git a/Dockerfile-lite b/Dockerfile-lite
deleted file mode 100644
index f41a8a8f..00000000
--- a/Dockerfile-lite
+++ /dev/null
@@ -1,54 +0,0 @@
-# Build jbig2enc in a separate stage
-FROM bellsoft/liberica-openjdk-debian:17
-RUN apt-get update && \
- apt-get install -y --no-install-recommends \
- libreoffice-core-nogui \
- libreoffice-common \
- libreoffice-writer-nogui \
- libreoffice-calc-nogui \
- libreoffice-impress-nogui \
- unoconv && \
- rm -rf /var/lib/apt/lists/*
-
-
-# Set Environment Variables
-ENV DOCKER_ENABLE_SECURITY=false \
- HOME=/home/stirlingpdfuser \
- VERSION_TAG=$VERSION_TAG
-# PUID=1000 \
-# PGID=1000 \
-# UMASK=022 \
-
-# Create user and group
-#RUN groupadd -g $PGID stirlingpdfgroup && \
-# useradd -u $PUID -g stirlingpdfgroup -s /bin/sh stirlingpdfuser && \
-# mkdir -p $HOME && chown stirlingpdfuser:stirlingpdfgroup $HOME
-
-# Set up necessary directories and permissions
-RUN mkdir -p /scripts /usr/share/fonts/opentype/noto /configs /customFiles
-
-# chown -R stirlingpdfuser:stirlingpdfgroup /usr/share/fonts/opentype/noto /configs /customFiles
-
-# Copy necessary files
-COPY src/main/resources/static/fonts/*.ttf /usr/share/fonts/opentype/noto/
-COPY src/main/resources/static/fonts/*.otf /usr/share/fonts/opentype/noto/
-COPY build/libs/*.jar app.jar
-
-# Set font cache and permissions
-RUN fc-cache -f -v
-# chown stirlingpdfuser:stirlingpdfgroup /app.jar
-
-
-
-
-# Expose the application port
-EXPOSE 8080
-
-# Set environment variables
-ENV ENDPOINTS_GROUPS_TO_REMOVE=Python,OpenCV,OCRmyPDF
-ENV DOCKER_ENABLE_SECURITY=false
-
-# Run the application
-#USER stirlingpdfuser
-
-CMD ["java", "-jar", "/app.jar"]
diff --git a/Dockerfile-ultra-lite b/Dockerfile-ultra-lite
deleted file mode 100644
index 84798820..00000000
--- a/Dockerfile-ultra-lite
+++ /dev/null
@@ -1,34 +0,0 @@
-# Build jbig2enc in a separate stage
-FROM bellsoft/liberica-openjdk-alpine:17
-
-# Set Environment Variables
-ENV PUID=1000 \
- PGID=1000 \
- UMASK=022 \
- DOCKER_ENABLE_SECURITY=false \
- HOME=/home/stirlingpdfuser \
- VERSION_TAG=$VERSION_TAG
-
-# Create user and group using Alpine's addgroup and adduser
-RUN addgroup -g $PGID stirlingpdfgroup && \
- adduser -u $PUID -G stirlingpdfgroup -s /bin/sh -D stirlingpdfuser && \
- mkdir -p $HOME && chown stirlingpdfuser:stirlingpdfgroup $HOME
-
-# Set up necessary directories and permissions
-RUN mkdir -p /scripts /configs /customFiles && \
- chown -R stirlingpdfuser:stirlingpdfgroup /scripts /configs /customFiles
-
-COPY build/libs/*.jar app.jar
-
-# Set font cache and permissions
-RUN chown stirlingpdfuser:stirlingpdfgroup /app.jar
-
-# Expose the application port
-EXPOSE 8080
-
-# Set environment variables
-ENV ENDPOINTS_GROUPS_TO_REMOVE=CLI
-ENV DOCKER_ENABLE_SECURITY=false
-
-# Run the application
-CMD ["java", "-jar", "/app.jar"]
diff --git a/DockerfileBase b/DockerfileBase
deleted file mode 100644
index d1c2df74..00000000
--- a/DockerfileBase
+++ /dev/null
@@ -1,37 +0,0 @@
-# Main stage
-FROM bellsoft/liberica-openjdk-debian:17 AS base
-RUN apt-get update && \
- apt-get install -y --no-install-recommends \
- libreoffice-core-nogui \
- libreoffice-common \
- libreoffice-writer-nogui \
- libreoffice-calc-nogui \
- libreoffice-impress-nogui \
- python3-uno \
- python3-pip \
- unoconv \
- pngquant \
- unpaper \
- ocrmypdf && \
- rm -rf /var/lib/apt/lists/* && \
- mkdir /usr/share/tesseract-ocr-original && \
- cp -r /usr/share/tesseract-ocr/* /usr/share/tesseract-ocr-original && \
- rm -rf /usr/share/tesseract-ocr
-
-# Python packages stage
-FROM base AS python-packages
-RUN apt-get update && \
- apt-get install -y --no-install-recommends \
- build-essential \
- libffi-dev \
- libssl-dev \
- zlib1g-dev \
- libjpeg-dev && \
- pip install --upgrade pip && \
- pip install --no-cache-dir \
- opencv-python-headless WeasyPrint && \
- rm -rf /var/lib/apt/lists/*
-
-# Final stage: Copy necessary files from the previous stage
-FROM base
-COPY --from=python-packages /usr/local /usr/local
\ No newline at end of file
diff --git a/Endpoint-groups.md b/Endpoint-groups.md
deleted file mode 100644
index 9c7f3ae6..00000000
--- a/Endpoint-groups.md
+++ /dev/null
@@ -1,46 +0,0 @@
-| Operation | PageOps | Convert | Security | Other | CLI | Python | OpenCV | LibreOffice | OCRmyPDF | Java | Javascript |
-|---------------------|---------|---------|----------|-------|------|--------|--------|-------------|----------|----------|------------|
-| adjust-contrast | ✔️ | | | | | | | | | | ✔️ |
-| auto-split-pdf | ✔️ | | | | | | | | | ✔️ | |
-| crop | ✔️ | | | | | | | | | ✔️ | |
-| extract-page | ✔️ | | | | | | | | | ✔️ | |
-| merge-pdfs | ✔️ | | | | | | | | | ✔️ | |
-| multi-page-layout | ✔️ | | | | | | | | | ✔️ | |
-| pdf-organizer | ✔️ | | | | | | | | | ✔️ | ✔️ |
-| pdf-to-single-page | ✔️ | | | | | | | | | ✔️ | |
-| remove-pages | ✔️ | | | | | | | | | ✔️ | |
-| rotate-pdf | ✔️ | | | | | | | | | ✔️ | |
-| scale-pages | ✔️ | | | | | | | | | ✔️ | |
-| split-pdfs | ✔️ | | | | | | | | | ✔️ | |
-| file-to-pdf | | ✔️ | | | ✔️ | | | ✔️ | | | |
-| img-to-pdf | | ✔️ | | | | | | | | ✔️ | |
-| pdf-to-html | | ✔️ | | | ✔️ | | | ✔️ | | | |
-| pdf-to-img | | ✔️ | | | | | | | | ✔️ | |
-| pdf-to-pdfa | | ✔️ | | | ✔️ | | | | ✔️ | | |
-| pdf-to-markdown | | ✔️ | | | | | | | | ✔️ | |
-| pdf-to-presentation | | ✔️ | | | ✔️ | | | ✔️ | | | |
-| pdf-to-text | | ✔️ | | | ✔️ | | | ✔️ | | | |
-| pdf-to-word | | ✔️ | | | ✔️ | | | ✔️ | | | |
-| pdf-to-xml | | ✔️ | | | ✔️ | | | ✔️ | | | |
-| xlsx-to-pdf | | ✔️ | | | ✔️ | | | ✔️ | | | |
-| add-password | | | ✔️ | | | | | | | ✔️ | |
-| add-watermark | | | ✔️ | | | | | | | ✔️ | |
-| cert-sign | | | ✔️ | | | | | | | ✔️ | |
-| change-permissions | | | ✔️ | | | | | | | ✔️ | |
-| remove-password | | | ✔️ | | | | | | | ✔️ | |
-| sanitize-pdf | | | ✔️ | | | | | | | ✔️ | |
-| add-image | | | | ✔️ | | | | | | ✔️ | |
-| add-page-numbers | | | | ✔️ | | | | | | ✔️ | |
-| auto-rename | | | | ✔️ | | | | | | ✔️ | |
-| change-metadata | | | | ✔️ | | | | | | ✔️ | |
-| compare | | | | ✔️ | | | | | | | ✔️ |
-| compress-pdf | | | | ✔️ | ✔️ | | | | ✔️ | | |
-| extract-image-scans | | | | ✔️ | ✔️ | ✔️ | ✔️ | | | | |
-| extract-images | | | | ✔️ | | | | | | ✔️ | |
-| flatten | | | | ✔️ | | | | | | | ✔️ |
-| get-info-on-pdf | | | | ✔️ | | | | | | ✔️ | |
-| ocr-pdf | | | | ✔️ | ✔️ | | | | ✔️ | | |
-| remove-blanks | | | | ✔️ | ✔️ | ✔️ | ✔️ | | | | |
-| repair | | | | ✔️ | ✔️ | | | ✔️ | | | |
-| show-javascript | | | | ✔️ | | | | | | | ✔️ |
-| sign | | | | ✔️ | | | | | | | ✔️ |
\ No newline at end of file
diff --git a/HowToAddNewLanguage.md b/HowToAddNewLanguage.md
deleted file mode 100644
index b6a7fa4a..00000000
--- a/HowToAddNewLanguage.md
+++ /dev/null
@@ -1,38 +0,0 @@
-
Stirling-PDF
-
-
-
-# How to add new languages to Stirling-PDF
-
-Fork Stirling-PDF and make a new branch out of Main
-
-Then add reference to the language in the navbar by adding a new language entry to the dropdown
-
-https://github.com/Frooodle/Stirling-PDF/blob/main/src/main/resources/templates/fragments/languages.html
-and add a flag svg file to
-https://github.com/Frooodle/Stirling-PDF/tree/main/src/main/resources/static/images/flags
-Any SVG flags are fine, i got most of mine from [here](https://flagicons.lipis.dev/)
-If your language isnt represented by a flag just find whichever closely matches it, such as for Arabic i chose Saudi Arabia
-
-
-For example to add Polish you would add
-```
-
- Polski
-
-```
-The data-language-code is the code used to reference the file in the next step.
-
-Start by copying the existing english property file
-
-[https://github.com/Frooodle/Stirling-PDF/blob/main/src/main/resources/messages_en_GB.properties](https://github.com/Frooodle/Stirling-PDF/blob/main/src/main/resources/messages_en_GB.properties)
-
-Copy and rename it to messages_{your data-language-code here}.properties, in the polish example you would set the name to messages_pl_PL.properties
-
-
-Then simply translate all property entries within that file and make a PR into main for others to use!
-
-If you do not have a java IDE i am happy to verify the changes worked once you raise PR (but wont be able to verify the translations themselves)
-
-
-
diff --git a/HowToUseOCR.md b/HowToUseOCR.md
deleted file mode 100644
index 37e33b5c..00000000
--- a/HowToUseOCR.md
+++ /dev/null
@@ -1,76 +0,0 @@
-# OCR Language Packs and Setup
-
-This document provides instructions on how to add additional language packs for the OCR tab in Stirling-PDF, both inside and outside of Docker.
-
-## How does the OCR Work
-Stirling-PDF uses [OCRmyPDF](https://github.com/ocrmypdf/OCRmyPDF) which in turn uses tesseract for its text recognition.
-All credit goes to them for this awesome work!
-
-## Language Packs
-
-Tesseract OCR supports a variety of languages. You can find additional language packs in the Tesseract GitHub repositories:
-
-- [tessdata_fast](https://github.com/tesseract-ocr/tessdata_fast): These language packs are smaller and faster to load, but may provide lower recognition accuracy.
-- [tessdata](https://github.com/tesseract-ocr/tessdata): These language packs are larger and provide better recognition accuracy, but may take longer to load.
-
-Depending on your requirements, you can choose the appropriate language pack for your use case. By default Stirling-PDF uses the tessdata_fast eng but this can be replaced.
-
-### Installing Language Packs
-
-1. Download the desired language pack(s) by selecting the `.traineddata` file(s) for the language(s) you need.
-2. Place the `.traineddata` files in the Tesseract tessdata directory: `/usr/share/tesseract-ocr/4.00/tessdata` (Debian) or `/usr/share/tesseract/tessdata` (Fedora)
-
-# DO NOT REMOVE EXISTING ENG.TRAINEDDATA, ITS REQUIRED.
-
-#### Docker
-
-If you are using Docker, you need to expose the Tesseract tessdata directory as a volume in order to use the additional language packs.
-#### Docker Compose
-Modify your `docker-compose.yml` file to include the following volume configuration:
-
-
-```yaml
-services:
- your_service_name:
- image: your_docker_image_name
- volumes:
- - /location/of/trainingData:/usr/share/tesseract-ocr/4.00/tessdata
-```
-
-
-#### Docker run
-Add the following to your existing docker run command
-```bash
--v /location/of/trainingData:/usr/share/tesseract-ocr/4.00/tessdata
-```
-
-#### Non-Docker
-If you are not using Docker, you need to install the OCR components, including the ocrmypdf app.
-You can see [OCRmyPDF install guide](https://ocrmypdf.readthedocs.io/en/latest/installation.html)
-
-Debian based systems, install languages with this command:
-
-```bash
-sudo apt update &&\
-# All languages
-# sudo apt install -y 'tesseract-ocr-*'
-
-# Find languages:
-apt search tesseract-ocr-
-
-# View installed languages:
-dpkg-query -W tesseract-ocr- | sed 's/tesseract-ocr-//g'
-```
-
-Fedora:
-
-```bash
-# All languages
-# sudo dnf install -y tesseract-langpack-*
-
-# Find languages:
-dnf search -C tesseract-langpack-
-
-# View installed languages:
-rpm -qa | grep tesseract-langpack | sed 's/tesseract-langpack-//g'
-```
diff --git a/Jenkinsfile b/Jenkinsfile
deleted file mode 100644
index dce948a4..00000000
--- a/Jenkinsfile
+++ /dev/null
@@ -1,33 +0,0 @@
-pipeline {
- agent any
- stages {
- stage('Build') {
- steps {
- sh 'chmod 755 gradlew'
- sh './gradlew build'
- }
- }
- stage('Docker Build') {
- steps {
- script {
- def appVersion = sh(returnStdout: true, script: './gradlew printVersion -q').trim()
- def image = "frooodle/s-pdf:$appVersion"
- sh "docker build -t $image ."
- }
- }
- }
- stage('Docker Push') {
- steps {
- script {
- def appVersion = sh(returnStdout: true, script: './gradlew printVersion -q').trim()
- def image = "frooodle/s-pdf:$appVersion"
- withCredentials([string(credentialsId: 'docker_hub_access_token', variable: 'DOCKER_HUB_ACCESS_TOKEN')]) {
- sh "docker login --username frooodle --password $DOCKER_HUB_ACCESS_TOKEN"
- sh "docker push $image"
- }
- }
- }
-
- }
- }
-}
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
deleted file mode 100644
index f288702d..00000000
--- a/LICENSE
+++ /dev/null
@@ -1,674 +0,0 @@
- GNU GENERAL PUBLIC LICENSE
- Version 3, 29 June 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc.
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The GNU General Public License is a free, copyleft license for
-software and other kinds of works.
-
- The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works. By contrast,
-the GNU General Public License is intended to guarantee your freedom to
-share and change all versions of a program--to make sure it remains free
-software for all its users. We, the Free Software Foundation, use the
-GNU General Public License for most of our software; it applies also to
-any other work released this way by its authors. You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-them if you wish), that you receive source code or can get it if you
-want it, that you can change the software or use pieces of it in new
-free programs, and that you know you can do these things.
-
- To protect your rights, we need to prevent others from denying you
-these rights or asking you to surrender the rights. Therefore, you have
-certain responsibilities if you distribute copies of the software, or if
-you modify it: responsibilities to respect the freedom of others.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must pass on to the recipients the same
-freedoms that you received. You must make sure that they, too, receive
-or can get the source code. And you must show them these terms so they
-know their rights.
-
- Developers that use the GNU GPL protect your rights with two steps:
-(1) assert copyright on the software, and (2) offer you this License
-giving you legal permission to copy, distribute and/or modify it.
-
- For the developers' and authors' protection, the GPL clearly explains
-that there is no warranty for this free software. For both users' and
-authors' sake, the GPL requires that modified versions be marked as
-changed, so that their problems will not be attributed erroneously to
-authors of previous versions.
-
- Some devices are designed to deny users access to install or run
-modified versions of the software inside them, although the manufacturer
-can do so. This is fundamentally incompatible with the aim of
-protecting users' freedom to change the software. The systematic
-pattern of such abuse occurs in the area of products for individuals to
-use, which is precisely where it is most unacceptable. Therefore, we
-have designed this version of the GPL to prohibit the practice for those
-products. If such problems arise substantially in other domains, we
-stand ready to extend this provision to those domains in future versions
-of the GPL, as needed to protect the freedom of users.
-
- Finally, every program is threatened constantly by software patents.
-States should not allow patents to restrict development and use of
-software on general-purpose computers, but in those that do, we wish to
-avoid the special danger that patents applied to a free program could
-make it effectively proprietary. To prevent this, the GPL assures that
-patents cannot be used to render the program non-free.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- TERMS AND CONDITIONS
-
- 0. Definitions.
-
- "This License" refers to version 3 of the GNU General Public License.
-
- "Copyright" also means copyright-like laws that apply to other kinds of
-works, such as semiconductor masks.
-
- "The Program" refers to any copyrightable work licensed under this
-License. Each licensee is addressed as "you". "Licensees" and
-"recipients" may be individuals or organizations.
-
- To "modify" a work means to copy from or adapt all or part of the work
-in a fashion requiring copyright permission, other than the making of an
-exact copy. The resulting work is called a "modified version" of the
-earlier work or a work "based on" the earlier work.
-
- A "covered work" means either the unmodified Program or a work based
-on the Program.
-
- To "propagate" a work means to do anything with it that, without
-permission, would make you directly or secondarily liable for
-infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy. Propagation includes copying,
-distribution (with or without modification), making available to the
-public, and in some countries other activities as well.
-
- To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies. Mere interaction with a user through
-a computer network, with no transfer of a copy, is not conveying.
-
- An interactive user interface displays "Appropriate Legal Notices"
-to the extent that it includes a convenient and prominently visible
-feature that (1) displays an appropriate copyright notice, and (2)
-tells the user that there is no warranty for the work (except to the
-extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License. If
-the interface presents a list of user commands or options, such as a
-menu, a prominent item in the list meets this criterion.
-
- 1. Source Code.
-
- The "source code" for a work means the preferred form of the work
-for making modifications to it. "Object code" means any non-source
-form of a work.
-
- A "Standard Interface" means an interface that either is an official
-standard defined by a recognized standards body, or, in the case of
-interfaces specified for a particular programming language, one that
-is widely used among developers working in that language.
-
- The "System Libraries" of an executable work include anything, other
-than the work as a whole, that (a) is included in the normal form of
-packaging a Major Component, but which is not part of that Major
-Component, and (b) serves only to enable use of the work with that
-Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form. A
-"Major Component", in this context, means a major essential component
-(kernel, window system, and so on) of the specific operating system
-(if any) on which the executable work runs, or a compiler used to
-produce the work, or an object code interpreter used to run it.
-
- The "Corresponding Source" for a work in object code form means all
-the source code needed to generate, install, and (for an executable
-work) run the object code and to modify the work, including scripts to
-control those activities. However, it does not include the work's
-System Libraries, or general-purpose tools or generally available free
-programs which are used unmodified in performing those activities but
-which are not part of the work. For example, Corresponding Source
-includes interface definition files associated with source files for
-the work, and the source code for shared libraries and dynamically
-linked subprograms that the work is specifically designed to require,
-such as by intimate data communication or control flow between those
-subprograms and other parts of the work.
-
- The Corresponding Source need not include anything that users
-can regenerate automatically from other parts of the Corresponding
-Source.
-
- The Corresponding Source for a work in source code form is that
-same work.
-
- 2. Basic Permissions.
-
- All rights granted under this License are granted for the term of
-copyright on the Program, and are irrevocable provided the stated
-conditions are met. This License explicitly affirms your unlimited
-permission to run the unmodified Program. The output from running a
-covered work is covered by this License only if the output, given its
-content, constitutes a covered work. This License acknowledges your
-rights of fair use or other equivalent, as provided by copyright law.
-
- You may make, run and propagate covered works that you do not
-convey, without conditions so long as your license otherwise remains
-in force. You may convey covered works to others for the sole purpose
-of having them make modifications exclusively for you, or provide you
-with facilities for running those works, provided that you comply with
-the terms of this License in conveying all material for which you do
-not control copyright. Those thus making or running the covered works
-for you must do so exclusively on your behalf, under your direction
-and control, on terms that prohibit them from making any copies of
-your copyrighted material outside their relationship with you.
-
- Conveying under any other circumstances is permitted solely under
-the conditions stated below. Sublicensing is not allowed; section 10
-makes it unnecessary.
-
- 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
- No covered work shall be deemed part of an effective technological
-measure under any applicable law fulfilling obligations under article
-11 of the WIPO copyright treaty adopted on 20 December 1996, or
-similar laws prohibiting or restricting circumvention of such
-measures.
-
- When you convey a covered work, you waive any legal power to forbid
-circumvention of technological measures to the extent such circumvention
-is effected by exercising rights under this License with respect to
-the covered work, and you disclaim any intention to limit operation or
-modification of the work as a means of enforcing, against the work's
-users, your or third parties' legal rights to forbid circumvention of
-technological measures.
-
- 4. Conveying Verbatim Copies.
-
- You may convey verbatim copies of the Program's source code as you
-receive it, in any medium, provided that you conspicuously and
-appropriately publish on each copy an appropriate copyright notice;
-keep intact all notices stating that this License and any
-non-permissive terms added in accord with section 7 apply to the code;
-keep intact all notices of the absence of any warranty; and give all
-recipients a copy of this License along with the Program.
-
- You may charge any price or no price for each copy that you convey,
-and you may offer support or warranty protection for a fee.
-
- 5. Conveying Modified Source Versions.
-
- You may convey a work based on the Program, or the modifications to
-produce it from the Program, in the form of source code under the
-terms of section 4, provided that you also meet all of these conditions:
-
- a) The work must carry prominent notices stating that you modified
- it, and giving a relevant date.
-
- b) The work must carry prominent notices stating that it is
- released under this License and any conditions added under section
- 7. This requirement modifies the requirement in section 4 to
- "keep intact all notices".
-
- c) You must license the entire work, as a whole, under this
- License to anyone who comes into possession of a copy. This
- License will therefore apply, along with any applicable section 7
- additional terms, to the whole of the work, and all its parts,
- regardless of how they are packaged. This License gives no
- permission to license the work in any other way, but it does not
- invalidate such permission if you have separately received it.
-
- d) If the work has interactive user interfaces, each must display
- Appropriate Legal Notices; however, if the Program has interactive
- interfaces that do not display Appropriate Legal Notices, your
- work need not make them do so.
-
- A compilation of a covered work with other separate and independent
-works, which are not by their nature extensions of the covered work,
-and which are not combined with it such as to form a larger program,
-in or on a volume of a storage or distribution medium, is called an
-"aggregate" if the compilation and its resulting copyright are not
-used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit. Inclusion of a covered work
-in an aggregate does not cause this License to apply to the other
-parts of the aggregate.
-
- 6. Conveying Non-Source Forms.
-
- You may convey a covered work in object code form under the terms
-of sections 4 and 5, provided that you also convey the
-machine-readable Corresponding Source under the terms of this License,
-in one of these ways:
-
- a) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by the
- Corresponding Source fixed on a durable physical medium
- customarily used for software interchange.
-
- b) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by a
- written offer, valid for at least three years and valid for as
- long as you offer spare parts or customer support for that product
- model, to give anyone who possesses the object code either (1) a
- copy of the Corresponding Source for all the software in the
- product that is covered by this License, on a durable physical
- medium customarily used for software interchange, for a price no
- more than your reasonable cost of physically performing this
- conveying of source, or (2) access to copy the
- Corresponding Source from a network server at no charge.
-
- c) Convey individual copies of the object code with a copy of the
- written offer to provide the Corresponding Source. This
- alternative is allowed only occasionally and noncommercially, and
- only if you received the object code with such an offer, in accord
- with subsection 6b.
-
- d) Convey the object code by offering access from a designated
- place (gratis or for a charge), and offer equivalent access to the
- Corresponding Source in the same way through the same place at no
- further charge. You need not require recipients to copy the
- Corresponding Source along with the object code. If the place to
- copy the object code is a network server, the Corresponding Source
- may be on a different server (operated by you or a third party)
- that supports equivalent copying facilities, provided you maintain
- clear directions next to the object code saying where to find the
- Corresponding Source. Regardless of what server hosts the
- Corresponding Source, you remain obligated to ensure that it is
- available for as long as needed to satisfy these requirements.
-
- e) Convey the object code using peer-to-peer transmission, provided
- you inform other peers where the object code and Corresponding
- Source of the work are being offered to the general public at no
- charge under subsection 6d.
-
- A separable portion of the object code, whose source code is excluded
-from the Corresponding Source as a System Library, need not be
-included in conveying the object code work.
-
- A "User Product" is either (1) a "consumer product", which means any
-tangible personal property which is normally used for personal, family,
-or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling. In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage. For a particular
-product received by a particular user, "normally used" refers to a
-typical or common use of that class of product, regardless of the status
-of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product. A product
-is a consumer product regardless of whether the product has substantial
-commercial, industrial or non-consumer uses, unless such uses represent
-the only significant mode of use of the product.
-
- "Installation Information" for a User Product means any methods,
-procedures, authorization keys, or other information required to install
-and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source. The information must
-suffice to ensure that the continued functioning of the modified object
-code is in no case prevented or interfered with solely because
-modification has been made.
-
- If you convey an object code work under this section in, or with, or
-specifically for use in, a User Product, and the conveying occurs as
-part of a transaction in which the right of possession and use of the
-User Product is transferred to the recipient in perpetuity or for a
-fixed term (regardless of how the transaction is characterized), the
-Corresponding Source conveyed under this section must be accompanied
-by the Installation Information. But this requirement does not apply
-if neither you nor any third party retains the ability to install
-modified object code on the User Product (for example, the work has
-been installed in ROM).
-
- The requirement to provide Installation Information does not include a
-requirement to continue to provide support service, warranty, or updates
-for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed. Access to a
-network may be denied when the modification itself materially and
-adversely affects the operation of the network or violates the rules and
-protocols for communication across the network.
-
- Corresponding Source conveyed, and Installation Information provided,
-in accord with this section must be in a format that is publicly
-documented (and with an implementation available to the public in
-source code form), and must require no special password or key for
-unpacking, reading or copying.
-
- 7. Additional Terms.
-
- "Additional permissions" are terms that supplement the terms of this
-License by making exceptions from one or more of its conditions.
-Additional permissions that are applicable to the entire Program shall
-be treated as though they were included in this License, to the extent
-that they are valid under applicable law. If additional permissions
-apply only to part of the Program, that part may be used separately
-under those permissions, but the entire Program remains governed by
-this License without regard to the additional permissions.
-
- When you convey a copy of a covered work, you may at your option
-remove any additional permissions from that copy, or from any part of
-it. (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.) You may place
-additional permissions on material, added by you to a covered work,
-for which you have or can give appropriate copyright permission.
-
- Notwithstanding any other provision of this License, for material you
-add to a covered work, you may (if authorized by the copyright holders of
-that material) supplement the terms of this License with terms:
-
- a) Disclaiming warranty or limiting liability differently from the
- terms of sections 15 and 16 of this License; or
-
- b) Requiring preservation of specified reasonable legal notices or
- author attributions in that material or in the Appropriate Legal
- Notices displayed by works containing it; or
-
- c) Prohibiting misrepresentation of the origin of that material, or
- requiring that modified versions of such material be marked in
- reasonable ways as different from the original version; or
-
- d) Limiting the use for publicity purposes of names of licensors or
- authors of the material; or
-
- e) Declining to grant rights under trademark law for use of some
- trade names, trademarks, or service marks; or
-
- f) Requiring indemnification of licensors and authors of that
- material by anyone who conveys the material (or modified versions of
- it) with contractual assumptions of liability to the recipient, for
- any liability that these contractual assumptions directly impose on
- those licensors and authors.
-
- All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10. If the Program as you
-received it, or any part of it, contains a notice stating that it is
-governed by this License along with a term that is a further
-restriction, you may remove that term. If a license document contains
-a further restriction but permits relicensing or conveying under this
-License, you may add to a covered work material governed by the terms
-of that license document, provided that the further restriction does
-not survive such relicensing or conveying.
-
- If you add terms to a covered work in accord with this section, you
-must place, in the relevant source files, a statement of the
-additional terms that apply to those files, or a notice indicating
-where to find the applicable terms.
-
- Additional terms, permissive or non-permissive, may be stated in the
-form of a separately written license, or stated as exceptions;
-the above requirements apply either way.
-
- 8. Termination.
-
- You may not propagate or modify a covered work except as expressly
-provided under this License. Any attempt otherwise to propagate or
-modify it is void, and will automatically terminate your rights under
-this License (including any patent licenses granted under the third
-paragraph of section 11).
-
- However, if you cease all violation of this License, then your
-license from a particular copyright holder is reinstated (a)
-provisionally, unless and until the copyright holder explicitly and
-finally terminates your license, and (b) permanently, if the copyright
-holder fails to notify you of the violation by some reasonable means
-prior to 60 days after the cessation.
-
- Moreover, your license from a particular copyright holder is
-reinstated permanently if the copyright holder notifies you of the
-violation by some reasonable means, this is the first time you have
-received notice of violation of this License (for any work) from that
-copyright holder, and you cure the violation prior to 30 days after
-your receipt of the notice.
-
- Termination of your rights under this section does not terminate the
-licenses of parties who have received copies or rights from you under
-this License. If your rights have been terminated and not permanently
-reinstated, you do not qualify to receive new licenses for the same
-material under section 10.
-
- 9. Acceptance Not Required for Having Copies.
-
- You are not required to accept this License in order to receive or
-run a copy of the Program. Ancillary propagation of a covered work
-occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance. However,
-nothing other than this License grants you permission to propagate or
-modify any covered work. These actions infringe copyright if you do
-not accept this License. Therefore, by modifying or propagating a
-covered work, you indicate your acceptance of this License to do so.
-
- 10. Automatic Licensing of Downstream Recipients.
-
- Each time you convey a covered work, the recipient automatically
-receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License. You are not responsible
-for enforcing compliance by third parties with this License.
-
- An "entity transaction" is a transaction transferring control of an
-organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations. If propagation of a covered
-work results from an entity transaction, each party to that
-transaction who receives a copy of the work also receives whatever
-licenses to the work the party's predecessor in interest had or could
-give under the previous paragraph, plus a right to possession of the
-Corresponding Source of the work from the predecessor in interest, if
-the predecessor has it or can get it with reasonable efforts.
-
- You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License. For example, you may
-not impose a license fee, royalty, or other charge for exercise of
-rights granted under this License, and you may not initiate litigation
-(including a cross-claim or counterclaim in a lawsuit) alleging that
-any patent claim is infringed by making, using, selling, offering for
-sale, or importing the Program or any portion of it.
-
- 11. Patents.
-
- A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based. The
-work thus licensed is called the contributor's "contributor version".
-
- A contributor's "essential patent claims" are all patent claims
-owned or controlled by the contributor, whether already acquired or
-hereafter acquired, that would be infringed by some manner, permitted
-by this License, of making, using, or selling its contributor version,
-but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version. For
-purposes of this definition, "control" includes the right to grant
-patent sublicenses in a manner consistent with the requirements of
-this License.
-
- Each contributor grants you a non-exclusive, worldwide, royalty-free
-patent license under the contributor's essential patent claims, to
-make, use, sell, offer for sale, import and otherwise run, modify and
-propagate the contents of its contributor version.
-
- In the following three paragraphs, a "patent license" is any express
-agreement or commitment, however denominated, not to enforce a patent
-(such as an express permission to practice a patent or covenant not to
-sue for patent infringement). To "grant" such a patent license to a
-party means to make such an agreement or commitment not to enforce a
-patent against the party.
-
- If you convey a covered work, knowingly relying on a patent license,
-and the Corresponding Source of the work is not available for anyone
-to copy, free of charge and under the terms of this License, through a
-publicly available network server or other readily accessible means,
-then you must either (1) cause the Corresponding Source to be so
-available, or (2) arrange to deprive yourself of the benefit of the
-patent license for this particular work, or (3) arrange, in a manner
-consistent with the requirements of this License, to extend the patent
-license to downstream recipients. "Knowingly relying" means you have
-actual knowledge that, but for the patent license, your conveying the
-covered work in a country, or your recipient's use of the covered work
-in a country, would infringe one or more identifiable patents in that
-country that you have reason to believe are valid.
-
- If, pursuant to or in connection with a single transaction or
-arrangement, you convey, or propagate by procuring conveyance of, a
-covered work, and grant a patent license to some of the parties
-receiving the covered work authorizing them to use, propagate, modify
-or convey a specific copy of the covered work, then the patent license
-you grant is automatically extended to all recipients of the covered
-work and works based on it.
-
- A patent license is "discriminatory" if it does not include within
-the scope of its coverage, prohibits the exercise of, or is
-conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License. You may not convey a covered
-work if you are a party to an arrangement with a third party that is
-in the business of distributing software, under which you make payment
-to the third party based on the extent of your activity of conveying
-the work, and under which the third party grants, to any of the
-parties who would receive the covered work from you, a discriminatory
-patent license (a) in connection with copies of the covered work
-conveyed by you (or copies made from those copies), or (b) primarily
-for and in connection with specific products or compilations that
-contain the covered work, unless you entered into that arrangement,
-or that patent license was granted, prior to 28 March 2007.
-
- Nothing in this License shall be construed as excluding or limiting
-any implied license or other defenses to infringement that may
-otherwise be available to you under applicable patent law.
-
- 12. No Surrender of Others' Freedom.
-
- If conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot convey a
-covered work so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you may
-not convey it at all. For example, if you agree to terms that obligate you
-to collect a royalty for further conveying from those to whom you convey
-the Program, the only way you could satisfy both those terms and this
-License would be to refrain entirely from conveying the Program.
-
- 13. Use with the GNU Affero General Public License.
-
- Notwithstanding any other provision of this License, you have
-permission to link or combine any covered work with a work licensed
-under version 3 of the GNU Affero General Public License into a single
-combined work, and to convey the resulting work. The terms of this
-License will continue to apply to the part which is the covered work,
-but the special requirements of the GNU Affero General Public License,
-section 13, concerning interaction through a network will apply to the
-combination as such.
-
- 14. Revised Versions of this License.
-
- The Free Software Foundation may publish revised and/or new versions of
-the GNU General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
-Program specifies that a certain numbered version of the GNU General
-Public License "or any later version" applies to it, you have the
-option of following the terms and conditions either of that numbered
-version or of any later version published by the Free Software
-Foundation. If the Program does not specify a version number of the
-GNU General Public License, you may choose any version ever published
-by the Free Software Foundation.
-
- If the Program specifies that a proxy can decide which future
-versions of the GNU General Public License can be used, that proxy's
-public statement of acceptance of a version permanently authorizes you
-to choose that version for the Program.
-
- Later license versions may give you additional or different
-permissions. However, no additional obligations are imposed on any
-author or copyright holder as a result of your choosing to follow a
-later version.
-
- 15. Disclaimer of Warranty.
-
- THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. Limitation of Liability.
-
- IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGES.
-
- 17. Interpretation of Sections 15 and 16.
-
- If the disclaimer of warranty and limitation of liability provided
-above cannot be given local legal effect according to their terms,
-reviewing courts shall apply local law that most closely approximates
-an absolute waiver of all civil liability in connection with the
-Program, unless a warranty or assumption of liability accompanies a
-copy of the Program in return for a fee.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-state the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-
- Copyright (C)
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see .
-
-Also add information on how to contact you by electronic and paper mail.
-
- If the program does terminal interaction, make it output a short
-notice like this when it starts in an interactive mode:
-
- Copyright (C)
- This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, your program's commands
-might be different; for a GUI interface, you would use an "about box".
-
- You should also get your employer (if you work as a programmer) or school,
-if any, to sign a "copyright disclaimer" for the program, if necessary.
-For more information on this, and how to apply and follow the GNU GPL, see
- .
-
- The GNU General Public License does not permit incorporating your program
-into proprietary programs. If your program is a subroutine library, you
-may consider it more useful to permit linking proprietary applications with
-the library. If this is what you want to do, use the GNU Lesser General
-Public License instead of this License. But first, please read
-.
diff --git a/LocalRunGuide.md b/LocalRunGuide.md
deleted file mode 100644
index 8293aee1..00000000
--- a/LocalRunGuide.md
+++ /dev/null
@@ -1,213 +0,0 @@
-
-To run the application without Docker, you will need to manually install all dependencies and build the necessary components.
-
-Note that some dependencies might not be available in the standard repositories of all Linux distributions, and may require additional steps to install.
-
-The following guide assumes you have a basic understanding of using a command line interface in your operating system.
-
-It should work on most Linux distributions and MacOS. For Windows, you might need to use Windows Subsystem for Linux (WSL) for certain steps.
-The amount of dependencies is to actually reduce overall size, ie installing LibreOffice sub components rather than full LibreOffice package.
-
-### Step 1: Prerequisites
-
-Install the following software, if not already installed:
-
-- Java 17 or later
-
-- Gradle 7.0 or later (included within repo so not needed on server)
-
-- Git
-
-- Python 3 (with pip)
-
-- Make
-
-- GCC/G++
-
-- Automake
-
-- Autoconf
-
-- libtool
-
-- pkg-config
-
-- zlib1g-dev
-
-- libleptonica-dev
-
-For Debian-based systems, you can use the following command:
-
-```bash
-sudo apt-get update
-sudo apt-get install -y git automake autoconf libtool libleptonica-dev pkg-config zlib1g-dev make g++ java-17-openjdk python3 python3-pip
-```
-
-For Fedora-based systems use this command:
-
-```bash
-sudo dnf install -y git automake autoconf libtool leptonica-devel pkg-config zlib-devel make gcc-c++ java-17-openjdk python3 python3-pip
-```
-
-### Step 2: Clone and Build jbig2enc (Only required for certain OCR functionality)
-
-```bash
-mkdir ~/.git
-cd ~/.git &&\
-git clone https://github.com/agl/jbig2enc.git &&\
-cd jbig2enc &&\
-./autogen.sh &&\
-./configure &&\
-make &&\
-sudo make install
-```
-
-### Step 3: Install Additional Software
-Next we need to install LibreOffice for conversions, ocrmypdf for OCR, and opencv for patern recognition functionality.
-
-Install the following software:
-
-- libreoffice-core
-
-- libreoffice-common
-
-- libreoffice-writer
-
-- libreoffice-calc
-
-- libreoffice-impress
-
-- python3-uno
-
-- unoconv
-
-- pngquant
-
-- unpaper
-
-- ocrmypdf
-
-- opencv-python-headless
-
-For Debian-based systems, you can use the following command:
-
-```bash
-sudo apt-get install -y libreoffice-writer libreoffice-calc libreoffice-impress unpaper ocrmypdf
-pip3 install uno opencv-python-headless unoconv pngquant
-```
-
-For Fedora:
-
-```bash
-sudo dnf install -y libreoffice-writer libreoffice-calc libreoffice-impress unpaper ocrmypdf
-pip3 install uno opencv-python-headless unoconv pngquant
-```
-
-### Step 4: Clone and Build Stirling-PDF
-
-```bash
-cd ~/.git &&\
-git clone https://github.com/Frooodle/Stirling-PDF.git &&\
-cd Stirling-PDF &&\
-chmod +x ./gradlew &&\
-./gradlew build
-```
-
-
-### Step 5: Move jar to desired location
-
-After the build process, a `.jar` file will be generated in the `build/libs` directory.
-You can move this file to a desired location, for example, `/opt/Stirling-PDF/`.
-You must also move the Script folder within the Stirling-PDF repo that you have downloaded to this directory.
-This folder is required for the python scripts using OpenCV
-
-```bash
-sudo mkdir /opt/Stirling-PDF &&\
-sudo mv ./build/libs/Stirling-PDF-*.jar /opt/Stirling-PDF/ &&\
-sudo mv scripts /opt/Stirling-PDF/ &&\
-echo "Scripts installed."
-```
-### Step 6: Other files
-#### OCR
-If you plan to use the OCR (Optical Character Recognition) functionality, you might need to install language packs for Tesseract if running non-english scanning.
-
-##### Installing Language Packs
-Easiest is to use the langpacks provided by your repositories. Skip the other steps
-
-Manual:
-
-1. Download the desired language pack(s) by selecting the `.traineddata` file(s) for the language(s) you need.
-2. Place the `.traineddata` files in the Tesseract tessdata directory: `/usr/share/tesseract-ocr/4.00/tessdata`
-3.
-Please view [OCRmyPDF install guide](https://ocrmypdf.readthedocs.io/en/latest/installation.html) for more info.
-**IMPORTANT:** DO NOT REMOVE EXISTING `eng.traineddata`, IT'S REQUIRED.
-
-Debian based systems, install languages with this command:
-
-```bash
-sudo apt update &&\
-# All languages
-# sudo apt install -y 'tesseract-ocr-*'
-
-# Find languages:
-apt search tesseract-ocr-
-
-# View installed languages:
-dpkg-query -W tesseract-ocr- | sed 's/tesseract-ocr-//g'
-```
-
-Fedora:
-
-```bash
-# All languages
-# sudo dnf install -y tesseract-langpack-*
-
-# Find languages:
-dnf search -C tesseract-langpack-
-
-# View installed languages:
-rpm -qa | grep tesseract-langpack | sed 's/tesseract-langpack-//g'
-```
-
-### Step 7: Run Stirling-PDF
-
-```bash
-./gradlew bootRun
-or
-java -jar build/libs/app.jar
-```
-
-### Step 8: Adding a Desktop icon
-
-This will add a modified Appstarter to your Appmenu.
-```bash
-location=$(pwd)/gradlew
-image=$(pwd)/docs/stirling-transparent.svg
-
-cat > ~/.local/share/applications/Stirling-PDF.desktop <Stirling-PDF
-
-
-[](https://hub.docker.com/r/frooodle/s-pdf)
-[](https://discord.gg/Cn8pWhQRxZ)
-[](https://github.com/Frooodle/Stirling-PDF/)
-[](https://github.com/Frooodle/stirling-pdf)
-[](https://www.paypal.com/paypalme/froodleplex)
-[](https://github.com/sponsors/Frooodle)
-
-[](https://cloud.digitalocean.com/apps/new?repo=https://github.com/Frooodle/Stirling-PDF/tree/digitalOcean&refcode=c3210994b1af)
-
-This is a powerful locally hosted web based PDF manipulation tool using docker that allows you to perform various operations on PDF files, such as splitting merging, converting, reorganizing, adding images, rotating, compressing, and more. This locally hosted web application started as a 100% ChatGPT-made application and has evolved to include a wide range of features to handle all your PDF needs.
-
-Stirling PDF makes no outbound calls for any record keeping or tracking.
-
-All files and PDFs are either purely client side, in server memory only during the execution of the task or within a temporay file only for execution of the task.
-Any file which has been downloaded by the user will have already been deleted from the server by that time.
-
-Feel free to request any features or bug fixes either in github issues or our [Discord](https://discord.gg/Cn8pWhQRxZ)
-
-
-
-## Features
-- Dark mode support.
-- Custom download options (see [here](https://github.com/Frooodle/Stirling-PDF/blob/main/images/settings.png) for example)
-- Parallel file processing and downloads
-- API for integration with external scripts
-- Optional Login and Authentication support (see [here](https://github.com/Frooodle/Stirling-PDF/tree/main#login-authentication) for documentation)
-
-
-## **PDF Features**
-
-### **Page Operations**
-- Full interactive GUI for merging/splitting/rotating/moving PDFs and their pages.
-- Merge multiple PDFs together into a single resultant file.
-- Split PDFs into multiple files at specified page numbers or extract all pages as individual files.
-- Reorganize PDF pages into different orders.
-- Rotate PDFs in 90-degree increments.
-- Remove pages.
-- Multi-page layout (Format PDFs into a multi-paged page).
-- Scale page contents size by set %.
-- Adjust Contrast.
-- Crop PDF.
-- Auto Split PDF (With physically scanned page dividers).
-- Extract page(s).
-- Convert PDF to a single page.
-
-### **Conversion Operations**
-- Convert PDFs to and from images.
-- Convert any common file to PDF (using LibreOffice).
-- Convert PDF to Word/Powerpoint/Others (using LibreOffice).
-- Convert HTML to PDF.
-- URL to PDF.
-- Markdown to PDF.
-
-### **Security & Permissions**
-- Add and remove passwords.
-- Change/set PDF Permissions.
-- Add watermark(s).
-- Certify/sign PDFs.
-- Sanitize PDFs.
-- Auto-redact text.
-
-### **Other Operations**
-- Add/Generate/Write signatures.
-- Repair PDFs.
-- Detect and remove blank pages.
-- Compare 2 PDFs and show differences in text.
-- Add images to PDFs.
-- Compress PDFs to decrease their filesize (Using OCRMyPDF).
-- Extract images from PDF.
-- Extract images from Scans.
-- Add page numbers.
-- Auto rename file by detecting PDF header text.
-- OCR on PDF (Using OCRMyPDF).
-- PDF/A conversion (Using OCRMyPDF).
-- Edit metadata.
-- Flatten PDFs.
-- Get all information on a PDF to view or export as JSON.
-
-
-For a overview of the tasks and the technology each uses please view [groups.md](https://github.com/Frooodle/Stirling-PDF/blob/main/Groups.md)
-Hosted instance/demo of the app can be seen [here](https://pdf.adminforge.de/) hosted by the team at adminforge.de
-
-## Technologies used
-- Spring Boot + Thymeleaf
-- PDFBox
-- [LibreOffice](https://www.libreoffice.org/discover/libreoffice/) for advanced conversions
-- [OcrMyPdf](https://github.com/ocrmypdf/OCRmyPDF)
-- HTML, CSS, JavaScript
-- Docker
-- PDF.js
-- PDF-LIB.js
-
-## How to use
-
-### Locally
-Please view https://github.com/Frooodle/Stirling-PDF/blob/main/LocalRunGuide.md
-
-### Docker
-https://hub.docker.com/r/frooodle/s-pdf
-
-Stirling PDF has 3 different versions, a Full version, Lite, and ultra-Lite. Depending on the types of features you use you may want a smaller image to save on space.
-To see what the different versions offer please look at our [version mapping](https://github.com/Frooodle/Stirling-PDF/blob/main/Version-groups.md)
-For people that don't mind about space optimization just use the latest tag.
-
-
-
-
-Docker Run
-```
-docker run -d \
- -p 8080:8080 \
- -v /location/of/trainingData:/usr/share/tesseract-ocr/4.00/tessdata \
- -v /location/of/extraConfigs:/configs \
- -e DOCKER_ENABLE_SECURITY=false \
- --name stirling-pdf \
- frooodle/s-pdf:latest
-
-
- Can also add these for customisation but are not required
-
- -v /location/of/customFiles:/customFiles \
-```
-Docker Compose
-```
-version: '3.3'
-services:
- stirling-pdf:
- image: frooodle/s-pdf:latest
- ports:
- - '8080:8080'
- volumes:
- - /location/of/trainingData:/usr/share/tesseract-ocr/4.00/tessdata #Required for extra OCR languages
- - /location/of/extraConfigs:/configs
-# - /location/of/customFiles:/customFiles/
- environment:
- - DOCKER_ENABLE_SECURITY=false
-```
-
-
-## Enable OCR/Compression feature
-Please view https://github.com/Frooodle/Stirling-PDF/blob/main/HowToUseOCR.md
-
-## Want to add your own language?
-Stirling PDF currently supports 18!
-- English (English) (en_GB)
-- English (US) (en_US)
-- Arabic (العربية) (ar_AR)
-- German (Deutsch) (de_DE)
-- French (Français) (fr_FR)
-- Spanish (Español) (es_ES)
-- Chinese (简体中文) (zh_CN)
-- Catalan (Català) (ca_CA)
-- Italian (Italiano) (it_IT)
-- Swedish (Svenska) (sv_SE)
-- Polish (Polski) (pl_PL)
-- Romanian (Română) (ro_RO)
-- Korean (한국어) (ko_KR)
-- Portuguese Brazilian (Português) (pt_BR)
-- Russian (Русский) (ru_RU)
-- Basque (Euskara) (eu_ES)
-- Japanese (日本語) (ja_JP)
-- Dutch (Nederlands) (nl_NL)
-
-If you want to add your own language to Stirling-PDF please refer
-https://github.com/Frooodle/Stirling-PDF/blob/main/HowToAddNewLanguage.md
-
-And please create a PR to merge it back in so others can use it!
-
-## How to View
-1. Open a web browser and navigate to `http://localhost:8080/`
-2. Use the application by following the instructions on the website.
-
-
-## Customisation
-Stirling PDF allows easy customization of the app.
-Includes things like
-- Custom application name
-- Custom slogans, icons, images, and even custom HTML (via file overrides)
-
-
-There are two options for this, either using the generated settings file ``settings.yml``
-This file is located in the ``/configs`` directory and follows standard YAML formatting
-
-Environment variables are also supported and would override the settings file
-For example in the settings.yml you have
-```
-system:
- defaultLocale: 'en-US'
-```
-
-To have this via an environment variable you would have ``SYSTEM_DEFAULTLOCALE``
-
-The Current list of settings is
-```
-security:
- enableLogin: false # set to 'true' to enable login
- csrfDisabled: true
-
-system:
- defaultLocale: 'en-US' # Set the default language (e.g. 'de-DE', 'fr-FR', etc)
- googlevisibility: false # 'true' to allow Google visibility (via robots.txt), 'false' to disallow
- customStaticFilePath: '/customFiles/static/' # Directory path for custom static files
-
-#ui:
-# appName: exampleAppName # Application's visible name
-# homeDescription: I am a description # Short description or tagline shown on homepage.
-# appNameNavbar: navbarName # Name displayed on the navigation bar
-
-endpoints:
- toRemove: [] # List endpoints to disable (e.g. ['img-to-pdf', 'remove-pages'])
- groupsToRemove: [] # List groups to disable (e.g. ['LibreOffice'])
-
-metrics:
- enabled: true # 'true' to enable Info APIs endpoints (view http://localhost:8080/swagger-ui/index.html#/API to learn more), 'false' to disable
-```
-### Extra notes
-- Endpoints. Currently, the endpoints ENDPOINTS_TO_REMOVE and GROUPS_TO_REMOVE can include comma separate lists of endpoints and groups to disable as example ENDPOINTS_TO_REMOVE=img-to-pdf,remove-pages would disable both image-to-pdf and remove pages, GROUPS_TO_REMOVE=LibreOffice Would disable all things that use LibreOffice. You can see a list of all endpoints and groups [here](https://github.com/Frooodle/Stirling-PDF/blob/main/groups.md)
-- customStaticFilePath. Customise static files such as the app logo by placing files in the /customFiles/static/ directory. An example of customising app logo is placing a /customFiles/static/favicon.svg to override current SVG. This can be used to change any images/icons/css/fonts/js etc in Stirling-PDF
-
-### Environment only parameters
-- ``SYSTEM_ROOTURIPATH`` ie set to ``/pdf-app`` to Set the application's root URI to ``localhost:8080/pdf-app``
-- ``SYSTEM_CONNECTIONTIMEOUTMINUTES`` to set custom connection timeout values
-- ``DOCKER_ENABLE_SECURITY`` to tell docker to download security jar (required as true for auth login)
-
-## API
-For those wanting to use Stirling-PDFs backend API to link with their own custom scripting to edit PDFs you can view all existing API documentation
-[here](https://app.swaggerhub.com/apis-docs/Frooodle/Stirling-PDF/) or navigate to /swagger-ui/index.html of your stirling-pdf instance for your versions documentation (Or by following the API button in your settings of Stirling-PDF)
-
-
-## Login authentication
-
-### Prerequisites:
-- User must have the folder ./configs volumed within docker so that it is retained during updates.
-- Docker uses must download the security jar version by setting ``DOCKER_ENABLE_SECURITY`` to ``true`` in environment variables.
-- Then either enable login via the settings.yml file or via setting ``SECURITY_ENABLE_LOGIN`` to ``true``
-- Now the initial user will be generated with username ``admin`` and password ``stirling``. On login you will be forced to change the password to a new one. You can also use the environment variables ``SECURITY_INITIALLOGIN_USERNAME`` and ``SECURITY_INITIALLOGIN_PASSWORD`` to set your own straight away (Recommended to remove them after user creation).
-
-Once the above has been done, on restart, a new stirling-pdf-DB.mv.db will show if everything worked.
-
-When you login to Stirling PDF you will be redirected to /login page to login with those default credentials. After login everything should function as normal
-
-To access your account settings go to Account settings in the settings cog menu (top right in navbar) This Account settings menu is also where you find your API key.
-
-To add new users go to the bottom of Account settings and hit 'Admin Settings', here you can add new users. The different roles mentioned within this are for rate limiting. This is a Work in progress which will be expanding on more in future
-
-For API usage you must provide a header with 'X-API-Key' and the associated API key for that user.
-
-
-## FAQ
-
-### Q1: What are your planned features?
-- Progress bar/Tracking
-- Full custom logic pipelines to combine multiple operations together.
-- Folder support with auto scanning to perform operations on
-- Redact text (Via UI not just automated way)
-- Add Forms
-- Annotations
-- Multi page layout (Stich PDF pages together) support x rows y columns and custom page sizing
-- Fill forms mannual and automatic
-
-### Q2: Why is my application downloading .htm files?
-This is a issue caused commonly by your NGINX congifuration. The default file upload size for NGINX is 1MB, you need to add the following in your Nginx sites-available file. ``client_max_body_size SIZE;`` Where "SIZE" is 50M for example for 50MB files.
-
-### Q3: Why is my download timing out
-NGINX has timeout values by default so if you are running Stirling-PDF behind NGINX you may need to set a timeout value such as adding the config ``proxy_read_timeout 3600;``
diff --git a/Version-groups.md b/Version-groups.md
deleted file mode 100644
index 90020579..00000000
--- a/Version-groups.md
+++ /dev/null
@@ -1,59 +0,0 @@
-|Technology | Ultra-Lite | Lite | Full |
-|----------------|:----------:|:----:|:----:|
-| Java | ✔️ | ✔️ | ✔️ |
-| JavaScript | ✔️ | ✔️ | ✔️ |
-| Libre | | ✔️ | ✔️ |
-| Python | | | ✔️ |
-| OpenCV | | | ✔️ |
-| OCRmyPDF | | | ✔️ |
-
-
-
-
-
-Operation | Ultra-Lite | Lite | Full
---------------------|------------|------|-----
-add-page-numbers | ✔️ | ✔️ | ✔️
-add-password | ✔️ | ✔️ | ✔️
-add-image | ✔️ | ✔️ | ✔️
-add-watermark | ✔️ | ✔️ | ✔️
-adjust-contrast | ✔️ | ✔️ | ✔️
-auto-split-pdf | ✔️ | ✔️ | ✔️
-auto-rename | ✔️ | ✔️ | ✔️
-cert-sign | ✔️ | ✔️ | ✔️
-crop | ✔️ | ✔️ | ✔️
-change-metadata | ✔️ | ✔️ | ✔️
-change-permissions | ✔️ | ✔️ | ✔️
-compare | ✔️ | ✔️ | ✔️
-extract-page | ✔️ | ✔️ | ✔️
-extract-images | ✔️ | ✔️ | ✔️
-flatten | ✔️ | ✔️ | ✔️
-get-info-on-pdf | ✔️ | ✔️ | ✔️
-img-to-pdf | ✔️ | ✔️ | ✔️
-markdown-to-pdf | ✔️ | ✔️ | ✔️
-merge-pdfs | ✔️ | ✔️ | ✔️
-multi-page-layout | ✔️ | ✔️ | ✔️
-pdf-organizer | ✔️ | ✔️ | ✔️
-pdf-to-img | ✔️ | ✔️ | ✔️
-pdf-to-single-page | ✔️ | ✔️ | ✔️
-remove-pages | ✔️ | ✔️ | ✔️
-remove-password | ✔️ | ✔️ | ✔️
-rotate-pdf | ✔️ | ✔️ | ✔️
-sanitize-pdf | ✔️ | ✔️ | ✔️
-scale-pages | ✔️ | ✔️ | ✔️
-sign | ✔️ | ✔️ | ✔️
-show-javascript | ✔️ | ✔️ | ✔️
-split-pdfs | ✔️ | ✔️ | ✔️
-file-to-pdf | | ✔️ | ✔️
-pdf-to-html | | ✔️ | ✔️
-pdf-to-presentation | | ✔️ | ✔️
-pdf-to-text | | ✔️ | ✔️
-pdf-to-word | | ✔️ | ✔️
-pdf-to-xml | | ✔️ | ✔️
-repair | | ✔️ | ✔️
-xlsx-to-pdf | | ✔️ | ✔️
-compress-pdf | | | ✔️
-extract-image-scans | | | ✔️
-ocr-pdf | | | ✔️
-pdf-to-pdfa | | | ✔️
-remove-blanks | | | ✔️
diff --git a/build.gradle b/build.gradle
deleted file mode 100644
index d020f2a9..00000000
--- a/build.gradle
+++ /dev/null
@@ -1,140 +0,0 @@
-plugins {
- id 'java'
- id 'org.springframework.boot' version '3.1.2'
- id 'io.spring.dependency-management' version '1.1.3'
- id 'org.springdoc.openapi-gradle-plugin' version '1.6.0'
- id "io.swagger.swaggerhub" version "1.2.0"
- id 'edu.sc.seis.launch4j' version '3.0.5'
-}
-
-group = 'stirling.software'
-version = '0.14.5'
-sourceCompatibility = '17'
-
-repositories {
- mavenCentral()
-}
-
-sourceSets {
- main {
- java {
- if (System.getenv('DOCKER_ENABLE_SECURITY') == 'false') {
- exclude 'stirling/software/SPDF/config/security/**'
- exclude 'stirling/software/SPDF/controller/api/UserController.java'
- exclude 'stirling/software/SPDF/controller/web/AccountWebController.java'
- exclude 'stirling/software/SPDF/model/ApiKeyAuthenticationToken.java'
- exclude 'stirling/software/SPDF/model/Authority.java'
- exclude 'stirling/software/SPDF/model/PersistentLogin.java'
- exclude 'stirling/software/SPDF/model/User.java'
- exclude 'stirling/software/SPDF/repository/**'
- }
- }
- }
-}
-
-
-openApi {
- apiDocsUrl = "http://localhost:8080/v1/api-docs"
- outputDir = file("$projectDir")
- outputFileName = "SwaggerDoc.json"
-}
-
-
-launch4j {
- icon = "${projectDir}/src/main/resources/static/favicon.ico"
-
- outfile="Stirling-PDF.exe"
- headerType="console"
- jarTask = tasks.bootJar
-
- errTitle="Encountered error, Do you have Java 17?"
- downloadUrl="https://download.oracle.com/java/17/latest/jdk-17_windows-x64_bin.exe"
- variables=["BROWSER_OPEN=true"]
- jreMinVersion="17"
-
- mutexName="Stirling-PDF"
- windowTitle="Stirling-PDF"
-
- messagesStartupError="An error occurred while starting Stirling-PDF"
- //messagesJreNotFoundError="This application requires a Java Runtime Environment, Please download Java 17."
- messagesJreVersionError="You are running the wrong version of Java, Please download Java 17."
- messagesLauncherError="Java is corrupted. Please uninstall and then install Java 17."
- messagesInstanceAlreadyExists="Stirling-PDF is already running."
-}
-
-dependencies {
- implementation 'org.yaml:snakeyaml:2.1'
- implementation 'org.springframework.boot:spring-boot-starter-web:3.1.2'
- implementation 'org.springframework.boot:spring-boot-starter-thymeleaf:3.1.2'
-
- if (System.getenv('DOCKER_ENABLE_SECURITY') != 'false') {
- implementation 'org.springframework.boot:spring-boot-starter-security:3.1.2'
- implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5:3.1.2.RELEASE'
- implementation "org.springframework.boot:spring-boot-starter-data-jpa"
- implementation "com.h2database:h2"
- }
-
- testImplementation 'org.springframework.boot:spring-boot-starter-test:3.1.4'
-
-
-
- // https://mvnrepository.com/artifact/org.apache.pdfbox/jbig2-imageio
- implementation group: 'org.apache.pdfbox', name: 'jbig2-imageio', version: '3.0.4'
- implementation 'commons-io:commons-io:2.13.0'
-
- implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.2.0'
-
- //general PDF
- implementation 'org.apache.pdfbox:pdfbox:2.0.29'
- implementation 'org.apache.pdfbox:xmpbox:2.0.29'
- implementation 'org.bouncycastle:bcprov-jdk15on:1.70'
- implementation 'org.bouncycastle:bcpkix-jdk15on:1.70'
- implementation 'org.springframework.boot:spring-boot-starter-actuator'
- implementation 'io.micrometer:micrometer-core'
- implementation group: 'com.google.zxing', name: 'core', version: '3.5.2'
- // https://mvnrepository.com/artifact/org.commonmark/commonmark
- implementation 'org.commonmark:commonmark:0.21.0'
- // https://mvnrepository.com/artifact/com.github.vladimir-bukhtoyarov/bucket4j-core
- implementation 'com.github.vladimir-bukhtoyarov:bucket4j-core:7.6.0'
-
- developmentOnly("org.springframework.boot:spring-boot-devtools")
- compileOnly 'org.projectlombok:lombok:1.18.28'
- annotationProcessor 'org.projectlombok:lombok:1.18.28'
-
-}
-
-task writeVersion {
- def propsFile = file('src/main/resources/version.properties')
- def props = new Properties()
- props.setProperty('version', version)
- props.store(propsFile.newWriter(), null)
-}
-
-swaggerhubUpload {
- //dependsOn generateOpenApiDocs // Depends on your task generating Swagger docs
- api 'Stirling-PDF' // The name of your API on SwaggerHub
- owner 'Frooodle' // Your SwaggerHub username (or organization name)
- version project.version // The version of your API
- inputFile './SwaggerDoc.json' // The path to your Swagger docs
- token "${System.getenv('SWAGGERHUB_API_KEY')}" // Your SwaggerHub API key, passed as an environment variable
- oas '3.0.0' // The version of the OpenAPI Specification you're using
-}
-
-
-
-jar {
- enabled = false
- manifest {
- attributes 'Implementation-Title': 'Stirling-PDF',
- 'Implementation-Version': project.version
- }
-
-}
-
-tasks.named('test') {
- useJUnitPlatform()
-}
-
-task printVersion {
- println project.version
-}
diff --git a/chart/stirling-pdf/Chart.yaml b/chart/stirling-pdf/Chart.yaml
deleted file mode 100644
index 3482b36d..00000000
--- a/chart/stirling-pdf/Chart.yaml
+++ /dev/null
@@ -1,15 +0,0 @@
-apiVersion: v2
-appVersion: 0.14.2
-description: locally hosted web application that allows you to perform various operations on PDF files
-home: https://github.com/Frooodle/Stirling-PDF
-keywords:
-- stirling-pdf
-- helm
-- charts repo
-maintainers:
-- name: Frooodle
- url: https://github.com/Frooodle/Stirling-PDF
-name: stirling-pdf
-sources:
-- https://github.com/Frooodle/Stirling-PDF
-version: 1.0.0
diff --git a/chart/stirling-pdf/templates/NOTES.txt b/chart/stirling-pdf/templates/NOTES.txt
deleted file mode 100644
index 3b432f00..00000000
--- a/chart/stirling-pdf/templates/NOTES.txt
+++ /dev/null
@@ -1,30 +0,0 @@
-** Please be patient while the chart is being deployed **
-
-Get the stirlingpdf URL by running:
-
-{{- if contains "NodePort" .Values.service.type }}
-
- export NODE_PORT=$(kubectl get --namespace {{ .Release.Namespace }} -o jsonpath="{.spec.ports[0].nodePort}" services {{ template "stirlingpdf.fullname" . }})
- export NODE_IP=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath="{.items[0].status.addresses[0].address}")
- echo http://$NODE_IP:$NODE_PORT/
-
-{{- else if contains "LoadBalancer" .Values.service.type }}
-
-** Please ensure an external IP is associated to the {{ template "stirlingpdf.fullname" . }} service before proceeding **
-** Watch the status using: kubectl get svc --namespace {{ .Release.Namespace }} -w {{ template "stirlingpdf.fullname" . }} **
-
- export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ template "stirlingpdf.fullname" . }} -o jsonpath='{.status.loadBalancer.ingress[0].ip}')
- echo http://$SERVICE_IP:{{ .Values.service.externalPort }}/
-
-OR
-
- export SERVICE_HOST=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ template "stirlingpdf.fullname" . }} -o jsonpath='{.status.loadBalancer.ingress[0].hostname}')
- echo http://$SERVICE_HOST:{{ .Values.service.externalPort }}/
-
-{{- else if contains "ClusterIP" .Values.service.type }}
-
- export POD_NAME=$(kubectl get pods --namespace {{ .Release.Namespace }} -l "app={{ template "stirlingpdf.name" . }}" -l "release={{ .Release.Name }}" -o jsonpath="{.items[0].metadata.name}")
- echo http://127.0.0.1:8080/
- kubectl port-forward $POD_NAME 8080:8080 --namespace {{ .Release.Namespace }}
-
-{{- end }}
diff --git a/chart/stirling-pdf/templates/_helpers.tpl b/chart/stirling-pdf/templates/_helpers.tpl
deleted file mode 100644
index 4c862604..00000000
--- a/chart/stirling-pdf/templates/_helpers.tpl
+++ /dev/null
@@ -1,129 +0,0 @@
-{{/*
-Expand the name of the chart.
-*/}}
-{{- define "stirlingpdf.name" -}}
-{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
-{{- end }}
-
-{{/*
-Create a default fully qualified app name.
-We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
-If release name contains chart name it will be used as a full name.
-*/}}
-{{- define "stirlingpdf.fullname" -}}
-{{- if .Values.fullnameOverride }}
-{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
-{{- else }}
-{{- $name := default .Chart.Name .Values.nameOverride }}
-{{- if contains $name .Release.Name }}
-{{- .Release.Name | trunc 63 | trimSuffix "-" }}
-{{- else }}
-{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
-{{- end }}
-{{- end }}
-{{- end }}
-
-{{- /*
-Create chart name and version as used by the chart label.
-
-It does minimal escaping for use in Kubernetes labels.
-
-Example output:
-
-stirlingpdf-0.4.5
-*/ -}}
-{{- define "stirlingpdf.chart" -}}
-{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
-{{- end -}}
-
-{{/*
-Common labels
-*/}}
-{{- define "stirlingpdf.labels" -}}
-helm.sh/chart: {{ include "stirlingpdf.chart" . }}
-{{ include "stirlingpdf.selectorLabels" . }}
-{{- if .Chart.AppVersion }}
-app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
-{{- end }}
-{{- if .Values.commonLabels}}
-{{ toYaml .Values.commonLabels }}
-{{- end }}
-app.kubernetes.io/managed-by: {{ .Release.Service }}
-{{- end }}
-
-{{/*
-Selector labels
-*/}}
-{{- define "stirlingpdf.selectorLabels" -}}
-app.kubernetes.io/name: {{ include "stirlingpdf.name" . }}
-app.kubernetes.io/instance: {{ .Release.Name }}
-{{- end }}
-
-{{/*
-Create the name of the service account to use
-*/}}
-{{- define "stirlingpdf.serviceAccountName" -}}
-{{- if .Values.serviceAccount.create }}
-{{- default (include "stirlingpdf.fullname" .) .Values.serviceAccount.name }}
-{{- else }}
-{{- default "default" .Values.serviceAccount.name }}
-{{- end }}
-{{- end }}
-
-{{/*
-Return the proper image name to change the volume permissions
-*/}}
-{{- define "stirlingpdf.volumePermissions.image" -}}
-{{- $registryName := .Values.volumePermissions.image.registry -}}
-{{- $repositoryName := .Values.volumePermissions.image.repository -}}
-{{- $tag := .Values.volumePermissions.image.tag | toString -}}
-{{/*
-Helm 2.11 supports the assignment of a value to a variable defined in a different scope,
-but Helm 2.9 and 2.10 doesn't support it, so we need to implement this if-else logic.
-Also, we can't use a single if because lazy evaluation is not an option
-*/}}
-{{- if .Values.global }}
- {{- if .Values.global.imageRegistry }}
- {{- printf "%s/%s:%s" .Values.global.imageRegistry $repositoryName $tag -}}
- {{- else -}}
- {{- printf "%s/%s:%s" $registryName $repositoryName $tag -}}
- {{- end -}}
-{{- else -}}
- {{- printf "%s/%s:%s" $registryName $repositoryName $tag -}}
-{{- end -}}
-{{- end -}}
-
-{{/*
-Return the proper Docker Image Registry Secret Names
-*/}}
-{{- define "stirlingpdf.imagePullSecrets" -}}
-{{/*
-Helm 2.11 supports the assignment of a value to a variable defined in a different scope,
-but Helm 2.9 and 2.10 does not support it, so we need to implement this if-else logic.
-Also, we can not use a single if because lazy evaluation is not an option
-*/}}
-{{- if .Values.global }}
-{{- if .Values.global.imagePullSecrets }}
-imagePullSecrets:
-{{- range .Values.global.imagePullSecrets }}
- - name: {{ . }}
-{{- end }}
-{{- else if or .Values.image.pullSecrets .Values.volumePermissions.image.pullSecrets }}
-imagePullSecrets:
-{{- range .Values.image.pullSecrets }}
- - name: {{ . }}
-{{- end }}
-{{- range .Values.volumePermissions.image.pullSecrets }}
- - name: {{ . }}
-{{- end }}
-{{- end -}}
-{{- else if or .Values.image.pullSecrets .Values.volumePermissions.image.pullSecrets }}
-imagePullSecrets:
-{{- range .Values.image.pullSecrets }}
- - name: {{ . }}
-{{- end }}
-{{- range .Values.volumePermissions.image.pullSecrets }}
- - name: {{ . }}
-{{- end }}
-{{- end -}}
-{{- end -}}
\ No newline at end of file
diff --git a/chart/stirling-pdf/templates/deployment.yaml b/chart/stirling-pdf/templates/deployment.yaml
deleted file mode 100644
index 290a56c9..00000000
--- a/chart/stirling-pdf/templates/deployment.yaml
+++ /dev/null
@@ -1,129 +0,0 @@
-apiVersion: apps/v1
-kind: Deployment
-metadata:
- name: {{ include "stirlingpdf.fullname" . }}
- {{- with .Values.deployment.annotations }}
- annotations:
- {{- toYaml . | nindent 4 }}
- {{- end }}
- labels:
- {{- include "stirlingpdf.labels" . | nindent 4 }}
- {{- if .Values.deployment.labels }}
- {{- toYaml .Values.deployment.labels | nindent 4 }}
- {{- end }}
-spec:
- selector:
- matchLabels:
- {{- include "stirlingpdf.selectorLabels" . | nindent 6 }}
- replicas: {{ .Values.replicaCount }}
- strategy:
-{{ toYaml .Values.strategy | indent 4 }}
- revisionHistoryLimit: 10
- template:
- metadata:
- {{- with .Values.podAnnotations }}
- annotations:
- {{- toYaml . | nindent 8 }}
- {{- end }}
- labels:
- {{- include "stirlingpdf.selectorLabels" . | nindent 8 }}
- {{- if .Values.podLabels }}
- {{- toYaml .Values.podLabels | nindent 8 }}
- {{- end }}
- spec:
- {{- if .Values.priorityClassName }}
- priorityClassName: "{{ .Values.priorityClassName }}"
- {{- end }}
- {{- if .Values.securityContext.enabled }}
- securityContext:
- fsGroup: {{ .Values.securityContext.fsGroup }}
- {{- if .Values.securityContext.runAsNonRoot }}
- runAsNonRoot: {{ .Values.securityContext.runAsNonRoot }}
- {{- end }}
- {{- if .Values.securityContext.supplementalGroups }}
- supplementalGroups: {{ .Values.securityContext.supplementalGroups }}
- {{- end }}
- {{- else if .Values.persistence.enabled }}
- initContainers:
- - name: volume-permissions
- image: {{ template "stirlingpdf.volumePermissions.image" . }}
- imagePullPolicy: "{{ .Values.volumePermissions.image.pullPolicy }}"
- securityContext:
- {{- toYaml .Values.containerSecurityContext | nindent 10 }}
- command: ['sh', '-c', 'chown -R {{ .Values.securityContext.fsGroup }}:{{ .Values.securityContext.fsGroup }} {{ .Values.persistence.path }}']
- volumeMounts:
- - mountPath: {{ .Values.persistence.path }}
- name: storage-volume
- {{- end }}
-{{- include "stirlingpdf.imagePullSecrets" . | indent 6 }}
- containers:
- - name: {{ .Chart.Name }}
- image: {{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}
- imagePullPolicy: {{ .Values.image.pullPolicy }}
- securityContext:
- {{- toYaml .Values.containerSecurityContext | nindent 10 }}
-{{- if .Values.envs }}
- env:
-{{ toYaml .Values.envs | indent 8 }}
-{{- end }}
-{{- if .Values.extraArgs }}
- args:
-{{ toYaml .Values.extraArgs | indent 8 }}
-{{- end }}
- ports:
- - name: http
- containerPort: 8080
- livenessProbe:
- httpGet:
- path: /
- port: http
-{{ toYaml .Values.probes.livenessHttpGetConfig | indent 12 }}
-{{ toYaml .Values.probes.liveness | indent 10 }}
- readinessProbe:
- httpGet:
- path: /
- port: http
-{{ toYaml .Values.probes.readinessHttpGetConfig | indent 12 }}
-{{ toYaml .Values.probes.readiness | indent 10 }}
- volumeMounts:
-{{- if .Values.deployment.extraVolumeMounts }}
- {{- toYaml .Values.deployment.extraVolumeMounts | nindent 8 }}
-{{- end }}
-{{- if .Values.deployment.sidecarContainers }}
-{{- range $name, $spec := .Values.deployment.sidecarContainers }}
- - name: {{ $name }}
-{{- toYaml $spec | nindent 8 }}
-{{- end }}
-{{- end }}
- {{- with .Values.resources }}
- resources:
-{{ toYaml . | indent 10 }}
- {{- end }}
- {{- with .Values.nodeSelector }}
- nodeSelector:
-{{ toYaml . | indent 8 }}
- {{- end }}
- {{- with .Values.affinity }}
- affinity:
-{{ toYaml . | indent 8 }}
- {{- end }}
- {{- with .Values.tolerations }}
- tolerations:
-{{ toYaml . | indent 8 }}
- {{- end }}
- {{- if .Values.schedulerName }}
- schedulerName: {{ .Values.schedulerName }}
- {{- end }}
- serviceAccountName: {{ include "stirlingpdf.serviceAccountName" . }}
- automountServiceAccountToken: {{ .Values.serviceAccount.automountServiceAccountToken }}
- volumes:
- {{- if .Values.deployment.extraVolumes }}
- {{- toYaml .Values.deployment.extraVolumes | nindent 6 }}
- {{- end }}
- - name: storage-volume
- {{- if .Values.persistence.enabled }}
- persistentVolumeClaim:
- claimName: {{ .Values.persistence.existingClaim | default (include "stirlingpdf.fullname" .) }}
- {{- else }}
- emptyDir: {}
- {{- end }}
diff --git a/chart/stirling-pdf/templates/ingress.yaml b/chart/stirling-pdf/templates/ingress.yaml
deleted file mode 100644
index c09fef68..00000000
--- a/chart/stirling-pdf/templates/ingress.yaml
+++ /dev/null
@@ -1,85 +0,0 @@
-{{- if .Values.ingress.enabled }}
-{{- $servicePort := .Values.service.externalPort -}}
-{{- $serviceName := include "stirlingpdf.fullname" . -}}
-{{- $ingressExtraPaths := .Values.ingress.extraPaths -}}
----
-{{- if semverCompare "<1.14-0" .Capabilities.KubeVersion.GitVersion }}
-apiVersion: extensions/v1beta1
-{{- else if semverCompare "<1.19-0" .Capabilities.KubeVersion.GitVersion }}
-apiVersion: networking.k8s.io/v1beta1
-{{- else }}
-apiVersion: networking.k8s.io/v1
-{{- end }}
-kind: Ingress
-metadata:
- name: {{ include "stirlingpdf.fullname" . }}
- {{- with .Values.ingress.annotations }}
- annotations:
- {{- toYaml . | nindent 4 }}
- {{- end }}
- labels:
- {{- include "stirlingpdf.labels" . | nindent 4 }}
- {{- with .Values.ingress.labels }}
- {{- toYaml . | nindent 4 }}
- {{- end }}
-spec:
- {{- with .Values.ingress.ingressClassName }}
- ingressClassName: {{ . }}
- {{- end }}
- rules:
- {{- range .Values.ingress.hosts }}
- - host: {{ .name }}
- http:
- paths:
- {{- range $ingressExtraPaths }}
- - path: {{ default "/" .path | quote }}
- backend:
- {{- if semverCompare "<1.19-0" $.Capabilities.KubeVersion.GitVersion }}
- {{- if $.Values.service.servicename }}
- serviceName: {{ $.Values.service.servicename }}
- {{- else }}
- serviceName: {{ default $serviceName .service }}
- {{- end }}
- servicePort: {{ default $servicePort .port }}
- {{- else }}
- service:
- {{- if $.Values.service.servicename }}
- name: {{ $.Values.service.servicename }}
- {{- else }}
- name: {{ default $serviceName .service }}
- {{- end }}
- port:
- number: {{ default $servicePort .port }}
- pathType: {{ default $.Values.ingress.pathType .pathType }}
- {{- end }}
- {{- end }}
- - path: {{ default "/" .path | quote }}
- backend:
- {{- if semverCompare "<1.19-0" $.Capabilities.KubeVersion.GitVersion }}
- {{- if $.Values.service.servicename }}
- serviceName: {{ $.Values.service.servicename }}
- {{- else }}
- serviceName: {{ default $serviceName .service }}
- {{- end }}
- servicePort: {{ default $servicePort .servicePort }}
- {{- else }}
- service:
- {{- if $.Values.service.servicename }}
- name: {{ $.Values.service.servicename }}
- {{- else }}
- name: {{ default $serviceName .service }}
- {{- end }}
- port:
- number: {{ default $servicePort .port }}
- pathType: {{ $.Values.ingress.pathType }}
- {{- end }}
- {{- end }}
- tls:
- {{- range .Values.ingress.hosts }}
- {{- if .tls }}
- - hosts:
- - {{ .name }}
- secretName: {{ .tlsSecret }}
- {{- end }}
- {{- end }}
-{{- end -}}
diff --git a/chart/stirling-pdf/templates/pv.yaml b/chart/stirling-pdf/templates/pv.yaml
deleted file mode 100644
index aa99c6a9..00000000
--- a/chart/stirling-pdf/templates/pv.yaml
+++ /dev/null
@@ -1,16 +0,0 @@
-{{- if .Values.persistence.pv.enabled -}}
-apiVersion: v1
-kind: PersistentVolume
-metadata:
- name: {{ .Values.persistence.pv.pvname | default (include "stirlingpdf.fullname" .) }}
- labels:
- {{- include "stirlingpdf.labels" . | nindent 4 }}
-spec:
- capacity:
- storage: {{ .Values.persistence.pv.capacity.storage }}
- accessModes:
- - {{ .Values.persistence.pv.accessMode | quote }}
- nfs:
- server: {{ .Values.persistence.pv.nfs.server }}
- path: {{ .Values.persistence.pv.nfs.path | quote }}
-{{- end }}
\ No newline at end of file
diff --git a/chart/stirling-pdf/templates/pvc.yaml b/chart/stirling-pdf/templates/pvc.yaml
deleted file mode 100644
index f7a21722..00000000
--- a/chart/stirling-pdf/templates/pvc.yaml
+++ /dev/null
@@ -1,27 +0,0 @@
-{{- if and .Values.persistence.enabled (not .Values.persistence.existingClaim) -}}
-kind: PersistentVolumeClaim
-apiVersion: v1
-metadata:
- name: {{ include "stirlingpdf.fullname" . }}
- labels:
- {{- include "stirlingpdf.labels" . | nindent 4 }}
- {{- with .Values.persistence.labels }}
- {{- toYaml . | nindent 4 }}
- {{- end }}
-spec:
- accessModes:
- - {{ .Values.persistence.accessMode | quote }}
- resources:
- requests:
- storage: {{ .Values.persistence.size | quote }}
-{{- if .Values.persistence.storageClass }}
-{{- if (eq "-" .Values.persistence.storageClass) }}
- storageClassName: ""
-{{- else }}
- storageClassName: "{{ .Values.persistence.storageClass }}"
-{{- end }}
-{{- if .Values.persistence.volumeName }}
- volumeName: "{{ .Values.persistence.volumeName }}"
-{{- end }}
-{{- end }}
-{{- end }}
diff --git a/chart/stirling-pdf/templates/service.yaml b/chart/stirling-pdf/templates/service.yaml
deleted file mode 100644
index a529c3f2..00000000
--- a/chart/stirling-pdf/templates/service.yaml
+++ /dev/null
@@ -1,48 +0,0 @@
-apiVersion: v1
-kind: Service
-metadata:
- name: {{ .Values.service.servicename | default (include "stirlingpdf.fullname" .) }}
- {{- with .Values.service.annotations }}
- annotations:
- {{- toYaml . | nindent 4 }}
- {{- end }}
- labels:
- {{- include "stirlingpdf.labels" . | nindent 4 }}
- {{- with .Values.service.labels }}
- {{- toYaml . | nindent 4 }}
- {{- end }}
-spec:
- type: {{ .Values.service.type }}
- {{- if (or (eq .Values.service.type "LoadBalancer") (and (eq .Values.service.type "NodePort") (not (empty .Values.service.nodePort)))) }}
- externalTrafficPolicy: {{ .Values.service.externalTrafficPolicy }}
- {{- end }}
- {{- if (and (eq .Values.service.type "LoadBalancer") .Values.service.loadBalancerIP) }}
- loadBalancerIP: {{ .Values.service.loadBalancerIP }}
- {{- end }}
- {{- if (and (eq .Values.service.type "LoadBalancer") .Values.service.loadBalancerSourceRanges) }}
- loadBalancerSourceRanges:
- {{- with .Values.service.loadBalancerSourceRanges }}
-{{ toYaml . | indent 2 }}
- {{- end }}
- {{- end }}
- {{- if eq .Values.service.type "ClusterIP" }}
- {{- if .Values.service.clusterIP }}
- clusterIP: {{ .Values.service.clusterIP }}
- {{- end }}
- {{- end }}
- ports:
- - port: {{ .Values.service.externalPort }}
-{{- if (and (eq .Values.service.type "NodePort") (not (empty .Values.service.nodePort))) }}
- nodePort: {{.Values.service.nodePort}}
-{{- end }}
-{{- if .Values.service.targetPort }}
- targetPort: {{ .Values.service.targetPort }}
- name: {{ .Values.service.targetPort }}
-{{- else }}
- targetPort: http
- name: http
-{{- end }}
- protocol: TCP
-
- selector:
- {{- include "stirlingpdf.selectorLabels" . | nindent 4 }}
diff --git a/chart/stirling-pdf/templates/serviceaccount.yaml b/chart/stirling-pdf/templates/serviceaccount.yaml
deleted file mode 100644
index 7156e4a4..00000000
--- a/chart/stirling-pdf/templates/serviceaccount.yaml
+++ /dev/null
@@ -1,13 +0,0 @@
-{{- if .Values.serviceAccount.create -}}
----
-apiVersion: v1
-kind: ServiceAccount
-metadata:
- name: {{ include "stirlingpdf.serviceAccountName" . }}
- {{- with .Values.serviceAccount.annotations }}
- annotations:
- {{ toYaml . | nindent 4 }}
- {{- end }}
- labels:
- {{- include "stirlingpdf.labels" . | nindent 4 }}
-{{- end }}
diff --git a/chart/stirling-pdf/templates/servicemonitor.yaml b/chart/stirling-pdf/templates/servicemonitor.yaml
deleted file mode 100644
index ca0d31bb..00000000
--- a/chart/stirling-pdf/templates/servicemonitor.yaml
+++ /dev/null
@@ -1,31 +0,0 @@
-{{- if and ( .Capabilities.APIVersions.Has "monitoring.coreos.com/v1" ) ( .Values.serviceMonitor.enabled ) }}
-apiVersion: monitoring.coreos.com/v1
-kind: ServiceMonitor
-metadata:
- name: {{ include "stirlingpdf.fullname" . }}
- namespace: {{ .Values.serviceMonitor.namespace | default .Release.Namespace }}
- labels:
- {{- include "stirlingpdf.labels" . | nindent 4 }}
- {{- with .Values.serviceMonitor.labels }}
- {{- toYaml . | nindent 4 }}
- {{- end }}
-spec:
- endpoints:
- - targetPort: 8080
-{{- if .Values.serviceMonitor.interval }}
- interval: {{ .Values.serviceMonitor.interval }}
-{{- end }}
-{{- if .Values.serviceMonitor.metricsPath }}
- path: {{ .Values.serviceMonitor.metricsPath }}
-{{- end }}
-{{- if .Values.serviceMonitor.timeout }}
- scrapeTimeout: {{ .Values.serviceMonitor.timeout }}
-{{- end }}
- jobLabel: {{ include "stirlingpdf.fullname" . }}
- namespaceSelector:
- matchNames:
- - {{ .Release.Namespace }}
- selector:
- matchLabels:
- {{- include "stirlingpdf.selectorLabels" . | nindent 6 }}
-{{- end }}
diff --git a/chart/stirling-pdf/values.yaml b/chart/stirling-pdf/values.yaml
deleted file mode 100644
index 3c4ca888..00000000
--- a/chart/stirling-pdf/values.yaml
+++ /dev/null
@@ -1,239 +0,0 @@
-extraArgs: []
- # - --storage-timestamp-tolerance 1s
-replicaCount: 1
-strategy:
- type: RollingUpdate
-image:
- repository: frooodle/s-pdf
- # took Chart appVersion by default
- tag: ~
- pullPolicy: IfNotPresent
-secret:
- labels: {}
-## Labels to apply to all resources
-##
-commonLabels: {}
-# team_name: dev
-
-envs: []
-# - name: PP_HOME_NAME
-# value: "Stirling PDF"
-# - name: APP_HOME_DESCRIPTION
-# value: "Your locally hosted one-stop-shop for all your PDF needs."
-# - name: APP_NAVBAR_NAME
-# value: "Stirling PDF"
-# - name: ALLOW_GOOGLE_VISIBILITY
-# value: "true"
-# - name: APP_ROOT_PATH
-# value: "/"
-# - name: APP_LOCALE
-# value: "en_GB"
-
-deployment:
- ## stirling-pdf Deployment annotations
- annotations: {}
- # name: value
- labels: {}
- # name: value
- # additional volumes
- extraVolumes: []
- # - name: nginx-config
- # secret:
- # secretName: nginx-config
- # additional volumes to mount
- extraVolumeMounts: []
- ## sidecarContainers for the stirling-pdf
- # Can be used to add a proxy to the pod that does
- # scanning for secrets, signing, authentication, validation
- # of the chart's content, send notifications...
- sidecarContainers: {}
- ## Example sidecarContainer which uses an extraVolume from above and
- ## a named port that can be referenced in the service as targetPort.
- # proxy:
- # image: nginx:latest
- # ports:
- # - name: proxy
- # containerPort: 8081
- # volumeMounts:
- # - name: nginx-config
- # readOnly: true
- # mountPath: /etc/nginx
-
-## Pod annotations
-## ref: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/
-## Read more about kube2iam to provide access to s3 https://github.com/jtblin/kube2iam
-##
-podAnnotations: {}
- # iam.amazonaws.com/role: role-arn
-
-## Pod labels
-## ref: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/
-podLabels: {}
- # name: value
-
-service:
- servicename:
- type: ClusterIP
- externalTrafficPolicy: Local
- ## Uses pre-assigned IP address from cloud provider
- ## Only valid if service.type: LoadBalancer
- loadBalancerIP:
- ## Limits which cidr blocks can connect to service's load balancer
- ## Only valid if service.type: LoadBalancer
- loadBalancerSourceRanges: []
- # clusterIP: None
- externalPort: 8080
- ## targetPort of the container to use. If a sidecar should handle the
- ## requests first, use the named port from the sidecar. See sidecar example
- ## from deployment above. Leave empty to use stirling-pdf directly.
- targetPort:
- nodePort:
- annotations: {}
- labels: {}
-
-serviceMonitor:
- enabled: false
- # namespace: prometheus
- labels: {}
- metricsPath: "/metrics"
- # timeout: 60
- # interval: 60
-
-resources: {}
-# limits:
-# cpu: 100m
-# memory: 128Mi
-# requests:
-# cpu: 80m
-# memory: 64Mi
-
-probes:
- liveness:
- initialDelaySeconds: 5
- periodSeconds: 10
- timeoutSeconds: 1
- successThreshold: 1
- failureThreshold: 3
- livenessHttpGetConfig:
- scheme: HTTP
- readiness:
- initialDelaySeconds: 5
- periodSeconds: 10
- timeoutSeconds: 1
- successThreshold: 1
- failureThreshold: 3
- readinessHttpGetConfig:
- scheme: HTTP
-
-serviceAccount:
- create: true
- name: ""
- automountServiceAccountToken: false
- ## Annotations for the Service Account
- annotations: {}
-
-# UID/GID 1000 is the default user "stirling-pdf" used in
-# the container image starting in v0.8.0 and above. This
-# is required for local persistent storage. If your cluster
-# does not allow this, try setting securityContext: {}
-securityContext:
- enabled: true
- fsGroup: 1000
- ## Optionally, specify supplementalGroups and/or
- ## runAsNonRoot for security purposes
- # runAsNonRoot: true
- # supplementalGroups: [1000]
-
-containerSecurityContext: {}
-
-priorityClassName: ""
-
-nodeSelector: {}
-
-tolerations: []
-
-affinity: {}
-
-persistence:
- enabled: false
- accessMode: ReadWriteOnce
- size: 8Gi
- labels: {}
- # name: value
- path: /tmp
- ## A manually managed Persistent Volume and Claim
- ## Requires persistence.enabled: true
- ## If defined, PVC must be created manually before volume will be bound
- # existingClaim:
-
- ## stirling-pdf data Persistent Volume Storage Class
- ## If defined, storageClassName:
- ## If set to "-", storageClassName: "", which disables dynamic provisioning
- ## If undefined (the default) or set to null, no storageClassName spec is
- ## set, choosing the default provisioner. (gp2 on AWS, standard on
- ## GKE, AWS & OpenStack)
- ##
- # storageClass: "-"
- # volumeName:
- pv:
- enabled: false
- pvname:
- capacity:
- storage: 8Gi
- accessMode: ReadWriteOnce
- nfs:
- server:
- path:
-
-## Init containers parameters:
-## volumePermissions: Change the owner of the persistent volume mountpoint to RunAsUser:fsGroup
-##
-volumePermissions:
- image:
- registry: docker.io
- repository: bitnami/minideb
- tag: buster
- pullPolicy: Always
- ## Optionally specify an array of imagePullSecrets.
- ## Secrets must be manually created in the namespace.
- ## ref: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/
- ##
- # pullSecrets:
- # - myRegistryKeySecretName
-
-## Ingress for load balancer
-ingress:
- enabled: false
- pathType: "ImplementationSpecific"
- ## stirling-pdf Ingress labels
- ##
- labels: {}
- # dns: "route53"
-
- ## stirling-pdf Ingress annotations
- ##
- annotations: {}
- # kubernetes.io/ingress.class: nginx
- # kubernetes.io/tls-acme: "true"
-
- ## stirling-pdf Ingress hostnames
- ## Must be provided if Ingress is enabled
- ##
- hosts: []
- # - name: stirling-pdf.domain1.com
- # path: /
- # tls: false
- # - name: stirling-pdf.domain2.com
- # path: /
- #
- # ## Set this to true in order to enable TLS on the ingress record
- # tls: true
- #
- # ## If TLS is set to true, you must declare what secret will store the key/certificate for TLS
- # ## Secrets must be added manually to the namespace
- # tlsSecret: stirling-pdf.domain2-tls
-
- # For Kubernetes >= 1.18 you should specify the ingress-controller via the field ingressClassName
- # See https://kubernetes.io/blog/2020/04/02/improvements-to-the-ingress-api-in-kubernetes-1.18/#specifying-the-class-of-an-ingress
- ingressClassName:
-
diff --git a/docs/stirling-pdf.png b/docs/stirling-pdf.png
deleted file mode 100644
index 11695d86..00000000
Binary files a/docs/stirling-pdf.png and /dev/null differ
diff --git a/docs/stirling-transparent.svg b/docs/stirling-transparent.svg
deleted file mode 100644
index 700e6444..00000000
--- a/docs/stirling-transparent.svg
+++ /dev/null
@@ -1,298 +0,0 @@
-
-
-
-
diff --git a/docs/stirling.png b/docs/stirling.png
deleted file mode 100644
index 11695d86..00000000
Binary files a/docs/stirling.png and /dev/null differ
diff --git a/docs/stirling.svg b/docs/stirling.svg
deleted file mode 100644
index 1a14a42f..00000000
--- a/docs/stirling.svg
+++ /dev/null
@@ -1,310 +0,0 @@
-
-
-
-
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
deleted file mode 100644
index 249e5832..00000000
Binary files a/gradle/wrapper/gradle-wrapper.jar and /dev/null differ
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
deleted file mode 100644
index 070cb702..00000000
--- a/gradle/wrapper/gradle-wrapper.properties
+++ /dev/null
@@ -1,5 +0,0 @@
-distributionBase=GRADLE_USER_HOME
-distributionPath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
-zipStoreBase=GRADLE_USER_HOME
-zipStorePath=wrapper/dists
diff --git a/gradlew b/gradlew
deleted file mode 100644
index a69d9cb6..00000000
--- a/gradlew
+++ /dev/null
@@ -1,240 +0,0 @@
-#!/bin/sh
-
-#
-# Copyright © 2015-2021 the original authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# https://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-##############################################################################
-#
-# Gradle start up script for POSIX generated by Gradle.
-#
-# Important for running:
-#
-# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
-# noncompliant, but you have some other compliant shell such as ksh or
-# bash, then to run this script, type that shell name before the whole
-# command line, like:
-#
-# ksh Gradle
-#
-# Busybox and similar reduced shells will NOT work, because this script
-# requires all of these POSIX shell features:
-# * functions;
-# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
-# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
-# * compound commands having a testable exit status, especially «case»;
-# * various built-in commands including «command», «set», and «ulimit».
-#
-# Important for patching:
-#
-# (2) This script targets any POSIX shell, so it avoids extensions provided
-# by Bash, Ksh, etc; in particular arrays are avoided.
-#
-# The "traditional" practice of packing multiple parameters into a
-# space-separated string is a well documented source of bugs and security
-# problems, so this is (mostly) avoided, by progressively accumulating
-# options in "$@", and eventually passing that to Java.
-#
-# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
-# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
-# see the in-line comments for details.
-#
-# There are tweaks for specific operating systems such as AIX, CygWin,
-# Darwin, MinGW, and NonStop.
-#
-# (3) This script is generated from the Groovy template
-# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
-# within the Gradle project.
-#
-# You can find Gradle at https://github.com/gradle/gradle/.
-#
-##############################################################################
-
-# Attempt to set APP_HOME
-
-# Resolve links: $0 may be a link
-app_path=$0
-
-# Need this for daisy-chained symlinks.
-while
- APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
- [ -h "$app_path" ]
-do
- ls=$( ls -ld "$app_path" )
- link=${ls#*' -> '}
- case $link in #(
- /*) app_path=$link ;; #(
- *) app_path=$APP_HOME$link ;;
- esac
-done
-
-APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
-
-APP_NAME="Gradle"
-APP_BASE_NAME=${0##*/}
-
-# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
-
-# Use the maximum available, or set MAX_FD != -1 to use that value.
-MAX_FD=maximum
-
-warn () {
- echo "$*"
-} >&2
-
-die () {
- echo
- echo "$*"
- echo
- exit 1
-} >&2
-
-# OS specific support (must be 'true' or 'false').
-cygwin=false
-msys=false
-darwin=false
-nonstop=false
-case "$( uname )" in #(
- CYGWIN* ) cygwin=true ;; #(
- Darwin* ) darwin=true ;; #(
- MSYS* | MINGW* ) msys=true ;; #(
- NONSTOP* ) nonstop=true ;;
-esac
-
-CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
-
-
-# Determine the Java command to use to start the JVM.
-if [ -n "$JAVA_HOME" ] ; then
- if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
- # IBM's JDK on AIX uses strange locations for the executables
- JAVACMD=$JAVA_HOME/jre/sh/java
- else
- JAVACMD=$JAVA_HOME/bin/java
- fi
- if [ ! -x "$JAVACMD" ] ; then
- die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
- fi
-else
- JAVACMD=java
- which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-
-Please set the JAVA_HOME variable in your environment to match the
-location of your Java installation."
-fi
-
-# Increase the maximum file descriptors if we can.
-if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
- case $MAX_FD in #(
- max*)
- MAX_FD=$( ulimit -H -n ) ||
- warn "Could not query maximum file descriptor limit"
- esac
- case $MAX_FD in #(
- '' | soft) :;; #(
- *)
- ulimit -n "$MAX_FD" ||
- warn "Could not set maximum file descriptor limit to $MAX_FD"
- esac
-fi
-
-# Collect all arguments for the java command, stacking in reverse order:
-# * args from the command line
-# * the main class name
-# * -classpath
-# * -D...appname settings
-# * --module-path (only if needed)
-# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
-
-# For Cygwin or MSYS, switch paths to Windows format before running java
-if "$cygwin" || "$msys" ; then
- APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
- CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
-
- JAVACMD=$( cygpath --unix "$JAVACMD" )
-
- # Now convert the arguments - kludge to limit ourselves to /bin/sh
- for arg do
- if
- case $arg in #(
- -*) false ;; # don't mess with options #(
- /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
- [ -e "$t" ] ;; #(
- *) false ;;
- esac
- then
- arg=$( cygpath --path --ignore --mixed "$arg" )
- fi
- # Roll the args list around exactly as many times as the number of
- # args, so each arg winds up back in the position where it started, but
- # possibly modified.
- #
- # NB: a `for` loop captures its iteration list before it begins, so
- # changing the positional parameters here affects neither the number of
- # iterations, nor the values presented in `arg`.
- shift # remove old arg
- set -- "$@" "$arg" # push replacement arg
- done
-fi
-
-# Collect all arguments for the java command;
-# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
-# shell script including quotes and variable substitutions, so put them in
-# double quotes to make sure that they get re-expanded; and
-# * put everything else in single quotes, so that it's not re-expanded.
-
-set -- \
- "-Dorg.gradle.appname=$APP_BASE_NAME" \
- -classpath "$CLASSPATH" \
- org.gradle.wrapper.GradleWrapperMain \
- "$@"
-
-# Stop when "xargs" is not available.
-if ! command -v xargs >/dev/null 2>&1
-then
- die "xargs is not available"
-fi
-
-# Use "xargs" to parse quoted args.
-#
-# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
-#
-# In Bash we could simply go:
-#
-# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
-# set -- "${ARGS[@]}" "$@"
-#
-# but POSIX shell has neither arrays nor command substitution, so instead we
-# post-process each arg (as a line of input to sed) to backslash-escape any
-# character that might be a shell metacharacter, then use eval to reverse
-# that process (while maintaining the separation between arguments), and wrap
-# the whole thing up as a single "set" statement.
-#
-# This will of course break if any of these variables contains a newline or
-# an unmatched quote.
-#
-
-eval "set -- $(
- printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
- xargs -n1 |
- sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
- tr '\n' ' '
- )" '"$@"'
-
-exec "$JAVACMD" "$@"
diff --git a/gradlew.bat b/gradlew.bat
deleted file mode 100644
index 53a6b238..00000000
--- a/gradlew.bat
+++ /dev/null
@@ -1,91 +0,0 @@
-@rem
-@rem Copyright 2015 the original author or authors.
-@rem
-@rem Licensed under the Apache License, Version 2.0 (the "License");
-@rem you may not use this file except in compliance with the License.
-@rem You may obtain a copy of the License at
-@rem
-@rem https://www.apache.org/licenses/LICENSE-2.0
-@rem
-@rem Unless required by applicable law or agreed to in writing, software
-@rem distributed under the License is distributed on an "AS IS" BASIS,
-@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-@rem See the License for the specific language governing permissions and
-@rem limitations under the License.
-@rem
-
-@if "%DEBUG%"=="" @echo off
-@rem ##########################################################################
-@rem
-@rem Gradle startup script for Windows
-@rem
-@rem ##########################################################################
-
-@rem Set local scope for the variables with windows NT shell
-if "%OS%"=="Windows_NT" setlocal
-
-set DIRNAME=%~dp0
-if "%DIRNAME%"=="" set DIRNAME=.
-set APP_BASE_NAME=%~n0
-set APP_HOME=%DIRNAME%
-
-@rem Resolve any "." and ".." in APP_HOME to make it shorter.
-for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
-
-@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
-set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
-
-@rem Find java.exe
-if defined JAVA_HOME goto findJavaFromJavaHome
-
-set JAVA_EXE=java.exe
-%JAVA_EXE% -version >NUL 2>&1
-if %ERRORLEVEL% equ 0 goto execute
-
-echo.
-echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
-
-goto fail
-
-:findJavaFromJavaHome
-set JAVA_HOME=%JAVA_HOME:"=%
-set JAVA_EXE=%JAVA_HOME%/bin/java.exe
-
-if exist "%JAVA_EXE%" goto execute
-
-echo.
-echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
-echo.
-echo Please set the JAVA_HOME variable in your environment to match the
-echo location of your Java installation.
-
-goto fail
-
-:execute
-@rem Setup the command line
-
-set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
-
-
-@rem Execute Gradle
-"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
-
-:end
-@rem End local scope for the variables with windows NT shell
-if %ERRORLEVEL% equ 0 goto mainEnd
-
-:fail
-rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
-rem the _cmd.exe /c_ return code!
-set EXIT_CODE=%ERRORLEVEL%
-if %EXIT_CODE% equ 0 set EXIT_CODE=1
-if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
-exit /b %EXIT_CODE%
-
-:mainEnd
-if "%OS%"=="Windows_NT" endlocal
-
-:omega
diff --git a/images/DemoGif.gif b/images/DemoGif.gif
deleted file mode 100644
index 5413bd36..00000000
Binary files a/images/DemoGif.gif and /dev/null differ
diff --git a/images/login-dark.png b/images/login-dark.png
deleted file mode 100644
index 672a6967..00000000
Binary files a/images/login-dark.png and /dev/null differ
diff --git a/images/login-light.png b/images/login-light.png
deleted file mode 100644
index 7b845c61..00000000
Binary files a/images/login-light.png and /dev/null differ
diff --git a/images/settings.png b/images/settings.png
deleted file mode 100644
index 49213054..00000000
Binary files a/images/settings.png and /dev/null differ
diff --git a/images/stirling-home-light.png b/images/stirling-home-light.png
deleted file mode 100644
index e6b09cad..00000000
Binary files a/images/stirling-home-light.png and /dev/null differ
diff --git a/images/stirling-home.png b/images/stirling-home.png
deleted file mode 100644
index c01af6f9..00000000
Binary files a/images/stirling-home.png and /dev/null differ
diff --git a/lauch4jConfig.xml b/lauch4jConfig.xml
deleted file mode 100644
index 918d6eaa..00000000
--- a/lauch4jConfig.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-
-
- false
- console
- .\build\libs\S-PDF-0.10.1.jar
- .\Stirling-PDF.exe
- Please download Java17
-
- .
- normal
- https://download.oracle.com/java/17/latest/jdk-17_windows-x64_bin.exe
-
- false
- false
-
- ./src/main/resources/static/favicon.ico
- BROWSER_OPEN=true
-
- Stirling-PDF
- Stirling-PDF
-
-
- %JAVA_HOME%;%PATH%
- false
- false
- 17
-
-
-
- An error occurred while starting Stirling-PDF
- This application requires a Java Runtime Environment, Please download Java 17.
- You are running the wrong version of Java, Please download Java 17.
- Java is corrupted. Please uninstall and then install Java 17.
- Stirling-PDF is already running.
-
-
\ No newline at end of file
diff --git a/scripts/PropSync.java b/scripts/PropSync.java
deleted file mode 100644
index 741712b5..00000000
--- a/scripts/PropSync.java
+++ /dev/null
@@ -1,80 +0,0 @@
-package stirling.software.Stirling.Stats;
-
-import java.nio.file.*;
-import java.nio.charset.MalformedInputException;
-import java.nio.charset.StandardCharsets;
-import java.io.*;
-import java.util.*;
-
-public class PropSync {
-
- public static void main(String[] args) throws IOException {
- File folder = new File("C:\\Users\\systo\\git\\Stirling-PDF\\src\\main\\resources");
- File[] files = folder.listFiles((dir, name) -> name.matches("messages_.*\\.properties"));
-
- List enLines = Files.readAllLines(Paths.get(folder + "\\messages_en_GB.properties"), StandardCharsets.UTF_8);
- Map enProps = linesToProps(enLines);
-
- for (File file : files) {
- if (!file.getName().equals("messages_en_GB.properties")) {
- System.out.println("Processing file: " + file.getName());
- List lines;
- try {
- lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
- } catch (MalformedInputException e) {
- System.out.println("Skipping due to not UTF8 format for file: " + file.getName());
- continue;
- } catch (IOException e) {
- throw new UncheckedIOException(e);
- }
-
- Map currentProps = linesToProps(lines);
- List newLines = syncPropsWithLines(enProps, currentProps, enLines);
-
- Files.write(file.toPath(), newLines, StandardCharsets.UTF_8);
- System.out.println("Finished processing file: " + file.getName());
- }
- }
- }
-
- private static Map linesToProps(List lines) {
- Map props = new LinkedHashMap<>();
- for (String line : lines) {
- if (!line.trim().isEmpty() && line.contains("=")) {
- String[] parts = line.split("=", 2);
- props.put(parts[0].trim(), parts[1].trim());
- }
- }
- return props;
- }
-
- private static List syncPropsWithLines(Map enProps, Map currentProps, List enLines) {
- List newLines = new ArrayList<>();
- boolean needsTranslateComment = false; // flag to check if we need to add "TODO: Translate"
-
- for (String line : enLines) {
- if (line.contains("=")) {
- String key = line.split("=", 2)[0].trim();
-
- if (currentProps.containsKey(key)) {
- newLines.add(key + "=" + currentProps.get(key));
- needsTranslateComment = false;
- } else {
- if (!needsTranslateComment) {
- newLines.add("##########################");
- newLines.add("### TODO: Translate ###");
- newLines.add("##########################");
- needsTranslateComment = true;
- }
- newLines.add(line);
- }
- } else {
- // handle comments and other non-property lines
- newLines.add(line);
- needsTranslateComment = false; // reset the flag when we encounter comments or empty lines
- }
- }
-
- return newLines;
- }
-}
diff --git a/scripts/detect-blank-pages.py b/scripts/detect-blank-pages.py
deleted file mode 100644
index 474c2735..00000000
--- a/scripts/detect-blank-pages.py
+++ /dev/null
@@ -1,47 +0,0 @@
-import cv2
-import sys
-import argparse
-
-def is_blank_image(image_path, threshold=10, white_percent=99, white_value=255, blur_size=5):
- image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
-
- if image is None:
- print(f"Error: Unable to read the image file: {image_path}")
- return False
-
- # Apply Gaussian blur to reduce noise
- blurred_image = cv2.GaussianBlur(image, (blur_size, blur_size), 0)
-
- _, thresholded_image = cv2.threshold(blurred_image, white_value - threshold, white_value, cv2.THRESH_BINARY)
-
- # Calculate the percentage of white pixels in the thresholded image
- white_pixels = 0
- total_pixels = thresholded_image.size
- for i in range(0, thresholded_image.shape[0], 2):
- for j in range(0, thresholded_image.shape[1], 2):
- if thresholded_image[i, j] == white_value:
- white_pixels += 1
- white_pixel_percentage = (white_pixels / (i * thresholded_image.shape[1] + j + 1)) * 100
- if white_pixel_percentage < white_percent:
- return False
-
- print(f"Page has white pixel percent of {white_pixel_percentage}")
- return True
-
-
-
-if __name__ == "__main__":
- parser = argparse.ArgumentParser(description='Detect if an image is considered blank or not.')
- parser.add_argument('image_path', help='The path to the image file.')
- parser.add_argument('-t', '--threshold', type=int, default=10, help='Threshold for determining white pixels. The default value is 10.')
- parser.add_argument('-w', '--white_percent', type=float, default=99, help='The percentage of white pixels for an image to be considered blank. The default value is 99.')
- args = parser.parse_args()
-
- blank = is_blank_image(args.image_path, args.threshold, args.white_percent)
-
- if blank:
- # Return code 1: The image is considered blank.
- sys.exit(1)
- else:
- # Return code 0: The image is not considered blank.
- sys.exit(0)
diff --git a/scripts/init.sh b/scripts/init.sh
deleted file mode 100644
index e65914c4..00000000
--- a/scripts/init.sh
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/bin/bash
-
-# Copy the original tesseract-ocr files to the volume directory without overwriting existing files
-echo "Copying original files without overwriting existing files"
-mkdir -p /usr/share/tesseract-ocr
-cp -rn /usr/share/tesseract-ocr-original/* /usr/share/tesseract-ocr
-
-# Check if TESSERACT_LANGS environment variable is set and is not empty
-if [[ -n "$TESSERACT_LANGS" ]]; then
- # Convert comma-separated values to a space-separated list
- LANGS=$(echo $TESSERACT_LANGS | tr ',' ' ')
-
- # Install each language pack
- for LANG in $LANGS; do
- apt-get install -y "tesseract-ocr-$LANG"
- done
-fi
-
-# Check for DOCKER_ENABLE_SECURITY and download the appropriate JAR if required
-if [ "$DOCKER_ENABLE_SECURITY" = "true" ] && [ "$VERSION_TAG" != "alpha" ]; then
- if [ ! -f app-security.jar ]; then
- echo "Trying to download from: https://github.com/Frooodle/Stirling-PDF/releases/download/v$VERSION_TAG/Stirling-PDF-with-login.jar"
- curl -L -o app-security.jar https://github.com/Frooodle/Stirling-PDF/releases/download/v$VERSION_TAG/Stirling-PDF-with-login.jar
-
- # If the first download attempt failed, try with the 'v' prefix
- if [ $? -ne 0 ]; then
- echo "Trying to download from: https://github.com/Frooodle/Stirling-PDF/releases/download/$VERSION_TAG/Stirling-PDF-with-login.jar"
- curl -L -o app-security.jar https://github.com/Frooodle/Stirling-PDF/releases/download/$VERSION_TAG/Stirling-PDF-with-login.jar
- fi
-
- if [ $? -eq 0 ]; then # checks if curl was successful
- rm -f app.jar
- ln -s app-security.jar app.jar
- fi
- fi
-fi
-
-
-# Run the main command
-exec "$@"
\ No newline at end of file
diff --git a/scripts/split_photos.py b/scripts/split_photos.py
deleted file mode 100644
index 49ecc22c..00000000
--- a/scripts/split_photos.py
+++ /dev/null
@@ -1,116 +0,0 @@
-import argparse
-import sys
-import cv2
-import numpy as np
-import os
-
-def find_photo_boundaries(image, background_color, tolerance=30, min_area=10000, min_contour_area=500):
- mask = cv2.inRange(image, background_color - tolerance, background_color + tolerance)
- mask = cv2.bitwise_not(mask)
- kernel = np.ones((5,5),np.uint8)
- mask = cv2.dilate(mask, kernel, iterations=2)
- contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
-
- photo_boundaries = []
- for contour in contours:
- x, y, w, h = cv2.boundingRect(contour)
- area = w * h
- contour_area = cv2.contourArea(contour)
- if area >= min_area and contour_area >= min_contour_area:
- photo_boundaries.append((x, y, w, h))
-
- return photo_boundaries
-
-def estimate_background_color(image, sample_points=5):
- h, w, _ = image.shape
- points = [
- (0, 0),
- (w - 1, 0),
- (w - 1, h - 1),
- (0, h - 1),
- (w // 2, h // 2),
- ]
-
- colors = []
- for x, y in points:
- colors.append(image[y, x])
-
- return np.median(colors, axis=0)
-
-def auto_rotate(image, angle_threshold=1):
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
- edges = cv2.Canny(gray, 50, 150, apertureSize=3)
- lines = cv2.HoughLines(edges, 1, np.pi / 180, 200)
-
- if lines is None:
- return image
-
- # compute the median angle of the lines
- angles = []
- for rho, theta in lines[:, 0]:
- angles.append((theta * 180) / np.pi - 90)
-
- angle = np.median(angles)
-
- if abs(angle) < angle_threshold:
- return image
-
- (h, w) = image.shape[:2]
- center = (w // 2, h // 2)
- M = cv2.getRotationMatrix2D(center, angle, 1.0)
- return cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
-
-
-
-
-def crop_borders(image, border_color, tolerance=30):
- mask = cv2.inRange(image, border_color - tolerance, border_color + tolerance)
-
- contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
- if len(contours) == 0:
- return image
-
- largest_contour = max(contours, key=cv2.contourArea)
- x, y, w, h = cv2.boundingRect(largest_contour)
-
- return image[y:y+h, x:x+w]
-
-def split_photos(input_file, output_directory, tolerance=30, min_area=10000, min_contour_area=500, angle_threshold=10, border_size=0):
- image = cv2.imread(input_file)
- background_color = estimate_background_color(image)
-
- # Add a constant border around the image
- image = cv2.copyMakeBorder(image, border_size, border_size, border_size, border_size, cv2.BORDER_CONSTANT, value=background_color)
-
- photo_boundaries = find_photo_boundaries(image, background_color, tolerance)
-
- if not os.path.exists(output_directory):
- os.makedirs(output_directory)
-
- # Get the input file's base name without the extension
- input_file_basename = os.path.splitext(os.path.basename(input_file))[0]
-
- for idx, (x, y, w, h) in enumerate(photo_boundaries):
- cropped_image = image[y:y+h, x:x+w]
- cropped_image = auto_rotate(cropped_image, angle_threshold)
-
- # Remove the added border
- cropped_image = cropped_image[border_size:-border_size, border_size:-border_size]
-
- output_path = os.path.join(output_directory, f"{input_file_basename}_{idx+1}.png")
- cv2.imwrite(output_path, cropped_image)
- print(f"Saved {output_path}")
-
-if __name__ == "__main__":
- parser = argparse.ArgumentParser(description="Split photos in an image")
- parser.add_argument("input_file", help="The input scanned image containing multiple photos.")
- parser.add_argument("output_directory", help="The directory where the result images should be placed.")
- parser.add_argument("--tolerance", type=int, default=30, help="Determines the range of color variation around the estimated background color (default: 30).")
- parser.add_argument("--min_area", type=int, default=10000, help="Sets the minimum area threshold for a photo (default: 10000).")
- parser.add_argument("--min_contour_area", type=int, default=500, help="Sets the minimum contour area threshold for a photo (default: 500).")
- parser.add_argument("--angle_threshold", type=int, default=10, help="Sets the minimum absolute angle required for the image to be rotated (default: 10).")
- parser.add_argument("--border_size", type=int, default=0, help="Sets the size of the border added and removed to prevent white borders in the output (default: 0).")
-
- args = parser.parse_args()
-
- split_photos(args.input_file, args.output_directory, tolerance=args.tolerance, min_area=args.min_area, min_contour_area=args.min_contour_area, angle_threshold=args.angle_threshold, border_size=args.border_size)
diff --git a/settings.gradle b/settings.gradle
deleted file mode 100644
index f8139930..00000000
--- a/settings.gradle
+++ /dev/null
@@ -1 +0,0 @@
-rootProject.name = 'Stirling-PDF'
diff --git a/src/main/java/stirling/software/SPDF/LibreOfficeListener.java b/src/main/java/stirling/software/SPDF/LibreOfficeListener.java
deleted file mode 100644
index 7f4fc160..00000000
--- a/src/main/java/stirling/software/SPDF/LibreOfficeListener.java
+++ /dev/null
@@ -1,96 +0,0 @@
-package stirling.software.SPDF;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.net.Socket;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-
-public class LibreOfficeListener {
-
- private static final long ACTIVITY_TIMEOUT = 20 * 60 * 1000; // 20 minutes
-
- private static final LibreOfficeListener INSTANCE = new LibreOfficeListener();
- private static final int LISTENER_PORT = 2002;
-
- public static LibreOfficeListener getInstance() {
- return INSTANCE;
- }
-
- private ExecutorService executorService;
- private long lastActivityTime;
-
- private Process process;
-
- private LibreOfficeListener() {
- }
-
- private boolean isListenerRunning() {
- try {
- System.out.println("waiting for listener to start");
- Socket socket = new Socket();
- socket.connect(new InetSocketAddress("localhost", 2002), 1000); // Timeout after 1 second
- socket.close();
- return true;
- } catch (IOException e) {
- return false;
- }
- }
-
- public void start() throws IOException {
- // Check if the listener is already running
- if (process != null && process.isAlive()) {
- return;
- }
-
- // Start the listener process
- process = Runtime.getRuntime().exec("unoconv --listener");
- lastActivityTime = System.currentTimeMillis();
-
- // Start a background thread to monitor the activity timeout
- executorService = Executors.newSingleThreadExecutor();
- executorService.submit(() -> {
- while (true) {
- long idleTime = System.currentTimeMillis() - lastActivityTime;
- if (idleTime >= ACTIVITY_TIMEOUT) {
- // If there has been no activity for too long, tear down the listener
- process.destroy();
- break;
- }
- try {
- Thread.sleep(5000); // Check for inactivity every 5 seconds
- } catch (InterruptedException e) {
- break;
- }
- }
- });
-
- // Wait for the listener to start up
- long startTime = System.currentTimeMillis();
- long timeout = 30000; // Timeout after 30 seconds
- while (System.currentTimeMillis() - startTime < timeout) {
- if (isListenerRunning()) {
-
- lastActivityTime = System.currentTimeMillis();
- return;
- }
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } // Check every 1 second
- }
- }
-
- public synchronized void stop() {
- // Stop the activity timeout monitor thread
- executorService.shutdownNow();
-
- // Stop the listener process
- if (process != null && process.isAlive()) {
- process.destroy();
- }
- }
-
-}
diff --git a/src/main/java/stirling/software/SPDF/SPdfApplication.java b/src/main/java/stirling/software/SPDF/SPdfApplication.java
deleted file mode 100644
index 5dd7fed3..00000000
--- a/src/main/java/stirling/software/SPDF/SPdfApplication.java
+++ /dev/null
@@ -1,82 +0,0 @@
-package stirling.software.SPDF;
-
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import java.util.Collections;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.SpringApplication;
-import org.springframework.boot.autoconfigure.SpringBootApplication;
-import org.springframework.core.env.Environment;
-
-import jakarta.annotation.PostConstruct;
-import stirling.software.SPDF.config.ConfigInitializer;
-import stirling.software.SPDF.utils.GeneralUtils;
-@SpringBootApplication
-
-//@EnableScheduling
-public class SPdfApplication {
-
- @Autowired
- private Environment env;
-
- @PostConstruct
- public void init() {
- // Check if the BROWSER_OPEN environment variable is set to true
- String browserOpenEnv = env.getProperty("BROWSER_OPEN");
- boolean browserOpen = browserOpenEnv != null && browserOpenEnv.equalsIgnoreCase("true");
-
- if (browserOpen) {
- try {
- String port = env.getProperty("local.server.port");
- if(port == null || port.length() == 0) {
- port="8080";
- }
- String url = "http://localhost:" + port;
-
- String os = System.getProperty("os.name").toLowerCase();
- Runtime rt = Runtime.getRuntime();
- if (os.contains("win")) {
- // For Windows
- rt.exec("rundll32 url.dll,FileProtocolHandler " + url);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
-
- public static void main(String[] args) {
- SpringApplication app = new SpringApplication(SPdfApplication.class);
- app.addInitializers(new ConfigInitializer());
- if (Files.exists(Paths.get("configs/settings.yml"))) {
- app.setDefaultProperties(Collections.singletonMap("spring.config.additional-location", "file:configs/settings.yml"));
- } else {
- System.out.println("External configuration file 'configs/settings.yml' does not exist. Using default configuration and environment configuration instead.");
- }
- app.run(args);
-
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- GeneralUtils.createDir("customFiles/static/");
- GeneralUtils.createDir("customFiles/templates/");
-
-
-
- System.out.println("Stirling-PDF Started.");
-
- String port = System.getProperty("local.server.port");
- if(port == null || port.length() == 0) {
- port="8080";
- }
- String url = "http://localhost:" + port;
- System.out.println("Navigate to " + url);
- }
-
-
-}
\ No newline at end of file
diff --git a/src/main/java/stirling/software/SPDF/config/AppConfig.java b/src/main/java/stirling/software/SPDF/config/AppConfig.java
deleted file mode 100644
index 5d4bad43..00000000
--- a/src/main/java/stirling/software/SPDF/config/AppConfig.java
+++ /dev/null
@@ -1,55 +0,0 @@
-package stirling.software.SPDF.config;
-
-import org.springframework.beans.PropertyEditorRegistrar;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-
-import stirling.software.SPDF.model.ApplicationProperties;
-@Configuration
-public class AppConfig {
-
-
- @Autowired
- ApplicationProperties applicationProperties;
-
- @Bean(name = "loginEnabled")
- public boolean loginEnabled() {
- return applicationProperties.getSecurity().getEnableLogin();
- }
-
- @Bean(name = "appName")
- public String appName() {
- String homeTitle = applicationProperties.getUi().getAppName();
- return (homeTitle != null) ? homeTitle : "Stirling PDF";
- }
-
- @Bean(name = "appVersion")
- public String appVersion() {
- String version = getClass().getPackage().getImplementationVersion();
- return (version != null) ? version : "0.0.0";
- }
-
- @Bean(name = "homeText")
- public String homeText() {
- return (applicationProperties.getUi().getHomeDescription() != null) ? applicationProperties.getUi().getHomeDescription() : "null";
- }
-
-
- @Bean(name = "navBarText")
- public String navBarText() {
- String defaultNavBar = applicationProperties.getUi().getAppNameNavbar() != null ? applicationProperties.getUi().getAppNameNavbar() : applicationProperties.getUi().getAppName();
- return (defaultNavBar != null) ? defaultNavBar : "Stirling PDF";
- }
-
- @Bean(name = "rateLimit")
- public boolean rateLimit() {
- String appName = System.getProperty("rateLimit");
- if (appName == null)
- appName = System.getenv("rateLimit");
- System.out.println("rateLimit=" + appName);
- return (appName != null) ? Boolean.valueOf(appName) : false;
- }
-
-
-}
\ No newline at end of file
diff --git a/src/main/java/stirling/software/SPDF/config/Beans.java b/src/main/java/stirling/software/SPDF/config/Beans.java
deleted file mode 100644
index d1c6a03b..00000000
--- a/src/main/java/stirling/software/SPDF/config/Beans.java
+++ /dev/null
@@ -1,65 +0,0 @@
-package stirling.software.SPDF.config;
-
-import java.util.Locale;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.web.servlet.LocaleResolver;
-import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
-import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
-import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
-import org.springframework.web.servlet.i18n.SessionLocaleResolver;
-
-import stirling.software.SPDF.model.ApplicationProperties;
-
-@Configuration
-public class Beans implements WebMvcConfigurer {
-
- @Autowired
- ApplicationProperties applicationProperties;
-
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- registry.addInterceptor(localeChangeInterceptor());
- registry.addInterceptor(new CleanUrlInterceptor());
- }
-
- @Bean
- public LocaleChangeInterceptor localeChangeInterceptor() {
- LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
- lci.setParamName("lang");
- return lci;
- }
-
- @Bean
- public LocaleResolver localeResolver() {
- SessionLocaleResolver slr = new SessionLocaleResolver();
-
-
- String appLocaleEnv = applicationProperties.getSystem().getDefaultLocale();
- Locale defaultLocale = Locale.UK; // Fallback to UK locale if environment variable is not set
-
- if (appLocaleEnv != null && !appLocaleEnv.isEmpty()) {
- Locale tempLocale = Locale.forLanguageTag(appLocaleEnv);
- String tempLanguageTag = tempLocale.toLanguageTag();
-
- if (appLocaleEnv.equalsIgnoreCase(tempLanguageTag)) {
- defaultLocale = tempLocale;
- } else {
- tempLocale = Locale.forLanguageTag(appLocaleEnv.replace("_","-"));
- tempLanguageTag = tempLocale.toLanguageTag();
-
- if (appLocaleEnv.equalsIgnoreCase(tempLanguageTag)) {
- defaultLocale = tempLocale;
- } else {
- System.err.println("Invalid APP_LOCALE environment variable value. Falling back to default Locale.UK.");
- }
- }
- }
-
- slr.setDefaultLocale(defaultLocale);
- return slr;
- }
-
-}
diff --git a/src/main/java/stirling/software/SPDF/config/CleanUrlInterceptor.java b/src/main/java/stirling/software/SPDF/config/CleanUrlInterceptor.java
deleted file mode 100644
index 894d50d8..00000000
--- a/src/main/java/stirling/software/SPDF/config/CleanUrlInterceptor.java
+++ /dev/null
@@ -1,68 +0,0 @@
-package stirling.software.SPDF.config;
-
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.springframework.web.servlet.HandlerInterceptor;
-import org.springframework.web.servlet.ModelAndView;
-
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpServletResponse;
-
-public class CleanUrlInterceptor implements HandlerInterceptor {
-
- private static final List ALLOWED_PARAMS = Arrays.asList("lang", "endpoint", "endpoints", "logout", "error", "file", "messageType");
-
-
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
- throws Exception {
- String queryString = request.getQueryString();
- if (queryString != null && !queryString.isEmpty()) {
- String requestURI = request.getRequestURI();
- Map parameters = new HashMap<>();
-
- // Keep only the allowed parameters
- String[] queryParameters = queryString.split("&");
- for (String param : queryParameters) {
- String[] keyValue = param.split("=");
- if (keyValue.length != 2) {
- continue;
- }
- if (ALLOWED_PARAMS.contains(keyValue[0])) {
- parameters.put(keyValue[0], keyValue[1]);
- }
- }
-
- // If there are any parameters that are not allowed
- if (parameters.size() != queryParameters.length) {
- // Construct new query string
- StringBuilder newQueryString = new StringBuilder();
- for (Map.Entry entry : parameters.entrySet()) {
- if (newQueryString.length() > 0) {
- newQueryString.append("&");
- }
- newQueryString.append(entry.getKey()).append("=").append(entry.getValue());
- }
-
- // Redirect to the URL with only allowed query parameters
- String redirectUrl = requestURI + "?" + newQueryString;
- response.sendRedirect(redirectUrl);
- return false;
- }
- }
- return true;
- }
-
- @Override
- public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
- ModelAndView modelAndView) {
- }
-
- @Override
- public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
- Exception ex) {
- }
-}
diff --git a/src/main/java/stirling/software/SPDF/config/ConfigInitializer.java b/src/main/java/stirling/software/SPDF/config/ConfigInitializer.java
deleted file mode 100644
index 862f5718..00000000
--- a/src/main/java/stirling/software/SPDF/config/ConfigInitializer.java
+++ /dev/null
@@ -1,129 +0,0 @@
-package stirling.software.SPDF.config;
-
-import java.io.BufferedReader;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.nio.charset.StandardCharsets;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Optional;
-import java.util.Set;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-
-import org.springframework.context.ApplicationContextInitializer;
-import org.springframework.context.ConfigurableApplicationContext;
-
-public class ConfigInitializer implements ApplicationContextInitializer {
-
- @Override
- public void initialize(ConfigurableApplicationContext applicationContext) {
- try {
- ensureConfigExists();
- } catch (IOException e) {
- throw new RuntimeException("Failed to initialize application configuration", e);
- }
- }
-
- public void ensureConfigExists() throws IOException {
- // Define the path to the external config directory
- Path destPath = Paths.get("configs", "settings.yml");
-
- // Check if the file already exists
- if (Files.notExists(destPath)) {
- // Ensure the destination directory exists
- Files.createDirectories(destPath.getParent());
-
- // Copy the resource from classpath to the external directory
- try (InputStream in = getClass().getClassLoader().getResourceAsStream("settings.yml.template")) {
- if (in != null) {
- Files.copy(in, destPath);
- } else {
- throw new FileNotFoundException("Resource file not found: settings.yml.template");
- }
- }
- } else {
- // If user file exists, we need to merge it with the template from the classpath
- List templateLines;
- try (InputStream in = getClass().getClassLoader().getResourceAsStream("settings.yml.template")) {
- templateLines = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)).lines()
- .collect(Collectors.toList());
- }
-
- mergeYamlFiles(templateLines, destPath, destPath);
- }
- }
-
- public void mergeYamlFiles(List templateLines, Path userFilePath, Path outputPath) throws IOException {
- List userLines = Files.readAllLines(userFilePath);
- List mergedLines = new ArrayList<>();
- boolean insideAutoGenerated = false;
- boolean beforeFirstKey = true;
-
- Function isCommented = line -> line.trim().startsWith("#");
- Function extractKey = line -> {
- String[] parts = line.split(":");
- return parts.length > 0 ? parts[0].trim().replace("#", "").trim() : "";
- };
-
- Set userKeys = userLines.stream().map(extractKey).collect(Collectors.toSet());
-
- for (String line : templateLines) {
- String key = extractKey.apply(line);
-
- if (line.trim().equalsIgnoreCase("AutomaticallyGenerated:")) {
- insideAutoGenerated = true;
- mergedLines.add(line);
- continue;
- } else if (insideAutoGenerated && line.trim().isEmpty()) {
- insideAutoGenerated = false;
- mergedLines.add(line);
- continue;
- }
-
- if (beforeFirstKey && (isCommented.apply(line) || line.trim().isEmpty())) {
- // Handle top comments and empty lines before the first key.
- mergedLines.add(line);
- continue;
- }
-
- if (!key.isEmpty())
- beforeFirstKey = false;
-
- if (userKeys.contains(key)) {
- // If user has any version (commented or uncommented) of this key, skip the
- // template line
- Optional userValue = userLines.stream()
- .filter(l -> extractKey.apply(l).equalsIgnoreCase(key) && !isCommented.apply(l)).findFirst();
- if (userValue.isPresent())
- mergedLines.add(userValue.get());
- continue;
- }
-
- if (isCommented.apply(line) || line.trim().isEmpty() || !userKeys.contains(key)) {
- mergedLines.add(line); // If line is commented, empty or key not present in user's file, retain the
- // template line
- continue;
- }
- }
-
- // Add any additional uncommented user lines that are not present in the
- // template
- for (String userLine : userLines) {
- String userKey = extractKey.apply(userLine);
- boolean isPresentInTemplate = templateLines.stream().map(extractKey)
- .anyMatch(templateKey -> templateKey.equalsIgnoreCase(userKey));
- if (!isPresentInTemplate && !isCommented.apply(userLine)) {
- mergedLines.add(userLine);
- }
- }
-
- Files.write(outputPath, mergedLines, StandardCharsets.UTF_8);
- }
-
-}
\ No newline at end of file
diff --git a/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java b/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java
deleted file mode 100644
index ee17e0b9..00000000
--- a/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java
+++ /dev/null
@@ -1,228 +0,0 @@
-package stirling.software.SPDF.config;
-
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-
-import stirling.software.SPDF.model.ApplicationProperties;
-@Service
-public class EndpointConfiguration {
- private static final Logger logger = LoggerFactory.getLogger(EndpointConfiguration.class);
- private Map endpointStatuses = new ConcurrentHashMap<>();
- private Map> endpointGroups = new ConcurrentHashMap<>();
-
- private final ApplicationProperties applicationProperties;
-
- @Autowired
- public EndpointConfiguration(ApplicationProperties applicationProperties) {
- this.applicationProperties = applicationProperties;
- init();
- processEnvironmentConfigs();
- }
-
- public void enableEndpoint(String endpoint) {
- endpointStatuses.put(endpoint, true);
- }
-
- public void disableEndpoint(String endpoint) {
- if(!endpointStatuses.containsKey(endpoint) || endpointStatuses.get(endpoint) != false) {
- logger.info("Disabling {}", endpoint);
- endpointStatuses.put(endpoint, false);
- }
- }
-
- public boolean isEndpointEnabled(String endpoint) {
- if (endpoint.startsWith("/")) {
- endpoint = endpoint.substring(1);
- }
- return endpointStatuses.getOrDefault(endpoint, true);
- }
-
- public void addEndpointToGroup(String group, String endpoint) {
- endpointGroups.computeIfAbsent(group, k -> new HashSet<>()).add(endpoint);
- }
-
- public void enableGroup(String group) {
- Set endpoints = endpointGroups.get(group);
- if (endpoints != null) {
- for (String endpoint : endpoints) {
- enableEndpoint(endpoint);
- }
- }
- }
-
- public void disableGroup(String group) {
- Set endpoints = endpointGroups.get(group);
- if (endpoints != null) {
- for (String endpoint : endpoints) {
- disableEndpoint(endpoint);
- }
- }
- }
-
- public void init() {
- // Adding endpoints to "PageOps" group
- addEndpointToGroup("PageOps", "remove-pages");
- addEndpointToGroup("PageOps", "merge-pdfs");
- addEndpointToGroup("PageOps", "split-pdfs");
- addEndpointToGroup("PageOps", "pdf-organizer");
- addEndpointToGroup("PageOps", "rotate-pdf");
- addEndpointToGroup("PageOps", "multi-page-layout");
- addEndpointToGroup("PageOps", "scale-pages");
- addEndpointToGroup("PageOps", "adjust-contrast");
- addEndpointToGroup("PageOps", "crop");
- addEndpointToGroup("PageOps", "auto-split-pdf");
- addEndpointToGroup("PageOps", "extract-page");
- addEndpointToGroup("PageOps", "pdf-to-single-page");
-
- // Adding endpoints to "Convert" group
- addEndpointToGroup("Convert", "pdf-to-img");
- addEndpointToGroup("Convert", "img-to-pdf");
- addEndpointToGroup("Convert", "pdf-to-pdfa");
- addEndpointToGroup("Convert", "file-to-pdf");
- addEndpointToGroup("Convert", "xlsx-to-pdf");
- addEndpointToGroup("Convert", "pdf-to-word");
- addEndpointToGroup("Convert", "pdf-to-presentation");
- addEndpointToGroup("Convert", "pdf-to-text");
- addEndpointToGroup("Convert", "pdf-to-html");
- addEndpointToGroup("Convert", "pdf-to-xml");
- addEndpointToGroup("Convert", "html-to-pdf");
- addEndpointToGroup("Convert", "url-to-pdf");
- addEndpointToGroup("Convert", "markdown-to-pdf");
-
- // Adding endpoints to "Security" group
- addEndpointToGroup("Security", "add-password");
- addEndpointToGroup("Security", "remove-password");
- addEndpointToGroup("Security", "change-permissions");
- addEndpointToGroup("Security", "add-watermark");
- addEndpointToGroup("Security", "cert-sign");
- addEndpointToGroup("Security", "sanitize-pdf");
-
-
- // Adding endpoints to "Other" group
- addEndpointToGroup("Other", "ocr-pdf");
- addEndpointToGroup("Other", "add-image");
- addEndpointToGroup("Other", "compress-pdf");
- addEndpointToGroup("Other", "extract-images");
- addEndpointToGroup("Other", "change-metadata");
- addEndpointToGroup("Other", "extract-image-scans");
- addEndpointToGroup("Other", "sign");
- addEndpointToGroup("Other", "flatten");
- addEndpointToGroup("Other", "repair");
- addEndpointToGroup("Other", "remove-blanks");
- addEndpointToGroup("Other", "compare");
- addEndpointToGroup("Other", "add-page-numbers");
- addEndpointToGroup("Other", "auto-rename");
- addEndpointToGroup("Other", "get-info-on-pdf");
- addEndpointToGroup("Other", "show-javascript");
-
-
-
- //CLI
- addEndpointToGroup("CLI", "compress-pdf");
- addEndpointToGroup("CLI", "extract-image-scans");
- addEndpointToGroup("CLI", "remove-blanks");
- addEndpointToGroup("CLI", "repair");
- addEndpointToGroup("CLI", "pdf-to-pdfa");
- addEndpointToGroup("CLI", "file-to-pdf");
- addEndpointToGroup("CLI", "xlsx-to-pdf");
- addEndpointToGroup("CLI", "pdf-to-word");
- addEndpointToGroup("CLI", "pdf-to-presentation");
- addEndpointToGroup("CLI", "pdf-to-text");
- addEndpointToGroup("CLI", "pdf-to-html");
- addEndpointToGroup("CLI", "pdf-to-xml");
- addEndpointToGroup("CLI", "ocr-pdf");
- addEndpointToGroup("CLI", "html-to-pdf");
- addEndpointToGroup("CLI", "url-to-pdf");
-
-
- //python
- addEndpointToGroup("Python", "extract-image-scans");
- addEndpointToGroup("Python", "remove-blanks");
- addEndpointToGroup("Python", "html-to-pdf");
- addEndpointToGroup("Python", "url-to-pdf");
-
- //openCV
- addEndpointToGroup("OpenCV", "extract-image-scans");
- addEndpointToGroup("OpenCV", "remove-blanks");
-
- //LibreOffice
- addEndpointToGroup("LibreOffice", "repair");
- addEndpointToGroup("LibreOffice", "file-to-pdf");
- addEndpointToGroup("LibreOffice", "xlsx-to-pdf");
- addEndpointToGroup("LibreOffice", "pdf-to-word");
- addEndpointToGroup("LibreOffice", "pdf-to-presentation");
- addEndpointToGroup("LibreOffice", "pdf-to-text");
- addEndpointToGroup("LibreOffice", "pdf-to-html");
- addEndpointToGroup("LibreOffice", "pdf-to-xml");
-
-
- //OCRmyPDF
- addEndpointToGroup("OCRmyPDF", "compress-pdf");
- addEndpointToGroup("OCRmyPDF", "pdf-to-pdfa");
- addEndpointToGroup("OCRmyPDF", "ocr-pdf");
-
- //Java
- addEndpointToGroup("Java", "merge-pdfs");
- addEndpointToGroup("Java", "remove-pages");
- addEndpointToGroup("Java", "split-pdfs");
- addEndpointToGroup("Java", "pdf-organizer");
- addEndpointToGroup("Java", "rotate-pdf");
- addEndpointToGroup("Java", "pdf-to-img");
- addEndpointToGroup("Java", "img-to-pdf");
- addEndpointToGroup("Java", "add-password");
- addEndpointToGroup("Java", "remove-password");
- addEndpointToGroup("Java", "change-permissions");
- addEndpointToGroup("Java", "add-watermark");
- addEndpointToGroup("Java", "add-image");
- addEndpointToGroup("Java", "extract-images");
- addEndpointToGroup("Java", "change-metadata");
- addEndpointToGroup("Java", "cert-sign");
- addEndpointToGroup("Java", "multi-page-layout");
- addEndpointToGroup("Java", "scale-pages");
- addEndpointToGroup("Java", "add-page-numbers");
- addEndpointToGroup("Java", "auto-rename");
- addEndpointToGroup("Java", "auto-split-pdf");
- addEndpointToGroup("Java", "sanitize-pdf");
- addEndpointToGroup("Java", "crop");
- addEndpointToGroup("Java", "get-info-on-pdf");
- addEndpointToGroup("Java", "extract-page");
- addEndpointToGroup("Java", "pdf-to-single-page");
- addEndpointToGroup("Java", "markdown-to-pdf");
- addEndpointToGroup("Java", "show-javascript");
-
- //Javascript
- addEndpointToGroup("Javascript", "pdf-organizer");
- addEndpointToGroup("Javascript", "sign");
- addEndpointToGroup("Javascript", "compare");
- addEndpointToGroup("Javascript", "adjust-contrast");
-
-
- }
-
- private void processEnvironmentConfigs() {
- List endpointsToRemove = applicationProperties.getEndpoints().getToRemove();
- List groupsToRemove = applicationProperties.getEndpoints().getGroupsToRemove();
-
- if (endpointsToRemove != null) {
- for (String endpoint : endpointsToRemove) {
- disableEndpoint(endpoint.trim());
- }
- }
-
- if (groupsToRemove != null) {
- for (String group : groupsToRemove) {
- disableGroup(group.trim());
- }
- }
- }
-
-}
-
diff --git a/src/main/java/stirling/software/SPDF/config/EndpointInterceptor.java b/src/main/java/stirling/software/SPDF/config/EndpointInterceptor.java
deleted file mode 100644
index 77191a41..00000000
--- a/src/main/java/stirling/software/SPDF/config/EndpointInterceptor.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package stirling.software.SPDF.config;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-import org.springframework.web.servlet.HandlerInterceptor;
-
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpServletResponse;
-
-@Component
-public class EndpointInterceptor implements HandlerInterceptor {
-
- @Autowired
- private EndpointConfiguration endpointConfiguration;
-
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
- throws Exception {
- String requestURI = request.getRequestURI();
- if (!endpointConfiguration.isEndpointEnabled(requestURI)) {
- response.sendError(HttpServletResponse.SC_FORBIDDEN, "This endpoint is disabled");
- return false;
- }
- return true;
- }
-}
\ No newline at end of file
diff --git a/src/main/java/stirling/software/SPDF/config/MetricsConfig.java b/src/main/java/stirling/software/SPDF/config/MetricsConfig.java
deleted file mode 100644
index 1cdc99e3..00000000
--- a/src/main/java/stirling/software/SPDF/config/MetricsConfig.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package stirling.software.SPDF.config;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-
-import io.micrometer.core.instrument.Meter;
-import io.micrometer.core.instrument.config.MeterFilter;
-import io.micrometer.core.instrument.config.MeterFilterReply;
-
-@Configuration
-public class MetricsConfig {
-
- @Bean
- public MeterFilter meterFilter() {
- return new MeterFilter() {
- @Override
- public MeterFilterReply accept(Meter.Id id) {
- if (id.getName().equals("http.requests")) {
- return MeterFilterReply.NEUTRAL;
- }
- return MeterFilterReply.DENY;
- }
- };
- }
-}
\ No newline at end of file
diff --git a/src/main/java/stirling/software/SPDF/config/MetricsFilter.java b/src/main/java/stirling/software/SPDF/config/MetricsFilter.java
deleted file mode 100644
index 6ee59db7..00000000
--- a/src/main/java/stirling/software/SPDF/config/MetricsFilter.java
+++ /dev/null
@@ -1,48 +0,0 @@
-package stirling.software.SPDF.config;
-
-import java.io.IOException;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-import org.springframework.web.filter.OncePerRequestFilter;
-
-import io.micrometer.core.instrument.Counter;
-import io.micrometer.core.instrument.MeterRegistry;
-import jakarta.servlet.FilterChain;
-import jakarta.servlet.ServletException;
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpServletResponse;
-
-@Component
-public class MetricsFilter extends OncePerRequestFilter {
-
- private final MeterRegistry meterRegistry;
-
- @Autowired
- public MetricsFilter(MeterRegistry meterRegistry) {
- this.meterRegistry = meterRegistry;
- }
-
- @Override
- protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
- throws ServletException, IOException {
- String uri = request.getRequestURI();
-
- //System.out.println("uri="+uri + ", method=" + request.getMethod() );
- // Ignore static resources
- if (!(uri.startsWith("/js") || uri.startsWith("api-docs") || uri.endsWith("robots.txt") || uri.startsWith("/images") || uri.endsWith(".png") || uri.endsWith(".ico") || uri.endsWith(".css") || uri.endsWith(".svg")|| uri.endsWith(".js") || uri.contains("swagger") || uri.startsWith("/api"))) {
- Counter counter = Counter.builder("http.requests")
- .tag("uri", uri)
- .tag("method", request.getMethod())
- .register(meterRegistry);
-
- counter.increment();
- //System.out.println("Counted");
- }
-
- filterChain.doFilter(request, response);
- }
-
-
-
-}
diff --git a/src/main/java/stirling/software/SPDF/config/OpenApiConfig.java b/src/main/java/stirling/software/SPDF/config/OpenApiConfig.java
deleted file mode 100644
index 2583277e..00000000
--- a/src/main/java/stirling/software/SPDF/config/OpenApiConfig.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package stirling.software.SPDF.config;
-
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-
-import io.swagger.v3.oas.models.Components;
-import io.swagger.v3.oas.models.OpenAPI;
-import io.swagger.v3.oas.models.info.Info;
-
-@Configuration
-public class OpenApiConfig {
-
- @Bean
- public OpenAPI customOpenAPI() {
- String version = getClass().getPackage().getImplementationVersion();
- if (version == null) {
-
- version = "1.0.0"; // default version if all else fails
-
- }
-
- return new OpenAPI().components(new Components()).info(
- new Info().title("Stirling PDF API").version(version).description("API documentation for all Server-Side processing.\nPlease note some functionality might be UI only and missing from here."));
- }
-
-
-}
diff --git a/src/main/java/stirling/software/SPDF/config/StartupApplicationListener.java b/src/main/java/stirling/software/SPDF/config/StartupApplicationListener.java
deleted file mode 100644
index 77b69c88..00000000
--- a/src/main/java/stirling/software/SPDF/config/StartupApplicationListener.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package stirling.software.SPDF.config;
-
-
-import java.time.LocalDateTime;
-
-import org.springframework.context.ApplicationListener;
-import org.springframework.context.event.ContextRefreshedEvent;
-import org.springframework.stereotype.Component;
-
-@Component
-public class StartupApplicationListener implements ApplicationListener {
-
- public static LocalDateTime startTime;
-
- @Override
- public void onApplicationEvent(ContextRefreshedEvent event) {
- startTime = LocalDateTime.now();
- }
-}
-
diff --git a/src/main/java/stirling/software/SPDF/config/WebMvcConfig.java b/src/main/java/stirling/software/SPDF/config/WebMvcConfig.java
deleted file mode 100644
index dca3f91c..00000000
--- a/src/main/java/stirling/software/SPDF/config/WebMvcConfig.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package stirling.software.SPDF.config;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
-import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
-import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
-
-@Configuration
-public class WebMvcConfig implements WebMvcConfigurer {
-
- @Autowired
- private EndpointInterceptor endpointInterceptor;
-
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- registry.addInterceptor(endpointInterceptor);
- }
-
- @Override
- public void addResourceHandlers(ResourceHandlerRegistry registry) {
- // Handler for external static resources
- registry.addResourceHandler("/**")
- .addResourceLocations("file:customFiles/static/", "classpath:/static/");
- //.setCachePeriod(0); // Optional: disable caching
- }
-}
diff --git a/src/main/java/stirling/software/SPDF/config/YamlPropertySourceFactory.java b/src/main/java/stirling/software/SPDF/config/YamlPropertySourceFactory.java
deleted file mode 100644
index 982cee94..00000000
--- a/src/main/java/stirling/software/SPDF/config/YamlPropertySourceFactory.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package stirling.software.SPDF.config;
-
-import java.io.IOException;
-import java.util.Properties;
-
-import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
-import org.springframework.core.env.PropertiesPropertySource;
-import org.springframework.core.env.PropertySource;
-import org.springframework.core.io.support.EncodedResource;
-import org.springframework.core.io.support.PropertySourceFactory;
-public class YamlPropertySourceFactory implements PropertySourceFactory {
-
- @Override
- public PropertySource> createPropertySource(String name, EncodedResource encodedResource)
- throws IOException {
- YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
- factory.setResources(encodedResource.getResource());
-
- Properties properties = factory.getObject();
-
- return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties);
- }
-}
\ No newline at end of file
diff --git a/src/main/java/stirling/software/SPDF/config/security/CustomAuthenticationFailureHandler.java b/src/main/java/stirling/software/SPDF/config/security/CustomAuthenticationFailureHandler.java
deleted file mode 100644
index 9f52a5e3..00000000
--- a/src/main/java/stirling/software/SPDF/config/security/CustomAuthenticationFailureHandler.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package stirling.software.SPDF.config.security;
-
-import java.io.IOException;
-
-import org.springframework.security.authentication.BadCredentialsException;
-import org.springframework.security.authentication.LockedException;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
-
-import jakarta.servlet.ServletException;
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpServletResponse;
-
-public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
-
- @Override
- public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
- throws IOException, ServletException {
- if (exception.getClass().isAssignableFrom(BadCredentialsException.class)) {
- setDefaultFailureUrl("/login?error=badcredentials");
- } else if (exception.getClass().isAssignableFrom(LockedException.class)) {
- setDefaultFailureUrl("/login?error=locked");
- }
- super.onAuthenticationFailure(request, response, exception);
- }
-}
diff --git a/src/main/java/stirling/software/SPDF/config/security/CustomUserDetailsService.java b/src/main/java/stirling/software/SPDF/config/security/CustomUserDetailsService.java
deleted file mode 100644
index 7ae1680b..00000000
--- a/src/main/java/stirling/software/SPDF/config/security/CustomUserDetailsService.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package stirling.software.SPDF.config.security;
-
-import java.util.Collection;
-import java.util.Set;
-import java.util.stream.Collectors;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.core.GrantedAuthority;
-import org.springframework.security.core.authority.SimpleGrantedAuthority;
-import org.springframework.security.core.userdetails.UserDetails;
-import org.springframework.security.core.userdetails.UserDetailsService;
-import org.springframework.security.core.userdetails.UsernameNotFoundException;
-import org.springframework.stereotype.Service;
-
-import stirling.software.SPDF.model.Authority;
-import stirling.software.SPDF.model.User;
-import stirling.software.SPDF.repository.UserRepository;
-
-@Service
-public class CustomUserDetailsService implements UserDetailsService {
-
- @Autowired
- private UserRepository userRepository;
-
-
- @Override
- public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
- User user = userRepository.findByUsername(username)
- .orElseThrow(() -> new UsernameNotFoundException("No user found with username: " + username));
-
- return new org.springframework.security.core.userdetails.User(
- user.getUsername(),
- user.getPassword(),
- user.isEnabled(),
- true, true, true,
- getAuthorities(user.getAuthorities())
- );
- }
-
- private Collection extends GrantedAuthority> getAuthorities(Set authorities) {
- return authorities.stream()
- .map(authority -> new SimpleGrantedAuthority(authority.getAuthority()))
- .collect(Collectors.toList());
- }
-}
diff --git a/src/main/java/stirling/software/SPDF/config/security/FirstLoginFilter.java b/src/main/java/stirling/software/SPDF/config/security/FirstLoginFilter.java
deleted file mode 100644
index 8e612464..00000000
--- a/src/main/java/stirling/software/SPDF/config/security/FirstLoginFilter.java
+++ /dev/null
@@ -1,53 +0,0 @@
-package stirling.software.SPDF.config.security;
-
-import java.io.IOException;
-import java.util.Optional;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Lazy;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.context.SecurityContextHolder;
-import org.springframework.stereotype.Component;
-import org.springframework.web.filter.OncePerRequestFilter;
-
-import jakarta.servlet.FilterChain;
-import jakarta.servlet.ServletException;
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpServletResponse;
-import stirling.software.SPDF.model.User;
-
-@Component
-public class FirstLoginFilter extends OncePerRequestFilter {
-
- @Autowired
- @Lazy
- private UserService userService;
-
- @Override
- protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
- String method = request.getMethod();
- String requestURI = request.getRequestURI();
- // Check if the request is for static resources
- boolean isStaticResource = requestURI.startsWith("/css/")
- || requestURI.startsWith("/js/")
- || requestURI.startsWith("/images/")
- || requestURI.startsWith("/public/")
- || requestURI.endsWith(".svg");
-
- // If it's a static resource, just continue the filter chain and skip the logic below
- if (isStaticResource) {
- filterChain.doFilter(request, response);
- return;
- }
-
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- if (authentication != null && authentication.isAuthenticated()) {
- Optional user = userService.findByUsername(authentication.getName());
- if ("GET".equalsIgnoreCase(method) && user.isPresent() && user.get().isFirstLogin() && !"/change-creds".equals(requestURI)) {
- response.sendRedirect("/change-creds");
- return;
- }
- }
- filterChain.doFilter(request, response);
- }
-}
diff --git a/src/main/java/stirling/software/SPDF/config/security/InitialSecuritySetup.java b/src/main/java/stirling/software/SPDF/config/security/InitialSecuritySetup.java
deleted file mode 100644
index 842375d8..00000000
--- a/src/main/java/stirling/software/SPDF/config/security/InitialSecuritySetup.java
+++ /dev/null
@@ -1,85 +0,0 @@
-package stirling.software.SPDF.config.security;
-
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.List;
-import java.util.UUID;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-import jakarta.annotation.PostConstruct;
-import stirling.software.SPDF.model.ApplicationProperties;
-import stirling.software.SPDF.model.Role;
-@Component
-public class InitialSecuritySetup {
-
- @Autowired
- private UserService userService;
-
-
- @Autowired
- ApplicationProperties applicationProperties;
-
- @PostConstruct
- public void init() {
- if (!userService.hasUsers()) {
-
-
- String initialUsername = applicationProperties.getSecurity().getInitialLogin().getUsername();
- String initialPassword = applicationProperties.getSecurity().getInitialLogin().getPassword();
- if (initialUsername != null && initialPassword != null) {
- userService.saveUser(initialUsername, initialPassword, Role.ADMIN.getRoleId());
- } else {
- initialUsername = "admin";
- initialPassword = "stirling";
- userService.saveUser(initialUsername, initialPassword, Role.ADMIN.getRoleId(), true);
- }
-
-
- }
- }
-
-
-
- @PostConstruct
- public void initSecretKey() throws IOException {
- String secretKey = applicationProperties.getAutomaticallyGenerated().getKey();
- if (secretKey == null || secretKey.isEmpty()) {
- secretKey = UUID.randomUUID().toString(); // Generating a random UUID as the secret key
- saveKeyToConfig(secretKey);
- }
- }
-
- private void saveKeyToConfig(String key) throws IOException {
- Path path = Paths.get("configs", "settings.yml"); // Target the configs/settings.yml
- List lines = Files.readAllLines(path);
- boolean keyFound = false;
-
- // Search for the existing key to replace it or place to add it
- for (int i = 0; i < lines.size(); i++) {
- if (lines.get(i).startsWith("AutomaticallyGenerated:")) {
- keyFound = true;
- if (i + 1 < lines.size() && lines.get(i + 1).trim().startsWith("key:")) {
- lines.set(i + 1, " key: " + key);
- break;
- } else {
- lines.add(i + 1, " key: " + key);
- break;
- }
- }
- }
-
- // If the section doesn't exist, append it
- if (!keyFound) {
- lines.add("# Automatically Generated Settings (Do Not Edit Directly)");
- lines.add("AutomaticallyGenerated:");
- lines.add(" key: " + key);
- }
-
- // Write back to the file
- Files.write(path, lines);
- }
-}
\ No newline at end of file
diff --git a/src/main/java/stirling/software/SPDF/config/security/SecurityConfiguration.java b/src/main/java/stirling/software/SPDF/config/security/SecurityConfiguration.java
deleted file mode 100644
index dfe782ac..00000000
--- a/src/main/java/stirling/software/SPDF/config/security/SecurityConfiguration.java
+++ /dev/null
@@ -1,106 +0,0 @@
-package stirling.software.SPDF.config.security;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Lazy;
-import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
-import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
-import org.springframework.security.config.annotation.web.builders.HttpSecurity;
-import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
-import org.springframework.security.core.userdetails.UserDetailsService;
-import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
-import org.springframework.security.crypto.password.PasswordEncoder;
-import org.springframework.security.web.SecurityFilterChain;
-import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
-import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
-import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
-
-import stirling.software.SPDF.repository.JPATokenRepositoryImpl;
-@Configuration
-@EnableWebSecurity()
-@EnableGlobalMethodSecurity(prePostEnabled = true)
-public class SecurityConfiguration {
-
- @Autowired
- private UserDetailsService userDetailsService;
-
- @Bean
- public PasswordEncoder passwordEncoder() {
- return new BCryptPasswordEncoder();
- }
- @Autowired
- @Lazy
- private UserService userService;
-
- @Autowired
- @Qualifier("loginEnabled")
- public boolean loginEnabledValue;
-
- @Autowired
- private UserAuthenticationFilter userAuthenticationFilter;
-
- @Autowired
- private FirstLoginFilter firstLoginFilter;
-
- @Bean
- public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
- http.addFilterBefore(userAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
-
- if(loginEnabledValue) {
-
- http.csrf(csrf -> csrf.disable());
- http.addFilterAfter(firstLoginFilter, UsernamePasswordAuthenticationFilter.class);
- http
- .formLogin(formLogin -> formLogin
- .loginPage("/login")
- .defaultSuccessUrl("/")
- .failureHandler(new CustomAuthenticationFailureHandler())
- .permitAll()
- )
- .logout(logout -> logout
- .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
- .logoutSuccessUrl("/login?logout=true")
- .invalidateHttpSession(true) // Invalidate session
- .deleteCookies("JSESSIONID", "remember-me")
- ).rememberMe(rememberMeConfigurer -> rememberMeConfigurer // Use the configurator directly
- .key("uniqueAndSecret")
- .tokenRepository(persistentTokenRepository())
- .tokenValiditySeconds(1209600) // 2 weeks
- )
- .authorizeHttpRequests(authz -> authz
- .requestMatchers(req -> req.getRequestURI().startsWith("/login") || req.getRequestURI().endsWith(".svg") || req.getRequestURI().startsWith("/register") || req.getRequestURI().startsWith("/error") || req.getRequestURI().startsWith("/images/") || req.getRequestURI().startsWith("/public/") || req.getRequestURI().startsWith("/css/") || req.getRequestURI().startsWith("/js/"))
- .permitAll()
- .anyRequest().authenticated()
- )
- .userDetailsService(userDetailsService)
- .authenticationProvider(authenticationProvider());
- } else {
- http.csrf(csrf -> csrf.disable())
- .authorizeHttpRequests(authz -> authz
- .anyRequest().permitAll()
- );
- }
- return http.build();
- }
-
-
-
- @Bean
- public DaoAuthenticationProvider authenticationProvider() {
- DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
- authProvider.setUserDetailsService(userDetailsService);
- authProvider.setPasswordEncoder(passwordEncoder());
- return authProvider;
- }
-
- @Bean
- public PersistentTokenRepository persistentTokenRepository() {
- return new JPATokenRepositoryImpl();
- }
-
-
-
-}
-
diff --git a/src/main/java/stirling/software/SPDF/config/security/UserAuthenticationFilter.java b/src/main/java/stirling/software/SPDF/config/security/UserAuthenticationFilter.java
deleted file mode 100644
index eca7f70e..00000000
--- a/src/main/java/stirling/software/SPDF/config/security/UserAuthenticationFilter.java
+++ /dev/null
@@ -1,113 +0,0 @@
-package stirling.software.SPDF.config.security;
-
-import java.io.IOException;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.context.annotation.Lazy;
-import org.springframework.http.HttpStatus;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.core.context.SecurityContextHolder;
-import org.springframework.security.core.userdetails.UserDetails;
-import org.springframework.security.core.userdetails.UserDetailsService;
-import org.springframework.stereotype.Component;
-import org.springframework.web.filter.OncePerRequestFilter;
-
-import jakarta.servlet.FilterChain;
-import jakarta.servlet.ServletException;
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpServletResponse;
-import stirling.software.SPDF.model.ApiKeyAuthenticationToken;
-@Component
-public class UserAuthenticationFilter extends OncePerRequestFilter {
-
- @Autowired
- private UserDetailsService userDetailsService;
-
- @Autowired
- @Lazy
- private UserService userService;
-
-
- @Autowired
- @Qualifier("loginEnabled")
- public boolean loginEnabledValue;
-
- @Override
- protected void doFilterInternal(HttpServletRequest request,
- HttpServletResponse response,
- FilterChain filterChain) throws ServletException, IOException {
-
- if (!loginEnabledValue) {
- // If login is not enabled, just pass all requests without authentication
- filterChain.doFilter(request, response);
- return;
- }
- String requestURI = request.getRequestURI();
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
-
- // Check for API key in the request headers if no authentication exists
- if (authentication == null || !authentication.isAuthenticated()) {
- String apiKey = request.getHeader("X-API-Key");
- if (apiKey != null && !apiKey.trim().isEmpty()) {
- try {
- // Use API key to authenticate. This requires you to have an authentication provider for API keys.
- UserDetails userDetails = userService.loadUserByApiKey(apiKey);
- if(userDetails == null)
- {
- response.setStatus(HttpStatus.UNAUTHORIZED.value());
- response.getWriter().write("Invalid API Key.");
- return;
- }
- authentication = new ApiKeyAuthenticationToken(userDetails, apiKey, userDetails.getAuthorities());
- SecurityContextHolder.getContext().setAuthentication(authentication);
- } catch (AuthenticationException e) {
- // If API key authentication fails, deny the request
- response.setStatus(HttpStatus.UNAUTHORIZED.value());
- response.getWriter().write("Invalid API Key.");
- return;
- }
- }
- }
-
- // If we still don't have any authentication, deny the request
- if (authentication == null || !authentication.isAuthenticated()) {
- String method = request.getMethod();
- if ("GET".equalsIgnoreCase(method) && !"/login".equals(requestURI)) {
- response.sendRedirect("/login"); // redirect to the login page
- return;
- } else {
- response.setStatus(HttpStatus.UNAUTHORIZED.value());
- response.getWriter().write("Authentication required. Please provide a X-API-KEY in request header.\nThis is found in Settings -> Account Settings -> API Key\nAlternativly you can disable authentication if this is unexpected");
- return;
- }
- }
-
- filterChain.doFilter(request, response);
- }
-
- @Override
- protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
- String uri = request.getRequestURI();
-
- String[] permitAllPatterns = {
- "/login",
- "/register",
- "/error",
- "/images/",
- "/public/",
- "/css/",
- "/js/"
- };
-
- for (String pattern : permitAllPatterns) {
- if (uri.startsWith(pattern) || uri.endsWith(".svg")) {
- return true;
- }
- }
-
- return false;
- }
-
-}
diff --git a/src/main/java/stirling/software/SPDF/config/security/UserBasedRateLimitingFilter.java b/src/main/java/stirling/software/SPDF/config/security/UserBasedRateLimitingFilter.java
deleted file mode 100644
index f23e5ce3..00000000
--- a/src/main/java/stirling/software/SPDF/config/security/UserBasedRateLimitingFilter.java
+++ /dev/null
@@ -1,125 +0,0 @@
-package stirling.software.SPDF.config.security;
-
-import java.io.IOException;
-import java.time.Duration;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.http.HttpStatus;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.GrantedAuthority;
-import org.springframework.security.core.context.SecurityContextHolder;
-import org.springframework.security.core.userdetails.UserDetails;
-import org.springframework.security.core.userdetails.UserDetailsService;
-import org.springframework.stereotype.Component;
-import org.springframework.web.filter.OncePerRequestFilter;
-
-import io.github.bucket4j.Bandwidth;
-import io.github.bucket4j.Bucket;
-import io.github.bucket4j.ConsumptionProbe;
-import io.github.bucket4j.Refill;
-import jakarta.servlet.FilterChain;
-import jakarta.servlet.ServletException;
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpServletResponse;
-import stirling.software.SPDF.model.Role;
-@Component
-public class UserBasedRateLimitingFilter extends OncePerRequestFilter {
-
- private final Map apiBuckets = new ConcurrentHashMap<>();
- private final Map webBuckets = new ConcurrentHashMap<>();
-
- @Autowired
- private UserDetailsService userDetailsService;
-
- @Autowired
- @Qualifier("rateLimit")
- public boolean rateLimit;
-
- @Override
- protected void doFilterInternal(HttpServletRequest request,
- HttpServletResponse response,
- FilterChain filterChain) throws ServletException, IOException {
- if (!rateLimit) {
- // If rateLimit is not enabled, just pass all requests without rate limiting
- filterChain.doFilter(request, response);
- return;
- }
-
- String method = request.getMethod();
- if (!"POST".equalsIgnoreCase(method)) {
- // If the request is not a POST, just pass it through without rate limiting
- filterChain.doFilter(request, response);
- return;
- }
-
- String identifier = null;
-
- // Check for API key in the request headers
- String apiKey = request.getHeader("X-API-Key");
- if (apiKey != null && !apiKey.trim().isEmpty()) {
- identifier = "API_KEY_" + apiKey; // Prefix to distinguish between API keys and usernames
- } else {
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- if (authentication != null && authentication.isAuthenticated()) {
- UserDetails userDetails = (UserDetails) authentication.getPrincipal();
- identifier = userDetails.getUsername();
- }
- }
-
- // If neither API key nor an authenticated user is present, use IP address
- if (identifier == null) {
- identifier = request.getRemoteAddr();
- }
-
- Role userRole = getRoleFromAuthentication(SecurityContextHolder.getContext().getAuthentication());
-
- if (request.getHeader("X-API-Key") != null) {
- // It's an API call
- processRequest(userRole.getApiCallsPerDay(), identifier, apiBuckets, request, response, filterChain);
- } else {
- // It's a Web UI call
- processRequest(userRole.getWebCallsPerDay(), identifier, webBuckets, request, response, filterChain);
- }
- }
-
- private Role getRoleFromAuthentication(Authentication authentication) {
- if (authentication != null && authentication.isAuthenticated()) {
- for (GrantedAuthority authority : authentication.getAuthorities()) {
- try {
- return Role.fromString(authority.getAuthority());
- } catch (IllegalArgumentException ex) {
- // Ignore and continue to next authority.
- }
- }
- }
- throw new IllegalStateException("User does not have a valid role.");
- }
-
- private void processRequest(int limitPerDay, String identifier, Map buckets,
- HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
- throws IOException, ServletException {
- Bucket userBucket = buckets.computeIfAbsent(identifier, k -> createUserBucket(limitPerDay));
- ConsumptionProbe probe = userBucket.tryConsumeAndReturnRemaining(1);
-
- if (probe.isConsumed()) {
- response.setHeader("X-Rate-Limit-Remaining", Long.toString(probe.getRemainingTokens()));
- filterChain.doFilter(request, response);
- } else {
- long waitForRefill = probe.getNanosToWaitForRefill() / 1_000_000_000;
- response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
- response.setHeader("X-Rate-Limit-Retry-After-Seconds", String.valueOf(waitForRefill));
- response.getWriter().write("Rate limit exceeded for POST requests.");
- }
- }
-
- private Bucket createUserBucket(int limitPerDay) {
- Bandwidth limit = Bandwidth.classic(limitPerDay, Refill.intervally(limitPerDay, Duration.ofDays(1)));
- return Bucket.builder().addLimit(limit).build();
- }
-}
-
-
-
diff --git a/src/main/java/stirling/software/SPDF/config/security/UserService.java b/src/main/java/stirling/software/SPDF/config/security/UserService.java
deleted file mode 100644
index 46c5aeff..00000000
--- a/src/main/java/stirling/software/SPDF/config/security/UserService.java
+++ /dev/null
@@ -1,191 +0,0 @@
-package stirling.software.SPDF.config.security;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Optional;
-import java.util.UUID;
-import java.util.stream.Collectors;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.GrantedAuthority;
-import org.springframework.security.core.authority.SimpleGrantedAuthority;
-import org.springframework.security.core.userdetails.UserDetails;
-import org.springframework.security.core.userdetails.UsernameNotFoundException;
-import org.springframework.security.crypto.password.PasswordEncoder;
-import org.springframework.stereotype.Service;
-
-import stirling.software.SPDF.model.Authority;
-import stirling.software.SPDF.model.User;
-import stirling.software.SPDF.repository.UserRepository;
-@Service
-public class UserService {
-
- @Autowired
- private UserRepository userRepository;
-
- @Autowired
- private PasswordEncoder passwordEncoder;
-
- public Authentication getAuthentication(String apiKey) {
- User user = getUserByApiKey(apiKey);
- if (user == null) {
- throw new UsernameNotFoundException("API key is not valid");
- }
-
- // Convert the user into an Authentication object
- return new UsernamePasswordAuthenticationToken(
- user, // principal (typically the user)
- null, // credentials (we don't expose the password or API key here)
- getAuthorities(user) // user's authorities (roles/permissions)
- );
- }
-
- private Collection extends GrantedAuthority> getAuthorities(User user) {
- // Convert each Authority object into a SimpleGrantedAuthority object.
- return user.getAuthorities().stream()
- .map((Authority authority) -> new SimpleGrantedAuthority(authority.getAuthority()))
- .collect(Collectors.toList());
-
-
- }
-
- private String generateApiKey() {
- String apiKey;
- do {
- apiKey = UUID.randomUUID().toString();
- } while (userRepository.findByApiKey(apiKey) != null); // Ensure uniqueness
- return apiKey;
- }
-
- public User addApiKeyToUser(String username) {
- User user = userRepository.findByUsername(username)
- .orElseThrow(() -> new UsernameNotFoundException("User not found"));
-
- user.setApiKey(generateApiKey());
- return userRepository.save(user);
- }
-
- public User refreshApiKeyForUser(String username) {
- return addApiKeyToUser(username); // reuse the add API key method for refreshing
- }
-
- public String getApiKeyForUser(String username) {
- User user = userRepository.findByUsername(username)
- .orElseThrow(() -> new UsernameNotFoundException("User not found"));
- return user.getApiKey();
- }
-
- public boolean isValidApiKey(String apiKey) {
- return userRepository.findByApiKey(apiKey) != null;
- }
-
- public User getUserByApiKey(String apiKey) {
- return userRepository.findByApiKey(apiKey);
- }
-
- public UserDetails loadUserByApiKey(String apiKey) {
- User userOptional = userRepository.findByApiKey(apiKey);
- if (userOptional != null) {
- User user = userOptional;
- // Convert your User entity to a UserDetails object with authorities
- return new org.springframework.security.core.userdetails.User(
- user.getUsername(),
- user.getPassword(), // you might not need this for API key auth
- getAuthorities(user)
- );
- }
- return null; // or throw an exception
- }
-
-
- public boolean validateApiKeyForUser(String username, String apiKey) {
- Optional userOpt = userRepository.findByUsername(username);
- return userOpt.isPresent() && userOpt.get().getApiKey().equals(apiKey);
- }
-
- public void saveUser(String username, String password) {
- User user = new User();
- user.setUsername(username);
- user.setPassword(passwordEncoder.encode(password));
- user.setEnabled(true);
- userRepository.save(user);
- }
-
- public void saveUser(String username, String password, String role, boolean firstLogin) {
- User user = new User();
- user.setUsername(username);
- user.setPassword(passwordEncoder.encode(password));
- user.addAuthority(new Authority(role, user));
- user.setEnabled(true);
- user.setFirstLogin(firstLogin);
- userRepository.save(user);
- }
-
- public void saveUser(String username, String password, String role) {
- User user = new User();
- user.setUsername(username);
- user.setPassword(passwordEncoder.encode(password));
- user.addAuthority(new Authority(role, user));
- user.setEnabled(true);
- user.setFirstLogin(false);
- userRepository.save(user);
- }
-
- public void deleteUser(String username) {
- Optional userOpt = userRepository.findByUsername(username);
- if (userOpt.isPresent()) {
- userRepository.delete(userOpt.get());
- }
- }
-
- public boolean usernameExists(String username) {
- return userRepository.findByUsername(username).isPresent();
- }
-
- public boolean hasUsers() {
- return userRepository.count() > 0;
- }
-
- public void updateUserSettings(String username, Map updates) {
- Optional userOpt = userRepository.findByUsername(username);
- if (userOpt.isPresent()) {
- User user = userOpt.get();
- Map settingsMap = user.getSettings();
-
- if(settingsMap == null) {
- settingsMap = new HashMap();
- }
- settingsMap.clear();
- settingsMap.putAll(updates);
- user.setSettings(settingsMap);
-
- userRepository.save(user);
- }
- }
-
- public Optional findByUsername(String username) {
- return userRepository.findByUsername(username);
- }
-
- public void changeUsername(User user, String newUsername) {
- user.setUsername(newUsername);
- userRepository.save(user);
- }
-
- public void changePassword(User user, String newPassword) {
- user.setPassword(passwordEncoder.encode(newPassword));
- userRepository.save(user);
- }
-
- public void changeFirstUse(User user, boolean firstUse) {
- user.setFirstLogin(firstUse);
- userRepository.save(user);
- }
-
-
- public boolean isPasswordCorrect(User user, String currentPassword) {
- return passwordEncoder.matches(currentPassword, user.getPassword());
- }
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/CropController.java b/src/main/java/stirling/software/SPDF/controller/api/CropController.java
deleted file mode 100644
index d2723cce..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/CropController.java
+++ /dev/null
@@ -1,86 +0,0 @@
-package stirling.software.SPDF.controller.api;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-
-import org.apache.pdfbox.multipdf.LayerUtility;
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.PDPage;
-import org.apache.pdfbox.pdmodel.PDPageContentStream;
-import org.apache.pdfbox.pdmodel.common.PDRectangle;
-import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.general.CropPdfForm;
-import stirling.software.SPDF.utils.WebResponseUtils;
-
-@RestController
-@RequestMapping("/api/v1/general")
-@Tag(name = "General", description = "General APIs")
-public class CropController {
-
- private static final Logger logger = LoggerFactory.getLogger(CropController.class);
-
- @PostMapping(value = "/crop", consumes = "multipart/form-data")
- @Operation(summary = "Crops a PDF document", description = "This operation takes an input PDF file and crops it according to the given coordinates. Input:PDF Output:PDF Type:SISO")
- public ResponseEntity cropPdf(@ModelAttribute CropPdfForm form)
- throws IOException {
-
-
-
-
-PDDocument sourceDocument = PDDocument.load(new ByteArrayInputStream(form.getFileInput().getBytes()));
-
-PDDocument newDocument = new PDDocument();
-
-int totalPages = sourceDocument.getNumberOfPages();
-
-LayerUtility layerUtility = new LayerUtility(newDocument);
-
-for (int i = 0; i < totalPages; i++) {
- PDPage sourcePage = sourceDocument.getPage(i);
-
- // Create a new page with the size of the source page
- PDPage newPage = new PDPage(sourcePage.getMediaBox());
- newDocument.addPage(newPage);
- PDPageContentStream contentStream = new PDPageContentStream(newDocument, newPage);
-
- // Import the source page as a form XObject
- PDFormXObject formXObject = layerUtility.importPageAsForm(sourceDocument, i);
-
- contentStream.saveGraphicsState();
-
- // Define the crop area
- contentStream.addRect(form.getX(), form.getY(), form.getWidth(), form.getHeight());
- contentStream.clip();
-
- // Draw the entire formXObject
- contentStream.drawForm(formXObject);
-
- contentStream.restoreGraphicsState();
-
- contentStream.close();
-
- // Now, set the new page's media box to the cropped size
- newPage.setMediaBox(new PDRectangle(form.getX(), form.getY(), form.getWidth(), form.getHeight()));
-}
-
-ByteArrayOutputStream baos = new ByteArrayOutputStream();
-newDocument.save(baos);
-newDocument.close();
-sourceDocument.close();
-
-byte[] pdfContent = baos.toByteArray();
-return WebResponseUtils.bytesToWebResponse(pdfContent, form.getFileInput().getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_cropped.pdf");
- }
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/MergeController.java b/src/main/java/stirling/software/SPDF/controller/api/MergeController.java
deleted file mode 100644
index 4727e195..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/MergeController.java
+++ /dev/null
@@ -1,115 +0,0 @@
-package stirling.software.SPDF.controller.api;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import java.nio.file.attribute.BasicFileAttributes;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.List;
-
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.PDPage;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.general.MergePdfsRequest;
-import stirling.software.SPDF.utils.WebResponseUtils;
-
-@RestController
-@RequestMapping("/api/v1/general")
-@Tag(name = "General", description = "General APIs")
-public class MergeController {
-
- private static final Logger logger = LoggerFactory.getLogger(MergeController.class);
-
-
-private PDDocument mergeDocuments(List documents) throws IOException {
- PDDocument mergedDoc = new PDDocument();
- for (PDDocument doc : documents) {
- for (PDPage page : doc.getPages()) {
- mergedDoc.addPage(page);
- }
- }
- return mergedDoc;
-}
-
-private Comparator getSortComparator(String sortType) {
- switch (sortType) {
- case "byFileName":
- return Comparator.comparing(MultipartFile::getOriginalFilename);
- case "byDateModified":
- return (file1, file2) -> {
- try {
- BasicFileAttributes attr1 = Files.readAttributes(Paths.get(file1.getOriginalFilename()), BasicFileAttributes.class);
- BasicFileAttributes attr2 = Files.readAttributes(Paths.get(file2.getOriginalFilename()), BasicFileAttributes.class);
- return attr1.lastModifiedTime().compareTo(attr2.lastModifiedTime());
- } catch (IOException e) {
- return 0; // If there's an error, treat them as equal
- }
- };
- case "byDateCreated":
- return (file1, file2) -> {
- try {
- BasicFileAttributes attr1 = Files.readAttributes(Paths.get(file1.getOriginalFilename()), BasicFileAttributes.class);
- BasicFileAttributes attr2 = Files.readAttributes(Paths.get(file2.getOriginalFilename()), BasicFileAttributes.class);
- return attr1.creationTime().compareTo(attr2.creationTime());
- } catch (IOException e) {
- return 0; // If there's an error, treat them as equal
- }
- };
- case "byPDFTitle":
- return (file1, file2) -> {
- try (PDDocument doc1 = PDDocument.load(file1.getInputStream());
- PDDocument doc2 = PDDocument.load(file2.getInputStream())) {
- String title1 = doc1.getDocumentInformation().getTitle();
- String title2 = doc2.getDocumentInformation().getTitle();
- return title1.compareTo(title2);
- } catch (IOException e) {
- return 0;
- }
- };
- case "orderProvided":
- default:
- return (file1, file2) -> 0; // Default is the order provided
- }
-}
-
-@PostMapping(consumes = "multipart/form-data", value = "/merge-pdfs")
-@Operation(summary = "Merge multiple PDF files into one",
- description = "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 mergePdfs(@ModelAttribute MergePdfsRequest form) throws IOException {
-
- MultipartFile[] files = form.getFileInput();
- Arrays.sort(files, getSortComparator(form.getSortType()));
-
- List documents = new ArrayList<>();
- for (MultipartFile file : files) {
- try (InputStream is = file.getInputStream()) {
- documents.add(PDDocument.load(is));
- }
- }
-
- try (PDDocument mergedDoc = mergeDocuments(documents)) {
- ResponseEntity response = WebResponseUtils.pdfDocToWebResponse(mergedDoc, files[0].getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_merged.pdf");
- return response;
- } finally {
- for (PDDocument doc : documents) {
- if (doc != null) {
- doc.close();
- }
- }
- }
-}
-
-}
\ No newline at end of file
diff --git a/src/main/java/stirling/software/SPDF/controller/api/MultiPageLayoutController.java b/src/main/java/stirling/software/SPDF/controller/api/MultiPageLayoutController.java
deleted file mode 100644
index ebe81ffd..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/MultiPageLayoutController.java
+++ /dev/null
@@ -1,124 +0,0 @@
-package stirling.software.SPDF.controller.api;
-
-
-import java.awt.Color;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-
-import org.apache.pdfbox.multipdf.LayerUtility;
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.PDPage;
-import org.apache.pdfbox.pdmodel.PDPageContentStream;
-import org.apache.pdfbox.pdmodel.common.PDRectangle;
-import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
-import org.apache.pdfbox.util.Matrix;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.general.MergeMultiplePagesRequest;
-import stirling.software.SPDF.utils.WebResponseUtils;
-
-@RestController
-@RequestMapping("/api/v1/general")
-@Tag(name = "General", description = "General APIs")
-public class MultiPageLayoutController {
-
- private static final Logger logger = LoggerFactory.getLogger(MultiPageLayoutController.class);
-
- @PostMapping(value = "/multi-page-layout", consumes = "multipart/form-data")
- @Operation(
- summary = "Merge multiple pages of a PDF document into a single page",
- description = "This operation takes an input PDF file and the number of pages to merge into a single sheet in the output PDF file. Input:PDF Output:PDF Type:SISO"
- )
- public ResponseEntity mergeMultiplePagesIntoOne(@ModelAttribute MergeMultiplePagesRequest request)
- throws IOException {
-
- int pagesPerSheet = request.getPagesPerSheet();
- MultipartFile file = request.getFileInput();
- boolean addBorder = request.isAddBorder();
-
- if (pagesPerSheet != 2 && pagesPerSheet != 3 && pagesPerSheet != (int) Math.sqrt(pagesPerSheet) * Math.sqrt(pagesPerSheet)) {
- throw new IllegalArgumentException("pagesPerSheet must be 2, 3 or a perfect square");
- }
-
- int cols = pagesPerSheet == 2 || pagesPerSheet == 3 ? pagesPerSheet : (int) Math.sqrt(pagesPerSheet);
- int rows = pagesPerSheet == 2 || pagesPerSheet == 3 ? 1 : (int) Math.sqrt(pagesPerSheet);
-
- PDDocument sourceDocument = PDDocument.load(file.getInputStream());
- PDDocument newDocument = new PDDocument();
- PDPage newPage = new PDPage(PDRectangle.A4);
- newDocument.addPage(newPage);
-
- int totalPages = sourceDocument.getNumberOfPages();
- float cellWidth = newPage.getMediaBox().getWidth() / cols;
- float cellHeight = newPage.getMediaBox().getHeight() / rows;
-
- PDPageContentStream contentStream = new PDPageContentStream(newDocument, newPage, PDPageContentStream.AppendMode.APPEND, true, true);
- LayerUtility layerUtility = new LayerUtility(newDocument);
-
- 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(newDocument, newPage, PDPageContentStream.AppendMode.APPEND, true, true);
- }
-
- 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; // This will reset the index for every new page
- 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(); // Close the final content stream
- sourceDocument.close();
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- newDocument.save(baos);
- newDocument.close();
-
- byte[] result = baos.toByteArray();
- return WebResponseUtils.bytesToWebResponse(result, file.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_layoutChanged.pdf");
- }
-
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/RearrangePagesPDFController.java b/src/main/java/stirling/software/SPDF/controller/api/RearrangePagesPDFController.java
deleted file mode 100644
index b76b6cee..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/RearrangePagesPDFController.java
+++ /dev/null
@@ -1,219 +0,0 @@
-package stirling.software.SPDF.controller.api;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.PDPage;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-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.RequestParam;
-import org.springframework.web.bind.annotation.RequestPart;
-import org.springframework.web.bind.annotation.RestController;
-import org.springframework.web.multipart.MultipartFile;
-
-import io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.Parameter;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.SortTypes;
-import stirling.software.SPDF.model.api.PDFWithPageNums;
-import stirling.software.SPDF.model.api.general.RearrangePagesRequest;
-import stirling.software.SPDF.utils.GeneralUtils;
-import stirling.software.SPDF.utils.WebResponseUtils;
-@RestController
-@RequestMapping("/api/v1/general")
-@Tag(name = "General", description = "General APIs")
-public class RearrangePagesPDFController {
-
- private static final Logger logger = LoggerFactory.getLogger(RearrangePagesPDFController.class);
-
- @PostMapping(consumes = "multipart/form-data", value = "/remove-pages")
- @Operation(summary = "Remove pages from a PDF file", description = "This endpoint removes specified pages from a given PDF file. Users can provide a comma-separated list of page numbers or ranges to delete. Input:PDF Output:PDF Type:SISO")
- public ResponseEntity deletePages(@ModelAttribute PDFWithPageNums request )
- throws IOException {
-
- MultipartFile pdfFile = request.getFileInput();
- String pagesToDelete = request.getPageNumbers();
-
- PDDocument document = PDDocument.load(pdfFile.getBytes());
-
- // Split the page order string into an array of page numbers or range of numbers
- String[] pageOrderArr = pagesToDelete.split(",");
-
- List pagesToRemove = GeneralUtils.parsePageList(pageOrderArr, document.getNumberOfPages());
-
- for (int i = pagesToRemove.size() - 1; i >= 0; i--) {
- int pageIndex = pagesToRemove.get(i);
- document.removePage(pageIndex);
- }
- return WebResponseUtils.pdfDocToWebResponse(document,
- pdfFile.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_removed_pages.pdf");
-
- }
-
-
-
- private List removeFirst(int totalPages) {
- if (totalPages <= 1)
- return new ArrayList<>();
- List newPageOrder = new ArrayList<>();
- for (int i = 2; i <= totalPages; i++) {
- newPageOrder.add(i - 1);
- }
- return newPageOrder;
- }
-
- private List removeLast(int totalPages) {
- if (totalPages <= 1)
- return new ArrayList<>();
- List newPageOrder = new ArrayList<>();
- for (int i = 1; i < totalPages; i++) {
- newPageOrder.add(i - 1);
- }
- return newPageOrder;
- }
-
- private List removeFirstAndLast(int totalPages) {
- if (totalPages <= 2)
- return new ArrayList<>();
- List newPageOrder = new ArrayList<>();
- for (int i = 2; i < totalPages; i++) {
- newPageOrder.add(i - 1);
- }
- return newPageOrder;
- }
-
- private List reverseOrder(int totalPages) {
- List newPageOrder = new ArrayList<>();
- for (int i = totalPages; i >= 1; i--) {
- newPageOrder.add(i - 1);
- }
- return newPageOrder;
- }
-
- private List duplexSort(int totalPages) {
- List newPageOrder = new ArrayList<>();
- int half = (totalPages + 1) / 2; // This ensures proper behavior with odd numbers of pages
- for (int i = 1; i <= half; i++) {
- newPageOrder.add(i - 1);
- if (i <= totalPages - half) { // Avoid going out of bounds
- newPageOrder.add(totalPages - i);
- }
- }
- return newPageOrder;
- }
-
- private List bookletSort(int totalPages) {
- List newPageOrder = new ArrayList<>();
- for (int i = 0; i < totalPages / 2; i++) {
- newPageOrder.add(i);
- newPageOrder.add(totalPages - i - 1);
- }
- return newPageOrder;
- }
-
- private List sideStitchBooklet(int totalPages) {
- List newPageOrder = new ArrayList<>();
- for (int i = 0; i < (totalPages + 3) / 4; i++) {
- int begin = i * 4;
- newPageOrder.add(Math.min(begin + 3, totalPages - 1));
- newPageOrder.add(Math.min(begin, totalPages - 1));
- newPageOrder.add(Math.min(begin + 1, totalPages - 1));
- newPageOrder.add(Math.min(begin + 2, totalPages - 1));
- }
- return newPageOrder;
- }
-
- private List oddEvenSplit(int totalPages) {
- List newPageOrder = new ArrayList<>();
- for (int i = 1; i <= totalPages; i += 2) {
- newPageOrder.add(i - 1);
- }
- for (int i = 2; i <= totalPages; i += 2) {
- newPageOrder.add(i - 1);
- }
- return newPageOrder;
- }
-
- private List processSortTypes(String sortTypes, int totalPages) {
- try {
- SortTypes mode = SortTypes.valueOf(sortTypes.toUpperCase());
- switch (mode) {
- case REVERSE_ORDER:
- return reverseOrder(totalPages);
- case DUPLEX_SORT:
- return duplexSort(totalPages);
- case BOOKLET_SORT:
- return bookletSort(totalPages);
- case SIDE_STITCH_BOOKLET_SORT:
- return sideStitchBooklet(totalPages);
- case ODD_EVEN_SPLIT:
- return oddEvenSplit(totalPages);
- case REMOVE_FIRST:
- return removeFirst(totalPages);
- case REMOVE_LAST:
- return removeLast(totalPages);
- case REMOVE_FIRST_AND_LAST:
- return removeFirstAndLast(totalPages);
- default:
- throw new IllegalArgumentException("Unsupported custom mode");
- }
- } catch (IllegalArgumentException e) {
- logger.error("Unsupported custom mode", e);
- return null;
- }
- }
-
- @PostMapping(consumes = "multipart/form-data", value = "/rearrange-pages")
- @Operation(summary = "Rearrange pages in a PDF file", description = "This endpoint rearranges pages in a given PDF file based on the specified page order or custom mode. Users can provide a page order as a comma-separated list of page numbers or page ranges, or a custom mode. Input:PDF Output:PDF")
- public ResponseEntity rearrangePages(@ModelAttribute RearrangePagesRequest request) throws IOException {
- MultipartFile pdfFile = request.getFileInput();
- String pageOrder = request.getPageNumbers();
- String sortType = request.getCustomMode();
- try {
- // Load the input PDF
- PDDocument document = PDDocument.load(pdfFile.getInputStream());
-
- // 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 newPageOrder;
- if (sortType != null && sortType.length() > 0) {
- newPageOrder = processSortTypes(sortType, totalPages);
- } else {
- newPageOrder = GeneralUtils.parsePageList(pageOrderArr, totalPages);
- }
- logger.info("newPageOrder = " +newPageOrder);
- logger.info("totalPages = " +totalPages);
- // Create a new list to hold the pages in the new order
- List newPages = new ArrayList<>();
- for (int i = 0; i < newPageOrder.size(); i++) {
- newPages.add(document.getPage(newPageOrder.get(i)));
- }
-
- // Remove all the pages from the original document
- for (int i = document.getNumberOfPages() - 1; i >= 0; i--) {
- document.removePage(i);
- }
-
- // Add the pages in the new order
- for (PDPage page : newPages) {
- document.addPage(page);
- }
-
- return WebResponseUtils.pdfDocToWebResponse(document,
- pdfFile.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_rearranged.pdf");
- } catch (IOException e) {
- logger.error("Failed rearranging documents", e);
- return null;
- }
- }
-
-
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/RotationController.java b/src/main/java/stirling/software/SPDF/controller/api/RotationController.java
deleted file mode 100644
index ed527549..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/RotationController.java
+++ /dev/null
@@ -1,52 +0,0 @@
-package stirling.software.SPDF.controller.api;
-
-import java.io.IOException;
-
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.PDPage;
-import org.apache.pdfbox.pdmodel.PDPageTree;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.general.RotatePDFRequest;
-import stirling.software.SPDF.utils.WebResponseUtils;
-
-@RestController
-@RequestMapping("/api/v1/general")
-@Tag(name = "General", description = "General APIs")
-public class RotationController {
-
- private static final Logger logger = LoggerFactory.getLogger(RotationController.class);
-
- @PostMapping(consumes = "multipart/form-data", value = "/rotate-pdf")
- @Operation(
- summary = "Rotate a PDF file",
- description = "This endpoint rotates a given PDF file by a specified angle. The angle must be a multiple of 90. Input:PDF Output:PDF Type:SISO"
- )
- public ResponseEntity rotatePDF(
- @ModelAttribute RotatePDFRequest request) throws IOException {
- MultipartFile pdfFile = request.getFileInput();
- Integer angle = request.getAngle();
- // Load the PDF document
- PDDocument document = PDDocument.load(pdfFile.getBytes());
-
- // Get the list of pages in the document
- PDPageTree pages = document.getPages();
-
- for (PDPage page : pages) {
- page.setRotation(page.getRotation() + angle);
- }
-
- return WebResponseUtils.pdfDocToWebResponse(document, pdfFile.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_rotated.pdf");
-
- }
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/ScalePagesController.java b/src/main/java/stirling/software/SPDF/controller/api/ScalePagesController.java
deleted file mode 100644
index 743ea6b1..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/ScalePagesController.java
+++ /dev/null
@@ -1,110 +0,0 @@
-package stirling.software.SPDF.controller.api;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.apache.pdfbox.multipdf.LayerUtility;
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.PDPage;
-import org.apache.pdfbox.pdmodel.PDPageContentStream;
-import org.apache.pdfbox.pdmodel.common.PDRectangle;
-import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
-import org.apache.pdfbox.util.Matrix;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.general.ScalePagesRequest;
-import stirling.software.SPDF.utils.WebResponseUtils;
-@RestController
-@RequestMapping("/api/v1/general")
-@Tag(name = "General", description = "General APIs")
-public class ScalePagesController {
-
- private static final Logger logger = LoggerFactory.getLogger(ScalePagesController.class);
-
- @PostMapping(value = "/scale-pages", consumes = "multipart/form-data")
- @Operation(summary = "Change the size of a PDF page/document", description = "This operation takes an input PDF file and the size to scale the pages to in the output PDF file. Input:PDF Output:PDF Type:SISO")
- public ResponseEntity scalePages(@ModelAttribute ScalePagesRequest request) throws IOException {
- MultipartFile file = request.getFileInput();
- String targetPDRectangle = request.getPageSize();
- float scaleFactor = request.getScaleFactor();
-
- Map sizeMap = new HashMap<>();
- // Add A0 - A10
- sizeMap.put("A0", PDRectangle.A0);
- sizeMap.put("A1", PDRectangle.A1);
- sizeMap.put("A2", PDRectangle.A2);
- sizeMap.put("A3", PDRectangle.A3);
- sizeMap.put("A4", PDRectangle.A4);
- sizeMap.put("A5", PDRectangle.A5);
- sizeMap.put("A6", PDRectangle.A6);
-
- // Add other sizes
- sizeMap.put("LETTER", PDRectangle.LETTER);
- sizeMap.put("LEGAL", PDRectangle.LEGAL);
-
- if (!sizeMap.containsKey(targetPDRectangle)) {
- throw new IllegalArgumentException(
- "Invalid PDRectangle. It must be one of the following: A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10");
- }
-
- PDRectangle targetSize = sizeMap.get(targetPDRectangle);
-
- PDDocument sourceDocument = PDDocument.load(file.getBytes());
- PDDocument outputDocument = new PDDocument();
-
- int totalPages = sourceDocument.getNumberOfPages();
- for (int i = 0; i < totalPages; i++) {
- PDPage sourcePage = sourceDocument.getPage(i);
- PDRectangle sourceSize = sourcePage.getMediaBox();
-
- float scaleWidth = targetSize.getWidth() / sourceSize.getWidth();
- float scaleHeight = targetSize.getHeight() / sourceSize.getHeight();
- float scale = Math.min(scaleWidth, scaleHeight) * scaleFactor;
-
- PDPage newPage = new PDPage(targetSize);
- outputDocument.addPage(newPage);
-
- PDPageContentStream contentStream = new PDPageContentStream(outputDocument, newPage, PDPageContentStream.AppendMode.APPEND, true);
-
- float x = (targetSize.getWidth() - sourceSize.getWidth() * scale) / 2;
- float y = (targetSize.getHeight() - sourceSize.getHeight() * scale) / 2;
-
- contentStream.saveGraphicsState();
- contentStream.transform(Matrix.getTranslateInstance(x, y));
- contentStream.transform(Matrix.getScaleInstance(scale, scale));
-
- LayerUtility layerUtility = new LayerUtility(outputDocument);
- PDFormXObject form = layerUtility.importPageAsForm(sourceDocument, i);
- contentStream.drawForm(form);
-
- contentStream.restoreGraphicsState();
- contentStream.close();
- }
-
-
-
-
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- outputDocument.save(baos);
- outputDocument.close();
- sourceDocument.close();
-
-
- return WebResponseUtils.bytesToWebResponse(baos.toByteArray(),
- file.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_scaled.pdf");
- }
-
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/SplitPDFController.java b/src/main/java/stirling/software/SPDF/controller/api/SplitPDFController.java
deleted file mode 100644
index 649dc8ec..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/SplitPDFController.java
+++ /dev/null
@@ -1,109 +0,0 @@
-package stirling.software.SPDF.controller.api;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.stream.Collectors;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipOutputStream;
-
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.PDPage;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.PDFWithPageNums;
-import stirling.software.SPDF.utils.WebResponseUtils;
-import org.apache.pdfbox.multipdf.Splitter;
-@RestController
-@RequestMapping("/api/v1/general")
-@Tag(name = "General", description = "General APIs")
-public class SplitPDFController {
-
- private static final Logger logger = LoggerFactory.getLogger(SplitPDFController.class);
-
- @PostMapping(consumes = "multipart/form-data", value = "/split-pages")
- @Operation(summary = "Split a PDF file into separate documents",
- description = "This endpoint splits a given PDF file into separate documents based on the specified page numbers or ranges. Users can specify pages using individual numbers, ranges, or 'all' for every page. Input:PDF Output:PDF Type:SIMO")
- public ResponseEntity splitPdf(@ModelAttribute PDFWithPageNums request) throws IOException {
- MultipartFile file = request.getFileInput();
- String pages = request.getPageNumbers();
- // open the pdf document
- InputStream inputStream = file.getInputStream();
- PDDocument document = PDDocument.load(inputStream);
-
- List pageNumbers = request.getPageNumbersList(document);
- if(!pageNumbers.contains(document.getNumberOfPages() - 1))
- pageNumbers.add(document.getNumberOfPages()- 1);
- logger.info("Splitting PDF into pages: {}", pageNumbers.stream().map(String::valueOf).collect(Collectors.joining(",")));
-
- Splitter splitter = new Splitter();
- List splitDocumentsBoas = new ArrayList<>();
-
- int previousPageNumber = 1; // PDFBox uses 1-based indexing for pages.
- for (int splitPoint : pageNumbers) {
- splitPoint = splitPoint + 1;
- splitter.setStartPage(previousPageNumber);
- splitter.setEndPage(splitPoint);
- List splitDocuments = splitter.split(document);
-
- for (PDDocument splitDoc : splitDocuments) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- splitDoc.save(baos);
- splitDocumentsBoas.add(baos);
- splitDoc.close();
- }
-
- previousPageNumber = splitPoint + 1;
- }
-
-
- // closing the original document
- document.close();
-
- Path zipFile = Files.createTempFile("split_documents", ".zip");
-
- String filename = file.getOriginalFilename().replaceFirst("[.][^.]+$", "");
- try (ZipOutputStream zipOut = new ZipOutputStream(Files.newOutputStream(zipFile))) {
- // loop through the split documents and write them to the zip file
- for (int i = 0; i < splitDocumentsBoas.size(); i++) {
- String fileName = filename + "_" + (i + 1) + ".pdf";
- ByteArrayOutputStream baos = splitDocumentsBoas.get(i);
- byte[] pdf = baos.toByteArray();
-
- // Add PDF file to the zip
- ZipEntry pdfEntry = new ZipEntry(fileName);
- zipOut.putNextEntry(pdfEntry);
- zipOut.write(pdf);
- zipOut.closeEntry();
-
- logger.info("Wrote split document {} to zip file", fileName);
- }
- } catch (Exception e) {
- logger.error("Failed writing to zip", e);
- throw e;
- }
-
- logger.info("Successfully created zip file with split documents: {}", zipFile.toString());
- byte[] data = Files.readAllBytes(zipFile);
- Files.delete(zipFile);
-
- // return the Resource in the response
- return WebResponseUtils.bytesToWebResponse(data, filename + ".zip", MediaType.APPLICATION_OCTET_STREAM);
-
- }
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/ToSinglePageController.java b/src/main/java/stirling/software/SPDF/controller/api/ToSinglePageController.java
deleted file mode 100644
index 22bf1d70..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/ToSinglePageController.java
+++ /dev/null
@@ -1,86 +0,0 @@
-package stirling.software.SPDF.controller.api;
-
-import java.awt.geom.AffineTransform;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-
-import org.apache.pdfbox.multipdf.LayerUtility;
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.PDPage;
-import org.apache.pdfbox.pdmodel.PDPageContentStream;
-import org.apache.pdfbox.pdmodel.common.PDRectangle;
-import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.PDFFile;
-import stirling.software.SPDF.utils.WebResponseUtils;
-@RestController
-@RequestMapping("/api/v1/general")
-@Tag(name = "General", description = "General APIs")
-public class ToSinglePageController {
-
- private static final Logger logger = LoggerFactory.getLogger(ToSinglePageController.class);
-
-
- @PostMapping(consumes = "multipart/form-data", value = "/pdf-to-single-page")
- @Operation(
- summary = "Convert a multi-page PDF into a single long page PDF",
- description = "This endpoint converts a multi-page PDF document into a single paged PDF document. The width of the single page will be same as the input's width, but the height will be the sum of all the pages' heights. Input:PDF Output:PDF Type:SISO"
- )
- public ResponseEntity pdfToSinglePage(@ModelAttribute PDFFile request) throws IOException {
-
- // Load the source document
- PDDocument sourceDocument = PDDocument.load(request.getFileInput().getInputStream());
-
- // Calculate total height and max width
- float totalHeight = 0;
- float maxWidth = 0;
- for (PDPage page : sourceDocument.getPages()) {
- PDRectangle pageSize = page.getMediaBox();
- totalHeight += pageSize.getHeight();
- maxWidth = Math.max(maxWidth, pageSize.getWidth());
- }
-
- // Create new document and page with calculated dimensions
- PDDocument newDocument = new PDDocument();
- PDPage newPage = new PDPage(new PDRectangle(maxWidth, totalHeight));
- newDocument.addPage(newPage);
-
- // Initialize the content stream of the new page
- PDPageContentStream contentStream = new PDPageContentStream(newDocument, newPage);
- contentStream.close();
-
- LayerUtility layerUtility = new LayerUtility(newDocument);
- float yOffset = totalHeight;
-
- // For each page, copy its content to the new page at the correct offset
- for (PDPage page : sourceDocument.getPages()) {
- PDFormXObject form = layerUtility.importPageAsForm(sourceDocument, sourceDocument.getPages().indexOf(page));
- AffineTransform af = AffineTransform.getTranslateInstance(0, yOffset - page.getMediaBox().getHeight());
- layerUtility.wrapInSaveRestore(newPage);
- String defaultLayerName = "Layer" + sourceDocument.getPages().indexOf(page);
- layerUtility.appendFormAsLayer(newPage, form, af, defaultLayerName);
- yOffset -= page.getMediaBox().getHeight();
- }
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- newDocument.save(baos);
- newDocument.close();
- sourceDocument.close();
-
- byte[] result = baos.toByteArray();
- return WebResponseUtils.bytesToWebResponse(result, request.getFileInput().getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_singlePage.pdf");
-
-
-
-
- }
-}
\ No newline at end of file
diff --git a/src/main/java/stirling/software/SPDF/controller/api/UserController.java b/src/main/java/stirling/software/SPDF/controller/api/UserController.java
deleted file mode 100644
index bf451567..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/UserController.java
+++ /dev/null
@@ -1,234 +0,0 @@
-package stirling.software.SPDF.controller.api;
-
-import java.security.Principal;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Optional;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.ResponseEntity;
-import org.springframework.security.access.prepost.PreAuthorize;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
-import org.springframework.stereotype.Controller;
-import org.springframework.ui.Model;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.servlet.mvc.support.RedirectAttributes;
-import org.springframework.web.servlet.view.RedirectView;
-
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpServletResponse;
-import stirling.software.SPDF.config.security.UserService;
-import stirling.software.SPDF.model.User;
-
-@Controller
-@RequestMapping("/api/v1/user")
-public class UserController {
-
- @Autowired
- private UserService userService;
-
- @PostMapping("/register")
- public String register(@RequestParam String username, @RequestParam String password, Model model) {
- if(userService.usernameExists(username)) {
- model.addAttribute("error", "Username already exists");
- return "register";
- }
-
- userService.saveUser(username, password);
- return "redirect:/login?registered=true";
- }
-
- @PostMapping("/change-username-and-password")
- public RedirectView changeUsernameAndPassword(Principal principal,
- @RequestParam String currentPassword,
- @RequestParam String newUsername,
- @RequestParam String newPassword,
- HttpServletRequest request,
- HttpServletResponse response,
- RedirectAttributes redirectAttributes) {
- if (principal == null) {
- return new RedirectView("/change-creds?messageType=notAuthenticated");
- }
-
- Optional userOpt = userService.findByUsername(principal.getName());
-
- if (userOpt == null || userOpt.isEmpty()) {
- return new RedirectView("/change-creds?messageType=userNotFound");
- }
-
- User user = userOpt.get();
-
- if (!userService.isPasswordCorrect(user, currentPassword)) {
- return new RedirectView("/change-creds?messageType=incorrectPassword");
- }
-
- if (!user.getUsername().equals(newUsername) && userService.usernameExists(newUsername)) {
- return new RedirectView("/change-creds?messageType=usernameExists");
- }
-
-
- userService.changePassword(user, newPassword);
- if(newUsername != null && newUsername.length() > 0 && !user.getUsername().equals(newUsername)) {
- userService.changeUsername(user, newUsername);
- }
- userService.changeFirstUse(user, false);
-
- // Logout using Spring's utility
- new SecurityContextLogoutHandler().logout(request, response, null);
-
- return new RedirectView("/login?messageType=credsUpdated");
- }
-
-
-
- @PostMapping("/change-username")
- public RedirectView changeUsername(Principal principal,
- @RequestParam String currentPassword,
- @RequestParam String newUsername,
- HttpServletRequest request,
- HttpServletResponse response,
- RedirectAttributes redirectAttributes) {
- if (principal == null) {
- return new RedirectView("/account?messageType=notAuthenticated");
- }
-
- Optional userOpt = userService.findByUsername(principal.getName());
-
- if (userOpt == null || userOpt.isEmpty()) {
- return new RedirectView("/account?messageType=userNotFound");
- }
-
- User user = userOpt.get();
-
- if (!userService.isPasswordCorrect(user, currentPassword)) {
- return new RedirectView("/account?messageType=incorrectPassword");
- }
-
- if (!user.getUsername().equals(newUsername) && userService.usernameExists(newUsername)) {
- return new RedirectView("/account?messageType=usernameExists");
- }
-
- if(newUsername != null && newUsername.length() > 0) {
- userService.changeUsername(user, newUsername);
- }
-
- // Logout using Spring's utility
- new SecurityContextLogoutHandler().logout(request, response, null);
-
- return new RedirectView("/login?messageType=credsUpdated");
- }
-
- @PostMapping("/change-password")
- public RedirectView changePassword(Principal principal,
- @RequestParam String currentPassword,
- @RequestParam String newPassword,
- HttpServletRequest request,
- HttpServletResponse response,
- RedirectAttributes redirectAttributes) {
- if (principal == null) {
- return new RedirectView("/account?messageType=notAuthenticated");
- }
-
- Optional userOpt = userService.findByUsername(principal.getName());
-
- if (userOpt == null || userOpt.isEmpty()) {
- return new RedirectView("/account?messageType=userNotFound");
- }
-
- User user = userOpt.get();
-
- if (!userService.isPasswordCorrect(user, currentPassword)) {
- return new RedirectView("/account?messageType=incorrectPassword");
- }
-
- userService.changePassword(user, newPassword);
-
- // Logout using Spring's utility
- new SecurityContextLogoutHandler().logout(request, response, null);
-
- return new RedirectView("/login?messageType=credsUpdated");
- }
-
-
- @PostMapping("/updateUserSettings")
- public String updateUserSettings(HttpServletRequest request, Principal principal) {
- Map paramMap = request.getParameterMap();
- Map updates = new HashMap<>();
-
- System.out.println("Received parameter map: " + paramMap);
-
- for (Map.Entry entry : paramMap.entrySet()) {
- updates.put(entry.getKey(), entry.getValue()[0]);
- }
-
- System.out.println("Processed updates: " + updates);
-
- // Assuming you have a method in userService to update the settings for a user
- userService.updateUserSettings(principal.getName(), updates);
-
- return "redirect:/account"; // Redirect to a page of your choice after updating
- }
-
- @PreAuthorize("hasRole('ROLE_ADMIN')")
- @PostMapping("/admin/saveUser")
- public RedirectView saveUser(@RequestParam String username, @RequestParam String password, @RequestParam String role,
- @RequestParam(name = "forceChange", required = false, defaultValue = "false") boolean forceChange) {
-
- if(userService.usernameExists(username)) {
- return new RedirectView("/addUsers?messageType=usernameExists");
- }
- userService.saveUser(username, password, role, forceChange);
- return new RedirectView("/addUsers"); // Redirect to account page after adding the user
- }
-
-
- @PreAuthorize("hasRole('ROLE_ADMIN')")
- @PostMapping("/admin/deleteUser/{username}")
- public String deleteUser(@PathVariable String username, Authentication authentication) {
-
- // Get the currently authenticated username
- String currentUsername = authentication.getName();
-
- // Check if the provided username matches the current session's username
- if (currentUsername.equals(username)) {
- throw new IllegalArgumentException("Cannot delete currently logined in user.");
- }
-
- userService.deleteUser(username);
- return "redirect:/addUsers";
- }
-
- @PostMapping("/get-api-key")
- public ResponseEntity getApiKey(Principal principal) {
- if (principal == null) {
- return ResponseEntity.status(HttpStatus.FORBIDDEN).body("User not authenticated.");
- }
- String username = principal.getName();
- String apiKey = userService.getApiKeyForUser(username);
- if (apiKey == null) {
- return ResponseEntity.status(HttpStatus.NOT_FOUND).body("API key not found for user.");
- }
- return ResponseEntity.ok(apiKey);
- }
-
- @PostMapping("/update-api-key")
- public ResponseEntity updateApiKey(Principal principal) {
- if (principal == null) {
- return ResponseEntity.status(HttpStatus.FORBIDDEN).body("User not authenticated.");
- }
- String username = principal.getName();
- User user = userService.refreshApiKeyForUser(username);
- String apiKey = user.getApiKey();
- if (apiKey == null) {
- return ResponseEntity.status(HttpStatus.NOT_FOUND).body("API key not found for user.");
- }
- return ResponseEntity.ok(apiKey);
- }
-
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertEpubToPdf.java b/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertEpubToPdf.java
deleted file mode 100644
index e821a36a..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertEpubToPdf.java
+++ /dev/null
@@ -1,130 +0,0 @@
-package stirling.software.SPDF.controller.api.converters;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.StringReader;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipInputStream;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-
-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.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
-import org.xml.sax.InputSource;
-
-import io.swagger.v3.oas.annotations.Hidden;
-import io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.GeneralFile;
-import stirling.software.SPDF.utils.FileToPdf;
-import stirling.software.SPDF.utils.WebResponseUtils;
-
-@RestController
-@RequestMapping("/api/v1/convert")
-@Tag(name = "Convert", description = "Convert APIs")
-public class ConvertEpubToPdf {
- //TODO
- @PostMapping(consumes = "multipart/form-data", value = "/epub-to-single-pdf")
- @Hidden
- @Operation(
- summary = "Convert an EPUB file to a single PDF",
- description = "This endpoint takes an EPUB file input and converts it to a single PDF."
- )
- public ResponseEntity epubToSinglePdf(
- @ModelAttribute GeneralFile request)
- throws Exception {
- MultipartFile fileInput = request.getFileInput();
- if (fileInput == null) {
- throw new IllegalArgumentException("Please provide an EPUB file for conversion.");
- }
-
- String originalFilename = fileInput.getOriginalFilename();
- if (originalFilename == null || !originalFilename.endsWith(".epub")) {
- throw new IllegalArgumentException("File must be in .epub format.");
- }
-
- Map epubContents = extractEpubContent(fileInput);
- List htmlFilesOrder = getHtmlFilesOrderFromOpf(epubContents);
-
- List individualPdfs = new ArrayList<>();
-
- for (String htmlFile : htmlFilesOrder) {
- byte[] htmlContent = epubContents.get(htmlFile);
- byte[] pdfBytes = FileToPdf.convertHtmlToPdf(htmlContent, htmlFile.replace(".html", ".pdf"));
- individualPdfs.add(pdfBytes);
- }
-
- // Pseudo-code to merge individual PDFs into one.
- byte[] mergedPdfBytes = mergeMultiplePdfsIntoOne(individualPdfs);
-
- return WebResponseUtils.bytesToWebResponse(mergedPdfBytes, originalFilename.replace(".epub", ".pdf"));
- }
-
- // Assuming a pseudo-code function that merges multiple PDFs into one.
- private byte[] mergeMultiplePdfsIntoOne(List individualPdfs) {
- // You can use a library such as PDFBox to perform the merging here.
- // Return the byte[] of the merged PDF.
- return null;
- }
-
- private Map extractEpubContent(MultipartFile fileInput) throws IOException {
- Map contentMap = new HashMap<>();
-
- try (ZipInputStream zis = new ZipInputStream(fileInput.getInputStream())) {
- ZipEntry zipEntry = zis.getNextEntry();
- while (zipEntry != null) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int read = 0;
- while ((read = zis.read(buffer)) != -1) {
- baos.write(buffer, 0, read);
- }
- contentMap.put(zipEntry.getName(), baos.toByteArray());
- zipEntry = zis.getNextEntry();
- }
- }
-
- return contentMap;
- }
-
- private List getHtmlFilesOrderFromOpf(Map epubContents) throws Exception {
- String opfContent = new String(epubContents.get("OEBPS/content.opf")); // Adjusting for given path
- DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
- InputSource is = new InputSource(new StringReader(opfContent));
- Document doc = dBuilder.parse(is);
-
- NodeList itemRefs = doc.getElementsByTagName("itemref");
- List htmlFilesOrder = new ArrayList<>();
-
- for (int i = 0; i < itemRefs.getLength(); i++) {
- Element itemRef = (Element) itemRefs.item(i);
- String idref = itemRef.getAttribute("idref");
-
- NodeList items = doc.getElementsByTagName("item");
- for (int j = 0; j < items.getLength(); j++) {
- Element item = (Element) items.item(j);
- if (idref.equals(item.getAttribute("id"))) {
- htmlFilesOrder.add(item.getAttribute("href")); // Fetching the actual href
- break;
- }
- }
- }
-
- return htmlFilesOrder;
- }
-
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertHtmlToPDF.java b/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertHtmlToPDF.java
deleted file mode 100644
index 5839dd2d..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertHtmlToPDF.java
+++ /dev/null
@@ -1,52 +0,0 @@
-package stirling.software.SPDF.controller.api.converters;
-
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.GeneralFile;
-import stirling.software.SPDF.utils.FileToPdf;
-import stirling.software.SPDF.utils.WebResponseUtils;
-
-@RestController
-@Tag(name = "Convert", description = "Convert APIs")
-@RequestMapping("/api/v1/convert")
-public class ConvertHtmlToPDF {
-
-
- @PostMapping(consumes = "multipart/form-data", value = "/html/pdf")
- @Operation(
- summary = "Convert an HTML or ZIP (containing HTML and CSS) to PDF",
- description = "This endpoint takes an HTML or ZIP file input and converts it to a PDF format."
- )
- public ResponseEntity HtmlToPdf(
- @ModelAttribute GeneralFile request)
- throws Exception {
- MultipartFile fileInput = request.getFileInput();
-
- if (fileInput == null) {
- throw new IllegalArgumentException("Please provide an HTML or ZIP file for conversion.");
- }
-
- String originalFilename = fileInput.getOriginalFilename();
- if (originalFilename == null || (!originalFilename.endsWith(".html") && !originalFilename.endsWith(".zip"))) {
- throw new IllegalArgumentException("File must be either .html or .zip format.");
- }byte[] pdfBytes = FileToPdf.convertHtmlToPdf( fileInput.getBytes(), originalFilename);
-
- String outputFilename = originalFilename.replaceFirst("[.][^.]+$", "") + ".pdf"; // Remove file extension and append .pdf
-
- return WebResponseUtils.bytesToWebResponse(pdfBytes, outputFilename);
- }
-
-
-
-
-
-
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertImgPDFController.java b/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertImgPDFController.java
deleted file mode 100644
index 0064a3ab..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertImgPDFController.java
+++ /dev/null
@@ -1,103 +0,0 @@
-package stirling.software.SPDF.controller.api.converters;
-
-import java.io.IOException;
-
-import org.apache.pdfbox.rendering.ImageType;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.core.io.ByteArrayResource;
-import org.springframework.core.io.Resource;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.HttpStatus;
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.converters.ConvertToImageRequest;
-import stirling.software.SPDF.model.api.converters.ConvertToPdfRequest;
-import stirling.software.SPDF.utils.PdfUtils;
-import stirling.software.SPDF.utils.WebResponseUtils;
-@RestController
-@RequestMapping("/api/v1/convert")
-@Tag(name = "Convert", description = "Convert APIs")
-public class ConvertImgPDFController {
-
- private static final Logger logger = LoggerFactory.getLogger(ConvertImgPDFController.class);
-
- @PostMapping(consumes = "multipart/form-data", value = "/pdf/img")
- @Operation(summary = "Convert PDF to image(s)",
- description = "This endpoint converts a PDF file to image(s) with the specified image format, color type, and DPI. Users can choose to get a single image or multiple images. Input:PDF Output:Image Type:SI-Conditional")
- public ResponseEntity convertToImage(@ModelAttribute ConvertToImageRequest request) throws IOException {
- MultipartFile file = request.getFileInput();
- String imageFormat = request.getImageFormat();
- String singleOrMultiple = request.getSingleOrMultiple();
- String colorType = request.getColorType();
- String dpi = request.getDpi();
-
- byte[] pdfBytes = file.getBytes();
- ImageType colorTypeResult = ImageType.RGB;
- if ("greyscale".equals(colorType)) {
- colorTypeResult = ImageType.GRAY;
- } else if ("blackwhite".equals(colorType)) {
- colorTypeResult = ImageType.BINARY;
- }
- // returns bytes for image
- boolean singleImage = singleOrMultiple.equals("single");
- byte[] result = null;
- String filename = file.getOriginalFilename().replaceFirst("[.][^.]+$", "");
- try {
- result = PdfUtils.convertFromPdf(pdfBytes, imageFormat.toUpperCase(), colorTypeResult, singleImage, Integer.valueOf(dpi), filename);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- if (singleImage) {
- HttpHeaders headers = new HttpHeaders();
- headers.setContentType(MediaType.parseMediaType(getMediaType(imageFormat)));
- ResponseEntity response = new ResponseEntity<>(new ByteArrayResource(result), headers, HttpStatus.OK);
- return response;
- } else {
- ByteArrayResource resource = new ByteArrayResource(result);
- // return the Resource in the response
- return ResponseEntity.ok()
- .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename + "_convertedToImages.zip")
- .contentType(MediaType.APPLICATION_OCTET_STREAM).contentLength(resource.contentLength()).body(resource);
- }
- }
-
- @PostMapping(consumes = "multipart/form-data", value = "/img/pdf")
- @Operation(summary = "Convert images to a PDF file",
- description = "This endpoint converts one or more images to a PDF file. Users can specify whether to stretch the images to fit the PDF page, and whether to automatically rotate the images. Input:Image Output:PDF Type:SISO?")
- public ResponseEntity convertToPdf(@ModelAttribute ConvertToPdfRequest request) throws IOException {
- MultipartFile[] file = request.getFileInput();
- String fitOption = request.getFitOption();
- String colorType = request.getColorType();
- boolean autoRotate = request.isAutoRotate();
-
- // Convert the file to PDF and get the resulting bytes
- byte[] bytes = PdfUtils.imageToPdf(file, fitOption, autoRotate, colorType);
- return WebResponseUtils.bytesToWebResponse(bytes, file[0].getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_converted.pdf");
- }
-
- private String getMediaType(String imageFormat) {
- if (imageFormat.equalsIgnoreCase("PNG"))
- return "image/png";
- else if (imageFormat.equalsIgnoreCase("JPEG") || imageFormat.equalsIgnoreCase("JPG"))
- return "image/jpeg";
- else if (imageFormat.equalsIgnoreCase("GIF"))
- return "image/gif";
- else
- return "application/octet-stream";
- }
-
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertMarkdownToPdf.java b/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertMarkdownToPdf.java
deleted file mode 100644
index 4191ecdf..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertMarkdownToPdf.java
+++ /dev/null
@@ -1,54 +0,0 @@
-package stirling.software.SPDF.controller.api.converters;
-
-import org.commonmark.node.Node;
-import org.commonmark.parser.Parser;
-import org.commonmark.renderer.html.HtmlRenderer;
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.GeneralFile;
-import stirling.software.SPDF.utils.FileToPdf;
-import stirling.software.SPDF.utils.WebResponseUtils;
-
-@RestController
-@Tag(name = "Convert", description = "Convert APIs")
-@RequestMapping("/api/v1/convert")
-public class ConvertMarkdownToPdf {
-
- @PostMapping(consumes = "multipart/form-data", value = "/markdown/pdf")
- @Operation(
- summary = "Convert a Markdown file to PDF",
- description = "This endpoint takes a Markdown file input, converts it to HTML, and then to PDF format."
- )
- public ResponseEntity markdownToPdf(
- @ModelAttribute GeneralFile request)
- throws Exception {
- MultipartFile fileInput = request.getFileInput();
-
- if (fileInput == null) {
- throw new IllegalArgumentException("Please provide a Markdown file for conversion.");
- }
-
- String originalFilename = fileInput.getOriginalFilename();
- if (originalFilename == null || !originalFilename.endsWith(".md")) {
- throw new IllegalArgumentException("File must be in .md format.");
- }
-
- // Convert Markdown to HTML using CommonMark
- Parser parser = Parser.builder().build();
- Node document = parser.parse(new String(fileInput.getBytes()));
- HtmlRenderer renderer = HtmlRenderer.builder().build();
- String htmlContent = renderer.render(document);
-
- byte[] pdfBytes = FileToPdf.convertHtmlToPdf(htmlContent.getBytes(), "converted.html");
-
- String outputFilename = originalFilename.replaceFirst("[.][^.]+$", "") + ".pdf"; // Remove file extension and append .pdf
- return WebResponseUtils.bytesToWebResponse(pdfBytes, outputFilename);
- }
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeController.java b/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeController.java
deleted file mode 100644
index e1c18a49..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeController.java
+++ /dev/null
@@ -1,78 +0,0 @@
-package stirling.software.SPDF.controller.api.converters;
-
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.StandardCopyOption;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.apache.commons.io.FilenameUtils;
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.GeneralFile;
-import stirling.software.SPDF.utils.ProcessExecutor;
-import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult;
-import stirling.software.SPDF.utils.WebResponseUtils;
-
-@RestController
-@Tag(name = "Convert", description = "Convert APIs")
-@RequestMapping("/api/v1/convert")
-public class ConvertOfficeController {
-
- public byte[] convertToPdf(MultipartFile inputFile) throws IOException, InterruptedException {
- // Check for valid file extension
- String originalFilename = inputFile.getOriginalFilename();
- if (originalFilename == null || !isValidFileExtension(FilenameUtils.getExtension(originalFilename))) {
- throw new IllegalArgumentException("Invalid file extension");
- }
-
- // Save the uploaded file to a temporary location
- Path tempInputFile = Files.createTempFile("input_", "." + FilenameUtils.getExtension(originalFilename));
- Files.copy(inputFile.getInputStream(), tempInputFile, StandardCopyOption.REPLACE_EXISTING);
-
- // Prepare the output file path
- Path tempOutputFile = Files.createTempFile("output_", ".pdf");
-
- // Run the LibreOffice command
- List command = new ArrayList<>(Arrays.asList("unoconv", "-vvv", "-f", "pdf", "-o", tempOutputFile.toString(), tempInputFile.toString()));
- ProcessExecutorResult returnCode = ProcessExecutor.getInstance(ProcessExecutor.Processes.LIBRE_OFFICE).runCommandWithOutputHandling(command);
-
- // Read the converted PDF file
- byte[] pdfBytes = Files.readAllBytes(tempOutputFile);
-
- // Clean up the temporary files
- Files.delete(tempInputFile);
- Files.delete(tempOutputFile);
-
- return pdfBytes;
- }
- private boolean isValidFileExtension(String fileExtension) {
- String extensionPattern = "^(?i)[a-z0-9]{2,4}$";
- return fileExtension.matches(extensionPattern);
- }
-
- @PostMapping(consumes = "multipart/form-data", value = "/file/pdf")
- @Operation(
- summary = "Convert a file to a PDF using LibreOffice",
- description = "This endpoint converts a given file to a PDF using LibreOffice API Input:Any Output:PDF Type:SISO"
- )
- public ResponseEntity processFileToPDF(@ModelAttribute GeneralFile request)
- throws Exception {
- MultipartFile inputFile = request.getFileInput();
- // unused but can start server instance if startup time is to long
- // LibreOfficeListener.getInstance().start();
-
- byte[] pdfByteArray = convertToPdf(inputFile);
- return WebResponseUtils.bytesToWebResponse(pdfByteArray, inputFile.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_convertedToPDF.pdf");
- }
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToOffice.java b/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToOffice.java
deleted file mode 100644
index 11279a27..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToOffice.java
+++ /dev/null
@@ -1,72 +0,0 @@
-package stirling.software.SPDF.controller.api.converters;
-
-import java.io.IOException;
-
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.PDFFile;
-import stirling.software.SPDF.model.api.converters.PdfToPresentationRequest;
-import stirling.software.SPDF.model.api.converters.PdfToTextOrRTFRequest;
-import stirling.software.SPDF.model.api.converters.PdfToWordRequest;
-import stirling.software.SPDF.utils.PDFToFile;
-
-@RestController
-@RequestMapping("/api/v1/convert")
-@Tag(name = "Convert", description = "Convert APIs")
-public class ConvertPDFToOffice {
-
- @PostMapping(consumes = "multipart/form-data", value = "/pdf/html")
- @Operation(summary = "Convert PDF to HTML", description = "This endpoint converts a PDF file to HTML format. Input:PDF Output:HTML Type:SISO")
- public ResponseEntity processPdfToHTML(@ModelAttribute PDFFile request)
- throws Exception {
- MultipartFile inputFile = request.getFileInput();
- PDFToFile pdfToFile = new PDFToFile();
- return pdfToFile.processPdfToOfficeFormat(inputFile, "html", "writer_pdf_import");
- }
-
- @PostMapping(consumes = "multipart/form-data", value = "/pdf/presentation")
- @Operation(summary = "Convert PDF to Presentation format", description = "This endpoint converts a given PDF file to a Presentation format. Input:PDF Output:PPT Type:SISO")
- public ResponseEntity processPdfToPresentation(@ModelAttribute PdfToPresentationRequest request) throws IOException, InterruptedException {
- MultipartFile inputFile = request.getFileInput();
- String outputFormat = request.getOutputFormat();
- PDFToFile pdfToFile = new PDFToFile();
- return pdfToFile.processPdfToOfficeFormat(inputFile, outputFormat, "impress_pdf_import");
- }
-
- @PostMapping(consumes = "multipart/form-data", value = "/pdf/text")
- @Operation(summary = "Convert PDF to Text or RTF format", description = "This endpoint converts a given PDF file to Text or RTF format. Input:PDF Output:TXT Type:SISO")
- public ResponseEntity processPdfToRTForTXT(@ModelAttribute PdfToTextOrRTFRequest request) throws IOException, InterruptedException {
- MultipartFile inputFile = request.getFileInput();
- String outputFormat = request.getOutputFormat();
-
- PDFToFile pdfToFile = new PDFToFile();
- return pdfToFile.processPdfToOfficeFormat(inputFile, outputFormat, "writer_pdf_import");
- }
-
- @PostMapping(consumes = "multipart/form-data", value = "/pdf/word")
- @Operation(summary = "Convert PDF to Word document", description = "This endpoint converts a given PDF file to a Word document format. Input:PDF Output:WORD Type:SISO")
- public ResponseEntity processPdfToWord(@ModelAttribute PdfToWordRequest request) throws IOException, InterruptedException {
- MultipartFile inputFile = request.getFileInput();
- String outputFormat = request.getOutputFormat();
- PDFToFile pdfToFile = new PDFToFile();
- return pdfToFile.processPdfToOfficeFormat(inputFile, outputFormat, "writer_pdf_import");
- }
-
- @PostMapping(consumes = "multipart/form-data", value = "/pdf/xml")
- @Operation(summary = "Convert PDF to XML", description = "This endpoint converts a PDF file to an XML file. Input:PDF Output:XML Type:SISO")
- public ResponseEntity processPdfToXML(@ModelAttribute PDFFile request)
- throws Exception {
- MultipartFile inputFile = request.getFileInput();
-
- PDFToFile pdfToFile = new PDFToFile();
- return pdfToFile.processPdfToOfficeFormat(inputFile, "xml", "writer_pdf_import");
- }
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFA.java b/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFA.java
deleted file mode 100644
index 32ccb84a..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFA.java
+++ /dev/null
@@ -1,67 +0,0 @@
-package stirling.software.SPDF.controller.api.converters;
-
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.ArrayList;
-import java.util.List;
-
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.PDFFile;
-import stirling.software.SPDF.utils.ProcessExecutor;
-import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult;
-import stirling.software.SPDF.utils.WebResponseUtils;
-
-@RestController
-@RequestMapping("/api/v1/convert")
-@Tag(name = "Convert", description = "Convert APIs")
-public class ConvertPDFToPDFA {
-
- @PostMapping(consumes = "multipart/form-data", value = "/pdf/pdfa")
- @Operation(
- summary = "Convert a PDF to a PDF/A",
- description = "This endpoint converts a PDF file to a PDF/A file. PDF/A is a format designed for long-term archiving of digital documents. Input:PDF Output:PDF Type:SISO"
- )
- public ResponseEntity pdfToPdfA(@ModelAttribute PDFFile request)
- throws Exception {
- MultipartFile inputFile = request.getFileInput();
-
- // Save the uploaded file to a temporary location
- Path tempInputFile = Files.createTempFile("input_", ".pdf");
- inputFile.transferTo(tempInputFile.toFile());
-
- // Prepare the output file path
- Path tempOutputFile = Files.createTempFile("output_", ".pdf");
-
- // Prepare the OCRmyPDF command
- List command = new ArrayList<>();
- command.add("ocrmypdf");
- command.add("--skip-text");
- command.add("--tesseract-timeout=0");
- command.add("--output-type");
- command.add("pdfa");
- command.add(tempInputFile.toString());
- command.add(tempOutputFile.toString());
-
- ProcessExecutorResult returnCode = ProcessExecutor.getInstance(ProcessExecutor.Processes.OCR_MY_PDF).runCommandWithOutputHandling(command);
-
- // Read the optimized PDF file
- byte[] pdfBytes = Files.readAllBytes(tempOutputFile);
-
- // Clean up the temporary files
- Files.delete(tempInputFile);
- Files.delete(tempOutputFile);
-
- // Return the optimized PDF as a response
- String outputFilename = inputFile.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_PDFA.pdf";
- return WebResponseUtils.bytesToWebResponse(pdfBytes, outputFilename);
- }
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertWebsiteToPDF.java b/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertWebsiteToPDF.java
deleted file mode 100644
index 7c81edf2..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertWebsiteToPDF.java
+++ /dev/null
@@ -1,76 +0,0 @@
-package stirling.software.SPDF.controller.api.converters;
-
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.ArrayList;
-import java.util.List;
-
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.converters.UrlToPdfRequest;
-import stirling.software.SPDF.utils.GeneralUtils;
-import stirling.software.SPDF.utils.ProcessExecutor;
-import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult;
-import stirling.software.SPDF.utils.WebResponseUtils;
-
-@RestController
-@Tag(name = "Convert", description = "Convert APIs")
-@RequestMapping("/api/v1/convert")
-public class ConvertWebsiteToPDF {
-
- @PostMapping(consumes = "multipart/form-data", value = "/url/pdf")
- @Operation(
- summary = "Convert a URL to a PDF",
- description = "This endpoint fetches content from a URL and converts it to a PDF format."
- )
- public ResponseEntity urlToPdf(@ModelAttribute UrlToPdfRequest request) throws IOException, InterruptedException {
- String URL = request.getUrlInput();
-
- // Validate the URL format
- if(!URL.matches("^https?://.*") || !GeneralUtils.isValidURL(URL)) {
- throw new IllegalArgumentException("Invalid URL format provided.");
- }
- Path tempOutputFile = null;
- byte[] pdfBytes;
- try {
- // Prepare the output file path
- tempOutputFile = Files.createTempFile("output_", ".pdf");
-
- // Prepare the OCRmyPDF command
- List command = new ArrayList<>();
- command.add("weasyprint");
- command.add(URL);
- command.add(tempOutputFile.toString());
-
- ProcessExecutorResult returnCode = ProcessExecutor.getInstance(ProcessExecutor.Processes.WEASYPRINT).runCommandWithOutputHandling(command);
-
- // Read the optimized PDF file
- pdfBytes = Files.readAllBytes(tempOutputFile);
- }
- finally {
- // Clean up the temporary files
- Files.delete(tempOutputFile);
- }
- // Convert URL to a safe filename
- String outputFilename = convertURLToFileName(URL);
-
- return WebResponseUtils.bytesToWebResponse(pdfBytes, outputFilename);
- }
-
- private String convertURLToFileName(String url) {
- String safeName = url.replaceAll("[^a-zA-Z0-9]", "_");
- if(safeName.length() > 50) {
- safeName = safeName.substring(0, 50); // restrict to 50 characters
- }
- return safeName + ".pdf";
- }
-
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/filters/FilterController.java b/src/main/java/stirling/software/SPDF/controller/api/filters/FilterController.java
deleted file mode 100644
index bdbb6613..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/filters/FilterController.java
+++ /dev/null
@@ -1,196 +0,0 @@
-package stirling.software.SPDF.controller.api.filters;
-
-import java.io.IOException;
-
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.PDPage;
-import org.apache.pdfbox.pdmodel.common.PDRectangle;
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.PDFComparisonAndCount;
-import stirling.software.SPDF.model.api.PDFWithPageNums;
-import stirling.software.SPDF.model.api.filter.ContainsTextRequest;
-import stirling.software.SPDF.model.api.filter.FileSizeRequest;
-import stirling.software.SPDF.model.api.filter.PageRotationRequest;
-import stirling.software.SPDF.model.api.filter.PageSizeRequest;
-import stirling.software.SPDF.utils.PdfUtils;
-import stirling.software.SPDF.utils.WebResponseUtils;
-
-@RestController
-@RequestMapping("/api/v1/filter")
-@Tag(name = "Filter", description = "Filter APIs")
-public class FilterController {
-
- @PostMapping(consumes = "multipart/form-data", value = "/filter-contains-text")
- @Operation(summary = "Checks if a PDF contains set text, returns true if does", description = "Input:PDF Output:Boolean Type:SISO")
- public ResponseEntity containsText(@ModelAttribute ContainsTextRequest request) throws IOException, InterruptedException {
- MultipartFile inputFile = request.getFileInput();
- String text = request.getText();
- String pageNumber = request.getPageNumbers();
-
- PDDocument pdfDocument = PDDocument.load(inputFile.getInputStream());
- if (PdfUtils.hasText(pdfDocument, pageNumber, text))
- return WebResponseUtils.pdfDocToWebResponse(pdfDocument, inputFile.getOriginalFilename());
- return null;
- }
-
- // TODO
- @PostMapping(consumes = "multipart/form-data", value = "/filter-contains-image")
- @Operation(summary = "Checks if a PDF contains an image", description = "Input:PDF Output:Boolean Type:SISO")
- public ResponseEntity containsImage(@ModelAttribute PDFWithPageNums request)
- throws IOException, InterruptedException {
- MultipartFile inputFile = request.getFileInput();
- String pageNumber = request.getPageNumbers();
-
- PDDocument pdfDocument = PDDocument.load(inputFile.getInputStream());
- if (PdfUtils.hasImages(pdfDocument, pageNumber))
- return WebResponseUtils.pdfDocToWebResponse(pdfDocument, inputFile.getOriginalFilename());
- return null;
- }
-
- @PostMapping(consumes = "multipart/form-data", value = "/filter-page-count")
- @Operation(summary = "Checks if a PDF is greater, less or equal to a setPageCount", description = "Input:PDF Output:Boolean Type:SISO")
- public ResponseEntity pageCount(@ModelAttribute PDFComparisonAndCount request) throws IOException, InterruptedException {
- MultipartFile inputFile = request.getFileInput();
- String pageCount = request.getPageCount();
- String comparator = request.getComparator();
- // Load the PDF
- PDDocument document = PDDocument.load(inputFile.getInputStream());
- int actualPageCount = document.getNumberOfPages();
-
- boolean valid = false;
- // Perform the comparison
- switch (comparator) {
- case "Greater":
- valid = actualPageCount > Integer.parseInt(pageCount);
- break;
- case "Equal":
- valid = actualPageCount == Integer.parseInt(pageCount);
- break;
- case "Less":
- valid = actualPageCount < Integer.parseInt(pageCount);
- break;
- default:
- throw new IllegalArgumentException("Invalid comparator: " + comparator);
- }
-
- if (valid)
- return WebResponseUtils.multiPartFileToWebResponse(inputFile);
- return null;
- }
-
- @PostMapping(consumes = "multipart/form-data", value = "/filter-page-size")
- @Operation(summary = "Checks if a PDF is of a certain size", description = "Input:PDF Output:Boolean Type:SISO")
- public ResponseEntity pageSize(@ModelAttribute PageSizeRequest request) throws IOException, InterruptedException {
- MultipartFile inputFile = request.getFileInput();
- String standardPageSize = request.getStandardPageSize();
- String comparator = request.getComparator();
-
- // Load the PDF
- PDDocument document = PDDocument.load(inputFile.getInputStream());
-
- PDPage firstPage = document.getPage(0);
- PDRectangle actualPageSize = firstPage.getMediaBox();
-
- // Calculate the area of the actual page size
- float actualArea = actualPageSize.getWidth() * actualPageSize.getHeight();
-
- // Get the standard size and calculate its area
- PDRectangle standardSize = PdfUtils.textToPageSize(standardPageSize);
- float standardArea = standardSize.getWidth() * standardSize.getHeight();
-
- boolean valid = false;
- // Perform the comparison
- switch (comparator) {
- case "Greater":
- valid = actualArea > standardArea;
- break;
- case "Equal":
- valid = actualArea == standardArea;
- break;
- case "Less":
- valid = actualArea < standardArea;
- break;
- default:
- throw new IllegalArgumentException("Invalid comparator: " + comparator);
- }
-
- if (valid)
- return WebResponseUtils.multiPartFileToWebResponse(inputFile);
- return null;
- }
-
- @PostMapping(consumes = "multipart/form-data", value = "/filter-file-size")
- @Operation(summary = "Checks if a PDF is a set file size", description = "Input:PDF Output:Boolean Type:SISO")
- public ResponseEntity fileSize(@ModelAttribute FileSizeRequest request) throws IOException, InterruptedException {
- MultipartFile inputFile = request.getFileInput();
- String fileSize = request.getFileSize();
- String comparator = request.getComparator();
-
- // Get the file size
- long actualFileSize = inputFile.getSize();
-
- boolean valid = false;
- // Perform the comparison
- switch (comparator) {
- case "Greater":
- valid = actualFileSize > Long.parseLong(fileSize);
- break;
- case "Equal":
- valid = actualFileSize == Long.parseLong(fileSize);
- break;
- case "Less":
- valid = actualFileSize < Long.parseLong(fileSize);
- break;
- default:
- throw new IllegalArgumentException("Invalid comparator: " + comparator);
- }
-
- if (valid)
- return WebResponseUtils.multiPartFileToWebResponse(inputFile);
- return null;
- }
-
- @PostMapping(consumes = "multipart/form-data", value = "/filter-page-rotation")
- @Operation(summary = "Checks if a PDF is of a certain rotation", description = "Input:PDF Output:Boolean Type:SISO")
- public ResponseEntity pageRotation(@ModelAttribute PageRotationRequest request) throws IOException, InterruptedException {
- MultipartFile inputFile = request.getFileInput();
- int rotation = request.getRotation();
- String comparator = request.getComparator();
-
- // Load the PDF
- PDDocument document = PDDocument.load(inputFile.getInputStream());
-
- // Get the rotation of the first page
- PDPage firstPage = document.getPage(0);
- int actualRotation = firstPage.getRotation();
- boolean valid = false;
- // Perform the comparison
- switch (comparator) {
- case "Greater":
- valid = actualRotation > rotation;
- break;
- case "Equal":
- valid = actualRotation == rotation;
- break;
- case "Less":
- valid = actualRotation < rotation;
- break;
- default:
- throw new IllegalArgumentException("Invalid comparator: " + comparator);
- }
-
- if (valid)
- return WebResponseUtils.multiPartFileToWebResponse(inputFile);
- return null;
-
- }
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/misc/AutoRenameController.java b/src/main/java/stirling/software/SPDF/controller/api/misc/AutoRenameController.java
deleted file mode 100644
index fe8337d2..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/misc/AutoRenameController.java
+++ /dev/null
@@ -1,128 +0,0 @@
-package stirling.software.SPDF.controller.api.misc;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Comparator;
-import java.util.List;
-
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.text.PDFTextStripper;
-import org.apache.pdfbox.text.TextPosition;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.misc.ExtractHeaderRequest;
-import stirling.software.SPDF.utils.WebResponseUtils;
-@RestController
-@RequestMapping("/api/v1/misc")
-@Tag(name = "Misc", description = "Miscellaneous APIs")
-public class AutoRenameController {
-
- private static final Logger logger = LoggerFactory.getLogger(AutoRenameController.class);
-
- private static final float TITLE_FONT_SIZE_THRESHOLD = 20.0f;
- private static final int LINE_LIMIT = 11;
-
- @PostMapping(consumes = "multipart/form-data", value = "/auto-rename")
- @Operation(summary = "Extract header from PDF file", description = "This endpoint accepts a PDF file and attempts to extract its title or header based on heuristics. Input:PDF Output:PDF Type:SISO")
- public ResponseEntity extractHeader(@ModelAttribute ExtractHeaderRequest request) throws Exception {
- MultipartFile file = request.getFileInput();
- Boolean useFirstTextAsFallback = request.isUseFirstTextAsFallback();
-
- PDDocument document = PDDocument.load(file.getInputStream());
- PDFTextStripper reader = new PDFTextStripper() {
- class LineInfo {
- String text;
- float fontSize;
-
- LineInfo(String text, float fontSize) {
- this.text = text;
- this.fontSize = fontSize;
- }
- }
-
- List 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) {
- maxFontSizeInLine = text.getFontSizeInPt();
- }
- }
- }
-
- private void processLine() {
- if (lineBuilder.length() > 0 && 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 mergedLineInfos = new ArrayList<>();
- for (int i = 0; i < lineInfos.size(); i++) {
- String mergedText = lineInfos.get(i).text;
- float fontSize = lineInfos.get(i).fontSize;
- while (i + 1 < lineInfos.size() && lineInfos.get(i + 1).fontSize == fontSize) {
- mergedText += " " + lineInfos.get(i + 1).text;
- i++;
- }
- mergedLineInfos.add(new LineInfo(mergedText, 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;
-
- return title != null ? title : (useFirstTextAsFallback ? (mergedLineInfos.isEmpty() ? null : mergedLineInfos.get(mergedLineInfos.size() - 1).text) : null);
- }
-
- };
-
- String header = reader.getText(document);
-
-
-
- // Sanitize the header string by removing characters not allowed in a filename.
- if (header != null && header.length() < 255) {
- header = header.replaceAll("[/\\\\?%*:|\"<>]", "");
- return WebResponseUtils.pdfDocToWebResponse(document, header + ".pdf");
- } else {
- logger.info("File has no good title to be found");
- return WebResponseUtils.pdfDocToWebResponse(document, file.getOriginalFilename());
- }
- }
-
-
-
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/misc/AutoSplitPdfController.java b/src/main/java/stirling/software/SPDF/controller/api/misc/AutoSplitPdfController.java
deleted file mode 100644
index b4b9b951..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/misc/AutoSplitPdfController.java
+++ /dev/null
@@ -1,144 +0,0 @@
-package stirling.software.SPDF.controller.api.misc;
-import java.awt.image.BufferedImage;
-import java.awt.image.DataBufferByte;
-import java.awt.image.DataBufferInt;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipOutputStream;
-
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.rendering.PDFRenderer;
-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 com.google.zxing.BinaryBitmap;
-import com.google.zxing.LuminanceSource;
-import com.google.zxing.MultiFormatReader;
-import com.google.zxing.NotFoundException;
-import com.google.zxing.PlanarYUVLuminanceSource;
-import com.google.zxing.Result;
-import com.google.zxing.common.HybridBinarizer;
-
-import io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.misc.AutoSplitPdfRequest;
-import stirling.software.SPDF.utils.WebResponseUtils;
-
-@RestController
-@RequestMapping("/api/v1/misc")
-@Tag(name = "Misc", description = "Miscellaneous APIs")
-public class AutoSplitPdfController {
-
- private static final String QR_CONTENT = "https://github.com/Frooodle/Stirling-PDF";
-
- @PostMapping(value = "/auto-split-pdf", consumes = "multipart/form-data")
- @Operation(summary = "Auto split PDF pages into separate documents", description = "This endpoint accepts a PDF file, scans each page for a specific QR code, and splits the document at the QR code boundaries. The output is a zip file containing each separate PDF document. Input:PDF Output:ZIP Type:SISO")
- public ResponseEntity autoSplitPdf(@ModelAttribute AutoSplitPdfRequest request) throws IOException {
- MultipartFile file = request.getFileInput();
- boolean duplexMode = request.isDuplexMode();
-
- InputStream inputStream = file.getInputStream();
- PDDocument document = PDDocument.load(inputStream);
- PDFRenderer pdfRenderer = new PDFRenderer(document);
-
- List splitDocuments = new ArrayList<>();
- List splitDocumentsBoas = new ArrayList<>();
-
- for (int page = 0; page < document.getNumberOfPages(); ++page) {
- BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 150);
- String result = decodeQRCode(bim);
-
- if (QR_CONTENT.equals(result) && page != 0) {
- splitDocuments.add(new PDDocument());
- }
-
- if (!splitDocuments.isEmpty() && !QR_CONTENT.equals(result)) {
- splitDocuments.get(splitDocuments.size() - 1).addPage(document.getPage(page));
- } else if (page == 0) {
- PDDocument firstDocument = new PDDocument();
- firstDocument.addPage(document.getPage(page));
- splitDocuments.add(firstDocument);
- }
-
- // If duplexMode is true and current page is a divider, then skip next page
- if (duplexMode && QR_CONTENT.equals(result)) {
- page++;
- }
- }
-
- // Remove split documents that have no pages
- splitDocuments.removeIf(pdDocument -> pdDocument.getNumberOfPages() == 0);
-
- for (PDDocument splitDocument : splitDocuments) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- splitDocument.save(baos);
- splitDocumentsBoas.add(baos);
- splitDocument.close();
- }
-
- document.close();
-
- Path zipFile = Files.createTempFile("split_documents", ".zip");
- String filename = file.getOriginalFilename().replaceFirst("[.][^.]+$", "");
- byte[] data;
-
- try (ZipOutputStream zipOut = new ZipOutputStream(Files.newOutputStream(zipFile))) {
- for (int i = 0; i < splitDocumentsBoas.size(); i++) {
- String fileName = filename + "_" + (i + 1) + ".pdf";
- ByteArrayOutputStream baos = splitDocumentsBoas.get(i);
- byte[] pdf = baos.toByteArray();
-
- ZipEntry pdfEntry = new ZipEntry(fileName);
- zipOut.putNextEntry(pdfEntry);
- zipOut.write(pdf);
- zipOut.closeEntry();
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- data = Files.readAllBytes(zipFile);
- Files.delete(zipFile);
- }
-
- return WebResponseUtils.bytesToWebResponse(data, filename + ".zip", MediaType.APPLICATION_OCTET_STREAM);
- }
-
-
- private static String decodeQRCode(BufferedImage bufferedImage) {
- LuminanceSource source;
-
- if (bufferedImage.getRaster().getDataBuffer() instanceof DataBufferByte) {
- byte[] pixels = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData();
- source = new PlanarYUVLuminanceSource(pixels, bufferedImage.getWidth(), bufferedImage.getHeight(), 0, 0, bufferedImage.getWidth(), bufferedImage.getHeight(), false);
- } else if (bufferedImage.getRaster().getDataBuffer() instanceof DataBufferInt) {
- int[] pixels = ((DataBufferInt) bufferedImage.getRaster().getDataBuffer()).getData();
- byte[] newPixels = new byte[pixels.length];
- for (int i = 0; i < pixels.length; i++) {
- newPixels[i] = (byte) (pixels[i] & 0xff);
- }
- source = new PlanarYUVLuminanceSource(newPixels, bufferedImage.getWidth(), bufferedImage.getHeight(), 0, 0, bufferedImage.getWidth(), bufferedImage.getHeight(), false);
- } else {
- throw new IllegalArgumentException("BufferedImage must have 8-bit gray scale, 24-bit RGB, 32-bit ARGB (packed int), byte gray, or 3-byte/4-byte RGB image data");
- }
-
- BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
-
- try {
- Result result = new MultiFormatReader().decode(bitmap);
- return result.getText();
- } catch (NotFoundException e) {
- return null; // there is no QR code in the image
- }
- }
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/misc/BlankPageController.java b/src/main/java/stirling/software/SPDF/controller/api/misc/BlankPageController.java
deleted file mode 100644
index c52ff61a..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/misc/BlankPageController.java
+++ /dev/null
@@ -1,122 +0,0 @@
-package stirling.software.SPDF.controller.api.misc;
-
-import java.awt.image.BufferedImage;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.stream.Collectors;
-import java.util.stream.IntStream;
-
-import javax.imageio.ImageIO;
-
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.PDPage;
-import org.apache.pdfbox.pdmodel.PDPageTree;
-import org.apache.pdfbox.rendering.PDFRenderer;
-import org.apache.pdfbox.text.PDFTextStripper;
-import org.springframework.http.HttpStatus;
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.misc.RemoveBlankPagesRequest;
-import stirling.software.SPDF.utils.PdfUtils;
-import stirling.software.SPDF.utils.ProcessExecutor;
-import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult;
-import stirling.software.SPDF.utils.WebResponseUtils;
-
-@RestController
-@RequestMapping("/api/v1/misc")
-@Tag(name = "Misc", description = "Miscellaneous APIs")
-public class BlankPageController {
-
- @PostMapping(consumes = "multipart/form-data", value = "/remove-blanks")
- @Operation(
- summary = "Remove blank pages from a PDF file",
- description = "This endpoint removes blank pages from a given PDF file. Users can specify the threshold and white percentage to tune the detection of blank pages. Input:PDF Output:PDF Type:SISO"
- )
- public ResponseEntity removeBlankPages(@ModelAttribute RemoveBlankPagesRequest request) throws IOException, InterruptedException {
- MultipartFile inputFile = request.getFileInput();
- int threshold = request.getThreshold();
- float whitePercent = request.getWhitePercent();
-
- PDDocument document = null;
- try {
- document = PDDocument.load(inputFile.getInputStream());
- PDPageTree pages = document.getDocumentCatalog().getPages();
- PDFTextStripper textStripper = new PDFTextStripper();
-
- List pagesToKeepIndex = new ArrayList<>();
- int pageIndex = 0;
- PDFRenderer pdfRenderer = new PDFRenderer(document);
-
- for (PDPage page : pages) {
- System.out.println("checking page " + pageIndex);
- textStripper.setStartPage(pageIndex + 1);
- textStripper.setEndPage(pageIndex + 1);
- String pageText = textStripper.getText(document);
- boolean hasText = !pageText.trim().isEmpty();
- if (hasText) {
- pagesToKeepIndex.add(pageIndex);
- System.out.println("page " + pageIndex + " has text");
- } else {
- boolean hasImages = PdfUtils.hasImagesOnPage(page);
- if (hasImages) {
- System.out.println("page " + pageIndex + " has image");
-
- Path tempFile = Files.createTempFile("image_", ".png");
-
- // Render image and save as temp file
- BufferedImage image = pdfRenderer.renderImageWithDPI(pageIndex, 300);
- ImageIO.write(image, "png", tempFile.toFile());
-
- List command = new ArrayList<>(Arrays.asList("python3", System.getProperty("user.dir") + "/scripts/detect-blank-pages.py", tempFile.toString() ,"--threshold", String.valueOf(threshold), "--white_percent", String.valueOf(whitePercent)));
-
- // Run CLI command
- ProcessExecutorResult returnCode = ProcessExecutor.getInstance(ProcessExecutor.Processes.PYTHON_OPENCV).runCommandWithOutputHandling(command);
-
- // does contain data
- if (returnCode.getRc() == 0) {
- System.out.println("page " + pageIndex + " has image which is not blank");
- pagesToKeepIndex.add(pageIndex);
- } else {
- System.out.println("Skipping, Image was blank for page #" + pageIndex);
- }
- }
- }
- pageIndex++;
-
- }
- System.out.print("pagesToKeep=" + pagesToKeepIndex.size());
-
- // Remove pages not present in pagesToKeepIndex
- List pageIndices = IntStream.range(0, pages.getCount()).boxed().collect(Collectors.toList());
- Collections.reverse(pageIndices); // Reverse to prevent index shifting during removal
- for (Integer i : pageIndices) {
- if (!pagesToKeepIndex.contains(i)) {
- pages.remove(i);
- }
- }
-
- return WebResponseUtils.pdfDocToWebResponse(document, inputFile.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_blanksRemoved.pdf");
- } catch (IOException e) {
- e.printStackTrace();
- return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
- } finally {
- if (document != null)
- document.close();
- }
- }
-
-
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/misc/CompressController.java b/src/main/java/stirling/software/SPDF/controller/api/misc/CompressController.java
deleted file mode 100644
index dd864bc1..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/misc/CompressController.java
+++ /dev/null
@@ -1,242 +0,0 @@
-package stirling.software.SPDF.controller.api.misc;
-
-import java.awt.Image;
-import java.awt.image.BufferedImage;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.imageio.ImageIO;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.pdfbox.cos.COSName;
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.PDPage;
-import org.apache.pdfbox.pdmodel.PDResources;
-import org.apache.pdfbox.pdmodel.graphics.PDXObject;
-import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.misc.OptimizePdfRequest;
-import stirling.software.SPDF.utils.GeneralUtils;
-import stirling.software.SPDF.utils.ProcessExecutor;
-import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult;
-import stirling.software.SPDF.utils.WebResponseUtils;
-
-@RestController
-@RequestMapping("/api/v1/misc")
-@Tag(name = "Misc", description = "Miscellaneous APIs")
-public class CompressController {
-
- private static final Logger logger = LoggerFactory.getLogger(CompressController.class);
-
- @PostMapping(consumes = "multipart/form-data", value = "/compress-pdf")
- @Operation(summary = "Optimize PDF file", description = "This endpoint accepts a PDF file and optimizes it based on the provided parameters. Input:PDF Output:PDF Type:SISO")
- public ResponseEntity optimizePdf(@ModelAttribute OptimizePdfRequest request) throws Exception {
- MultipartFile inputFile = request.getFileInput();
- Integer optimizeLevel = request.getOptimizeLevel();
- String expectedOutputSizeString = request.getExpectedOutputSize();
-
-
- if(expectedOutputSizeString == null && optimizeLevel == null) {
- throw new Exception("Both expected output size and optimize level are not specified");
- }
-
- Long expectedOutputSize = 0L;
- boolean autoMode = false;
- if (expectedOutputSizeString != null && expectedOutputSizeString.length() > 1 ) {
- expectedOutputSize = GeneralUtils.convertSizeToBytes(expectedOutputSizeString);
- autoMode = true;
- }
-
- // Save the uploaded file to a temporary location
- Path tempInputFile = Files.createTempFile("input_", ".pdf");
- inputFile.transferTo(tempInputFile.toFile());
-
- long inputFileSize = Files.size(tempInputFile);
-
- // Prepare the output file path
- Path tempOutputFile = Files.createTempFile("output_", ".pdf");
-
- // Determine initial optimization level based on expected size reduction, only if in autoMode
- if(autoMode) {
- double sizeReductionRatio = expectedOutputSize / (double) inputFileSize;
- if (sizeReductionRatio > 0.7) {
- optimizeLevel = 1;
- } else if (sizeReductionRatio > 0.5) {
- optimizeLevel = 2;
- } else if (sizeReductionRatio > 0.35) {
- optimizeLevel = 3;
- } else {
- optimizeLevel = 3;
- }
- }
-
- boolean sizeMet = false;
- while (!sizeMet && optimizeLevel <= 4) {
- // Prepare the Ghostscript command
- List command = new ArrayList<>();
- command.add("gs");
- command.add("-sDEVICE=pdfwrite");
- command.add("-dCompatibilityLevel=1.4");
-
- switch (optimizeLevel) {
- case 1:
- command.add("-dPDFSETTINGS=/prepress");
- break;
- case 2:
- command.add("-dPDFSETTINGS=/printer");
- break;
- case 3:
- command.add("-dPDFSETTINGS=/ebook");
- break;
- case 4:
- command.add("-dPDFSETTINGS=/screen");
- break;
- default:
- command.add("-dPDFSETTINGS=/default");
- }
-
- command.add("-dNOPAUSE");
- command.add("-dQUIET");
- command.add("-dBATCH");
- command.add("-sOutputFile=" + tempOutputFile.toString());
- command.add(tempInputFile.toString());
-
- ProcessExecutorResult returnCode = ProcessExecutor.getInstance(ProcessExecutor.Processes.GHOSTSCRIPT).runCommandWithOutputHandling(command);
-
- // Check if file size is within expected size or not auto mode so instantly finish
- long outputFileSize = Files.size(tempOutputFile);
- if (outputFileSize <= expectedOutputSize || !autoMode) {
- sizeMet = true;
- } else {
- // Increase optimization level for next iteration
- optimizeLevel++;
- if(autoMode && optimizeLevel > 3) {
- System.out.println("Skipping level 4 due to bad results in auto mode");
- sizeMet = true;
- } else if(optimizeLevel == 5) {
-
- } else {
- System.out.println("Increasing ghostscript optimisation level to " + optimizeLevel);
- }
- }
- }
-
-
-
- if (expectedOutputSize != null && autoMode) {
- long outputFileSize = Files.size(tempOutputFile);
- if (outputFileSize > expectedOutputSize) {
- try (PDDocument doc = PDDocument.load(new File(tempOutputFile.toString()))) {
- long previousFileSize = 0;
- double scaleFactor = 1.0;
- while (true) {
- for (PDPage page : doc.getPages()) {
- PDResources res = page.getResources();
-
- for (COSName name : res.getXObjectNames()) {
- PDXObject xobj = res.getXObject(name);
- if (xobj instanceof PDImageXObject) {
- PDImageXObject image = (PDImageXObject) xobj;
-
- // Get the image in BufferedImage format
- BufferedImage bufferedImage = image.getImage();
-
- // Calculate the new dimensions
- int newWidth = (int)(bufferedImage.getWidth() * scaleFactor);
- int newHeight = (int)(bufferedImage.getHeight() * scaleFactor);
-
- // If the new dimensions are zero, skip this iteration
- if (newWidth == 0 || newHeight == 0) {
- continue;
- }
-
- // Otherwise, proceed with the scaling
- Image scaledImage = bufferedImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
-
- // Convert the scaled image back to a BufferedImage
- BufferedImage scaledBufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
- scaledBufferedImage.getGraphics().drawImage(scaledImage, 0, 0, null);
-
- // Compress the scaled image
- ByteArrayOutputStream compressedImageStream = new ByteArrayOutputStream();
- ImageIO.write(scaledBufferedImage, "jpeg", compressedImageStream);
- byte[] imageBytes = compressedImageStream.toByteArray();
- compressedImageStream.close();
-
- // Convert compressed image back to PDImageXObject
- ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes);
- PDImageXObject compressedImage = PDImageXObject.createFromByteArray(doc, imageBytes, image.getCOSObject().toString());
-
- // Replace the image in the resources with the compressed version
- res.put(name, compressedImage);
- }
- }
- }
-
- // save the document to tempOutputFile again
- doc.save(tempOutputFile.toString());
-
- long currentSize = Files.size(tempOutputFile);
- // Check if the overall PDF size is still larger than expectedOutputSize
- if (currentSize > expectedOutputSize) {
- // Log the current file size and scaleFactor
-
- System.out.println("Current file size: " + FileUtils.byteCountToDisplaySize(currentSize));
- System.out.println("Current scale factor: " + scaleFactor);
-
- // The file is still too large, reduce scaleFactor and try again
- scaleFactor *= 0.9; // reduce scaleFactor by 10%
- // Avoid scaleFactor being too small, causing the image to shrink to 0
- if(scaleFactor < 0.2 || previousFileSize == currentSize){
- throw new RuntimeException("Could not reach the desired size without excessively degrading image quality, lowest size recommended is " + FileUtils.byteCountToDisplaySize(currentSize) + ", " + currentSize + " bytes");
- }
- previousFileSize = currentSize;
- } else {
- // The file is small enough, break the loop
- break;
- }
- }
-
- }
-
-
- }
- }
-
- // Read the optimized PDF file
- byte[] pdfBytes = Files.readAllBytes(tempOutputFile);
-
- // Check if optimized file is larger than the original
- if(pdfBytes.length > inputFileSize) {
- // Log the occurrence
- logger.warn("Optimized file is larger than the original. Returning the original file instead.");
-
- // Read the original file again
- pdfBytes = Files.readAllBytes(tempInputFile);
- }
-
- // Clean up the temporary files
- Files.delete(tempInputFile);
- Files.delete(tempOutputFile);
-
- // Return the optimized PDF as a response
- String outputFilename = inputFile.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_Optimized.pdf";
- return WebResponseUtils.bytesToWebResponse(pdfBytes, outputFilename);
- }
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/misc/ExtractImageScansController.java b/src/main/java/stirling/software/SPDF/controller/api/misc/ExtractImageScansController.java
deleted file mode 100644
index d5906970..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/misc/ExtractImageScansController.java
+++ /dev/null
@@ -1,153 +0,0 @@
-package stirling.software.SPDF.controller.api.misc;
-
-import java.awt.image.BufferedImage;
-import java.io.ByteArrayInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.StandardCopyOption;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.stream.Collectors;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipOutputStream;
-
-import javax.imageio.ImageIO;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.rendering.PDFRenderer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.http.MediaType;
-import org.springframework.http.ResponseEntity;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
-
-import io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.media.Content;
-import io.swagger.v3.oas.annotations.media.Schema;
-import io.swagger.v3.oas.annotations.parameters.RequestBody;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.misc.ExtractImageScansRequest;
-import stirling.software.SPDF.utils.ProcessExecutor;
-import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult;
-import stirling.software.SPDF.utils.WebResponseUtils;
-@RestController
-@RequestMapping("/api/v1/misc")
-@Tag(name = "Misc", description = "Miscellaneous APIs")
-public class ExtractImageScansController {
-
- private static final Logger logger = LoggerFactory.getLogger(ExtractImageScansController.class);
-
- @PostMapping(consumes = "multipart/form-data", value = "/extract-image-scans")
- @Operation(summary = "Extract image scans from an input file",
- description = "This endpoint extracts image scans from a given file based on certain parameters. Users can specify angle threshold, tolerance, minimum area, minimum contour area, and border size. Input:PDF Output:IMAGE/ZIP Type:SIMO")
- public ResponseEntity extractImageScans(
- @RequestBody(
- description = "Form data containing file and extraction parameters",
- required = true,
- content = @Content(
- mediaType = "multipart/form-data",
- schema = @Schema(implementation = ExtractImageScansRequest.class) // This should represent your form's structure
- )
- )
- ExtractImageScansRequest form) throws IOException, InterruptedException {
- String fileName = form.getFileInput().getOriginalFilename();
- String extension = fileName.substring(fileName.lastIndexOf(".") + 1);
-
- List images = new ArrayList<>();
-
- // Check if input file is a PDF
- if (extension.equalsIgnoreCase("pdf")) {
- // Load PDF document
- try (PDDocument document = PDDocument.load(new ByteArrayInputStream(form.getFileInput().getBytes()))) {
- PDFRenderer pdfRenderer = new PDFRenderer(document);
- int pageCount = document.getNumberOfPages();
- images = new ArrayList<>();
-
- // Create images of all pages
- for (int i = 0; i < pageCount; i++) {
- // Create temp file to save the image
- Path tempFile = Files.createTempFile("image_", ".png");
-
- // Render image and save as temp file
- BufferedImage image = pdfRenderer.renderImageWithDPI(i, 300);
- ImageIO.write(image, "png", tempFile.toFile());
-
- // Add temp file path to images list
- images.add(tempFile.toString());
- }
- }
- } else {
- Path tempInputFile = Files.createTempFile("input_", "." + extension);
- Files.copy(form.getFileInput().getInputStream(), tempInputFile, StandardCopyOption.REPLACE_EXISTING);
- // Add input file path to images list
- images.add(tempInputFile.toString());
- }
-
- List processedImageBytes = new ArrayList<>();
-
- // Process each image
- for (int i = 0; i < images.size(); i++) {
-
- Path tempDir = Files.createTempDirectory("openCV_output");
- List command = new ArrayList<>(Arrays.asList(
- "python3",
- "./scripts/split_photos.py",
- images.get(i),
- tempDir.toString(),
- "--angle_threshold", String.valueOf(form.getAngleThreshold()),
- "--tolerance", String.valueOf(form.getTolerance()),
- "--min_area", String.valueOf(form.getMinArea()),
- "--min_contour_area", String.valueOf(form.getMinContourArea()),
- "--border_size", String.valueOf(form.getBorderSize())
- ));
-
-
- // Run CLI command
- ProcessExecutorResult returnCode = ProcessExecutor.getInstance(ProcessExecutor.Processes.PYTHON_OPENCV).runCommandWithOutputHandling(command);
-
- // Read the output photos in temp directory
- List tempOutputFiles = Files.list(tempDir).sorted().collect(Collectors.toList());
- for (Path tempOutputFile : tempOutputFiles) {
- byte[] imageBytes = Files.readAllBytes(tempOutputFile);
- processedImageBytes.add(imageBytes);
- }
- // Clean up the temporary directory
- FileUtils.deleteDirectory(tempDir.toFile());
- }
-
- // Create zip file if multiple images
- if (processedImageBytes.size() > 1) {
- String outputZipFilename = fileName.replaceFirst("[.][^.]+$", "") + "_processed.zip";
- Path tempZipFile = Files.createTempFile("output_", ".zip");
-
- try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(tempZipFile.toFile()))) {
- // Add processed images to the zip
- for (int i = 0; i < processedImageBytes.size(); i++) {
- ZipEntry entry = new ZipEntry(fileName.replaceFirst("[.][^.]+$", "") + "_" + (i + 1) + ".png");
- zipOut.putNextEntry(entry);
- zipOut.write(processedImageBytes.get(i));
- zipOut.closeEntry();
- }
- }
-
- byte[] zipBytes = Files.readAllBytes(tempZipFile);
-
- // Clean up the temporary zip file
- Files.delete(tempZipFile);
-
- return WebResponseUtils.bytesToWebResponse(zipBytes, outputZipFilename, MediaType.APPLICATION_OCTET_STREAM);
- } else {
- // Return the processed image as a response
- byte[] imageBytes = processedImageBytes.get(0);
- return WebResponseUtils.bytesToWebResponse(imageBytes, fileName.replaceFirst("[.][^.]+$", "") + ".png", MediaType.IMAGE_PNG);
- }
-
- }
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/misc/ExtractImagesController.java b/src/main/java/stirling/software/SPDF/controller/api/misc/ExtractImagesController.java
deleted file mode 100644
index b24ac892..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/misc/ExtractImagesController.java
+++ /dev/null
@@ -1,119 +0,0 @@
-package stirling.software.SPDF.controller.api.misc;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.awt.Graphics2D;
-import java.awt.Image;
-import java.awt.image.BufferedImage;
-import java.awt.image.RenderedImage;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.util.zip.Deflater;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipOutputStream;
-
-import javax.imageio.ImageIO;
-
-import org.apache.pdfbox.cos.COSName;
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.PDPage;
-import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.PDFWithImageFormatRequest;
-import stirling.software.SPDF.utils.WebResponseUtils;
-@RestController
-@RequestMapping("/api/v1/misc")
-@Tag(name = "Misc", description = "Miscellaneous APIs")
-public class ExtractImagesController {
-
- private static final Logger logger = LoggerFactory.getLogger(ExtractImagesController.class);
-
- @PostMapping(consumes = "multipart/form-data", value = "/extract-images")
- @Operation(summary = "Extract images from a PDF file",
- description = "This endpoint extracts images from a given PDF file and returns them in a zip file. Users can specify the output image format. Input:PDF Output:IMAGE/ZIP Type:SIMO")
- public ResponseEntity extractImages(@ModelAttribute PDFWithImageFormatRequest request) throws IOException {
- MultipartFile file = request.getFileInput();
- String format = request.getFormat();
-
- System.out.println(System.currentTimeMillis() + "file=" + file.getName() + ", format=" + format);
- PDDocument document = PDDocument.load(file.getBytes());
-
- // Create ByteArrayOutputStream to write zip file to byte array
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
- // Create ZipOutputStream to create zip file
- ZipOutputStream zos = new ZipOutputStream(baos);
-
- // Set compression level
- zos.setLevel(Deflater.BEST_COMPRESSION);
-
- int imageIndex = 1;
- String filename = file.getOriginalFilename().replaceFirst("[.][^.]+$", "");
- int pageNum = 0;
- Set processedImages = new HashSet<>();
- // Iterate over each page
- for (PDPage page : document.getPages()) {
- ++pageNum;
- // Extract images from page
- for (COSName name : page.getResources().getXObjectNames()) {
- if (page.getResources().isImageXObject(name)) {
- PDImageXObject image = (PDImageXObject) page.getResources().getXObject(name);
- int imageHash = image.hashCode();
- if(processedImages.contains(imageHash)) {
- continue; // Skip already processed images
- }
- processedImages.add(imageHash);
-
- // Convert image to desired format
- RenderedImage renderedImage = image.getImage();
- BufferedImage bufferedImage = null;
- if (format.equalsIgnoreCase("png")) {
- bufferedImage = new BufferedImage(renderedImage.getWidth(), renderedImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
- } else if (format.equalsIgnoreCase("jpeg") || format.equalsIgnoreCase("jpg")) {
- bufferedImage = new BufferedImage(renderedImage.getWidth(), renderedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
- } else if (format.equalsIgnoreCase("gif")) {
- bufferedImage = new BufferedImage(renderedImage.getWidth(), renderedImage.getHeight(), BufferedImage.TYPE_BYTE_INDEXED);
- }
-
- // Write image to zip file
- String imageName = filename + "_" + imageIndex + " (Page " + pageNum + ")." + format;
- ZipEntry zipEntry = new ZipEntry(imageName);
- zos.putNextEntry(zipEntry);
-
- Graphics2D g = bufferedImage.createGraphics();
- g.drawImage((Image) renderedImage, 0, 0, null);
- g.dispose();
- // Write image bytes to zip file
- ByteArrayOutputStream imageBaos = new ByteArrayOutputStream();
- ImageIO.write(bufferedImage, format, imageBaos);
- zos.write(imageBaos.toByteArray());
-
- zos.closeEntry();
- imageIndex++;
- }
- }
- }
-
- // Close ZipOutputStream and PDDocument
- zos.close();
- document.close();
-
- // Create ByteArrayResource from byte array
- byte[] zipContents = baos.toByteArray();
-
- return WebResponseUtils.boasToWebResponse(baos, filename + "_extracted-images.zip", MediaType.APPLICATION_OCTET_STREAM);
- }
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/misc/FakeScanControllerWIP.java b/src/main/java/stirling/software/SPDF/controller/api/misc/FakeScanControllerWIP.java
deleted file mode 100644
index 68e026ab..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/misc/FakeScanControllerWIP.java
+++ /dev/null
@@ -1,150 +0,0 @@
-package stirling.software.SPDF.controller.api.misc;
-
-import java.awt.Color;
-import java.awt.geom.AffineTransform;
-import java.awt.image.AffineTransformOp;
-//Required for image manipulation
-import java.awt.image.BufferedImage;
-import java.awt.image.BufferedImageOp;
-import java.awt.image.ConvolveOp;
-import java.awt.image.Kernel;
-import java.awt.image.RescaleOp;
-import java.io.ByteArrayOutputStream;
-//Required for file input/output
-import java.io.File;
-import java.io.IOException;
-//Other required classes
-import java.util.Random;
-
-//Required for image input/output
-import javax.imageio.ImageIO;
-
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.PDPage;
-import org.apache.pdfbox.pdmodel.PDPageContentStream;
-import org.apache.pdfbox.pdmodel.common.PDRectangle;
-import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;
-import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
-import org.apache.pdfbox.rendering.ImageType;
-import org.apache.pdfbox.rendering.PDFRenderer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-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 io.swagger.v3.oas.annotations.Hidden;
-import io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.PDFFile;
-import stirling.software.SPDF.utils.WebResponseUtils;
-
-@RestController
-@RequestMapping("/api/v1/misc")
-@Tag(name = "Misc", description = "Miscellaneous APIs")
-public class FakeScanControllerWIP {
-
- private static final Logger logger = LoggerFactory.getLogger(FakeScanControllerWIP.class);
-
- //TODO
- @Hidden
- @PostMapping(consumes = "multipart/form-data", value = "/fakeScan")
- @Operation(
- summary = "Repair a PDF file",
- description = "This endpoint repairs a given PDF file by running Ghostscript command. The PDF is first saved to a temporary location, repaired, read back, and then returned as a response."
- )
- public ResponseEntity repairPdf(@ModelAttribute PDFFile request) throws IOException {
- MultipartFile inputFile = request.getFileInput();
-
- PDDocument document = PDDocument.load(inputFile.getBytes());
- PDFRenderer pdfRenderer = new PDFRenderer(document);
- for (int page = 0; page < document.getNumberOfPages(); ++page)
- {
- BufferedImage image = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB);
- ImageIO.write(image, "png", new File("scanned-" + (page+1) + ".png"));
- }
- document.close();
-
- // Constants
- int scannedness = 90; // Value between 0 and 100
- int dirtiness = 0; // Value between 0 and 100
-
- // Load the source image
- BufferedImage sourceImage = ImageIO.read(new File("scanned-1.png"));
-
- // Create the destination image
- BufferedImage destinationImage = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), sourceImage.getType());
-
- // Apply a brightness and contrast effect based on the "scanned-ness"
- float scaleFactor = 1.0f + (scannedness / 100.0f) * 0.5f; // Between 1.0 and 1.5
- float offset = scannedness * 1.5f; // Between 0 and 150
- BufferedImageOp op = new RescaleOp(scaleFactor, offset, null);
- op.filter(sourceImage, destinationImage);
-
- // Apply a rotation effect
- double rotationRequired = Math.toRadians((new Random().nextInt(3 - 1) + 1)); // Random angle between 1 and 3 degrees
- double locationX = destinationImage.getWidth() / 2;
- double locationY = destinationImage.getHeight() / 2;
- AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);
- AffineTransformOp rotateOp = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
- destinationImage = rotateOp.filter(destinationImage, null);
-
- // Apply a blur effect based on the "scanned-ness"
- float blurIntensity = scannedness / 100.0f * 0.2f; // Between 0.0 and 0.2
- float[] matrix = {
- blurIntensity, blurIntensity, blurIntensity,
- blurIntensity, blurIntensity, blurIntensity,
- blurIntensity, blurIntensity, blurIntensity
- };
- BufferedImageOp blurOp = new ConvolveOp(new Kernel(3, 3, matrix), ConvolveOp.EDGE_NO_OP, null);
- destinationImage = blurOp.filter(destinationImage, null);
-
- // Add noise to the image based on the "dirtiness"
- Random random = new Random();
- for (int y = 0; y < destinationImage.getHeight(); y++) {
- for (int x = 0; x < destinationImage.getWidth(); x++) {
- if (random.nextInt(100) < dirtiness) {
- // Change the pixel color to black randomly based on the "dirtiness"
- destinationImage.setRGB(x, y, Color.BLACK.getRGB());
- }
- }
- }
-
- // Save the image
- ImageIO.write(destinationImage, "PNG", new File("scanned-1.png"));
-
-
-
-
-
-
-
- PDDocument documentOut = new PDDocument();
- for (int page = 1; page <= document.getNumberOfPages(); ++page)
- {
- BufferedImage bim = ImageIO.read(new File("scanned-" + page + ".png"));
-
- // Adjust the dimensions of the page
- PDPage pdPage = new PDPage(new PDRectangle(bim.getWidth() - 1, bim.getHeight() - 1));
- documentOut.addPage(pdPage);
-
- PDImageXObject pdImage = LosslessFactory.createFromImage(documentOut, bim);
- PDPageContentStream contentStream = new PDPageContentStream(documentOut, pdPage);
-
- // Draw the image with a slight offset and enlarged dimensions
- contentStream.drawImage(pdImage, -1, -1, bim.getWidth() + 2, bim.getHeight() + 2);
- contentStream.close();
- }
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- documentOut.save(baos);
- documentOut.close();
-
- // Return the optimized PDF as a response
- String outputFilename = inputFile.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_scanned.pdf";
- return WebResponseUtils.boasToWebResponse(baos, outputFilename);
- }
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/misc/MetadataController.java b/src/main/java/stirling/software/SPDF/controller/api/misc/MetadataController.java
deleted file mode 100644
index 027c6240..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/misc/MetadataController.java
+++ /dev/null
@@ -1,153 +0,0 @@
-package stirling.software.SPDF.controller.api.misc;
-
-import java.io.IOException;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.apache.pdfbox.cos.COSName;
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.PDDocumentInformation;
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.misc.MetadataRequest;
-import stirling.software.SPDF.utils.WebResponseUtils;
-
-@RestController
-@RequestMapping("/api/v1/misc")
-@Tag(name = "Misc", description = "Miscellaneous APIs")
-public class MetadataController {
-
-
- private String checkUndefined(String entry) {
- // Check if the string is "undefined"
- if ("undefined".equals(entry)) {
- // Return null if it is
- return null;
- }
- // Return the original string if it's not "undefined"
- return entry;
-
- }
-
- @PostMapping(consumes = "multipart/form-data", value = "/update-metadata")
- @Operation(summary = "Update metadata of a PDF file",
- description = "This endpoint allows you to update the metadata of a given PDF file. You can add, modify, or delete standard and custom metadata fields. Input:PDF Output:PDF Type:SISO")
- public ResponseEntity metadata(@ModelAttribute MetadataRequest request) throws IOException {
-
- // Extract PDF file from the request object
- MultipartFile pdfFile = request.getFileInput();
-
- // Extract metadata information
- Boolean deleteAll = request.isDeleteAll();
- String author = request.getAuthor();
- String creationDate = request.getCreationDate();
- String creator = request.getCreator();
- String keywords = request.getKeywords();
- String modificationDate = request.getModificationDate();
- String producer = request.getProducer();
- String subject = request.getSubject();
- String title = request.getTitle();
- String trapped = request.getTrapped();
-
- // Extract additional custom parameters
- Map allRequestParams = request.getAllRequestParams();
- if(allRequestParams == null) {
- allRequestParams = new java.util.HashMap();
- }
- // Load the PDF file into a PDDocument
- PDDocument document = PDDocument.load(pdfFile.getBytes());
-
- // 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);
-
- // 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 entry : allRequestParams.entrySet()) {
- String key = entry.getKey();
- // Check if the key is a standard metadata key
- if (!key.equalsIgnoreCase("Author") && !key.equalsIgnoreCase("CreationDate") && !key.equalsIgnoreCase("Creator") && !key.equalsIgnoreCase("Keywords")
- && !key.equalsIgnoreCase("modificationDate") && !key.equalsIgnoreCase("Producer") && !key.equalsIgnoreCase("Subject") && !key.equalsIgnoreCase("Title")
- && !key.equalsIgnoreCase("Trapped") && !key.contains("customKey") && !key.contains("customValue")) {
- info.setCustomMetadataValue(key, entry.getValue());
- } else if (key.contains("customKey")) {
- int number = Integer.parseInt(key.replaceAll("\\D", ""));
- String customKey = entry.getValue();
- String customValue = allRequestParams.get("customValue" + number);
- info.setCustomMetadataValue(customKey, customValue);
- }
- }
- }
- if (creationDate != null && creationDate.length() > 0) {
- Calendar creationDateCal = Calendar.getInstance();
- try {
- creationDateCal.setTime(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(creationDate));
- } catch (ParseException e) {
- e.printStackTrace();
- }
- info.setCreationDate(creationDateCal);
- } else {
- info.setCreationDate(null);
- }
- if (modificationDate != null && modificationDate.length() > 0) {
- Calendar modificationDateCal = Calendar.getInstance();
- try {
- modificationDateCal.setTime(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(modificationDate));
- } catch (ParseException e) {
- e.printStackTrace();
- }
- info.setModificationDate(modificationDateCal);
- } else {
- info.setModificationDate(null);
- }
- 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, pdfFile.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_metadata.pdf");
- }
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/misc/OCRController.java b/src/main/java/stirling/software/SPDF/controller/api/misc/OCRController.java
deleted file mode 100644
index 5ee06c19..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/misc/OCRController.java
+++ /dev/null
@@ -1,189 +0,0 @@
-package stirling.software.SPDF.controller.api.misc;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.StandardCopyOption;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.stream.Collectors;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipOutputStream;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.misc.ProcessPdfWithOcrRequest;
-import stirling.software.SPDF.utils.ProcessExecutor;
-import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult;
-import stirling.software.SPDF.utils.WebResponseUtils;
-
-@RestController
-@RequestMapping("/api/v1/misc")
-@Tag(name = "Misc", description = "Miscellaneous APIs")
-public class OCRController {
-
- private static final Logger logger = LoggerFactory.getLogger(OCRController.class);
-
- public List getAvailableTesseractLanguages() {
- String tessdataDir = "/usr/share/tesseract-ocr/4.00/tessdata";
- File[] files = new File(tessdataDir).listFiles();
- if (files == null) {
- return Collections.emptyList();
- }
- return Arrays.stream(files).filter(file -> file.getName().endsWith(".traineddata")).map(file -> file.getName().replace(".traineddata", ""))
- .filter(lang -> !lang.equalsIgnoreCase("osd")).collect(Collectors.toList());
- }
-
- @PostMapping(consumes = "multipart/form-data", value = "/ocr-pdf")
- @Operation(summary = "Process a PDF file with OCR",
- description = "This endpoint processes a PDF file using OCR (Optical Character Recognition). Users can specify languages, sidecar, deskew, clean, cleanFinal, ocrType, ocrRenderType, and removeImagesAfter options. Input:PDF Output:PDF Type:SI-Conditional")
- public ResponseEntity processPdfWithOCR(@ModelAttribute ProcessPdfWithOcrRequest request) throws IOException, InterruptedException {
- MultipartFile inputFile = request.getFileInput();
- List selectedLanguages = request.getLanguages();
- Boolean sidecar = request.isSidecar();
- Boolean deskew = request.isDeskew();
- Boolean clean = request.isClean();
- Boolean cleanFinal = request.isCleanFinal();
- String ocrType = request.getOcrType();
- String ocrRenderType = request.getOcrRenderType();
- Boolean removeImagesAfter = request.isRemoveImagesAfter();
- // --output-type pdfa
- if (selectedLanguages == null || selectedLanguages.isEmpty()) {
- throw new IOException("Please select at least one language.");
- }
-
- if(!ocrRenderType.equals("hocr") && !ocrRenderType.equals("sandwich")) {
- throw new IOException("ocrRenderType wrong");
- }
-
- // Get available Tesseract languages
- List availableLanguages = getAvailableTesseractLanguages();
-
- // Validate selected languages
- selectedLanguages = selectedLanguages.stream().filter(availableLanguages::contains).toList();
-
- if (selectedLanguages.isEmpty()) {
- throw new IOException("None of the selected languages are valid.");
- }
- // Save the uploaded file to a temporary location
- Path tempInputFile = Files.createTempFile("input_", ".pdf");
- Files.copy(inputFile.getInputStream(), tempInputFile, StandardCopyOption.REPLACE_EXISTING);
-
- // Prepare the output file path
- Path tempOutputFile = Files.createTempFile("output_", ".pdf");
-
- // Prepare the output file path
- Path sidecarTextPath = null;
-
- // Run OCR Command
- String languageOption = String.join("+", selectedLanguages);
-
-
- List command = new ArrayList<>(Arrays.asList("ocrmypdf", "--verbose", "2", "--output-type", "pdf", "--pdf-renderer" , ocrRenderType));
-
- if (sidecar != null && sidecar) {
- sidecarTextPath = Files.createTempFile("sidecar", ".txt");
- command.add("--sidecar");
- command.add(sidecarTextPath.toString());
- }
-
- if (deskew != null && deskew) {
- command.add("--deskew");
- }
- if (clean != null && clean) {
- command.add("--clean");
- }
- if (cleanFinal != null && cleanFinal) {
- command.add("--clean-final");
- }
- if (ocrType != null && !ocrType.equals("")) {
- if ("skip-text".equals(ocrType)) {
- command.add("--skip-text");
- } else if ("force-ocr".equals(ocrType)) {
- command.add("--force-ocr");
- } else if ("Normal".equals(ocrType)) {
-
- }
- }
-
- command.addAll(Arrays.asList("--language", languageOption, tempInputFile.toString(), tempOutputFile.toString()));
-
- // Run CLI command
- ProcessExecutorResult result = ProcessExecutor.getInstance(ProcessExecutor.Processes.OCR_MY_PDF).runCommandWithOutputHandling(command);
- if(result.getRc() != 0 && result.getMessages().contains("multiprocessing/synchronize.py") && result.getMessages().contains("OSError: [Errno 38] Function not implemented")) {
- command.add("--jobs");
- command.add("1");
- result = ProcessExecutor.getInstance(ProcessExecutor.Processes.OCR_MY_PDF).runCommandWithOutputHandling(command);
- }
-
-
-
-
- // Remove images from the OCR processed PDF if the flag is set to true
- if (removeImagesAfter != null && removeImagesAfter) {
- Path tempPdfWithoutImages = Files.createTempFile("output_", "_no_images.pdf");
-
- List gsCommand = Arrays.asList("gs", "-sDEVICE=pdfwrite", "-dFILTERIMAGE", "-o", tempPdfWithoutImages.toString(), tempOutputFile.toString());
-
- ProcessExecutor.getInstance(ProcessExecutor.Processes.GHOSTSCRIPT).runCommandWithOutputHandling(gsCommand);
- tempOutputFile = tempPdfWithoutImages;
- }
- // Read the OCR processed PDF file
- byte[] pdfBytes = Files.readAllBytes(tempOutputFile);
- // Clean up the temporary files
- Files.delete(tempInputFile);
-
- // Return the OCR processed PDF as a response
- String outputFilename = inputFile.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_OCR.pdf";
-
- if (sidecar != null && sidecar) {
- // Create a zip file containing both the PDF and the text file
- String outputZipFilename = inputFile.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_OCR.zip";
- Path tempZipFile = Files.createTempFile("output_", ".zip");
-
- try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(tempZipFile.toFile()))) {
- // Add PDF file to the zip
- ZipEntry pdfEntry = new ZipEntry(outputFilename);
- zipOut.putNextEntry(pdfEntry);
- Files.copy(tempOutputFile, zipOut);
- zipOut.closeEntry();
-
- // Add text file to the zip
- ZipEntry txtEntry = new ZipEntry(outputFilename.replace(".pdf", ".txt"));
- zipOut.putNextEntry(txtEntry);
- Files.copy(sidecarTextPath, zipOut);
- zipOut.closeEntry();
- }
-
- byte[] zipBytes = Files.readAllBytes(tempZipFile);
-
- // Clean up the temporary zip file
- Files.delete(tempZipFile);
- Files.delete(tempOutputFile);
- Files.delete(sidecarTextPath);
-
- // Return the zip file containing both the PDF and the text file
- return WebResponseUtils.bytesToWebResponse(zipBytes, outputZipFilename, MediaType.APPLICATION_OCTET_STREAM);
- } else {
- // Return the OCR processed PDF as a response
- Files.delete(tempOutputFile);
- return WebResponseUtils.bytesToWebResponse(pdfBytes, outputFilename);
- }
-
- }
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/misc/OverlayImageController.java b/src/main/java/stirling/software/SPDF/controller/api/misc/OverlayImageController.java
deleted file mode 100644
index e28f7535..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/misc/OverlayImageController.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package stirling.software.SPDF.controller.api.misc;
-
-import java.io.IOException;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.http.HttpStatus;
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.misc.OverlayImageRequest;
-import stirling.software.SPDF.utils.PdfUtils;
-import stirling.software.SPDF.utils.WebResponseUtils;
-
-@RestController
-@RequestMapping("/api/v1/misc")
-@Tag(name = "Misc", description = "Miscellaneous APIs")
-public class OverlayImageController {
-
- private static final Logger logger = LoggerFactory.getLogger(OverlayImageController.class);
-
- @PostMapping(consumes = "multipart/form-data", value = "/add-image")
- @Operation(
- summary = "Overlay image onto a PDF file",
- description = "This endpoint overlays an image onto a PDF file at the specified coordinates. The image can be overlaid on every page of the PDF if specified. Input:PDF/IMAGE Output:PDF Type:MF-SISO"
- )
- public ResponseEntity overlayImage(@ModelAttribute OverlayImageRequest request) {
- MultipartFile pdfFile = request.getFileInput();
- MultipartFile imageFile = request.getImageFile();
- float x = request.getX();
- float y = request.getY();
- boolean everyPage = request.isEveryPage();
- try {
- byte[] pdfBytes = pdfFile.getBytes();
- byte[] imageBytes = imageFile.getBytes();
- byte[] result = PdfUtils.overlayImage(pdfBytes, imageBytes, x, y, everyPage);
-
- return WebResponseUtils.bytesToWebResponse(result, pdfFile.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_overlayed.pdf");
- } catch (IOException e) {
- logger.error("Failed to add image to PDF", e);
- return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
- }
- }
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/misc/PageNumbersController.java b/src/main/java/stirling/software/SPDF/controller/api/misc/PageNumbersController.java
deleted file mode 100644
index 61a1ec97..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/misc/PageNumbersController.java
+++ /dev/null
@@ -1,135 +0,0 @@
-package stirling.software.SPDF.controller.api.misc;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.util.List;
-
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.PDPage;
-import org.apache.pdfbox.pdmodel.PDPageContentStream;
-import org.apache.pdfbox.pdmodel.common.PDRectangle;
-import org.apache.pdfbox.pdmodel.font.PDType1Font;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.misc.AddPageNumbersRequest;
-import stirling.software.SPDF.utils.GeneralUtils;
-import stirling.software.SPDF.utils.WebResponseUtils;
-
-@RestController
-@RequestMapping("/api/v1/misc")
-@Tag(name = "Misc", description = "Miscellaneous APIs")
-public class PageNumbersController {
-
- private static final Logger logger = LoggerFactory.getLogger(PageNumbersController.class);
-
- @PostMapping(value = "/add-page-numbers", consumes = "multipart/form-data")
- @Operation(summary = "Add page numbers to a PDF document", description = "This operation takes an input PDF file and adds page numbers to it. Input:PDF Output:PDF Type:SISO")
- public ResponseEntity addPageNumbers(@ModelAttribute AddPageNumbersRequest request) throws IOException {
- MultipartFile file = request.getFileInput();
- String customMargin = request.getCustomMargin();
- int position = request.getPosition();
- int startingNumber = request.getStartingNumber();
- String pagesToNumber = request.getPagesToNumber();
- String customText = request.getCustomText();
- int pageNumber = startingNumber;
- byte[] fileBytes = file.getBytes();
- PDDocument document = PDDocument.load(fileBytes);
-
- float marginFactor;
- switch (customMargin.toLowerCase()) {
- case "small":
- marginFactor = 0.02f;
- break;
- case "medium":
- marginFactor = 0.035f;
- break;
- case "large":
- marginFactor = 0.05f;
- break;
- case "x-large":
- marginFactor = 0.075f;
- break;
-
-
- default:
- marginFactor = 0.035f;
- break;
- }
-
- float fontSize = 12.0f;
- PDType1Font font = PDType1Font.HELVETICA;
- if(pagesToNumber == null || pagesToNumber.length() == 0) {
- pagesToNumber = "all";
- }
- if(customText == null || customText.length() == 0) {
- customText = "{n}";
- }
- List pagesToNumberList = GeneralUtils.parsePageList(pagesToNumber.split(","), document.getNumberOfPages());
-
- for (int i : pagesToNumberList) {
- PDPage page = document.getPage(i);
- PDRectangle pageSize = page.getMediaBox();
-
- String text = customText != null ? customText.replace("{n}", String.valueOf(pageNumber)).replace("{total}", String.valueOf(document.getNumberOfPages())).replace("{filename}", file.getOriginalFilename().replaceFirst("[.][^.]+$", "")) : String.valueOf(pageNumber);
-
- float x, y;
-
- int xGroup = (position - 1) % 3;
- int yGroup = 2 - (position - 1) / 3;
-
- switch (xGroup) {
- case 0: // left
- x = pageSize.getLowerLeftX() + marginFactor * pageSize.getWidth();
- break;
- case 1: // center
- x = pageSize.getLowerLeftX() + (pageSize.getWidth() / 2);
- break;
- default: // right
- x = pageSize.getUpperRightX() - marginFactor * pageSize.getWidth();
- break;
- }
-
- switch (yGroup) {
- case 0: // bottom
- y = pageSize.getLowerLeftY() + marginFactor * pageSize.getHeight();
- break;
- case 1: // middle
- y = pageSize.getLowerLeftY() + (pageSize.getHeight() / 2);
- break;
- default: // top
- y = pageSize.getUpperRightY() - marginFactor * pageSize.getHeight();
- break;
- }
-
- PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true);
- contentStream.beginText();
- contentStream.setFont(font, fontSize);
- contentStream.newLineAtOffset(x, y);
- contentStream.showText(text);
- contentStream.endText();
- contentStream.close();
-
- pageNumber++;
- }
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- document.save(baos);
- document.close();
-
- return WebResponseUtils.bytesToWebResponse(baos.toByteArray(), file.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_numbersAdded.pdf", MediaType.APPLICATION_PDF);
-
- }
-
-
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/misc/RepairController.java b/src/main/java/stirling/software/SPDF/controller/api/misc/RepairController.java
deleted file mode 100644
index f9ae541d..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/misc/RepairController.java
+++ /dev/null
@@ -1,68 +0,0 @@
-package stirling.software.SPDF.controller.api.misc;
-
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.PDFFile;
-import stirling.software.SPDF.utils.ProcessExecutor;
-import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult;
-import stirling.software.SPDF.utils.WebResponseUtils;
-
-@RestController
-@RequestMapping("/api/v1/misc")
-@Tag(name = "Misc", description = "Miscellaneous APIs")
-public class RepairController {
-
- private static final Logger logger = LoggerFactory.getLogger(RepairController.class);
-
- @PostMapping(consumes = "multipart/form-data", value = "/repair")
- @Operation(
- summary = "Repair a PDF file",
- description = "This endpoint repairs a given PDF file by running Ghostscript command. The PDF is first saved to a temporary location, repaired, read back, and then returned as a response. Input:PDF Output:PDF Type:SISO"
- )
- public ResponseEntity repairPdf(@ModelAttribute PDFFile request) throws IOException, InterruptedException {
- MultipartFile inputFile = request.getFileInput();
- // Save the uploaded file to a temporary location
- Path tempInputFile = Files.createTempFile("input_", ".pdf");
- inputFile.transferTo(tempInputFile.toFile());
-
- // Prepare the output file path
- Path tempOutputFile = Files.createTempFile("output_", ".pdf");
-
- List command = new ArrayList<>();
- command.add("gs");
- command.add("-o");
- command.add(tempOutputFile.toString());
- command.add("-sDEVICE=pdfwrite");
- command.add(tempInputFile.toString());
-
-
- ProcessExecutorResult returnCode = ProcessExecutor.getInstance(ProcessExecutor.Processes.GHOSTSCRIPT).runCommandWithOutputHandling(command);
-
- // Read the optimized PDF file
- byte[] pdfBytes = Files.readAllBytes(tempOutputFile);
-
- // Clean up the temporary files
- Files.delete(tempInputFile);
- Files.delete(tempOutputFile);
-
- // Return the optimized PDF as a response
- String outputFilename = inputFile.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_repaired.pdf";
- return WebResponseUtils.bytesToWebResponse(pdfBytes, outputFilename);
- }
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/misc/ShowJavascript.java b/src/main/java/stirling/software/SPDF/controller/api/misc/ShowJavascript.java
deleted file mode 100644
index 27431346..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/misc/ShowJavascript.java
+++ /dev/null
@@ -1,61 +0,0 @@
-package stirling.software.SPDF.controller.api.misc;
-
-import java.nio.charset.StandardCharsets;
-import java.util.Map;
-
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.common.PDNameTreeNode;
-import org.apache.pdfbox.pdmodel.interactive.action.PDActionJavaScript;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-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 io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.PDFFile;
-import stirling.software.SPDF.utils.WebResponseUtils;
-@RestController
-@RequestMapping("/api/v1/misc")
-@Tag(name = "Misc", description = "Miscellaneous APIs")
-public class ShowJavascript {
-
- private static final Logger logger = LoggerFactory.getLogger(ShowJavascript.class);
- @PostMapping(consumes = "multipart/form-data", value = "/show-javascript")
- public ResponseEntity extractHeader(@ModelAttribute PDFFile request) throws Exception {
- MultipartFile inputFile = request.getFileInput();
- String script = "";
-
- try (PDDocument document = PDDocument.load(inputFile.getInputStream())) {
-
- if(document.getDocumentCatalog() != null && document.getDocumentCatalog().getNames() != null) {
- PDNameTreeNode jsTree = document.getDocumentCatalog().getNames().getJavaScript();
-
- if (jsTree != null) {
- Map jsEntries = jsTree.getNames();
-
- for (Map.Entry entry : jsEntries.entrySet()) {
- String name = entry.getKey();
- PDActionJavaScript jsAction = entry.getValue();
- String jsCodeStr = jsAction.getAction();
-
- script += "// File: " + inputFile.getOriginalFilename() + ", Script: " + name + "\n" + jsCodeStr + "\n";
- }
- }
- }
-
- if (script.isEmpty()) {
- script = "PDF '" + inputFile.getOriginalFilename() + "' does not contain Javascript";
- }
-
- return WebResponseUtils.bytesToWebResponse(script.getBytes(StandardCharsets.UTF_8), inputFile.getOriginalFilename() + ".js");
- }
- }
-
-
-
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/pipeline/PipelineController.java b/src/main/java/stirling/software/SPDF/controller/api/pipeline/PipelineController.java
deleted file mode 100644
index c12fe724..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/pipeline/PipelineController.java
+++ /dev/null
@@ -1,524 +0,0 @@
-package stirling.software.SPDF.controller.api.pipeline;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.time.LocalDate;
-import java.time.LocalTime;
-import java.time.format.DateTimeFormatter;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.stream.Stream;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipInputStream;
-import java.util.zip.ZipOutputStream;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.core.io.ByteArrayResource;
-import org.springframework.core.io.Resource;
-import org.springframework.http.HttpEntity;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.HttpMethod;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.MediaType;
-import org.springframework.http.ResponseEntity;
-import org.springframework.scheduling.annotation.Scheduled;
-import org.springframework.util.LinkedMultiValueMap;
-import org.springframework.util.MultiValueMap;
-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.client.RestTemplate;
-import org.springframework.web.multipart.MultipartFile;
-
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.ApplicationProperties;
-import stirling.software.SPDF.model.PipelineConfig;
-import stirling.software.SPDF.model.PipelineOperation;
-import stirling.software.SPDF.model.api.HandleDataRequest;
-import stirling.software.SPDF.utils.WebResponseUtils;
-
-@RestController
-@RequestMapping("/api/v1/pipeline")
-@Tag(name = "Pipeline", description = "Pipeline APIs")
-public class PipelineController {
-
- private static final Logger logger = LoggerFactory.getLogger(PipelineController.class);
- @Autowired
- private ObjectMapper objectMapper;
-
- final String jsonFileName = "pipelineConfig.json";
- final String watchedFoldersDir = "./pipeline/watchedFolders/";
- final String finishedFoldersDir = "./pipeline/finishedFolders/";
-
- @Scheduled(fixedRate = 25000)
- public void scanFolders() {
- logger.info("Scanning folders...");
- Path watchedFolderPath = Paths.get(watchedFoldersDir);
- if (!Files.exists(watchedFolderPath)) {
- try {
- Files.createDirectories(watchedFolderPath);
- logger.info("Created directory: {}", watchedFolderPath);
- } catch (IOException e) {
- logger.error("Error creating directory: {}", watchedFolderPath, e);
- return;
- }
- }
- try (Stream paths = Files.walk(watchedFolderPath)) {
- paths.filter(Files::isDirectory).forEach(t -> {
- try {
- if (!t.equals(watchedFolderPath) && !t.endsWith("processing")) {
- handleDirectory(t);
- }
- } catch (Exception e) {
- logger.error("Error handling directory: {}", t, e);
- }
- });
- } catch (Exception e) {
- logger.error("Error walking through directory: {}", watchedFolderPath, e);
- }
- }
-
- @Autowired
- ApplicationProperties applicationProperties;
-
-
- private void handleDirectory(Path dir) throws Exception {
- logger.info("Handling directory: {}", dir);
- Path jsonFile = dir.resolve(jsonFileName);
- Path processingDir = dir.resolve("processing"); // Directory to move files during processing
- if (!Files.exists(processingDir)) {
- Files.createDirectory(processingDir);
- logger.info("Created processing directory: {}", processingDir);
- }
-
- if (Files.exists(jsonFile)) {
- // Read JSON file
- String jsonString;
- try {
- jsonString = new String(Files.readAllBytes(jsonFile));
- logger.info("Read JSON file: {}", jsonFile);
- } catch (IOException e) {
- logger.error("Error reading JSON file: {}", jsonFile, e);
- return;
- }
-
- // Decode JSON to PipelineConfig
- PipelineConfig config;
- try {
- config = objectMapper.readValue(jsonString, PipelineConfig.class);
- // Assuming your PipelineConfig class has getters for all necessary fields, you
- // can perform checks here
- if (config.getOperations() == null || config.getOutputDir() == null || config.getName() == null) {
- throw new IOException("Invalid JSON format");
- }
- } catch (IOException e) {
- logger.error("Error parsing PipelineConfig: {}", jsonString, e);
- return;
- }
-
- // For each operation in the pipeline
- for (PipelineOperation operation : config.getOperations()) {
- // Collect all files based on fileInput
- File[] files;
- String fileInput = (String) operation.getParameters().get("fileInput");
- if ("automated".equals(fileInput)) {
- // If fileInput is "automated", process all files in the directory
- try (Stream paths = Files.list(dir)) {
- files = paths
- .filter(path -> !Files.isDirectory(path)) // exclude directories
- .filter(path -> !path.equals(jsonFile)) // exclude jsonFile
- .map(Path::toFile)
- .toArray(File[]::new);
-
- } catch (IOException e) {
- e.printStackTrace();
- return;
- }
- } else {
- // If fileInput contains a path, process only this file
- files = new File[] { new File(fileInput) };
- }
-
- // Prepare the files for processing
- List filesToProcess = new ArrayList<>();
- for (File file : files) {
- logger.info(file.getName());
- logger.info("{} to {}",file.toPath(), processingDir.resolve(file.getName()));
- Files.move(file.toPath(), processingDir.resolve(file.getName()));
- filesToProcess.add(processingDir.resolve(file.getName()).toFile());
- }
-
- // Process the files
- try {
- List resources = handleFiles(filesToProcess.toArray(new File[0]), jsonString);
-
- if(resources == null) {
- return;
- }
- // Move resultant files and rename them as per config in JSON file
- for (Resource resource : resources) {
- String resourceName = resource.getFilename();
- String baseName = resourceName.substring(0, resourceName.lastIndexOf("."));
- String extension = resourceName.substring(resourceName.lastIndexOf(".")+1);
-
- String outputFileName = config.getOutputPattern().replace("{filename}", baseName);
-
- outputFileName = outputFileName.replace("{pipelineName}", config.getName());
- DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
- outputFileName = outputFileName.replace("{date}", LocalDate.now().format(dateFormatter));
- DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HHmmss");
- outputFileName = outputFileName.replace("{time}", LocalTime.now().format(timeFormatter));
-
- outputFileName += "." + extension;
- // {filename} {folder} {date} {tmime} {pipeline}
- String outputDir = config.getOutputDir();
-
- String outputFolder = applicationProperties.getAutoPipeline().getOutputFolder();
-
- if (outputFolder == null || outputFolder.isEmpty()) {
- // If the environment variable is not set, use the default value
- outputFolder = finishedFoldersDir;
- }
- logger.info("outputDir 0={}", outputDir);
- // Replace the placeholders in the outputDir string
- outputDir = outputDir.replace("{outputFolder}", outputFolder);
- outputDir = outputDir.replace("{folderName}", dir.toString());
- logger.info("outputDir 1={}", outputDir);
- outputDir = outputDir.replace("\\watchedFolders", "");
- outputDir = outputDir.replace("//watchedFolders", "");
- outputDir = outputDir.replace("\\\\watchedFolders", "");
- outputDir = outputDir.replace("/watchedFolders", "");
-
- Path outputPath;
- logger.info("outputDir 2={}", outputDir);
- if (Paths.get(outputDir).isAbsolute()) {
- // If it's an absolute path, use it directly
- outputPath = Paths.get(outputDir);
- } else {
- // If it's a relative path, make it relative to the current working directory
- outputPath = Paths.get(".", outputDir);
- }
-
- logger.info("outputPath={}", outputPath);
-
- if (!Files.exists(outputPath)) {
- try {
- Files.createDirectories(outputPath);
- logger.info("Created directory: {}", outputPath);
- } catch (IOException e) {
- logger.error("Error creating directory: {}", outputPath, e);
- return;
- }
- }
- logger.info("outputPath {}", outputPath);
- logger.info("outputPath.resolve(outputFileName).toString() {}", outputPath.resolve(outputFileName).toString());
- File newFile = new File(outputPath.resolve(outputFileName).toString());
- OutputStream os = new FileOutputStream(newFile);
- os.write(((ByteArrayResource)resource).getByteArray());
- os.close();
- logger.info("made {}", outputPath.resolve(outputFileName));
- }
-
- // If successful, delete the original files
- for (File file : filesToProcess) {
- Files.deleteIfExists(processingDir.resolve(file.getName()));
- }
- } catch (Exception e) {
- // If an error occurs, move the original files back
- for (File file : filesToProcess) {
- Files.move(processingDir.resolve(file.getName()), file.toPath());
- }
- throw e;
- }
- }
- }
- }
-
- List processFiles(List outputFiles, String jsonString) throws Exception {
-
- ObjectMapper mapper = new ObjectMapper();
- JsonNode jsonNode = mapper.readTree(jsonString);
-
- JsonNode pipelineNode = jsonNode.get("pipeline");
- logger.info("Running pipelineNode: {}", pipelineNode);
- ByteArrayOutputStream logStream = new ByteArrayOutputStream();
- PrintStream logPrintStream = new PrintStream(logStream);
-
- boolean hasErrors = false;
-
- for (JsonNode operationNode : pipelineNode) {
- String operation = operationNode.get("operation").asText();
- logger.info("Running operation: {}", operation);
- JsonNode parametersNode = operationNode.get("parameters");
- String inputFileExtension = "";
- if (operationNode.has("inputFileType")) {
- inputFileExtension = operationNode.get("inputFileType").asText();
- } else {
- inputFileExtension = ".pdf";
- }
-
- List newOutputFiles = new ArrayList<>();
- boolean hasInputFileType = false;
-
- for (Resource file : outputFiles) {
- if (file.getFilename().endsWith(inputFileExtension)) {
- hasInputFileType = true;
- MultiValueMap body = new LinkedMultiValueMap<>();
- body.add("fileInput", file);
-
- Iterator> parameters = parametersNode.fields();
- while (parameters.hasNext()) {
- Map.Entry parameter = parameters.next();
- body.add(parameter.getKey(), parameter.getValue().asText());
- }
-
- HttpHeaders headers = new HttpHeaders();
- headers.setContentType(MediaType.MULTIPART_FORM_DATA);
-
- HttpEntity> entity = new HttpEntity<>(body, headers);
-
- RestTemplate restTemplate = new RestTemplate();
- String url = "http://localhost:8080/" + operation;
-
- ResponseEntity response = restTemplate.exchange(url, HttpMethod.POST, entity, byte[].class);
-
- // If the operation is filter and the response body is null or empty, skip this file
- if (operation.startsWith("filter-") && (response.getBody() == null || response.getBody().length == 0)) {
- logger.info("Skipping file due to failing {}", operation);
- continue;
- }
-
- if (!response.getStatusCode().equals(HttpStatus.OK)) {
- logPrintStream.println("Error: " + response.getBody());
- hasErrors = true;
- continue;
- }
-
-
- // Define filename
- String filename;
- if ("auto-rename".equals(operation)) {
- // If the operation is "auto-rename", generate a new filename.
- // This is a simple example of generating a filename using current timestamp.
- // Modify as per your needs.
- filename = "file_" + System.currentTimeMillis();
- } else {
- // Otherwise, keep the original filename.
- filename = file.getFilename();
- }
-
- // Check if the response body is a zip file
- if (isZip(response.getBody())) {
- // Unzip the file and add all the files to the new output files
- newOutputFiles.addAll(unzip(response.getBody()));
- } else {
- Resource outputResource = new ByteArrayResource(response.getBody()) {
- @Override
- public String getFilename() {
- return filename;
- }
- };
- newOutputFiles.add(outputResource);
- }
- }
-
- if (!hasInputFileType) {
- logPrintStream.println(
- "No files with extension " + inputFileExtension + " found for operation " + operation);
- hasErrors = true;
- }
-
- outputFiles = newOutputFiles;
- }
- logPrintStream.close();
-
- }
- if (hasErrors) {
- logger.error("Errors occurred during processing. Log: {}", logStream.toString());
- }
- return outputFiles;
- }
-
- List handleFiles(File[] files, String jsonString) throws Exception {
- if(files == null || files.length == 0) {
- logger.info("No files");
- return null;
- }
-
- logger.info("Handling files: {} files, with JSON string of length: {}", files.length, jsonString.length());
-
- ObjectMapper mapper = new ObjectMapper();
- JsonNode jsonNode = mapper.readTree(jsonString);
-
- JsonNode pipelineNode = jsonNode.get("pipeline");
-
- boolean hasErrors = false;
- List outputFiles = new ArrayList<>();
-
- for (File file : files) {
- Path path = Paths.get(file.getAbsolutePath());
- System.out.println("Reading file: " + path); // debug statement
-
- if (Files.exists(path)) {
- Resource fileResource = new ByteArrayResource(Files.readAllBytes(path)) {
- @Override
- public String getFilename() {
- return file.getName();
- }
- };
- outputFiles.add(fileResource);
- } else {
- System.out.println("File not found: " + path); // debug statement
- }
- }
- logger.info("Files successfully loaded. Starting processing...");
- return processFiles(outputFiles, jsonString);
- }
-
- List handleFiles(MultipartFile[] files, String jsonString) throws Exception {
- if(files == null || files.length == 0) {
- logger.info("No files");
- return null;
- }
- logger.info("Handling files: {} files, with JSON string of length: {}", files.length, jsonString.length());
- ObjectMapper mapper = new ObjectMapper();
- JsonNode jsonNode = mapper.readTree(jsonString);
-
- JsonNode pipelineNode = jsonNode.get("pipeline");
-
- boolean hasErrors = false;
- List outputFiles = new ArrayList<>();
-
- for (MultipartFile file : files) {
- Resource fileResource = new ByteArrayResource(file.getBytes()) {
- @Override
- public String getFilename() {
- return file.getOriginalFilename();
- }
- };
- outputFiles.add(fileResource);
- }
- logger.info("Files successfully loaded. Starting processing...");
- return processFiles(outputFiles, jsonString);
- }
-
- @PostMapping("/handleData")
- public ResponseEntity handleData(@ModelAttribute HandleDataRequest request) {
- MultipartFile[] files = request.getFileInputs();
- String jsonString = request.getJsonString();
- logger.info("Received POST request to /handleData with {} files", files.length);
- try {
- List outputFiles = handleFiles(files, jsonString);
-
- if (outputFiles != null && outputFiles.size() == 1) {
- // If there is only one file, return it directly
- Resource singleFile = outputFiles.get(0);
- InputStream is = singleFile.getInputStream();
- byte[] bytes = new byte[(int) singleFile.contentLength()];
- is.read(bytes);
- is.close();
-
- logger.info("Returning single file response...");
- return WebResponseUtils.bytesToWebResponse(bytes, singleFile.getFilename(),
- MediaType.APPLICATION_OCTET_STREAM);
- } else if (outputFiles == null) {
- return null;
- }
-
- // Create a ByteArrayOutputStream to hold the zip
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ZipOutputStream zipOut = new ZipOutputStream(baos);
-
- // Loop through each file and add it to the zip
- for (Resource file : outputFiles) {
- ZipEntry zipEntry = new ZipEntry(file.getFilename());
- zipOut.putNextEntry(zipEntry);
-
- // Read the file into a byte array
- InputStream is = file.getInputStream();
- byte[] bytes = new byte[(int) file.contentLength()];
- is.read(bytes);
-
- // Write the bytes of the file to the zip
- zipOut.write(bytes, 0, bytes.length);
- zipOut.closeEntry();
-
- is.close();
- }
-
- zipOut.close();
-
- logger.info("Returning zipped file response...");
- return WebResponseUtils.boasToWebResponse(baos, "output.zip", MediaType.APPLICATION_OCTET_STREAM);
- } catch (Exception e) {
- logger.error("Error handling data: ", e);
- return null;
- }
- }
-
- private boolean isZip(byte[] data) {
- if (data == null || data.length < 4) {
- return false;
- }
-
- // Check the first four bytes of the data against the standard zip magic number
- return data[0] == 0x50 && data[1] == 0x4B && data[2] == 0x03 && data[3] == 0x04;
- }
-
- private List unzip(byte[] data) throws IOException {
- logger.info("Unzipping data of length: {}", data.length);
- List unzippedFiles = new ArrayList<>();
-
- try (ByteArrayInputStream bais = new ByteArrayInputStream(data);
- ZipInputStream zis = new ZipInputStream(bais)) {
-
- ZipEntry entry;
- while ((entry = zis.getNextEntry()) != null) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int count;
-
- while ((count = zis.read(buffer)) != -1) {
- baos.write(buffer, 0, count);
- }
-
- final String filename = entry.getName();
- Resource fileResource = new ByteArrayResource(baos.toByteArray()) {
- @Override
- public String getFilename() {
- return filename;
- }
- };
-
- // If the unzipped file is a zip file, unzip it
- if (isZip(baos.toByteArray())) {
- logger.info("File {} is a zip file. Unzipping...", filename);
- unzippedFiles.addAll(unzip(baos.toByteArray()));
- } else {
- unzippedFiles.add(fileResource);
- }
- }
- }
-
- logger.info("Unzipping completed. {} files were unzipped.", unzippedFiles.size());
- return unzippedFiles;
- }
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/security/CertSignController.java b/src/main/java/stirling/software/SPDF/controller/api/security/CertSignController.java
deleted file mode 100644
index b0e5f2aa..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/security/CertSignController.java
+++ /dev/null
@@ -1,258 +0,0 @@
-package stirling.software.SPDF.controller.api.security;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.security.KeyFactory;
-import java.security.KeyStore;
-import java.security.PrivateKey;
-import java.security.Security;
-import java.security.cert.CertificateFactory;
-import java.security.cert.X509Certificate;
-import java.security.spec.PKCS8EncodedKeySpec;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-import java.util.Collections;
-import java.util.Date;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.PDPage;
-import org.apache.pdfbox.pdmodel.PDPageContentStream;
-import org.apache.pdfbox.pdmodel.PDResources;
-import org.apache.pdfbox.pdmodel.common.PDRectangle;
-import org.apache.pdfbox.pdmodel.font.PDType1Font;
-import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget;
-import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceDictionary;
-import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceStream;
-import org.apache.pdfbox.pdmodel.interactive.digitalsignature.ExternalSigningSupport;
-import org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature;
-import org.apache.pdfbox.pdmodel.interactive.digitalsignature.SignatureOptions;
-import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
-import org.apache.pdfbox.pdmodel.interactive.form.PDSignatureField;
-import org.bouncycastle.cert.jcajce.JcaCertStore;
-import org.bouncycastle.cms.CMSProcessableByteArray;
-import org.bouncycastle.cms.CMSSignedData;
-import org.bouncycastle.cms.CMSSignedDataGenerator;
-import org.bouncycastle.cms.CMSTypedData;
-import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder;
-import org.bouncycastle.jce.provider.BouncyCastleProvider;
-import org.bouncycastle.operator.ContentSigner;
-import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
-import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
-import org.bouncycastle.util.io.pem.PemReader;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.security.SignPDFWithCertRequest;
-import stirling.software.SPDF.utils.WebResponseUtils;
-
-@RestController
-@RequestMapping("/api/v1/security")
-@Tag(name = "Security", description = "Security APIs")
-public class CertSignController {
-
- private static final Logger logger = LoggerFactory.getLogger(CertSignController.class);
-
- static {
- Security.addProvider(new BouncyCastleProvider());
- }
-
- @PostMapping(consumes = "multipart/form-data", value = "/cert-sign")
- @Operation(summary = "Sign PDF with a Digital Certificate", description = "This endpoint accepts a PDF file, a digital certificate and related information to sign the PDF. It then returns the digitally signed PDF file. Input:PDF Output:PDF Type:MF-SISO")
- public ResponseEntity signPDFWithCert(@ModelAttribute SignPDFWithCertRequest request) throws Exception {
- MultipartFile pdf = request.getFileInput();
- String certType = request.getCertType();
- MultipartFile privateKeyFile = request.getPrivateKeyFile();
- MultipartFile certFile = request.getCertFile();
- MultipartFile p12File = request.getP12File();
- String password = request.getPassword();
- Boolean showSignature = request.isShowSignature();
- String reason = request.getReason();
- String location = request.getLocation();
- String name = request.getName();
- Integer pageNumber = request.getPageNumber();
-
- PrivateKey privateKey = null;
- X509Certificate cert = null;
-
- if (certType != null) {
- logger.info("Cert type provided: {}", certType);
- switch (certType) {
- case "PKCS12":
- if (p12File != null) {
- KeyStore ks = KeyStore.getInstance("PKCS12");
- ks.load(new ByteArrayInputStream(p12File.getBytes()), password.toCharArray());
- String alias = ks.aliases().nextElement();
- if (!ks.isKeyEntry(alias)) {
- throw new IllegalArgumentException("The provided PKCS12 file does not contain a private key.");
- }
- privateKey = (PrivateKey) ks.getKey(alias, password.toCharArray());
- cert = (X509Certificate) ks.getCertificate(alias);
- }
- break;
- case "PEM":
- if (privateKeyFile != null && certFile != null) {
- // Load private key
- KeyFactory keyFactory = KeyFactory.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
- if (isPEM(privateKeyFile.getBytes())) {
- privateKey = keyFactory
- .generatePrivate(new PKCS8EncodedKeySpec(parsePEM(privateKeyFile.getBytes())));
- } else {
- privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyFile.getBytes()));
- }
-
- // Load certificate
- CertificateFactory certFactory = CertificateFactory.getInstance("X.509",
- BouncyCastleProvider.PROVIDER_NAME);
- if (isPEM(certFile.getBytes())) {
- cert = (X509Certificate) certFactory
- .generateCertificate(new ByteArrayInputStream(parsePEM(certFile.getBytes())));
- } else {
- cert = (X509Certificate) certFactory
- .generateCertificate(new ByteArrayInputStream(certFile.getBytes()));
- }
- }
- break;
- }
- }
- PDSignature signature = new PDSignature();
- signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE); // default filter
- signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_SHA1);
- signature.setName(name);
- signature.setLocation(location);
- signature.setReason(reason);
- signature.setSignDate(Calendar.getInstance());
-
- // Load the PDF
- try (PDDocument document = PDDocument.load(pdf.getBytes())) {
- logger.info("Successfully loaded the provided PDF");
- SignatureOptions signatureOptions = new SignatureOptions();
-
- // If you want to show the signature
-
- // ATTEMPT 2
- if (showSignature != null && showSignature) {
- PDPage page = document.getPage(pageNumber - 1);
-
- PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();
- if (acroForm == null) {
- acroForm = new PDAcroForm(document);
- document.getDocumentCatalog().setAcroForm(acroForm);
- }
-
- // Create a new signature field and widget
-
- PDSignatureField signatureField = new PDSignatureField(acroForm);
- PDAnnotationWidget widget = signatureField.getWidgets().get(0);
- PDRectangle rect = new PDRectangle(100, 100, 200, 50); // Define the rectangle size here
- widget.setRectangle(rect);
- page.getAnnotations().add(widget);
-
-// Set the appearance for the signature field
- PDAppearanceDictionary appearanceDict = new PDAppearanceDictionary();
- PDAppearanceStream appearanceStream = new PDAppearanceStream(document);
- appearanceStream.setResources(new PDResources());
- appearanceStream.setBBox(rect);
- appearanceDict.setNormalAppearance(appearanceStream);
- widget.setAppearance(appearanceDict);
-
- try (PDPageContentStream contentStream = new PDPageContentStream(document, appearanceStream)) {
- contentStream.beginText();
- contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12);
- contentStream.newLineAtOffset(110, 130);
- contentStream.showText("Digitally signed by: " + (name != null ? name : "Unknown"));
- contentStream.newLineAtOffset(0, -15);
- contentStream.showText("Date: " + new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z").format(new Date()));
- contentStream.newLineAtOffset(0, -15);
- if (reason != null && !reason.isEmpty()) {
- contentStream.showText("Reason: " + reason);
- contentStream.newLineAtOffset(0, -15);
- }
- if (location != null && !location.isEmpty()) {
- contentStream.showText("Location: " + location);
- contentStream.newLineAtOffset(0, -15);
- }
- contentStream.endText();
- }
-
- // Add the widget annotation to the page
- page.getAnnotations().add(widget);
-
- // Add the signature field to the acroform
- acroForm.getFields().add(signatureField);
-
- // Handle multiple signatures by ensuring a unique field name
- String baseFieldName = "Signature";
- String signatureFieldName = baseFieldName;
- int suffix = 1;
- while (acroForm.getField(signatureFieldName) != null) {
- suffix++;
- signatureFieldName = baseFieldName + suffix;
- }
- signatureField.setPartialName(signatureFieldName);
- }
-
- document.addSignature(signature, signatureOptions);
- logger.info("Signature added to the PDF document");
- // External signing
- ExternalSigningSupport externalSigning = document
- .saveIncrementalForExternalSigning(new ByteArrayOutputStream());
-
- byte[] content = IOUtils.toByteArray(externalSigning.getContent());
-
- // Using BouncyCastle to sign
- CMSTypedData cmsData = new CMSProcessableByteArray(content);
-
- CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
- ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA")
- .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(privateKey);
-
- gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
- new JcaDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build())
- .build(signer, cert));
-
- gen.addCertificates(new JcaCertStore(Collections.singletonList(cert)));
- CMSSignedData signedData = gen.generate(cmsData, false);
-
- byte[] cmsSignature = signedData.getEncoded();
- logger.info("About to sign content using BouncyCastle");
- externalSigning.setSignature(cmsSignature);
- logger.info("Signature set successfully");
-
- // After setting the signature, return the resultant PDF
- try (ByteArrayOutputStream signedPdfOutput = new ByteArrayOutputStream()) {
- document.save(signedPdfOutput);
- return WebResponseUtils.boasToWebResponse(signedPdfOutput,
- pdf.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_signed.pdf");
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- return null;
- }
-
- private byte[] parsePEM(byte[] content) throws IOException {
- PemReader pemReader = new PemReader(new InputStreamReader(new ByteArrayInputStream(content)));
- return pemReader.readPemObject().getContent();
- }
-
- private boolean isPEM(byte[] content) {
- String contentStr = new String(content);
- return contentStr.contains("-----BEGIN") && contentStr.contains("-----END");
- }
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.java b/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.java
deleted file mode 100644
index 791dc736..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/security/GetInfoOnPDF.java
+++ /dev/null
@@ -1,807 +0,0 @@
-package stirling.software.SPDF.controller.api.security;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.pdfbox.cos.COSDocument;
-import org.apache.pdfbox.cos.COSInputStream;
-import org.apache.pdfbox.cos.COSName;
-import org.apache.pdfbox.cos.COSObject;
-import org.apache.pdfbox.cos.COSStream;
-import org.apache.pdfbox.cos.COSString;
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
-import org.apache.pdfbox.pdmodel.PDDocumentInformation;
-import org.apache.pdfbox.pdmodel.PDDocumentNameDictionary;
-import org.apache.pdfbox.pdmodel.PDEmbeddedFilesNameTreeNode;
-import org.apache.pdfbox.pdmodel.PDJavascriptNameTreeNode;
-import org.apache.pdfbox.pdmodel.PDPage;
-import org.apache.pdfbox.pdmodel.PDResources;
-import org.apache.pdfbox.pdmodel.common.PDMetadata;
-import org.apache.pdfbox.pdmodel.common.PDRectangle;
-import org.apache.pdfbox.pdmodel.common.PDStream;
-import org.apache.pdfbox.pdmodel.common.filespecification.PDComplexFileSpecification;
-import org.apache.pdfbox.pdmodel.common.filespecification.PDEmbeddedFile;
-import org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDStructureElement;
-import org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDStructureNode;
-import org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDStructureTreeRoot;
-import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
-import org.apache.pdfbox.pdmodel.encryption.PDEncryption;
-import org.apache.pdfbox.pdmodel.font.PDFont;
-import org.apache.pdfbox.pdmodel.font.PDFontDescriptor;
-import org.apache.pdfbox.pdmodel.graphics.PDXObject;
-import org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace;
-import org.apache.pdfbox.pdmodel.graphics.color.PDICCBased;
-import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
-import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
-import org.apache.pdfbox.pdmodel.graphics.optionalcontent.PDOptionalContentGroup;
-import org.apache.pdfbox.pdmodel.graphics.optionalcontent.PDOptionalContentProperties;
-import org.apache.pdfbox.pdmodel.interactive.action.PDActionJavaScript;
-import org.apache.pdfbox.pdmodel.interactive.action.PDActionURI;
-import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
-import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationFileAttachment;
-import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink;
-import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem;
-import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineNode;
-import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
-import org.apache.pdfbox.pdmodel.interactive.form.PDField;
-import org.apache.pdfbox.text.PDFTextStripper;
-import org.apache.xmpbox.XMPMetadata;
-import org.apache.xmpbox.xml.DomXmpParser;
-import org.apache.xmpbox.xml.XmpParsingException;
-import org.apache.xmpbox.xml.XmpSerializer;
-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 com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.node.ArrayNode;
-import com.fasterxml.jackson.databind.node.ObjectNode;
-
-import io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.PDFFile;
-import stirling.software.SPDF.utils.WebResponseUtils;
-@RestController
-@RequestMapping("/api/v1/security")
-@Tag(name = "Security", description = "Security APIs")
-public class GetInfoOnPDF {
-
- static ObjectMapper objectMapper = new ObjectMapper();
-
- @PostMapping(consumes = "multipart/form-data", value = "/get-info-on-pdf")
- @Operation(summary = "Summary here", description = "desc. Input:PDF Output:JSON Type:SISO")
- public ResponseEntity getPdfInfo(@ModelAttribute PDFFile request)
- throws IOException {
- MultipartFile inputFile = request.getFileInput();
- try (
- PDDocument pdfBoxDoc = PDDocument.load(inputFile.getInputStream());
- ) {
- ObjectMapper objectMapper = new ObjectMapper();
- ObjectNode jsonOutput = objectMapper.createObjectNode();
-
- // Metadata using PDFBox
- PDDocumentInformation info = pdfBoxDoc.getDocumentInformation();
- ObjectNode metadata = objectMapper.createObjectNode();
- ObjectNode basicInfo = objectMapper.createObjectNode();
- ObjectNode docInfoNode = objectMapper.createObjectNode();
- ObjectNode compliancy = objectMapper.createObjectNode();
- ObjectNode encryption = objectMapper.createObjectNode();
- ObjectNode other = objectMapper.createObjectNode();
-
-
- metadata.put("Title", info.getTitle());
- metadata.put("Author", info.getAuthor());
- metadata.put("Subject", info.getSubject());
- metadata.put("Keywords", info.getKeywords());
- metadata.put("Producer", info.getProducer());
- metadata.put("Creator", info.getCreator());
- metadata.put("CreationDate", formatDate(info.getCreationDate()));
- metadata.put("ModificationDate", formatDate(info.getModificationDate()));
- jsonOutput.set("Metadata", metadata);
-
-
-
-
- // Total file size of the PDF
- long fileSizeInBytes = inputFile.getSize();
- basicInfo.put("FileSizeInBytes", fileSizeInBytes);
-
- // Number of words, paragraphs, and images in the entire document
- String fullText = new PDFTextStripper().getText(pdfBoxDoc);
- String[] words = fullText.split("\\s+");
- int wordCount = words.length;
- int paragraphCount = fullText.split("\r\n|\r|\n").length;
- basicInfo.put("WordCount", wordCount);
- basicInfo.put("ParagraphCount", paragraphCount);
- // Number of characters in the entire document (including spaces and special characters)
- int charCount = fullText.length();
- basicInfo.put("CharacterCount", charCount);
-
-
- // Initialize the flags and types
- boolean hasCompression = false;
- String compressionType = "None";
-
- COSDocument cosDoc = pdfBoxDoc.getDocument();
- for (COSObject cosObject : cosDoc.getObjects()) {
- if (cosObject.getObject() instanceof COSStream) {
- COSStream cosStream = (COSStream) cosObject.getObject();
- if (COSName.OBJ_STM.equals(cosStream.getItem(COSName.TYPE))) {
- hasCompression = true;
- compressionType = "Object Streams";
- break;
- }
- }
- }
- basicInfo.put("Compression", hasCompression);
- if(hasCompression)
- basicInfo.put("CompressionType", compressionType);
-
- String language = pdfBoxDoc.getDocumentCatalog().getLanguage();
- basicInfo.put("Language", language);
- basicInfo.put("Number of pages", pdfBoxDoc.getNumberOfPages());
-
-
- PDDocumentCatalog catalog = pdfBoxDoc.getDocumentCatalog();
- String pageMode = catalog.getPageMode().name();
-
- // Document Information using PDFBox
- docInfoNode.put("PDF version", pdfBoxDoc.getVersion());
- docInfoNode.put("Trapped", info.getTrapped());
- docInfoNode.put("Page Mode", getPageModeDescription(pageMode));;
-
-
-
-
-
- PDAcroForm acroForm = pdfBoxDoc.getDocumentCatalog().getAcroForm();
-
- ObjectNode formFieldsNode = objectMapper.createObjectNode();
- if (acroForm != null) {
- for (PDField field : acroForm.getFieldTree()) {
- formFieldsNode.put(field.getFullyQualifiedName(), field.getValueAsString());
- }
- }
- jsonOutput.set("FormFields", formFieldsNode);
-
-
-
-
-
-
- //embeed files TODO size
- if(catalog.getNames() != null) {
- PDEmbeddedFilesNameTreeNode efTree = catalog.getNames().getEmbeddedFiles();
-
- ArrayNode embeddedFilesArray = objectMapper.createArrayNode();
- if (efTree != null) {
- Map efMap = efTree.getNames();
- if (efMap != null) {
- for (Map.Entry entry : efMap.entrySet()) {
- ObjectNode embeddedFileNode = objectMapper.createObjectNode();
- embeddedFileNode.put("Name", entry.getKey());
- PDEmbeddedFile embeddedFile = entry.getValue().getEmbeddedFile();
- if (embeddedFile != null) {
- embeddedFileNode.put("FileSize", embeddedFile.getLength()); // size in bytes
- }
- embeddedFilesArray.add(embeddedFileNode);
- }
- }
- }
- other.set("EmbeddedFiles", embeddedFilesArray);
- }
-
-
-
- //attachments TODO size
- ArrayNode attachmentsArray = objectMapper.createArrayNode();
- for (PDPage page : pdfBoxDoc.getPages()) {
- for (PDAnnotation annotation : page.getAnnotations()) {
- if (annotation instanceof PDAnnotationFileAttachment) {
- PDAnnotationFileAttachment fileAttachmentAnnotation = (PDAnnotationFileAttachment) annotation;
-
- ObjectNode attachmentNode = objectMapper.createObjectNode();
- attachmentNode.put("Name", fileAttachmentAnnotation.getAttachmentName());
- attachmentNode.put("Description", fileAttachmentAnnotation.getContents());
-
- attachmentsArray.add(attachmentNode);
- }
- }
- }
- other.set("Attachments", attachmentsArray);
-
- //Javascript
- PDDocumentNameDictionary namesDict = catalog.getNames();
- ArrayNode javascriptArray = objectMapper.createArrayNode();
-
- if (namesDict != null) {
- PDJavascriptNameTreeNode javascriptDict = namesDict.getJavaScript();
- if (javascriptDict != null) {
- try {
- Map jsEntries = javascriptDict.getNames();
-
- for (Map.Entry entry : jsEntries.entrySet()) {
- ObjectNode jsNode = objectMapper.createObjectNode();
- jsNode.put("JS Name", entry.getKey());
-
- PDActionJavaScript jsAction = entry.getValue();
- if (jsAction != null) {
- String jsCodeStr = jsAction.getAction();
- if (jsCodeStr != null) {
- jsNode.put("JS Script Length", jsCodeStr.length());
- }
- }
-
- javascriptArray.add(jsNode);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- other.set("JavaScript", javascriptArray);
-
-
- //TODO size
- PDOptionalContentProperties ocProperties = pdfBoxDoc.getDocumentCatalog().getOCProperties();
- ArrayNode layersArray = objectMapper.createArrayNode();
-
- if (ocProperties != null) {
- for (PDOptionalContentGroup ocg : ocProperties.getOptionalContentGroups()) {
- ObjectNode layerNode = objectMapper.createObjectNode();
- layerNode.put("Name", ocg.getName());
- layersArray.add(layerNode);
- }
- }
-
- other.set("Layers", layersArray);
-
- //TODO Security
-
-
-
-
-
- PDStructureTreeRoot structureTreeRoot = pdfBoxDoc.getDocumentCatalog().getStructureTreeRoot();
- ArrayNode structureTreeArray;
- try {
- if(structureTreeRoot != null) {
- structureTreeArray = exploreStructureTree(structureTreeRoot.getKids());
- other.set("StructureTree", structureTreeArray);
- }
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
-
- boolean isPdfACompliant = checkForStandard(pdfBoxDoc, "PDF/A");
- boolean isPdfXCompliant = checkForStandard(pdfBoxDoc, "PDF/X");
- boolean isPdfECompliant = checkForStandard(pdfBoxDoc, "PDF/E");
- boolean isPdfVTCompliant = checkForStandard(pdfBoxDoc, "PDF/VT");
- boolean isPdfUACompliant = checkForStandard(pdfBoxDoc, "PDF/UA");
- boolean isPdfBCompliant = checkForStandard(pdfBoxDoc, "PDF/B"); // If you want to check for PDF/Broadcast, though this isn't an official ISO standard.
- boolean isPdfSECCompliant = checkForStandard(pdfBoxDoc, "PDF/SEC"); // This might not be effective since PDF/SEC was under development in 2021.
-
- compliancy.put("IsPDF/ACompliant", isPdfACompliant);
- compliancy.put("IsPDF/XCompliant", isPdfXCompliant);
- compliancy.put("IsPDF/ECompliant", isPdfECompliant);
- compliancy.put("IsPDF/VTCompliant", isPdfVTCompliant);
- compliancy.put("IsPDF/UACompliant", isPdfUACompliant);
- compliancy.put("IsPDF/BCompliant", isPdfBCompliant);
- compliancy.put("IsPDF/SECCompliant", isPdfSECCompliant);
-
-
-
-
-
- PDOutlineNode root = pdfBoxDoc.getDocumentCatalog().getDocumentOutline();
- ArrayNode bookmarksArray = objectMapper.createArrayNode();
-
- if (root != null) {
- for (PDOutlineItem child : root.children()) {
- addOutlinesToArray(child, bookmarksArray);
- }
- }
-
- other.set("Bookmarks/Outline/TOC", bookmarksArray);
-
-
-
- PDMetadata pdMetadata = pdfBoxDoc.getDocumentCatalog().getMetadata();
-
- String xmpString = null;
-
- if (pdMetadata != null) {
- try {
- COSInputStream is = pdMetadata.createInputStream();
- DomXmpParser domXmpParser = new DomXmpParser();
- XMPMetadata xmpMeta = domXmpParser.parse(is);
-
- ByteArrayOutputStream os = new ByteArrayOutputStream();
- new XmpSerializer().serialize(xmpMeta, os, true);
- xmpString = new String(os.toByteArray(), StandardCharsets.UTF_8);
- } catch (XmpParsingException | IOException e) {
- e.printStackTrace();
- }
- }
-
- other.put("XMPMetadata", xmpString);
-
-
-
- if (pdfBoxDoc.isEncrypted()) {
- encryption.put("IsEncrypted", true);
-
- // Retrieve encryption details using getEncryption()
- PDEncryption pdfEncryption = pdfBoxDoc.getEncryption();
- encryption.put("EncryptionAlgorithm", pdfEncryption.getFilter());
- encryption.put("KeyLength", pdfEncryption.getLength());
- AccessPermission ap = pdfBoxDoc.getCurrentAccessPermission();
- if (ap != null) {
- ObjectNode permissionsNode = objectMapper.createObjectNode();
-
- permissionsNode.put("CanAssembleDocument", ap.canAssembleDocument());
- permissionsNode.put("CanExtractContent", ap.canExtractContent());
- permissionsNode.put("CanExtractForAccessibility", ap.canExtractForAccessibility());
- permissionsNode.put("CanFillInForm", ap.canFillInForm());
- permissionsNode.put("CanModify", ap.canModify());
- permissionsNode.put("CanModifyAnnotations", ap.canModifyAnnotations());
- permissionsNode.put("CanPrint", ap.canPrint());
- permissionsNode.put("CanPrintDegraded", ap.canPrintDegraded());
-
- encryption.set("Permissions", permissionsNode); // set the node under "Permissions"
- }
- // Add other encryption-related properties as needed
- } else {
- encryption.put("IsEncrypted", false);
- }
-
-
-
-
- ObjectNode pageInfoParent = objectMapper.createObjectNode();
- for (int pageNum = 0; pageNum < pdfBoxDoc.getNumberOfPages(); pageNum++) {
- ObjectNode pageInfo = objectMapper.createObjectNode();
-
- // Retrieve the page
- PDPage page = pdfBoxDoc.getPage(pageNum);
-
- // Page-level Information
- PDRectangle mediaBox = page.getMediaBox();
-
- float width = mediaBox.getWidth();
- float height = mediaBox.getHeight();
-
- ObjectNode sizeInfo = objectMapper.createObjectNode();
-
- getDimensionInfo(sizeInfo, width, height);
-
- sizeInfo.put("Standard Page", getPageSize(width, height));
- pageInfo.set("Size", sizeInfo);
-
- pageInfo.put("Rotation", page.getRotation());
- pageInfo.put("Page Orientation", getPageOrientation(width, height));
-
-
- // Boxes
- pageInfo.put("MediaBox", mediaBox.toString());
-
- // Assuming the following boxes are defined for your document; if not, you may get null values.
- PDRectangle cropBox = page.getCropBox();
- pageInfo.put("CropBox", cropBox == null ? "Undefined" : cropBox.toString());
-
- PDRectangle bleedBox = page.getBleedBox();
- pageInfo.put("BleedBox", bleedBox == null ? "Undefined" : bleedBox.toString());
-
- PDRectangle trimBox = page.getTrimBox();
- pageInfo.put("TrimBox", trimBox == null ? "Undefined" : trimBox.toString());
-
- PDRectangle artBox = page.getArtBox();
- pageInfo.put("ArtBox", artBox == null ? "Undefined" : artBox.toString());
-
- // Content Extraction
- PDFTextStripper textStripper = new PDFTextStripper();
- textStripper.setStartPage(pageNum + 1);
- textStripper.setEndPage(pageNum +1);
- String pageText = textStripper.getText(pdfBoxDoc);
-
- pageInfo.put("Text Characters Count", pageText.length()); //
-
- // Annotations
-
- List annotations = page.getAnnotations();
-
- int subtypeCount = 0;
- int contentsCount = 0;
-
- for (PDAnnotation annotation : annotations) {
- if (annotation.getSubtype() != null) {
- subtypeCount++; // Increase subtype count
- }
- if (annotation.getContents() != null) {
- contentsCount++; // Increase contents count
- }
- }
-
- ObjectNode annotationsObject = objectMapper.createObjectNode();
- annotationsObject.put("AnnotationsCount", annotations.size());
- annotationsObject.put("SubtypeCount", subtypeCount);
- annotationsObject.put("ContentsCount", contentsCount);
- pageInfo.set("Annotations", annotationsObject);
-
-
-
- // Images (simplified)
- // This part is non-trivial as images can be embedded in multiple ways in a PDF.
- // Here is a basic structure to recognize image XObjects on a page.
- ArrayNode imagesArray = objectMapper.createArrayNode();
- PDResources resources = page.getResources();
-
-
- for (COSName name : resources.getXObjectNames()) {
- PDXObject xObject = resources.getXObject(name);
- if (xObject instanceof PDImageXObject) {
- PDImageXObject image = (PDImageXObject) xObject;
-
- ObjectNode imageNode = objectMapper.createObjectNode();
- imageNode.put("Width", image.getWidth());
- imageNode.put("Height", image.getHeight());
- if(image.getMetadata() != null && image.getMetadata().getFile() != null && image.getMetadata().getFile().getFile() != null) {
- imageNode.put("Name", image.getMetadata().getFile().getFile());
- }
- if (image.getColorSpace() != null) {
- imageNode.put("ColorSpace", image.getColorSpace().getName());
- }
-
- imagesArray.add(imageNode);
- }
- }
- pageInfo.set("Images", imagesArray);
-
-
- // Links
- ArrayNode linksArray = objectMapper.createArrayNode();
- Set uniqueURIs = new HashSet<>(); // To store unique URIs
-
- for (PDAnnotation annotation : annotations) {
- if (annotation instanceof PDAnnotationLink) {
- PDAnnotationLink linkAnnotation = (PDAnnotationLink) annotation;
- if (linkAnnotation.getAction() instanceof PDActionURI) {
- PDActionURI uriAction = (PDActionURI) linkAnnotation.getAction();
- String uri = uriAction.getURI();
- uniqueURIs.add(uri); // Add to set to ensure uniqueness
- }
- }
- }
-
- // Add unique URIs to linksArray
- for (String uri : uniqueURIs) {
- ObjectNode linkNode = objectMapper.createObjectNode();
- linkNode.put("URI", uri);
- linksArray.add(linkNode);
- }
- pageInfo.set("Links", linksArray);
-
-
- // Fonts
- ArrayNode fontsArray = objectMapper.createArrayNode();
- Map uniqueFontsMap = new HashMap<>();
-
- for (COSName fontName : resources.getFontNames()) {
- PDFont font = resources.getFont(fontName);
- ObjectNode fontNode = objectMapper.createObjectNode();
-
- fontNode.put("IsEmbedded", font.isEmbedded());
-
- // PDFBox provides Font's BaseFont (i.e., the font name) directly
- fontNode.put("Name", font.getName());
-
- fontNode.put("Subtype", font.getType());
-
- PDFontDescriptor fontDescriptor = font.getFontDescriptor();
-
- if (fontDescriptor != null) {
- fontNode.put("ItalicAngle", fontDescriptor.getItalicAngle());
- int flags = fontDescriptor.getFlags();
- fontNode.put("IsItalic", (flags & 1) != 0);
- fontNode.put("IsBold", (flags & 64) != 0);
- fontNode.put("IsFixedPitch", (flags & 2) != 0);
- fontNode.put("IsSerif", (flags & 4) != 0);
- fontNode.put("IsSymbolic", (flags & 8) != 0);
- fontNode.put("IsScript", (flags & 16) != 0);
- fontNode.put("IsNonsymbolic", (flags & 32) != 0);
-
- fontNode.put("FontFamily", fontDescriptor.getFontFamily());
- // Font stretch and BBox are not directly available in PDFBox's API, so these are omitted for simplicity
- fontNode.put("FontWeight", fontDescriptor.getFontWeight());
- }
-
-
- // Create a unique key for this font node based on its attributes
- String uniqueKey = fontNode.toString();
-
- // Increment count if this font exists, or initialize it if new
- if (uniqueFontsMap.containsKey(uniqueKey)) {
- ObjectNode existingFontNode = uniqueFontsMap.get(uniqueKey);
- int count = existingFontNode.get("Count").asInt() + 1;
- existingFontNode.put("Count", count);
- } else {
- fontNode.put("Count", 1);
- uniqueFontsMap.put(uniqueKey, fontNode);
- }
- }
-
- // Add unique font entries to fontsArray
- for (ObjectNode uniqueFontNode : uniqueFontsMap.values()) {
- fontsArray.add(uniqueFontNode);
- }
-
- pageInfo.set("Fonts", fontsArray);
-
-
-
-
-
-
-
-
-
-
-
- // Access resources dictionary
- ArrayNode colorSpacesArray = objectMapper.createArrayNode();
-
- Iterable colorSpaceNames = resources.getColorSpaceNames();
- for (COSName name : colorSpaceNames) {
- PDColorSpace colorSpace = resources.getColorSpace(name);
- if (colorSpace instanceof PDICCBased) {
- PDICCBased iccBased = (PDICCBased) colorSpace;
- PDStream iccData = iccBased.getPDStream();
- byte[] iccBytes = iccData.toByteArray();
-
- // TODO: Further decode and analyze the ICC data if needed
- ObjectNode iccProfileNode = objectMapper.createObjectNode();
- iccProfileNode.put("ICC Profile Length", iccBytes.length);
- colorSpacesArray.add(iccProfileNode);
- }
- }
- pageInfo.set("Color Spaces & ICC Profiles", colorSpacesArray);
-
-
- // Other XObjects
- Map xObjectCountMap = new HashMap<>(); // To store the count for each type
- for (COSName name : resources.getXObjectNames()) {
- PDXObject xObject = resources.getXObject(name);
- String xObjectType;
-
- if (xObject instanceof PDImageXObject) {
- xObjectType = "Image";
- } else if (xObject instanceof PDFormXObject) {
- xObjectType = "Form";
- } else {
- xObjectType = "Other";
- }
-
- // Increment the count for this type in the map
- xObjectCountMap.put(xObjectType, xObjectCountMap.getOrDefault(xObjectType, 0) + 1);
- }
-
- // Add the count map to pageInfo (or wherever you want to store it)
- ObjectNode xObjectCountNode = objectMapper.createObjectNode();
- for (Map.Entry entry : xObjectCountMap.entrySet()) {
- xObjectCountNode.put(entry.getKey(), entry.getValue());
- }
- pageInfo.set("XObjectCounts", xObjectCountNode);
-
-
-
-
- ArrayNode multimediaArray = objectMapper.createArrayNode();
-
- for (PDAnnotation annotation : annotations) {
- if ("RichMedia".equals(annotation.getSubtype())) {
- ObjectNode multimediaNode = objectMapper.createObjectNode();
- // Extract details from the annotation as needed
- multimediaArray.add(multimediaNode);
- }
- }
-
- pageInfo.set("Multimedia", multimediaArray);
-
-
-
- pageInfoParent.set("Page " + (pageNum+1), pageInfo);
- }
-
-
- jsonOutput.set("BasicInfo", basicInfo);
- jsonOutput.set("DocumentInfo", docInfoNode);
- jsonOutput.set("Compliancy", compliancy);
- jsonOutput.set("Encryption", encryption);
- jsonOutput.set("Other", other);
- jsonOutput.set("PerPageInfo", pageInfoParent);
-
-
-
- // Save JSON to file
- String jsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonOutput);
-
-
-
- return WebResponseUtils.bytesToWebResponse(jsonString.getBytes(StandardCharsets.UTF_8), "response.json", MediaType.APPLICATION_JSON);
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
-
- private static void addOutlinesToArray(PDOutlineItem outline, ArrayNode arrayNode) {
- if (outline == null) return;
-
- ObjectNode outlineNode = objectMapper.createObjectNode();
- outlineNode.put("Title", outline.getTitle());
- // You can add other properties if needed
- arrayNode.add(outlineNode);
-
- PDOutlineItem child = outline.getFirstChild();
- while (child != null) {
- addOutlinesToArray(child, arrayNode);
- child = child.getNextSibling();
- }
- }
-
- public String getPageOrientation(double width, double height) {
- if (width > height) {
- return "Landscape";
- } else if (height > width) {
- return "Portrait";
- } else {
- return "Square";
- }
- }
- public String getPageSize(float width, float height) {
- // Define standard page sizes
- Map standardSizes = new HashMap<>();
- standardSizes.put("Letter", PDRectangle.LETTER);
- standardSizes.put("LEGAL", PDRectangle.LEGAL);
- standardSizes.put("A0", PDRectangle.A0);
- standardSizes.put("A1", PDRectangle.A1);
- standardSizes.put("A2", PDRectangle.A2);
- standardSizes.put("A3", PDRectangle.A3);
- standardSizes.put("A4", PDRectangle.A4);
- standardSizes.put("A5", PDRectangle.A5);
- standardSizes.put("A6", PDRectangle.A6);
-
- for (Map.Entry entry : standardSizes.entrySet()) {
- PDRectangle size = entry.getValue();
- if (isCloseToSize(width, height, size.getWidth(), size.getHeight())) {
- return entry.getKey();
- }
- }
- return "Custom";
- }
-
- private boolean isCloseToSize(float width, float height, float standardWidth, float standardHeight) {
- float tolerance = 1.0f; // You can adjust the tolerance as needed
- return Math.abs(width - standardWidth) <= tolerance && Math.abs(height - standardHeight) <= tolerance;
- }
-
-
- public ObjectNode getDimensionInfo(ObjectNode dimensionInfo, float width, float height) {
- float ppi = 72; // Points Per Inch
-
- float widthInInches = width / ppi;
- float heightInInches = height / ppi;
-
- float widthInCm = widthInInches * 2.54f;
- float heightInCm = heightInInches * 2.54f;
-
- dimensionInfo.put("Width (px)", String.format("%.2f", width));
- dimensionInfo.put("Height (px)", String.format("%.2f", height));
- dimensionInfo.put("Width (in)", String.format("%.2f", widthInInches));
- dimensionInfo.put("Height (in)", String.format("%.2f", heightInInches));
- dimensionInfo.put("Width (cm)", String.format("%.2f", widthInCm));
- dimensionInfo.put("Height (cm)", String.format("%.2f", heightInCm));
- return dimensionInfo;
- }
-
-
-
-public static boolean checkForStandard(PDDocument document, String standardKeyword) {
- // Check XMP Metadata
- try {
- PDMetadata pdMetadata = document.getDocumentCatalog().getMetadata();
- if (pdMetadata != null) {
- COSInputStream metaStream = pdMetadata.createInputStream();
- DomXmpParser domXmpParser = new DomXmpParser();
- XMPMetadata xmpMeta = domXmpParser.parse(metaStream);
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- new XmpSerializer().serialize(xmpMeta, baos, true);
- String xmpString = new String(baos.toByteArray(), StandardCharsets.UTF_8);
-
- if (xmpString.contains(standardKeyword)) {
- return true;
- }
- }
- } catch (Exception e) { // Catching general exception for brevity, ideally you'd catch specific exceptions.
- e.printStackTrace();
- }
-
- return false;
-}
-
-
- public ArrayNode exploreStructureTree(List nodes) {
- ArrayNode elementsArray = objectMapper.createArrayNode();
- if (nodes != null) {
- for (Object obj : nodes) {
- if (obj instanceof PDStructureNode) {
- PDStructureNode node = (PDStructureNode) obj;
- ObjectNode elementNode = objectMapper.createObjectNode();
-
- if (node instanceof PDStructureElement) {
- PDStructureElement structureElement = (PDStructureElement) node;
- elementNode.put("Type", structureElement.getStructureType());
- elementNode.put("Content", getContent(structureElement));
-
- // Recursively explore child elements
- ArrayNode childElements = exploreStructureTree(structureElement.getKids());
- if (childElements.size() > 0) {
- elementNode.set("Children", childElements);
- }
- }
- elementsArray.add(elementNode);
- }
- }
- }
- return elementsArray;
- }
-
-
- public String getContent(PDStructureElement structureElement) {
- StringBuilder contentBuilder = new StringBuilder();
-
- for (Object item : structureElement.getKids()) {
- if (item instanceof COSString) {
- COSString cosString = (COSString) item;
- contentBuilder.append(cosString.getString());
- } else if (item instanceof PDStructureElement) {
- // For simplicity, we're handling only COSString and PDStructureElement here
- // but a more comprehensive method would handle other types too
- contentBuilder.append(getContent((PDStructureElement) item));
- }
- }
-
- return contentBuilder.toString();
- }
-
-
- private String formatDate(Calendar calendar) {
- if (calendar != null) {
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- return sdf.format(calendar.getTime());
- } else {
- return null;
- }
- }
-
- private String getPageModeDescription(String pageMode) {
- return pageMode != null ? pageMode.toString().replaceFirst("/", "") : "Unknown";
- }
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/security/PasswordController.java b/src/main/java/stirling/software/SPDF/controller/api/security/PasswordController.java
deleted file mode 100644
index 639b6973..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/security/PasswordController.java
+++ /dev/null
@@ -1,89 +0,0 @@
-package stirling.software.SPDF.controller.api.security;
-
-import java.io.IOException;
-
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
-import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.security.AddPasswordRequest;
-import stirling.software.SPDF.model.api.security.PDFPasswordRequest;
-import stirling.software.SPDF.utils.WebResponseUtils;
-@RestController
-@RequestMapping("/api/v1/security")
-@Tag(name = "Security", description = "Security APIs")
-public class PasswordController {
-
- private static final Logger logger = LoggerFactory.getLogger(PasswordController.class);
-
-
- @PostMapping(consumes = "multipart/form-data", value = "/remove-password")
- @Operation(
- summary = "Remove password from a PDF file",
- description = "This endpoint removes the password from a protected PDF file. Users need to provide the existing password. Input:PDF Output:PDF Type:SISO"
- )
- public ResponseEntity removePassword(@ModelAttribute PDFPasswordRequest request) throws IOException {
- MultipartFile fileInput = request.getFileInput();
- String password = request.getPassword();
-
-
-
- PDDocument document = PDDocument.load(fileInput.getBytes(), password);
- document.setAllSecurityToBeRemoved(true);
- return WebResponseUtils.pdfDocToWebResponse(document, fileInput.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_password_removed.pdf");
- }
-
- @PostMapping(consumes = "multipart/form-data", value = "/add-password")
- @Operation(
- summary = "Add password to a PDF file",
- description = "This endpoint adds password protection to a PDF file. Users can specify a set of permissions that should be applied to the file. Input:PDF Output:PDF"
- )
- public ResponseEntity addPassword(@ModelAttribute AddPasswordRequest request) throws IOException {
- MultipartFile fileInput = request.getFileInput();
- String ownerPassword = request.getOwnerPassword();
- String password = request.getPassword();
- int keyLength = request.getKeyLength();
- boolean canAssembleDocument = request.isCanAssembleDocument();
- boolean canExtractContent = request.isCanExtractContent();
- boolean canExtractForAccessibility = request.isCanExtractForAccessibility();
- boolean canFillInForm = request.isCanFillInForm();
- boolean canModify = request.isCanModify();
- boolean canModifyAnnotations = request.isCanModifyAnnotations();
- boolean canPrint = request.isCanPrint();
- boolean canPrintFaithful = request.isCanPrintFaithful();
-
- PDDocument document = PDDocument.load(fileInput.getBytes());
- AccessPermission ap = new AccessPermission();
- ap.setCanAssembleDocument(!canAssembleDocument);
- ap.setCanExtractContent(!canExtractContent);
- ap.setCanExtractForAccessibility(!canExtractForAccessibility);
- ap.setCanFillInForm(!canFillInForm);
- ap.setCanModify(!canModify);
- ap.setCanModifyAnnotations(!canModifyAnnotations);
- ap.setCanPrint(!canPrint);
- ap.setCanPrintFaithful(!canPrintFaithful);
- StandardProtectionPolicy spp = new StandardProtectionPolicy(ownerPassword, password, ap);
-
- if(!"".equals(ownerPassword) || !"".equals(password)) {
- spp.setEncryptionKeyLength(keyLength);
- }
- spp.setPermissions(ap);
- document.protect(spp);
-
- if("".equals(ownerPassword) && "".equals(password))
- return WebResponseUtils.pdfDocToWebResponse(document, fileInput.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_permissions.pdf");
- return WebResponseUtils.pdfDocToWebResponse(document, fileInput.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_passworded.pdf");
- }
-
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/security/RedactController.java b/src/main/java/stirling/software/SPDF/controller/api/security/RedactController.java
deleted file mode 100644
index 825544dc..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/security/RedactController.java
+++ /dev/null
@@ -1,123 +0,0 @@
-package stirling.software.SPDF.controller.api.security;
-
-import java.awt.Color;
-import java.awt.image.BufferedImage;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.util.List;
-
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.PDPage;
-import org.apache.pdfbox.pdmodel.PDPageContentStream;
-import org.apache.pdfbox.pdmodel.common.PDRectangle;
-import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;
-import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
-import org.apache.pdfbox.rendering.ImageType;
-import org.apache.pdfbox.rendering.PDFRenderer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.PDFText;
-import stirling.software.SPDF.model.api.security.RedactPdfRequest;
-import stirling.software.SPDF.pdf.TextFinder;
-import stirling.software.SPDF.utils.WebResponseUtils;
-@RestController
-@RequestMapping("/api/v1/security")
-@Tag(name = "Security", description = "Security APIs")
-public class RedactController {
-
- private static final Logger logger = LoggerFactory.getLogger(RedactController.class);
-
-
- @PostMapping(value = "/auto-redact", consumes = "multipart/form-data")
- @Operation(summary = "Redacts listOfText in a PDF document",
- description = "This operation takes an input PDF file and redacts the provided listOfText. Input:PDF, Output:PDF, Type:SISO")
- public ResponseEntity redactPdf(@ModelAttribute RedactPdfRequest request) throws Exception {
- MultipartFile file = request.getFileInput();
- String listOfTextString = request.getListOfText();
- boolean useRegex = request.isUseRegex();
- boolean wholeWordSearchBool = request.isWholeWordSearch();
- String colorString = request.getRedactColor();
- float customPadding = request.getCustomPadding();
- boolean convertPDFToImage = request.isConvertPDFToImage();
-
- System.out.println(listOfTextString);
- String[] listOfText = listOfTextString.split("\n");
- byte[] bytes = file.getBytes();
- PDDocument document = PDDocument.load(new ByteArrayInputStream(bytes));
-
- Color redactColor;
- try {
- if (!colorString.startsWith("#")) {
- colorString = "#" + colorString;
- }
- redactColor = Color.decode(colorString);
- } catch (NumberFormatException e) {
- logger.warn("Invalid color string provided. Using default color BLACK for redaction.");
- redactColor = Color.BLACK;
- }
-
-
-
- for (String text : listOfText) {
- text = text.trim();
- System.out.println(text);
- TextFinder textFinder = new TextFinder(text, useRegex, wholeWordSearchBool);
- List foundTexts = textFinder.getTextLocations(document);
- redactFoundText(document, foundTexts, customPadding,redactColor);
- }
-
-
-
- if (convertPDFToImage) {
- PDDocument imageDocument = new PDDocument();
- PDFRenderer pdfRenderer = new PDFRenderer(document);
- for (int page = 0; page < document.getNumberOfPages(); ++page) {
- BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB);
- PDPage newPage = new PDPage(new PDRectangle(bim.getWidth(), bim.getHeight()));
- imageDocument.addPage(newPage);
- PDImageXObject pdImage = LosslessFactory.createFromImage(imageDocument, bim);
- PDPageContentStream contentStream = new PDPageContentStream(imageDocument, newPage);
- contentStream.drawImage(pdImage, 0, 0);
- contentStream.close();
- }
- document.close();
- document = imageDocument;
- }
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- document.save(baos);
- document.close();
-
- byte[] pdfContent = baos.toByteArray();
- return WebResponseUtils.bytesToWebResponse(pdfContent,
- file.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_redacted.pdf");
- }
-
-
- private void redactFoundText(PDDocument document, List blocks, float customPadding, Color redactColor) throws IOException {
- var allPages = document.getDocumentCatalog().getPages();
-
- for (PDFText block : blocks) {
- var page = allPages.get(block.getPageIndex());
- PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true);
- contentStream.setNonStrokingColor(redactColor);
- float padding = (block.getY2() - block.getY1()) * 0.3f + customPadding;
- PDRectangle pageBox = page.getBBox();
- contentStream.addRect(block.getX1(), pageBox.getHeight() - block.getY1() - padding, block.getX2() - block.getX1(), block.getY2() - block.getY1() + 2 * padding);
- contentStream.fill();
- contentStream.close();
- }
- }
-
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/security/SanitizeController.java b/src/main/java/stirling/software/SPDF/controller/api/security/SanitizeController.java
deleted file mode 100644
index dab9d1d7..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/security/SanitizeController.java
+++ /dev/null
@@ -1,167 +0,0 @@
-package stirling.software.SPDF.controller.api.security;
-import java.io.IOException;
-
-import org.apache.pdfbox.cos.COSDictionary;
-import org.apache.pdfbox.cos.COSName;
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
-import org.apache.pdfbox.pdmodel.PDPage;
-import org.apache.pdfbox.pdmodel.PDPageTree;
-import org.apache.pdfbox.pdmodel.PDResources;
-import org.apache.pdfbox.pdmodel.common.PDMetadata;
-import org.apache.pdfbox.pdmodel.interactive.action.PDAction;
-import org.apache.pdfbox.pdmodel.interactive.action.PDActionJavaScript;
-import org.apache.pdfbox.pdmodel.interactive.action.PDActionLaunch;
-import org.apache.pdfbox.pdmodel.interactive.action.PDActionURI;
-import org.apache.pdfbox.pdmodel.interactive.action.PDFormFieldAdditionalActions;
-import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
-import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink;
-import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget;
-import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
-import org.apache.pdfbox.pdmodel.interactive.form.PDField;
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.security.SanitizePdfRequest;
-import stirling.software.SPDF.utils.WebResponseUtils;
-
-@RestController
-@RequestMapping("/api/v1/security")
-@Tag(name = "Security", description = "Security APIs")
-public class SanitizeController {
-
- @PostMapping(consumes = "multipart/form-data", value = "/sanitize-pdf")
- @Operation(summary = "Sanitize a PDF file",
- description = "This endpoint processes a PDF file and removes specific elements based on the provided options. Input:PDF Output:PDF Type:SISO")
- public ResponseEntity sanitizePDF(@ModelAttribute SanitizePdfRequest request) throws IOException {
- MultipartFile inputFile = request.getFileInput();
- boolean removeJavaScript = request.isRemoveJavaScript();
- boolean removeEmbeddedFiles = request.isRemoveEmbeddedFiles();
- boolean removeMetadata = request.isRemoveMetadata();
- boolean removeLinks = request.isRemoveLinks();
- boolean removeFonts = request.isRemoveFonts();
-
- try (PDDocument document = PDDocument.load(inputFile.getInputStream())) {
- if (removeJavaScript) {
- sanitizeJavaScript(document);
- }
-
- if (removeEmbeddedFiles) {
- sanitizeEmbeddedFiles(document);
- }
-
- if (removeMetadata) {
- sanitizeMetadata(document);
- }
-
- if (removeLinks) {
- sanitizeLinks(document);
- }
-
- if (removeFonts) {
- sanitizeFonts(document);
- }
-
- return WebResponseUtils.pdfDocToWebResponse(document, inputFile.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_sanitized.pdf");
- }
- }
- private void sanitizeJavaScript(PDDocument document) throws IOException {
- // Get the root dictionary (catalog) of the PDF
- PDDocumentCatalog catalog = document.getDocumentCatalog();
-
- // Get the Names dictionary
- COSDictionary namesDict = (COSDictionary) catalog.getCOSObject().getDictionaryObject(COSName.NAMES);
-
- if (namesDict != null) {
- // Get the JavaScript dictionary
- COSDictionary javaScriptDict = (COSDictionary) namesDict.getDictionaryObject(COSName.getPDFName("JavaScript"));
-
- if (javaScriptDict != null) {
- // Remove the JavaScript dictionary
- namesDict.removeItem(COSName.getPDFName("JavaScript"));
- }
- }
-
- for (PDPage page : document.getPages()) {
- for (PDAnnotation annotation : page.getAnnotations()) {
- if (annotation instanceof PDAnnotationWidget) {
- PDAnnotationWidget widget = (PDAnnotationWidget) annotation;
- PDAction action = widget.getAction();
- if (action instanceof PDActionJavaScript) {
- widget.setAction(null);
- }
- }
- }
- PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();
- if (acroForm != null) {
- for (PDField field : acroForm.getFields()) {
- PDFormFieldAdditionalActions actions = field.getActions();
- if(actions != null) {
- if (actions.getC() instanceof PDActionJavaScript) {
- actions.setC(null);
- }
- if (actions.getF() instanceof PDActionJavaScript) {
- actions.setF(null);
- }
- if (actions.getK() instanceof PDActionJavaScript) {
- actions.setK(null);
- }
- if (actions.getV() instanceof PDActionJavaScript) {
- actions.setV(null);
- }
- }
- }
- }
- }
- }
-
-
-
-
- private void sanitizeEmbeddedFiles(PDDocument document) {
- PDPageTree allPages = document.getPages();
-
- for (PDPage page : allPages) {
- PDResources res = page.getResources();
-
- // Remove embedded files from the PDF
- res.getCOSObject().removeItem(COSName.getPDFName("EmbeddedFiles"));
- }
- }
-
-
- private void sanitizeMetadata(PDDocument document) {
- PDMetadata metadata = document.getDocumentCatalog().getMetadata();
- if (metadata != null) {
- document.getDocumentCatalog().setMetadata(null);
- }
- }
-
-
-
- private void sanitizeLinks(PDDocument document) throws IOException {
- for (PDPage page : document.getPages()) {
- for (PDAnnotation annotation : page.getAnnotations()) {
- if (annotation instanceof PDAnnotationLink) {
- PDAction action = ((PDAnnotationLink) annotation).getAction();
- if (action instanceof PDActionLaunch || action instanceof PDActionURI) {
- ((PDAnnotationLink) annotation).setAction(null);
- }
- }
- }
- }
- }
-
- private void sanitizeFonts(PDDocument document) {
- for (PDPage page : document.getPages()) {
- page.getResources().getCOSObject().removeItem(COSName.getPDFName("Font"));
- }
- }
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/api/security/WatermarkController.java b/src/main/java/stirling/software/SPDF/controller/api/security/WatermarkController.java
deleted file mode 100644
index b19636cd..00000000
--- a/src/main/java/stirling/software/SPDF/controller/api/security/WatermarkController.java
+++ /dev/null
@@ -1,191 +0,0 @@
-package stirling.software.SPDF.controller.api.security;
-
-import java.awt.Color;
-import java.awt.image.BufferedImage;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-import javax.imageio.ImageIO;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.pdmodel.PDPage;
-import org.apache.pdfbox.pdmodel.PDPageContentStream;
-import org.apache.pdfbox.pdmodel.font.PDFont;
-import org.apache.pdfbox.pdmodel.font.PDType0Font;
-import org.apache.pdfbox.pdmodel.font.PDType1Font;
-import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;
-import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
-import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState;
-import org.apache.pdfbox.util.Matrix;
-import org.springframework.core.io.ClassPathResource;
-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 io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import stirling.software.SPDF.model.api.security.AddWatermarkRequest;
-import stirling.software.SPDF.utils.WebResponseUtils;
-
-@RestController
-@RequestMapping("/api/v1/security")
-@Tag(name = "Security", description = "Security APIs")
-public class WatermarkController {
-
- @PostMapping(consumes = "multipart/form-data", value = "/add-watermark")
- @Operation(summary = "Add watermark to a PDF file", description = "This endpoint adds a watermark to a given PDF file. Users can specify the watermark type (text or image), rotation, opacity, width spacer, and height spacer. Input:PDF Output:PDF Type:SISO")
- public ResponseEntity addWatermark(@ModelAttribute AddWatermarkRequest request) throws IOException, Exception {
- MultipartFile pdfFile = request.getFileInput();
- String watermarkType = request.getWatermarkType();
- String watermarkText = request.getWatermarkText();
- MultipartFile watermarkImage = request.getWatermarkImage();
- String alphabet = request.getAlphabet();
- float fontSize = request.getFontSize();
- float rotation = request.getRotation();
- float opacity = request.getOpacity();
- int widthSpacer = request.getWidthSpacer();
- int heightSpacer = request.getHeightSpacer();
-
- // Load the input PDF
- PDDocument document = PDDocument.load(pdfFile.getInputStream());
-
- // Create a page in the document
- for (PDPage page : document.getPages()) {
-
- // Get the page's content stream
- PDPageContentStream contentStream = new PDPageContentStream(document, page,
- PDPageContentStream.AppendMode.APPEND, true);
-
- // Set transparency
- PDExtendedGraphicsState graphicsState = new PDExtendedGraphicsState();
- graphicsState.setNonStrokingAlphaConstant(opacity);
- contentStream.setGraphicsStateParameters(graphicsState);
-
- if (watermarkType.equalsIgnoreCase("text")) {
- addTextWatermark(contentStream, watermarkText, document, page, rotation, widthSpacer, heightSpacer,
- fontSize, alphabet);
- } else if (watermarkType.equalsIgnoreCase("image")) {
- addImageWatermark(contentStream, watermarkImage, document, page, rotation, widthSpacer, heightSpacer,
- fontSize);
- }
-
- // Close the content stream
- contentStream.close();
- }
-
- return WebResponseUtils.pdfDocToWebResponse(document,
- pdfFile.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_watermarked.pdf");
- }
-
- private void addTextWatermark(PDPageContentStream contentStream, String watermarkText, PDDocument document,
- PDPage page, float rotation, int widthSpacer, int heightSpacer, float fontSize, String alphabet) throws IOException {
- String resourceDir = "";
- PDFont font = PDType1Font.HELVETICA_BOLD;
- switch (alphabet) {
- case "arabic":
- resourceDir = "static/fonts/NotoSansArabic-Regular.ttf";
- break;
- case "japanese":
- resourceDir = "static/fonts/Meiryo.ttf";
- break;
- case "korean":
- resourceDir = "static/fonts/malgun.ttf";
- break;
- case "chinese":
- resourceDir = "static/fonts/SimSun.ttf";
- break;
- case "roman":
- default:
- resourceDir = "static/fonts/NotoSans-Regular.ttf";
- break;
- }
-
-
- if(!resourceDir.equals("")) {
- ClassPathResource classPathResource = new ClassPathResource(resourceDir);
- String fileExtension = resourceDir.substring(resourceDir.lastIndexOf("."));
- File tempFile = File.createTempFile("NotoSansFont", fileExtension);
- try (InputStream is = classPathResource.getInputStream(); FileOutputStream os = new FileOutputStream(tempFile)) {
- IOUtils.copy(is, os);
- }
-
- font = PDType0Font.load(document, tempFile);
- tempFile.deleteOnExit();
- }
-
- contentStream.setFont(font, fontSize);
- contentStream.setNonStrokingColor(Color.LIGHT_GRAY);
-
- // Set size and location of text watermark
- float watermarkWidth = widthSpacer + font.getStringWidth(watermarkText) * fontSize / 1000;
- float watermarkHeight = heightSpacer + fontSize;
- float pageWidth = page.getMediaBox().getWidth();
- float pageHeight = page.getMediaBox().getHeight();
- int watermarkRows = (int) (pageHeight / watermarkHeight + 1);
- int watermarkCols = (int) (pageWidth / watermarkWidth + 1);
-
- // Add the text watermark
- for (int i = 0; i < watermarkRows; i++) {
- for (int j = 0; j < watermarkCols; j++) {
- contentStream.beginText();
- contentStream.setTextMatrix(Matrix.getRotateInstance((float) Math.toRadians(rotation),
- j * watermarkWidth, i * watermarkHeight));
- contentStream.showText(watermarkText);
- contentStream.endText();
- }
- }
- }
-
- private void addImageWatermark(PDPageContentStream contentStream, MultipartFile watermarkImage, PDDocument document, PDPage page, float rotation,
- int widthSpacer, int heightSpacer, float fontSize) throws IOException {
-
-// Load the watermark image
-BufferedImage image = ImageIO.read(watermarkImage.getInputStream());
-
-// Compute width based on original aspect ratio
-float aspectRatio = (float) image.getWidth() / (float) image.getHeight();
-
-// Desired physical height (in PDF points)
-float desiredPhysicalHeight = fontSize ;
-
-// Desired physical width based on the aspect ratio
-float desiredPhysicalWidth = desiredPhysicalHeight * aspectRatio;
-
-// Convert the BufferedImage to PDImageXObject
-PDImageXObject xobject = LosslessFactory.createFromImage(document, image);
-
-// Calculate the number of rows and columns for watermarks
-float pageWidth = page.getMediaBox().getWidth();
-float pageHeight = page.getMediaBox().getHeight();
-int watermarkRows = (int) ((pageHeight + heightSpacer) / (desiredPhysicalHeight + heightSpacer));
-int watermarkCols = (int) ((pageWidth + widthSpacer) / (desiredPhysicalWidth + widthSpacer));
-
-for (int i = 0; i < watermarkRows; i++) {
-for (int j = 0; j < watermarkCols; j++) {
-float x = j * (desiredPhysicalWidth + widthSpacer);
-float y = i * (desiredPhysicalHeight + heightSpacer);
-
-// Save the graphics state
-contentStream.saveGraphicsState();
-
-// Create rotation matrix and rotate
-contentStream.transform(Matrix.getTranslateInstance(x + desiredPhysicalWidth / 2, y + desiredPhysicalHeight / 2));
-contentStream.transform(Matrix.getRotateInstance(Math.toRadians(rotation), 0, 0));
-contentStream.transform(Matrix.getTranslateInstance(-desiredPhysicalWidth / 2, -desiredPhysicalHeight / 2));
-
-// Draw the image and restore the graphics state
-contentStream.drawImage(xobject, 0, 0, desiredPhysicalWidth, desiredPhysicalHeight);
-contentStream.restoreGraphicsState();
-}
-
-}
-
- }
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/web/AccountWebController.java b/src/main/java/stirling/software/SPDF/controller/web/AccountWebController.java
deleted file mode 100644
index cba7ebb5..00000000
--- a/src/main/java/stirling/software/SPDF/controller/web/AccountWebController.java
+++ /dev/null
@@ -1,135 +0,0 @@
-package stirling.software.SPDF.controller.web;
-import java.util.List;
-import java.util.Optional;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.access.prepost.PreAuthorize;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.userdetails.UserDetails;
-import org.springframework.stereotype.Controller;
-import org.springframework.ui.Model;
-import org.springframework.web.bind.annotation.GetMapping;
-
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-import io.swagger.v3.oas.annotations.tags.Tag;
-import jakarta.servlet.http.HttpServletRequest;
-import stirling.software.SPDF.model.User;
-import stirling.software.SPDF.repository.UserRepository;
-@Controller
-@Tag(name = "Account Security", description = "Account Security APIs")
-public class AccountWebController {
-
-
- @GetMapping("/login")
- public String login(HttpServletRequest request, Model model, Authentication authentication) {
- if (authentication != null && authentication.isAuthenticated()) {
- return "redirect:/";
- }
-
- if (request.getParameter("error") != null) {
-
- model.addAttribute("error", request.getParameter("error"));
- }
- if (request.getParameter("logout") != null) {
-
- model.addAttribute("logoutMessage", "You have been logged out.");
- }
-
- return "login";
- }
- @Autowired
- private UserRepository userRepository; // Assuming you have a repository for user operations
-
-
- @PreAuthorize("hasRole('ROLE_ADMIN')")
- @GetMapping("/addUsers")
- public String showAddUserForm(Model model, Authentication authentication) {
- List allUsers = userRepository.findAll();
- model.addAttribute("users", allUsers);
- model.addAttribute("currentUsername", authentication.getName());
- return "addUsers";
- }
-
-
-
- @GetMapping("/account")
- public String account(HttpServletRequest request, Model model, Authentication authentication) {
- if (authentication == null || !authentication.isAuthenticated()) {
- return "redirect:/";
- }
- if (authentication != null && authentication.isAuthenticated()) {
- Object principal = authentication.getPrincipal();
-
- if (principal instanceof UserDetails) {
- // Cast the principal object to UserDetails
- UserDetails userDetails = (UserDetails) principal;
-
- // Retrieve username and other attributes
- String username = userDetails.getUsername();
-
- // Fetch user details from the database
- Optional user = userRepository.findByUsername(username); // Assuming findByUsername method exists
- if (!user.isPresent()) {
- // Handle error appropriately
- return "redirect:/error"; // Example redirection in case of error
- }
-
- // Convert settings map to JSON string
- ObjectMapper objectMapper = new ObjectMapper();
- String settingsJson;
- try {
- settingsJson = objectMapper.writeValueAsString(user.get().getSettings());
- } catch (JsonProcessingException e) {
- // Handle JSON conversion error
- e.printStackTrace();
- return "redirect:/error"; // Example redirection in case of error
- }
-
- // Add attributes to the model
- model.addAttribute("username", username);
- model.addAttribute("role", user.get().getRolesAsString());
- model.addAttribute("settings", settingsJson);
- model.addAttribute("changeCredsFlag", user.get().isFirstLogin());
- }
- } else {
- return "redirect:/";
- }
- return "account";
- }
-
-
-
- @GetMapping("/change-creds")
- public String changeCreds(HttpServletRequest request, Model model, Authentication authentication) {
- if (authentication == null || !authentication.isAuthenticated()) {
- return "redirect:/";
- }
- if (authentication != null && authentication.isAuthenticated()) {
- Object principal = authentication.getPrincipal();
-
- if (principal instanceof UserDetails) {
- // Cast the principal object to UserDetails
- UserDetails userDetails = (UserDetails) principal;
-
- // Retrieve username and other attributes
- String username = userDetails.getUsername();
-
- // Fetch user details from the database
- Optional user = userRepository.findByUsername(username); // Assuming findByUsername method exists
- if (!user.isPresent()) {
- // Handle error appropriately
- return "redirect:/error"; // Example redirection in case of error
- }
- // Add attributes to the model
- model.addAttribute("username", username);
- }
- } else {
- return "redirect:/";
- }
- return "change-creds";
- }
-
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/web/ConverterWebController.java b/src/main/java/stirling/software/SPDF/controller/web/ConverterWebController.java
deleted file mode 100644
index 76e7be8f..00000000
--- a/src/main/java/stirling/software/SPDF/controller/web/ConverterWebController.java
+++ /dev/null
@@ -1,109 +0,0 @@
-package stirling.software.SPDF.controller.web;
-
-import org.springframework.stereotype.Controller;
-import org.springframework.ui.Model;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.servlet.ModelAndView;
-
-import io.swagger.v3.oas.annotations.Hidden;
-import io.swagger.v3.oas.annotations.tags.Tag;
-
-@Controller
-@Tag(name = "Convert", description = "Convert APIs")
-public class ConverterWebController {
-
- @GetMapping("/img-to-pdf")
- @Hidden
- public String convertImgToPdfForm(Model model) {
- model.addAttribute("currentPage", "img-to-pdf");
- return "convert/img-to-pdf";
- }
-
- @GetMapping("/html-to-pdf")
- @Hidden
- public String convertHTMLToPdfForm(Model model) {
- model.addAttribute("currentPage", "html-to-pdf");
- return "convert/html-to-pdf";
- }
- @GetMapping("/markdown-to-pdf")
- @Hidden
- public String convertMarkdownToPdfForm(Model model) {
- model.addAttribute("currentPage", "markdown-to-pdf");
- return "convert/markdown-to-pdf";
- }
-
-
- @GetMapping("/url-to-pdf")
- @Hidden
- public String convertURLToPdfForm(Model model) {
- model.addAttribute("currentPage", "url-to-pdf");
- return "convert/url-to-pdf";
- }
-
-
- @GetMapping("/pdf-to-img")
- @Hidden
- public String pdfToimgForm(Model model) {
- model.addAttribute("currentPage", "pdf-to-img");
- return "convert/pdf-to-img";
- }
-
- @GetMapping("/file-to-pdf")
- @Hidden
- public String convertToPdfForm(Model model) {
- model.addAttribute("currentPage", "file-to-pdf");
- return "convert/file-to-pdf";
- }
-
-
-
- //PDF TO......
-
- @GetMapping("/pdf-to-html")
- @Hidden
- public ModelAndView pdfToHTML() {
- ModelAndView modelAndView = new ModelAndView("convert/pdf-to-html");
- modelAndView.addObject("currentPage", "pdf-to-html");
- return modelAndView;
- }
-
- @GetMapping("/pdf-to-presentation")
- @Hidden
- public ModelAndView pdfToPresentation() {
- ModelAndView modelAndView = new ModelAndView("convert/pdf-to-presentation");
- modelAndView.addObject("currentPage", "pdf-to-presentation");
- return modelAndView;
- }
-
- @GetMapping("/pdf-to-text")
- @Hidden
- public ModelAndView pdfToText() {
- ModelAndView modelAndView = new ModelAndView("convert/pdf-to-text");
- modelAndView.addObject("currentPage", "pdf-to-text");
- return modelAndView;
- }
-
- @GetMapping("/pdf-to-word")
- @Hidden
- public ModelAndView pdfToWord() {
- ModelAndView modelAndView = new ModelAndView("convert/pdf-to-word");
- modelAndView.addObject("currentPage", "pdf-to-word");
- return modelAndView;
- }
-
- @GetMapping("/pdf-to-xml")
- @Hidden
- public ModelAndView pdfToXML() {
- ModelAndView modelAndView = new ModelAndView("convert/pdf-to-xml");
- modelAndView.addObject("currentPage", "pdf-to-xml");
- return modelAndView;
- }
-
-
- @GetMapping("/pdf-to-pdfa")
- @Hidden
- public String pdfToPdfAForm(Model model) {
- model.addAttribute("currentPage", "pdf-to-pdfa");
- return "convert/pdf-to-pdfa";
- }
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/web/GeneralWebController.java b/src/main/java/stirling/software/SPDF/controller/web/GeneralWebController.java
deleted file mode 100644
index 6c934290..00000000
--- a/src/main/java/stirling/software/SPDF/controller/web/GeneralWebController.java
+++ /dev/null
@@ -1,268 +0,0 @@
-package stirling.software.SPDF.controller.web;
-import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.core.io.Resource;
-import org.springframework.core.io.ResourceLoader;
-import org.springframework.core.io.support.ResourcePatternUtils;
-import org.springframework.stereotype.Controller;
-import org.springframework.ui.Model;
-import org.springframework.web.bind.annotation.GetMapping;
-
-import com.fasterxml.jackson.core.type.TypeReference;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-import io.swagger.v3.oas.annotations.Hidden;
-import io.swagger.v3.oas.annotations.tags.Tag;
-
-@Controller
-@Tag(name = "General", description = "General APIs")
-public class GeneralWebController {
-
-
-
-
- @GetMapping("/pipeline")
- @Hidden
- public String pipelineForm(Model model) {
- model.addAttribute("currentPage", "pipeline");
-
- List pipelineConfigs = new ArrayList<>();
- try (Stream paths = Files.walk(Paths.get("./pipeline/defaultWebUIConfigs/"))) {
- List jsonFiles = paths
- .filter(Files::isRegularFile)
- .filter(p -> p.toString().endsWith(".json"))
- .collect(Collectors.toList());
-
- for (Path jsonFile : jsonFiles) {
- String content = Files.readString(jsonFile, StandardCharsets.UTF_8);
- pipelineConfigs.add(content);
- }
- List> pipelineConfigsWithNames = new ArrayList<>();
- for (String config : pipelineConfigs) {
- Map jsonContent = new ObjectMapper().readValue(config, new TypeReference>(){});
-
- String name = (String) jsonContent.get("name");
- Map configWithName = new HashMap<>();
- configWithName.put("json", config);
- configWithName.put("name", name);
- pipelineConfigsWithNames.add(configWithName);
- }
- model.addAttribute("pipelineConfigsWithNames", pipelineConfigsWithNames);
-
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- model.addAttribute("pipelineConfigs", pipelineConfigs);
-
- return "pipeline";
- }
-
-
-
-
- @GetMapping("/merge-pdfs")
- @Hidden
- public String mergePdfForm(Model model) {
- model.addAttribute("currentPage", "merge-pdfs");
- return "merge-pdfs";
- }
-
-
- @GetMapping("/multi-tool")
- @Hidden
- public String multiToolForm(Model model) {
- model.addAttribute("currentPage", "multi-tool");
- return "multi-tool";
- }
-
-
- @GetMapping("/remove-pages")
- @Hidden
- public String pageDeleter(Model model) {
- model.addAttribute("currentPage", "remove-pages");
- return "remove-pages";
- }
-
- @GetMapping("/pdf-organizer")
- @Hidden
- public String pageOrganizer(Model model) {
- model.addAttribute("currentPage", "pdf-organizer");
- return "pdf-organizer";
- }
-
- @GetMapping("/extract-page")
- @Hidden
- public String extractPages(Model model) {
- model.addAttribute("currentPage", "extract-page");
- return "extract-page";
- }
-
- @GetMapping("/pdf-to-single-page")
- @Hidden
- public String pdfToSinglePage(Model model) {
- model.addAttribute("currentPage", "pdf-to-single-page");
- return "pdf-to-single-page";
- }
-
- @GetMapping("/rotate-pdf")
- @Hidden
- public String rotatePdfForm(Model model) {
- model.addAttribute("currentPage", "rotate-pdf");
- return "rotate-pdf";
- }
-
- @GetMapping("/split-pdfs")
- @Hidden
- public String splitPdfForm(Model model) {
- model.addAttribute("currentPage", "split-pdfs");
- return "split-pdfs";
- }
-
- @GetMapping("/sign")
- @Hidden
- public String signForm(Model model) {
- model.addAttribute("currentPage", "sign");
- model.addAttribute("fonts", getFontNames());
- return "sign";
- }
-
- @GetMapping("/multi-page-layout")
- @Hidden
- public String multiPageLayoutForm(Model model) {
- model.addAttribute("currentPage", "multi-page-layout");
- return "multi-page-layout";
- }
-
-
- @GetMapping("/scale-pages")
- @Hidden
- public String scalePagesFrom(Model model) {
- model.addAttribute("currentPage", "scale-pages");
- return "scale-pages";
- }
-
-
-
- @Autowired
- private ResourceLoader resourceLoader;
-
- private List getFontNames() {
- List fontNames = new ArrayList<>();
-
- // Extract font names from classpath
- fontNames.addAll(getFontNamesFromLocation("classpath:static/fonts/*.woff2"));
-
- // Extract font names from external directory
- fontNames.addAll(getFontNamesFromLocation("file:customFiles/static/fonts/*"));
-
- return fontNames;
- }
-
- private List getFontNamesFromLocation(String locationPattern) {
- try {
- Resource[] resources = ResourcePatternUtils.getResourcePatternResolver(resourceLoader)
- .getResources(locationPattern);
- return Arrays.stream(resources)
- .map(resource -> {
- try {
- String filename = resource.getFilename();
- if (filename != null) {
- int lastDotIndex = filename.lastIndexOf('.');
- if (lastDotIndex != -1) {
- String name = filename.substring(0, lastDotIndex);
- String extension = filename.substring(lastDotIndex + 1);
- return new FontResource(name, extension);
- }
- }
- return null;
- } catch (Exception e) {
- throw new RuntimeException("Error processing filename", e);
- }
- })
- .filter(Objects::nonNull)
- .collect(Collectors.toList());
- } catch (Exception e) {
- throw new RuntimeException("Failed to read font directory from " + locationPattern, e);
- }
- }
-
-
- public String getFormatFromExtension(String extension) {
- switch (extension) {
- case "ttf": return "truetype";
- case "woff": return "woff";
- case "woff2": return "woff2";
- case "eot": return "embedded-opentype";
- case "svg": return "svg";
- default: return ""; // or throw an exception if an unexpected extension is encountered
- }
- }
-
-
- public class FontResource {
- private String name;
- private String extension;
- private String type;
- public FontResource(String name, String extension) {
- this.name = name;
- this.extension = extension;
- this.type = getFormatFromExtension(extension);
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getExtension() {
- return extension;
- }
-
- public void setExtension(String extension) {
- this.extension = extension;
- }
-
- public String getType() {
- return type;
- }
-
- public void setType(String type) {
- this.type = type;
- }
-
-
- }
-
-
- @GetMapping("/crop")
- @Hidden
- public String cropForm(Model model) {
- model.addAttribute("currentPage", "crop");
- return "crop";
- }
-
-
- @GetMapping("/auto-split-pdf")
- @Hidden
- public String autoSPlitPDFForm(Model model) {
- model.addAttribute("currentPage", "auto-split-pdf");
- return "auto-split-pdf";
- }
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/web/HomeWebController.java b/src/main/java/stirling/software/SPDF/controller/web/HomeWebController.java
deleted file mode 100644
index b6d08fbf..00000000
--- a/src/main/java/stirling/software/SPDF/controller/web/HomeWebController.java
+++ /dev/null
@@ -1,52 +0,0 @@
-package stirling.software.SPDF.controller.web;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.MediaType;
-import org.springframework.stereotype.Controller;
-import org.springframework.ui.Model;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.ResponseBody;
-
-import io.swagger.v3.oas.annotations.Hidden;
-import stirling.software.SPDF.model.ApplicationProperties;
-
-@Controller
-public class HomeWebController {
-
- @GetMapping("/about")
- @Hidden
- public String gameForm(Model model) {
- model.addAttribute("currentPage", "about");
- return "about";
- }
-
-
-
- @GetMapping("/")
- public String home(Model model) {
- model.addAttribute("currentPage", "home");
- return "home";
- }
-
- @GetMapping("/home")
- public String root(Model model) {
- return "redirect:/";
- }
-
- @Autowired
- ApplicationProperties applicationProperties;
-
-
- @GetMapping(value = "/robots.txt", produces = MediaType.TEXT_PLAIN_VALUE)
- @ResponseBody
- @Hidden
- public String getRobotsTxt() {
- Boolean allowGoogle = applicationProperties.getSystem().getGooglevisibility();
- if(Boolean.TRUE.equals(allowGoogle)) {
- return "User-agent: Googlebot\nAllow: /\n\nUser-agent: *\nAllow: /";
- } else {
- return "User-agent: Googlebot\nDisallow: /\n\nUser-agent: *\nDisallow: /";
- }
- }
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/web/MetricsController.java b/src/main/java/stirling/software/SPDF/controller/web/MetricsController.java
deleted file mode 100644
index 9dc4f2b7..00000000
--- a/src/main/java/stirling/software/SPDF/controller/web/MetricsController.java
+++ /dev/null
@@ -1,265 +0,0 @@
-package stirling.software.SPDF.controller.web;
-import java.time.Duration;
-import java.time.LocalDateTime;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.stream.Collectors;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.ResponseEntity;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.bind.annotation.RestController;
-
-import io.micrometer.core.instrument.Counter;
-import io.micrometer.core.instrument.Meter;
-import io.micrometer.core.instrument.MeterRegistry;
-import io.swagger.v3.oas.annotations.Operation;
-import io.swagger.v3.oas.annotations.Parameter;
-import io.swagger.v3.oas.annotations.tags.Tag;
-import jakarta.annotation.PostConstruct;
-import stirling.software.SPDF.config.StartupApplicationListener;
-import stirling.software.SPDF.model.ApplicationProperties;
-
-@RestController
-@RequestMapping("/api/v1")
-@Tag(name = "API", description = "Info APIs")
-public class MetricsController {
-
-
- @Autowired
- ApplicationProperties applicationProperties;
-
-
- private final MeterRegistry meterRegistry;
-
- private boolean metricsEnabled;
-
- @PostConstruct
- public void init() {
- Boolean metricsEnabled = applicationProperties.getMetrics().getEnabled();
- if(metricsEnabled == null)
- metricsEnabled = true;
- this.metricsEnabled = metricsEnabled;
- }
-
- public MetricsController(MeterRegistry meterRegistry) {
- this.meterRegistry = meterRegistry;
- }
-
- @GetMapping("/status")
- @Operation(summary = "Application status and version",
- description = "This endpoint returns the status of the application and its version number.")
- public ResponseEntity> getStatus() {
- if (!metricsEnabled) {
- return ResponseEntity.status(HttpStatus.FORBIDDEN).body("This endpoint is disabled.");
- }
-
- Map status = new HashMap<>();
- status.put("status", "UP");
- status.put("version", getClass().getPackage().getImplementationVersion());
- return ResponseEntity.ok(status);
- }
-
- @GetMapping("/loads")
- @Operation(summary = "GET request count",
- description = "This endpoint returns the total count of GET requests or the count of GET requests for a specific endpoint.")
- public ResponseEntity> getPageLoads(@RequestParam(required = false, name = "endpoint") @Parameter(description = "endpoint") Optional endpoint) {
- if (!metricsEnabled) {
- return ResponseEntity.status(HttpStatus.FORBIDDEN).body("This endpoint is disabled.");
- }
- try {
-
- double count = 0.0;
-
- for (Meter meter : meterRegistry.getMeters()) {
- if (meter.getId().getName().equals("http.requests")) {
- String method = meter.getId().getTag("method");
- if (method != null && method.equals("GET")) {
-
- if (endpoint.isPresent() && !endpoint.get().isBlank()) {
- if(!endpoint.get().startsWith("/")) {
- endpoint = Optional.of("/" + endpoint.get());
- }
- System.out.println("loads " + endpoint.get() + " vs " + meter.getId().getTag("uri"));
- if(endpoint.get().equals(meter.getId().getTag("uri"))){
- if (meter instanceof Counter) {
- count += ((Counter) meter).count();
- }
- }
- } else {
- if (meter instanceof Counter) {
- count += ((Counter) meter).count();
- }
- }
- }
- }
- }
-
- return ResponseEntity.ok(count);
- } catch (Exception e) {
- return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
- }
- }
-
- @GetMapping("/loads/all")
- @Operation(summary = "GET requests count for all endpoints",
- description = "This endpoint returns the count of GET requests for each endpoint.")
- public ResponseEntity> getAllEndpointLoads() {
- if (!metricsEnabled) {
- return ResponseEntity.status(HttpStatus.FORBIDDEN).body("This endpoint is disabled.");
- }
- try {
- Map counts = new HashMap<>();
-
- for (Meter meter : meterRegistry.getMeters()) {
- if (meter.getId().getName().equals("http.requests")) {
- String method = meter.getId().getTag("method");
- if (method != null && method.equals("GET")) {
- String uri = meter.getId().getTag("uri");
- if (uri != null) {
- double currentCount = counts.getOrDefault(uri, 0.0);
- if (meter instanceof Counter) {
- currentCount += ((Counter) meter).count();
- }
- counts.put(uri, currentCount);
- }
- }
- }
- }
-
- List results = counts.entrySet().stream()
- .map(entry -> new EndpointCount(entry.getKey(), entry.getValue()))
- .sorted(Comparator.comparing(EndpointCount::getCount).reversed())
- .collect(Collectors.toList());
-
- return ResponseEntity.ok(results);
- } catch (Exception e) {
- return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
- }
- }
-
- public class EndpointCount {
- private String endpoint;
- private double count;
-
- public EndpointCount(String endpoint, double count) {
- this.endpoint = endpoint;
- this.count = count;
- }
- public String getEndpoint() {
- return endpoint;
- }
- public void setEndpoint(String endpoint) {
- this.endpoint = endpoint;
- }
- public double getCount() {
- return count;
- }
- public void setCount(double count) {
- this.count = count;
- }
-
- }
-
-
- @GetMapping("/requests")
- @Operation(summary = "POST request count",
- description = "This endpoint returns the total count of POST requests or the count of POST requests for a specific endpoint.")
- public ResponseEntity> getTotalRequests(@RequestParam(required = false, name = "endpoint") @Parameter(description = "endpoint") Optional endpoint) {
- if (!metricsEnabled) {
- return ResponseEntity.status(HttpStatus.FORBIDDEN).body("This endpoint is disabled.");
- }
- try {
- double count = 0.0;
-
- for (Meter meter : meterRegistry.getMeters()) {
- if (meter.getId().getName().equals("http.requests")) {
- String method = meter.getId().getTag("method");
- if (method != null && method.equals("POST")) {
- if (endpoint.isPresent() && !endpoint.get().isBlank()) {
- if (!endpoint.get().startsWith("/")) {
- endpoint = Optional.of("/" + endpoint.get());
- }
- if (endpoint.get().equals(meter.getId().getTag("uri"))) {
- if (meter instanceof Counter) {
- count += ((Counter) meter).count();
- }
- }
- } else {
- if (meter instanceof Counter) {
- count += ((Counter) meter).count();
- }
- }
- }
- }
- }
- return ResponseEntity.ok(count);
- } catch (Exception e) {
- return ResponseEntity.ok(-1);
- }
- }
-
-
- @GetMapping("/requests/all")
- @Operation(summary = "POST requests count for all endpoints",
- description = "This endpoint returns the count of POST requests for each endpoint.")
- public ResponseEntity> getAllPostRequests() {
- if (!metricsEnabled) {
- return ResponseEntity.status(HttpStatus.FORBIDDEN).body("This endpoint is disabled.");
- }
- try {
- Map counts = new HashMap<>();
-
- for (Meter meter : meterRegistry.getMeters()) {
- if (meter.getId().getName().equals("http.requests")) {
- String method = meter.getId().getTag("method");
- if (method != null && method.equals("POST")) {
- String uri = meter.getId().getTag("uri");
- if (uri != null) {
- double currentCount = counts.getOrDefault(uri, 0.0);
- if (meter instanceof Counter) {
- currentCount += ((Counter) meter).count();
- }
- counts.put(uri, currentCount);
- }
- }
- }
- }
-
- List results = counts.entrySet().stream()
- .map(entry -> new EndpointCount(entry.getKey(), entry.getValue()))
- .sorted(Comparator.comparing(EndpointCount::getCount).reversed())
- .collect(Collectors.toList());
-
- return ResponseEntity.ok(results);
- } catch (Exception e) {
- return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
- }
- }
-
-
- @GetMapping("/uptime")
- public ResponseEntity> getUptime() {
- if (!metricsEnabled) {
- return ResponseEntity.status(HttpStatus.FORBIDDEN).body("This endpoint is disabled.");
- }
-
- LocalDateTime now = LocalDateTime.now();
- Duration uptime = Duration.between(StartupApplicationListener.startTime, now);
- return ResponseEntity.ok(formatDuration(uptime));
- }
-
- private String formatDuration(Duration duration) {
- long days = duration.toDays();
- long hours = duration.toHoursPart();
- long minutes = duration.toMinutesPart();
- long seconds = duration.toSecondsPart();
- return String.format("%dd %dh %dm %ds", days, hours, minutes, seconds);
- }
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/web/OtherWebController.java b/src/main/java/stirling/software/SPDF/controller/web/OtherWebController.java
deleted file mode 100644
index 827523cb..00000000
--- a/src/main/java/stirling/software/SPDF/controller/web/OtherWebController.java
+++ /dev/null
@@ -1,147 +0,0 @@
-package stirling.software.SPDF.controller.web;
-
-import java.io.File;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.stream.Collectors;
-
-import org.springframework.stereotype.Controller;
-import org.springframework.ui.Model;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.servlet.ModelAndView;
-
-import io.swagger.v3.oas.annotations.Hidden;
-import io.swagger.v3.oas.annotations.tags.Tag;
-
-@Controller
-@Tag(name = "Misc", description = "Miscellaneous APIs")
-public class OtherWebController {
- @GetMapping("/compress-pdf")
- @Hidden
- public String compressPdfForm(Model model) {
- model.addAttribute("currentPage", "compress-pdf");
- return "misc/compress-pdf";
- }
-
- @GetMapping("/extract-image-scans")
- @Hidden
- public ModelAndView extractImageScansForm() {
- ModelAndView modelAndView = new ModelAndView("misc/extract-image-scans");
- modelAndView.addObject("currentPage", "extract-image-scans");
- return modelAndView;
- }
-
- @GetMapping("/show-javascript")
- @Hidden
- public String extractJavascriptForm(Model model) {
- model.addAttribute("currentPage", "show-javascript");
- return "misc/show-javascript";
- }
-
-
- @GetMapping("/add-page-numbers")
- @Hidden
- public String addPageNumbersForm(Model model) {
- model.addAttribute("currentPage", "add-page-numbers");
- return "misc/add-page-numbers";
- }
-
- @GetMapping("/extract-images")
- @Hidden
- public String extractImagesForm(Model model) {
- model.addAttribute("currentPage", "extract-images");
- return "misc/extract-images";
- }
-
- @GetMapping("/flatten")
- @Hidden
- public String flattenForm(Model model) {
- model.addAttribute("currentPage", "flatten");
- return "misc/flatten";
- }
-
-
-
- @GetMapping("/change-metadata")
- @Hidden
- public String addWatermarkForm(Model model) {
- model.addAttribute("currentPage", "change-metadata");
- return "misc/change-metadata";
- }
-
- @GetMapping("/compare")
- @Hidden
- public String compareForm(Model model) {
- model.addAttribute("currentPage", "compare");
- return "misc/compare";
- }
-
- public List getAvailableTesseractLanguages() {
- String tessdataDir = "/usr/share/tesseract-ocr/4.00/tessdata";
- File[] files = new File(tessdataDir).listFiles();
- if (files == null) {
- return Collections.emptyList();
- }
- return Arrays.stream(files).filter(file -> file.getName().endsWith(".traineddata")).map(file -> file.getName().replace(".traineddata", ""))
- .filter(lang -> !lang.equalsIgnoreCase("osd")).collect(Collectors.toList());
- }
-
- @GetMapping("/ocr-pdf")
- @Hidden
- public ModelAndView ocrPdfPage() {
- ModelAndView modelAndView = new ModelAndView("misc/ocr-pdf");
- List languages = getAvailableTesseractLanguages();
- Collections.sort(languages);
- modelAndView.addObject("languages", languages);
- modelAndView.addObject("currentPage", "ocr-pdf");
- return modelAndView;
- }
-
-
- @GetMapping("/add-image")
- @Hidden
- public String overlayImage(Model model) {
- model.addAttribute("currentPage", "add-image");
- return "misc/add-image";
- }
-
- @GetMapping("/adjust-contrast")
- @Hidden
- public String contrast(Model model) {
- model.addAttribute("currentPage", "adjust-contrast");
- return "misc/adjust-contrast";
- }
-
- @GetMapping("/repair")
- @Hidden
- public String repairForm(Model model) {
- model.addAttribute("currentPage", "repair");
- return "misc/repair";
- }
-
- @GetMapping("/remove-blanks")
- @Hidden
- public String removeBlanksForm(Model model) {
- model.addAttribute("currentPage", "remove-blanks");
- return "misc/remove-blanks";
- }
-
-
- @GetMapping("/auto-crop")
- @Hidden
- public String autoCropForm(Model model) {
- model.addAttribute("currentPage", "auto-crop");
- return "misc/auto-crop";
- }
-
- @GetMapping("/auto-rename")
- @Hidden
- public String autoRenameForm(Model model) {
- model.addAttribute("currentPage", "auto-rename");
- return "misc/auto-rename";
- }
-
-
-
-}
diff --git a/src/main/java/stirling/software/SPDF/controller/web/SecurityWebController.java b/src/main/java/stirling/software/SPDF/controller/web/SecurityWebController.java
deleted file mode 100644
index 2cbf245f..00000000
--- a/src/main/java/stirling/software/SPDF/controller/web/SecurityWebController.java
+++ /dev/null
@@ -1,68 +0,0 @@
-package stirling.software.SPDF.controller.web;
-
-import org.springframework.stereotype.Controller;
-import org.springframework.ui.Model;
-import org.springframework.web.bind.annotation.GetMapping;
-
-import io.swagger.v3.oas.annotations.Hidden;
-import io.swagger.v3.oas.annotations.tags.Tag;
-
-@Controller
-@Tag(name = "Security", description = "Security APIs")
-public class SecurityWebController {
-
- @GetMapping("/auto-redact")
- @Hidden
- public String autoRedactForm(Model model) {
- model.addAttribute("currentPage", "auto-redact");
- return "security/auto-redact";
- }
-
- @GetMapping("/add-password")
- @Hidden
- public String addPasswordForm(Model model) {
- model.addAttribute("currentPage", "add-password");
- return "security/add-password";
- }
- @GetMapping("/change-permissions")
- @Hidden
- public String permissionsForm(Model model) {
- model.addAttribute("currentPage", "change-permissions");
- return "security/change-permissions";
- }
-
- @GetMapping("/remove-password")
- @Hidden
- public String removePasswordForm(Model model) {
- model.addAttribute("currentPage", "remove-password");
- return "security/remove-password";
- }
-
- @GetMapping("/add-watermark")
- @Hidden
- public String addWatermarkForm(Model model) {
- model.addAttribute("currentPage", "add-watermark");
- return "security/add-watermark";
- }
-
- @GetMapping("/cert-sign")
- @Hidden
- public String certSignForm(Model model) {
- model.addAttribute("currentPage", "cert-sign");
- return "security/cert-sign";
- }
-
- @GetMapping("/sanitize-pdf")
- @Hidden
- public String sanitizeForm(Model model) {
- model.addAttribute("currentPage", "sanitize-pdf");
- return "security/sanitize-pdf";
- }
-
- @GetMapping("/get-info-on-pdf")
- @Hidden
- public String getInfo(Model model) {
- model.addAttribute("currentPage", "get-info-on-pdf");
- return "security/get-info-on-pdf";
- }
-}
diff --git a/src/main/java/stirling/software/SPDF/model/ApiKeyAuthenticationToken.java b/src/main/java/stirling/software/SPDF/model/ApiKeyAuthenticationToken.java
deleted file mode 100644
index 54b61c1b..00000000
--- a/src/main/java/stirling/software/SPDF/model/ApiKeyAuthenticationToken.java
+++ /dev/null
@@ -1,49 +0,0 @@
-package stirling.software.SPDF.model;
-import java.util.Collection;
-
-import org.springframework.security.authentication.AbstractAuthenticationToken;
-import org.springframework.security.core.GrantedAuthority;
-
-public class ApiKeyAuthenticationToken extends AbstractAuthenticationToken {
-
- private final Object principal;
- private Object credentials;
-
- public ApiKeyAuthenticationToken(String apiKey) {
- super(null);
- this.principal = null;
- this.credentials = apiKey;
- setAuthenticated(false);
- }
-
- public ApiKeyAuthenticationToken(Object principal, String apiKey, Collection extends GrantedAuthority> authorities) {
- super(authorities);
- this.principal = principal; // principal can be a UserDetails object
- this.credentials = apiKey;
- super.setAuthenticated(true); // this authentication is trusted
- }
-
- @Override
- public Object getCredentials() {
- return credentials;
- }
-
- @Override
- public Object getPrincipal() {
- return principal;
- }
-
- @Override
- public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
- if (isAuthenticated) {
- throw new IllegalArgumentException("Cannot set this token to trusted. Use constructor which takes a GrantedAuthority list instead.");
- }
- super.setAuthenticated(false);
- }
-
- @Override
- public void eraseCredentials() {
- super.eraseCredentials();
- credentials = null;
- }
-}
diff --git a/src/main/java/stirling/software/SPDF/model/ApplicationProperties.java b/src/main/java/stirling/software/SPDF/model/ApplicationProperties.java
deleted file mode 100644
index dc068779..00000000
--- a/src/main/java/stirling/software/SPDF/model/ApplicationProperties.java
+++ /dev/null
@@ -1,335 +0,0 @@
-package stirling.software.SPDF.model;
-
-import java.util.List;
-
-import org.springframework.boot.context.properties.ConfigurationProperties;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.PropertySource;
-
-import stirling.software.SPDF.config.YamlPropertySourceFactory;
-
-@Configuration
-@ConfigurationProperties(prefix = "")
-@PropertySource(value = "file:./configs/settings.yml", factory = YamlPropertySourceFactory.class)
-public class ApplicationProperties {
- private Security security;
- private System system;
- private Ui ui;
- private Endpoints endpoints;
- private Metrics metrics;
- private AutomaticallyGenerated automaticallyGenerated;
- private AutoPipeline autoPipeline;
-
- public AutoPipeline getAutoPipeline() {
- return autoPipeline != null ? autoPipeline : new AutoPipeline();
- }
-
- public void setAutoPipeline(AutoPipeline autoPipeline) {
- this.autoPipeline = autoPipeline;
- }
-
- public Security getSecurity() {
- return security != null ? security : new Security();
- }
-
- public void setSecurity(Security security) {
- this.security = security;
- }
-
- public System getSystem() {
- return system != null ? system : new System();
- }
-
- public void setSystem(System system) {
- this.system = system;
- }
-
- public Ui getUi() {
- return ui != null ? ui : new Ui();
- }
-
- public void setUi(Ui ui) {
- this.ui = ui;
- }
-
- public Endpoints getEndpoints() {
- return endpoints != null ? endpoints : new Endpoints();
- }
-
- public void setEndpoints(Endpoints endpoints) {
- this.endpoints = endpoints;
- }
-
- public Metrics getMetrics() {
- return metrics != null ? metrics : new Metrics();
- }
-
- public void setMetrics(Metrics metrics) {
- this.metrics = metrics;
- }
-
- public AutomaticallyGenerated getAutomaticallyGenerated() {
- return automaticallyGenerated != null ? automaticallyGenerated : new AutomaticallyGenerated();
- }
-
- public void setAutomaticallyGenerated(AutomaticallyGenerated automaticallyGenerated) {
- this.automaticallyGenerated = automaticallyGenerated;
- }
-
- @Override
- public String toString() {
- return "ApplicationProperties [security=" + security + ", system=" + system + ", ui=" + ui + ", endpoints="
- + endpoints + ", metrics=" + metrics + ", automaticallyGenerated=" + automaticallyGenerated
- + ", autoPipeline=" + autoPipeline + "]";
- }
-
- public static class AutoPipeline {
- private String outputFolder;
-
- public String getOutputFolder() {
- return outputFolder;
- }
-
- public void setOutputFolder(String outputFolder) {
- this.outputFolder = outputFolder;
- }
-
- @Override
- public String toString() {
- return "AutoPipeline [outputFolder=" + outputFolder + "]";
- }
-
-
-
- }
- public static class Security {
- private Boolean enableLogin;
- private Boolean csrfDisabled;
- private InitialLogin initialLogin;
-
- public InitialLogin getInitialLogin() {
- return initialLogin != null ? initialLogin : new InitialLogin();
- }
-
- public void setInitialLogin(InitialLogin initialLogin) {
- this.initialLogin = initialLogin;
- }
-
- public Boolean getEnableLogin() {
- return enableLogin;
- }
-
- public void setEnableLogin(Boolean enableLogin) {
- this.enableLogin = enableLogin;
- }
-
- public Boolean getCsrfDisabled() {
- return csrfDisabled;
- }
-
- public void setCsrfDisabled(Boolean csrfDisabled) {
- this.csrfDisabled = csrfDisabled;
- }
-
-
- @Override
- public String toString() {
- return "Security [enableLogin=" + enableLogin + ", initialLogin=" + initialLogin + ", csrfDisabled="
- + csrfDisabled + "]";
- }
-
- public static class InitialLogin {
-
- private String username;
- private String password;
-
- public String getUsername() {
- return username;
- }
-
- public void setUsername(String username) {
- this.username = username;
- }
-
- public String getPassword() {
- return password;
- }
-
- public void setPassword(String password) {
- this.password = password;
- }
-
- @Override
- public String toString() {
- return "InitialLogin [username=" + username + ", password=" + (password != null && !password.isEmpty() ? "MASKED" : "NULL") + "]";
- }
-
-
-
- }
- }
-
- public static class System {
- private String defaultLocale;
- private Boolean googlevisibility;
- private String rootURIPath;
- private String customStaticFilePath;
- private Integer maxFileSize;
-
- public String getDefaultLocale() {
- return defaultLocale;
- }
-
- public void setDefaultLocale(String defaultLocale) {
- this.defaultLocale = defaultLocale;
- }
-
- public Boolean getGooglevisibility() {
- return googlevisibility;
- }
-
- public void setGooglevisibility(Boolean googlevisibility) {
- this.googlevisibility = googlevisibility;
- }
-
- public String getRootURIPath() {
- return rootURIPath;
- }
-
- public void setRootURIPath(String rootURIPath) {
- this.rootURIPath = rootURIPath;
- }
-
- public String getCustomStaticFilePath() {
- return customStaticFilePath;
- }
-
- public void setCustomStaticFilePath(String customStaticFilePath) {
- this.customStaticFilePath = customStaticFilePath;
- }
-
- public Integer getMaxFileSize() {
- return maxFileSize;
- }
-
- public void setMaxFileSize(Integer maxFileSize) {
- this.maxFileSize = maxFileSize;
- }
-
- @Override
- public String toString() {
- return "System [defaultLocale=" + defaultLocale + ", googlevisibility=" + googlevisibility + ", rootURIPath="
- + rootURIPath + ", customStaticFilePath=" + customStaticFilePath + ", maxFileSize=" + maxFileSize
- + "]";
- }
-
-
- }
-
- public static class Ui {
- private String appName;
- private String homeDescription;
- private String appNameNavbar;
-
- public String getAppName() {
- if(appName != null && appName.trim().length() == 0)
- return null;
- return appName;
- }
-
- public void setAppName(String appName) {
- this.appName = appName;
- }
-
- public String getHomeDescription() {
- if(homeDescription != null && homeDescription.trim().length() == 0)
- return null;
- return homeDescription;
- }
-
- public void setHomeDescription(String homeDescription) {
- this.homeDescription = homeDescription;
- }
-
- public String getAppNameNavbar() {
- if(appNameNavbar != null && appNameNavbar.trim().length() == 0)
- return null;
- return appNameNavbar;
- }
-
- public void setAppNameNavbar(String appNameNavbar) {
- this.appNameNavbar = appNameNavbar;
- }
-
- @Override
- public String toString() {
- return "UserInterface [appName=" + appName + ", homeDescription=" + homeDescription + ", appNameNavbar=" + appNameNavbar + "]";
- }
- }
-
-
- public static class Endpoints {
- private List toRemove;
- private List groupsToRemove;
-
- public List getToRemove() {
- return toRemove;
- }
-
- public void setToRemove(List toRemove) {
- this.toRemove = toRemove;
- }
-
- public List getGroupsToRemove() {
- return groupsToRemove;
- }
-
- public void setGroupsToRemove(List groupsToRemove) {
- this.groupsToRemove = groupsToRemove;
- }
-
- @Override
- public String toString() {
- return "Endpoints [toRemove=" + toRemove + ", groupsToRemove=" + groupsToRemove + "]";
- }
-
-
- }
-
- public static class Metrics {
- private Boolean enabled;
-
- public Boolean getEnabled() {
- return enabled;
- }
-
- public void setEnabled(Boolean enabled) {
- this.enabled = enabled;
- }
-
- @Override
- public String toString() {
- return "Metrics [enabled=" + enabled + "]";
- }
-
-
- }
-
- public static class AutomaticallyGenerated {
- private String key;
-
- public String getKey() {
- return key;
- }
-
- public void setKey(String key) {
- this.key = key;
- }
-
- @Override
- public String toString() {
- return "AutomaticallyGenerated [key=" + (key != null && !key.isEmpty() ? "MASKED" : "NULL") + "]";
- }
-
- }
-}
diff --git a/src/main/java/stirling/software/SPDF/model/Authority.java b/src/main/java/stirling/software/SPDF/model/Authority.java
deleted file mode 100644
index 8be853ea..00000000
--- a/src/main/java/stirling/software/SPDF/model/Authority.java
+++ /dev/null
@@ -1,64 +0,0 @@
-package stirling.software.SPDF.model;
-
-import jakarta.persistence.Column;
-import jakarta.persistence.Entity;
-import jakarta.persistence.GeneratedValue;
-import jakarta.persistence.GenerationType;
-import jakarta.persistence.Id;
-import jakarta.persistence.JoinColumn;
-import jakarta.persistence.ManyToOne;
-import jakarta.persistence.Table;
-
-@Entity
-@Table(name = "authorities")
-public class Authority {
-
- public Authority() {
-
- }
-
-
- public Authority(String authority, User user) {
- this.authority = authority;
- this.user = user;
- user.getAuthorities().add(this);
- }
-
-
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Long id;
-
- @Column(name = "authority")
- private String authority;
-
- @ManyToOne
- @JoinColumn(name = "user_id")
- private User user;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getAuthority() {
- return authority;
- }
-
- public void setAuthority(String authority) {
- this.authority = authority;
- }
-
- public User getUser() {
- return user;
- }
-
- public void setUser(User user) {
- this.user = user;
- }
-
-
-}
diff --git a/src/main/java/stirling/software/SPDF/model/PDFText.java b/src/main/java/stirling/software/SPDF/model/PDFText.java
deleted file mode 100644
index 9a4909d0..00000000
--- a/src/main/java/stirling/software/SPDF/model/PDFText.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package stirling.software.SPDF.model;
-public class PDFText {
- private final int pageIndex;
- private final float x1;
- private final float y1;
- private final float x2;
- private final float y2;
- private final String text;
-
- public PDFText(int pageIndex, float x1, float y1, float x2, float y2, String text) {
- this.pageIndex = pageIndex;
- this.x1 = x1;
- this.y1 = y1;
- this.x2 = x2;
- this.y2 = y2;
- this.text = text;
- }
-
- public int getPageIndex() {
- return pageIndex;
- }
-
- public float getX1() {
- return x1;
- }
-
- public float getY1() {
- return y1;
- }
-
- public float getX2() {
- return x2;
- }
-
- public float getY2() {
- return y2;
- }
-
- public String getText() {
- return text;
- }
-}
\ No newline at end of file
diff --git a/src/main/java/stirling/software/SPDF/model/PersistentLogin.java b/src/main/java/stirling/software/SPDF/model/PersistentLogin.java
deleted file mode 100644
index 0747c1eb..00000000
--- a/src/main/java/stirling/software/SPDF/model/PersistentLogin.java
+++ /dev/null
@@ -1,61 +0,0 @@
-package stirling.software.SPDF.model;
-
-import java.util.Date;
-
-import jakarta.persistence.Column;
-import jakarta.persistence.Entity;
-import jakarta.persistence.Id;
-import jakarta.persistence.Table;
-
-@Entity
-@Table(name = "persistent_logins")
-public class PersistentLogin {
-
- @Id
- @Column(name = "series")
- private String series;
-
- @Column(name = "username", length = 64, nullable = false)
- private String username;
-
- @Column(name = "token", length = 64, nullable = false)
- private String token;
-
- @Column(name = "last_used", nullable = false)
- private Date lastUsed;
-
- public String getSeries() {
- return series;
- }
-
- public void setSeries(String series) {
- this.series = series;
- }
-
- public String getUsername() {
- return username;
- }
-
- public void setUsername(String username) {
- this.username = username;
- }
-
- public String getToken() {
- return token;
- }
-
- public void setToken(String token) {
- this.token = token;
- }
-
- public Date getLastUsed() {
- return lastUsed;
- }
-
- public void setLastUsed(Date lastUsed) {
- this.lastUsed = lastUsed;
- }
-
-
- // Getters, setters, etc.
-}
diff --git a/src/main/java/stirling/software/SPDF/model/PipelineConfig.java b/src/main/java/stirling/software/SPDF/model/PipelineConfig.java
deleted file mode 100644
index 77ef7a05..00000000
--- a/src/main/java/stirling/software/SPDF/model/PipelineConfig.java
+++ /dev/null
@@ -1,51 +0,0 @@
-package stirling.software.SPDF.model;
-import java.util.List;
-
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-public class PipelineConfig {
- private String name;
-
- @JsonProperty("pipeline")
- private List operations;
-
- private String outputDir;
-
- @JsonProperty("outputFileName")
- private String outputPattern;
-
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public List getOperations() {
- return operations;
- }
-
- public void setOperations(List operations) {
- this.operations = operations;
- }
-
- public String getOutputDir() {
- return outputDir;
- }
-
- public void setOutputDir(String outputDir) {
- this.outputDir = outputDir;
- }
-
- public String getOutputPattern() {
- return outputPattern;
- }
-
- public void setOutputPattern(String outputPattern) {
- this.outputPattern = outputPattern;
- }
-
-
-}
diff --git a/src/main/java/stirling/software/SPDF/model/PipelineOperation.java b/src/main/java/stirling/software/SPDF/model/PipelineOperation.java
deleted file mode 100644
index 10c27bfc..00000000
--- a/src/main/java/stirling/software/SPDF/model/PipelineOperation.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package stirling.software.SPDF.model;
-
-import java.util.Map;
-
-public class PipelineOperation {
- private String operation;
- private Map parameters;
-
-
- public String getOperation() {
- return operation;
- }
-
- public void setOperation(String operation) {
- this.operation = operation;
- }
-
- public Map getParameters() {
- return parameters;
- }
-
- public void setParameters(Map parameters) {
- this.parameters = parameters;
- }
-
- @Override
- public String toString() {
- return "PipelineOperation [operation=" + operation + ", parameters=" + parameters + "]";
- }
-
-
- }
\ No newline at end of file
diff --git a/src/main/java/stirling/software/SPDF/model/Role.java b/src/main/java/stirling/software/SPDF/model/Role.java
deleted file mode 100644
index 1b775de0..00000000
--- a/src/main/java/stirling/software/SPDF/model/Role.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package stirling.software.SPDF.model;
-public enum Role {
-
- // Unlimited access
- ADMIN("ROLE_ADMIN", Integer.MAX_VALUE, Integer.MAX_VALUE),
-
- // Unlimited access
- USER("ROLE_USER", Integer.MAX_VALUE, Integer.MAX_VALUE),
-
- // 40 API calls Per Day, 40 web calls
- LIMITED_API_USER("ROLE_LIMITED_API_USER", 40, 40),
-
- // 20 API calls Per Day, 20 web calls
- EXTRA_LIMITED_API_USER("ROLE_EXTRA_LIMITED_API_USER", 20, 20),
-
- // 0 API calls per day and 20 web calls
- WEB_ONLY_USER("ROLE_WEB_ONLY_USER", 0, 20);
-
- private final String roleId;
- private final int apiCallsPerDay;
- private final int webCallsPerDay;
-
- Role(String roleId, int apiCallsPerDay, int webCallsPerDay) {
- this.roleId = roleId;
- this.apiCallsPerDay = apiCallsPerDay;
- this.webCallsPerDay = webCallsPerDay;
- }
-
- public String getRoleId() {
- return roleId;
- }
-
- public int getApiCallsPerDay() {
- return apiCallsPerDay;
- }
-
- public int getWebCallsPerDay() {
- return webCallsPerDay;
- }
-
- public static Role fromString(String roleId) {
- for (Role role : Role.values()) {
- if (role.getRoleId().equalsIgnoreCase(roleId)) {
- return role;
- }
- }
- throw new IllegalArgumentException("No Role defined for id: " + roleId);
- }
-
-}
diff --git a/src/main/java/stirling/software/SPDF/model/SortTypes.java b/src/main/java/stirling/software/SPDF/model/SortTypes.java
deleted file mode 100644
index 21181cfa..00000000
--- a/src/main/java/stirling/software/SPDF/model/SortTypes.java
+++ /dev/null
@@ -1,4 +0,0 @@
-package stirling.software.SPDF.model;
-public enum SortTypes {
- REVERSE_ORDER, DUPLEX_SORT, BOOKLET_SORT, SIDE_STITCH_BOOKLET_SORT, ODD_EVEN_SPLIT, REMOVE_FIRST, REMOVE_LAST, REMOVE_FIRST_AND_LAST,
-}
\ No newline at end of file
diff --git a/src/main/java/stirling/software/SPDF/model/User.java b/src/main/java/stirling/software/SPDF/model/User.java
deleted file mode 100644
index f771a821..00000000
--- a/src/main/java/stirling/software/SPDF/model/User.java
+++ /dev/null
@@ -1,134 +0,0 @@
-package stirling.software.SPDF.model;
-
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import java.util.stream.Collectors;
-
-import jakarta.persistence.CascadeType;
-import jakarta.persistence.CollectionTable;
-import jakarta.persistence.Column;
-import jakarta.persistence.ElementCollection;
-import jakarta.persistence.Entity;
-import jakarta.persistence.FetchType;
-import jakarta.persistence.GeneratedValue;
-import jakarta.persistence.GenerationType;
-import jakarta.persistence.Id;
-import jakarta.persistence.JoinColumn;
-import jakarta.persistence.MapKeyColumn;
-import jakarta.persistence.OneToMany;
-import jakarta.persistence.Table;
-@Entity
-@Table(name = "users")
-public class User {
-
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- @Column(name = "user_id")
- private Long id;
-
- @Column(name = "username", unique = true)
- private String username;
-
- @Column(name = "password")
- private String password;
-
- @Column(name = "apiKey")
- private String apiKey;
-
- @Column(name = "enabled")
- private boolean enabled;
-
- @Column(name = "isFirstLogin")
- private Boolean isFirstLogin = false;
-
- @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "user")
- private Set authorities = new HashSet<>();
-
- @ElementCollection
- @MapKeyColumn(name = "setting_key")
- @Column(name = "setting_value")
- @CollectionTable(name = "user_settings", joinColumns = @JoinColumn(name = "user_id"))
- private Map settings = new HashMap<>(); // Key-value pairs of settings.
-
-
- public boolean isFirstLogin() {
- return isFirstLogin != null && isFirstLogin;
- }
-
- public void setFirstLogin(boolean isFirstLogin) {
- this.isFirstLogin = isFirstLogin;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getApiKey() {
- return apiKey;
- }
-
- public void setApiKey(String apiKey) {
- this.apiKey = apiKey;
- }
-
- public Map getSettings() {
- return settings;
- }
-
- public void setSettings(Map settings) {
- this.settings = settings;
- }
-
- public String getUsername() {
- return username;
- }
-
- public void setUsername(String username) {
- this.username = username;
- }
-
- public String getPassword() {
- return password;
- }
-
- public void setPassword(String password) {
- this.password = password;
- }
-
- public boolean isEnabled() {
- return enabled;
- }
-
- public void setEnabled(boolean enabled) {
- this.enabled = enabled;
- }
-
- public Set getAuthorities() {
- return authorities;
- }
-
- public void setAuthorities(Set authorities) {
- this.authorities = authorities;
- }
-
- public void addAuthorities(Set authorities) {
- this.authorities.addAll(authorities);
- }
- public void addAuthority(Authority authorities) {
- this.authorities.add(authorities);
- }
-
- public String getRolesAsString() {
- return this.authorities.stream()
- .map(Authority::getAuthority)
- .collect(Collectors.joining(", "));
- }
-
-
-}
diff --git a/src/main/java/stirling/software/SPDF/model/api/GeneralFile.java b/src/main/java/stirling/software/SPDF/model/api/GeneralFile.java
deleted file mode 100644
index 441d904a..00000000
--- a/src/main/java/stirling/software/SPDF/model/api/GeneralFile.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package stirling.software.SPDF.model.api;
-
-import org.springframework.web.multipart.MultipartFile;
-
-import io.swagger.v3.oas.annotations.media.Schema;
-import lombok.Data;
-import lombok.EqualsAndHashCode;
-import lombok.NoArgsConstructor;
-
-@Data
-@EqualsAndHashCode
-@NoArgsConstructor
-public class GeneralFile {
-
- @Schema(description = "The input file")
- private MultipartFile fileInput;
-}
diff --git a/src/main/java/stirling/software/SPDF/model/api/HandleDataRequest.java b/src/main/java/stirling/software/SPDF/model/api/HandleDataRequest.java
deleted file mode 100644
index 1d7a8afe..00000000
--- a/src/main/java/stirling/software/SPDF/model/api/HandleDataRequest.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package stirling.software.SPDF.model.api;
-
-import org.springframework.web.multipart.MultipartFile;
-
-import io.swagger.v3.oas.annotations.media.Schema;
-import lombok.Data;
-import lombok.EqualsAndHashCode;
-import lombok.NoArgsConstructor;
-
-@Data
-@NoArgsConstructor
-@EqualsAndHashCode
-public class HandleDataRequest {
-
- @Schema(description = "The input files")
- private MultipartFile[] fileInputs;
-
- @Schema(description = "JSON String")
- private String jsonString;
-}
diff --git a/src/main/java/stirling/software/SPDF/model/api/ImageFile.java b/src/main/java/stirling/software/SPDF/model/api/ImageFile.java
deleted file mode 100644
index 02079843..00000000
--- a/src/main/java/stirling/software/SPDF/model/api/ImageFile.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package stirling.software.SPDF.model.api;
-
-import org.springframework.web.multipart.MultipartFile;
-
-import io.swagger.v3.oas.annotations.media.Schema;
-import lombok.Data;
-import lombok.EqualsAndHashCode;
-import lombok.NoArgsConstructor;
-
-@Data
-@NoArgsConstructor
-@EqualsAndHashCode
-public class ImageFile {
- @Schema(description = "The input image file")
- private MultipartFile fileInput;
-}
diff --git a/src/main/java/stirling/software/SPDF/model/api/MultiplePDFFiles.java b/src/main/java/stirling/software/SPDF/model/api/MultiplePDFFiles.java
deleted file mode 100644
index 937a4265..00000000
--- a/src/main/java/stirling/software/SPDF/model/api/MultiplePDFFiles.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package stirling.software.SPDF.model.api;
-
-import org.springframework.web.multipart.MultipartFile;
-
-import io.swagger.v3.oas.annotations.media.Schema;
-import lombok.Data;
-import lombok.EqualsAndHashCode;
-import lombok.NoArgsConstructor;
-@Data
-@NoArgsConstructor
-@EqualsAndHashCode
-public class MultiplePDFFiles {
- @Schema(description = "The input PDF files", type = "array", format = "binary")
- private MultipartFile[] fileInput;
-}
diff --git a/src/main/java/stirling/software/SPDF/model/api/PDFComparison.java b/src/main/java/stirling/software/SPDF/model/api/PDFComparison.java
deleted file mode 100644
index 1f902d88..00000000
--- a/src/main/java/stirling/software/SPDF/model/api/PDFComparison.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package stirling.software.SPDF.model.api;
-
-import io.swagger.v3.oas.annotations.media.Schema;
-import lombok.Data;
-import lombok.EqualsAndHashCode;
-import lombok.NoArgsConstructor;
-@Data
-@NoArgsConstructor
-@EqualsAndHashCode(callSuper=true)
-public class PDFComparison extends PDFFile {
-
- @Schema(description = "The comparison type, accepts Greater, Equal, Less than", allowableValues = {
- "Greater", "Equal", "Less" })
- private String comparator;
-
-}
diff --git a/src/main/java/stirling/software/SPDF/model/api/PDFComparisonAndCount.java b/src/main/java/stirling/software/SPDF/model/api/PDFComparisonAndCount.java
deleted file mode 100644
index 14462f0a..00000000
--- a/src/main/java/stirling/software/SPDF/model/api/PDFComparisonAndCount.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package stirling.software.SPDF.model.api;
-
-import io.swagger.v3.oas.annotations.media.Schema;
-import lombok.Data;
-import lombok.EqualsAndHashCode;
-import lombok.NoArgsConstructor;
-@Data
-@NoArgsConstructor
-@EqualsAndHashCode(callSuper=true)
-public class PDFComparisonAndCount extends PDFComparison {
- @Schema(description = "Count")
- private String pageCount;
-
-
-}
diff --git a/src/main/java/stirling/software/SPDF/model/api/PDFFile.java b/src/main/java/stirling/software/SPDF/model/api/PDFFile.java
deleted file mode 100644
index 378b3c03..00000000
--- a/src/main/java/stirling/software/SPDF/model/api/PDFFile.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package stirling.software.SPDF.model.api;
-
-import org.springframework.web.multipart.MultipartFile;
-
-import io.swagger.v3.oas.annotations.media.Schema;
-import lombok.Data;
-import lombok.EqualsAndHashCode;
-@Data
-@EqualsAndHashCode
-public class PDFFile {
- @Schema(description = "The input PDF file")
- private MultipartFile fileInput;
-}
diff --git a/src/main/java/stirling/software/SPDF/model/api/PDFWithImageFormatRequest.java b/src/main/java/stirling/software/SPDF/model/api/PDFWithImageFormatRequest.java
deleted file mode 100644
index aa8fe08b..00000000
--- a/src/main/java/stirling/software/SPDF/model/api/PDFWithImageFormatRequest.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package stirling.software.SPDF.model.api;
-
-import io.swagger.v3.oas.annotations.media.Schema;
-import lombok.Data;
-import lombok.EqualsAndHashCode;
-
-@Data
-@EqualsAndHashCode(callSuper=true)
-public class PDFWithImageFormatRequest extends PDFFile {
-
- @Schema(description = "The output image format e.g., 'png', 'jpeg', or 'gif'",
- allowableValues = { "png", "jpeg", "gif" })
- private String format;
-}
diff --git a/src/main/java/stirling/software/SPDF/model/api/PDFWithPageNums.java b/src/main/java/stirling/software/SPDF/model/api/PDFWithPageNums.java
deleted file mode 100644
index d53d8d12..00000000
--- a/src/main/java/stirling/software/SPDF/model/api/PDFWithPageNums.java
+++ /dev/null
@@ -1,39 +0,0 @@
-package stirling.software.SPDF.model.api;
-
-import java.io.IOException;
-import java.util.List;
-
-import org.apache.pdfbox.pdmodel.PDDocument;
-
-import io.swagger.v3.oas.annotations.media.Schema;
-import lombok.Data;
-import lombok.EqualsAndHashCode;
-import lombok.NoArgsConstructor;
-import stirling.software.SPDF.utils.GeneralUtils;
-@Data
-@NoArgsConstructor
-@EqualsAndHashCode(callSuper=true)
-public class PDFWithPageNums extends PDFFile {
-
- @Schema(description = "The pages to select, Supports ranges (e.g., '1,3,5-9'), or 'all' or functions in the format 'an+b' where 'a' is the multiplier of the page number 'n', and 'b' is a constant (e.g., '2n+1', '3n', '6n-5')\"")
- private String pageNumbers;
-
-
- public List