Compare commits

...

74 Commits

Author SHA1 Message Date
Anthony Stirling
e5a7a0631b Merge pull request #360 from Frooodle/itextRemoval
Itext removal password enhancement and others
2023-09-14 14:36:10 +01:00
Anthony Stirling
315cba07f0 Merge branch 'main' into itextRemoval 2023-09-14 14:34:14 +01:00
Anthony Stirling
cd5bd92a41 docs 2023-09-14 14:30:39 +01:00
Anthony Stirling
10126ce979 readme 2023-09-14 13:35:33 +01:00
Anthony Stirling
f6c4f08254 docs 2023-09-14 13:32:49 +01:00
Anthony Stirling
fc4feb2096 lang 2023-09-14 11:33:02 +01:00
Anthony Stirling
82b641458f fixes 2023-09-13 00:46:30 +01:00
Anthony Stirling
2c0fb33548 slow rework testing, still on multipage 2023-09-12 00:42:22 +01:00
Anthony Stirling
24e665bfd5 cleanup and defaults 2023-09-11 23:42:18 +01:00
Anthony Stirling
1404e33386 Merge branch 'itextRemoval' of git@github.com:Frooodle/Stirling-PDF.git
into itextRemoval
2023-09-11 23:21:05 +01:00
Anthony Stirling
0b1fd61188 api /api/v1/ 2023-09-11 23:19:50 +01:00
Anthony Stirling
80b4c67e35 super call 2023-09-10 09:24:20 +01:00
Anthony Stirling
1f4aae9249 finishing forms 2023-09-10 01:10:24 +01:00
Anthony Stirling
145e8006f0 metadata 2023-09-09 18:51:43 +01:00
Anthony Stirling
872f562aad misc beginings 2023-09-09 18:21:55 +01:00
Anthony Stirling
db70d67180 Merge branch 'itextRemoval' of git@github.com:Frooodle/Stirling-PDF.git into itextRemoval 2023-09-09 00:25:47 +01:00
Anthony Stirling
b1fd798a5c init 2023-09-09 00:25:27 +01:00
Anthony Stirling
fefa8347da Merge pull request #342 from Frooodle/itextRemoval
Itext removal
2023-09-06 22:23:29 +01:00
Anthony Stirling
cd7ca09a3f Update settings.yml.template 2023-09-06 22:22:13 +01:00
Anthony Stirling
3960b2d6f9 Merge branch 'main' into itextRemoval 2023-09-06 22:10:41 +01:00
Anthony Stirling
264969e80c Merge branch 'itextRemoval' of git@github.com:Frooodle/Stirling-PDF.git into itextRemoval 2023-09-06 21:58:36 +01:00
Anthony Stirling
4e2911f648 custom font fix 2023-09-06 21:58:28 +01:00
Anthony Stirling
7b07a706e1 Merge pull request #350 from Ale1x/main
Update content in messages_it.properties file
2023-09-06 16:35:49 +01:00
Anthony Stirling
8fef9dc8a8 Merge branch 'main' into itextRemoval 2023-09-06 15:41:39 +01:00
Anthony Stirling
83936bf4c8 security fix 2023-09-06 15:41:15 +01:00
Alessandro Passarelli
65f89e283e Fixed Mistakes 2023-09-06 15:57:43 +02:00
Alessandro Passarelli
1aa65bd3d1 Update content in messages_it.properties file
This commit includes changes to the content of the messages_it.properties file. Modifications were made to enhance the clarity and accuracy of the messages for the Italian localization.
2023-09-06 15:45:20 +02:00
Anthony Stirling
0547ec3c49 Merge pull request #349 from rubenixnagios/rubenixnagios-patch-2
Update messages_ca_CA.properties
2023-09-06 12:32:49 +01:00
Rubens
7e1cbe572d Update messages_ca_CA.properties
updated catalan missing translations
2023-09-06 13:13:20 +02:00
Anthony Stirling
7a98f30d05 Merge pull request #347 from darddan/main
Add side stitch booklet rearrangement
2023-09-05 21:44:11 +01:00
Anthony Stirling
c565bd4400 test 2023-09-05 20:58:18 +01:00
Dardan
d039c8e62e Use tabs instead of spaces 2023-09-05 20:06:18 +02:00
Dardan
da7f0561cb Add side stitch booklet rearrangement 2023-09-05 19:48:16 +02:00
Anthony Stirling
00210b75c7 Merge pull request #344 from c-jaenicke/main
translate text to german
2023-09-05 11:09:44 +01:00
c-jaenicke
3fe8973ae6 Merge branch 'main' into main 2023-09-05 11:36:36 +02:00
Anthony Stirling
87c4b42683 Merge pull request #346 from tkymmm/tkymmm-patch-1
Update messages_ja_JP.properties
2023-09-05 09:42:00 +01:00
tkymmm
0901eaac45 Update messages_ja_JP.properties
Japanese translation of new features.
2023-09-05 14:58:31 +09:00
Anthony Stirling
c7c81a7243 security 2023-09-04 18:42:22 +01:00
Anthony Stirling
ac019ac196 Merge remote-tracking branch 'origin/main' into itextRemoval 2023-09-04 18:30:30 +01:00
Anthony Stirling
b12c1305ea Merge pull request #345 from ikerib/basque_locale
[Locale] [Basque] Add new strings
2023-09-04 18:00:51 +01:00
ikerib
1876c2afae Add new strings 2023-09-04 17:58:03 +02:00
c-jaenicke
4575375ea9 fix line 1 comment 2023-09-04 12:31:56 +02:00
c-jaenicke
aac7836dce spellchecking and last translation 2023-09-04 12:16:42 +02:00
c-jaenicke
df5de2d60d make format consistent 2023-09-04 11:47:18 +02:00
c-jaenicke
b026283ef2 translate text to german 2023-09-04 11:45:00 +02:00
c-jaenicke
548e5d108c translate text to german 2023-09-04 11:32:15 +02:00
c-jaenicke
4d31152a02 translate text to german 2023-09-04 11:08:05 +02:00
Anthony Stirling
fd08513212 dipslay stuf 2023-09-04 00:12:27 +01:00
Anthony Stirling
3175ac16d1 Merge pull request #343 from deraw/update-fr-translations
Update messages_fr_FR.properties
2023-09-04 00:00:30 +01:00
Dylan Broussard
0cb5a6c7ad Update messages_fr_FR.properties 2023-09-04 00:48:08 +02:00
Anthony Stirling
0bb2df135b testing messages 2023-09-03 19:44:16 +01:00
Anthony Stirling
adadf7428c Merge branch 'itextRemoval' of git@github.com:Frooodle/Stirling-PDF.git into itextRemoval 2023-09-03 16:41:00 +01:00
Anthony Stirling
146dd3c00b cred change start 2023-09-03 16:40:40 +01:00
Anthony Stirling
78bfa84afd Update README.md 2023-09-03 01:46:02 +01:00
Anthony Stirling
07512c7e2c Merge branch 'main' into itextRemoval 2023-09-03 01:24:49 +01:00
Anthony Stirling
9fe96bec40 import cleanup 2023-09-03 01:24:02 +01:00
Anthony Stirling
18172aa33a complete itext removal 2023-09-03 01:23:44 +01:00
Anthony Stirling
9ece6dacbd removal 2023-09-02 20:32:44 +01:00
Anthony Stirling
ef07963d79 itext removal 2023-09-02 20:21:55 +01:00
Anthony Stirling
862086eae5 itext removal fixes 2023-09-02 19:12:08 +01:00
Anthony Stirling
277aa0c7e1 Merge pull request #341 from shalak/tune_docs
Update settings docs
2023-09-02 12:13:15 +01:00
Shalak
fc52741435 Update settings docs 2023-09-02 12:30:27 +02:00
Anthony Stirling
a7cd6bfd2e itext changes 2023-09-02 00:05:50 +01:00
Anthony Stirling
648df7b3d3 Update README.md 2023-08-31 21:24:53 +01:00
Anthony Stirling
01f7f1f59c fix max size issue 2023-08-31 13:52:54 +01:00
Anthony Stirling
ff7f089f69 v tag fix 2023-08-30 22:55:33 +01:00
Anthony Stirling
ca5ce905c7 version bump 2023-08-30 22:52:53 +01:00
Anthony Stirling
0fc29de02c redact allow colors, bug fixes 2023-08-30 22:52:38 +01:00
Anthony Stirling
8509a16d6e fix init for multi downloads 2023-08-30 21:40:29 +01:00
Anthony Stirling
0ed021357b change metadata fix 2023-08-30 18:52:31 +01:00
Anthony Stirling
58ad7a1e8a info permission fix 2023-08-30 00:12:40 +01:00
Anthony Stirling
622ee29dd8 Update README.md 2023-08-28 13:01:57 +01:00
Anthony Stirling
5cbb4c6223 Update README.md 2023-08-28 13:01:16 +01:00
Anthony Stirling
5299859385 Update README.md 2023-08-28 12:49:23 +01:00
181 changed files with 4624 additions and 3186 deletions

View File

@@ -1,31 +1,39 @@
# Build jbig2enc in a separate stage # Use the base image
FROM frooodle/stirling-pdf-base:beta4 FROM frooodle/stirling-pdf-base:beta4
ARG VERSION_TAG # Set Environment Variables
ENV VERSION_TAG=$VERSION_TAG ENV PUID=1000 \
PGID=1000 \
UMASK=022 \
DOCKER_ENABLE_SECURITY=false \
HOME=/home/stirlingpdfuser \
VERSION_TAG=$VERSION_TAG
ENV DOCKER_ENABLE_SECURITY=false # 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
# Create scripts folder and copy local scripts # Set up necessary directories and permissions
RUN mkdir /scripts 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 ./scripts/* /scripts/
#Install fonts
RUN mkdir /usr/share/fonts/opentype/noto/
COPY src/main/resources/static/fonts/*.ttf /usr/share/fonts/opentype/noto/ 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 src/main/resources/static/fonts/*.otf /usr/share/fonts/opentype/noto/
RUN fc-cache -f -v
# Always copy the JAR
COPY build/libs/*.jar app.jar COPY build/libs/*.jar app.jar
# Expose the application port # Set font cache and permissions
RUN fc-cache -f -v && \
chown stirlingpdfuser:stirlingpdfgroup /app.jar && \
chmod +x /scripts/init.sh
# Expose necessary ports
EXPOSE 8080 EXPOSE 8080
# Set environment variables # Set user and run command
ENV APP_HOME_NAME="Stirling PDF" USER stirlingpdfuser
# Run the application
RUN chmod +x /scripts/init.sh
ENTRYPOINT ["/scripts/init.sh"] ENTRYPOINT ["/scripts/init.sh"]
CMD ["java", "-jar", "/app.jar"] CMD ["java", "-jar", "/app.jar"]

View File

@@ -10,17 +10,43 @@ RUN apt-get update && \
unoconv && \ unoconv && \
rm -rf /var/lib/apt/lists/* rm -rf /var/lib/apt/lists/*
# Copy the application JAR file
# 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
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 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 the application port
EXPOSE 8080 EXPOSE 8080
# Set environment variables # Set environment variables
ENV GROUPS_TO_REMOVE=Python,OpenCV,OCRmyPDF ENV ENDPOINTS_GROUPS_TO_REMOVE=Python,OpenCV,OCRmyPDF
ENV DOCKER_ENABLE_SECURITY=false ENV DOCKER_ENABLE_SECURITY=false
# Run the application # Run the application
USER stirlingpdfuser
CMD ["java", "-jar", "/app.jar"] CMD ["java", "-jar", "/app.jar"]

View File

@@ -1,16 +1,33 @@
# Build jbig2enc in a separate stage # Build jbig2enc in a separate stage
FROM bellsoft/liberica-openjdk-alpine:17 FROM bellsoft/liberica-openjdk-alpine:17
# Copy the application JAR file # 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 COPY build/libs/*.jar app.jar
# Set font cache and permissions
RUN chown stirlingpdfuser:stirlingpdfgroup /app.jar
# Expose the application port # Expose the application port
EXPOSE 8080 EXPOSE 8080
# Set environment variables # Set environment variables
ENV GROUPS_TO_REMOVE=CLI ENV ENDPOINTS_GROUPS_TO_REMOVE=CLI
ENV DOCKER_ENABLE_SECURITY=false ENV DOCKER_ENABLE_SECURITY=false
# Run the application # Run the application

View File

@@ -8,7 +8,7 @@ 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 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/navbar.html#L306 https://github.com/Frooodle/Stirling-PDF/blob/main/src/main/resources/templates/fragments/languages.html
and add a flag svg file to and add a flag svg file to
https://github.com/Frooodle/Stirling-PDF/tree/main/src/main/resources/static/images/flags 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/) Any SVG flags are fine, i got most of mine from [here](https://flagicons.lipis.dev/)
@@ -25,7 +25,7 @@ The data-language-code is the code used to reference the file in the next step.
Start by copying the existing english property file Start by copying the existing english property file
[https://github.com/Frooodle/Stirling-PDF/tree/langSetup/src/main/resources/messages_en_GB.properties](https://github.com/Frooodle/Stirling-PDF/blob/main/src/main/resources/messages_en_US.properties) [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 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

194
README.md
View File

@@ -23,42 +23,63 @@ Feel free to request any features or bug fixes either in github issues or our [D
![stirling-home](images/stirling-home.png) ![stirling-home](images/stirling-home.png)
## Features ## Features
- Full interactive GUI for merging/splitting/rotating/moving PDFs and their pages.
- Split PDFs into multiple files at specified page numbers or extract all pages as individual files.
- Merge multiple PDFs together into a single resultant file
- Convert PDFs to and from images
- Reorganize PDF pages into different orders.
- Add/Generate signatures
- 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)
- Flatten PDFs
- Repair PDFs
- Detect and remove blank pages
- Compare 2 PDFs and show differences in text
- Add images to PDFs
- Rotating PDFs in 90 degree increments.
- Compressing PDFs to decrease their filesize. (Using OCRMyPDF)
- Add and remove passwords
- Set PDF Permissions
- Add watermark(s)
- Convert Any common file to PDF (using LibreOffice)
- Convert PDF to Word/Powerpoint/Others (using LibreOffice)
- Convert HTML to PDF
- URL to PDF
- 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
- Dark mode support. - Dark mode support.
- Custom download options (see [here](https://github.com/Frooodle/Stirling-PDF/blob/main/images/settings.png) for example) - Custom download options (see [here](https://github.com/Frooodle/Stirling-PDF/blob/main/images/settings.png) for example)
- Parallel file processing and downloads - Parallel file processing and downloads
- API for integration with external scripts - 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) 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 Hosted instance/demo of the app can be seen [here](https://pdf.adminforge.de/) hosted by the team at adminforge.de
@@ -66,7 +87,6 @@ Hosted instance/demo of the app can be seen [here](https://pdf.adminforge.de/) h
## Technologies used ## Technologies used
- Spring Boot + Thymeleaf - Spring Boot + Thymeleaf
- PDFBox - PDFBox
- IText7
- [LibreOffice](https://www.libreoffice.org/discover/libreoffice/) for advanced conversions - [LibreOffice](https://www.libreoffice.org/discover/libreoffice/) for advanced conversions
- [OcrMyPdf](https://github.com/ocrmypdf/OCRmyPDF) - [OcrMyPdf](https://github.com/ocrmypdf/OCRmyPDF)
- HTML, CSS, JavaScript - HTML, CSS, JavaScript
@@ -82,9 +102,9 @@ Please view https://github.com/Frooodle/Stirling-PDF/blob/main/LocalRunGuide.md
### Docker ### Docker
https://hub.docker.com/r/frooodle/s-pdf 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. 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) 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 dont mind about space optimisation just use latest tag. For people that don't mind about space optimization just use the latest tag.
![Docker Image Size (tag)](https://img.shields.io/docker/image-size/frooodle/s-pdf/latest?label=Stirling-PDF%20Full) ![Docker Image Size (tag)](https://img.shields.io/docker/image-size/frooodle/s-pdf/latest?label=Stirling-PDF%20Full)
![Docker Image Size (tag)](https://img.shields.io/docker/image-size/frooodle/s-pdf/latest-lite?label=Stirling-PDF%20Lite) ![Docker Image Size (tag)](https://img.shields.io/docker/image-size/frooodle/s-pdf/latest-lite?label=Stirling-PDF%20Lite)
![Docker Image Size (tag)](https://img.shields.io/docker/image-size/frooodle/s-pdf/latest-ultra-lite?label=Stirling-PDF%20Ultra-Lite) ![Docker Image Size (tag)](https://img.shields.io/docker/image-size/frooodle/s-pdf/latest-ultra-lite?label=Stirling-PDF%20Ultra-Lite)
@@ -94,19 +114,15 @@ Docker Run
docker run -d \ docker run -d \
-p 8080:8080 \ -p 8080:8080 \
-v /location/of/trainingData:/usr/share/tesseract-ocr/4.00/tessdata \ -v /location/of/trainingData:/usr/share/tesseract-ocr/4.00/tessdata \
-v /location/of/extraConfigs:/configs \
-e DOCKER_ENABLE_SECURITY=false \
--name stirling-pdf \ --name stirling-pdf \
frooodle/s-pdf:latest frooodle/s-pdf:latest
Can also add these for customisation but are not required Can also add these for customisation but are not required
-v /location/of/extraConfigs:/configs \
-v /location/of/customFiles:/customFiles \ -v /location/of/customFiles:/customFiles \
-e APP_HOME_NAME="Stirling PDF" \
-e APP_HOME_DESCRIPTION="Your locally hosted one-stop-shop for all your PDF needs." \
-e APP_NAVBAR_NAME="Stirling PDF" \
-e ALLOW_GOOGLE_VISIBILITY="true" \
-e APP_ROOT_PATH="/" \
-e APP_LOCALE="en_GB" \
``` ```
Docker Compose Docker Compose
``` ```
@@ -118,16 +134,10 @@ services:
- '8080:8080' - '8080:8080'
volumes: volumes:
- /location/of/trainingData:/usr/share/tesseract-ocr/4.00/tessdata #Required for extra OCR languages - /location/of/trainingData:/usr/share/tesseract-ocr/4.00/tessdata #Required for extra OCR languages
# - /location/of/extraConfigs:/configs - /location/of/extraConfigs:/configs
# - /location/of/customFiles:/customFiles/ # - /location/of/customFiles:/customFiles/
# environment: environment:
# APP_LOCALE: en_GB - DOCKER_ENABLE_SECURITY=false
# APP_HOME_NAME: Stirling PDF
# APP_HOME_DESCRIPTION: Your locally hosted one-stop-shop for all your PDF needs.
# APP_NAVBAR_NAME: Stirling PDF
# APP_ROOT_PATH: /
# ALLOW_GOOGLE_VISIBILITY: true
``` ```
@@ -135,8 +145,9 @@ services:
Please view https://github.com/Frooodle/Stirling-PDF/blob/main/HowToUseOCR.md Please view https://github.com/Frooodle/Stirling-PDF/blob/main/HowToUseOCR.md
## Want to add your own language? ## Want to add your own language?
Stirling PDF currently supports 16! Stirling PDF currently supports 18!
- English (English) (en_GB) - English (English) (en_GB)
- English (US) (en_US)
- Arabic (العربية) (ar_AR) - Arabic (العربية) (ar_AR)
- German (Deutsch) (de_DE) - German (Deutsch) (de_DE)
- French (Français) (fr_FR) - French (Français) (fr_FR)
@@ -152,52 +163,87 @@ Stirling PDF currently supports 16!
- Russian (Русский) (ru_RU) - Russian (Русский) (ru_RU)
- Basque (Euskara) (eu_ES) - Basque (Euskara) (eu_ES)
- Japanese (日本語) (ja_JP) - Japanese (日本語) (ja_JP)
- Dutch (Nederlands) (nl_NL)
If you want to add your own language to Stirling-PDF please refer If you want to add your own language to Stirling-PDF please refer
https://github.com/Frooodle/Stirling-PDF/blob/main/HowToAddNewLanguage.md 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! And please create a PR to merge it back in so others can use it!
Also please note as i add new features i will google translate existing languages so that they dont lose support. This could mean that new features need grammer corrections as added.
## How to View ## How to View
1. Open a web browser and navigate to `http://localhost:8080/` 1. Open a web browser and navigate to `http://localhost:8080/`
2. Use the application by following the instructions on the website. 2. Use the application by following the instructions on the website.
## Customize App ## Customisation
Stirling PDF allows easy customization of the visible application name. Stirling PDF allows easy customization of the app.
Simply use environment variables APP_HOME_NAME, APP_HOME_DESCRIPTION and APP_NAVBAR_NAME with Docker or Java. Includes things like
If running Java directly, you can also pass these as properties using -D arguments. - Custom application name
- Custom slogans, icons, images, and even custom HTML (via file overrides)
Using the same method you can also change
- The default language by providing APP_LOCALE with values like de-DE fr-FR or ar-AR (Note the - character not _ ) to select your default language (Will always default to English on invalid locale) Current accepted locales can be seen above in the Want to add your own language section There are two options for this, either using the generated settings file ``settings.yml``
- Enable/Disable search engine visiblility with ALLOW_GOOGLE_VISIBILITY with true / false values. Default disable visiblility. This file is located in the ``/configs`` directory and follows standard YAML formatting
- Change root URI for Stirling-PDF ie change server.com/ to server.com/pdf-app by running APP_ROOT_PATH as pdf-app
- Disable and remove endpoints and functionality from Stirling-PDF. Currently the endpoints ENDPOINTS_TO_REMOVE and GROUPS_TO_REMOVE can include comma seperated 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) Environment variables are also supported and would override the settings file
- Change the max file size allowed through the server with the environment variable MAX_FILE_SIZE. default 2000MB For example in the settings.yml you have
- Customise static files such as app logo by placing files in the /customFiles/static/ directory. Example to customise 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 ```
- Enable/Disable metric api endpoints with ENABLE_API_METRICS. Default enabled 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 tp ``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 ## 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 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) [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 (CURRENTLY ALPHA TAG ONLY) ## Login authentication
### Prerequisites: ### Prerequisites:
- User must have the folder ./configs volumed within docker so that it is retained during updates. - User must have the folder ./configs volumed within docker so that it is retained during updates.
- The environment variable 'login.enabled' must be set to true - Docker uses must download the security jar version by setting ``DOCKER_ENABLE_SECURITY`` to ``true`` in environment variables.
- The environment variables "INITIAL_USERNAME" and "INITIAL_PASSWORD" must also be populated (only required on first boot to create initial user, ignored after.) - 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.
Once the above has been done, on restart a new stirling-pdf-DB.mv.db will show if everything worked. 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 credentials. After login everything should function as normal 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 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 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 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. For API usage you must provide a header with 'X-API-Key' and the associated API key for that user.
@@ -208,7 +254,7 @@ For API usage you must provide a header with 'X-API-Key' and the associated API
- Progress bar/Tracking - Progress bar/Tracking
- Full custom logic pipelines to combine multiple operations together. - Full custom logic pipelines to combine multiple operations together.
- Folder support with auto scanning to perform operations on - Folder support with auto scanning to perform operations on
- Redact text (Via UI) - Redact text (Via UI not just automated way)
- Add Forms - Add Forms
- Annotations - Annotations
- Multi page layout (Stich PDF pages together) support x rows y columns and custom page sizing - Multi page layout (Stich PDF pages together) support x rows y columns and custom page sizing

View File

@@ -8,7 +8,7 @@ plugins {
} }
group = 'stirling.software' group = 'stirling.software'
version = '0.13.0' version = '0.14.0'
sourceCompatibility = '17' sourceCompatibility = '17'
repositories { repositories {
@@ -86,9 +86,9 @@ dependencies {
//general PDF //general PDF
implementation 'org.apache.pdfbox:pdfbox:2.0.29' 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:bcprov-jdk15on:1.70'
implementation 'org.bouncycastle:bcpkix-jdk15on:1.70' implementation 'org.bouncycastle:bcpkix-jdk15on:1.70'
implementation 'com.itextpdf:itext7-core:7.2.5'
implementation 'org.springframework.boot:spring-boot-starter-actuator' implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'io.micrometer:micrometer-core' implementation 'io.micrometer:micrometer-core'
implementation group: 'com.google.zxing', name: 'core', version: '3.5.1' implementation group: 'com.google.zxing', name: 'core', version: '3.5.1'
@@ -98,6 +98,8 @@ dependencies {
implementation 'com.github.vladimir-bukhtoyarov:bucket4j-core:7.6.0' implementation 'com.github.vladimir-bukhtoyarov:bucket4j-core:7.6.0'
developmentOnly("org.springframework.boot:spring-boot-devtools") developmentOnly("org.springframework.boot:spring-boot-devtools")
compileOnly 'org.projectlombok:lombok:1.18.28'
annotationProcessor 'org.projectlombok:lombok:1.18.28'
} }

BIN
images/login-dark.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

BIN
images/login-light.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 118 KiB

After

Width:  |  Height:  |  Size: 131 KiB

View File

@@ -18,11 +18,20 @@ fi
# Check for DOCKER_ENABLE_SECURITY and download the appropriate JAR if required # Check for DOCKER_ENABLE_SECURITY and download the appropriate JAR if required
if [ "$DOCKER_ENABLE_SECURITY" = "true" ] && [ "$VERSION_TAG" != "alpha" ]; then if [ "$DOCKER_ENABLE_SECURITY" = "true" ] && [ "$VERSION_TAG" != "alpha" ]; then
echo "Downloading from: https://github.com/Frooodle/Stirling-PDF/releases/download/$VERSION_TAG/Stirling-PDF-with-login.jar" if [ ! -f app-security.jar ]; then
curl -L -o new-app.jar https://github.com/Frooodle/Stirling-PDF/releases/download/$VERSION_TAG/Stirling-PDF-with-login.jar echo "Trying to download from: https://github.com/Frooodle/Stirling-PDF/releases/download/v$VERSION_TAG/Stirling-PDF-with-login.jar"
if [ $? -eq 0 ]; then # checks if curl was successful curl -L -o app-security.jar https://github.com/Frooodle/Stirling-PDF/releases/download/v$VERSION_TAG/Stirling-PDF-with-login.jar
rm -f app.jar
mv new-app.jar app.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
fi fi

View File

@@ -9,7 +9,6 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import jakarta.annotation.PostConstruct; import jakarta.annotation.PostConstruct;
import stirling.software.SPDF.config.ConfigInitializer; import stirling.software.SPDF.config.ConfigInitializer;
import stirling.software.SPDF.utils.GeneralUtils; import stirling.software.SPDF.utils.GeneralUtils;
@@ -51,7 +50,7 @@ public class SPdfApplication {
SpringApplication app = new SpringApplication(SPdfApplication.class); SpringApplication app = new SpringApplication(SPdfApplication.class);
app.addInitializers(new ConfigInitializer()); app.addInitializers(new ConfigInitializer());
if (Files.exists(Paths.get("configs/settings.yml"))) { if (Files.exists(Paths.get("configs/settings.yml"))) {
app.setDefaultProperties(Collections.singletonMap("spring.config.location", "file:configs/settings.yml")); app.setDefaultProperties(Collections.singletonMap("spring.config.additional-location", "file:configs/settings.yml"));
} else { } else {
System.out.println("External configuration file 'configs/settings.yml' does not exist. Using default configuration and environment configuration instead."); System.out.println("External configuration file 'configs/settings.yml' does not exist. Using default configuration and environment configuration instead.");
} }
@@ -66,7 +65,6 @@ public class SPdfApplication {
GeneralUtils.createDir("customFiles/static/"); GeneralUtils.createDir("customFiles/static/");
GeneralUtils.createDir("customFiles/templates/"); GeneralUtils.createDir("customFiles/templates/");
GeneralUtils.createDir("config");

View File

@@ -13,7 +13,6 @@ public class AppConfig {
@Bean(name = "loginEnabled") @Bean(name = "loginEnabled")
public boolean loginEnabled() { public boolean loginEnabled() {
System.out.println(applicationProperties.toString());
return applicationProperties.getSecurity().getEnableLogin(); return applicationProperties.getSecurity().getEnableLogin();
} }

View File

@@ -13,7 +13,7 @@ import jakarta.servlet.http.HttpServletResponse;
public class CleanUrlInterceptor implements HandlerInterceptor { public class CleanUrlInterceptor implements HandlerInterceptor {
private static final List<String> ALLOWED_PARAMS = Arrays.asList("lang", "endpoint", "endpoints", "logout", "error", "file"); private static final List<String> ALLOWED_PARAMS = Arrays.asList("lang", "endpoint", "endpoints", "logout", "error", "file", "messageType");
@Override @Override
@@ -22,7 +22,6 @@ public class CleanUrlInterceptor implements HandlerInterceptor {
String queryString = request.getQueryString(); String queryString = request.getQueryString();
if (queryString != null && !queryString.isEmpty()) { if (queryString != null && !queryString.isEmpty()) {
String requestURI = request.getRequestURI(); String requestURI = request.getRequestURI();
Map<String, String> parameters = new HashMap<>(); Map<String, String> parameters = new HashMap<>();
// Keep only the allowed parameters // Keep only the allowed parameters
@@ -32,7 +31,6 @@ public class CleanUrlInterceptor implements HandlerInterceptor {
if (keyValue.length != 2) { if (keyValue.length != 2) {
continue; continue;
} }
if (ALLOWED_PARAMS.contains(keyValue[0])) { if (ALLOWED_PARAMS.contains(keyValue[0])) {
parameters.put(keyValue[0], keyValue[1]); parameters.put(keyValue[0], keyValue[1]);
} }

View File

@@ -1,10 +1,18 @@
package stirling.software.SPDF.config; package stirling.software.SPDF.config;
import java.io.BufferedReader;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
@@ -20,24 +28,74 @@ public class ConfigInitializer implements ApplicationContextInitializer<Configur
} }
} }
public void ensureConfigExists() throws IOException { public void ensureConfigExists() throws IOException {
// Define the path to the external config directory // Define the path to the external config directory
Path destPath = Paths.get("configs", "settings.yml"); Path destPath = Paths.get("configs", "settings.yml");
// Check if the file already exists // Check if the file already exists
if (Files.notExists(destPath)) { if (Files.notExists(destPath)) {
// Ensure the destination directory exists // Ensure the destination directory exists
Files.createDirectories(destPath.getParent()); Files.createDirectories(destPath.getParent());
// Copy the resource from classpath to the external directory // Copy the resource from classpath to the external directory
try (InputStream in = getClass().getClassLoader().getResourceAsStream("settings.yml.template")) { try (InputStream in = getClass().getClassLoader().getResourceAsStream("settings.yml.template")) {
if (in != null) { if (in != null) {
Files.copy(in, destPath); Files.copy(in, destPath);
} else { } else {
throw new FileNotFoundException("Resource file not found: settings.yml.template"); 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<String> 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<String> templateLines, Path userFilePath, Path outputPath) throws IOException {
List<String> userLines = Files.readAllLines(userFilePath);
List<String> mergedLines = new ArrayList<>();
boolean insideAutoGenerated = false;
for (String line : templateLines) {
// Check if we've entered or left the AutomaticallyGenerated section
if (line.trim().equalsIgnoreCase("AutomaticallyGenerated:")) {
insideAutoGenerated = true;
mergedLines.add(line);
continue;
} else if (insideAutoGenerated && line.trim().isEmpty()) {
// We have reached the end of the AutomaticallyGenerated section
insideAutoGenerated = false;
mergedLines.add(line);
continue;
}
if (insideAutoGenerated) {
// Add lines from user's settings if we are inside AutomaticallyGenerated
Optional<String> userAutoGenValue = userLines.stream().filter(l -> l.trim().startsWith(line.split(":")[0].trim())).findFirst();
if (userAutoGenValue.isPresent()) {
mergedLines.add(userAutoGenValue.get());
continue;
}
} else {
// Outside of AutomaticallyGenerated, continue as before
if (line.contains(": ")) {
String key = line.split(": ")[0].trim();
Optional<String> userValue = userLines.stream().filter(l -> l.trim().startsWith(key)).findFirst();
if (userValue.isPresent()) {
mergedLines.add(userValue.get());
continue;
}
}
mergedLines.add(line);
}
}
Files.write(outputPath, mergedLines, StandardCharsets.UTF_8);
}
}

View File

@@ -1,9 +1,5 @@
package stirling.software.SPDF.config; package stirling.software.SPDF.config;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@@ -18,14 +14,9 @@ public class OpenApiConfig {
public OpenAPI customOpenAPI() { public OpenAPI customOpenAPI() {
String version = getClass().getPackage().getImplementationVersion(); String version = getClass().getPackage().getImplementationVersion();
if (version == null) { if (version == null) {
Properties props = new Properties();
try (InputStream input = getClass().getClassLoader().getResourceAsStream("version.properties")) {
props.load(input);
version = props.getProperty("version");
} catch (IOException ex) {
ex.printStackTrace();
version = "1.0.0"; // default version if all else fails version = "1.0.0"; // default version if all else fails
}
} }
return new OpenAPI().components(new Components()).info( return new OpenAPI().components(new Components()).info(

View File

@@ -0,0 +1,53 @@
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> 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);
}
}

View File

@@ -11,28 +11,27 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import jakarta.annotation.PostConstruct; import jakarta.annotation.PostConstruct;
import stirling.software.SPDF.config.security.UserService;
import stirling.software.SPDF.model.ApplicationProperties; import stirling.software.SPDF.model.ApplicationProperties;
import stirling.software.SPDF.model.Role; import stirling.software.SPDF.model.Role;
@Component @Component
public class InitialSecuritySetup { public class InitialSecuritySetup {
@Autowired @Autowired
private UserService userService; private UserService userService;
@Autowired @Autowired
ApplicationProperties applicationProperties; ApplicationProperties applicationProperties;
@PostConstruct @PostConstruct
public void init() { public void init() {
if (!userService.hasUsers()) { if (!userService.hasUsers()) {
String initialUsername = applicationProperties.getSecurity().getInitialLogin().getUsername(); String initialUsername = "admin";
String initialPassword = applicationProperties.getSecurity().getInitialLogin().getPassword(); String initialPassword = "stirling";
if (initialUsername != null && initialPassword != null) { userService.saveUser(initialUsername, initialPassword, Role.ADMIN.getRoleId(), true);
userService.saveUser(initialUsername, initialPassword, Role.ADMIN.getRoleId());
}
} }
} }

View File

@@ -1,15 +1,14 @@
package stirling.software.SPDF.config.security; package stirling.software.SPDF.config.security;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider; 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.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
@@ -42,6 +41,9 @@ public class SecurityConfiguration {
@Autowired @Autowired
private UserAuthenticationFilter userAuthenticationFilter; private UserAuthenticationFilter userAuthenticationFilter;
@Autowired
private FirstLoginFilter firstLoginFilter;
@Bean @Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.addFilterBefore(userAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); http.addFilterBefore(userAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
@@ -49,6 +51,7 @@ public class SecurityConfiguration {
if(loginEnabledValue) { if(loginEnabledValue) {
http.csrf(csrf -> csrf.disable()); http.csrf(csrf -> csrf.disable());
http.addFilterAfter(firstLoginFilter, UsernamePasswordAuthenticationFilter.class);
http http
.formLogin(formLogin -> formLogin .formLogin(formLogin -> formLogin
.loginPage("/login") .loginPage("/login")

View File

@@ -44,7 +44,7 @@ public class UserAuthenticationFilter extends OncePerRequestFilter {
filterChain.doFilter(request, response); filterChain.doFilter(request, response);
return; return;
} }
String requestURI = request.getRequestURI();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
// Check for API key in the request headers if no authentication exists // Check for API key in the request headers if no authentication exists
@@ -74,13 +74,14 @@ public class UserAuthenticationFilter extends OncePerRequestFilter {
// If we still don't have any authentication, deny the request // If we still don't have any authentication, deny the request
if (authentication == null || !authentication.isAuthenticated()) { if (authentication == null || !authentication.isAuthenticated()) {
String method = request.getMethod(); String method = request.getMethod();
if ("GET".equalsIgnoreCase(method)) { if ("GET".equalsIgnoreCase(method) && !"/login".equals(requestURI)) {
response.sendRedirect("/login"); // redirect to the login page response.sendRedirect("/login"); // redirect to the login page
return; 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;
} }
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); filterChain.doFilter(request, response);

View File

@@ -113,12 +113,23 @@ public class UserService {
userRepository.save(user); 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) { public void saveUser(String username, String password, String role) {
User user = new User(); User user = new User();
user.setUsername(username); user.setUsername(username);
user.setPassword(passwordEncoder.encode(password)); user.setPassword(passwordEncoder.encode(password));
user.addAuthority(new Authority(role, user)); user.addAuthority(new Authority(role, user));
user.setEnabled(true); user.setEnabled(true);
user.setFirstLogin(false);
userRepository.save(user); userRepository.save(user);
} }
@@ -168,6 +179,12 @@ public class UserService {
userRepository.save(user); userRepository.save(user);
} }
public void changeFirstUse(User user, boolean firstUse) {
user.setFirstLogin(firstUse);
userRepository.save(user);
}
public boolean isPasswordCorrect(User user, String currentPassword) { public boolean isPasswordCorrect(User user, String currentPassword) {
return passwordEncoder.matches(currentPassword, user.getPassword()); return passwordEncoder.matches(currentPassword, user.getPassword());
} }

View File

@@ -4,75 +4,83 @@ import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import stirling.software.SPDF.model.api.general.CropPdfForm;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@RequestMapping("/api/v1/general")
@Tag(name = "General", description = "General APIs") @Tag(name = "General", description = "General APIs")
public class CropController { public class CropController {
private static final Logger logger = LoggerFactory.getLogger(CropController.class); private static final Logger logger = LoggerFactory.getLogger(CropController.class);
@PostMapping(value = "/crop", consumes = "multipart/form-data") @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") @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<byte[]> cropPdf( public ResponseEntity<byte[]> cropPdf(@ModelAttribute CropPdfForm form)
@Parameter(description = "The input PDF file", required = true) @RequestParam("fileInput") MultipartFile file, throws IOException {
@Parameter(description = "The x-coordinate of the top-left corner of the crop area", required = true, schema = @Schema(type = "number")) @RequestParam("x") float x,
@Parameter(description = "The y-coordinate of the top-left corner of the crop area", required = true, schema = @Schema(type = "number")) @RequestParam("y") float y,
@Parameter(description = "The width of the crop area", required = true, schema = @Schema(type = "number")) @RequestParam("width") float width,
@Parameter(description = "The height of the crop area", required = true, schema = @Schema(type = "number")) @RequestParam("height") float height) throws IOException {
byte[] bytes = file.getBytes();
System.out.println("x=" + x + ", " + "y=" + y + ", " + "width=" + width + ", " +"height=" + height );
PdfReader reader = new PdfReader(new ByteArrayInputStream(bytes));
PdfDocument pdfDoc = new PdfDocument(reader);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter writer = new PdfWriter(baos);
PdfDocument outputPdf = new PdfDocument(writer);
int totalPages = pdfDoc.getNumberOfPages();
for (int i = 1; i <= totalPages; i++) {
PdfPage page = outputPdf.addNewPage(new PageSize(width, height));
PdfCanvas pdfCanvas = new PdfCanvas(page);
PdfFormXObject formXObject = pdfDoc.getPage(i).copyAsFormXObject(outputPdf);
// Save the graphics state, apply the transformations, add the object, and then
// restore the graphics state
pdfCanvas.saveState();
pdfCanvas.rectangle(x, y, width, height);
pdfCanvas.clip();
pdfCanvas.addXObject(formXObject, -x, -y);
pdfCanvas.restoreState();
}
outputPdf.close(); PDDocument sourceDocument = PDDocument.load(new ByteArrayInputStream(form.getFileInput().getBytes()));
byte[] pdfContent = baos.toByteArray();
pdfDoc.close(); PDDocument newDocument = new PDDocument();
return WebResponseUtils.bytesToWebResponse(pdfContent,
file.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_cropped.pdf"); 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");
} }
} }

View File

@@ -15,19 +15,19 @@ import org.apache.pdfbox.pdmodel.PDPage;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import stirling.software.SPDF.model.api.general.MergePdfsRequest;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@RequestMapping("/api/v1/general")
@Tag(name = "General", description = "General APIs") @Tag(name = "General", description = "General APIs")
public class MergeController { public class MergeController {
@@ -88,20 +88,10 @@ private Comparator<MultipartFile> getSortComparator(String sortType) {
@PostMapping(consumes = "multipart/form-data", value = "/merge-pdfs") @PostMapping(consumes = "multipart/form-data", value = "/merge-pdfs")
@Operation(summary = "Merge multiple PDF files into one", @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") 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<byte[]> mergePdfs( public ResponseEntity<byte[]> mergePdfs(@ModelAttribute MergePdfsRequest form) throws IOException {
@RequestPart(required = true, value = "fileInput") MultipartFile[] files,
@RequestParam(value = "sortType", defaultValue = "orderProvided")
@Parameter(schema = @Schema(description = "The type of sorting to be applied on the input files before merging.",
allowableValues = {
"orderProvided",
"byFileName",
"byDateModified",
"byDateCreated",
"byPDFTitle"
}))
String sortType) throws IOException {
Arrays.sort(files, getSortComparator(sortType)); MultipartFile[] files = form.getFileInput();
Arrays.sort(files, getSortComparator(form.getSortType()));
List<PDDocument> documents = new ArrayList<>(); List<PDDocument> documents = new ArrayList<>();
for (MultipartFile file : files) { for (MultipartFile file : files) {

View File

@@ -1,101 +1,110 @@
package stirling.software.SPDF.controller.api; package stirling.software.SPDF.controller.api;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import stirling.software.SPDF.model.api.general.MergeMultiplePagesRequest;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@RequestMapping("/api/v1/general")
@Tag(name = "General", description = "General APIs") @Tag(name = "General", description = "General APIs")
public class MultiPageLayoutController { public class MultiPageLayoutController {
private static final Logger logger = LoggerFactory.getLogger(MultiPageLayoutController.class); private static final Logger logger = LoggerFactory.getLogger(MultiPageLayoutController.class);
@PostMapping(value = "/multi-page-layout", consumes = "multipart/form-data") @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") @Operation(
public ResponseEntity<byte[]> mergeMultiplePagesIntoOne( summary = "Merge multiple pages of a PDF document into a single page",
@Parameter(description = "The input PDF file", required = true) @RequestParam("fileInput") MultipartFile file, 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"
@Parameter(description = "The number of pages to fit onto a single sheet in the output PDF. Acceptable values are 2, 3, 4, 9, 16.", required = true, schema = @Schema(type = "integer", allowableValues = { )
"2", "3", "4", "9", "16" })) @RequestParam("pagesPerSheet") int pagesPerSheet) public ResponseEntity<byte[]> mergeMultiplePagesIntoOne(@ModelAttribute MergeMultiplePagesRequest request)
throws IOException { throws IOException {
if (pagesPerSheet != 2 && pagesPerSheet != 3 int pagesPerSheet = request.getPagesPerSheet();
&& pagesPerSheet != (int) Math.sqrt(pagesPerSheet) * Math.sqrt(pagesPerSheet)) { MultipartFile file = request.getFileInput();
throw new IllegalArgumentException("pagesPerSheet must be 2, 3 or a perfect square");
}
int cols = pagesPerSheet == 2 || pagesPerSheet == 3 ? pagesPerSheet : (int) Math.sqrt(pagesPerSheet); if (pagesPerSheet != 2 && pagesPerSheet != 3 && pagesPerSheet != (int) Math.sqrt(pagesPerSheet) * Math.sqrt(pagesPerSheet)) {
int rows = pagesPerSheet == 2 || pagesPerSheet == 3 ? 1 : (int) Math.sqrt(pagesPerSheet); throw new IllegalArgumentException("pagesPerSheet must be 2, 3 or a perfect square");
}
byte[] bytes = file.getBytes(); int cols = pagesPerSheet == 2 || pagesPerSheet == 3 ? pagesPerSheet : (int) Math.sqrt(pagesPerSheet);
PdfReader reader = new PdfReader(new ByteArrayInputStream(bytes)); int rows = pagesPerSheet == 2 || pagesPerSheet == 3 ? 1 : (int) Math.sqrt(pagesPerSheet);
PdfDocument pdfDoc = new PdfDocument(reader);
ByteArrayOutputStream baos = new ByteArrayOutputStream(); PDDocument sourceDocument = PDDocument.load(file.getInputStream());
PdfWriter writer = new PdfWriter(baos); PDDocument newDocument = new PDDocument();
PdfDocument outputPdf = new PdfDocument(writer); PDPage newPage = new PDPage(PDRectangle.A4);
PageSize pageSize = new PageSize(PageSize.A4.rotate()); newDocument.addPage(newPage);
int totalPages = pdfDoc.getNumberOfPages(); int totalPages = sourceDocument.getNumberOfPages();
float cellWidth = pageSize.getWidth() / cols; float cellWidth = newPage.getMediaBox().getWidth() / cols;
float cellHeight = pageSize.getHeight() / rows; float cellHeight = newPage.getMediaBox().getHeight() / rows;
for (int i = 1; i <= totalPages; i += pagesPerSheet) { PDPageContentStream contentStream = new PDPageContentStream(newDocument, newPage, PDPageContentStream.AppendMode.APPEND, true, true);
PdfPage page = outputPdf.addNewPage(pageSize); LayerUtility layerUtility = new LayerUtility(newDocument);
PdfCanvas pdfCanvas = new PdfCanvas(page);
for (int row = 0; row < rows; row++) { for (int i = 0; i < totalPages; i++) {
for (int col = 0; col < cols; col++) { if (i != 0 && i % pagesPerSheet == 0) {
int index = i + row * cols + col; // Close the current content stream and create a new page and content stream
if (index <= totalPages) { contentStream.close();
// Get the page and calculate scaling factors newPage = new PDPage(PDRectangle.A4);
Rectangle rect = pdfDoc.getPage(index).getPageSize(); newDocument.addPage(newPage);
float scaleWidth = cellWidth / rect.getWidth(); contentStream = new PDPageContentStream(newDocument, newPage, PDPageContentStream.AppendMode.APPEND, true, true);
float scaleHeight = cellHeight / rect.getHeight(); }
float scale = Math.min(scaleWidth, scaleHeight);
PdfFormXObject formXObject = pdfDoc.getPage(index).copyAsFormXObject(outputPdf); PDPage sourcePage = sourceDocument.getPage(i);
float x = col * cellWidth + (cellWidth - rect.getWidth() * scale) / 2; PDRectangle rect = sourcePage.getMediaBox();
float y = (rows - 1 - row) * cellHeight + (cellHeight - rect.getHeight() * scale) / 2; float scaleWidth = cellWidth / rect.getWidth();
float scaleHeight = cellHeight / rect.getHeight();
float scale = Math.min(scaleWidth, scaleHeight);
// Save the graphics state, apply the transformations, add the object, and then int adjustedPageIndex = i % pagesPerSheet; // This will reset the index for every new page
// restore the graphics state int rowIndex = adjustedPageIndex / cols;
pdfCanvas.saveState(); int colIndex = adjustedPageIndex % cols;
pdfCanvas.concatMatrix(scale, 0, 0, scale, x, y);
pdfCanvas.addXObject(formXObject, 0, 0);
pdfCanvas.restoreState();
}
}
}
}
outputPdf.close(); float x = colIndex * cellWidth + (cellWidth - rect.getWidth() * scale) / 2;
byte[] pdfContent = baos.toByteArray(); float y = newPage.getMediaBox().getHeight() - ((rowIndex + 1) * cellHeight - (cellHeight - rect.getHeight() * scale) / 2);
pdfDoc.close();
contentStream.saveGraphicsState();
return WebResponseUtils.bytesToWebResponse(pdfContent, file.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_layoutChanged.pdf"); contentStream.transform(Matrix.getTranslateInstance(x, y));
contentStream.transform(Matrix.getScaleInstance(scale, scale));
PDFormXObject formXObject = layerUtility.importPageAsForm(sourceDocument, i);
contentStream.drawForm(formXObject);
contentStream.restoreGraphicsState();
}
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");
} }
} }

View File

@@ -9,7 +9,9 @@ import org.apache.pdfbox.pdmodel.PDPage;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@@ -17,12 +19,13 @@ import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import stirling.software.SPDF.model.SortTypes;
import stirling.software.SPDF.model.api.general.RearrangePagesRequest;
import stirling.software.SPDF.utils.GeneralUtils; import stirling.software.SPDF.utils.GeneralUtils;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@RequestMapping("/api/v1/general")
@Tag(name = "General", description = "General APIs") @Tag(name = "General", description = "General APIs")
public class RearrangePagesPDFController { public class RearrangePagesPDFController {
@@ -51,9 +54,7 @@ public class RearrangePagesPDFController {
} }
private enum CustomMode {
REVERSE_ORDER, DUPLEX_SORT, BOOKLET_SORT, ODD_EVEN_SPLIT, REMOVE_FIRST, REMOVE_LAST, REMOVE_FIRST_AND_LAST,
}
private List<Integer> removeFirst(int totalPages) { private List<Integer> removeFirst(int totalPages) {
if (totalPages <= 1) if (totalPages <= 1)
@@ -114,6 +115,18 @@ public class RearrangePagesPDFController {
return newPageOrder; return newPageOrder;
} }
private List<Integer> sideStitchBooklet(int totalPages) {
List<Integer> 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<Integer> oddEvenSplit(int totalPages) { private List<Integer> oddEvenSplit(int totalPages) {
List<Integer> newPageOrder = new ArrayList<>(); List<Integer> newPageOrder = new ArrayList<>();
for (int i = 1; i <= totalPages; i += 2) { for (int i = 1; i <= totalPages; i += 2) {
@@ -125,9 +138,9 @@ public class RearrangePagesPDFController {
return newPageOrder; return newPageOrder;
} }
private List<Integer> processCustomMode(String customMode, int totalPages) { private List<Integer> processSortTypes(String sortTypes, int totalPages) {
try { try {
CustomMode mode = CustomMode.valueOf(customMode.toUpperCase()); SortTypes mode = SortTypes.valueOf(sortTypes.toUpperCase());
switch (mode) { switch (mode) {
case REVERSE_ORDER: case REVERSE_ORDER:
return reverseOrder(totalPages); return reverseOrder(totalPages);
@@ -135,6 +148,8 @@ public class RearrangePagesPDFController {
return duplexSort(totalPages); return duplexSort(totalPages);
case BOOKLET_SORT: case BOOKLET_SORT:
return bookletSort(totalPages); return bookletSort(totalPages);
case SIDE_STITCH_BOOKLET_SORT:
return sideStitchBooklet(totalPages);
case ODD_EVEN_SPLIT: case ODD_EVEN_SPLIT:
return oddEvenSplit(totalPages); return oddEvenSplit(totalPages);
case REMOVE_FIRST: case REMOVE_FIRST:
@@ -154,16 +169,10 @@ public class RearrangePagesPDFController {
@PostMapping(consumes = "multipart/form-data", value = "/rearrange-pages") @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") @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<byte[]> rearrangePages( public ResponseEntity<byte[]> rearrangePages(@ModelAttribute RearrangePagesRequest request) throws IOException {
@RequestPart(required = true, value = "fileInput") @Parameter(description = "The input PDF file to rearrange pages") MultipartFile pdfFile, MultipartFile pdfFile = request.getFileInput();
@RequestParam(required = false, value = "pageOrder") @Parameter(description = "The new page order as a comma-separated list of page numbers, page ranges (e.g., '1,3,5-7'), 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')") String pageOrder, String pageOrder = request.getPageNumbers();
@RequestParam(required = false, value = "customMode") @Parameter(schema = @Schema(implementation = CustomMode.class, description = "The custom mode for page rearrangement. " String sortType = request.getCustomMode();
+ "Valid values are:\n" + "REVERSE_ORDER: Reverses the order of all pages.\n"
+ "DUPLEX_SORT: Sorts pages as if all fronts were scanned then all backs in reverse (1, n, 2, n-1, ...). "
+ "BOOKLET_SORT: Arranges pages for booklet printing (last, first, second, second last, ...).\n"
+ "ODD_EVEN_SPLIT: Splits and arranges pages into odd and even numbered pages.\n"
+ "REMOVE_FIRST: Removes the first page.\n" + "REMOVE_LAST: Removes the last page.\n"
+ "REMOVE_FIRST_AND_LAST: Removes both the first and the last pages.\n")) String customMode) {
try { try {
// Load the input PDF // Load the input PDF
PDDocument document = PDDocument.load(pdfFile.getInputStream()); PDDocument document = PDDocument.load(pdfFile.getInputStream());
@@ -171,15 +180,14 @@ public class RearrangePagesPDFController {
// Split the page order string into an array of page numbers or range of numbers // Split the page order string into an array of page numbers or range of numbers
String[] pageOrderArr = pageOrder != null ? pageOrder.split(",") : new String[0]; String[] pageOrderArr = pageOrder != null ? pageOrder.split(",") : new String[0];
int totalPages = document.getNumberOfPages(); int totalPages = document.getNumberOfPages();
System.out.println("pageOrder=" + pageOrder);
System.out.println("customMode length =" + customMode.length());
List<Integer> newPageOrder; List<Integer> newPageOrder;
if (customMode != null && customMode.length() > 0) { if (sortType != null && sortType.length() > 0) {
newPageOrder = processCustomMode(customMode, totalPages); newPageOrder = processSortTypes(sortType, totalPages);
} else { } else {
newPageOrder = GeneralUtils.parsePageList(pageOrderArr, totalPages); 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 // Create a new list to hold the pages in the new order
List<PDPage> newPages = new ArrayList<>(); List<PDPage> newPages = new ArrayList<>();
for (int i = 0; i < newPageOrder.size(); i++) { for (int i = 0; i < newPageOrder.size(); i++) {

View File

@@ -8,18 +8,19 @@ import org.apache.pdfbox.pdmodel.PDPageTree;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import stirling.software.SPDF.model.api.general.RotatePDFRequest;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@RequestMapping("/api/v1/general")
@Tag(name = "General", description = "General APIs") @Tag(name = "General", description = "General APIs")
public class RotationController { public class RotationController {
@@ -31,13 +32,9 @@ public class RotationController {
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" 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<byte[]> rotatePDF( public ResponseEntity<byte[]> rotatePDF(
@RequestPart(required = true, value = "fileInput") @ModelAttribute RotatePDFRequest request) throws IOException {
@Parameter(description = "The PDF file to be rotated", required = true) MultipartFile pdfFile = request.getFileInput();
MultipartFile pdfFile, Integer angle = request.getAngle();
@RequestParam("angle")
@Parameter(description = "The angle by which to rotate the PDF file. This should be a multiple of 90.", example = "90", required = true)
Integer angle) throws IOException {
// Load the PDF document // Load the PDF document
PDDocument document = PDDocument.load(pdfFile.getBytes()); PDDocument document = PDDocument.load(pdfFile.getBytes());

View File

@@ -1,48 +1,32 @@
package stirling.software.SPDF.controller.api; package stirling.software.SPDF.controller.api;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.canvas.parser.EventType;
import com.itextpdf.kernel.pdf.canvas.parser.PdfCanvasProcessor;
import com.itextpdf.kernel.pdf.canvas.parser.data.IEventData;
import com.itextpdf.kernel.pdf.canvas.parser.data.TextRenderInfo;
import com.itextpdf.kernel.pdf.canvas.parser.listener.IEventListener;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import stirling.software.SPDF.model.api.general.ScalePagesRequest;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@RequestMapping("/api/v1/general")
@Tag(name = "General", description = "General APIs") @Tag(name = "General", description = "General APIs")
public class ScalePagesController { public class ScalePagesController {
@@ -50,194 +34,77 @@ public class ScalePagesController {
@PostMapping(value = "/scale-pages", consumes = "multipart/form-data") @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") @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<byte[]> scalePages( public ResponseEntity<byte[]> scalePages(@ModelAttribute ScalePagesRequest request) throws IOException {
@Parameter(description = "The input PDF file", required = true) @RequestParam("fileInput") MultipartFile file, MultipartFile file = request.getFileInput();
@Parameter(description = "The scale of pages in the output PDF. Acceptable values are A0-A10, B0-B9, LETTER, TABLOID, LEDGER, LEGAL, EXECUTIVE.", required = true, schema = @Schema(type = "string", allowableValues = { String targetPDRectangle = request.getPageSize();
"A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "A10", "B0", "B1", "B2", "B3", "B4", float scaleFactor = request.getScaleFactor();
"B5", "B6", "B7", "B8", "B9", "LETTER", "TABLOID", "LEDGER", "LEGAL",
"EXECUTIVE" })) @RequestParam("pageSize") String targetPageSize,
@Parameter(description = "The scale of the content on the pages of the output PDF. Acceptable values are floats.", required = true, schema = @Schema(type = "integer")) @RequestParam("scaleFactor") float scaleFactor)
throws IOException {
Map<String, PageSize> sizeMap = new HashMap<>(); Map<String, PDRectangle> sizeMap = new HashMap<>();
// Add A0 - A10 // Add A0 - A10
sizeMap.put("A0", PageSize.A0); sizeMap.put("A0", PDRectangle.A0);
sizeMap.put("A1", PageSize.A1); sizeMap.put("A1", PDRectangle.A1);
sizeMap.put("A2", PageSize.A2); sizeMap.put("A2", PDRectangle.A2);
sizeMap.put("A3", PageSize.A3); sizeMap.put("A3", PDRectangle.A3);
sizeMap.put("A4", PageSize.A4); sizeMap.put("A4", PDRectangle.A4);
sizeMap.put("A5", PageSize.A5); sizeMap.put("A5", PDRectangle.A5);
sizeMap.put("A6", PageSize.A6); sizeMap.put("A6", PDRectangle.A6);
sizeMap.put("A7", PageSize.A7);
sizeMap.put("A8", PageSize.A8);
sizeMap.put("A9", PageSize.A9);
sizeMap.put("A10", PageSize.A10);
// Add B0 - B9
sizeMap.put("B0", PageSize.B0);
sizeMap.put("B1", PageSize.B1);
sizeMap.put("B2", PageSize.B2);
sizeMap.put("B3", PageSize.B3);
sizeMap.put("B4", PageSize.B4);
sizeMap.put("B5", PageSize.B5);
sizeMap.put("B6", PageSize.B6);
sizeMap.put("B7", PageSize.B7);
sizeMap.put("B8", PageSize.B8);
sizeMap.put("B9", PageSize.B9);
// Add other sizes // Add other sizes
sizeMap.put("LETTER", PageSize.LETTER); sizeMap.put("LETTER", PDRectangle.LETTER);
sizeMap.put("TABLOID", PageSize.TABLOID); sizeMap.put("LEGAL", PDRectangle.LEGAL);
sizeMap.put("LEDGER", PageSize.LEDGER);
sizeMap.put("LEGAL", PageSize.LEGAL);
sizeMap.put("EXECUTIVE", PageSize.EXECUTIVE);
if (!sizeMap.containsKey(targetPageSize)) { if (!sizeMap.containsKey(targetPDRectangle)) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"Invalid pageSize. It must be one of the following: A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10"); "Invalid PDRectangle. It must be one of the following: A0, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10");
} }
PageSize pageSize = sizeMap.get(targetPageSize); PDRectangle targetSize = sizeMap.get(targetPDRectangle);
byte[] bytes = file.getBytes(); PDDocument sourceDocument = PDDocument.load(file.getBytes());
PdfReader reader = new PdfReader(new ByteArrayInputStream(bytes)); PDDocument outputDocument = new PDDocument();
PdfDocument pdfDoc = new PdfDocument(reader);
ByteArrayOutputStream baos = new ByteArrayOutputStream(); int totalPages = sourceDocument.getNumberOfPages();
PdfWriter writer = new PdfWriter(baos); for (int i = 0; i < totalPages; i++) {
PdfDocument outputPdf = new PdfDocument(writer); 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);
int totalPages = pdfDoc.getNumberOfPages(); contentStream.restoreGraphicsState();
contentStream.close();
}
for (int i = 1; i <= totalPages; i++) {
PdfPage page = outputPdf.addNewPage(pageSize);
PdfCanvas pdfCanvas = new PdfCanvas(page);
// Get the page and calculate scaling factors
Rectangle rect = pdfDoc.getPage(i).getPageSize();
float scaleWidth = pageSize.getWidth() / rect.getWidth();
float scaleHeight = pageSize.getHeight() / rect.getHeight();
float scale = Math.min(scaleWidth, scaleHeight) * scaleFactor;
System.out.println("Scale: " + scale);
PdfFormXObject formXObject = pdfDoc.getPage(i).copyAsFormXObject(outputPdf);
float x = (pageSize.getWidth() - rect.getWidth() * scale) / 2; // Center Page
float y = (pageSize.getHeight() - rect.getHeight() * scale) / 2;
// Save the graphics state, apply the transformations, add the object, and then
// restore the graphics state
pdfCanvas.saveState();
pdfCanvas.concatMatrix(scale, 0, 0, scale, x, y);
pdfCanvas.addXObject(formXObject, 0, 0);
pdfCanvas.restoreState();
}
outputPdf.close(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] pdfContent = baos.toByteArray(); outputDocument.save(baos);
pdfDoc.close(); outputDocument.close();
return WebResponseUtils.bytesToWebResponse(pdfContent, sourceDocument.close();
return WebResponseUtils.bytesToWebResponse(baos.toByteArray(),
file.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_scaled.pdf"); file.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_scaled.pdf");
} }
//TODO
@Hidden
@PostMapping(value = "/auto-crop", consumes = "multipart/form-data")
public ResponseEntity<byte[]> cropPdf(@RequestParam("fileInput") MultipartFile file) throws IOException {
byte[] bytes = file.getBytes();
PdfReader reader = new PdfReader(new ByteArrayInputStream(bytes));
PdfDocument pdfDoc = new PdfDocument(reader);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter writer = new PdfWriter(baos);
PdfDocument outputPdf = new PdfDocument(writer);
int totalPages = pdfDoc.getNumberOfPages();
for (int i = 1; i <= totalPages; i++) {
PdfPage page = pdfDoc.getPage(i);
Rectangle originalMediaBox = page.getMediaBox();
Rectangle contentBox = determineContentBox(page);
// Make sure we don't go outside the original media box.
Rectangle intersection = originalMediaBox.getIntersection(contentBox);
page.setCropBox(intersection);
// Copy page to the new document
outputPdf.addPage(page.copyTo(outputPdf));
}
outputPdf.close();
byte[] pdfContent = baos.toByteArray();
pdfDoc.close();
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""
+ file.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_cropped.pdf\"")
.contentType(MediaType.APPLICATION_PDF).body(pdfContent);
}
private Rectangle determineContentBox(PdfPage page) {
// Extract the text from the page and find the bounding box.
TextBoundingRectangleFinder finder = new TextBoundingRectangleFinder();
PdfCanvasProcessor processor = new PdfCanvasProcessor(finder);
processor.processPageContent(page);
return finder.getBoundingBox();
}
private static class TextBoundingRectangleFinder implements IEventListener {
private List<Rectangle> allTextBoxes = new ArrayList<>();
public Rectangle getBoundingBox() {
// Sort the text boxes based on their vertical position
allTextBoxes.sort(Comparator.comparingDouble(Rectangle::getTop));
// Consider a box an outlier if its top is more than 1.5 times the IQR above the
// third quartile.
int q1Index = allTextBoxes.size() / 4;
int q3Index = 3 * allTextBoxes.size() / 4;
double iqr = allTextBoxes.get(q3Index).getTop() - allTextBoxes.get(q1Index).getTop();
double threshold = allTextBoxes.get(q3Index).getTop() + 1.5 * iqr;
// Initialize boundingBox to the first non-outlier box
int i = 0;
while (i < allTextBoxes.size() && allTextBoxes.get(i).getTop() > threshold) {
i++;
}
if (i == allTextBoxes.size()) {
// If all boxes are outliers, just return the first one
return allTextBoxes.get(0);
}
Rectangle boundingBox = allTextBoxes.get(i);
// Extend the bounding box to include all non-outlier boxes
for (; i < allTextBoxes.size(); i++) {
Rectangle textBoundingBox = allTextBoxes.get(i);
if (textBoundingBox.getTop() > threshold) {
// This box is an outlier, skip it
continue;
}
float left = Math.min(boundingBox.getLeft(), textBoundingBox.getLeft());
float bottom = Math.min(boundingBox.getBottom(), textBoundingBox.getBottom());
float right = Math.max(boundingBox.getRight(), textBoundingBox.getRight());
float top = Math.max(boundingBox.getTop(), textBoundingBox.getTop());
// Add a small padding around the bounding box
float padding = 10;
boundingBox = new Rectangle(left - padding, bottom - padding, right - left + 2 * padding,
top - bottom + 2 * padding);
}
return boundingBox;
}
@Override
public void eventOccurred(IEventData data, EventType type) {
if (type == EventType.RENDER_TEXT) {
TextRenderInfo renderInfo = (TextRenderInfo) data;
allTextBoxes.add(renderInfo.getBaseline().getBoundingRectangle());
}
}
@Override
public Set<EventType> getSupportedEvents() {
return Collections.singleton(EventType.RENDER_TEXT);
}
}
} }

View File

@@ -17,19 +17,19 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import stirling.software.SPDF.utils.GeneralUtils; import stirling.software.SPDF.model.api.PDFWithPageNums;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@RequestMapping("/api/v1/general")
@Tag(name = "General", description = "General APIs") @Tag(name = "General", description = "General APIs")
public class SplitPDFController { public class SplitPDFController {
@@ -38,35 +38,16 @@ public class SplitPDFController {
@PostMapping(consumes = "multipart/form-data", value = "/split-pages") @PostMapping(consumes = "multipart/form-data", value = "/split-pages")
@Operation(summary = "Split a PDF file into separate documents", @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") 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<byte[]> splitPdf( public ResponseEntity<byte[]> splitPdf(@ModelAttribute PDFWithPageNums request) throws IOException {
@RequestPart(required = true, value = "fileInput") MultipartFile file = request.getFileInput();
@Parameter(description = "The input PDF file to be split") String pages = request.getPageNumbers();
MultipartFile file,
@RequestParam("pages")
@Parameter(description = "The pages to be included in separate documents. Specify individual page numbers (e.g., '1,3,5'), ranges (e.g., '1-3,5-7'), or 'all' for every page.")
String pages) throws IOException {
// parse user input
// open the pdf document // open the pdf document
InputStream inputStream = file.getInputStream(); InputStream inputStream = file.getInputStream();
PDDocument document = PDDocument.load(inputStream); PDDocument document = PDDocument.load(inputStream);
List<Integer> pageNumbers = new ArrayList<>(); List<Integer> pageNumbers = request.getPageNumbersList(document);
pages = pages.replaceAll("\\s+", ""); // remove whitespaces if(!pageNumbers.contains(document.getNumberOfPages() - 1))
if (pages.toLowerCase().equals("all")) { pageNumbers.add(document.getNumberOfPages()- 1);
for (int i = 0; i < document.getNumberOfPages(); i++) {
pageNumbers.add(i);
}
} else {
String[] splitPoints = pages.split(",");
for (String splitPoint : splitPoints) {
List<Integer> orderedPages = GeneralUtils.parsePageList(new String[] {splitPoint}, document.getNumberOfPages());
pageNumbers.addAll(orderedPages);
}
// Add the last page as a split point
pageNumbers.add(document.getNumberOfPages() - 1);
}
logger.info("Splitting PDF into pages: {}", pageNumbers.stream().map(String::valueOf).collect(Collectors.joining(","))); logger.info("Splitting PDF into pages: {}", pageNumbers.stream().map(String::valueOf).collect(Collectors.joining(",")));
// split the document // split the document

View File

@@ -1,30 +1,29 @@
package stirling.software.SPDF.controller.api; package stirling.software.SPDF.controller.api;
import java.awt.geom.AffineTransform;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import stirling.software.SPDF.model.api.PDFFile;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@RequestMapping("/api/v1/general")
@Tag(name = "General", description = "General APIs") @Tag(name = "General", description = "General APIs")
public class ToSinglePageController { public class ToSinglePageController {
@@ -36,45 +35,52 @@ public class ToSinglePageController {
summary = "Convert a multi-page PDF into a single long page PDF", 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" 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<byte[]> pdfToSinglePage( public ResponseEntity<byte[]> pdfToSinglePage(@ModelAttribute PDFFile request) throws IOException {
@RequestPart(required = true, value = "fileInput")
@Parameter(description = "The input multi-page PDF file to be converted into a single page", required = true)
MultipartFile file) throws IOException {
PdfReader reader = new PdfReader(file.getInputStream()); // Load the source document
PdfDocument sourceDocument = new PdfDocument(reader); PDDocument sourceDocument = PDDocument.load(request.getFileInput().getInputStream());
float totalHeight = 0;
float width = 0;
for (int i = 1; i <= sourceDocument.getNumberOfPages(); i++) { // Calculate total height and max width
Rectangle pageSize = sourceDocument.getPage(i).getPageSize(); float totalHeight = 0;
totalHeight += pageSize.getHeight(); float maxWidth = 0;
if(width < pageSize.getWidth()) for (PDPage page : sourceDocument.getPages()) {
width = pageSize.getWidth(); PDRectangle pageSize = page.getMediaBox();
} totalHeight += pageSize.getHeight();
maxWidth = Math.max(maxWidth, pageSize.getWidth());
}
ByteArrayOutputStream baos = new ByteArrayOutputStream(); // Create new document and page with calculated dimensions
PdfWriter writer = new PdfWriter(baos); PDDocument newDocument = new PDDocument();
PdfDocument newDocument = new PdfDocument(writer); PDPage newPage = new PDPage(new PDRectangle(maxWidth, totalHeight));
PageSize newPageSize = new PageSize(width, totalHeight); newDocument.addPage(newPage);
newDocument.addNewPage(newPageSize);
Document layoutDoc = new Document(newDocument); // Initialize the content stream of the new page
float yOffset = totalHeight; PDPageContentStream contentStream = new PDPageContentStream(newDocument, newPage);
contentStream.close();
LayerUtility layerUtility = new LayerUtility(newDocument);
float yOffset = totalHeight;
for (int i = 1; i <= sourceDocument.getNumberOfPages(); i++) { // For each page, copy its content to the new page at the correct offset
PdfFormXObject pageCopy = sourceDocument.getPage(i).copyAsFormXObject(newDocument); for (PDPage page : sourceDocument.getPages()) {
Image copiedPage = new Image(pageCopy); PDFormXObject form = layerUtility.importPageAsForm(sourceDocument, sourceDocument.getPages().indexOf(page));
copiedPage.setFixedPosition(0, yOffset - sourceDocument.getPage(i).getPageSize().getHeight()); AffineTransform af = AffineTransform.getTranslateInstance(0, yOffset - page.getMediaBox().getHeight());
yOffset -= sourceDocument.getPage(i).getPageSize().getHeight(); layerUtility.wrapInSaveRestore(newPage);
layoutDoc.add(copiedPage); String defaultLayerName = "Layer" + sourceDocument.getPages().indexOf(page);
} layerUtility.appendFormAsLayer(newPage, form, af, defaultLayerName);
yOffset -= page.getMediaBox().getHeight();
}
layoutDoc.close(); ByteArrayOutputStream baos = new ByteArrayOutputStream();
sourceDocument.close(); newDocument.save(baos);
newDocument.close();
sourceDocument.close();
byte[] result = baos.toByteArray(); byte[] result = baos.toByteArray();
return WebResponseUtils.bytesToWebResponse(result, file.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_singlePage.pdf"); return WebResponseUtils.bytesToWebResponse(result, request.getFileInput().getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_singlePage.pdf");
} }
} }

View File

@@ -9,13 +9,16 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; 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.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.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
@@ -23,6 +26,7 @@ import stirling.software.SPDF.config.security.UserService;
import stirling.software.SPDF.model.User; import stirling.software.SPDF.model.User;
@Controller @Controller
@RequestMapping("/api/v1/user")
public class UserController { public class UserController {
@Autowired @Autowired
@@ -39,59 +43,117 @@ public class UserController {
return "redirect:/login?registered=true"; return "redirect:/login?registered=true";
} }
@PostMapping("/change-username") @PostMapping("/change-username-and-password")
public ResponseEntity<String> changeUsername(Principal principal, @RequestParam String currentPassword, @RequestParam String newUsername, HttpServletRequest request, HttpServletResponse response) { public RedirectView changeUsernameAndPassword(Principal principal,
if (principal == null) { @RequestParam String currentPassword,
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("User not authenticated."); @RequestParam String newUsername,
} @RequestParam String newPassword,
HttpServletRequest request,
Optional<User> userOpt = userService.findByUsername(principal.getName()); HttpServletResponse response,
RedirectAttributes redirectAttributes) {
if(userOpt == null || userOpt.isEmpty()) { if (principal == null) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found."); return new RedirectView("/change-creds?messageType=notAuthenticated");
} }
User user = userOpt.get();
if(!userService.isPasswordCorrect(user, currentPassword)) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Current password is incorrect.");
}
if(userService.usernameExists(newUsername)) {
return ResponseEntity.status(HttpStatus.CONFLICT).body("New username already exists.");
}
userService.changeUsername(user, newUsername); Optional<User> 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 // Logout using Spring's utility
new SecurityContextLogoutHandler().logout(request, response, null); new SecurityContextLogoutHandler().logout(request, response, null);
return new RedirectView("/login?messageType=credsUpdated");
return ResponseEntity.ok("Username updated successfully."); }
@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<User> 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") @PostMapping("/change-password")
public ResponseEntity<String> changePassword(Principal principal, @RequestParam String currentPassword, @RequestParam String newPassword, HttpServletRequest request, HttpServletResponse response) { public RedirectView changePassword(Principal principal,
if (principal == null) { @RequestParam String currentPassword,
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("User not authenticated."); @RequestParam String newPassword,
} HttpServletRequest request,
HttpServletResponse response,
RedirectAttributes redirectAttributes) {
if (principal == null) {
return new RedirectView("/account?messageType=notAuthenticated");
}
Optional<User> userOpt = userService.findByUsername(principal.getName()); Optional<User> userOpt = userService.findByUsername(principal.getName());
if(userOpt == null || userOpt.isEmpty()) { if (userOpt == null || userOpt.isEmpty()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found."); return new RedirectView("/account?messageType=userNotFound");
} }
User user = userOpt.get();
if(!userService.isPasswordCorrect(user, currentPassword)) { User user = userOpt.get();
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Current password is incorrect.");
} if (!userService.isPasswordCorrect(user, currentPassword)) {
return new RedirectView("/account?messageType=incorrectPassword");
}
userService.changePassword(user, newPassword); userService.changePassword(user, newPassword);
// Logout using Spring's utility // Logout using Spring's utility
new SecurityContextLogoutHandler().logout(request, response, null); new SecurityContextLogoutHandler().logout(request, response, null);
return ResponseEntity.ok("Password updated successfully."); return new RedirectView("/login?messageType=credsUpdated");
} }
@PostMapping("/updateUserSettings") @PostMapping("/updateUserSettings")
public String updateUserSettings(HttpServletRequest request, Principal principal) { public String updateUserSettings(HttpServletRequest request, Principal principal) {
@@ -114,15 +176,29 @@ public class UserController {
@PreAuthorize("hasRole('ROLE_ADMIN')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping("/admin/saveUser") @PostMapping("/admin/saveUser")
public String saveUser(@RequestParam String username, @RequestParam String password, @RequestParam String role) { public RedirectView saveUser(@RequestParam String username, @RequestParam String password, @RequestParam String role,
userService.saveUser(username, password, role); @RequestParam(name = "forceChange", required = false, defaultValue = "false") boolean forceChange) {
return "redirect:/addUsers"; // Redirect to account page after adding the user
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')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping("/admin/deleteUser/{username}") @PostMapping("/admin/deleteUser/{username}")
public String deleteUser(@PathVariable String 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); userService.deleteUser(username);
return "redirect:/addUsers"; return "redirect:/addUsers";
} }

View File

@@ -14,8 +14,9 @@ import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.Document; import org.w3c.dom.Document;
@@ -26,10 +27,12 @@ import org.xml.sax.InputSource;
import io.swagger.v3.oas.annotations.Hidden; import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; 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.FileToPdf;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@RequestMapping("/api/v1/convert")
@Tag(name = "Convert", description = "Convert APIs") @Tag(name = "Convert", description = "Convert APIs")
public class ConvertEpubToPdf { public class ConvertEpubToPdf {
//TODO //TODO
@@ -40,9 +43,9 @@ public class ConvertEpubToPdf {
description = "This endpoint takes an EPUB file input and converts it to a single PDF." description = "This endpoint takes an EPUB file input and converts it to a single PDF."
) )
public ResponseEntity<byte[]> epubToSinglePdf( public ResponseEntity<byte[]> epubToSinglePdf(
@RequestPart(required = true, value = "fileInput") MultipartFile fileInput) @ModelAttribute GeneralFile request)
throws Exception { throws Exception {
MultipartFile fileInput = request.getFileInput();
if (fileInput == null) { if (fileInput == null) {
throw new IllegalArgumentException("Please provide an EPUB file for conversion."); throw new IllegalArgumentException("Please provide an EPUB file for conversion.");
} }
@@ -71,7 +74,7 @@ public class ConvertEpubToPdf {
// Assuming a pseudo-code function that merges multiple PDFs into one. // Assuming a pseudo-code function that merges multiple PDFs into one.
private byte[] mergeMultiplePdfsIntoOne(List<byte[]> individualPdfs) { private byte[] mergeMultiplePdfsIntoOne(List<byte[]> individualPdfs) {
// You can use a library such as iText or PDFBox to perform the merging here. // You can use a library such as PDFBox to perform the merging here.
// Return the byte[] of the merged PDF. // Return the byte[] of the merged PDF.
return null; return null;
} }

View File

@@ -1,30 +1,33 @@
package stirling.software.SPDF.controller.api.converters; package stirling.software.SPDF.controller.api.converters;
import java.io.IOException;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; 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.FileToPdf;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@Tag(name = "Convert", description = "Convert APIs") @Tag(name = "Convert", description = "Convert APIs")
@RequestMapping("/api/v1/convert")
public class ConvertHtmlToPDF { public class ConvertHtmlToPDF {
@PostMapping(consumes = "multipart/form-data", value = "/html-to-pdf") @PostMapping(consumes = "multipart/form-data", value = "/html/pdf")
@Operation( @Operation(
summary = "Convert an HTML or ZIP (containing HTML and CSS) to PDF", 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." description = "This endpoint takes an HTML or ZIP file input and converts it to a PDF format."
) )
public ResponseEntity<byte[]> HtmlToPdf( public ResponseEntity<byte[]> HtmlToPdf(
@RequestPart(required = true, value = "fileInput") MultipartFile fileInput) throws IOException, InterruptedException { @ModelAttribute GeneralFile request)
throws Exception {
MultipartFile fileInput = request.getFileInput();
if (fileInput == null) { if (fileInput == null) {
throw new IllegalArgumentException("Please provide an HTML or ZIP file for conversion."); throw new IllegalArgumentException("Please provide an HTML or ZIP file for conversion.");

View File

@@ -11,44 +11,35 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag; 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.PdfUtils;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@RequestMapping("/api/v1/convert")
@Tag(name = "Convert", description = "Convert APIs") @Tag(name = "Convert", description = "Convert APIs")
public class ConvertImgPDFController { public class ConvertImgPDFController {
private static final Logger logger = LoggerFactory.getLogger(ConvertImgPDFController.class); private static final Logger logger = LoggerFactory.getLogger(ConvertImgPDFController.class);
@PostMapping(consumes = "multipart/form-data", value = "/pdf-to-img") @PostMapping(consumes = "multipart/form-data", value = "/pdf/img")
@Operation(summary = "Convert PDF to image(s)", @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") 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<Resource> convertToImage( public ResponseEntity<Resource> convertToImage(@ModelAttribute ConvertToImageRequest request) throws IOException {
@RequestPart(required = true, value = "fileInput") MultipartFile file = request.getFileInput();
@Parameter(description = "The input PDF file to be converted") String imageFormat = request.getImageFormat();
MultipartFile file, String singleOrMultiple = request.getSingleOrMultiple();
@RequestParam("imageFormat") String colorType = request.getColorType();
@Parameter(description = "The output image format", schema = @Schema(allowableValues = {"png", "jpeg", "jpg", "gif"})) String dpi = request.getDpi();
String imageFormat,
@RequestParam("singleOrMultiple")
@Parameter(description = "Choose between a single image containing all pages or separate images for each page", schema = @Schema(allowableValues = {"single", "multiple"}))
String singleOrMultiple,
@RequestParam("colorType")
@Parameter(description = "The color type of the output image(s)", schema = @Schema(allowableValues = {"color", "greyscale", "blackwhite"}))
String colorType,
@RequestParam("dpi")
@Parameter(description = "The DPI (dots per inch) for the output image(s)")
String dpi) throws IOException {
byte[] pdfBytes = file.getBytes(); byte[] pdfBytes = file.getBytes();
ImageType colorTypeResult = ImageType.RGB; ImageType colorTypeResult = ImageType.RGB;
if ("greyscale".equals(colorType)) { if ("greyscale".equals(colorType)) {
@@ -83,22 +74,15 @@ public class ConvertImgPDFController {
} }
} }
@PostMapping(consumes = "multipart/form-data", value = "/img-to-pdf") @PostMapping(consumes = "multipart/form-data", value = "/img/pdf")
@Operation(summary = "Convert images to a PDF file", @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?") 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<byte[]> convertToPdf( public ResponseEntity<byte[]> convertToPdf(@ModelAttribute ConvertToPdfRequest request) throws IOException {
@RequestPart(required = true, value = "fileInput") MultipartFile[] file = request.getFileInput();
@Parameter(description = "The input images to be converted to a PDF file") boolean stretchToFit = request.isStretchToFit();
MultipartFile[] file, String colorType = request.getColorType();
@RequestParam(defaultValue = "false", name = "stretchToFit") boolean autoRotate = request.isAutoRotate();
@Parameter(description = "Whether to stretch the images to fit the PDF page or maintain the aspect ratio", example = "false")
boolean stretchToFit,
@RequestParam("colorType")
@Parameter(description = "The color type of the output image(s)", schema = @Schema(allowableValues = {"color", "greyscale", "blackwhite"}))
String colorType,
@RequestParam(defaultValue = "false", name = "autoRotate")
@Parameter(description = "Whether to automatically rotate the images to better fit the PDF page", example = "true")
boolean autoRotate) throws IOException {
// Convert the file to PDF and get the resulting bytes // Convert the file to PDF and get the resulting bytes
byte[] bytes = PdfUtils.imageToPdf(file, stretchToFit, autoRotate, colorType); byte[] bytes = PdfUtils.imageToPdf(file, stretchToFit, autoRotate, colorType);
return WebResponseUtils.bytesToWebResponse(bytes, file[0].getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_converted.pdf"); return WebResponseUtils.bytesToWebResponse(bytes, file[0].getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_converted.pdf");

View File

@@ -1,33 +1,35 @@
package stirling.software.SPDF.controller.api.converters; package stirling.software.SPDF.controller.api.converters;
import java.io.IOException;
import org.commonmark.node.Node; import org.commonmark.node.Node;
import org.commonmark.parser.Parser; import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer; import org.commonmark.renderer.html.HtmlRenderer;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; 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.FileToPdf;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@Tag(name = "Convert", description = "Convert APIs") @Tag(name = "Convert", description = "Convert APIs")
@RequestMapping("/api/v1/convert")
public class ConvertMarkdownToPdf { public class ConvertMarkdownToPdf {
@PostMapping(consumes = "multipart/form-data", value = "/markdown-to-pdf") @PostMapping(consumes = "multipart/form-data", value = "/markdown/pdf")
@Operation( @Operation(
summary = "Convert a Markdown file to PDF", summary = "Convert a Markdown file to PDF",
description = "This endpoint takes a Markdown file input, converts it to HTML, and then to PDF format." description = "This endpoint takes a Markdown file input, converts it to HTML, and then to PDF format."
) )
public ResponseEntity<byte[]> markdownToPdf( public ResponseEntity<byte[]> markdownToPdf(
@RequestPart(required = true, value = "fileInput") MultipartFile fileInput) @ModelAttribute GeneralFile request)
throws IOException, InterruptedException { throws Exception {
MultipartFile fileInput = request.getFileInput();
if (fileInput == null) { if (fileInput == null) {
throw new IllegalArgumentException("Please provide a Markdown file for conversion."); throw new IllegalArgumentException("Please provide a Markdown file for conversion.");

View File

@@ -10,20 +10,22 @@ import java.util.List;
import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.FilenameUtils;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; 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;
import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult; import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@Tag(name = "Convert", description = "Convert APIs") @Tag(name = "Convert", description = "Convert APIs")
@RequestMapping("/api/v1/convert")
public class ConvertOfficeController { public class ConvertOfficeController {
public byte[] convertToPdf(MultipartFile inputFile) throws IOException, InterruptedException { public byte[] convertToPdf(MultipartFile inputFile) throws IOException, InterruptedException {
@@ -58,19 +60,14 @@ public class ConvertOfficeController {
return fileExtension.matches(extensionPattern); return fileExtension.matches(extensionPattern);
} }
@PostMapping(consumes = "multipart/form-data", value = "/file-to-pdf") @PostMapping(consumes = "multipart/form-data", value = "/file/pdf")
@Operation( @Operation(
summary = "Convert a file to a PDF using LibreOffice", 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" description = "This endpoint converts a given file to a PDF using LibreOffice API Input:Any Output:PDF Type:SISO"
) )
public ResponseEntity<byte[]> processFileToPDF( public ResponseEntity<byte[]> processFileToPDF(@ModelAttribute GeneralFile request)
@RequestPart(required = true, value = "fileInput") throws Exception {
@Parameter( MultipartFile inputFile = request.getFileInput();
description = "The input file to be converted to a PDF file using LibreOffice",
required = true
)
MultipartFile inputFile
) throws IOException, InterruptedException {
// unused but can start server instance if startup time is to long // unused but can start server instance if startup time is to long
// LibreOfficeListener.getInstance().start(); // LibreOfficeListener.getInstance().start();

View File

@@ -3,69 +3,67 @@ package stirling.software.SPDF.controller.api.converters;
import java.io.IOException; import java.io.IOException;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag; 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; import stirling.software.SPDF.utils.PDFToFile;
@RestController @RestController
@RequestMapping("/api/v1/convert")
@Tag(name = "Convert", description = "Convert APIs") @Tag(name = "Convert", description = "Convert APIs")
public class ConvertPDFToOffice { public class ConvertPDFToOffice {
@PostMapping(consumes = "multipart/form-data", value = "/pdf-to-html") @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") @Operation(summary = "Convert PDF to HTML", description = "This endpoint converts a PDF file to HTML format. Input:PDF Output:HTML Type:SISO")
public ResponseEntity<byte[]> processPdfToHTML( public ResponseEntity<byte[]> processPdfToHTML(@ModelAttribute PDFFile request)
@RequestPart(required = true, value = "fileInput") @Parameter(description = "The input PDF file to be converted to HTML format", required = true) MultipartFile inputFile) throws Exception {
throws IOException, InterruptedException { MultipartFile inputFile = request.getFileInput();
PDFToFile pdfToFile = new PDFToFile(); PDFToFile pdfToFile = new PDFToFile();
return pdfToFile.processPdfToOfficeFormat(inputFile, "html", "writer_pdf_import"); return pdfToFile.processPdfToOfficeFormat(inputFile, "html", "writer_pdf_import");
} }
@PostMapping(consumes = "multipart/form-data", value = "/pdf-to-presentation") @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") @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<byte[]> processPdfToPresentation( public ResponseEntity<byte[]> processPdfToPresentation(@ModelAttribute PdfToPresentationRequest request) throws IOException, InterruptedException {
@RequestPart(required = true, value = "fileInput") @Parameter(description = "The input PDF file") MultipartFile inputFile, MultipartFile inputFile = request.getFileInput();
@RequestParam("outputFormat") @Parameter(description = "The output Presentation format", schema = @Schema(allowableValues = { String outputFormat = request.getOutputFormat();
"ppt", "pptx", "odp" })) String outputFormat)
throws IOException, InterruptedException {
PDFToFile pdfToFile = new PDFToFile(); PDFToFile pdfToFile = new PDFToFile();
return pdfToFile.processPdfToOfficeFormat(inputFile, outputFormat, "impress_pdf_import"); return pdfToFile.processPdfToOfficeFormat(inputFile, outputFormat, "impress_pdf_import");
} }
@PostMapping(consumes = "multipart/form-data", value = "/pdf-to-text") @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") @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<byte[]> processPdfToRTForTXT( public ResponseEntity<byte[]> processPdfToRTForTXT(@ModelAttribute PdfToTextOrRTFRequest request) throws IOException, InterruptedException {
@RequestPart(required = true, value = "fileInput") @Parameter(description = "The input PDF file") MultipartFile inputFile, MultipartFile inputFile = request.getFileInput();
@RequestParam("outputFormat") @Parameter(description = "The output Text or RTF format", schema = @Schema(allowableValues = { String outputFormat = request.getOutputFormat();
"rtf", "txt:Text" })) String outputFormat)
throws IOException, InterruptedException {
PDFToFile pdfToFile = new PDFToFile(); PDFToFile pdfToFile = new PDFToFile();
return pdfToFile.processPdfToOfficeFormat(inputFile, outputFormat, "writer_pdf_import"); return pdfToFile.processPdfToOfficeFormat(inputFile, outputFormat, "writer_pdf_import");
} }
@PostMapping(consumes = "multipart/form-data", value = "/pdf-to-word") @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") @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<byte[]> processPdfToWord( public ResponseEntity<byte[]> processPdfToWord(@ModelAttribute PdfToWordRequest request) throws IOException, InterruptedException {
@RequestPart(required = true, value = "fileInput") @Parameter(description = "The input PDF file") MultipartFile inputFile, MultipartFile inputFile = request.getFileInput();
@RequestParam("outputFormat") @Parameter(description = "The output Word document format", schema = @Schema(allowableValues = { String outputFormat = request.getOutputFormat();
"doc", "docx", "odt" })) String outputFormat)
throws IOException, InterruptedException {
PDFToFile pdfToFile = new PDFToFile(); PDFToFile pdfToFile = new PDFToFile();
return pdfToFile.processPdfToOfficeFormat(inputFile, outputFormat, "writer_pdf_import"); return pdfToFile.processPdfToOfficeFormat(inputFile, outputFormat, "writer_pdf_import");
} }
@PostMapping(consumes = "multipart/form-data", value = "/pdf-to-xml") @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") @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<byte[]> processPdfToXML( public ResponseEntity<byte[]> processPdfToXML(@ModelAttribute PDFFile request)
@RequestPart(required = true, value = "fileInput") @Parameter(description = "The input PDF file to be converted to an XML file", required = true) MultipartFile inputFile) throws Exception {
throws IOException, InterruptedException { MultipartFile inputFile = request.getFileInput();
PDFToFile pdfToFile = new PDFToFile(); PDFToFile pdfToFile = new PDFToFile();
return pdfToFile.processPdfToOfficeFormat(inputFile, "xml", "writer_pdf_import"); return pdfToFile.processPdfToOfficeFormat(inputFile, "xml", "writer_pdf_import");

View File

@@ -1,37 +1,37 @@
package stirling.software.SPDF.controller.api.converters; package stirling.software.SPDF.controller.api.converters;
import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; 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;
import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult; import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@RequestMapping("/api/v1/convert")
@Tag(name = "Convert", description = "Convert APIs") @Tag(name = "Convert", description = "Convert APIs")
public class ConvertPDFToPDFA { public class ConvertPDFToPDFA {
@PostMapping(consumes = "multipart/form-data", value = "/pdf-to-pdfa") @PostMapping(consumes = "multipart/form-data", value = "/pdf/pdfa")
@Operation( @Operation(
summary = "Convert a PDF to a PDF/A", 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" 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<byte[]> pdfToPdfA( public ResponseEntity<byte[]> pdfToPdfA(@ModelAttribute PDFFile request)
@RequestPart(required = true, value = "fileInput") throws Exception {
@Parameter(description = "The input PDF file to be converted to a PDF/A file", required = true) MultipartFile inputFile = request.getFileInput();
MultipartFile inputFile) throws IOException, InterruptedException {
// Save the uploaded file to a temporary location // Save the uploaded file to a temporary location
Path tempInputFile = Files.createTempFile("input_", ".pdf"); Path tempInputFile = Files.createTempFile("input_", ".pdf");

View File

@@ -7,13 +7,14 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; 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.GeneralUtils;
import stirling.software.SPDF.utils.ProcessExecutor; import stirling.software.SPDF.utils.ProcessExecutor;
import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult; import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult;
@@ -21,17 +22,16 @@ import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@Tag(name = "Convert", description = "Convert APIs") @Tag(name = "Convert", description = "Convert APIs")
@RequestMapping("/api/v1/convert")
public class ConvertWebsiteToPDF { public class ConvertWebsiteToPDF {
@PostMapping(consumes = "multipart/form-data", value = "/url-to-pdf") @PostMapping(consumes = "multipart/form-data", value = "/url/pdf")
@Operation( @Operation(
summary = "Convert a URL to a PDF", summary = "Convert a URL to a PDF",
description = "This endpoint fetches content from a URL and converts it to a PDF format." description = "This endpoint fetches content from a URL and converts it to a PDF format."
) )
public ResponseEntity<byte[]> urlToPdf( public ResponseEntity<byte[]> urlToPdf(@ModelAttribute UrlToPdfRequest request) throws IOException, InterruptedException {
@RequestParam(required = true, value = "urlInput") String URL = request.getUrlInput();
@Parameter(description = "The input URL to be converted to a PDF file", required = true)
String URL) throws IOException, InterruptedException {
// Validate the URL format // Validate the URL format
if(!URL.matches("^https?://.*") || !GeneralUtils.isValidURL(URL)) { if(!URL.matches("^https?://.*") || !GeneralUtils.isValidURL(URL)) {

View File

@@ -6,29 +6,35 @@ import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag; 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.PdfUtils;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@RequestMapping("/api/v1/filter")
@Tag(name = "Filter", description = "Filter APIs") @Tag(name = "Filter", description = "Filter APIs")
public class FilterController { public class FilterController {
@PostMapping(consumes = "multipart/form-data", value = "/filter-contains-text") @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") @Operation(summary = "Checks if a PDF contains set text, returns true if does", description = "Input:PDF Output:Boolean Type:SISO")
public ResponseEntity<byte[]> containsText( public ResponseEntity<byte[]> containsText(@ModelAttribute ContainsTextRequest request) throws IOException, InterruptedException {
@RequestPart(required = true, value = "fileInput") @Parameter(description = "The input PDF file to be converted to a PDF/A file", required = true) MultipartFile inputFile, MultipartFile inputFile = request.getFileInput();
@Parameter(description = "The text to check for", required = true) String text, String text = request.getText();
@Parameter(description = "The page number to check for text on accepts 'All', ranges like '1-4'", required = false) String pageNumber) String pageNumber = request.getPageNumbers();
throws IOException, InterruptedException {
PDDocument pdfDocument = PDDocument.load(inputFile.getInputStream()); PDDocument pdfDocument = PDDocument.load(inputFile.getInputStream());
if (PdfUtils.hasText(pdfDocument, pageNumber, text)) if (PdfUtils.hasText(pdfDocument, pageNumber, text))
return WebResponseUtils.pdfDocToWebResponse(pdfDocument, inputFile.getOriginalFilename()); return WebResponseUtils.pdfDocToWebResponse(pdfDocument, inputFile.getOriginalFilename());
@@ -38,10 +44,11 @@ public class FilterController {
// TODO // TODO
@PostMapping(consumes = "multipart/form-data", value = "/filter-contains-image") @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") @Operation(summary = "Checks if a PDF contains an image", description = "Input:PDF Output:Boolean Type:SISO")
public ResponseEntity<byte[]> containsImage( public ResponseEntity<byte[]> containsImage(@ModelAttribute PDFWithPageNums request)
@RequestPart(required = true, value = "fileInput") @Parameter(description = "The input PDF file to be converted to a PDF/A file", required = true) MultipartFile inputFile,
@Parameter(description = "The page number to check for image on accepts 'All', ranges like '1-4'", required = false) String pageNumber)
throws IOException, InterruptedException { throws IOException, InterruptedException {
MultipartFile inputFile = request.getFileInput();
String pageNumber = request.getPageNumbers();
PDDocument pdfDocument = PDDocument.load(inputFile.getInputStream()); PDDocument pdfDocument = PDDocument.load(inputFile.getInputStream());
if (PdfUtils.hasImages(pdfDocument, pageNumber)) if (PdfUtils.hasImages(pdfDocument, pageNumber))
return WebResponseUtils.pdfDocToWebResponse(pdfDocument, inputFile.getOriginalFilename()); return WebResponseUtils.pdfDocToWebResponse(pdfDocument, inputFile.getOriginalFilename());
@@ -50,12 +57,10 @@ public class FilterController {
@PostMapping(consumes = "multipart/form-data", value = "/filter-page-count") @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") @Operation(summary = "Checks if a PDF is greater, less or equal to a setPageCount", description = "Input:PDF Output:Boolean Type:SISO")
public ResponseEntity<byte[]> pageCount( public ResponseEntity<byte[]> pageCount(@ModelAttribute PDFComparisonAndCount request) throws IOException, InterruptedException {
@RequestPart(required = true, value = "fileInput") @Parameter(description = "The input PDF file", required = true) MultipartFile inputFile, MultipartFile inputFile = request.getFileInput();
@Parameter(description = "Page Count", required = true) String pageCount, String pageCount = request.getPageCount();
@Parameter(description = "Comparison type", schema = @Schema(description = "The comparison type, accepts Greater, Equal, Less than", allowableValues = { String comparator = request.getComparator();
"Greater", "Equal", "Less" })) String comparator)
throws IOException, InterruptedException {
// Load the PDF // Load the PDF
PDDocument document = PDDocument.load(inputFile.getInputStream()); PDDocument document = PDDocument.load(inputFile.getInputStream());
int actualPageCount = document.getNumberOfPages(); int actualPageCount = document.getNumberOfPages();
@@ -83,12 +88,10 @@ public class FilterController {
@PostMapping(consumes = "multipart/form-data", value = "/filter-page-size") @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") @Operation(summary = "Checks if a PDF is of a certain size", description = "Input:PDF Output:Boolean Type:SISO")
public ResponseEntity<byte[]> pageSize( public ResponseEntity<byte[]> pageSize(@ModelAttribute PageSizeRequest request) throws IOException, InterruptedException {
@RequestPart(required = true, value = "fileInput") @Parameter(description = "The input PDF file", required = true) MultipartFile inputFile, MultipartFile inputFile = request.getFileInput();
@Parameter(description = "Standard Page Size", required = true) String standardPageSize, String standardPageSize = request.getStandardPageSize();
@Parameter(description = "Comparison type", schema = @Schema(description = "The comparison type, accepts Greater, Equal, Less than", allowableValues = { String comparator = request.getComparator();
"Greater", "Equal", "Less" })) String comparator)
throws IOException, InterruptedException {
// Load the PDF // Load the PDF
PDDocument document = PDDocument.load(inputFile.getInputStream()); PDDocument document = PDDocument.load(inputFile.getInputStream());
@@ -126,12 +129,10 @@ public class FilterController {
@PostMapping(consumes = "multipart/form-data", value = "/filter-file-size") @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") @Operation(summary = "Checks if a PDF is a set file size", description = "Input:PDF Output:Boolean Type:SISO")
public ResponseEntity<byte[]> fileSize( public ResponseEntity<byte[]> fileSize(@ModelAttribute FileSizeRequest request) throws IOException, InterruptedException {
@RequestPart(required = true, value = "fileInput") @Parameter(description = "The input PDF file", required = true) MultipartFile inputFile, MultipartFile inputFile = request.getFileInput();
@Parameter(description = "File Size", required = true) String fileSize, String fileSize = request.getFileSize();
@Parameter(description = "Comparison type", schema = @Schema(description = "The comparison type, accepts Greater, Equal, Less than", allowableValues = { String comparator = request.getComparator();
"Greater", "Equal", "Less" })) String comparator)
throws IOException, InterruptedException {
// Get the file size // Get the file size
long actualFileSize = inputFile.getSize(); long actualFileSize = inputFile.getSize();
@@ -159,12 +160,10 @@ public class FilterController {
@PostMapping(consumes = "multipart/form-data", value = "/filter-page-rotation") @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") @Operation(summary = "Checks if a PDF is of a certain rotation", description = "Input:PDF Output:Boolean Type:SISO")
public ResponseEntity<byte[]> pageRotation( public ResponseEntity<byte[]> pageRotation(@ModelAttribute PageRotationRequest request) throws IOException, InterruptedException {
@RequestPart(required = true, value = "fileInput") @Parameter(description = "The input PDF file", required = true) MultipartFile inputFile, MultipartFile inputFile = request.getFileInput();
@Parameter(description = "Rotation in degrees", required = true) int rotation, int rotation = request.getRotation();
@Parameter(description = "Comparison type", schema = @Schema(description = "The comparison type, accepts Greater, Equal, Less than", allowableValues = { String comparator = request.getComparator();
"Greater", "Equal", "Less" })) String comparator)
throws IOException, InterruptedException {
// Load the PDF // Load the PDF
PDDocument document = PDDocument.load(inputFile.getInputStream()); PDDocument document = PDDocument.load(inputFile.getInputStream());

View File

@@ -1,4 +1,4 @@
package stirling.software.SPDF.controller.api.other; package stirling.software.SPDF.controller.api.misc;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
@@ -11,18 +11,19 @@ import org.apache.pdfbox.text.TextPosition;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import stirling.software.SPDF.model.api.misc.ExtractHeaderRequest;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@Tag(name = "Other", description = "Other APIs") @RequestMapping("/api/v1/misc")
@Tag(name = "Misc", description = "Miscellaneous APIs")
public class AutoRenameController { public class AutoRenameController {
private static final Logger logger = LoggerFactory.getLogger(AutoRenameController.class); private static final Logger logger = LoggerFactory.getLogger(AutoRenameController.class);
@@ -32,10 +33,9 @@ public class AutoRenameController {
@PostMapping(consumes = "multipart/form-data", value = "/auto-rename") @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") @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<byte[]> extractHeader( public ResponseEntity<byte[]> extractHeader(@ModelAttribute ExtractHeaderRequest request) throws Exception {
@RequestPart(value = "fileInput") @Parameter(description = "The input PDF file from which the header is to be extracted.", required = true) MultipartFile file, MultipartFile file = request.getFileInput();
@RequestParam(required = false, defaultValue = "false") @Parameter(description = "Flag indicating whether to use the first text as a fallback if no suitable title is found. Defaults to false.", required = false) Boolean useFirstTextAsFallback) Boolean useFirstTextAsFallback = request.isUseFirstTextAsFallback();
throws Exception {
PDDocument document = PDDocument.load(file.getInputStream()); PDDocument document = PDDocument.load(file.getInputStream());
PDFTextStripper reader = new PDFTextStripper() { PDFTextStripper reader = new PDFTextStripper() {

View File

@@ -1,4 +1,4 @@
package stirling.software.SPDF.controller.api.other; package stirling.software.SPDF.controller.api.misc;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte; import java.awt.image.DataBufferByte;
import java.awt.image.DataBufferInt; import java.awt.image.DataBufferInt;
@@ -16,8 +16,9 @@ import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer; import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
@@ -30,20 +31,22 @@ import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer; import com.google.zxing.common.HybridBinarizer;
import io.swagger.v3.oas.annotations.Operation; 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.api.misc.AutoSplitPdfRequest;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@RequestMapping("/api/v1/misc")
@Tag(name = "Misc", description = "Miscellaneous APIs")
public class AutoSplitPdfController { public class AutoSplitPdfController {
private static final String QR_CONTENT = "https://github.com/Frooodle/Stirling-PDF"; private static final String QR_CONTENT = "https://github.com/Frooodle/Stirling-PDF";
@PostMapping(value = "/auto-split-pdf", consumes = "multipart/form-data") @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") @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<byte[]> autoSplitPdf( public ResponseEntity<byte[]> autoSplitPdf(@ModelAttribute AutoSplitPdfRequest request) throws IOException {
@RequestParam("fileInput") @Parameter(description = "The input PDF file which needs to be split into separate documents based on QR code boundaries.", required = true) MultipartFile file, MultipartFile file = request.getFileInput();
@RequestParam(value ="duplexMode",defaultValue = "false") @Parameter(description = "Flag indicating if the duplex mode is active, where the page after the divider also gets removed.", required = false) boolean duplexMode) boolean duplexMode = request.isDuplexMode();
throws IOException {
InputStream inputStream = file.getInputStream(); InputStream inputStream = file.getInputStream();
PDDocument document = PDDocument.load(inputStream); PDDocument document = PDDocument.load(inputStream);

View File

@@ -1,4 +1,4 @@
package stirling.software.SPDF.controller.api.other; package stirling.software.SPDF.controller.api.misc;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.IOException; import java.io.IOException;
@@ -20,22 +20,23 @@ import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.text.PDFTextStripper; import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; 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.PdfUtils;
import stirling.software.SPDF.utils.ProcessExecutor; import stirling.software.SPDF.utils.ProcessExecutor;
import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult; import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@Tag(name = "Other", description = "Other APIs") @RequestMapping("/api/v1/misc")
@Tag(name = "Misc", description = "Miscellaneous APIs")
public class BlankPageController { public class BlankPageController {
@PostMapping(consumes = "multipart/form-data", value = "/remove-blanks") @PostMapping(consumes = "multipart/form-data", value = "/remove-blanks")
@@ -43,16 +44,10 @@ public class BlankPageController {
summary = "Remove blank pages from a PDF file", 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" 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<byte[]> removeBlankPages( public ResponseEntity<byte[]> removeBlankPages(@ModelAttribute RemoveBlankPagesRequest request) throws IOException, InterruptedException {
@RequestPart(required = true, value = "fileInput") MultipartFile inputFile = request.getFileInput();
@Parameter(description = "The input PDF file from which blank pages will be removed", required = true) int threshold = request.getThreshold();
MultipartFile inputFile, float whitePercent = request.getWhitePercent();
@RequestParam(defaultValue = "10", name = "threshold")
@Parameter(description = "The threshold value to determine blank pages", example = "10")
int threshold,
@RequestParam(defaultValue = "99.9", name = "whitePercent")
@Parameter(description = "The percentage of white color on a page to consider it as blank", example = "99.9")
float whitePercent) throws IOException, InterruptedException {
PDDocument document = null; PDDocument document = null;
try { try {

View File

@@ -1,4 +1,4 @@
package stirling.software.SPDF.controller.api.other; package stirling.software.SPDF.controller.api.misc;
import java.awt.Image; import java.awt.Image;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
@@ -22,35 +22,34 @@ import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag; 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.GeneralUtils;
import stirling.software.SPDF.utils.ProcessExecutor; import stirling.software.SPDF.utils.ProcessExecutor;
import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult; import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@Tag(name = "Other", description = "Other APIs") @RequestMapping("/api/v1/misc")
@Tag(name = "Misc", description = "Miscellaneous APIs")
public class CompressController { public class CompressController {
private static final Logger logger = LoggerFactory.getLogger(CompressController.class); private static final Logger logger = LoggerFactory.getLogger(CompressController.class);
@PostMapping(consumes = "multipart/form-data", value = "/compress-pdf") @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") @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<byte[]> optimizePdf( public ResponseEntity<byte[]> optimizePdf(@ModelAttribute OptimizePdfRequest request) throws Exception {
@RequestPart(value = "fileInput") @Parameter(description = "The input PDF file to be optimized.", required = true) MultipartFile inputFile, MultipartFile inputFile = request.getFileInput();
@RequestParam(required = false, value = "optimizeLevel") @Parameter(description = "The level of optimization to apply to the PDF file. Higher values indicate greater compression but may reduce quality.", schema = @Schema(allowableValues = { Integer optimizeLevel = request.getOptimizeLevel();
"1", "2", "3", "4", "5" })) Integer optimizeLevel, String expectedOutputSizeString = request.getExpectedOutputSize();
@RequestParam(value = "expectedOutputSize", required = false) @Parameter(description = "The expected output size, e.g. '100MB', '25KB', etc.", required = false) String expectedOutputSizeString)
throws Exception {
if(expectedOutputSizeString == null && optimizeLevel == null) { if(expectedOutputSizeString == null && optimizeLevel == null) {
throw new Exception("Both expected output size and optimize level are not specified"); throw new Exception("Both expected output size and optimize level are not specified");

View File

@@ -1,4 +1,4 @@
package stirling.software.SPDF.controller.api.other; package stirling.software.SPDF.controller.api.misc;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
@@ -24,20 +24,21 @@ import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController; 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.Operation;
import io.swagger.v3.oas.annotations.Parameter; 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 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;
import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult; import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@Tag(name = "Other", description = "Other APIs") @RequestMapping("/api/v1/misc")
@Tag(name = "Misc", description = "Miscellaneous APIs")
public class ExtractImageScansController { public class ExtractImageScansController {
private static final Logger logger = LoggerFactory.getLogger(ExtractImageScansController.class); private static final Logger logger = LoggerFactory.getLogger(ExtractImageScansController.class);
@@ -46,26 +47,16 @@ public class ExtractImageScansController {
@Operation(summary = "Extract image scans from an input file", @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") 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<byte[]> extractImageScans( public ResponseEntity<byte[]> extractImageScans(
@RequestPart(required = true, value = "fileInput") @RequestBody(
@Parameter(description = "The input file containing image scans") description = "Form data containing file and extraction parameters",
MultipartFile inputFile, required = true,
@RequestParam(name = "angle_threshold", defaultValue = "5") content = @Content(
@Parameter(description = "The angle threshold for the image scan extraction", example = "5") mediaType = "multipart/form-data",
int angleThreshold, schema = @Schema(implementation = ExtractImageScansRequest.class) // This should represent your form's structure
@RequestParam(name = "tolerance", defaultValue = "20") )
@Parameter(description = "The tolerance for the image scan extraction", example = "20") )
int tolerance, ExtractImageScansRequest form) throws IOException, InterruptedException {
@RequestParam(name = "min_area", defaultValue = "8000") String fileName = form.getFileInput().getOriginalFilename();
@Parameter(description = "The minimum area for the image scan extraction", example = "8000")
int minArea,
@RequestParam(name = "min_contour_area", defaultValue = "500")
@Parameter(description = "The minimum contour area for the image scan extraction", example = "500")
int minContourArea,
@RequestParam(name = "border_size", defaultValue = "1")
@Parameter(description = "The border size for the image scan extraction", example = "1")
int borderSize) throws IOException, InterruptedException {
String fileName = inputFile.getOriginalFilename();
String extension = fileName.substring(fileName.lastIndexOf(".") + 1); String extension = fileName.substring(fileName.lastIndexOf(".") + 1);
List<String> images = new ArrayList<>(); List<String> images = new ArrayList<>();
@@ -73,7 +64,7 @@ public class ExtractImageScansController {
// Check if input file is a PDF // Check if input file is a PDF
if (extension.equalsIgnoreCase("pdf")) { if (extension.equalsIgnoreCase("pdf")) {
// Load PDF document // Load PDF document
try (PDDocument document = PDDocument.load(new ByteArrayInputStream(inputFile.getBytes()))) { try (PDDocument document = PDDocument.load(new ByteArrayInputStream(form.getFileInput().getBytes()))) {
PDFRenderer pdfRenderer = new PDFRenderer(document); PDFRenderer pdfRenderer = new PDFRenderer(document);
int pageCount = document.getNumberOfPages(); int pageCount = document.getNumberOfPages();
images = new ArrayList<>(); images = new ArrayList<>();
@@ -93,7 +84,7 @@ public class ExtractImageScansController {
} }
} else { } else {
Path tempInputFile = Files.createTempFile("input_", "." + extension); Path tempInputFile = Files.createTempFile("input_", "." + extension);
Files.copy(inputFile.getInputStream(), tempInputFile, StandardCopyOption.REPLACE_EXISTING); Files.copy(form.getFileInput().getInputStream(), tempInputFile, StandardCopyOption.REPLACE_EXISTING);
// Add input file path to images list // Add input file path to images list
images.add(tempInputFile.toString()); images.add(tempInputFile.toString());
} }
@@ -109,11 +100,11 @@ public class ExtractImageScansController {
"./scripts/split_photos.py", "./scripts/split_photos.py",
images.get(i), images.get(i),
tempDir.toString(), tempDir.toString(),
"--angle_threshold", String.valueOf(angleThreshold), "--angle_threshold", String.valueOf(form.getAngleThreshold()),
"--tolerance", String.valueOf(tolerance), "--tolerance", String.valueOf(form.getTolerance()),
"--min_area", String.valueOf(minArea), "--min_area", String.valueOf(form.getMinArea()),
"--min_contour_area", String.valueOf(minContourArea), "--min_contour_area", String.valueOf(form.getMinContourArea()),
"--border_size", String.valueOf(borderSize) "--border_size", String.valueOf(form.getBorderSize())
)); ));

View File

@@ -1,4 +1,4 @@
package stirling.software.SPDF.controller.api.other; package stirling.software.SPDF.controller.api.misc;
import java.awt.Graphics2D; import java.awt.Graphics2D;
import java.awt.Image; import java.awt.Image;
@@ -20,19 +20,19 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import stirling.software.SPDF.model.api.PDFWithImageFormatRequest;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@Tag(name = "Other", description = "Other APIs") @RequestMapping("/api/v1/misc")
@Tag(name = "Misc", description = "Miscellaneous APIs")
public class ExtractImagesController { public class ExtractImagesController {
private static final Logger logger = LoggerFactory.getLogger(ExtractImagesController.class); private static final Logger logger = LoggerFactory.getLogger(ExtractImagesController.class);
@@ -40,13 +40,9 @@ public class ExtractImagesController {
@PostMapping(consumes = "multipart/form-data", value = "/extract-images") @PostMapping(consumes = "multipart/form-data", value = "/extract-images")
@Operation(summary = "Extract images from a PDF file", @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") 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<byte[]> extractImages( public ResponseEntity<byte[]> extractImages(@ModelAttribute PDFWithImageFormatRequest request) throws IOException {
@RequestPart(required = true, value = "fileInput") MultipartFile file = request.getFileInput();
@Parameter(description = "The input PDF file containing images") String format = request.getFormat();
MultipartFile file,
@RequestParam("format")
@Parameter(description = "The output image format e.g., 'png', 'jpeg', or 'gif'", schema = @Schema(allowableValues = {"png", "jpeg", "gif"}))
String format) throws IOException {
System.out.println(System.currentTimeMillis() + "file=" + file.getName() + ", format=" + format); System.out.println(System.currentTimeMillis() + "file=" + file.getName() + ", format=" + format);
PDDocument document = PDDocument.load(file.getBytes()); PDDocument document = PDDocument.load(file.getBytes());

View File

@@ -1,4 +1,4 @@
package stirling.software.SPDF.controller.api.other; package stirling.software.SPDF.controller.api.misc;
import java.awt.Color; import java.awt.Color;
import java.awt.geom.AffineTransform; import java.awt.geom.AffineTransform;
@@ -9,6 +9,7 @@ import java.awt.image.BufferedImageOp;
import java.awt.image.ConvolveOp; import java.awt.image.ConvolveOp;
import java.awt.image.Kernel; import java.awt.image.Kernel;
import java.awt.image.RescaleOp; import java.awt.image.RescaleOp;
import java.io.ByteArrayOutputStream;
//Required for file input/output //Required for file input/output
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@@ -29,21 +30,21 @@ import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import com.itextpdf.io.source.ByteArrayOutputStream;
import io.swagger.v3.oas.annotations.Hidden; import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import stirling.software.SPDF.model.api.PDFFile;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@Tag(name = "Other", description = "Other APIs") @RequestMapping("/api/v1/misc")
@Tag(name = "Misc", description = "Miscellaneous APIs")
public class FakeScanControllerWIP { public class FakeScanControllerWIP {
private static final Logger logger = LoggerFactory.getLogger(FakeScanControllerWIP.class); private static final Logger logger = LoggerFactory.getLogger(FakeScanControllerWIP.class);
@@ -55,10 +56,8 @@ public class FakeScanControllerWIP {
summary = "Repair a PDF file", 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." 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<byte[]> repairPdf( public ResponseEntity<byte[]> repairPdf(@ModelAttribute PDFFile request) throws IOException {
@RequestPart(required = true, value = "fileInput") MultipartFile inputFile = request.getFileInput();
@Parameter(description = "The input PDF file to be repaired", required = true)
MultipartFile inputFile) throws IOException, InterruptedException {
PDDocument document = PDDocument.load(inputFile.getBytes()); PDDocument document = PDDocument.load(inputFile.getBytes());
PDFRenderer pdfRenderer = new PDFRenderer(document); PDFRenderer pdfRenderer = new PDFRenderer(document);

View File

@@ -1,4 +1,4 @@
package stirling.software.SPDF.controller.api.other; package stirling.software.SPDF.controller.api.misc;
import java.io.IOException; import java.io.IOException;
import java.text.ParseException; import java.text.ParseException;
@@ -11,19 +11,20 @@ import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation; import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import stirling.software.SPDF.model.api.misc.MetadataRequest;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@Tag(name = "Other", description = "Other APIs") @RequestMapping("/api/v1/misc")
@Tag(name = "Misc", description = "Miscellaneous APIs")
public class MetadataController { public class MetadataController {
@@ -41,44 +42,28 @@ public class MetadataController {
@PostMapping(consumes = "multipart/form-data", value = "/update-metadata") @PostMapping(consumes = "multipart/form-data", value = "/update-metadata")
@Operation(summary = "Update metadata of a PDF file", @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") 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<byte[]> metadata( public ResponseEntity<byte[]> metadata(@ModelAttribute MetadataRequest request) throws IOException {
@RequestPart(required = true, value = "fileInput")
@Parameter(description = "The input PDF file to update metadata") // Extract PDF file from the request object
MultipartFile pdfFile, MultipartFile pdfFile = request.getFileInput();
@RequestParam(value = "deleteAll", required = false, defaultValue = "false")
@Parameter(description = "Delete all metadata if set to true")
Boolean deleteAll,
@RequestParam(value = "author", required = false)
@Parameter(description = "The author of the document")
String author,
@RequestParam(value = "creationDate", required = false)
@Parameter(description = "The creation date of the document (format: yyyy/MM/dd HH:mm:ss)")
String creationDate,
@RequestParam(value = "creator", required = false)
@Parameter(description = "The creator of the document")
String creator,
@RequestParam(value = "keywords", required = false)
@Parameter(description = "The keywords for the document")
String keywords,
@RequestParam(value = "modificationDate", required = false)
@Parameter(description = "The modification date of the document (format: yyyy/MM/dd HH:mm:ss)")
String modificationDate,
@RequestParam(value = "producer", required = false)
@Parameter(description = "The producer of the document")
String producer,
@RequestParam(value = "subject", required = false)
@Parameter(description = "The subject of the document")
String subject,
@RequestParam(value = "title", required = false)
@Parameter(description = "The title of the document")
String title,
@RequestParam(value = "trapped", required = false)
@Parameter(description = "The trapped status of the document")
String trapped,
@Parameter(description = "Map list of key and value of custom parameters, note these must start with customKey and customValue if they are non standard")
@RequestParam Map<String, String> allRequestParams)
throws IOException {
// 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<String, String> allRequestParams = request.getAllRequestParams();
if(allRequestParams == null) {
allRequestParams = new java.util.HashMap<String, String>();
}
// Load the PDF file into a PDDocument // Load the PDF file into a PDDocument
PDDocument document = PDDocument.load(pdfFile.getBytes()); PDDocument document = PDDocument.load(pdfFile.getBytes());

View File

@@ -1,4 +1,4 @@
package stirling.software.SPDF.controller.api.other; package stirling.software.SPDF.controller.api.misc;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
@@ -18,22 +18,22 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag; 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;
import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult; import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@Tag(name = "Other", description = "Other APIs") @RequestMapping("/api/v1/misc")
@Tag(name = "Misc", description = "Miscellaneous APIs")
public class OCRController { public class OCRController {
private static final Logger logger = LoggerFactory.getLogger(OCRController.class); private static final Logger logger = LoggerFactory.getLogger(OCRController.class);
@@ -51,35 +51,16 @@ public class OCRController {
@PostMapping(consumes = "multipart/form-data", value = "/ocr-pdf") @PostMapping(consumes = "multipart/form-data", value = "/ocr-pdf")
@Operation(summary = "Process a PDF file with OCR", @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") 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<byte[]> processPdfWithOCR( public ResponseEntity<byte[]> processPdfWithOCR(@ModelAttribute ProcessPdfWithOcrRequest request) throws IOException, InterruptedException {
@RequestPart(required = true, value = "fileInput") MultipartFile inputFile = request.getFileInput();
@Parameter(description = "The input PDF file to be processed with OCR") List<String> selectedLanguages = request.getLanguages();
MultipartFile inputFile, Boolean sidecar = request.isSidecar();
@RequestParam("languages") Boolean deskew = request.isDeskew();
@Parameter(description = "List of languages to use in OCR processing") Boolean clean = request.isClean();
List<String> selectedLanguages, Boolean cleanFinal = request.isCleanFinal();
@RequestParam(name = "sidecar", required = false) String ocrType = request.getOcrType();
@Parameter(description = "Include OCR text in a sidecar text file if set to true") String ocrRenderType = request.getOcrRenderType();
Boolean sidecar, Boolean removeImagesAfter = request.isRemoveImagesAfter();
@RequestParam(name = "deskew", required = false)
@Parameter(description = "Deskew the input file if set to true")
Boolean deskew,
@RequestParam(name = "clean", required = false)
@Parameter(description = "Clean the input file if set to true")
Boolean clean,
@RequestParam(name = "clean-final", required = false)
@Parameter(description = "Clean the final output if set to true")
Boolean cleanFinal,
@RequestParam(name = "ocrType", required = false)
@Parameter(description = "Specify the OCR type, e.g., 'skip-text', 'force-ocr', or 'Normal'", schema = @Schema(allowableValues = {"skip-text", "force-ocr", "Normal"}))
String ocrType,
@RequestParam(name = "ocrRenderType", required = false, defaultValue = "hocr")
@Parameter(description = "Specify the OCR render type, either 'hocr' or 'sandwich'", schema = @Schema(allowableValues = {"hocr", "sandwich"}))
String ocrRenderType,
@RequestParam(name = "removeImagesAfter", required = false)
@Parameter(description = "Remove images from the output PDF if set to true")
Boolean removeImagesAfter) throws IOException, InterruptedException {
// --output-type pdfa // --output-type pdfa
if (selectedLanguages == null || selectedLanguages.isEmpty()) { if (selectedLanguages == null || selectedLanguages.isEmpty()) {
throw new IOException("Please select at least one language."); throw new IOException("Please select at least one language.");

View File

@@ -1,4 +1,4 @@
package stirling.software.SPDF.controller.api.other; package stirling.software.SPDF.controller.api.misc;
import java.io.IOException; import java.io.IOException;
@@ -6,20 +6,21 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; 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.PdfUtils;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@Tag(name = "Other", description = "Other APIs") @RequestMapping("/api/v1/misc")
@Tag(name = "Misc", description = "Miscellaneous APIs")
public class OverlayImageController { public class OverlayImageController {
private static final Logger logger = LoggerFactory.getLogger(OverlayImageController.class); private static final Logger logger = LoggerFactory.getLogger(OverlayImageController.class);
@@ -29,22 +30,12 @@ public class OverlayImageController {
summary = "Overlay image onto a PDF file", 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" 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<byte[]> overlayImage( public ResponseEntity<byte[]> overlayImage(@ModelAttribute OverlayImageRequest request) {
@RequestPart(required = true, value = "fileInput") MultipartFile pdfFile = request.getFileInput();
@Parameter(description = "The input PDF file to overlay the image onto.", required = true) MultipartFile imageFile = request.getImageFile();
MultipartFile pdfFile, float x = request.getX();
@RequestParam("fileInput2") float y = request.getY();
@Parameter(description = "The image file to be overlaid onto the PDF.", required = true) boolean everyPage = request.isEveryPage();
MultipartFile imageFile,
@RequestParam("x")
@Parameter(description = "The x-coordinate at which to place the top-left corner of the image.", example = "0")
float x,
@RequestParam("y")
@Parameter(description = "The y-coordinate at which to place the top-left corner of the image.", example = "0")
float y,
@RequestParam("everyPage")
@Parameter(description = "Whether to overlay the image onto every page of the PDF.", example = "false")
boolean everyPage) {
try { try {
byte[] pdfBytes = pdfFile.getBytes(); byte[] pdfBytes = pdfFile.getBytes();
byte[] imageBytes = imageFile.getBytes(); byte[] imageBytes = imageFile.getBytes();

View File

@@ -0,0 +1,135 @@
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<byte[]> 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<Integer> 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);
}
}

View File

@@ -1,4 +1,4 @@
package stirling.software.SPDF.controller.api.other; package stirling.software.SPDF.controller.api.misc;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
@@ -9,20 +9,22 @@ import java.util.List;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; 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;
import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult; import stirling.software.SPDF.utils.ProcessExecutor.ProcessExecutorResult;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@Tag(name = "Other", description = "Other APIs") @RequestMapping("/api/v1/misc")
@Tag(name = "Misc", description = "Miscellaneous APIs")
public class RepairController { public class RepairController {
private static final Logger logger = LoggerFactory.getLogger(RepairController.class); private static final Logger logger = LoggerFactory.getLogger(RepairController.class);
@@ -32,11 +34,8 @@ public class RepairController {
summary = "Repair a PDF file", 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" 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<byte[]> repairPdf( public ResponseEntity<byte[]> repairPdf(@ModelAttribute PDFFile request) throws IOException, InterruptedException {
@RequestPart(required = true, value = "fileInput") MultipartFile inputFile = request.getFileInput();
@Parameter(description = "The input PDF file to be repaired", required = true)
MultipartFile inputFile) throws IOException, InterruptedException {
// Save the uploaded file to a temporary location // Save the uploaded file to a temporary location
Path tempInputFile = Files.createTempFile("input_", ".pdf"); Path tempInputFile = Files.createTempFile("input_", ".pdf");
inputFile.transferTo(tempInputFile.toFile()); inputFile.transferTo(tempInputFile.toFile());

View File

@@ -0,0 +1,61 @@
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<byte[]> 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<PDActionJavaScript> jsTree = document.getDocumentCatalog().getNames().getJavaScript();
if (jsTree != null) {
Map<String, PDActionJavaScript> jsEntries = jsTree.getNames();
for (Map.Entry<String, PDActionJavaScript> 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");
}
}
}

View File

@@ -1,148 +0,0 @@
package stirling.software.SPDF.controller.api.other;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.properties.TextAlignment;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import stirling.software.SPDF.utils.GeneralUtils;
import stirling.software.SPDF.utils.WebResponseUtils;
@RestController
@Tag(name = "Other", description = "Other 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<byte[]> addPageNumbers(
@Parameter(description = "The input PDF file", required = true) @RequestParam("fileInput") MultipartFile file,
@Parameter(description = "Custom margin: small/medium/large", required = true, schema = @Schema(type = "string", allowableValues = {"small", "medium", "large"})) @RequestParam("customMargin") String customMargin,
@Parameter(description = "Position: 1 of 9 positions", required = true, schema = @Schema(type = "integer", minimum = "1", maximum = "9")) @RequestParam("position") int position,
@Parameter(description = "Starting number", required = true, schema = @Schema(type = "integer", minimum = "1")) @RequestParam("startingNumber") int startingNumber,
@Parameter(description = "Which pages to number, default all", required = false, schema = @Schema(type = "string")) @RequestParam(value = "pagesToNumber", required = false) String pagesToNumber,
@Parameter(description = "Custom text: defaults to just number but can have things like \"Page {n} of {p}\"", required = false, schema = @Schema(type = "string")) @RequestParam(value = "customText", required = false) String customText)
throws IOException {
byte[] fileBytes = file.getBytes();
ByteArrayInputStream bais = new ByteArrayInputStream(fileBytes);
int pageNumber = startingNumber;
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.1f;
break;
default:
marginFactor = 0.035f;
break;
}
float fontSize = 12.0f;
PdfReader reader = new PdfReader(bais);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter writer = new PdfWriter(baos);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
List<Integer> pagesToNumberList = GeneralUtils.parsePageList(pagesToNumber.split(","), pdfDoc.getNumberOfPages());
for (int i : pagesToNumberList) {
PdfPage page = pdfDoc.getPage(i+1);
Rectangle pageSize = page.getPageSize();
PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamAfter(), page.getResources(), pdfDoc);
String text = customText != null ? customText.replace("{n}", String.valueOf(pageNumber)).replace("{total}", String.valueOf(pdfDoc.getNumberOfPages())).replace("{filename}", file.getOriginalFilename().replaceFirst("[.][^.]+$", "")) : String.valueOf(pageNumber);
PdfFont font = PdfFontFactory.createFont(StandardFonts.HELVETICA);
float textWidth = font.getWidth(text, fontSize);
float textHeight = font.getAscent(text, fontSize) - font.getDescent(text, fontSize);
float x, y;
TextAlignment alignment;
int xGroup = (position - 1) % 3;
int yGroup = 2 - (position - 1) / 3;
switch (xGroup) {
case 0: // left
x = pageSize.getLeft() + marginFactor * pageSize.getWidth();
alignment = TextAlignment.LEFT;
break;
case 1: // center
x = pageSize.getLeft() + (pageSize.getWidth()) / 2;
alignment = TextAlignment.CENTER;
break;
default: // right
x = pageSize.getRight() - marginFactor * pageSize.getWidth();
alignment = TextAlignment.RIGHT;
break;
}
switch (yGroup) {
case 0: // bottom
y = pageSize.getBottom() + marginFactor * pageSize.getHeight();
break;
case 1: // middle
y = pageSize.getBottom() + (pageSize.getHeight() ) / 2;
break;
default: // top
y = pageSize.getTop() - marginFactor * pageSize.getHeight();
break;
}
new Canvas(pdfCanvas, page.getPageSize())
.showTextAligned(new Paragraph(text).setFont(font).setFontSize(fontSize), x, y, alignment);
pageNumber++;
}
pdfDoc.close();
byte[] resultBytes = baos.toByteArray();
return WebResponseUtils.bytesToWebResponse(resultBytes, URLEncoder.encode(file.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_numbersAdded.pdf", "UTF-8"), MediaType.APPLICATION_PDF);
}
}

View File

@@ -1,85 +0,0 @@
package stirling.software.SPDF.controller.api.other;
import java.nio.charset.StandardCharsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.itextpdf.kernel.pdf.PdfArray;
import com.itextpdf.kernel.pdf.PdfDictionary;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfName;
import com.itextpdf.kernel.pdf.PdfObject;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfStream;
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.utils.WebResponseUtils;
@RestController
@Tag(name = "Other", description = "Other APIs")
public class ShowJavascript {
private static final Logger logger = LoggerFactory.getLogger(ShowJavascript.class);
@PostMapping(consumes = "multipart/form-data", value = "/show-javascript")
@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<byte[]> extractHeader(
@RequestPart(value = "fileInput") @Parameter(description = "The input PDF file from which the javascript is to be extracted.", required = true) MultipartFile inputFile)
throws Exception {
try (
PdfDocument itextDoc = new PdfDocument(new PdfReader(inputFile.getInputStream()))
) {
String name = "";
String script = "";
String entryName = "File: "+inputFile.getOriginalFilename() + ", Script: ";
//Javascript
PdfDictionary namesDict = itextDoc.getCatalog().getPdfObject().getAsDictionary(PdfName.Names);
if (namesDict != null) {
PdfDictionary javascriptDict = namesDict.getAsDictionary(PdfName.JavaScript);
if (javascriptDict != null) {
PdfArray namesArray = javascriptDict.getAsArray(PdfName.Names);
for (int i = 0; i < namesArray.size(); i += 2) {
if(namesArray.getAsString(i) != null)
name = namesArray.getAsString(i).toString();
PdfObject jsCode = namesArray.get(i+1);
if (jsCode instanceof PdfStream) {
byte[] jsCodeBytes = ((PdfStream)jsCode).getBytes();
String jsCodeStr = new String(jsCodeBytes, StandardCharsets.UTF_8);
script = "//" + entryName + name + "\n" +jsCodeStr;
} else if (jsCode instanceof PdfDictionary) {
// If the JS code is in a dictionary, you'll need to know the key to use.
// Assuming the key is PdfName.JS:
PdfStream jsCodeStream = ((PdfDictionary)jsCode).getAsStream(PdfName.JS);
if (jsCodeStream != null) {
byte[] jsCodeBytes = jsCodeStream.getBytes();
String jsCodeStr = new String(jsCodeBytes, StandardCharsets.UTF_8);
script = "//" + entryName + name + "\n" +jsCodeStr;
}
}
}
}
}
if(script.equals("")) {
script = "PDF '" +inputFile.getOriginalFilename() + "' does not contain Javascript";
}
return WebResponseUtils.bytesToWebResponse(script.getBytes(), name + ".js");
}
}
}

View File

@@ -37,9 +37,9 @@ import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
@@ -51,9 +51,11 @@ import io.swagger.v3.oas.annotations.tags.Tag;
import stirling.software.SPDF.model.ApplicationProperties; import stirling.software.SPDF.model.ApplicationProperties;
import stirling.software.SPDF.model.PipelineConfig; import stirling.software.SPDF.model.PipelineConfig;
import stirling.software.SPDF.model.PipelineOperation; import stirling.software.SPDF.model.PipelineOperation;
import stirling.software.SPDF.model.api.HandleDataRequest;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@RequestMapping("/api/v1/pipeline")
@Tag(name = "Pipeline", description = "Pipeline APIs") @Tag(name = "Pipeline", description = "Pipeline APIs")
public class PipelineController { public class PipelineController {
@@ -418,8 +420,9 @@ public class PipelineController {
} }
@PostMapping("/handleData") @PostMapping("/handleData")
public ResponseEntity<byte[]> handleData(@RequestPart("fileInput") MultipartFile[] files, public ResponseEntity<byte[]> handleData(@ModelAttribute HandleDataRequest request) {
@RequestParam("json") String jsonString) { MultipartFile[] files = request.getFileInputs();
String jsonString = request.getJsonString();
logger.info("Received POST request to /handleData with {} files", files.length); logger.info("Received POST request to /handleData with {} files", files.length);
try { try {
List<Resource> outputFiles = handleFiles(files, jsonString); List<Resource> outputFiles = handleFiles(files, jsonString);

View File

@@ -3,294 +3,254 @@ package stirling.software.SPDF.controller.api.security;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.security.KeyFactory; import java.security.KeyFactory;
import java.security.KeyStore; import java.security.KeyStore;
import java.security.Principal;
import java.security.PrivateKey; import java.security.PrivateKey;
import java.security.Security; import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory; import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.PKCS8EncodedKeySpec;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Arrays; import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.List;
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.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.bouncycastle.util.io.pem.PemReader;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.StampingProperties;
import com.itextpdf.signatures.BouncyCastleDigest;
import com.itextpdf.signatures.DigestAlgorithms;
import com.itextpdf.signatures.IExternalDigest;
import com.itextpdf.signatures.IExternalSignature;
import com.itextpdf.signatures.PdfPKCS7;
import com.itextpdf.signatures.PdfSignatureAppearance;
import com.itextpdf.signatures.PdfSigner;
import com.itextpdf.signatures.PrivateKeySignature;
import com.itextpdf.signatures.SignatureUtil;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import stirling.software.SPDF.model.api.security.SignPDFWithCertRequest;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@RequestMapping("/api/v1/security")
@Tag(name = "Security", description = "Security APIs") @Tag(name = "Security", description = "Security APIs")
public class CertSignController { public class CertSignController {
private static final Logger logger = LoggerFactory.getLogger(CertSignController.class); private static final Logger logger = LoggerFactory.getLogger(CertSignController.class);
static { static {
Security.addProvider(new BouncyCastleProvider()); Security.addProvider(new BouncyCastleProvider());
} }
@PostMapping(consumes = "multipart/form-data", value = "/cert-sign") @PostMapping(consumes = "multipart/form-data", value = "/cert-sign")
@Operation(summary = "Sign PDF with a Digital Certificate", @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")
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<byte[]> signPDFWithCert(@ModelAttribute SignPDFWithCertRequest request) throws Exception {
public ResponseEntity<byte[]> signPDF( MultipartFile pdf = request.getFileInput();
@RequestPart(required = true, value = "fileInput") String certType = request.getCertType();
@Parameter(description = "The input PDF file to be signed") MultipartFile privateKeyFile = request.getPrivateKeyFile();
MultipartFile pdf, 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();
@RequestParam(value = "certType", required = false) PrivateKey privateKey = null;
@Parameter(description = "The type of the digital certificate", schema = @Schema(allowableValues = {"PKCS12", "PEM"})) X509Certificate cert = null;
String certType,
@RequestParam(value = "key", required = false) if (certType != null) {
@Parameter(description = "The private key for the digital certificate (required for PEM type certificates)") logger.info("Cert type provided: {}", certType);
MultipartFile privateKeyFile, 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()));
}
@RequestParam(value = "cert", required = false) // Load certificate
@Parameter(description = "The digital certificate (required for PEM type certificates)") CertificateFactory certFactory = CertificateFactory.getInstance("X.509",
MultipartFile certFile, 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);
@RequestParam(value = "p12", required = false) // Load the PDF
@Parameter(description = "The PKCS12 keystore file (required for PKCS12 type certificates)") try (PDDocument document = PDDocument.load(pdf.getBytes())) {
MultipartFile p12File, logger.info("Successfully loaded the provided PDF");
SignatureOptions signatureOptions = new SignatureOptions();
@RequestParam(value = "password", required = false) // If you want to show the signature
@Parameter(description = "The password for the keystore or the private key")
String password,
@RequestParam(value = "showSignature", required = false) // ATTEMPT 2
@Parameter(description = "Whether to visually show the signature in the PDF file") if (showSignature != null && showSignature) {
Boolean showSignature, PDPage page = document.getPage(pageNumber - 1);
@RequestParam(value = "reason", required = false) PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();
@Parameter(description = "The reason for signing the PDF") if (acroForm == null) {
String reason, acroForm = new PDAcroForm(document);
document.getDocumentCatalog().setAcroForm(acroForm);
}
@RequestParam(value = "location", required = false) // Create a new signature field and widget
@Parameter(description = "The location where the PDF is signed")
String location,
@RequestParam(value = "name", required = false) PDSignatureField signatureField = new PDSignatureField(acroForm);
@Parameter(description = "The name of the signer") PDAnnotationWidget widget = signatureField.getWidgets().get(0);
String name, PDRectangle rect = new PDRectangle(100, 100, 200, 50); // Define the rectangle size here
widget.setRectangle(rect);
page.getAnnotations().add(widget);
@RequestParam(value = "pageNumber", required = false) // Set the appearance for the signature field
@Parameter(description = "The page number where the signature should be visible. This is required if showSignature is set to true") PDAppearanceDictionary appearanceDict = new PDAppearanceDictionary();
Integer pageNumber) throws Exception { PDAppearanceStream appearanceStream = new PDAppearanceStream(document);
appearanceStream.setResources(new PDResources());
BouncyCastleProvider provider = new BouncyCastleProvider(); appearanceStream.setBBox(rect);
Security.addProvider(provider); appearanceDict.setNormalAppearance(appearanceStream);
widget.setAppearance(appearanceDict);
PrivateKey privateKey = null; try (PDPageContentStream contentStream = new PDPageContentStream(document, appearanceStream)) {
X509Certificate cert = null; contentStream.beginText();
contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12);
if (certType != null) { contentStream.newLineAtOffset(110, 130);
switch (certType) { contentStream.showText("Digitally signed by: " + (name != null ? name : "Unknown"));
case "PKCS12": contentStream.newLineAtOffset(0, -15);
if (p12File != null) { contentStream.showText("Date: " + new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z").format(new Date()));
KeyStore ks = KeyStore.getInstance("PKCS12"); contentStream.newLineAtOffset(0, -15);
ks.load(new ByteArrayInputStream(p12File.getBytes()), password.toCharArray()); if (reason != null && !reason.isEmpty()) {
String alias = ks.aliases().nextElement(); contentStream.showText("Reason: " + reason);
privateKey = (PrivateKey) ks.getKey(alias, password.toCharArray()); contentStream.newLineAtOffset(0, -15);
cert = (X509Certificate) ks.getCertificate(alias); }
} if (location != null && !location.isEmpty()) {
break; contentStream.showText("Location: " + location);
case "PEM": contentStream.newLineAtOffset(0, -15);
if (privateKeyFile != null && certFile != null) { }
// Load private key contentStream.endText();
KeyFactory keyFactory = KeyFactory.getInstance("RSA", provider); }
if (isPEM(privateKeyFile.getBytes())) {
privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(parsePEM(privateKeyFile.getBytes())));
} else {
privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyFile.getBytes()));
}
// Load certificate // Add the widget annotation to the page
CertificateFactory certFactory = CertificateFactory.getInstance("X.509", provider); page.getAnnotations().add(widget);
if (isPEM(certFile.getBytes())) {
cert = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(parsePEM(certFile.getBytes())));
} else {
cert = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(certFile.getBytes()));
}
}
break;
}
}
Principal principal = cert.getSubjectDN(); // Add the signature field to the acroform
String dn = principal.getName(); acroForm.getFields().add(signatureField);
// Extract the "CN" (Common Name) field from the distinguished name (if it's present) // Handle multiple signatures by ensuring a unique field name
String cn = null; String baseFieldName = "Signature";
for (String part : dn.split(",")) { String signatureFieldName = baseFieldName;
if (part.trim().startsWith("CN=")) { int suffix = 1;
cn = part.trim().substring("CN=".length()); while (acroForm.getField(signatureFieldName) != null) {
break; suffix++;
} signatureFieldName = baseFieldName + suffix;
} }
signatureField.setPartialName(signatureFieldName);
// Set up the PDF reader and stamper }
PdfReader reader = new PdfReader(new ByteArrayInputStream(pdf.getBytes()));
ByteArrayOutputStream signedPdf = new ByteArrayOutputStream(); document.addSignature(signature, signatureOptions);
PdfSigner signer = new PdfSigner(reader, signedPdf, new StampingProperties()); logger.info("Signature added to the PDF document");
// External signing
ExternalSigningSupport externalSigning = document
.saveIncrementalForExternalSigning(new ByteArrayOutputStream());
// Set up the signing appearance byte[] content = IOUtils.toByteArray(externalSigning.getContent());
PdfSignatureAppearance appearance = signer.getSignatureAppearance()
.setReason("Test")
.setLocation("TestLocation");
if (showSignature != null && showSignature) { // Using BouncyCastle to sign
float fontSize = 4; // the font size of the signature CMSTypedData cmsData = new CMSProcessableByteArray(content);
float marginRight = 36; // Margin from the right
float marginBottom = 36; // Margin from the bottom
String signingDate = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z").format(new Date());
// Prepare the text for the digital signature CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
StringBuilder layer2TextBuilder = new StringBuilder(String.format("Digitally signed by: %s\nDate: %s", ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA")
name != null ? name : "Unknown", signingDate)); .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(privateKey);
if (reason != null && !reason.isEmpty()) { gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
layer2TextBuilder.append("\nReason: ").append(reason); new JcaDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build())
} .build(signer, cert));
if (location != null && !location.isEmpty()) { gen.addCertificates(new JcaCertStore(Collections.singletonList(cert)));
layer2TextBuilder.append("\nLocation: ").append(location); CMSSignedData signedData = gen.generate(cmsData, false);
}
String layer2Text = layer2TextBuilder.toString();
// Get the PDF font and measure the width and height of the text block
PdfFont font = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
float textWidth = Arrays.stream(layer2Text.split("\n"))
.map(line -> font.getWidth(line, fontSize))
.max(Float::compare)
.orElse(0f);
int numLines = layer2Text.split("\n").length;
float textHeight = numLines * fontSize;
// Calculate the signature rectangle size byte[] cmsSignature = signedData.getEncoded();
float sigWidth = textWidth + marginRight * 2; logger.info("About to sign content using BouncyCastle");
float sigHeight = textHeight + marginBottom * 2; externalSigning.setSignature(cmsSignature);
logger.info("Signature set successfully");
// Get the page size // After setting the signature, return the resultant PDF
PdfPage page = signer.getDocument().getPage(1); try (ByteArrayOutputStream signedPdfOutput = new ByteArrayOutputStream()) {
Rectangle pageSize = page.getPageSize(); document.save(signedPdfOutput);
return WebResponseUtils.boasToWebResponse(signedPdfOutput,
pdf.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_signed.pdf");
// Define the position and dimension of the signature field } catch (Exception e) {
Rectangle rect = new Rectangle( e.printStackTrace();
pageSize.getRight() - sigWidth - marginRight, }
pageSize.getBottom() + marginBottom, } catch (Exception e) {
sigWidth, e.printStackTrace();
sigHeight }
);
// Configure the appearance of the digital signature return null;
appearance.setPageRect(rect) }
.setContact(name != null ? name : "")
.setPageNumber(pageNumber)
.setReason(reason != null ? reason : "")
.setLocation(location != null ? location : "")
.setReuseAppearance(false)
.setLayer2Text(layer2Text.toString());
signer.setFieldName("sig"); private byte[] parsePEM(byte[] content) throws IOException {
} else { PemReader pemReader = new PemReader(new InputStreamReader(new ByteArrayInputStream(content)));
appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.DESCRIPTION); return pemReader.readPemObject().getContent();
} }
// Set up the signer
PrivateKeySignature pks = new PrivateKeySignature(privateKey, DigestAlgorithms.SHA256, provider.getName());
IExternalSignature pss = new PrivateKeySignature(privateKey, DigestAlgorithms.SHA256, provider.getName());
IExternalDigest digest = new BouncyCastleDigest();
// Call iTex7 to sign the PDF
signer.signDetached(digest, pks, new Certificate[] {cert}, null, null, null, 0, PdfSigner.CryptoStandard.CMS);
System.out.println("Signed PDF size: " + signedPdf.size());
System.out.println("PDF signed = " + isPdfSigned(signedPdf.toByteArray()));
return WebResponseUtils.bytesToWebResponse(signedPdf.toByteArray(), "example.pdf");
}
public boolean isPdfSigned(byte[] pdfData) throws IOException {
InputStream pdfStream = new ByteArrayInputStream(pdfData);
PdfDocument pdfDoc = new PdfDocument(new PdfReader(pdfStream));
SignatureUtil signatureUtil = new SignatureUtil(pdfDoc);
List<String> names = signatureUtil.getSignatureNames();
boolean isSigned = false;
for (String name : names) {
PdfPKCS7 pkcs7 = signatureUtil.readSignatureData(name);
if (pkcs7 != null) {
System.out.println("Signature found.");
// Log certificate details
Certificate[] signChain = pkcs7.getSignCertificateChain();
for (Certificate cert : signChain) {
if (cert instanceof X509Certificate) {
X509Certificate x509 = (X509Certificate) cert;
System.out.println("Certificate Details:");
System.out.println("Subject: " + x509.getSubjectDN());
System.out.println("Issuer: " + x509.getIssuerDN());
System.out.println("Serial: " + x509.getSerialNumber());
System.out.println("Not Before: " + x509.getNotBefore());
System.out.println("Not After: " + x509.getNotAfter());
}
}
isSigned = true;
}
}
pdfDoc.close();
return isSigned;
}
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");
}
private boolean isPEM(byte[] content) {
String contentStr = new String(content);
return contentStr.contains("-----BEGIN") && contentStr.contains("-----END");
}
} }

View File

@@ -1,5 +1,6 @@
package stirling.software.SPDF.controller.api.security; package stirling.software.SPDF.controller.api.security;
import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
@@ -10,53 +11,71 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; 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.cos.COSString;
import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDDocumentInformation; 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.PDStructureElement;
import org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDStructureNode; import org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDStructureNode;
import org.apache.pdfbox.pdmodel.documentinterchange.logicalstructure.PDStructureTreeRoot; 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.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.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.MediaType;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.fields.PdfFormField;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfArray;
import com.itextpdf.kernel.pdf.PdfCatalog;
import com.itextpdf.kernel.pdf.PdfDictionary;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfName;
import com.itextpdf.kernel.pdf.PdfObject;
import com.itextpdf.kernel.pdf.PdfOutline;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfResources;
import com.itextpdf.kernel.pdf.PdfStream;
import com.itextpdf.kernel.pdf.PdfString;
import com.itextpdf.kernel.pdf.annot.PdfAnnotation;
import com.itextpdf.kernel.pdf.annot.PdfFileAttachmentAnnotation;
import com.itextpdf.kernel.pdf.annot.PdfLinkAnnotation;
import com.itextpdf.kernel.pdf.layer.PdfLayer;
import com.itextpdf.kernel.pdf.layer.PdfOCProperties;
import com.itextpdf.kernel.xmp.XMPException;
import com.itextpdf.kernel.xmp.XMPMeta;
import com.itextpdf.kernel.xmp.XMPMetaFactory;
import com.itextpdf.kernel.xmp.options.SerializeOptions;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import stirling.software.SPDF.model.api.PDFFile;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@RequestMapping("/api/v1/security")
@Tag(name = "Security", description = "Security APIs") @Tag(name = "Security", description = "Security APIs")
public class GetInfoOnPDF { public class GetInfoOnPDF {
@@ -64,14 +83,11 @@ public class GetInfoOnPDF {
@PostMapping(consumes = "multipart/form-data", value = "/get-info-on-pdf") @PostMapping(consumes = "multipart/form-data", value = "/get-info-on-pdf")
@Operation(summary = "Summary here", description = "desc. Input:PDF Output:JSON Type:SISO") @Operation(summary = "Summary here", description = "desc. Input:PDF Output:JSON Type:SISO")
public ResponseEntity<byte[]> getPdfInfo( public ResponseEntity<byte[]> getPdfInfo(@ModelAttribute PDFFile request)
@RequestPart(required = true, value = "fileInput")
@Parameter(description = "The input PDF file to get info on", required = true) MultipartFile inputFile)
throws IOException { throws IOException {
MultipartFile inputFile = request.getFileInput();
try ( try (
PDDocument pdfBoxDoc = PDDocument.load(inputFile.getInputStream()); PDDocument pdfBoxDoc = PDDocument.load(inputFile.getInputStream());
PdfDocument itextDoc = new PdfDocument(new PdfReader(inputFile.getInputStream()))
) { ) {
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
ObjectNode jsonOutput = objectMapper.createObjectNode(); ObjectNode jsonOutput = objectMapper.createObjectNode();
@@ -119,21 +135,17 @@ public class GetInfoOnPDF {
boolean hasCompression = false; boolean hasCompression = false;
String compressionType = "None"; String compressionType = "None";
// Check for object streams COSDocument cosDoc = pdfBoxDoc.getDocument();
for (int i = 1; i <= itextDoc.getNumberOfPdfObjects(); i++) { for (COSObject cosObject : cosDoc.getObjects()) {
PdfObject obj = itextDoc.getPdfObject(i); if (cosObject.getObject() instanceof COSStream) {
if (obj != null && obj.isStream() && ((PdfStream) obj).get(PdfName.Type) == PdfName.ObjStm) { COSStream cosStream = (COSStream) cosObject.getObject();
hasCompression = true; if (COSName.OBJ_STM.equals(cosStream.getItem(COSName.TYPE))) {
compressionType = "Object Streams"; hasCompression = true;
break; compressionType = "Object Streams";
break;
}
} }
} }
// If not compressed using object streams, check for compressed Xref tables
if (!hasCompression && itextDoc.getReader().hasRebuiltXref()) {
hasCompression = true;
compressionType = "Compressed Xref or Rebuilt Xref";
}
basicInfo.put("Compression", hasCompression); basicInfo.put("Compression", hasCompression);
if(hasCompression) if(hasCompression)
basicInfo.put("CompressionType", compressionType); basicInfo.put("CompressionType", compressionType);
@@ -143,9 +155,8 @@ public class GetInfoOnPDF {
basicInfo.put("Number of pages", pdfBoxDoc.getNumberOfPages()); basicInfo.put("Number of pages", pdfBoxDoc.getNumberOfPages());
// Page Mode using iText7 PDDocumentCatalog catalog = pdfBoxDoc.getDocumentCatalog();
PdfCatalog catalog = itextDoc.getCatalog(); String pageMode = catalog.getPageMode().name();
PdfName pageMode = catalog.getPdfObject().getAsName(PdfName.PageMode);
// Document Information using PDFBox // Document Information using PDFBox
docInfoNode.put("PDF version", pdfBoxDoc.getVersion()); docInfoNode.put("PDF version", pdfBoxDoc.getVersion());
@@ -156,49 +167,56 @@ public class GetInfoOnPDF {
PdfAcroForm acroForm = PdfAcroForm.getAcroForm(itextDoc, false); PDAcroForm acroForm = pdfBoxDoc.getDocumentCatalog().getAcroForm();
ObjectNode formFieldsNode = objectMapper.createObjectNode(); ObjectNode formFieldsNode = objectMapper.createObjectNode();
if (acroForm != null) { if (acroForm != null) {
for (Map.Entry<String, PdfFormField> entry : acroForm.getFormFields().entrySet()) { for (PDField field : acroForm.getFieldTree()) {
formFieldsNode.put(entry.getKey(), entry.getValue().getValueAsString()); formFieldsNode.put(field.getFullyQualifiedName(), field.getValueAsString());
} }
} }
jsonOutput.set("FormFields", formFieldsNode); jsonOutput.set("FormFields", formFieldsNode);
//embeed files TODO size //embeed files TODO size
ArrayNode embeddedFilesArray = objectMapper.createArrayNode(); if(catalog.getNames() != null) {
if(itextDoc.getCatalog().getPdfObject().getAsDictionary(PdfName.Names) != null) PDEmbeddedFilesNameTreeNode efTree = catalog.getNames().getEmbeddedFiles();
{
PdfDictionary embeddedFiles = itextDoc.getCatalog().getPdfObject().getAsDictionary(PdfName.Names) ArrayNode embeddedFilesArray = objectMapper.createArrayNode();
.getAsDictionary(PdfName.EmbeddedFiles); if (efTree != null) {
if (embeddedFiles != null) { Map<String, PDComplexFileSpecification> efMap = efTree.getNames();
if (efMap != null) {
PdfArray namesArray = embeddedFiles.getAsArray(PdfName.Names); for (Map.Entry<String, PDComplexFileSpecification> entry : efMap.entrySet()) {
if(namesArray != null) { ObjectNode embeddedFileNode = objectMapper.createObjectNode();
for (int i = 0; i < namesArray.size(); i += 2) { embeddedFileNode.put("Name", entry.getKey());
ObjectNode embeddedFileNode = objectMapper.createObjectNode(); PDEmbeddedFile embeddedFile = entry.getValue().getEmbeddedFile();
embeddedFileNode.put("Name", namesArray.getAsString(i).toString()); if (embeddedFile != null) {
// Add other details if required embeddedFileNode.put("FileSize", embeddedFile.getLength()); // size in bytes
embeddedFilesArray.add(embeddedFileNode); }
embeddedFilesArray.add(embeddedFileNode);
}
} }
} }
other.set("EmbeddedFiles", embeddedFilesArray);
} }
}
other.set("EmbeddedFiles", embeddedFilesArray);
//attachments TODO size //attachments TODO size
ArrayNode attachmentsArray = objectMapper.createArrayNode(); ArrayNode attachmentsArray = objectMapper.createArrayNode();
for (int pageNum = 1; pageNum <= itextDoc.getNumberOfPages(); pageNum++) { for (PDPage page : pdfBoxDoc.getPages()) {
for (PdfAnnotation annotation : itextDoc.getPage(pageNum).getAnnotations()) { for (PDAnnotation annotation : page.getAnnotations()) {
if (annotation instanceof PdfFileAttachmentAnnotation) { if (annotation instanceof PDAnnotationFileAttachment) {
PDAnnotationFileAttachment fileAttachmentAnnotation = (PDAnnotationFileAttachment) annotation;
ObjectNode attachmentNode = objectMapper.createObjectNode(); ObjectNode attachmentNode = objectMapper.createObjectNode();
attachmentNode.put("Name", ((PdfFileAttachmentAnnotation) annotation).getName().toString()); attachmentNode.put("Name", fileAttachmentAnnotation.getAttachmentName());
attachmentNode.put("Description", annotation.getContents().getValue()); attachmentNode.put("Description", fileAttachmentAnnotation.getContents());
attachmentsArray.add(attachmentNode); attachmentsArray.add(attachmentNode);
} }
} }
@@ -206,65 +224,54 @@ public class GetInfoOnPDF {
other.set("Attachments", attachmentsArray); other.set("Attachments", attachmentsArray);
//Javascript //Javascript
PdfDictionary namesDict = itextDoc.getCatalog().getPdfObject().getAsDictionary(PdfName.Names); PDDocumentNameDictionary namesDict = catalog.getNames();
ArrayNode javascriptArray = objectMapper.createArrayNode(); ArrayNode javascriptArray = objectMapper.createArrayNode();
if (namesDict != null) { if (namesDict != null) {
PdfDictionary javascriptDict = namesDict.getAsDictionary(PdfName.JavaScript); PDJavascriptNameTreeNode javascriptDict = namesDict.getJavaScript();
if (javascriptDict != null) { if (javascriptDict != null) {
try {
Map<String, PDActionJavaScript> jsEntries = javascriptDict.getNames();
PdfArray namesArray = javascriptDict.getAsArray(PdfName.Names); for (Map.Entry<String, PDActionJavaScript> entry : jsEntries.entrySet()) {
for (int i = 0; i < namesArray.size(); i += 2) { ObjectNode jsNode = objectMapper.createObjectNode();
ObjectNode jsNode = objectMapper.createObjectNode(); jsNode.put("JS Name", entry.getKey());
if(namesArray.getAsString(i) != null)
jsNode.put("JS Name", namesArray.getAsString(i).toString());
// Here we check for a PdfStream object and retrieve the JS code from it PDActionJavaScript jsAction = entry.getValue();
PdfObject jsCode = namesArray.get(i+1); if (jsAction != null) {
if (jsCode instanceof PdfStream) { String jsCodeStr = jsAction.getAction();
byte[] jsCodeBytes = ((PdfStream)jsCode).getBytes(); if (jsCodeStr != null) {
String jsCodeStr = new String(jsCodeBytes, StandardCharsets.UTF_8); jsNode.put("JS Script Length", jsCodeStr.length());
jsNode.put("JS Script Length", jsCodeStr.length()); }
} else if (jsCode instanceof PdfDictionary) {
// If the JS code is in a dictionary, you'll need to know the key to use.
// Assuming the key is PdfName.JS:
PdfStream jsCodeStream = ((PdfDictionary)jsCode).getAsStream(PdfName.JS);
if (jsCodeStream != null) {
byte[] jsCodeBytes = jsCodeStream.getBytes();
String jsCodeStr = new String(jsCodeBytes, StandardCharsets.UTF_8);
jsNode.put("JS Script Character Length", jsCodeStr.length());
} }
javascriptArray.add(jsNode);
} }
} catch (IOException e) {
javascriptArray.add(jsNode); e.printStackTrace();
} }
} }
} }
other.set("JavaScript", javascriptArray); other.set("JavaScript", javascriptArray);
//TODO size //TODO size
PdfOCProperties ocProperties = itextDoc.getCatalog().getOCProperties(false); PDOptionalContentProperties ocProperties = pdfBoxDoc.getDocumentCatalog().getOCProperties();
ArrayNode layersArray = objectMapper.createArrayNode(); ArrayNode layersArray = objectMapper.createArrayNode();
if (ocProperties != null) { if (ocProperties != null) {
for (PDOptionalContentGroup ocg : ocProperties.getOptionalContentGroups()) {
for (PdfLayer layer : ocProperties.getLayers()) {
ObjectNode layerNode = objectMapper.createObjectNode(); ObjectNode layerNode = objectMapper.createObjectNode();
layerNode.put("Name", layer.getPdfObject().getAsString(PdfName.Name).toString()); layerNode.put("Name", ocg.getName());
layersArray.add(layerNode); layersArray.add(layerNode);
} }
} }
other.set("Layers", layersArray); other.set("Layers", layersArray);
//TODO Security //TODO Security
// Digital Signatures using iText7 TODO
@@ -281,13 +288,13 @@ public class GetInfoOnPDF {
} }
boolean isPdfACompliant = checkOutputIntent(itextDoc, "PDF/A"); boolean isPdfACompliant = checkForStandard(pdfBoxDoc, "PDF/A");
boolean isPdfXCompliant = checkOutputIntent(itextDoc, "PDF/X"); boolean isPdfXCompliant = checkForStandard(pdfBoxDoc, "PDF/X");
boolean isPdfECompliant = checkForStandard(itextDoc, "PDF/E"); boolean isPdfECompliant = checkForStandard(pdfBoxDoc, "PDF/E");
boolean isPdfVTCompliant = checkForStandard(itextDoc, "PDF/VT"); boolean isPdfVTCompliant = checkForStandard(pdfBoxDoc, "PDF/VT");
boolean isPdfUACompliant = checkForStandard(itextDoc, "PDF/UA"); boolean isPdfUACompliant = checkForStandard(pdfBoxDoc, "PDF/UA");
boolean isPdfBCompliant = checkForStandard(itextDoc, "PDF/B"); // If you want to check for PDF/Broadcast, though this isn't an official ISO standard. 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(itextDoc, "PDF/SEC"); // This might not be effective since PDF/SEC was under development in 2021. 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/ACompliant", isPdfACompliant);
compliancy.put("IsPDF/XCompliant", isPdfXCompliant); compliancy.put("IsPDF/XCompliant", isPdfXCompliant);
@@ -301,27 +308,39 @@ public class GetInfoOnPDF {
PDOutlineNode root = pdfBoxDoc.getDocumentCatalog().getDocumentOutline();
ArrayNode bookmarksArray = objectMapper.createArrayNode(); ArrayNode bookmarksArray = objectMapper.createArrayNode();
PdfOutline root = itextDoc.getOutlines(false);
if (root != null) { if (root != null) {
for (PdfOutline child : root.getAllChildren()) { for (PDOutlineItem child : root.children()) {
addOutlinesToArray(child, bookmarksArray); addOutlinesToArray(child, bookmarksArray);
} }
} }
other.set("Bookmarks/Outline/TOC", bookmarksArray); other.set("Bookmarks/Outline/TOC", bookmarksArray);
byte[] xmpBytes = itextDoc.getXmpMetadata();
String xmpString = null;
if (xmpBytes != null) { PDMetadata pdMetadata = pdfBoxDoc.getDocumentCatalog().getMetadata();
try {
XMPMeta xmpMeta = XMPMetaFactory.parseFromBuffer(xmpBytes); String xmpString = null;
xmpString = new String(XMPMetaFactory.serializeToBuffer(xmpMeta, new SerializeOptions()));
} catch (XMPException e) { if (pdMetadata != null) {
e.printStackTrace(); try {
} COSInputStream is = pdMetadata.createInputStream();
} DomXmpParser domXmpParser = new DomXmpParser();
other.put("XMPMetadata", xmpString); 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()) { if (pdfBoxDoc.isEncrypted()) {
@@ -331,8 +350,21 @@ public class GetInfoOnPDF {
PDEncryption pdfEncryption = pdfBoxDoc.getEncryption(); PDEncryption pdfEncryption = pdfBoxDoc.getEncryption();
encryption.put("EncryptionAlgorithm", pdfEncryption.getFilter()); encryption.put("EncryptionAlgorithm", pdfEncryption.getFilter());
encryption.put("KeyLength", pdfEncryption.getLength()); encryption.put("KeyLength", pdfEncryption.getLength());
encryption.put("Permissions", pdfBoxDoc.getCurrentAccessPermission().toString()); 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 // Add other encryption-related properties as needed
} else { } else {
encryption.put("IsEncrypted", false); encryption.put("IsEncrypted", false);
@@ -342,43 +374,61 @@ public class GetInfoOnPDF {
ObjectNode pageInfoParent = objectMapper.createObjectNode(); ObjectNode pageInfoParent = objectMapper.createObjectNode();
for (int pageNum = 1; pageNum <= itextDoc.getNumberOfPages(); pageNum++) { for (int pageNum = 0; pageNum < pdfBoxDoc.getNumberOfPages(); pageNum++) {
ObjectNode pageInfo = objectMapper.createObjectNode(); ObjectNode pageInfo = objectMapper.createObjectNode();
// Retrieve the page
PDPage page = pdfBoxDoc.getPage(pageNum);
// Page-level Information // Page-level Information
Rectangle pageSize = itextDoc.getPage(pageNum).getPageSize(); PDRectangle mediaBox = page.getMediaBox();
pageInfo.put("Width", pageSize.getWidth());
pageInfo.put("Height", pageSize.getHeight()); float width = mediaBox.getWidth();
pageInfo.put("Rotation", itextDoc.getPage(pageNum).getRotation()); float height = mediaBox.getHeight();
pageInfo.put("Page Orientation", getPageOrientation(pageSize.getWidth(),pageSize.getHeight()));
pageInfo.put("Standard Size", getPageSize(pageSize.getWidth(),pageSize.getHeight())); pageInfo.put("Width", width);
pageInfo.put("Height", height);
pageInfo.put("Rotation", page.getRotation());
pageInfo.put("Page Orientation", getPageOrientation(width, height));
pageInfo.put("Standard Size", getPageSize(width, height));
// Boxes // Boxes
pageInfo.put("MediaBox", itextDoc.getPage(pageNum).getMediaBox().toString()); pageInfo.put("MediaBox", mediaBox.toString());
pageInfo.put("CropBox", itextDoc.getPage(pageNum).getCropBox().toString());
pageInfo.put("BleedBox", itextDoc.getPage(pageNum).getBleedBox().toString()); // Assuming the following boxes are defined for your document; if not, you may get null values.
pageInfo.put("TrimBox", itextDoc.getPage(pageNum).getTrimBox().toString()); PDRectangle cropBox = page.getCropBox();
pageInfo.put("ArtBox", itextDoc.getPage(pageNum).getArtBox().toString()); 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 // Content Extraction
PDFTextStripper textStripper = new PDFTextStripper(); PDFTextStripper textStripper = new PDFTextStripper();
textStripper.setStartPage(pageNum -1); textStripper.setStartPage(pageNum + 1);
textStripper.setEndPage(pageNum - 1); textStripper.setEndPage(pageNum +1);
String pageText = textStripper.getText(pdfBoxDoc); String pageText = textStripper.getText(pdfBoxDoc);
pageInfo.put("Text Characters Count", pageText.length()); // pageInfo.put("Text Characters Count", pageText.length()); //
// Annotations // Annotations
List<PdfAnnotation> annotations = itextDoc.getPage(pageNum).getAnnotations();
List<PDAnnotation> annotations = page.getAnnotations();
int subtypeCount = 0; int subtypeCount = 0;
int contentsCount = 0; int contentsCount = 0;
for (PdfAnnotation annotation : annotations) { for (PDAnnotation annotation : annotations) {
if(annotation.getSubtype() != null) { if (annotation.getSubtype() != null) {
subtypeCount++; // Increase subtype count subtypeCount++; // Increase subtype count
} }
if(annotation.getContents() != null) { if (annotation.getContents() != null) {
contentsCount++; // Increase contents count contentsCount++; // Increase contents count
} }
} }
@@ -389,25 +439,31 @@ public class GetInfoOnPDF {
annotationsObject.put("ContentsCount", contentsCount); annotationsObject.put("ContentsCount", contentsCount);
pageInfo.set("Annotations", annotationsObject); pageInfo.set("Annotations", annotationsObject);
// Images (simplified) // Images (simplified)
// This part is non-trivial as images can be embedded in multiple ways in a PDF. // 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. // Here is a basic structure to recognize image XObjects on a page.
ArrayNode imagesArray = objectMapper.createArrayNode(); ArrayNode imagesArray = objectMapper.createArrayNode();
PdfResources resources = itextDoc.getPage(pageNum).getResources(); PDResources resources = page.getResources();
for (PdfName name : resources.getResourceNames()) {
PdfObject obj = resources.getResource(name);
if (obj instanceof PdfStream) { for (COSName name : resources.getXObjectNames()) {
PdfStream stream = (PdfStream) obj; PDXObject xObject = resources.getXObject(name);
if (PdfName.Image.equals(stream.getAsName(PdfName.Subtype))) { if (xObject instanceof PDImageXObject) {
ObjectNode imageNode = objectMapper.createObjectNode(); PDImageXObject image = (PDImageXObject) xObject;
imageNode.put("Width", stream.getAsNumber(PdfName.Width).intValue());
imageNode.put("Height", stream.getAsNumber(PdfName.Height).intValue()); ObjectNode imageNode = objectMapper.createObjectNode();
PdfObject colorSpace = stream.get(PdfName.ColorSpace); imageNode.put("Width", image.getWidth());
if (colorSpace != null) { imageNode.put("Height", image.getHeight());
imageNode.put("ColorSpace", colorSpace.toString()); if(image.getMetadata() != null && image.getMetadata().getFile() != null && image.getMetadata().getFile().getFile() != null) {
} imageNode.put("Name", image.getMetadata().getFile().getFile());
imagesArray.add(imageNode);
} }
if (image.getColorSpace() != null) {
imageNode.put("ColorSpace", image.getColorSpace().getName());
}
imagesArray.add(imageNode);
} }
} }
pageInfo.set("Images", imagesArray); pageInfo.set("Images", imagesArray);
@@ -417,12 +473,13 @@ public class GetInfoOnPDF {
ArrayNode linksArray = objectMapper.createArrayNode(); ArrayNode linksArray = objectMapper.createArrayNode();
Set<String> uniqueURIs = new HashSet<>(); // To store unique URIs Set<String> uniqueURIs = new HashSet<>(); // To store unique URIs
for (PdfAnnotation annotation : annotations) { for (PDAnnotation annotation : annotations) {
if (annotation instanceof PdfLinkAnnotation) { if (annotation instanceof PDAnnotationLink) {
PdfLinkAnnotation linkAnnotation = (PdfLinkAnnotation) annotation; PDAnnotationLink linkAnnotation = (PDAnnotationLink) annotation;
if(linkAnnotation != null && linkAnnotation.getAction() != null) { if (linkAnnotation.getAction() instanceof PDActionURI) {
String uri = linkAnnotation.getAction().toString(); PDActionURI uriAction = (PDActionURI) linkAnnotation.getAction();
uniqueURIs.add(uri); // Add to set to ensure uniqueness String uri = uriAction.getURI();
uniqueURIs.add(uri); // Add to set to ensure uniqueness
} }
} }
} }
@@ -435,96 +492,52 @@ public class GetInfoOnPDF {
} }
pageInfo.set("Links", linksArray); pageInfo.set("Links", linksArray);
// Fonts
// Fonts
ArrayNode fontsArray = objectMapper.createArrayNode(); ArrayNode fontsArray = objectMapper.createArrayNode();
PdfDictionary fontDicts = resources.getResource(PdfName.Font);
Set<String> uniqueSubtypes = new HashSet<>(); // To store unique subtypes
// Map to store unique fonts and their counts
Map<String, ObjectNode> uniqueFontsMap = new HashMap<>(); Map<String, ObjectNode> uniqueFontsMap = new HashMap<>();
if (fontDicts != null) { for (COSName fontName : resources.getFontNames()) {
for (PdfName key : fontDicts.keySet()) { PDFont font = resources.getFont(fontName);
ObjectNode fontNode = objectMapper.createObjectNode(); // Create a new font node for each font ObjectNode fontNode = objectMapper.createObjectNode();
PdfDictionary font = fontDicts.getAsDictionary(key);
boolean isEmbedded = font.containsKey(PdfName.FontFile) || fontNode.put("IsEmbedded", font.isEmbedded());
font.containsKey(PdfName.FontFile2) ||
font.containsKey(PdfName.FontFile3);
fontNode.put("IsEmbedded", isEmbedded);
if (font.containsKey(PdfName.Encoding)) { // PDFBox provides Font's BaseFont (i.e., the font name) directly
String encoding = font.getAsName(PdfName.Encoding).toString(); fontNode.put("Name", font.getName());
fontNode.put("Encoding", encoding);
}
if (font.getAsString(PdfName.BaseFont) != null) { fontNode.put("Subtype", font.getType());
fontNode.put("Name", font.getAsString(PdfName.BaseFont).toString());
}
String subtype = null; PDFontDescriptor fontDescriptor = font.getFontDescriptor();
if (font.containsKey(PdfName.Subtype)) {
subtype = font.getAsName(PdfName.Subtype).toString();
uniqueSubtypes.add(subtype); // Add to set to ensure uniqueness
}
fontNode.put("Subtype", subtype);
PdfDictionary fontDescriptor = font.getAsDictionary(PdfName.FontDescriptor); if (fontDescriptor != null) {
if (fontDescriptor != null) { fontNode.put("ItalicAngle", fontDescriptor.getItalicAngle());
if (fontDescriptor.containsKey(PdfName.ItalicAngle)) { int flags = fontDescriptor.getFlags();
fontNode.put("ItalicAngle", fontDescriptor.getAsNumber(PdfName.ItalicAngle).floatValue()); 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);
if (fontDescriptor.containsKey(PdfName.Flags)) { fontNode.put("FontFamily", fontDescriptor.getFontFamily());
int flags = fontDescriptor.getAsNumber(PdfName.Flags).intValue(); // Font stretch and BBox are not directly available in PDFBox's API, so these are omitted for simplicity
fontNode.put("IsItalic", (flags & 64) != 0); fontNode.put("FontWeight", fontDescriptor.getFontWeight());
fontNode.put("IsBold", (flags & 1 << 16) != 0); }
fontNode.put("IsFixedPitch", (flags & 1) != 0);
fontNode.put("IsSerif", (flags & 2) != 0);
fontNode.put("IsSymbolic", (flags & 4) != 0);
fontNode.put("IsScript", (flags & 8) != 0);
fontNode.put("IsNonsymbolic", (flags & 16) != 0);
}
if (fontDescriptor.containsKey(PdfName.FontFamily)) {
String fontFamily = fontDescriptor.getAsString(PdfName.FontFamily).toString();
fontNode.put("FontFamily", fontFamily);
}
if (fontDescriptor.containsKey(PdfName.FontStretch)) { // Create a unique key for this font node based on its attributes
String fontStretch = fontDescriptor.getAsName(PdfName.FontStretch).toString(); String uniqueKey = fontNode.toString();
fontNode.put("FontStretch", fontStretch);
}
if (fontDescriptor.containsKey(PdfName.FontBBox)) { // Increment count if this font exists, or initialize it if new
PdfArray bbox = fontDescriptor.getAsArray(PdfName.FontBBox); if (uniqueFontsMap.containsKey(uniqueKey)) {
fontNode.put("FontBoundingBox", bbox.toString()); ObjectNode existingFontNode = uniqueFontsMap.get(uniqueKey);
} int count = existingFontNode.get("Count").asInt() + 1;
existingFontNode.put("Count", count);
if (fontDescriptor.containsKey(PdfName.FontWeight)) { } else {
float fontWeight = fontDescriptor.getAsNumber(PdfName.FontWeight).floatValue(); fontNode.put("Count", 1);
fontNode.put("FontWeight", fontWeight); uniqueFontsMap.put(uniqueKey, fontNode);
}
}
if (font.containsKey(PdfName.ToUnicode)) {
fontNode.put("HasToUnicodeMap", true);
}
if (fontNode.size() > 0) {
// 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);
}
}
} }
} }
@@ -538,41 +551,49 @@ public class GetInfoOnPDF {
// Access resources dictionary
PdfDictionary resourcesDict = itextDoc.getPage(pageNum).getResources().getPdfObject();
// Color Spaces & ICC Profiles
// Access resources dictionary
ArrayNode colorSpacesArray = objectMapper.createArrayNode(); ArrayNode colorSpacesArray = objectMapper.createArrayNode();
PdfDictionary colorSpaces = resourcesDict.getAsDictionary(PdfName.ColorSpace);
if (colorSpaces != null) { Iterable<COSName> colorSpaceNames = resources.getColorSpaceNames();
for (PdfName name : colorSpaces.keySet()) { for (COSName name : colorSpaceNames) {
PdfObject colorSpaceObject = colorSpaces.get(name); PDColorSpace colorSpace = resources.getColorSpace(name);
if (colorSpaceObject instanceof PdfArray) { if (colorSpace instanceof PDICCBased) {
PdfArray colorSpaceArray = (PdfArray) colorSpaceObject; PDICCBased iccBased = (PDICCBased) colorSpace;
if (colorSpaceArray.size() > 1 && colorSpaceArray.get(0) instanceof PdfName && PdfName.ICCBased.equals(colorSpaceArray.get(0))) { PDStream iccData = iccBased.getPDStream();
ObjectNode iccProfileNode = objectMapper.createObjectNode(); byte[] iccBytes = iccData.toByteArray();
PdfStream iccStream = (PdfStream) colorSpaceArray.get(1);
byte[] iccData = iccStream.getBytes(); // TODO: Further decode and analyze the ICC data if needed
// TODO: Further decode and analyze the ICC data if needed ObjectNode iccProfileNode = objectMapper.createObjectNode();
iccProfileNode.put("ICC Profile Length", iccData.length); iccProfileNode.put("ICC Profile Length", iccBytes.length);
colorSpacesArray.add(iccProfileNode); colorSpacesArray.add(iccProfileNode);
}
}
} }
} }
pageInfo.set("Color Spaces & ICC Profiles", colorSpacesArray); pageInfo.set("Color Spaces & ICC Profiles", colorSpacesArray);
// Other XObjects // Other XObjects
Map<String, Integer> xObjectCountMap = new HashMap<>(); // To store the count for each type Map<String, Integer> xObjectCountMap = new HashMap<>(); // To store the count for each type
PdfDictionary xObjects = resourcesDict.getAsDictionary(PdfName.XObject); for (COSName name : resources.getXObjectNames()) {
if (xObjects != null) { PDXObject xObject = resources.getXObject(name);
for (PdfName name : xObjects.keySet()) { String xObjectType;
PdfStream xObjectStream = xObjects.getAsStream(name);
String xObjectType = xObjectStream.getAsName(PdfName.Subtype).toString(); if (xObject instanceof PDImageXObject) {
xObjectType = "Image";
// Increment the count for this type in the map } else if (xObject instanceof PDFormXObject) {
xObjectCountMap.put(xObjectType, xObjectCountMap.getOrDefault(xObjectType, 0) + 1); 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) // Add the count map to pageInfo (or wherever you want to store it)
@@ -584,14 +605,17 @@ public class GetInfoOnPDF {
ArrayNode multimediaArray = objectMapper.createArrayNode(); ArrayNode multimediaArray = objectMapper.createArrayNode();
for (PdfAnnotation annotation : annotations) {
if (PdfName.RichMedia.equals(annotation.getSubtype())) { for (PDAnnotation annotation : annotations) {
if ("RichMedia".equals(annotation.getSubtype())) {
ObjectNode multimediaNode = objectMapper.createObjectNode(); ObjectNode multimediaNode = objectMapper.createObjectNode();
// Extract details from the dictionary as needed // Extract details from the annotation as needed
multimediaArray.add(multimediaNode); multimediaArray.add(multimediaNode);
} }
} }
pageInfo.set("Multimedia", multimediaArray); pageInfo.set("Multimedia", multimediaArray);
@@ -622,17 +646,21 @@ public class GetInfoOnPDF {
return null; return null;
} }
private static void addOutlinesToArray(PdfOutline outline, ArrayNode arrayNode) { private static void addOutlinesToArray(PDOutlineItem outline, ArrayNode arrayNode) {
if (outline == null) return; if (outline == null) return;
ObjectNode outlineNode = objectMapper.createObjectNode(); ObjectNode outlineNode = objectMapper.createObjectNode();
outlineNode.put("Title", outline.getTitle()); outlineNode.put("Title", outline.getTitle());
// You can add other properties if needed // You can add other properties if needed
arrayNode.add(outlineNode); arrayNode.add(outlineNode);
for (PdfOutline child : outline.getAllChildren()) { PDOutlineItem child = outline.getFirstChild();
while (child != null) {
addOutlinesToArray(child, arrayNode); addOutlinesToArray(child, arrayNode);
child = child.getNextSibling();
} }
} }
public String getPageOrientation(double width, double height) { public String getPageOrientation(double width, double height) {
if (width > height) { if (width > height) {
return "Landscape"; return "Landscape";
@@ -664,45 +692,33 @@ public class GetInfoOnPDF {
return Math.abs(pageAspectRatio - aspectRatio) <= 0.05; return Math.abs(pageAspectRatio - aspectRatio) <= 0.05;
} }
public boolean checkForStandard(PdfDocument document, String standardKeyword) {
// Check Output Intents
boolean foundInOutputIntents = checkOutputIntent(document, standardKeyword);
if (foundInOutputIntents) return true;
// Check XMP Metadata (rudimentary)
try {
byte[] metadataBytes = document.getXmpMetadata();
if (metadataBytes != null) {
XMPMeta xmpMeta = XMPMetaFactory.parseFromBuffer(metadataBytes);
String xmpString = xmpMeta.dumpObject();
if (xmpString.contains(standardKeyword)) {
return true;
}
}
} catch (XMPException e) {
e.printStackTrace();
}
return false;
}
public boolean checkOutputIntent(PdfDocument document, String standard) { public static boolean checkForStandard(PDDocument document, String standardKeyword) {
PdfArray outputIntents = document.getCatalog().getPdfObject().getAsArray(PdfName.OutputIntents); // Check XMP Metadata
if (outputIntents != null && !outputIntents.isEmpty()) { try {
for (int i = 0; i < outputIntents.size(); i++) { PDMetadata pdMetadata = document.getDocumentCatalog().getMetadata();
PdfDictionary outputIntentDict = outputIntents.getAsDictionary(i); if (pdMetadata != null) {
if (outputIntentDict != null) { COSInputStream metaStream = pdMetadata.createInputStream();
PdfString s = outputIntentDict.getAsString(PdfName.S); DomXmpParser domXmpParser = new DomXmpParser();
if (s != null && s.toString().contains(standard)) { XMPMetadata xmpMeta = domXmpParser.parse(metaStream);
return true;
} 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;
} }
} }
return false; } catch (Exception e) { // Catching general exception for brevity, ideally you'd catch specific exceptions.
e.printStackTrace();
} }
return false;
}
public ArrayNode exploreStructureTree(List<Object> nodes) { public ArrayNode exploreStructureTree(List<Object> nodes) {
ArrayNode elementsArray = objectMapper.createArrayNode(); ArrayNode elementsArray = objectMapper.createArrayNode();
if (nodes != null) { if (nodes != null) {
@@ -757,7 +773,7 @@ public class GetInfoOnPDF {
} }
} }
private String getPageModeDescription(PdfName pageMode) { private String getPageModeDescription(String pageMode) {
return pageMode != null ? pageMode.toString().replaceFirst("/", "") : "Unknown"; return pageMode != null ? pageMode.toString().replaceFirst("/", "") : "Unknown";
} }
} }

View File

@@ -8,18 +8,19 @@ import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag; 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; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@RequestMapping("/api/v1/security")
@Tag(name = "Security", description = "Security APIs") @Tag(name = "Security", description = "Security APIs")
public class PasswordController { public class PasswordController {
@@ -31,13 +32,12 @@ public class PasswordController {
summary = "Remove password from a PDF file", 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" 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<byte[]> removePassword( public ResponseEntity<byte[]> removePassword(@ModelAttribute PDFPasswordRequest request) throws IOException {
@RequestPart(required = true, value = "fileInput") MultipartFile fileInput = request.getFileInput();
@Parameter(description = "The input PDF file from which the password should be removed", required = true) String password = request.getPassword();
MultipartFile fileInput,
@RequestParam(name = "password")
@Parameter(description = "The password of the PDF file", required = true)
String password) throws IOException {
PDDocument document = PDDocument.load(fileInput.getBytes(), password); PDDocument document = PDDocument.load(fileInput.getBytes(), password);
document.setAllSecurityToBeRemoved(true); document.setAllSecurityToBeRemoved(true);
return WebResponseUtils.pdfDocToWebResponse(document, fileInput.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_password_removed.pdf"); return WebResponseUtils.pdfDocToWebResponse(document, fileInput.getOriginalFilename().replaceFirst("[.][^.]+$", "") + "_password_removed.pdf");
@@ -48,44 +48,19 @@ public class PasswordController {
summary = "Add password to a PDF file", 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" 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<byte[]> addPassword( public ResponseEntity<byte[]> addPassword(@ModelAttribute AddPasswordRequest request) throws IOException {
@RequestPart(required = true, value = "fileInput") MultipartFile fileInput = request.getFileInput();
@Parameter(description = "The input PDF file to which the password should be added", required = true) String ownerPassword = request.getOwnerPassword();
MultipartFile fileInput, String password = request.getPassword();
@RequestParam(value = "", name = "ownerPassword", required = false, defaultValue = "") int keyLength = request.getKeyLength();
@Parameter(description = "The owner password to be added to the PDF file (Restricts what can be done with the document once it is opened)") boolean canAssembleDocument = request.isCanAssembleDocument();
String ownerPassword, boolean canExtractContent = request.isCanExtractContent();
@RequestParam( name = "password", required = false, defaultValue = "") boolean canExtractForAccessibility = request.isCanExtractForAccessibility();
@Parameter(description = "The password to be added to the PDF file (Restricts the opening of the document itself.)") boolean canFillInForm = request.isCanFillInForm();
String password, boolean canModify = request.isCanModify();
@RequestParam( name = "keyLength", required = false, defaultValue = "256") boolean canModifyAnnotations = request.isCanModifyAnnotations();
@Parameter(description = "The length of the encryption key", schema = @Schema(allowableValues = {"40", "128", "256"})) boolean canPrint = request.isCanPrint();
int keyLength, boolean canPrintFaithful = request.isCanPrintFaithful();
@RequestParam( name = "canAssembleDocument", required = false)
@Parameter(description = "Whether the document assembly is allowed", example = "false")
boolean canAssembleDocument,
@RequestParam( name = "canExtractContent", required = false)
@Parameter(description = "Whether content extraction for accessibility is allowed", example = "false")
boolean canExtractContent,
@RequestParam( name = "canExtractForAccessibility", required = false)
@Parameter(description = "Whether content extraction for accessibility is allowed", example = "false")
boolean canExtractForAccessibility,
@RequestParam( name = "canFillInForm", required = false)
@Parameter(description = "Whether form filling is allowed", example = "false")
boolean canFillInForm,
@RequestParam( name = "canModify", required = false)
@Parameter(description = "Whether the document modification is allowed", example = "false")
boolean canModify,
@RequestParam( name = "canModifyAnnotations", required = false)
@Parameter(description = "Whether modification of annotations is allowed", example = "false")
boolean canModifyAnnotations,
@RequestParam(name = "canPrint", required = false)
@Parameter(description = "Whether printing of the document is allowed", example = "false")
boolean canPrint,
@RequestParam( name = "canPrintFaithful", required = false)
@Parameter(description = "Whether faithful printing is allowed", example = "false")
boolean canPrintFaithful
) throws IOException {
PDDocument document = PDDocument.load(fileInput.getBytes()); PDDocument document = PDDocument.load(fileInput.getBytes());
AccessPermission ap = new AccessPermission(); AccessPermission ap = new AccessPermission();

View File

@@ -18,19 +18,20 @@ import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import stirling.software.SPDF.model.PDFText; import stirling.software.SPDF.model.PDFText;
import stirling.software.SPDF.model.api.security.RedactPdfRequest;
import stirling.software.SPDF.pdf.TextFinder; import stirling.software.SPDF.pdf.TextFinder;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@RequestMapping("/api/v1/security")
@Tag(name = "Security", description = "Security APIs") @Tag(name = "Security", description = "Security APIs")
public class RedactController { public class RedactController {
@@ -40,24 +41,39 @@ public class RedactController {
@PostMapping(value = "/auto-redact", consumes = "multipart/form-data") @PostMapping(value = "/auto-redact", consumes = "multipart/form-data")
@Operation(summary = "Redacts listOfText in a PDF document", @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") description = "This operation takes an input PDF file and redacts the provided listOfText. Input:PDF, Output:PDF, Type:SISO")
public ResponseEntity<byte[]> redactPdf( public ResponseEntity<byte[]> redactPdf(@ModelAttribute RedactPdfRequest request) throws Exception {
@Parameter(description = "The input PDF file", required = true) @RequestParam("fileInput") MultipartFile file, MultipartFile file = request.getFileInput();
@Parameter(description = "List of listOfText to redact from the PDF", required = true, schema = @Schema(type = "string")) @RequestParam("listOfText") String listOfTextString, String listOfTextString = request.getListOfText();
@RequestParam(value = "useRegex", required = false) boolean useRegex, boolean useRegex = request.isUseRegex();
@RequestParam(value = "wholeWordSearch", required = false) boolean wholeWordSearchBool, boolean wholeWordSearchBool = request.isWholeWordSearch();
@RequestParam(value = "customPadding", required = false) float customPadding, String colorString = request.getRedactColor();
@RequestParam(value = "convertPDFToImage", required = false) boolean convertPDFToImage) throws Exception { float customPadding = request.getCustomPadding();
boolean convertPDFToImage = request.isConvertPDFToImage();
System.out.println(listOfTextString); System.out.println(listOfTextString);
String[] listOfText = listOfTextString.split("\n"); String[] listOfText = listOfTextString.split("\n");
byte[] bytes = file.getBytes(); byte[] bytes = file.getBytes();
PDDocument document = PDDocument.load(new ByteArrayInputStream(bytes)); 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) { for (String text : listOfText) {
text = text.trim(); text = text.trim();
System.out.println(text); System.out.println(text);
TextFinder textFinder = new TextFinder(text, useRegex, wholeWordSearchBool); TextFinder textFinder = new TextFinder(text, useRegex, wholeWordSearchBool);
List<PDFText> foundTexts = textFinder.getTextLocations(document); List<PDFText> foundTexts = textFinder.getTextLocations(document);
redactFoundText(document, foundTexts, customPadding); redactFoundText(document, foundTexts, customPadding,redactColor);
} }
@@ -88,13 +104,13 @@ public class RedactController {
} }
private void redactFoundText(PDDocument document, List<PDFText> blocks, float customPadding) throws IOException { private void redactFoundText(PDDocument document, List<PDFText> blocks, float customPadding, Color redactColor) throws IOException {
var allPages = document.getDocumentCatalog().getPages(); var allPages = document.getDocumentCatalog().getPages();
for (PDFText block : blocks) { for (PDFText block : blocks) {
var page = allPages.get(block.getPageIndex()); var page = allPages.get(block.getPageIndex());
PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true); PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true);
contentStream.setNonStrokingColor(Color.BLACK); contentStream.setNonStrokingColor(redactColor);
float padding = (block.getY2() - block.getY1()) * 0.3f + customPadding; float padding = (block.getY2() - block.getY1()) * 0.3f + customPadding;
PDRectangle pageBox = page.getBBox(); PDRectangle pageBox = page.getBBox();
contentStream.addRect(block.getX1(), pageBox.getHeight() - block.getY1() - padding, block.getX2() - block.getX1(), block.getY2() - block.getY1() + 2 * padding); contentStream.addRect(block.getX1(), pageBox.getHeight() - block.getY1() - padding, block.getX2() - block.getX1(), block.getY2() - block.getY1() + 2 * padding);
@@ -103,4 +119,5 @@ public class RedactController {
} }
} }
} }

View File

@@ -20,41 +20,32 @@ import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm; import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDField; import org.apache.pdfbox.pdmodel.interactive.form.PDField;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation; 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.api.security.SanitizePdfRequest;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@RequestMapping("/api/v1/security")
@Tag(name = "Security", description = "Security APIs")
public class SanitizeController { public class SanitizeController {
@PostMapping(consumes = "multipart/form-data", value = "/sanitize-pdf") @PostMapping(consumes = "multipart/form-data", value = "/sanitize-pdf")
@Operation(summary = "Sanitize a PDF file", @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") description = "This endpoint processes a PDF file and removes specific elements based on the provided options. Input:PDF Output:PDF Type:SISO")
public ResponseEntity<byte[]> sanitizePDF( public ResponseEntity<byte[]> sanitizePDF(@ModelAttribute SanitizePdfRequest request) throws IOException {
@RequestPart(required = true, value = "fileInput") MultipartFile inputFile = request.getFileInput();
@Parameter(description = "The input PDF file to be sanitized") boolean removeJavaScript = request.isRemoveJavaScript();
MultipartFile inputFile, boolean removeEmbeddedFiles = request.isRemoveEmbeddedFiles();
@RequestParam(name = "removeJavaScript", required = false, defaultValue = "false") boolean removeMetadata = request.isRemoveMetadata();
@Parameter(description = "Remove JavaScript actions from the PDF if set to true") boolean removeLinks = request.isRemoveLinks();
Boolean removeJavaScript, boolean removeFonts = request.isRemoveFonts();
@RequestParam(name = "removeEmbeddedFiles", required = false, defaultValue = "false")
@Parameter(description = "Remove embedded files from the PDF if set to true")
Boolean removeEmbeddedFiles,
@RequestParam(name = "removeMetadata", required = false, defaultValue = "false")
@Parameter(description = "Remove metadata from the PDF if set to true")
Boolean removeMetadata,
@RequestParam(name = "removeLinks", required = false, defaultValue = "false")
@Parameter(description = "Remove links from the PDF if set to true")
Boolean removeLinks,
@RequestParam(name = "removeFonts", required = false, defaultValue = "false")
@Parameter(description = "Remove fonts from the PDF if set to true")
Boolean removeFonts) throws IOException {
try (PDDocument document = PDDocument.load(inputFile.getInputStream())) { try (PDDocument document = PDDocument.load(inputFile.getInputStream())) {
if (removeJavaScript) { if (removeJavaScript) {

View File

@@ -22,40 +22,35 @@ import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState;
import org.apache.pdfbox.util.Matrix; import org.apache.pdfbox.util.Matrix;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import org.springframework.http.ResponseEntity; 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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import stirling.software.SPDF.model.api.security.AddWatermarkRequest;
import stirling.software.SPDF.utils.WebResponseUtils; import stirling.software.SPDF.utils.WebResponseUtils;
@RestController @RestController
@RequestMapping("/api/v1/security")
@Tag(name = "Security", description = "Security APIs") @Tag(name = "Security", description = "Security APIs")
public class WatermarkController { public class WatermarkController {
@PostMapping(consumes = "multipart/form-data", value = "/add-watermark") @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") @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<byte[]> addWatermark( public ResponseEntity<byte[]> addWatermark(@ModelAttribute AddWatermarkRequest request) throws IOException, Exception {
@RequestPart(required = true, value = "fileInput") @Parameter(description = "The input PDF file to add a watermark") MultipartFile pdfFile, MultipartFile pdfFile = request.getFileInput();
@RequestParam(required = true) @Parameter(description = "The watermark type (text or image)") String watermarkType, String watermarkType = request.getWatermarkType();
@RequestParam(required = false) @Parameter(description = "The watermark text") String watermarkText, String watermarkText = request.getWatermarkText();
@RequestPart(required = false) @Parameter(description = "The watermark image") MultipartFile watermarkImage, MultipartFile watermarkImage = request.getWatermarkImage();
String alphabet = request.getAlphabet();
@RequestParam(defaultValue = "roman", name = "alphabet") @Parameter(description = "The selected alphabet", float fontSize = request.getFontSize();
schema = @Schema(type = "string", float rotation = request.getRotation();
allowableValues = {"roman","arabic","japanese","korean","chinese"}, float opacity = request.getOpacity();
defaultValue = "roman")) String alphabet, int widthSpacer = request.getWidthSpacer();
@RequestParam(defaultValue = "30", name = "fontSize") @Parameter(description = "The font size of the watermark text", example = "30") float fontSize, int heightSpacer = request.getHeightSpacer();
@RequestParam(defaultValue = "0", name = "rotation") @Parameter(description = "The rotation of the watermark in degrees", example = "0") float rotation,
@RequestParam(defaultValue = "0.5", name = "opacity") @Parameter(description = "The opacity of the watermark (0.0 - 1.0)", example = "0.5") float opacity,
@RequestParam(defaultValue = "50", name = "widthSpacer") @Parameter(description = "The width spacer between watermark elements", example = "50") int widthSpacer,
@RequestParam(defaultValue = "50", name = "heightSpacer") @Parameter(description = "The height spacer between watermark elements", example = "50") int heightSpacer)
throws IOException, Exception {
// Load the input PDF // Load the input PDF
PDDocument document = PDDocument.load(pdfFile.getInputStream()); PDDocument document = PDDocument.load(pdfFile.getInputStream());

View File

@@ -1,22 +1,8 @@
package stirling.software.SPDF.controller.web; 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.List;
import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.springframework.beans.factory.annotation.Autowired; 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.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
@@ -27,10 +13,8 @@ import org.springframework.web.bind.annotation.GetMapping;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import stirling.software.SPDF.config.security.UserService;
import stirling.software.SPDF.model.User; import stirling.software.SPDF.model.User;
import stirling.software.SPDF.repository.UserRepository; import stirling.software.SPDF.repository.UserRepository;
@Controller @Controller
@@ -58,14 +42,13 @@ public class AccountWebController {
@Autowired @Autowired
private UserRepository userRepository; // Assuming you have a repository for user operations private UserRepository userRepository; // Assuming you have a repository for user operations
@Autowired
private UserService userService; // Assuming you have a repository for user operations
@PreAuthorize("hasRole('ROLE_ADMIN')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping("/addUsers") @GetMapping("/addUsers")
public String showAddUserForm(Model model) { public String showAddUserForm(Model model, Authentication authentication) {
List<User> allUsers = userRepository.findAll(); List<User> allUsers = userRepository.findAll();
model.addAttribute("users", allUsers); model.addAttribute("users", allUsers);
model.addAttribute("currentUsername", authentication.getName());
return "addUsers"; return "addUsers";
} }
@@ -108,6 +91,7 @@ public class AccountWebController {
model.addAttribute("username", username); model.addAttribute("username", username);
model.addAttribute("role", user.get().getRolesAsString()); model.addAttribute("role", user.get().getRolesAsString());
model.addAttribute("settings", settingsJson); model.addAttribute("settings", settingsJson);
model.addAttribute("changeCredsFlag", user.get().isFirstLogin());
} }
} else { } else {
return "redirect:/"; return "redirect:/";
@@ -117,5 +101,35 @@ public class AccountWebController {
@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> 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";
}
} }

View File

@@ -9,6 +9,7 @@ import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
@@ -20,6 +21,7 @@ import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Hidden; import io.swagger.v3.oas.annotations.Hidden;
@@ -50,7 +52,8 @@ public class GeneralWebController {
} }
List<Map<String, String>> pipelineConfigsWithNames = new ArrayList<>(); List<Map<String, String>> pipelineConfigsWithNames = new ArrayList<>();
for (String config : pipelineConfigs) { for (String config : pipelineConfigs) {
Map<String, Object> jsonContent = new ObjectMapper().readValue(config, Map.class); Map<String, Object> jsonContent = new ObjectMapper().readValue(config, new TypeReference<Map<String, Object>>(){});
String name = (String) jsonContent.get("name"); String name = (String) jsonContent.get("name");
Map<String, String> configWithName = new HashMap<>(); Map<String, String> configWithName = new HashMap<>();
configWithName.put("json", config); configWithName.put("json", config);
@@ -137,30 +140,116 @@ public class GeneralWebController {
return "sign"; 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 @Autowired
private ResourceLoader resourceLoader; private ResourceLoader resourceLoader;
private List<String> getFontNames() { private List<FontResource> getFontNames() {
List<FontResource> 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<FontResource> getFontNamesFromLocation(String locationPattern) {
try { try {
Resource[] resources = ResourcePatternUtils.getResourcePatternResolver(resourceLoader) Resource[] resources = ResourcePatternUtils.getResourcePatternResolver(resourceLoader)
.getResources("classpath:static/fonts/*.woff2"); .getResources(locationPattern);
return Arrays.stream(resources) return Arrays.stream(resources)
.map(resource -> { .map(resource -> {
try { try {
String filename = resource.getFilename(); String filename = resource.getFilename();
return filename.substring(0, filename.length() - 6); // Remove .woff2 extension 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) { } catch (Exception e) {
throw new RuntimeException("Error processing filename", e); throw new RuntimeException("Error processing filename", e);
} }
}) })
.filter(Objects::nonNull)
.collect(Collectors.toList()); .collect(Collectors.toList());
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException("Failed to read font directory", 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") @GetMapping("/crop")
@Hidden @Hidden

View File

@@ -15,19 +15,19 @@ import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
@Controller @Controller
@Tag(name = "Other", description = "Other APIs") @Tag(name = "Misc", description = "Miscellaneous APIs")
public class OtherWebController { public class OtherWebController {
@GetMapping("/compress-pdf") @GetMapping("/compress-pdf")
@Hidden @Hidden
public String compressPdfForm(Model model) { public String compressPdfForm(Model model) {
model.addAttribute("currentPage", "compress-pdf"); model.addAttribute("currentPage", "compress-pdf");
return "other/compress-pdf"; return "misc/compress-pdf";
} }
@GetMapping("/extract-image-scans") @GetMapping("/extract-image-scans")
@Hidden @Hidden
public ModelAndView extractImageScansForm() { public ModelAndView extractImageScansForm() {
ModelAndView modelAndView = new ModelAndView("other/extract-image-scans"); ModelAndView modelAndView = new ModelAndView("misc/extract-image-scans");
modelAndView.addObject("currentPage", "extract-image-scans"); modelAndView.addObject("currentPage", "extract-image-scans");
return modelAndView; return modelAndView;
} }
@@ -36,7 +36,7 @@ public class OtherWebController {
@Hidden @Hidden
public String extractJavascriptForm(Model model) { public String extractJavascriptForm(Model model) {
model.addAttribute("currentPage", "show-javascript"); model.addAttribute("currentPage", "show-javascript");
return "other/show-javascript"; return "misc/show-javascript";
} }
@@ -44,21 +44,21 @@ public class OtherWebController {
@Hidden @Hidden
public String addPageNumbersForm(Model model) { public String addPageNumbersForm(Model model) {
model.addAttribute("currentPage", "add-page-numbers"); model.addAttribute("currentPage", "add-page-numbers");
return "other/add-page-numbers"; return "misc/add-page-numbers";
} }
@GetMapping("/extract-images") @GetMapping("/extract-images")
@Hidden @Hidden
public String extractImagesForm(Model model) { public String extractImagesForm(Model model) {
model.addAttribute("currentPage", "extract-images"); model.addAttribute("currentPage", "extract-images");
return "other/extract-images"; return "misc/extract-images";
} }
@GetMapping("/flatten") @GetMapping("/flatten")
@Hidden @Hidden
public String flattenForm(Model model) { public String flattenForm(Model model) {
model.addAttribute("currentPage", "flatten"); model.addAttribute("currentPage", "flatten");
return "other/flatten"; return "misc/flatten";
} }
@@ -67,14 +67,14 @@ public class OtherWebController {
@Hidden @Hidden
public String addWatermarkForm(Model model) { public String addWatermarkForm(Model model) {
model.addAttribute("currentPage", "change-metadata"); model.addAttribute("currentPage", "change-metadata");
return "other/change-metadata"; return "misc/change-metadata";
} }
@GetMapping("/compare") @GetMapping("/compare")
@Hidden @Hidden
public String compareForm(Model model) { public String compareForm(Model model) {
model.addAttribute("currentPage", "compare"); model.addAttribute("currentPage", "compare");
return "other/compare"; return "misc/compare";
} }
public List<String> getAvailableTesseractLanguages() { public List<String> getAvailableTesseractLanguages() {
@@ -90,7 +90,7 @@ public class OtherWebController {
@GetMapping("/ocr-pdf") @GetMapping("/ocr-pdf")
@Hidden @Hidden
public ModelAndView ocrPdfPage() { public ModelAndView ocrPdfPage() {
ModelAndView modelAndView = new ModelAndView("other/ocr-pdf"); ModelAndView modelAndView = new ModelAndView("misc/ocr-pdf");
List<String> languages = getAvailableTesseractLanguages(); List<String> languages = getAvailableTesseractLanguages();
Collections.sort(languages); Collections.sort(languages);
modelAndView.addObject("languages", languages); modelAndView.addObject("languages", languages);
@@ -103,56 +103,43 @@ public class OtherWebController {
@Hidden @Hidden
public String overlayImage(Model model) { public String overlayImage(Model model) {
model.addAttribute("currentPage", "add-image"); model.addAttribute("currentPage", "add-image");
return "other/add-image"; return "misc/add-image";
} }
@GetMapping("/adjust-contrast") @GetMapping("/adjust-contrast")
@Hidden @Hidden
public String contrast(Model model) { public String contrast(Model model) {
model.addAttribute("currentPage", "adjust-contrast"); model.addAttribute("currentPage", "adjust-contrast");
return "other/adjust-contrast"; return "misc/adjust-contrast";
} }
@GetMapping("/repair") @GetMapping("/repair")
@Hidden @Hidden
public String repairForm(Model model) { public String repairForm(Model model) {
model.addAttribute("currentPage", "repair"); model.addAttribute("currentPage", "repair");
return "other/repair"; return "misc/repair";
} }
@GetMapping("/remove-blanks") @GetMapping("/remove-blanks")
@Hidden @Hidden
public String removeBlanksForm(Model model) { public String removeBlanksForm(Model model) {
model.addAttribute("currentPage", "remove-blanks"); model.addAttribute("currentPage", "remove-blanks");
return "other/remove-blanks"; return "misc/remove-blanks";
}
@GetMapping("/multi-page-layout")
@Hidden
public String multiPageLayoutForm(Model model) {
model.addAttribute("currentPage", "multi-page-layout");
return "other/multi-page-layout";
}
@GetMapping("/scale-pages")
@Hidden
public String scalePagesFrom(Model model) {
model.addAttribute("currentPage", "scale-pages");
return "other/scale-pages";
} }
@GetMapping("/auto-crop") @GetMapping("/auto-crop")
@Hidden @Hidden
public String autoCropForm(Model model) { public String autoCropForm(Model model) {
model.addAttribute("currentPage", "auto-crop"); model.addAttribute("currentPage", "auto-crop");
return "other/auto-crop"; return "misc/auto-crop";
} }
@GetMapping("/auto-rename") @GetMapping("/auto-rename")
@Hidden @Hidden
public String autoRenameForm(Model model) { public String autoRenameForm(Model model) {
model.addAttribute("currentPage", "auto-rename"); model.addAttribute("currentPage", "auto-rename");
return "other/auto-rename"; return "misc/auto-rename";
} }

View File

@@ -104,7 +104,6 @@ public class ApplicationProperties {
} }
public static class Security { public static class Security {
private Boolean enableLogin; private Boolean enableLogin;
private InitialLogin initialLogin;
private Boolean csrfDisabled; private Boolean csrfDisabled;
public Boolean getEnableLogin() { public Boolean getEnableLogin() {
@@ -115,14 +114,6 @@ public class ApplicationProperties {
this.enableLogin = enableLogin; this.enableLogin = enableLogin;
} }
public InitialLogin getInitialLogin() {
return initialLogin != null ? initialLogin : new InitialLogin();
}
public void setInitialLogin(InitialLogin initialLogin) {
this.initialLogin = initialLogin;
}
public Boolean getCsrfDisabled() { public Boolean getCsrfDisabled() {
return csrfDisabled; return csrfDisabled;
} }
@@ -134,40 +125,9 @@ public class ApplicationProperties {
@Override @Override
public String toString() { public String toString() {
return "Security [enableLogin=" + enableLogin + ", initialLogin=" + initialLogin + ", csrfDisabled=" return "Security [enableLogin=" + enableLogin + ", csrfDisabled="
+ 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 { public static class System {

View File

@@ -0,0 +1,4 @@
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,
}

View File

@@ -40,6 +40,9 @@ public class User {
@Column(name = "enabled") @Column(name = "enabled")
private boolean enabled; private boolean enabled;
@Column(name = "isFirstLogin")
private Boolean isFirstLogin = false;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "user") @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "user")
private Set<Authority> authorities = new HashSet<>(); private Set<Authority> authorities = new HashSet<>();
@@ -50,7 +53,14 @@ public class User {
private Map<String, String> settings = new HashMap<>(); // Key-value pairs of settings. private Map<String, String> 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() { public Long getId() {
return id; return id;
} }

View File

@@ -0,0 +1,17 @@
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;
}

View File

@@ -0,0 +1,20 @@
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;
}

View File

@@ -0,0 +1,16 @@
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;
}

View File

@@ -0,0 +1,15 @@
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;
}

View File

@@ -0,0 +1,16 @@
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;
}

View File

@@ -0,0 +1,15 @@
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;
}

View File

@@ -0,0 +1,13 @@
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;
}

View File

@@ -0,0 +1,14 @@
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;
}

View File

@@ -0,0 +1,39 @@
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<Integer> getPageNumbersList(){
int pageCount = 0;
try {
pageCount = PDDocument.load(getFileInput().getInputStream()).getNumberOfPages();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return GeneralUtils.parsePageString(pageNumbers, pageCount);
}
public List<Integer> getPageNumbersList(PDDocument doc){
int pageCount = 0;
pageCount = doc.getNumberOfPages();
return GeneralUtils.parsePageString(pageNumbers, pageCount);
}
}

View File

@@ -0,0 +1,16 @@
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 PDFWithPageSize extends PDFFile {
@Schema(description = "The scale of pages in the output PDF. Acceptable values are A0-A6, LETTER, LEGAL.",
allowableValues = {
"A0", "A1", "A2", "A3", "A4", "A5", "A6", "LETTER", "LEGAL"
})
private String pageSize;
}

View File

@@ -0,0 +1,23 @@
package stirling.software.SPDF.model.api.converters;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import stirling.software.SPDF.model.api.PDFFile;
@Data
@EqualsAndHashCode(callSuper=true)
public class ConvertToImageRequest extends PDFFile {
@Schema(description = "The output image format", allowableValues = {"png", "jpeg", "jpg", "gif"})
private String imageFormat;
@Schema(description = "Choose between a single image containing all pages or separate images for each page", allowableValues = {"single", "multiple"})
private String singleOrMultiple;
@Schema(description = "The color type of the output image(s)", allowableValues = {"color", "greyscale", "blackwhite"})
private String colorType;
@Schema(description = "The DPI (dots per inch) for the output image(s)")
private String dpi;
}

View File

@@ -0,0 +1,24 @@
package stirling.software.SPDF.model.api.converters;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode
public class ConvertToPdfRequest {
@Schema(description = "The input images to be converted to a PDF file")
private MultipartFile[] fileInput;
@Schema(description = "Whether to stretch the images to fit the PDF page or maintain the aspect ratio", example = "false")
private boolean stretchToFit;
@Schema(description = "The color type of the output image(s)", allowableValues = {"color", "greyscale", "blackwhite"})
private String colorType;
@Schema(description = "Whether to automatically rotate the images to better fit the PDF page", example = "true")
private boolean autoRotate;
}

View File

@@ -0,0 +1,14 @@
package stirling.software.SPDF.model.api.converters;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import stirling.software.SPDF.model.api.PDFFile;
@Data
@EqualsAndHashCode(callSuper=true)
public class PdfToPresentationRequest extends PDFFile {
@Schema(description = "The output Presentation format", allowableValues = {"ppt", "pptx", "odp"})
private String outputFormat;
}

View File

@@ -0,0 +1,14 @@
package stirling.software.SPDF.model.api.converters;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import stirling.software.SPDF.model.api.PDFFile;
@Data
@EqualsAndHashCode(callSuper=true)
public class PdfToTextOrRTFRequest extends PDFFile {
@Schema(description = "The output Text or RTF format", allowableValues = {"rtf", "txt:Text"})
private String outputFormat;
}

View File

@@ -0,0 +1,14 @@
package stirling.software.SPDF.model.api.converters;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import stirling.software.SPDF.model.api.PDFFile;
@Data
@EqualsAndHashCode(callSuper=true)
public class PdfToWordRequest extends PDFFile {
@Schema(description = "The output Word document format", allowableValues = {"doc", "docx", "odt"})
private String outputFormat;
}

View File

@@ -0,0 +1,13 @@
package stirling.software.SPDF.model.api.converters;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode
public class UrlToPdfRequest {
@Schema(description = "The input URL to be converted to a PDF file", required = true)
private String urlInput;
}

View File

@@ -0,0 +1,14 @@
package stirling.software.SPDF.model.api.filter;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import stirling.software.SPDF.model.api.PDFWithPageNums;
@Data
@EqualsAndHashCode(callSuper=true)
public class ContainsTextRequest extends PDFWithPageNums {
@Schema(description = "The text to check for", required = true)
private String text;
}

View File

@@ -0,0 +1,16 @@
package stirling.software.SPDF.model.api.filter;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import stirling.software.SPDF.model.api.PDFComparison;
@Data
@EqualsAndHashCode(callSuper=true)
public class FileSizeRequest extends PDFComparison {
@Schema(description = "File Size", required = true)
private String fileSize;
}

View File

@@ -0,0 +1,15 @@
package stirling.software.SPDF.model.api.filter;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import stirling.software.SPDF.model.api.PDFComparison;
@Data
@EqualsAndHashCode(callSuper=true)
public class PageRotationRequest extends PDFComparison {
@Schema(description = "Rotation in degrees", required = true)
private int rotation;
}

View File

@@ -0,0 +1,16 @@
package stirling.software.SPDF.model.api.filter;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import stirling.software.SPDF.model.api.PDFComparison;
@Data
@EqualsAndHashCode(callSuper=true)
public class PageSizeRequest extends PDFComparison {
@Schema(description = "Standard Page Size", required = true)
private String standardPageSize;
}

View File

@@ -0,0 +1,24 @@
package stirling.software.SPDF.model.api.general;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import stirling.software.SPDF.model.api.PDFFile;
@Data
@EqualsAndHashCode(callSuper=true)
public class CropPdfForm extends PDFFile {
@Schema(description = "The x-coordinate of the top-left corner of the crop area", type = "number")
private float x;
@Schema(description = "The y-coordinate of the top-left corner of the crop area", type = "number")
private float y;
@Schema(description = "The width of the crop area", type = "number")
private float width;
@Schema(description = "The height of the crop area", type = "number")
private float height;
}

View File

@@ -0,0 +1,15 @@
package stirling.software.SPDF.model.api.general;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import stirling.software.SPDF.model.api.PDFFile;
@Data
@EqualsAndHashCode(callSuper=true)
public class MergeMultiplePagesRequest extends PDFFile {
@Schema(description = "The number of pages to fit onto a single sheet in the output PDF.",
type = "integer", allowableValues = {"2", "3", "4", "9", "16"})
private int pagesPerSheet;
}

View File

@@ -0,0 +1,22 @@
package stirling.software.SPDF.model.api.general;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import stirling.software.SPDF.model.api.MultiplePDFFiles;
@Data
@EqualsAndHashCode(callSuper=true)
public class MergePdfsRequest extends MultiplePDFFiles {
@Schema(description = "The type of sorting to be applied on the input files before merging.",
allowableValues = {
"orderProvided",
"byFileName",
"byDateModified",
"byDateCreated",
"byPDFTitle"
},
defaultValue = "orderProvided")
private String sortType = "orderProvided";
}

View File

@@ -0,0 +1,23 @@
package stirling.software.SPDF.model.api.general;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import stirling.software.SPDF.model.SortTypes;
import stirling.software.SPDF.model.api.PDFWithPageNums;
@Data
@EqualsAndHashCode(callSuper=true)
public class RearrangePagesRequest extends PDFWithPageNums {
@Schema(implementation = SortTypes.class, description = "The custom mode for page rearrangement. Valid values are:\n"
+ "REVERSE_ORDER: Reverses the order of all pages.\n"
+ "DUPLEX_SORT: Sorts pages as if all fronts were scanned then all backs in reverse (1, n, 2, n-1, ...). "
+ "BOOKLET_SORT: Arranges pages for booklet printing (last, first, second, second last, ...).\n"
+ "ODD_EVEN_SPLIT: Splits and arranges pages into odd and even numbered pages.\n"
+ "REMOVE_FIRST: Removes the first page.\n" + "REMOVE_LAST: Removes the last page.\n"
+ "REMOVE_FIRST_AND_LAST: Removes both the first and the last pages.\n")
private String customMode;
}

View File

@@ -0,0 +1,14 @@
package stirling.software.SPDF.model.api.general;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import stirling.software.SPDF.model.api.PDFFile;
@Data
@EqualsAndHashCode(callSuper=true)
public class RotatePDFRequest extends PDFFile {
@Schema(description = "The angle by which to rotate the PDF file. This should be a multiple of 90.", example = "90")
private Integer angle;
}

View File

@@ -0,0 +1,15 @@
package stirling.software.SPDF.model.api.general;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import stirling.software.SPDF.model.api.PDFFile;
import stirling.software.SPDF.model.api.PDFWithPageSize;
@Data
@EqualsAndHashCode(callSuper=true)
public class ScalePagesRequest extends PDFWithPageSize {
@Schema(description = "The scale of the content on the pages of the output PDF. Acceptable values are floats.")
private float scaleFactor;
}

View File

@@ -0,0 +1,26 @@
package stirling.software.SPDF.model.api.misc;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import stirling.software.SPDF.model.api.PDFWithPageNums;
@Data
@EqualsAndHashCode(callSuper=true)
public class AddPageNumbersRequest extends PDFWithPageNums {
@Schema(description = "Custom margin: small/medium/large", allowableValues = {"small", "medium", "large"})
private String customMargin;
@Schema(description = "Position: 1 of 9 positions", minimum = "1", maximum = "9")
private int position;
@Schema(description = "Starting number", minimum = "1")
private int startingNumber;
@Schema(description = "Which pages to number, default all")
private String pagesToNumber;
@Schema(description = "Custom text: defaults to just number but can have things like \"Page {n} of {p}\"")
private String customText;
}

View File

@@ -0,0 +1,14 @@
package stirling.software.SPDF.model.api.misc;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import stirling.software.SPDF.model.api.PDFFile;
@Data
@EqualsAndHashCode(callSuper=true)
public class AutoSplitPdfRequest extends PDFFile {
@Schema(description = "Flag indicating if the duplex mode is active, where the page after the divider also gets removed.", required = false, defaultValue = "false")
private boolean duplexMode;
}

View File

@@ -0,0 +1,14 @@
package stirling.software.SPDF.model.api.misc;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import stirling.software.SPDF.model.api.PDFFile;
@Data
@EqualsAndHashCode(callSuper=true)
public class ExtractHeaderRequest extends PDFFile {
@Schema(description = "Flag indicating whether to use the first text as a fallback if no suitable title is found. Defaults to false.", required = false, defaultValue = "false")
private boolean useFirstTextAsFallback;
}

View File

@@ -0,0 +1,29 @@
package stirling.software.SPDF.model.api.misc;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode
public class ExtractImageScansRequest {
@Schema(description = "The input file containing image scans", required = true)
private MultipartFile fileInput;
@Schema(description = "The angle threshold for the image scan extraction", defaultValue = "5", example = "5")
private int angleThreshold = 5;
@Schema(description = "The tolerance for the image scan extraction", defaultValue = "20", example = "20")
private int tolerance = 20;
@Schema(description = "The minimum area for the image scan extraction", defaultValue = "8000", example = "8000")
private int minArea = 8000;
@Schema(description = "The minimum contour area for the image scan extraction", defaultValue = "500", example = "500")
private int minContourArea = 500;
@Schema(description = "The border size for the image scan extraction", defaultValue = "1", example = "1")
private int borderSize =1;
}

View File

@@ -0,0 +1,46 @@
package stirling.software.SPDF.model.api.misc;
import java.util.Map;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import stirling.software.SPDF.model.api.PDFFile;
@Data
@EqualsAndHashCode(callSuper=true)
public class MetadataRequest extends PDFFile {
@Schema(description = "Delete all metadata if set to true")
private boolean deleteAll;
@Schema(description = "The author of the document")
private String author;
@Schema(description = "The creation date of the document (format: yyyy/MM/dd HH:mm:ss)")
private String creationDate;
@Schema(description = "The creator of the document")
private String creator;
@Schema(description = "The keywords for the document")
private String keywords;
@Schema(description = "The modification date of the document (format: yyyy/MM/dd HH:mm:ss)")
private String modificationDate;
@Schema(description = "The producer of the document")
private String producer;
@Schema(description = "The subject of the document")
private String subject;
@Schema(description = "The title of the document")
private String title;
@Schema(description = "The trapped status of the document")
private String trapped;
@Schema(description = "Map list of key and value of custom parameters. Note these must start with customKey and customValue if they are non-standard")
private Map<String, String> allRequestParams;
}

View File

@@ -0,0 +1,18 @@
package stirling.software.SPDF.model.api.misc;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import stirling.software.SPDF.model.api.PDFFile;
@Data
@EqualsAndHashCode(callSuper=true)
public class OptimizePdfRequest extends PDFFile {
@Schema(description = "The level of optimization to apply to the PDF file. Higher values indicate greater compression but may reduce quality.",
allowableValues = { "1", "2", "3", "4", "5" })
private Integer optimizeLevel;
@Schema(description = "The expected output size, e.g. '100MB', '25KB', etc.")
private String expectedOutputSize;
}

View File

@@ -0,0 +1,25 @@
package stirling.software.SPDF.model.api.misc;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import stirling.software.SPDF.model.api.PDFFile;
@Data
@EqualsAndHashCode(callSuper=true)
public class OverlayImageRequest extends PDFFile {
@Schema(description = "The image file to be overlaid onto the PDF.")
private MultipartFile imageFile;
@Schema(description = "The x-coordinate at which to place the top-left corner of the image.", example = "0")
private float x;
@Schema(description = "The y-coordinate at which to place the top-left corner of the image.", example = "0")
private float y;
@Schema(description = "Whether to overlay the image onto every page of the PDF.", example = "false")
private boolean everyPage;
}

View File

@@ -0,0 +1,37 @@
package stirling.software.SPDF.model.api.misc;
import java.util.List;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import stirling.software.SPDF.model.api.PDFFile;
@Data
@EqualsAndHashCode(callSuper=true)
public class ProcessPdfWithOcrRequest extends PDFFile {
@Schema(description = "List of languages to use in OCR processing")
private List<String> languages;
@Schema(description = "Include OCR text in a sidecar text file if set to true")
private boolean sidecar;
@Schema(description = "Deskew the input file if set to true")
private boolean deskew;
@Schema(description = "Clean the input file if set to true")
private boolean clean;
@Schema(description = "Clean the final output if set to true")
private boolean cleanFinal;
@Schema(description = "Specify the OCR type, e.g., 'skip-text', 'force-ocr', or 'Normal'", allowableValues = {"skip-text", "force-ocr", "Normal"})
private String ocrType;
@Schema(description = "Specify the OCR render type, either 'hocr' or 'sandwich'", allowableValues = {"hocr", "sandwich"}, defaultValue = "hocr")
private String ocrRenderType = "hocr";
@Schema(description = "Remove images from the output PDF if set to true")
private boolean removeImagesAfter;
}

Some files were not shown because too many files have changed in this diff Show More