Compare commits

...
Author SHA1 Message Date
bd75ad042a [V2] fix(automation): enhance parameter handling and default values across operations, fix error in ManyToOne tools (#5123)
# Description of Changes
This pull request focuses on improving the handling of tool parameters
in the frontend automation and tool operation system. The main changes
ensure that default parameter values are consistently applied, missing
or undefined values are handled gracefully, and custom tools like
Automate and Merge correctly track input file consumption. These updates
enhance reliability and reduce errors due to missing or improperly
formatted parameters.

**Parameter Handling and Defaults:**

* Tool configuration and automation forms now merge user-provided
parameters with tool-specific default parameters, guaranteeing all
required fields are present during initialization and execution
(`ToolConfigurationModal.tsx`, `useAutomationForm.ts`,
`automationExecutor.ts`).
* All tool operation hooks (e.g., Add Watermark, Merge, Sanitize, Split,
Compress, Change Permissions, OCR) have been updated to safely handle
missing or undefined parameter values by providing sensible defaults,
preventing runtime errors and backend issues
(`useAddWatermarkOperation.ts`, `useMergeOperation.ts`,
`useSanitizeOperation.ts`, `useSplitOperation.ts`,
`useCompressOperation.ts`, `useChangePermissionsOperation.ts`,
`useOCROperation.ts`).

**Tool Operation Configuration Enhancements:**

* The `BaseToolOperationConfig` interface now supports a
`consumesAllInputs` flag, allowing tools with complex input-output
relationships (like Automate and Merge) to mark all input files as
successfully processed when appropriate (`useToolOperation.ts`).
* The Automate tool operation is configured to use this new flag, and
the core hook logic is updated to respect it when determining success
(`useAutomateOperation.ts`, `useToolOperation.ts`).

**Registry and Configuration Consistency:**

* Default parameters are now explicitly included in tool operation
configs (e.g., Merge), ensuring consistency between registry definitions
and runtime behavior (`useMergeOperation.ts`).

**Dependency Updates:**

* React hooks and callbacks now correctly include dependencies related
to parameter defaults to avoid stale values in forms and modals
(`useAutomationForm.ts`).

These changes collectively improve the robustness and maintainability of
the automation and tool configuration system.


<!--
Please provide a summary of the changes, including:

- What was changed
- Why the change was made
- Any challenges encountered

Closes #(issue_number)
-->

---

## Checklist

### General

- [X] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md)
(if applicable)
- [X] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [X] I have performed a self-review of my own code
- [X] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [X] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md#6-testing)
for more details.

---------

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
Co-authored-by: Reece Browne <74901996+reecebrowne@users.noreply.github.com>
2026-01-20 14:57:44 +00:00
LudyandGitHub 8bb807471f chore(ci): enable Gradle dependency caching across GitHub workflows (#5400)
# Description of Changes

This pull request updates the CI/CD workflows and Gradle configuration
to improve build reproducibility, security, and external dependency
management. The main changes include standardizing Gradle setup across
workflows, securely injecting Maven credentials, and enabling Gradle
build caching. There are also minor improvements to dependency version
management and plugin repository configuration.

**CI/CD Workflow Improvements:**

- Standardized Gradle setup across all GitHub Actions workflows by
explicitly adding a `Setup Gradle` step using
`gradle/actions/setup-gradle@v5.0.0` and specifying Gradle version 8.14.
This replaces previous usages and ensures consistency.
[[1]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R71-R81)
[[2]](diffhunk://#diff-8d23782ae5caff72d55828bb25814854f5f2523f299d7dbcda4a3537dd84c5c3L157-R176)
[[3]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R134-R144)
[[4]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R206-R216)
[[5]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R260-R264)
[[6]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R331-R341)
[[7]](diffhunk://#diff-3c0f521958c53ad27c967692b4d5480ead136acb33622ee97d39df814b1b202eR339-R351)
[[8]](diffhunk://#diff-895b214ee023c8c26048a2a3b946cfb1ebc4f26fbc8a9c2fa54b77c12e763b6bL53-R54)
[[9]](diffhunk://#diff-895b214ee023c8c26048a2a3b946cfb1ebc4f26fbc8a9c2fa54b77c12e763b6bL121-R127)
[[10]](diffhunk://#diff-895b214ee023c8c26048a2a3b946cfb1ebc4f26fbc8a9c2fa54b77c12e763b6bR206-R217)
[[11]](diffhunk://#diff-6a2e9fb077e57351f4a7e10d03b114e256298babdf06e7e7ae666781a5cf36a1R60-R70)
[[12]](diffhunk://#diff-62dcbe64a950b4efb54d691e1e87451a8cd535400aa9ea1e40893de5b57cd73bL45-R46)
[[13]](diffhunk://#diff-76056236de05155107f6a660f1e3956059e37338011b8f0e72188afcb9b17b6fL46-R56)
[[14]](diffhunk://#diff-fd60dc2adec58c1005c4e4164e9c24362fd6082fd3ab0403e54d276d9835fa6eL42-R65)
[[15]](diffhunk://#diff-b34ab107dd4bc92075b2e89b6f16e4a2813e267ca7c2afebdb1931a0a3900d5aR102-R114)
[[16]](diffhunk://#diff-98b618771a57e1758961359ecacbac2cff7cfef29aa021c3bc294ae926c4ce5bL47-R51)

- Enabled Gradle build cache (`--build-cache`) for all build-related
commands in workflows, improving build performance and consistency. Also
removed unnecessary `clean` commands before builds to further optimize
workflow times.
[[1]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R71-R81)
[[2]](diffhunk://#diff-8d23782ae5caff72d55828bb25814854f5f2523f299d7dbcda4a3537dd84c5c3L157-R176)
[[3]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R134-R144)
[[4]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R206-R216)
[[5]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R331-R341)
[[6]](diffhunk://#diff-3c0f521958c53ad27c967692b4d5480ead136acb33622ee97d39df814b1b202eR339-R351)
[[7]](diffhunk://#diff-895b214ee023c8c26048a2a3b946cfb1ebc4f26fbc8a9c2fa54b77c12e763b6bL134-R144)
[[8]](diffhunk://#diff-895b214ee023c8c26048a2a3b946cfb1ebc4f26fbc8a9c2fa54b77c12e763b6bR206-R217)
[[9]](diffhunk://#diff-6a2e9fb077e57351f4a7e10d03b114e256298babdf06e7e7ae666781a5cf36a1R60-R70)
[[10]](diffhunk://#diff-76056236de05155107f6a660f1e3956059e37338011b8f0e72188afcb9b17b6fL46-R56)
[[11]](diffhunk://#diff-fd60dc2adec58c1005c4e4164e9c24362fd6082fd3ab0403e54d276d9835fa6eL42-R65)
[[12]](diffhunk://#diff-b34ab107dd4bc92075b2e89b6f16e4a2813e267ca7c2afebdb1931a0a3900d5aR102-R114)
[[13]](diffhunk://#diff-98b618771a57e1758961359ecacbac2cff7cfef29aa021c3bc294ae926c4ce5bL47-R51)

**Security and Dependency Management:**

- Injected Maven credentials (`MAVEN_USER`, `MAVEN_PASSWORD`,
`MAVEN_PUBLIC_URL`) as environment variables in all relevant workflow
steps, supporting secure access to private or custom Maven repositories.
[[1]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R71-R81)
[[2]](diffhunk://#diff-8d23782ae5caff72d55828bb25814854f5f2523f299d7dbcda4a3537dd84c5c3L157-R176)
[[3]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R134-R144)
[[4]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R206-R216)
[[5]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R290-R293)
[[6]](diffhunk://#diff-5c3fa597431eda03ac3339ae6bf7f05e1a50d6fc7333679ec38e21b337cb6721R331-R341)
[[7]](diffhunk://#diff-3c0f521958c53ad27c967692b4d5480ead136acb33622ee97d39df814b1b202eR339-R351)
[[8]](diffhunk://#diff-895b214ee023c8c26048a2a3b946cfb1ebc4f26fbc8a9c2fa54b77c12e763b6bR66-R69)
[[9]](diffhunk://#diff-895b214ee023c8c26048a2a3b946cfb1ebc4f26fbc8a9c2fa54b77c12e763b6bL134-R144)
[[10]](diffhunk://#diff-895b214ee023c8c26048a2a3b946cfb1ebc4f26fbc8a9c2fa54b77c12e763b6bR281-R283)
[[11]](diffhunk://#diff-62dcbe64a950b4efb54d691e1e87451a8cd535400aa9ea1e40893de5b57cd73bR57-R60)
[[12]](diffhunk://#diff-76056236de05155107f6a660f1e3956059e37338011b8f0e72188afcb9b17b6fR73-R76)
[[13]](diffhunk://#diff-fd60dc2adec58c1005c4e4164e9c24362fd6082fd3ab0403e54d276d9835fa6eL42-R65)
[[14]](diffhunk://#diff-b34ab107dd4bc92075b2e89b6f16e4a2813e267ca7c2afebdb1931a0a3900d5aR178-R180)
[[15]](diffhunk://#diff-98b618771a57e1758961359ecacbac2cff7cfef29aa021c3bc294ae926c4ce5bL47-R51)

- Added a `pluginManagement` block in `settings.gradle` to allow Gradle
plugins to be resolved from a custom Maven repository if specified by
environment variables, increasing flexibility for plugin sourcing.

**Build and Dependency Versioning:**

- Updated `app/proprietary/build.gradle` to use the
`bouncycastleVersion` variable for the Bouncy Castle dependency version,
improving maintainability and consistency of dependency versioning.

**Workflow Trigger Improvements:**

- Expanded the file path triggers in
`.github/workflows/sync_files_v2.yml` to include additional Gradle build
files, ensuring the workflow runs when any core build files are changed.

---

## Checklist

### General

- [ ] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [ ] I have performed a self-review of my own code
- [ ] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [ ] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md#6-testing)
for more details.
2026-01-19 19:03:50 +00:00
Balázs SzücsandGitHub 59d816bfa7 feat(pipeline): improve file processing with resource management and temp file handling (#5488)
# Description of Changes

<!--
Please provide a summary of the changes, including:

- What was changed
- Why the change was made
- Any challenges encountered

Closes #(issue_number)
-->

---

## Checklist

### General

- [ ] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [ ] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md)
(if applicable)
- [ ] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [ ] I have performed a self-review of my own code
- [ ] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [ ] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md#6-testing)
for more details.

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
2026-01-17 19:44:02 +00:00
stirlingbot[bot]GitHubstirlingbot[bot] <195170888+stirlingbot[bot]@users.noreply.github.com>
473021a13c 🤖 format everything with pre-commit by stirlingbot (#5484)
Auto-generated by [create-pull-request][1] with **stirlingbot**

[1]: https://github.com/peter-evans/create-pull-request

Signed-off-by: stirlingbot[bot] <stirlingbot[bot]@users.noreply.github.com>
Co-authored-by: stirlingbot[bot] <195170888+stirlingbot[bot]@users.noreply.github.com>
2026-01-17 00:12:06 +00:00
stirlingbot[bot]GitHubstirlingbot[bot] <195170888+stirlingbot[bot]@users.noreply.github.com>
f616486bee 🌐 Sync Translations + Update README Progress Table (#5489)
### Description of Changes

This Pull Request was automatically generated to synchronize updates to
translation files and documentation. Below are the details of the
changes made:

#### **1. Synchronization of Translation Files**
- Updated translation files
(`frontend/public/locales/*/translation.toml`) to reflect changes in the
reference file `en-GB/translation.toml`.
- Ensured consistency and synchronization across all supported language
files.
- Highlighted any missing or incomplete translations.
- **Format**: TOML

#### **2. Update README.md**
- Generated the translation progress table in `README.md` using
`counter_translation_v3.py`.
- Added a summary of the current translation status for all supported
languages.
- Included up-to-date statistics on translation coverage.

#### **Why these changes are necessary**
- Keeps translation files aligned with the latest reference updates.
- Ensures the documentation reflects the current translation progress.

---

Auto-generated by [create-pull-request][1].

[1]: https://github.com/peter-evans/create-pull-request

Co-authored-by: stirlingbot[bot] <195170888+stirlingbot[bot]@users.noreply.github.com>
2026-01-16 21:01:11 +00:00
Balázs SzücsandGitHub cb5c2a5803 feat(conversion): add SVG to PDF conversion functionality (#5431)
# Description of Changes


This pull request introduces a new SVG to PDF conversion feature,
including both backend and frontend changes. The backend adds a secure,
vector-preserving SVG-to-PDF conversion endpoint with comprehensive SVG
sanitization to prevent XSS and SSRF attacks. The frontend is updated to
route SVG-to-PDF conversions through this new endpoint and to
distinguish SVG from other image formats. Additionally, a new dependency
is added for PDF rendering.

**Backend: SVG to PDF Conversion and Security**

* Adds a new API endpoint and controller (`ConvertSvgToPDF`) for
converting SVG files to PDF, using Batik and PDFBox with vector graphics
preservation and robust error handling.
* Implements SVG sanitization (`SvgSanitizer`) to remove scripts, event
handlers, and dangerous URLs, protecting against XSS and SSRF attacks.
* Introduces a utility (`SvgToPdf`) for rendering SVG to PDF with
timeout protection against resource exhaustion attacks.
* Defines a new request model (`SvgToPdfRequest`) for SVG to PDF
conversion requests.
* Adds the `pdfbox-graphics2d` dependency for vector graphics PDF
rendering.

**Frontend: Routing and Format Handling**

* Updates conversion endpoint constants to add `svg-pdf` and maps SVG
files to use the new `svg-to-pdf` route instead of the generic
image-to-PDF route.
* Removes SVG from the generic image format list and introduces a
dedicated check for SVG format (`isSvgFormat`).
<img width="1133" height="995" alt="image"
src="https://github.com/user-attachments/assets/dec8cf27-ccb9-490d-af76-bff69feb0423"
/>

<!--
Please provide a summary of the changes, including:

- What was changed
- Why the change was made
- Any challenges encountered

Closes #(issue_number)
-->

---

## Checklist

### General

- [X] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [X] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md)
(if applicable)
- [X] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [X] I have performed a self-review of my own code
- [X] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [X] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md#6-testing)
for more details.

---------

Signed-off-by: Balázs Szücs <bszucs1209@gmail.com>
2026-01-16 18:45:50 +00:00
89 changed files with 1785 additions and 151 deletions
@@ -153,9 +153,14 @@ jobs:
- name: Set up JDK 21
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
with:
java-version: "17"
java-version: "21"
distribution: "temurin"
- name: Setup Gradle
uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
with:
gradle-version: 8.14
- name: Run Gradle Command
run: |
if [ "${{ needs.check-comment.outputs.disable_security }}" == "true" ]; then
@@ -163,8 +168,11 @@ jobs:
else
export DISABLE_ADDITIONAL_FEATURES=false
fi
./gradlew clean build
./gradlew build
env:
MAVEN_USER: ${{ secrets.MAVEN_USER }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
MAVEN_PUBLIC_URL: ${{ secrets.MAVEN_PUBLIC_URL }}
STIRLING_PDF_DESKTOP_UI: false
- name: Set up Docker Buildx
+45 -3
View File
@@ -68,9 +68,17 @@ jobs:
java-version: ${{ matrix.jdk-version }}
distribution: "temurin"
- name: Setup Gradle
uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
with:
gradle-version: 8.14
- name: Build with Gradle and spring security ${{ matrix.spring-security }}
run: ./gradlew clean build -PnoSpotless
run: ./gradlew build -PnoSpotless
env:
MAVEN_USER: ${{ secrets.MAVEN_USER }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
MAVEN_PUBLIC_URL: ${{ secrets.MAVEN_PUBLIC_URL }}
DISABLE_ADDITIONAL_FEATURES: ${{ matrix.spring-security }}
- name: Check Test Reports Exist
@@ -135,9 +143,17 @@ jobs:
java-version: "21"
distribution: "temurin"
- name: Setup Gradle
uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
with:
gradle-version: 8.14
- name: Generate OpenAPI documentation
run: ./gradlew :stirling-pdf:generateOpenApiDocs
env:
MAVEN_USER: ${{ secrets.MAVEN_USER }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
MAVEN_PUBLIC_URL: ${{ secrets.MAVEN_PUBLIC_URL }}
DISABLE_ADDITIONAL_FEATURES: true
- name: Upload OpenAPI Documentation
@@ -199,8 +215,17 @@ jobs:
java-version: "21"
distribution: "temurin"
- name: Setup Gradle
uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
with:
gradle-version: 8.14
- name: check the licenses for compatibility
run: ./gradlew clean checkLicense
run: ./gradlew checkLicense
env:
MAVEN_USER: ${{ secrets.MAVEN_USER }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
MAVEN_PUBLIC_URL: ${{ secrets.MAVEN_PUBLIC_URL }}
- name: FAILED - check the licenses for compatibility
if: failure()
@@ -244,6 +269,11 @@ jobs:
java-version: "21"
distribution: "temurin"
- name: Setup Gradle
uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
with:
gradle-version: 8.14
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0
@@ -269,6 +299,10 @@ jobs:
chmod +x ./testing/test.sh
chmod +x ./testing/test_disabledEndpoints.sh
./testing/test.sh
env:
MAVEN_USER: ${{ secrets.MAVEN_USER }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
MAVEN_PUBLIC_URL: ${{ secrets.MAVEN_PUBLIC_URL }}
test-build-docker-images:
if: github.event_name == 'pull_request' && needs.files-changed.outputs.project == 'true'
@@ -306,9 +340,17 @@ jobs:
java-version: "21"
distribution: "temurin"
- name: Setup Gradle
uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
with:
gradle-version: 8.14
- name: Build application
run: ./gradlew clean build
run: ./gradlew build
env:
MAVEN_USER: ${{ secrets.MAVEN_USER }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
MAVEN_PUBLIC_URL: ${{ secrets.MAVEN_PUBLIC_URL }}
DISABLE_ADDITIONAL_FEATURES: true
STIRLING_PDF_DESKTOP_UI: false
@@ -336,11 +336,19 @@ jobs:
java-version: "21"
distribution: "temurin"
- name: Setup Gradle
uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
with:
gradle-version: 8.14
- name: Check licenses and generate report
id: license-check
run: |
./gradlew clean checkLicense generateLicenseReport || echo "LICENSE_CHECK_FAILED=true" >> $GITHUB_ENV
./gradlew checkLicense generateLicenseReport || echo "LICENSE_CHECK_FAILED=true" >> $GITHUB_ENV
env:
MAVEN_USER: ${{ secrets.MAVEN_USER }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
MAVEN_PUBLIC_URL: ${{ secrets.MAVEN_PUBLIC_URL }}
DISABLE_ADDITIONAL_FEATURES: false
STIRLING_PDF_DESKTOP_UI: true
+21 -4
View File
@@ -50,7 +50,8 @@ jobs:
java-version: "21"
distribution: "temurin"
- uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
- name: Setup Gradle
uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
with:
gradle-version: 8.14
@@ -62,6 +63,10 @@ jobs:
VERSION=$(./gradlew printVersion --quiet | tail -1)
echo "Extracted version: $VERSION"
echo "versionNumber=$VERSION" >> $GITHUB_OUTPUT
env:
MAVEN_USER: ${{ secrets.MAVEN_USER }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
MAVEN_PUBLIC_URL: ${{ secrets.MAVEN_PUBLIC_URL }}
- name: Determine build matrix
id: set-matrix
@@ -118,7 +123,8 @@ jobs:
java-version: "21"
distribution: "temurin"
- uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
- name: Setup Gradle
uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
with:
gradle-version: 8.14
@@ -131,8 +137,11 @@ jobs:
cache-dependency-path: frontend/package-lock.json
- name: Build JAR
run: ./gradlew clean build ${{ matrix.variant.build_frontend && '-PbuildWithFrontend=true' || '' }} -x spotlessApply -x spotlessCheck -x test -x sonarqube
run: ./gradlew build ${{ matrix.variant.build_frontend && '-PbuildWithFrontend=true' || '' }} -x spotlessApply -x spotlessCheck -x test -x sonarqube
env:
MAVEN_USER: ${{ secrets.MAVEN_USER }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
MAVEN_PUBLIC_URL: ${{ secrets.MAVEN_PUBLIC_URL }}
DISABLE_ADDITIONAL_FEATURES: ${{ matrix.variant.disable_security }}
STIRLING_PDF_DESKTOP_UI: false
@@ -194,13 +203,18 @@ jobs:
java-version: "21"
distribution: "temurin"
- name: Setup Gradle
uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
with:
gradle-version: 8.14
- name: Build Java backend with JLink
working-directory: ./
shell: bash
run: |
chmod +x ./gradlew
echo "🔧 Building Stirling-PDF JAR..."
./gradlew clean build -x spotlessApply -x spotlessCheck -x test -x sonarqube
./gradlew build -x spotlessApply -x spotlessCheck -x test -x sonarqube
# Find the built JAR
STIRLING_JAR=$(ls app/core/build/libs/stirling-pdf-*.jar | head -n 1)
@@ -264,6 +278,9 @@ jobs:
RUNTIME_SIZE=$(du -sh ./frontend/src-tauri/runtime/jre | cut -f1)
echo "📊 Custom JRE size: $RUNTIME_SIZE"
env:
MAVEN_USER: ${{ secrets.MAVEN_USER }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
MAVEN_PUBLIC_URL: ${{ secrets.MAVEN_PUBLIC_URL }}
DISABLE_ADDITIONAL_FEATURES: true
- name: Install frontend dependencies
+10 -1
View File
@@ -57,8 +57,17 @@ jobs:
java-version: 21
distribution: "temurin"
- name: Setup Gradle
uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
with:
gradle-version: 8.14
- name: Build with Gradle
run: ./gradlew clean build
run: ./gradlew build
env:
MAVEN_USER: ${{ secrets.MAVEN_USER }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
MAVEN_PUBLIC_URL: ${{ secrets.MAVEN_PUBLIC_URL }}
- name: git add
run: |
+12 -1
View File
@@ -45,7 +45,8 @@ jobs:
java-version: "21"
distribution: "temurin"
- uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
- name: Setup Gradle
uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
with:
gradle-version: 8.14
@@ -56,6 +57,16 @@ jobs:
- name: Get version number
id: versionNumber
run: echo "versionNumber=$(./gradlew printVersion --quiet | tail -1)" >> $GITHUB_OUTPUT
env:
MAVEN_USER: ${{ secrets.MAVEN_USER }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
MAVEN_PUBLIC_URL: ${{ secrets.MAVEN_PUBLIC_URL }}
- name: Install cosign
if: github.ref == 'refs/heads/master' || github.ref == 'refs/heads/V2-master'
uses: sigstore/cosign-installer@faadad0cce49287aee09b3a48701e75088a2c6ad # v4.0.0
with:
cosign-release: "v2.4.1"
- name: Install cosign
if: github.ref == 'refs/heads/master' || github.ref == 'refs/heads/V2-master'
+11 -1
View File
@@ -39,7 +39,10 @@ jobs:
java-version: "21"
distribution: "temurin"
- uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
- name: Setup Gradle
uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
with:
gradle-version: 8.14
- name: Generate Swagger documentation
run: ./gradlew :stirling-pdf:generateOpenApiDocs
@@ -47,12 +50,19 @@ jobs:
- name: Upload Swagger Documentation to SwaggerHub
run: ./gradlew swaggerhubUpload
env:
MAVEN_USER: ${{ secrets.MAVEN_USER }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
MAVEN_PUBLIC_URL: ${{ secrets.MAVEN_PUBLIC_URL }}
SWAGGERHUB_API_KEY: ${{ secrets.SWAGGERHUB_API_KEY }}
SWAGGERHUB_USER: "Frooodle"
- name: Get version number
id: versionNumber
run: echo "versionNumber=$(./gradlew printVersion --quiet | tail -1)" >> $GITHUB_OUTPUT
env:
MAVEN_USER: ${{ secrets.MAVEN_USER }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
MAVEN_PUBLIC_URL: ${{ secrets.MAVEN_PUBLIC_URL }}
- name: Set API version as published and default on SwaggerHub
run: |
+3
View File
@@ -7,6 +7,9 @@ on:
- main
paths:
- "build.gradle"
- "app/common/build.gradle"
- "app/core/build.gradle"
- "app/proprietary/build.gradle"
- "README.md"
- "frontend/public/locales/*/translation.toml"
- "app/core/src/main/resources/static/3rdPartyLicenses.json"
+10 -2
View File
@@ -99,14 +99,19 @@ jobs:
java-version: "21"
distribution: "temurin"
- name: Setup Gradle
uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
with:
gradle-version: 8.14
- name: Build Java backend with JLink
working-directory: ./
shell: bash
run: |
chmod +x ./gradlew
echo "🔧 Building Stirling-PDF JAR..."
# STIRLING_PDF_DESKTOP_UI=false ./gradlew clean bootJar --no-daemon
./gradlew clean build -x spotlessApply -x spotlessCheck -x test -x sonarqube
# STIRLING_PDF_DESKTOP_UI=false ./gradlew bootJar --no-daemon
./gradlew build -x spotlessApply -x spotlessCheck -x test -x sonarqube
# Find the built JAR
STIRLING_JAR=$(ls app/core/build/libs/stirling-pdf-*.jar | head -n 1)
@@ -170,6 +175,9 @@ jobs:
RUNTIME_SIZE=$(du -sh ./frontend/src-tauri/runtime/jre | cut -f1)
echo "📊 Custom JRE size: $RUNTIME_SIZE"
env:
MAVEN_USER: ${{ secrets.MAVEN_USER }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
MAVEN_PUBLIC_URL: ${{ secrets.MAVEN_PUBLIC_URL }}
DISABLE_ADDITIONAL_FEATURES: true
- name: Install frontend dependencies
+4 -1
View File
@@ -44,8 +44,11 @@ jobs:
gradle-version: 8.14
- name: Build with Gradle
run: ./gradlew clean build
run: ./gradlew build
env:
MAVEN_USER: ${{ secrets.MAVEN_USER }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
MAVEN_PUBLIC_URL: ${{ secrets.MAVEN_PUBLIC_URL }}
DISABLE_ADDITIONAL_FEATURES: true
- name: Set up Docker Buildx
@@ -0,0 +1,280 @@
package stirling.software.common.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.service.SsrfProtectionService;
@Component
@RequiredArgsConstructor
@Slf4j
public class SvgSanitizer {
private static final Set<String> DANGEROUS_ELEMENTS =
Set.of("script", "foreignobject", "iframe", "object", "embed", "handler", "listener");
private static final Set<String> URL_ATTRIBUTES = Set.of("href", "xlink:href", "src", "data");
private static final Pattern JAVASCRIPT_URL_PATTERN =
Pattern.compile("^\\s*javascript\\s*:", Pattern.CASE_INSENSITIVE);
private static final Pattern DATA_SCRIPT_PATTERN =
Pattern.compile(
"^\\s*data\\s*:[^,]*(?:script|javascript|vbscript)", Pattern.CASE_INSENSITIVE);
private final SsrfProtectionService ssrfProtectionService;
private final ApplicationProperties applicationProperties;
public byte[] sanitize(byte[] svgBytes) throws IOException {
if (svgBytes == null || svgBytes.length == 0) {
throw new IOException("SVG input is empty or null");
}
if (applicationProperties.getSystem().isDisableSanitize()) {
log.debug("SVG sanitization disabled by configuration");
return svgBytes;
}
try {
Document doc = parseSecurely(svgBytes);
Element root = doc.getDocumentElement();
if (root == null) {
throw new IOException("SVG document has no root element");
}
sanitizeNode(root);
byte[] result = serializeDocument(doc);
if (result == null || result.length == 0) {
throw new IOException("SVG sanitization produced empty output");
}
return result;
} catch (ParserConfigurationException | SAXException | TransformerException e) {
throw new IOException("Failed to sanitize SVG content", e);
}
}
private Document parseSecurely(byte[] svgBytes)
throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
factory.setXIncludeAware(false);
factory.setExpandEntityReferences(false);
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new ByteArrayInputStream(svgBytes));
}
private void sanitizeNode(Node node) {
if (node == null) {
return;
}
NodeList children = node.getChildNodes();
Set<Node> nodesToRemove = new HashSet<>();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
String localName = child.getLocalName();
if (localName == null) {
localName = child.getNodeName();
}
if (isDangerousElement(localName)) {
log.warn("Removing dangerous SVG element: {}", localName);
nodesToRemove.add(child);
} else {
sanitizeNode(child);
}
}
}
for (Node toRemove : nodesToRemove) {
node.removeChild(toRemove);
}
if (node.getNodeType() == Node.ELEMENT_NODE) {
sanitizeAttributes((Element) node);
}
}
private void sanitizeAttributes(Element element) {
NamedNodeMap attributes = element.getAttributes();
Set<String> attributesToRemove = new HashSet<>();
for (int i = 0; i < attributes.getLength(); i++) {
Node attr = attributes.item(i);
String attrName = attr.getNodeName().toLowerCase();
String attrValue = attr.getNodeValue();
if (isEventHandler(attrName)) {
log.warn("Removing event handler attribute: {}", attrName);
attributesToRemove.add(attr.getNodeName());
continue;
}
if (isUrlAttribute(attrName)) {
if (isDangerousUrl(attrValue)) {
log.warn(
"Removing dangerous URL in attribute {}: {}",
attrName,
truncateForLog(attrValue));
attributesToRemove.add(attr.getNodeName());
continue;
}
if (isExternalUrl(attrValue) && !isUrlAllowed(attrValue)) {
log.warn(
"Removing SSRF-blocked URL in attribute {}: {}",
attrName,
truncateForLog(attrValue));
attributesToRemove.add(attr.getNodeName());
}
}
}
for (String attrName : attributesToRemove) {
element.removeAttribute(attrName);
}
}
private boolean isDangerousElement(String localName) {
return DANGEROUS_ELEMENTS.contains(localName.toLowerCase());
}
private boolean isEventHandler(String attrName) {
return attrName.startsWith("on");
}
private boolean isUrlAttribute(String attrName) {
return URL_ATTRIBUTES.contains(attrName.toLowerCase())
|| attrName.toLowerCase().endsWith(":href");
}
private boolean isDangerousUrl(String url) {
if (url == null || url.trim().isEmpty()) {
return false;
}
String normalized = normalizeUrl(url);
if (JAVASCRIPT_URL_PATTERN.matcher(normalized).find()) {
return true;
}
if (DATA_SCRIPT_PATTERN.matcher(normalized).find()) {
return true;
}
return false;
}
private String normalizeUrl(String url) {
if (url == null) {
return "";
}
String result = url.trim();
result = result.replaceAll("\u0000", "");
for (int i = 0; i < 3; i++) {
try {
String decoded = URLDecoder.decode(result, StandardCharsets.UTF_8);
if (decoded.equals(result)) {
break; // No more decoding needed
}
result = decoded;
} catch (Exception e) {
log.debug("Failed to decode URL, continuing with current value", e);
break;
}
}
return result.toLowerCase();
}
private boolean isExternalUrl(String url) {
if (url == null || url.trim().isEmpty()) {
return false;
}
String normalized = normalizeUrl(url);
if (normalized.startsWith("#")) {
return false;
}
if (normalized.startsWith("data:")) {
return false;
}
return normalized.startsWith("http://")
|| normalized.startsWith("https://")
|| normalized.startsWith("//")
|| normalized.startsWith("file:");
}
private boolean isUrlAllowed(String url) {
if (ssrfProtectionService == null) {
return true;
}
return ssrfProtectionService.isUrlAllowed(url);
}
private byte[] serializeDocument(Document doc) throws TransformerException {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "no");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
transformer.transform(new DOMSource(doc), new StreamResult(outputStream));
return outputStream.toByteArray();
}
private String truncateForLog(String value) {
if (value == null) {
return "null";
}
return value.length() > 50 ? value.substring(0, 50) + "..." : value;
}
}
+3 -5
View File
@@ -2,11 +2,6 @@ apply plugin: 'org.springframework.boot'
import org.apache.tools.ant.taskdefs.condition.Os
repositories {
maven { url = 'https://build.shibboleth.net/maven/releases' }
maven { url = 'https://maven.pkg.github.com/jcefmaven/jcefmaven' }
}
configurations {
developmentOnly
runtimeClasspath {
@@ -91,6 +86,9 @@ dependencies {
// Batik
implementation 'org.apache.xmlgraphics:batik-all:1.19'
// PDFBox Graphics2D bridge for Batik SVG to PDF conversion
implementation 'de.rototor.pdfbox:graphics2d:3.0.5'
// TwelveMonkeys
runtimeOnly "com.twelvemonkeys.imageio:imageio-batik:$imageioVersion"
runtimeOnly "com.twelvemonkeys.imageio:imageio-bmp:$imageioVersion"
@@ -0,0 +1,244 @@
package stirling.software.SPDF.controller.api.converters;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.multipart.MultipartFile;
import io.github.pixee.security.Filenames;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.config.swagger.MultiFileResponse;
import stirling.software.SPDF.model.api.converters.SvgToPdfRequest;
import stirling.software.SPDF.utils.SvgToPdf;
import stirling.software.common.annotations.AutoJobPostMapping;
import stirling.software.common.annotations.api.ConvertApi;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.GeneralUtils;
import stirling.software.common.util.SvgSanitizer;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
@ConvertApi
@Slf4j
@RequiredArgsConstructor
public class ConvertSvgToPDF {
private final CustomPDFDocumentFactory pdfDocumentFactory;
private final SvgSanitizer svgSanitizer;
private final TempFileManager tempFileManager;
@AutoJobPostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE, value = "/svg/pdf")
@MultiFileResponse
@Operation(
summary = "Convert SVG to PDF",
description =
"This endpoint converts one or more SVG (Scalable Vector Graphics) files to PDF format. "
+ "Each SVG is converted to a separate PDF file. "
+ "The conversion preserves vector graphics for crisp output at any resolution - no rasterization occurs. "
+ "SVG dimensions (width/height) determine the PDF page size; defaults to A4 if not specified. "
+ "SVG content is sanitized to prevent XSS attacks. "
+ "Input: SVG file(s), Output: PDF file(s) or ZIP. Type: MIMO")
public ResponseEntity<byte[]> convertSvgToPdf(@ModelAttribute SvgToPdfRequest request) {
MultipartFile[] inputFiles = request.getFileInput();
boolean combineIntoSinglePdf = Boolean.TRUE.equals(request.getCombineIntoSinglePdf());
// Validate input
if (inputFiles == null || inputFiles.length == 0) {
log.error("No files provided for SVG to PDF conversion.");
return ResponseEntity.badRequest()
.body("No files provided".getBytes(StandardCharsets.UTF_8));
}
try {
List<byte[]> sanitizedSvgs = new ArrayList<>();
List<String> filenames = new ArrayList<>();
for (MultipartFile inputFile : inputFiles) {
if (inputFile == null || inputFile.isEmpty()) {
log.warn("Skipping empty file in batch conversion");
continue;
}
String originalFilename = inputFile.getOriginalFilename();
if (originalFilename == null || originalFilename.trim().isEmpty()) {
log.warn("Skipping file with null or empty filename");
continue;
}
String lowerFilename = originalFilename.toLowerCase(Locale.ROOT);
if (!lowerFilename.endsWith(".svg")) {
log.warn("Skipping non-SVG file: {}", originalFilename);
continue;
}
try {
byte[] fileBytes = inputFile.getBytes();
byte[] sanitizedBytes = svgSanitizer.sanitize(fileBytes);
sanitizedSvgs.add(sanitizedBytes);
filenames.add(Filenames.toSimpleFileName(originalFilename));
} catch (IOException e) {
log.error(
"SVG sanitization/reading failed for {}: {}",
originalFilename,
e.getMessage());
}
}
if (sanitizedSvgs.isEmpty()) {
log.error("No valid SVG files were found");
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("No valid SVG files were found".getBytes(StandardCharsets.UTF_8));
}
if (combineIntoSinglePdf) {
return handleCombinedConversion(sanitizedSvgs, filenames);
} else {
return handleSeparateConversion(sanitizedSvgs, filenames);
}
} catch (Exception e) {
log.error("Unexpected error during SVG to PDF conversion", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(
"An unexpected error occurred during conversion"
.getBytes(StandardCharsets.UTF_8));
}
}
private ResponseEntity<byte[]> handleCombinedConversion(
List<byte[]> sanitizedSvgs, List<String> filenames) {
try {
log.info("Combining {} SVG files into single PDF", sanitizedSvgs.size());
byte[] pdfBytes = SvgToPdf.combineIntoPdf(sanitizedSvgs);
if (pdfBytes == null || pdfBytes.length == 0) {
log.error("PDF conversion failed - empty output");
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(
"PDF conversion failed - empty output"
.getBytes(StandardCharsets.UTF_8));
}
pdfBytes = pdfDocumentFactory.createNewBytesBasedOnOldDocument(pdfBytes);
String outputFilename =
filenames.isEmpty()
? "combined_svgs.pdf"
: GeneralUtils.generateFilename(filenames.get(0), "_combined.pdf");
log.info("Successfully combined {} SVGs into single PDF", sanitizedSvgs.size());
return WebResponseUtils.bytesToWebResponse(
pdfBytes, outputFilename, MediaType.APPLICATION_PDF);
} catch (IOException e) {
log.error("Error combining SVGs into PDF", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(
("Conversion failed: " + e.getMessage())
.getBytes(StandardCharsets.UTF_8));
}
}
private ResponseEntity<byte[]> handleSeparateConversion(
List<byte[]> sanitizedSvgs, List<String> filenames) {
List<ConvertedPdf> convertedPdfs = new ArrayList<>();
for (int i = 0; i < sanitizedSvgs.size(); i++) {
byte[] sanitizedBytes = sanitizedSvgs.get(i);
String baseFilename = filenames.get(i);
try {
byte[] pdfBytes = SvgToPdf.convert(sanitizedBytes);
if (pdfBytes == null || pdfBytes.length == 0) {
log.error("PDF conversion failed - empty output for {}", baseFilename);
continue;
}
pdfBytes = pdfDocumentFactory.createNewBytesBasedOnOldDocument(pdfBytes);
String outputFilename = GeneralUtils.generateFilename(baseFilename, ".pdf");
convertedPdfs.add(new ConvertedPdf(outputFilename, pdfBytes));
log.info("Successfully converted SVG to PDF: {}", baseFilename);
} catch (IOException e) {
log.error("File processing error for SVG to PDF: {}", baseFilename, e);
}
}
if (convertedPdfs.isEmpty()) {
log.error("No files were successfully converted");
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("No files were successfully converted".getBytes(StandardCharsets.UTF_8));
}
try {
if (convertedPdfs.size() == 1) {
ConvertedPdf pdf = convertedPdfs.get(0);
return WebResponseUtils.bytesToWebResponse(
pdf.content, pdf.filename, MediaType.APPLICATION_PDF);
}
String zipFilename =
filenames.isEmpty()
? "converted_svgs.zip"
: GeneralUtils.generateFilename(
filenames.get(0), "_converted_svgs.zip");
byte[] zipBytes = createZipFromPdfs(convertedPdfs);
return WebResponseUtils.bytesToWebResponse(
zipBytes, zipFilename, MediaType.APPLICATION_OCTET_STREAM);
} catch (IOException e) {
log.error("Failed to create response", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Failed to create response".getBytes(StandardCharsets.UTF_8));
}
}
private byte[] createZipFromPdfs(List<ConvertedPdf> pdfs) throws IOException {
try (TempFile tempZipFile = new TempFile(tempFileManager, ".zip");
ZipOutputStream zipOut =
new ZipOutputStream(Files.newOutputStream(tempZipFile.getPath()))) {
for (ConvertedPdf pdf : pdfs) {
ZipEntry pdfEntry = new ZipEntry(pdf.filename);
zipOut.putNextEntry(pdfEntry);
zipOut.write(pdf.content);
zipOut.closeEntry();
log.debug("Added {} to ZIP", pdf.filename);
}
return Files.readAllBytes(tempZipFile.getPath());
}
}
private static class ConvertedPdf {
final String filename;
final byte[] content;
ConvertedPdf(String filename, byte[] content) {
this.filename = filename;
this.content = content;
}
}
}
@@ -1,7 +1,12 @@
package stirling.software.SPDF.controller.api.misc;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
@@ -14,11 +19,11 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.model.api.misc.OverlayImageRequest;
import stirling.software.SPDF.utils.SvgOverlayUtil;
import stirling.software.common.annotations.AutoJobPostMapping;
import stirling.software.common.annotations.api.MiscApi;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.GeneralUtils;
import stirling.software.common.util.PdfUtils;
import stirling.software.common.util.WebResponseUtils;
@MiscApi
@@ -32,25 +37,63 @@ public class OverlayImageController {
@Operation(
summary = "Overlay image onto a PDF file",
description =
"This endpoint overlays an image onto a PDF file at the specified coordinates."
+ " The image can be overlaid on every page of the PDF if specified. "
+ " Input:PDF/IMAGE Output:PDF Type:SISO")
"This endpoint overlays an image onto a PDF file at the specified coordinates. "
+ "Supports both raster formats (PNG, JPEG, etc.) and vector format (SVG). "
+ "SVG files are rendered as vector graphics for crisp output at any resolution. "
+ "The image can be overlaid on every page of the PDF if specified. "
+ "Input:PDF/IMAGE/SVG Output:PDF Type:SISO")
public ResponseEntity<byte[]> overlayImage(@ModelAttribute OverlayImageRequest request) {
MultipartFile pdfFile = request.getFileInput();
MultipartFile imageFile = request.getImageFile();
float x = request.getX();
float y = request.getY();
boolean everyPage = Boolean.TRUE.equals(request.getEveryPage());
try {
byte[] pdfBytes = pdfFile.getBytes();
byte[] imageBytes = imageFile.getBytes();
byte[] result =
PdfUtils.overlayImage(
pdfDocumentFactory, pdfBytes, imageBytes, x, y, everyPage);
boolean isSvg = SvgOverlayUtil.isSvgImage(imageBytes);
PDDocument document = pdfDocumentFactory.load(pdfBytes);
int pages = document.getNumberOfPages();
for (int i = 0; i < pages; i++) {
PDPage page = document.getPage(i);
if (isSvg) {
SvgOverlayUtil.overlaySvgOnPage(document, page, imageBytes, x, y);
} else {
try (PDPageContentStream contentStream =
new PDPageContentStream(
document,
page,
PDPageContentStream.AppendMode.APPEND,
true,
true)) {
PDImageXObject image =
PDImageXObject.createFromByteArray(document, imageBytes, "");
contentStream.drawImage(image, x, y);
log.info("Image successfully overlaid onto PDF page {}", i);
}
}
if (!everyPage && i == 0) {
break;
}
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
document.save(baos);
document.close();
byte[] result = baos.toByteArray();
log.info("PDF with overlaid image successfully created");
return WebResponseUtils.bytesToWebResponse(
result,
GeneralUtils.generateFilename(pdfFile.getOriginalFilename(), "_overlayed.pdf"));
} catch (IOException e) {
log.error("Failed to add image to PDF", e);
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
@@ -1,9 +1,6 @@
package stirling.software.SPDF.controller.api.pipeline;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystemException;
import java.nio.file.FileVisitResult;
@@ -24,7 +21,6 @@ import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@@ -164,7 +160,8 @@ public class PipelineDirectoryProcessor {
postHogService.captureEvent("pipeline_directory_event", properties);
List<File> filesToProcess = prepareFilesForProcessing(files, processingDir);
runPipelineAgainstFiles(filesToProcess, config, dir, processingDir);
try (PipelineResult result =
runPipelineAgainstFiles(filesToProcess, config, dir, processingDir)) {}
}
}
@@ -303,14 +300,14 @@ public class PipelineDirectoryProcessor {
}
}
private void runPipelineAgainstFiles(
private PipelineResult runPipelineAgainstFiles(
List<File> filesToProcess, PipelineConfig config, Path dir, Path processingDir)
throws IOException {
try {
List<Resource> inputFiles =
processor.generateInputFiles(filesToProcess.toArray(new File[0]));
if (inputFiles == null || inputFiles.isEmpty()) {
return;
return new PipelineResult();
}
PipelineResult result = processor.runPipelineAgainstFiles(inputFiles, config);
@@ -321,9 +318,11 @@ public class PipelineDirectoryProcessor {
moveAndRenameFiles(result.getOutputFiles(), config, dir);
deleteOriginalFiles(filesToProcess, processingDir);
}
return result;
} catch (Exception e) {
log.error("Error during processing", e);
moveFilesBack(filesToProcess, processingDir);
return new PipelineResult();
}
}
@@ -350,8 +349,9 @@ public class PipelineDirectoryProcessor {
log.info("Created directory: {}", outputPath);
}
Path outputFile = outputPath.resolve(outputFileName);
try (OutputStream os = new FileOutputStream(outputFile.toFile())) {
os.write(((ByteArrayResource) resource).getByteArray());
try (OutputStream os = new FileOutputStream(outputFile.toFile());
InputStream is = resource.getInputStream()) {
is.transferTo(os);
}
log.info("File moved and renamed to {}", outputFile);
}
@@ -15,9 +15,10 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
@@ -38,6 +39,8 @@ import stirling.software.SPDF.model.PipelineResult;
import stirling.software.SPDF.service.ApiDocService;
import stirling.software.common.model.enumeration.Role;
import stirling.software.common.service.UserServiceInterface;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
@Service
@Slf4j
@@ -49,13 +52,17 @@ public class PipelineProcessor {
private final ServletContext servletContext;
private final TempFileManager tempFileManager;
public PipelineProcessor(
ApiDocService apiDocService,
@Autowired(required = false) UserServiceInterface userService,
ServletContext servletContext) {
ServletContext servletContext,
TempFileManager tempFileManager) {
this.apiDocService = apiDocService;
this.userService = userService;
this.servletContext = servletContext;
this.tempFileManager = tempFileManager;
}
public static String removeTrailingNaming(String filename) {
@@ -137,14 +144,18 @@ public class PipelineProcessor {
body.add(entry.getKey(), entry.getValue());
}
}
ResponseEntity<byte[]> response = sendWebRequest(url, body);
ResponseEntity<Resource> response = sendWebRequest(url, body);
// If the operation is filter and the response body is null or empty,
// skip
// this
// file
if (response.getBody() instanceof TempFileResource tempFileResource) {
result.addTempFile(tempFileResource.getTempFile());
}
if (operation.startsWith("/api/v1/filter/filter-")
&& (response.getBody() == null
|| response.getBody().length == 0)) {
|| response.getBody().contentLength() == 0)) {
filtersApplied = true;
log.info("Skipping file due to filtering {}", operation);
continue;
@@ -154,7 +165,7 @@ public class PipelineProcessor {
hasErrors = true;
continue;
}
processOutputFiles(operation, response, newOutputFiles);
processOutputFiles(operation, response, newOutputFiles, result);
}
}
if (!hasInputFileType) {
@@ -215,10 +226,13 @@ public class PipelineProcessor {
body.add(entry.getKey(), entry.getValue());
}
}
ResponseEntity<byte[]> response = sendWebRequest(url, body);
ResponseEntity<Resource> response = sendWebRequest(url, body);
if (response.getBody() instanceof TempFileResource tempFileResource) {
result.addTempFile(tempFileResource.getTempFile());
}
// Handle the response
if (HttpStatus.OK.equals(response.getStatusCode())) {
processOutputFiles(operation, response, newOutputFiles);
processOutputFiles(operation, response, newOutputFiles, result);
} else {
// Log error if the response status is not OK
logPrintStream.println(
@@ -267,7 +281,7 @@ public class PipelineProcessor {
return result;
}
/* package */ ResponseEntity<byte[]> sendWebRequest(
/* package */ ResponseEntity<Resource> sendWebRequest(
String url, MultiValueMap<String, Object> body) {
RestTemplate restTemplate = new RestTemplate();
// Set up headers, including API key
@@ -275,14 +289,37 @@ public class PipelineProcessor {
String apiKey = getApiKeyForUser();
headers.add("X-API-KEY", apiKey);
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
// Create HttpEntity with the body and headers
HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(body, headers);
// Make the request to the REST endpoint
return restTemplate.exchange(url, HttpMethod.POST, entity, byte[].class);
return restTemplate.execute(
url,
HttpMethod.POST,
request -> {
request.getHeaders().putAll(headers);
new FormHttpMessageConverter()
.write(body, MediaType.MULTIPART_FORM_DATA, request);
},
response -> {
try {
TempFile tempFile = tempFileManager.createManagedTempFile("pipeline");
Files.copy(
response.getBody(),
tempFile.getPath(),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
TempFileResource resource = new TempFileResource(tempFile);
return ResponseEntity.status(response.getStatusCode())
.headers(response.getHeaders())
.body(resource);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
private List<Resource> processOutputFiles(
String operation, ResponseEntity<byte[]> response, List<Resource> newOutputFiles)
String operation,
ResponseEntity<Resource> response,
List<Resource> newOutputFiles,
PipelineResult result)
throws IOException {
// Define filename
String newFilename;
@@ -298,10 +335,14 @@ public class PipelineProcessor {
// Check if the response body is a zip file
if (isZip(response.getBody(), newFilename)) {
// Unzip the file and add all the files to the new output files
newOutputFiles.addAll(unzip(response.getBody()));
newOutputFiles.addAll(unzip(response.getBody(), result));
} else {
final Resource tempResource = response.getBody();
if (tempResource instanceof TempFileResource) {
result.addTempFile(((TempFileResource) tempResource).getTempFile());
}
Resource outputResource =
new ByteArrayResource(response.getBody()) {
new FileSystemResource(tempResource.getFile()) {
@Override
public String getFilename() {
@@ -313,7 +354,7 @@ public class PipelineProcessor {
return newOutputFiles;
}
public String extractFilename(ResponseEntity<byte[]> response) {
public String extractFilename(ResponseEntity<Resource> response) {
// Default filename if not found
String filename = "default-filename.ext";
HttpHeaders headers = response.getHeaders();
@@ -348,14 +389,7 @@ public class PipelineProcessor {
// debug statement
log.info("Reading file: {}", path);
if (Files.exists(path)) {
Resource fileResource =
new ByteArrayResource(Files.readAllBytes(path)) {
@Override
public String getFilename() {
return file.getName();
}
};
Resource fileResource = new FileSystemResource(file);
outputFiles.add(fileResource);
} else {
log.info("File not found: {}", path);
@@ -372,8 +406,11 @@ public class PipelineProcessor {
}
List<Resource> outputFiles = new ArrayList<>();
for (MultipartFile file : files) {
Path tempFile = Files.createTempFile("SPDF-upload-", ".tmp");
file.transferTo(tempFile);
Resource fileResource =
new ByteArrayResource(file.getBytes()) {
new FileSystemResource(tempFile.toFile()) {
@Override
public String getFilename() {
@@ -386,8 +423,8 @@ public class PipelineProcessor {
return outputFiles;
}
private boolean isZip(byte[] data, String filename) {
if (data == null || data.length < 4) {
private boolean isZip(Resource data, String filename) throws IOException {
if (data == null || data.contentLength() < 4) {
return false;
}
if (filename != null) {
@@ -398,29 +435,41 @@ public class PipelineProcessor {
}
}
// Check the first four bytes of the data against the standard zip magic number
return data[0] == 0x50 && data[1] == 0x4B && data[2] == 0x03 && data[3] == 0x04;
try (InputStream is = data.getInputStream()) {
byte[] header = new byte[4];
if (is.read(header) < 4) {
return false;
}
return header[0] == 0x50 && header[1] == 0x4B && header[2] == 0x03 && header[3] == 0x04;
}
}
private boolean isZip(byte[] data) {
private boolean isZip(Resource data) throws IOException {
return isZip(data, null);
}
private List<Resource> unzip(byte[] data) throws IOException {
log.info("Unzipping data of length: {}", data.length);
private List<Resource> unzip(Resource data, PipelineResult result) throws IOException {
log.info("Unzipping data of length: {}", data.contentLength());
List<Resource> unzippedFiles = new ArrayList<>();
try (ByteArrayInputStream bais = new ByteArrayInputStream(data);
try (InputStream bais = data.getInputStream();
ZipInputStream zis = ZipSecurity.createHardenedInputStream(bais)) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count;
while ((count = zis.read(buffer)) != -1) {
baos.write(buffer, 0, count);
if (entry.isDirectory()) {
continue;
}
TempFile tempFile = tempFileManager.createManagedTempFile("unzip");
result.addTempFile(tempFile);
try (OutputStream os = Files.newOutputStream(tempFile.getPath())) {
byte[] buffer = new byte[4096];
int count;
while ((count = zis.read(buffer)) != -1) {
os.write(buffer, 0, count);
}
}
final String filename = entry.getName();
Resource fileResource =
new ByteArrayResource(baos.toByteArray()) {
new FileSystemResource(tempFile.getFile()) {
@Override
public String getFilename() {
@@ -428,9 +477,9 @@ public class PipelineProcessor {
}
};
// If the unzipped file is a zip file, unzip it
if (isZip(baos.toByteArray(), filename)) {
if (isZip(fileResource, filename)) {
log.info("File {} is a zip file. Unzipping...", filename);
unzippedFiles.addAll(unzip(baos.toByteArray()));
unzippedFiles.addAll(unzip(fileResource, result));
} else {
unzippedFiles.add(fileResource);
}
@@ -439,4 +488,17 @@ public class PipelineProcessor {
log.info("Unzipping completed. {} files were unzipped.", unzippedFiles.size());
return unzippedFiles;
}
private static class TempFileResource extends FileSystemResource {
private final TempFile tempFile;
public TempFileResource(TempFile tempFile) {
super(tempFile.getFile());
this.tempFile = tempFile;
}
public TempFile getTempFile() {
return tempFile;
}
}
}
@@ -1,14 +1,37 @@
package stirling.software.SPDF.model;
import java.util.ArrayList;
import java.util.List;
import org.springframework.core.io.Resource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.util.TempFile;
@Data
public class PipelineResult {
@Slf4j
public class PipelineResult implements AutoCloseable {
private List<Resource> outputFiles;
private boolean hasErrors;
private boolean filtersApplied;
private List<TempFile> tempFiles = new ArrayList<>();
public void addTempFile(TempFile tempFile) {
tempFiles.add(tempFile);
}
@Override
public void close() {
for (TempFile file : tempFiles) {
file.close();
log.debug("Deleted temp file: {}", file.getAbsolutePath());
}
tempFiles.clear();
}
public void cleanup() {
close();
}
}
@@ -0,0 +1,29 @@
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 SvgToPdfRequest {
@Schema(
description =
"The SVG file(s) to be converted to PDF. "
+ "SVGs are scalable and have inherent dimensions - the conversion uses these dimensions "
+ "to determine the PDF page size. If dimensions are not specified in the SVG, A4 size is used.",
requiredMode = Schema.RequiredMode.REQUIRED)
private MultipartFile[] fileInput;
@Schema(
description =
"Whether to combine all SVG files into a single PDF (each SVG as a separate page) "
+ "or create separate PDF files for each SVG.",
requiredMode = Schema.RequiredMode.REQUIRED,
defaultValue = "false")
private Boolean combineIntoSinglePdf;
}
@@ -14,7 +14,10 @@ import stirling.software.common.model.api.PDFFile;
public class OverlayImageRequest extends PDFFile {
@Schema(
description = "The image file to be overlaid onto the PDF.",
description =
"The image file to be overlaid onto the PDF. "
+ "Supports raster formats (PNG, JPEG, etc.) and vector format (SVG). "
+ "SVG files are rendered as vector graphics for crisp output at any resolution.",
requiredMode = Schema.RequiredMode.REQUIRED,
format = "binary")
private MultipartFile imageFile;
@@ -0,0 +1,97 @@
package stirling.software.SPDF.utils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.apache.batik.anim.dom.SAXSVGDocumentFactory;
import org.apache.batik.bridge.BridgeContext;
import org.apache.batik.bridge.DocumentLoader;
import org.apache.batik.bridge.GVTBuilder;
import org.apache.batik.bridge.UserAgent;
import org.apache.batik.bridge.UserAgentAdapter;
import org.apache.batik.gvt.GraphicsNode;
import org.apache.batik.util.XMLResourceDescriptor;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
import org.apache.pdfbox.util.Matrix;
import org.w3c.dom.svg.SVGDocument;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import de.rototor.pdfbox.graphics2d.PdfBoxGraphics2D;
@UtilityClass
@Slf4j
public class SvgOverlayUtil {
public void overlaySvgOnPage(
PDDocument document, PDPage page, byte[] svgBytes, float x, float y)
throws IOException {
try {
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory(parser);
SVGDocument svgDoc;
try (ByteArrayInputStream inputStream = new ByteArrayInputStream(svgBytes)) {
svgDoc = factory.createSVGDocument("file:///overlay.svg", inputStream);
}
UserAgent userAgent = new UserAgentAdapter();
DocumentLoader loader = new DocumentLoader(userAgent);
BridgeContext ctx = new BridgeContext(userAgent, loader);
ctx.setDynamicState(BridgeContext.DYNAMIC);
GVTBuilder builder = new GVTBuilder();
GraphicsNode rootNode = builder.build(ctx, svgDoc);
float svgWidth = (float) ctx.getDocumentSize().getWidth();
float svgHeight = (float) ctx.getDocumentSize().getHeight();
PdfBoxGraphics2D pdfGraphics = new PdfBoxGraphics2D(document, svgWidth, svgHeight);
try {
rootNode.paint(pdfGraphics);
} finally {
pdfGraphics.dispose();
}
PDFormXObject xform = pdfGraphics.getXFormObject();
try (PDPageContentStream newContentStream =
new PDPageContentStream(
document, page, PDPageContentStream.AppendMode.APPEND, true, true)) {
newContentStream.saveGraphicsState();
newContentStream.transform(new Matrix(1, 0, 0, 1, x, y));
newContentStream.drawForm(xform);
newContentStream.restoreGraphicsState();
}
log.info("SVG successfully overlaid as vector graphic at ({}, {})", x, y);
} catch (Exception e) {
log.error("Failed to overlay SVG as vector graphic", e);
throw new IOException("SVG overlay failed: " + e.getMessage(), e);
}
}
public boolean isSvgImage(byte[] bytes) {
if (bytes == null || bytes.length < 5) {
return false;
}
// Check for SVG markers: <?xml or <svg
String start =
new String(
bytes,
0,
Math.min(200, bytes.length),
java.nio.charset.StandardCharsets.UTF_8)
.toLowerCase();
return start.contains("<svg") || (start.contains("<?xml") && start.contains("svg"));
}
}
@@ -0,0 +1,234 @@
package stirling.software.SPDF.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.batik.anim.dom.SAXSVGDocumentFactory;
import org.apache.batik.bridge.BridgeContext;
import org.apache.batik.bridge.DocumentLoader;
import org.apache.batik.bridge.GVTBuilder;
import org.apache.batik.bridge.UserAgent;
import org.apache.batik.bridge.UserAgentAdapter;
import org.apache.batik.gvt.GraphicsNode;
import org.apache.batik.util.XMLResourceDescriptor;
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.w3c.dom.svg.SVGDocument;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import de.rototor.pdfbox.graphics2d.PdfBoxGraphics2D;
@UtilityClass
@Slf4j
public class SvgToPdf {
/** Default page width in points (A4) */
private static final float DEFAULT_PAGE_WIDTH = 595f;
/** Default page height in points (A4) */
private static final float DEFAULT_PAGE_HEIGHT = 842f;
/** Timeout for SVG rendering in seconds (prevents DoS via complex SVGs) */
private static final int RENDERING_TIMEOUT_SECONDS = 30;
public byte[] convert(byte[] svgBytes) throws IOException {
if (svgBytes == null || svgBytes.length == 0) {
throw new IOException("SVG input is empty or null");
}
log.debug("Starting SVG to PDF conversion, input size: {} bytes", svgBytes.length);
try {
// 1. Load SVG using Batik
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory(parser);
SVGDocument svgDoc;
try (ByteArrayInputStream inputStream = new ByteArrayInputStream(svgBytes)) {
svgDoc = factory.createSVGDocument("file:///input.svg", inputStream);
}
// 2. Build the GVT (Graphics Vector Tree) with timeout protection
UserAgent userAgent = new UserAgentAdapter();
DocumentLoader loader = new DocumentLoader(userAgent);
BridgeContext ctx = new BridgeContext(userAgent, loader);
ctx.setDynamicState(BridgeContext.DYNAMIC);
GraphicsNode rootNode = buildGvtWithTimeout(ctx, svgDoc);
// 3. Get SVG dimensions
float width = (float) ctx.getDocumentSize().getWidth();
float height = (float) ctx.getDocumentSize().getHeight();
if (width <= 0) {
width = DEFAULT_PAGE_WIDTH;
log.warn("SVG width not specified, using default: {}", width);
}
if (height <= 0) {
height = DEFAULT_PAGE_HEIGHT;
log.warn("SVG height not specified, using default: {}", height);
}
log.debug("SVG dimensions: {}x{} points", width, height);
// 4. Create PDF document and render
return renderToPdf(rootNode, width, height);
} catch (Exception e) {
log.error("Failed to convert SVG to PDF", e);
throw new IOException("SVG to PDF conversion failed: " + e.getMessage(), e);
}
}
private GraphicsNode buildGvtWithTimeout(BridgeContext ctx, SVGDocument svgDoc)
throws IOException {
GVTBuilder builder = new GVTBuilder();
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<GraphicsNode> buildTask = () -> builder.build(ctx, svgDoc);
Future<GraphicsNode> future = executor.submit(buildTask);
try {
return future.get(RENDERING_TIMEOUT_SECONDS, TimeUnit.SECONDS);
} catch (TimeoutException e) {
future.cancel(true);
throw new IOException(
"SVG rendering timed out after "
+ RENDERING_TIMEOUT_SECONDS
+ " seconds. The SVG may be too complex.");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("SVG rendering was interrupted", e);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
throw new IOException(
"SVG rendering failed: "
+ (cause != null ? cause.getMessage() : e.getMessage()),
cause);
} finally {
executor.shutdownNow();
}
}
private byte[] renderToPdf(GraphicsNode rootNode, float width, float height)
throws IOException {
try (PDDocument document = new PDDocument();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
PDPage page = new PDPage(new PDRectangle(width, height));
document.addPage(page);
// Create and use PdfBoxGraphics2D with proper resource management
PdfBoxGraphics2D pdfGraphics = new PdfBoxGraphics2D(document, width, height);
try {
rootNode.paint(pdfGraphics);
} finally {
pdfGraphics.dispose();
}
PDFormXObject xform = pdfGraphics.getXFormObject();
try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
contentStream.drawForm(xform);
}
document.save(outputStream);
byte[] result = outputStream.toByteArray();
log.debug("SVG to PDF conversion complete, output size: {} bytes", result.length);
return result;
}
}
public byte[] combineIntoPdf(List<byte[]> svgBytesList) throws IOException {
if (svgBytesList == null || svgBytesList.isEmpty()) {
throw new IOException("SVG list is empty or null");
}
log.debug("Combining {} SVG files into single PDF", svgBytesList.size());
try (PDDocument document = new PDDocument();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
for (int i = 0; i < svgBytesList.size(); i++) {
byte[] svgBytes = svgBytesList.get(i);
if (svgBytes == null || svgBytes.length == 0) {
log.warn("Skipping empty SVG at index {}", i);
continue;
}
try {
addSvgAsPage(document, svgBytes);
log.debug("Added SVG {} of {} to combined PDF", i + 1, svgBytesList.size());
} catch (Exception e) {
log.error("Failed to add SVG {} to combined PDF: {}", i, e.getMessage());
// Continue with other SVGs
}
}
if (document.getNumberOfPages() == 0) {
throw new IOException("No SVG files were successfully added to the PDF");
}
document.save(outputStream);
byte[] result = outputStream.toByteArray();
log.debug(
"Combined SVG to PDF conversion complete, output size: {} bytes",
result.length);
return result;
}
}
private void addSvgAsPage(PDDocument document, byte[] svgBytes) throws IOException {
String parser = XMLResourceDescriptor.getXMLParserClassName();
SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory(parser);
SVGDocument svgDoc;
try (ByteArrayInputStream inputStream = new ByteArrayInputStream(svgBytes)) {
svgDoc = factory.createSVGDocument("file:///input.svg", inputStream);
}
UserAgent userAgent = new UserAgentAdapter();
DocumentLoader loader = new DocumentLoader(userAgent);
BridgeContext ctx = new BridgeContext(userAgent, loader);
ctx.setDynamicState(BridgeContext.DYNAMIC);
GraphicsNode rootNode = buildGvtWithTimeout(ctx, svgDoc);
float svgWidth = (float) ctx.getDocumentSize().getWidth();
float svgHeight = (float) ctx.getDocumentSize().getHeight();
if (svgWidth <= 0) svgWidth = DEFAULT_PAGE_WIDTH;
if (svgHeight <= 0) svgHeight = DEFAULT_PAGE_HEIGHT;
// Use SVG dimensions directly for the PDF page
PDPage page = new PDPage(new PDRectangle(svgWidth, svgHeight));
document.addPage(page);
PdfBoxGraphics2D pdfGraphics = new PdfBoxGraphics2D(document, svgWidth, svgHeight);
try {
rootNode.paint(pdfGraphics);
} finally {
pdfGraphics.dispose();
}
PDFormXObject xform = pdfGraphics.getXFormObject();
try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
contentStream.drawForm(xform);
}
}
}
@@ -4,6 +4,8 @@ import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
@@ -13,6 +15,7 @@ import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@@ -24,6 +27,7 @@ import stirling.software.SPDF.model.PipelineOperation;
import stirling.software.SPDF.model.PipelineResult;
import stirling.software.SPDF.service.ApiDocService;
import stirling.software.common.service.UserServiceInterface;
import stirling.software.common.util.TempFileManager;
@ExtendWith(MockitoExtension.class)
class PipelineProcessorTest {
@@ -34,11 +38,16 @@ class PipelineProcessorTest {
@Mock ServletContext servletContext;
@Mock TempFileManager tempFileManager;
PipelineProcessor pipelineProcessor;
@BeforeEach
void setUp() {
pipelineProcessor = spy(new PipelineProcessor(apiDocService, userService, servletContext));
pipelineProcessor =
spy(
new PipelineProcessor(
apiDocService, userService, servletContext, tempFileManager));
}
@Test
@@ -59,12 +68,18 @@ class PipelineProcessorTest {
when(apiDocService.isValidOperation(eq("/api/v1/filter/filter-page-count"), anyMap()))
.thenReturn(true);
doReturn(new ResponseEntity<>(new byte[0], HttpStatus.OK))
// Use a FileSystemResource backed by a temp file to avoid FileNotFoundException
Path emptyTemp = Files.createTempFile("empty", ".tmp");
Resource emptyResource = new FileSystemResource(emptyTemp.toFile());
doReturn(new ResponseEntity<>(emptyResource, HttpStatus.OK))
.when(pipelineProcessor)
.sendWebRequest(anyString(), any());
PipelineResult result = pipelineProcessor.runPipelineAgainstFiles(files, config);
Files.deleteIfExists(emptyTemp);
assertTrue(
result.isFiltersApplied(),
"Filter flag should be true when operation filters file");
@@ -72,6 +87,45 @@ class PipelineProcessorTest {
assertTrue(result.getOutputFiles().isEmpty(), "Filtered file list should be empty");
}
@Test
void testPipelineSuccessWithResource() throws Exception {
PipelineOperation op = new PipelineOperation();
op.setOperation("/api/v1/misc/compress");
op.setParameters(Map.of());
PipelineConfig config = new PipelineConfig();
config.setOperations(List.of(op));
Resource inputFile = new MyFileByteArrayResource();
List<Resource> files = List.of(inputFile);
Path tempPath = Files.createTempFile("test-output", ".pdf");
Files.write(tempPath, "processed_data".getBytes());
Resource outputResource =
new FileSystemResource(tempPath.toFile()) {
@Override
public String getFilename() {
return "processed.pdf";
}
};
when(apiDocService.isMultiInput(anyString())).thenReturn(false);
when(apiDocService.getExtensionTypes(anyBoolean(), anyString())).thenReturn(List.of("pdf"));
when(apiDocService.isValidOperation(anyString(), anyMap())).thenReturn(true);
doReturn(new ResponseEntity<>(outputResource, HttpStatus.OK))
.when(pipelineProcessor)
.sendWebRequest(anyString(), any());
PipelineResult result = pipelineProcessor.runPipelineAgainstFiles(files, config);
verify(pipelineProcessor).sendWebRequest(anyString(), any());
assertFalse(result.isHasErrors());
// Clean up
Files.deleteIfExists(tempPath);
}
private static class MyFileByteArrayResource extends ByteArrayResource {
public MyFileByteArrayResource() {
super("data".getBytes());
+2 -2
View File
@@ -1,5 +1,5 @@
repositories {
maven { url = "https://build.shibboleth.net/maven/releases" }
maven { url "https://build.shibboleth.net/maven/releases" }
}
ext {
@@ -53,7 +53,7 @@ dependencies {
implementation 'com.bucket4j:bucket4j_jdk17-core:8.15.0'
// https://mvnrepository.com/artifact/com.bucket4j/bucket4j_jdk17
implementation 'org.bouncycastle:bcprov-jdk18on:1.83'
implementation "org.bouncycastle:bcprov-jdk18on:$bouncycastleVersion"
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5:3.1.3.RELEASE'
api 'io.micrometer:micrometer-registry-prometheus'
+26 -7
View File
@@ -38,6 +38,16 @@ ext.isSecurityDisabled = { ->
System.getProperty('DISABLE_ADDITIONAL_FEATURES') == 'true')
}
ext.mavenUrl = System.getenv("MAVEN_PUBLIC_URL") ?: ""
ext.username = System.getenv('MAVEN_USER') ?: ""
ext.password = System.getenv('MAVEN_PASSWORD') ?: ""
if (rootProject.ext.mavenUrl.isEmpty()) {
println "No custom MAVEN_PUBLIC_URL set, defaulting to Maven Central"
} else {
println "MAVEN_PUBLIC_URL set"
}
jar {
enabled = false
manifest {
@@ -55,11 +65,6 @@ springBoot {
mainClass = 'stirling.software.SPDF.SPDFApplication'
}
repositories {
mavenCentral()
maven { url = 'https://build.shibboleth.net/maven/releases' }
}
allprojects {
group = 'stirling.software'
version = '2.3.0'
@@ -135,13 +140,27 @@ subprojects {
sourceCompatibility = JavaVersion.VERSION_17
}
if (project.name != "stirling-pdf") {
if (project.name != "stirling-pdf") {
bootJar {
enabled = false
}
}
}
repositories {
if (!rootProject.ext.mavenUrl.isEmpty()) {
maven {
url rootProject.ext.mavenUrl + '/releases'
credentials(PasswordCredentials) {
username rootProject.ext.username
password rootProject.ext.password
}
authentication {
basic(BasicAuthentication)
}
allowInsecureProtocol true
}
}
maven { url "https://build.shibboleth.net/maven/releases" }
mavenCentral()
}
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI لعرض الصور"
cbrOptions = "خيارات CBR"
cbrOutputOptions = "خيارات تحويل PDF إلى CBR"
cbrDpi = "DPI لعرض الصور"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "خيارات تحويل الكتب الإلكترونية إلى PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "تطبيق الصور"
name = "صورة"
placeholder = "ارفع صورة"
label = "ملف صورة"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "تهيئة الصورة"
@@ -1295,6 +1295,10 @@ cbzDpi = "Şəkil göstərilməsi üçün DPI"
cbrOptions = "CBR seçimləri"
cbrOutputOptions = "PDF-dən CBR-ə seçimlər"
cbrDpi = "Şəkil göstərilməsi üçün DPI"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "eBook-dan PDF-ə seçimlər"
@@ -1396,6 +1400,7 @@ applySignatures = "Şəkilləri tətbiq et"
name = "Şəkil"
placeholder = "Şəkil yükləyin"
label = "Şəkil faylı"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Şəkili tənzimlə"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI за изобразяване на изображение"
cbrOptions = "Опции за CBR"
cbrOutputOptions = "Опции за PDF към CBR"
cbrDpi = "DPI за рендериране на изображения"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "Опции за eBook към PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "Приложи изображения"
name = "Изображение"
placeholder = "Качете изображение"
label = "Файл с изображение"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Конфигурирай изображението"
@@ -1295,6 +1295,10 @@ cbzDpi = "པར་རིས་པར་ལེན་ཆེད་ཀྱི་DPI
cbrOptions = "CBR གདམ་ག།"
cbrOutputOptions = "PDF ནས་ CBR གདམ་ག།"
cbrDpi = "པར་རིས་པར་ལེན་ཆེད་ཀྱི་DPI།"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "གློག་རྡུལ་དེབ་ནས་PDFགདམ་ག།"
@@ -1396,6 +1400,7 @@ applySignatures = "པར་རིས་སྦྱར་བ།"
name = "པར་རིས"
placeholder = "པར་རིས་ཤིག་བསྒྱུར།"
label = "པར་རིས་ཡིག་ཆ།"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "པར་རིས་སྒྲིག་བཀོད་བྱེད་པ།"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI per al renderitzat d'imatges"
cbrOptions = "Opcions CBR"
cbrOutputOptions = "Opcions de PDF a CBR"
cbrDpi = "DPI per al renderitzat d'imatges"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "Opcions d'eBook a PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "Aplica les imatges"
name = "Imatge"
placeholder = "Puja una imatge"
label = "Fitxer d'imatge"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Configura la imatge"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI pro vykreslení obrázků"
cbrOptions = "CBR Options"
cbrOutputOptions = "PDF to CBR Options"
cbrDpi = "DPI for image rendering"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "eBook to PDF Options"
@@ -1396,6 +1400,7 @@ applySignatures = "Použít obrázky"
name = "Obrázek"
placeholder = "Nahrajte obrázek"
label = "Soubor obrázku"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Nastavit obrázek"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI for billedgengivelse"
cbrOptions = "CBR-indstillinger"
cbrOutputOptions = "PDF til CBR-indstillinger"
cbrDpi = "DPI for billedgengivelse"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "e-bog til PDF-indstillinger"
@@ -1396,6 +1400,7 @@ applySignatures = "Anvend billeder"
name = "Billede"
placeholder = "Upload et billede"
label = "Billedfil"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Konfigurer billede"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI für Bildrendering"
cbrOptions = "CBR-Optionen"
cbrOutputOptions = "Optionen: PDF zu CBR"
cbrDpi = "DPI für Bildrendering"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "Optionen: E-Book zu PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "Bilder anwenden"
name = "Bild"
placeholder = "Ein Bild hochladen"
label = "Bilddatei"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Bild konfigurieren"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI για απόδοση εικόνας"
cbrOptions = "Επιλογές CBR"
cbrOutputOptions = "Επιλογές PDF σε CBR"
cbrDpi = "DPI για απόδοση εικόνων"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "Επιλογές eBook σε PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "Εφαρμογή εικόνων"
name = "Εικόνα"
placeholder = "Ανεβάστε μια εικόνα"
label = "Αρχείο εικόνας"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Ρύθμιση εικόνας"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI for image rendering"
cbrOptions = "CBR Options"
cbrOutputOptions = "PDF to CBR Options"
cbrDpi = "DPI for image rendering"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "eBook to PDF Options"
@@ -1396,6 +1400,7 @@ applySignatures = "Apply Images"
name = "Image"
placeholder = "Upload an image"
label = "Image file"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Configure Image"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI para renderizado de imágenes"
cbrOptions = "Opciones de CBR"
cbrOutputOptions = "Opciones de PDF a CBR"
cbrDpi = "DPI para el renderizado de imágenes"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "Opciones de eBook a PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "Aplicar imágenes"
name = "Imagen"
placeholder = "Suba una imagen"
label = "Archivo de imagen"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Configurar imagen"
@@ -1295,6 +1295,10 @@ cbzDpi = "Irudien errendatzeko DPI"
cbrOptions = "CBR aukerak"
cbrOutputOptions = "PDFtik CBRrako aukerak"
cbrDpi = "Irudien errendatzeko DPIa"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "eBooketik PDFra aukerak"
@@ -1396,6 +1400,7 @@ applySignatures = "Aplikatu irudiak"
name = "Irudia"
placeholder = "Igo irudi bat"
label = "Irudi fitxategia"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Irudia konfiguratu"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI برای رندر تصویر"
cbrOptions = "گزینه‌های CBR"
cbrOutputOptions = "گزینه‌های PDF به CBR"
cbrDpi = "DPI برای رندر تصویر"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "گزینه‌های eBook به PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "اعمال تصاویر"
name = "تصویر"
placeholder = "بارگذاری یک تصویر"
label = "فایل تصویر"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "پیکربندی تصویر"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI pour le rendu des images"
cbrOptions = "Options CBR"
cbrOutputOptions = "Options PDF vers CBR"
cbrDpi = "DPI pour le rendu des images"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "Options eBook vers PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "Appliquer les images"
name = "Image"
placeholder = "Téléverser une image"
label = "Fichier image"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Configurer l’image"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI le haghaidh rindreáil íomhá"
cbrOptions = "CRoghanna BR"
cbrOutputOptions = "Roghanna PDF go CBR"
cbrDpi = "DPI le haghaidh rindreáil íomhá"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "Roghanna ríomhleabhar go PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "Cuir Íomhánna i bhFeidhm"
name = "Íomhá"
placeholder = "Uaslódáil íomhá"
label = "Comhad íomhá"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Cumraigh Íomhá"
@@ -1295,6 +1295,10 @@ cbzDpi = "इमेज रेंडरिंग के लिए DPI"
cbrOptions = "CBR विकल्प"
cbrOutputOptions = "PDF से CBR विकल्प"
cbrDpi = "छवि रेंडरिंग के लिए DPI"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "eBook से PDF विकल्प"
@@ -1396,6 +1400,7 @@ applySignatures = "इमेज लागू करें"
name = "इमेज"
placeholder = "एक इमेज अपलोड करें"
label = "इमेज फ़ाइल"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "इमेज कॉन्फ़िगर करें"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI za renderiranje slike"
cbrOptions = "CBR opcije"
cbrOutputOptions = "Opcije PDF u CBR"
cbrDpi = "DPI za renderiranje slike"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "Opcije eBook u PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "Primijeni slike"
name = "Slika"
placeholder = "Učitaj sliku"
label = "Datoteka slike"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Konfiguriraj sliku"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI a képrendereléshez"
cbrOptions = "CBR beállítások"
cbrOutputOptions = "PDF → CBR beállítások"
cbrDpi = "DPI a képrendereléshez"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "E-könyv → PDF beállítások"
@@ -1396,6 +1400,7 @@ applySignatures = "Képek alkalmazása"
name = "Kép"
placeholder = "Töltsön fel egy képet"
label = "Képfájl"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Kép beállítása"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI untuk perenderan gambar"
cbrOptions = "Opsi CBR"
cbrOutputOptions = "Opsi PDF ke CBR"
cbrDpi = "DPI untuk perenderan gambar"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "Opsi eBook ke PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "Terapkan Gambar"
name = "Gambar"
placeholder = "Unggah gambar"
label = "File gambar"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Konfigurasi Gambar"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI per il rendering delle immagini"
cbrOptions = "Opzioni CBR"
cbrOutputOptions = "Opzioni da PDF a CBR"
cbrDpi = "DPI per il rendering delle immagini"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "Opzioni da eBook a PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "Applica immagini"
name = "Immagine"
placeholder = "Carica un'immagine"
label = "File immagine"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Configura immagine"
@@ -1295,6 +1295,10 @@ cbzDpi = "画像レンダリングの DPI"
cbrOptions = "CBR オプション"
cbrOutputOptions = "PDF から CBR へのオプション"
cbrDpi = "画像レンダリング用 DPI"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "eBook から PDF へのオプション"
@@ -1396,6 +1400,7 @@ applySignatures = "画像を適用"
name = "画像"
placeholder = "画像をアップロード"
label = "画像ファイル"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "画像を設定"
@@ -1295,6 +1295,10 @@ cbzDpi = "이미지 렌더링용 DPI"
cbrOptions = "CBR 옵션"
cbrOutputOptions = "PDF에서 CBR로 옵션"
cbrDpi = "이미지 렌더링용 DPI"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "eBook에서 PDF로 옵션"
@@ -1396,6 +1400,7 @@ applySignatures = "이미지 적용"
name = "이미지"
placeholder = "이미지 업로드"
label = "이미지 파일"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "이미지 구성"
@@ -1295,6 +1295,10 @@ cbzDpi = "ഇമേജ് റെൻഡറിംഗിനുള്ള DPI"
cbrOptions = "CBR ഓപ്ഷനുകൾ"
cbrOutputOptions = "PDF-നെ CBR ആക്കാനുള്ള ഓപ്ഷനുകൾ"
cbrDpi = "ഇമേജ് റൻഡറിംഗിനുള്ള DPI"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "eBook-നെ PDF ആക്കാനുള്ള ഓപ്ഷനുകൾ"
@@ -1396,6 +1400,7 @@ applySignatures = "ചിത്രങ്ങൾ പ്രയോഗിക്കു
name = "ചിത്രം"
placeholder = "ഒരു ചിത്രം അപ്‌ലോഡ് ചെയ്യുക"
label = "ചിത്ര ഫയൽ"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "ചിത്രം ക്രമീകരിക്കുക"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI voor weergave van afbeeldingen"
cbrOptions = "CBR-opties"
cbrOutputOptions = "Opties voor PDF naar CBR"
cbrDpi = "DPI voor afbeeldingsrendering"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "Opties voor eBook naar PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "Afbeeldingen toepassen"
name = "Afbeelding"
placeholder = "Upload een afbeelding"
label = "Afbeeldingsbestand"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Afbeelding configureren"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI for bildegjengivelse"
cbrOptions = "CBR-alternativer"
cbrOutputOptions = "Alternativer for PDF til CBR"
cbrDpi = "DPI for bildegjengivelse"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "Alternativer for eBook til PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "Bruk bilder"
name = "Bilde"
placeholder = "Last opp et bilde"
label = "Bildefil"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Konfigurer bilde"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI renderowania obrazu"
cbrOptions = "Opcje CBR"
cbrOutputOptions = "Opcje konwersji PDF do CBR"
cbrDpi = "DPI renderowania obrazu"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "Opcje konwersji eBook do PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "Zastosuj obrazy"
name = "Obraz"
placeholder = "Prześlij obraz"
label = "Plik obrazu"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Skonfiguruj obraz"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI para renderização de imagem"
cbrOptions = "Opções de CBR"
cbrOutputOptions = "Opções de PDF para CBR"
cbrDpi = "DPI para renderização de imagem"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "Opções de eBook para PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "Aplicar imagens"
name = "Imagem"
placeholder = "Enviar uma imagem"
label = "Arquivo de imagem"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Configurar imagem"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI para renderização de imagem"
cbrOptions = "Opções de CBR"
cbrOutputOptions = "Opções de PDF para CBR"
cbrDpi = "DPI para renderização de imagem"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "Opções de eBook para PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "Aplicar imagens"
name = "Imagem"
placeholder = "Carregar uma imagem"
label = "Ficheiro de imagem"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Configurar imagem"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI pentru randarea imaginilor"
cbrOptions = "Opțiuni CBR"
cbrOutputOptions = "Opțiuni PDF către CBR"
cbrDpi = "DPI pentru randarea imaginilor"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "Opțiuni eBook către PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "Aplică imagini"
name = "Imagine"
placeholder = "Încarcă o imagine"
label = "Fișier imagine"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Configurează imaginea"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI для отрисовки изображений"
cbrOptions = "Параметры CBR"
cbrOutputOptions = "Параметры PDF в CBR"
cbrDpi = "DPI для отрисовки изображений"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "Параметры eBook в PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "Применить изображения"
name = "Изображение"
placeholder = "Загрузите изображение"
label = "Файл изображения"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Настроить изображение"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI pre vykresľovanie obrázkov"
cbrOptions = "Možnosti CBR"
cbrOutputOptions = "Možnosti PDF na CBR"
cbrDpi = "DPI pre vykresľovanie obrázkov"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "Možnosti eBook na PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "Použiť obrázky"
name = "Obrázok"
placeholder = "Nahrajte obrázok"
label = "Súbor obrázka"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Nastaviť obrázok"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI za upodabljanje slik"
cbrOptions = "Možnosti CBR"
cbrOutputOptions = "Možnosti PDF v CBR"
cbrDpi = "DPI za upodabljanje slik"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "Možnosti eBook v PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "Uporabi slike"
name = "Slika"
placeholder = "Naložite sliko"
label = "Slikovna datoteka"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Nastavi sliko"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI za renderovanje slike"
cbrOptions = "CBR opcije"
cbrOutputOptions = "Opcije za PDF u CBR"
cbrDpi = "DPI za renderovanje slike"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "Opcije za eBook u PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "Primeni slike"
name = "Slika"
placeholder = "Otpremite sliku"
label = "Datoteka slike"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Podesi sliku"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI för bildrendering"
cbrOptions = "CBR-alternativ"
cbrOutputOptions = "Alternativ för PDF till CBR"
cbrDpi = "DPI för bildrendering"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "Alternativ för e-bok till PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "Använd bilder"
name = "Bild"
placeholder = "Ladda upp en bild"
label = "Bildfil"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Konfigurera bild"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI สำหรับการเรนเดอร์ภาพ"
cbrOptions = "ตัวเลือก CBR"
cbrOutputOptions = "ตัวเลือก PDF เป็น CBR"
cbrDpi = "DPI สำหรับการเรนเดอร์ภาพ"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "ตัวเลือก eBook เป็น PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "ใช้รูปภาพ"
name = "รูปภาพ"
placeholder = "อัปโหลดรูปภาพ"
label = "ไฟล์รูปภาพ"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "ตั้งค่ารูปภาพ"
@@ -1295,6 +1295,10 @@ cbzDpi = "Görüntü oluşturma için DPI"
cbrOptions = "CBR Seçenekleri"
cbrOutputOptions = "PDF'den CBR'ye Dönüştürme Seçenekleri"
cbrDpi = "Görüntü oluşturma için DPI"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "eBook'tan PDF'ye Dönüştürme Seçenekleri"
@@ -1396,6 +1400,7 @@ applySignatures = "Resimleri Uygula"
name = "Resim"
placeholder = "Bir resim yükleyin"
label = "Resim dosyası"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Resmi Yapılandır"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI для рендерингу зображень"
cbrOptions = "Параметри CBR"
cbrOutputOptions = "Параметри перетворення PDF у CBR"
cbrDpi = "DPI для рендерингу зображень"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "Параметри перетворення електронної книги у PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "Застосувати зображення"
name = "Зображення"
placeholder = "Завантажте зображення"
label = "Файл зображення"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Налаштувати зображення"
@@ -1295,6 +1295,10 @@ cbzDpi = "DPI cho kết xuất ảnh"
cbrOptions = "Tùy chọn CBR"
cbrOutputOptions = "Tùy chọn PDF sang CBR"
cbrDpi = "DPI cho kết xuất hình ảnh"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "Tùy chọn eBook sang PDF"
@@ -1396,6 +1400,7 @@ applySignatures = "Áp dụng ảnh"
name = "Ảnh"
placeholder = "Tải lên một ảnh"
label = "Tệp ảnh"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "Cấu hình ảnh"
@@ -1295,6 +1295,10 @@ cbzDpi = "图像渲染的 DPI"
cbrOptions = "CBR 选项"
cbrOutputOptions = "PDF 转 CBR 选项"
cbrDpi = "图像渲染的 DPI"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "电子书转 PDF 选项"
@@ -1396,6 +1400,7 @@ applySignatures = "应用图像"
name = "图像"
placeholder = "上传图像"
label = "图像文件"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "配置图像"
@@ -1295,6 +1295,10 @@ cbzDpi = "图像渲染的 DPI"
cbrOptions = "CBR 选项"
cbrOutputOptions = "PDF 转 CBR 选项"
cbrDpi = "用于图像渲染的 DPI"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "电子书转 PDF 选项"
@@ -1396,6 +1400,7 @@ applySignatures = "应用图片"
name = "图片"
placeholder = "上传图片"
label = "图片文件"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "配置图片"
@@ -1295,6 +1295,10 @@ cbzDpi = "影像轉繪的 DPI"
cbrOptions = "CBR 選項"
cbrOutputOptions = "PDF 轉 CBR 選項"
cbrDpi = "影像渲染的 DPI"
svgPdfOptions = "SVG to PDF Options"
combineSvgs = "Combine SVGs into single PDF"
combineSvgsDescription = "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG"
svgVectorNote = "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size."
[convert.ebookOptions]
ebookOptions = "電子書轉 PDF 選項"
@@ -1396,6 +1400,7 @@ applySignatures = "套用圖片"
name = "圖片"
placeholder = "上傳一張圖片"
label = "圖片檔"
hint = "Supports PNG, JPEG, GIF, BMP, TIFF, and SVG files. SVG files will be converted to PNG for embedding."
[addImage.steps]
configure = "設定圖片"
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"productName": "Stirling-PDF",
"version": "2.2.1",
"version": "2.3.0",
"identifier": "stirling.pdf.dev",
"build": {
"frontendDist": "../dist",
@@ -77,15 +77,26 @@ export const ImageUploader: React.FC<ImageUploaderProps> = ({
setCurrentFile(file);
onImageChange(file);
const originalDataUrl = await new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => resolve(e.target?.result as string);
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(file);
});
let dataUrlToProcess: string;
// Check if file is SVG
const isSvg = file.type === 'image/svg+xml' || file.name.toLowerCase().endsWith('.svg');
if (isSvg) {
// For SVG, convert to PNG so it can be embedded in PDF
dataUrlToProcess = await convertSvgToPng(file);
} else {
// For other images, read as data URL directly
dataUrlToProcess = await new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => resolve(e.target?.result as string);
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(file);
});
}
setOriginalImageData(originalDataUrl);
await processImage(file, removeBackground);
setOriginalImageData(dataUrlToProcess);
await processImage(dataUrlToProcess, removeBackground);
} catch (error) {
console.error('Error processing image file:', error);
}
@@ -98,6 +109,115 @@ export const ImageUploader: React.FC<ImageUploaderProps> = ({
}
};
// Helper function to convert SVG to PNG
const convertSvgToPng = async (file: File): Promise<string> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = async (e) => {
try {
const svgText = e.target?.result as string;
// Parse SVG to get dimensions
const parser = new DOMParser();
const svgDoc = parser.parseFromString(svgText, 'image/svg+xml');
const svgElement = svgDoc.documentElement;
// Get SVG dimensions
let width = 800; // Default width
let height = 600; // Default height
if (svgElement.hasAttribute('width') && svgElement.hasAttribute('height')) {
width = parseFloat(svgElement.getAttribute('width') || '800');
height = parseFloat(svgElement.getAttribute('height') || '600');
} else if (svgElement.hasAttribute('viewBox')) {
const viewBox = svgElement.getAttribute('viewBox')?.split(/\s+|,/);
if (viewBox && viewBox.length === 4) {
width = parseFloat(viewBox[2]);
height = parseFloat(viewBox[3]);
}
}
// Ensure reasonable dimensions
if (width === 0 || height === 0 || !isFinite(width) || !isFinite(height)) {
width = 800;
height = 600;
}
// Scale large SVGs down
const maxDimension = 2048;
if (width > maxDimension || height > maxDimension) {
const scale = Math.min(maxDimension / width, maxDimension / height);
width *= scale;
height *= scale;
}
console.log('Converting SVG to PNG:', { width, height });
// Create an image element to render SVG
const img = new Image();
const blob = new Blob([svgText], { type: 'image/svg+xml;charset=utf-8' });
const url = URL.createObjectURL(blob);
img.onload = () => {
try {
// Use computed dimensions or image natural dimensions
const finalWidth = img.naturalWidth || img.width || width;
const finalHeight = img.naturalHeight || img.height || height;
console.log('Image loaded:', { naturalWidth: img.naturalWidth, naturalHeight: img.naturalHeight, finalWidth, finalHeight });
// Create canvas to convert to PNG
const canvas = document.createElement('canvas');
canvas.width = finalWidth;
canvas.height = finalHeight;
const ctx = canvas.getContext('2d');
if (!ctx) {
URL.revokeObjectURL(url);
reject(new Error('Failed to get canvas context'));
return;
}
// Fill with white background (optional, for transparency support)
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, finalWidth, finalHeight);
// Draw SVG
ctx.drawImage(img, 0, 0, finalWidth, finalHeight);
URL.revokeObjectURL(url);
// Convert canvas to PNG data URL
const pngDataUrl = canvas.toDataURL('image/png');
console.log('SVG converted to PNG successfully');
resolve(pngDataUrl);
} catch (error) {
URL.revokeObjectURL(url);
console.error('Error during canvas rendering:', error);
reject(error);
}
};
img.onerror = (error) => {
URL.revokeObjectURL(url);
console.error('Failed to load SVG image:', error);
reject(new Error('Failed to load SVG image'));
};
img.src = url;
} catch (error) {
console.error('Error parsing SVG:', error);
reject(error);
}
};
reader.onerror = () => {
console.error('Error reading file:', reader.error);
reject(reader.error);
};
reader.readAsText(file);
});
};
const handleBackgroundRemovalChange = async (checked: boolean) => {
if (isProcessing) return; // Prevent race conditions
setRemoveBackground(checked);
@@ -59,7 +59,7 @@ export const ImageTool: React.FC<ImageToolProps> = ({
disabled={disabled}
label="Upload Image"
placeholder="Select image file"
hint="Upload a PNG, JPG, or other image file to place on the PDF"
hint="Upload a PNG, JPG, SVG, or other image file to place on the PDF. SVG files will be converted to PNG for compatibility."
/>
</Stack>
</BaseAnnotationTool>
@@ -41,13 +41,16 @@ export default function ToolConfigurationModal({ opened, tool, onSave, onCancel,
// Initialize parameters from tool (which should contain defaults from registry)
useEffect(() => {
const toolConfig = toolRegistry[tool.operation as ToolId]?.operationConfig;
const defaultParams = toolConfig?.defaultParameters || {};
if (tool.parameters) {
setParameters(tool.parameters);
setParameters({ ...defaultParams, ...tool.parameters });
} else {
// Fallback to empty parameters if none provided
setParameters({});
// Fallback to default parameters if none provided
setParameters({ ...defaultParams });
}
}, [tool.parameters, tool.operation]);
}, [tool.parameters, tool.operation, toolRegistry]);
// Render the settings component
const renderToolSettings = () => {
@@ -0,0 +1,41 @@
import { Stack, Text, Switch } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { ConvertParameters } from "@app/hooks/tools/convert/useConvertParameters";
interface ConvertFromSvgSettingsProps {
parameters: ConvertParameters;
onParameterChange: <K extends keyof ConvertParameters>(key: K, value: ConvertParameters[K]) => void;
disabled?: boolean;
}
const ConvertFromSvgSettings = ({
parameters,
onParameterChange,
disabled = false
}: ConvertFromSvgSettingsProps) => {
const { t } = useTranslation();
return (
<Stack gap="sm" data-testid="svg-pdf-options-section">
<Text size="sm" fw={500}>{t("convert.svgPdfOptions", "SVG to PDF Options")}:</Text>
<Switch
data-testid="combine-svgs-switch"
label={t("convert.combineSvgs", "Combine SVGs into single PDF")}
description={t("convert.combineSvgsDescription", "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG")}
checked={parameters.imageOptions.combineImages}
onChange={(event) => onParameterChange('imageOptions', {
...parameters.imageOptions,
combineImages: event.currentTarget.checked
})}
disabled={disabled}
/>
<Text size="xs" c="dimmed" mt="xs">
{t("convert.svgVectorNote", "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size.")}
</Text>
</Stack>
);
};
export default ConvertFromSvgSettings;
@@ -20,6 +20,7 @@ import ConvertToPdfaSettings from "@app/components/tools/convert/ConvertToPdfaSe
import ConvertFromCbrSettings from "@app/components/tools/convert/ConvertFromCbrSettings";
import ConvertToCbrSettings from "@app/components/tools/convert/ConvertToCbrSettings";
import ConvertFromEbookSettings from "@app/components/tools/convert/ConvertFromEbookSettings";
import ConvertFromSvgSettings from "@app/components/tools/convert/ConvertFromSvgSettings";
import ConvertToEpubSettings from "@app/components/tools/convert/ConvertToEpubSettings";
import { ConvertParameters } from "@app/hooks/tools/convert/useConvertParameters";
import {
@@ -331,6 +332,18 @@ const ConvertSettings = ({
</>
) : null}
{/* SVG to PDF options */}
{parameters.fromExtension === 'svg' && parameters.toExtension === 'pdf' && (
<>
<Divider />
<ConvertFromSvgSettings
parameters={parameters}
onParameterChange={onParameterChange}
disabled={disabled}
/>
</>
)}
{/* Web to PDF options */}
{((isWebFormat(parameters.fromExtension) && parameters.toExtension === 'pdf') ||
(parameters.isSmartDetection && parameters.smartDetectionType === 'web')) ? (
@@ -21,6 +21,7 @@ export const CONVERSION_ENDPOINTS = {
'office-pdf': '/api/v1/convert/file/pdf',
'pdf-image': '/api/v1/convert/pdf/img',
'image-pdf': '/api/v1/convert/img/pdf',
'svg-pdf': '/api/v1/convert/svg/pdf',
'cbz-pdf': '/api/v1/convert/cbz/pdf',
'pdf-cbz': '/api/v1/convert/pdf/cbz',
'pdf-office-word': '/api/v1/convert/pdf/word',
@@ -46,6 +47,7 @@ export const ENDPOINT_NAMES = {
'office-pdf': 'file-to-pdf',
'pdf-image': 'pdf-to-img',
'image-pdf': 'img-to-pdf',
'svg-pdf': 'svg-to-pdf',
'cbz-pdf': 'cbz-to-pdf',
'pdf-cbz': 'pdf-to-cbz',
'pdf-office-word': 'pdf-to-word',
@@ -171,7 +173,8 @@ export const EXTENSION_TO_ENDPOINT: Record<string, Record<string, string>> = {
'xlsx': { 'pdf': 'file-to-pdf' }, 'xls': { 'pdf': 'file-to-pdf' }, 'ods': { 'pdf': 'file-to-pdf' },
'pptx': { 'pdf': 'file-to-pdf' }, 'ppt': { 'pdf': 'file-to-pdf' }, 'odp': { 'pdf': 'file-to-pdf' },
'jpg': { 'pdf': 'img-to-pdf' }, 'jpeg': { 'pdf': 'img-to-pdf' }, 'png': { 'pdf': 'img-to-pdf' },
'gif': { 'pdf': 'img-to-pdf' }, 'bmp': { 'pdf': 'img-to-pdf' }, 'tiff': { 'pdf': 'img-to-pdf' }, 'webp': { 'pdf': 'img-to-pdf' }, 'svg': { 'pdf': 'img-to-pdf' },
'gif': { 'pdf': 'img-to-pdf' }, 'bmp': { 'pdf': 'img-to-pdf' }, 'tiff': { 'pdf': 'img-to-pdf' }, 'webp': { 'pdf': 'img-to-pdf' },
'svg': { 'pdf': 'svg-to-pdf' },
'html': { 'pdf': 'html-to-pdf' },
'zip': { 'pdf': 'html-to-pdf' },
'md': { 'pdf': 'markdown-to-pdf' },
@@ -18,7 +18,7 @@ export const buildAddWatermarkFormData = (parameters: AddWatermarkParameters, fi
formData.append("watermarkImage", parameters.watermarkImage);
}
// Required parameters with correct formatting
// Required parameters with correct formatting (defaults merged in automationExecutor)
formData.append("fontSize", parameters.fontSize.toString());
formData.append("rotation", parameters.rotation.toString());
formData.append("opacity", (parameters.opacity / 100).toString()); // Convert percentage to decimal
@@ -26,9 +26,9 @@ export const buildAddWatermarkFormData = (parameters: AddWatermarkParameters, fi
formData.append("heightSpacer", parameters.heightSpacer.toString());
// Backend-expected parameters from user input
formData.append("alphabet", parameters.alphabet);
formData.append("customColor", parameters.customColor);
formData.append("convertPDFToImage", parameters.convertPDFToImage.toString());
formData.append("alphabet", parameters.alphabet || "");
formData.append("customColor", parameters.customColor || "");
formData.append("convertPDFToImage", (parameters.convertPDFToImage ?? false).toString());
return formData;
};
@@ -38,7 +38,7 @@ export function useAutomateOperation() {
console.log(`✅ Automation completed, returning ${finalResults.length} files`);
return {
files: finalResults,
consumedAllInputs: false,
consumedAllInputs: true,
};
}, [toolRegistry]);
@@ -46,5 +46,6 @@ export function useAutomateOperation() {
toolType: ToolType.custom,
operationType: 'automate',
customProcessor,
consumesAllInputs: true,
});
}
@@ -52,7 +52,7 @@ export function useAutomationForm({ mode, existingAutomation, toolRegistry }: Us
operation: operation,
name: getToolName(operation),
configured: isConfigured,
parameters: typeof op === 'object' ? op.parameters || {} : {}
parameters: typeof op === 'object' ? { ...getToolDefaultParameters(operation), ...(op.parameters || {}) } : getToolDefaultParameters(operation)
};
});
@@ -68,7 +68,7 @@ export function useAutomationForm({ mode, existingAutomation, toolRegistry }: Us
}));
setSelectedTools(defaultTools);
}
}, [mode, existingAutomation, t, getToolName]);
}, [mode, existingAutomation, t, getToolName, getToolDefaultParameters]);
const addTool = (operation: string) => {
const toolEntry = toolRegistry[operation as ToolId];
@@ -3,11 +3,12 @@ import { ToolType, useToolOperation } from '@app/hooks/tools/shared/useToolOpera
import { createStandardErrorHandler } from '@app/utils/toolErrorHandler';
import { ChangePermissionsParameters, defaultParameters } from '@app/hooks/tools/changePermissions/useChangePermissionsParameters';
export const getFormData = ((parameters: ChangePermissionsParameters) =>
Object.entries(parameters).map(([key, value]) =>
[key, value.toString()]
) as string[][]
);
export const getFormData = ((parameters: ChangePermissionsParameters) => {
if (!parameters) return [];
return Object.entries(parameters).map(([key, value]) =>
[key, (value ?? false).toString()]
) as string[][];
});
// Static function that can be used by both the hook and automation executor
export const buildChangePermissionsFormData = (parameters: ChangePermissionsParameters, file: File): FormData => {
@@ -18,7 +18,7 @@ export const buildCompressFormData = (parameters: CompressParameters, file: File
}
}
formData.append("grayscale", parameters.grayscale.toString());
formData.append("grayscale", (parameters.grayscale ?? false).toString());
formData.append("lineArt", parameters.lineArt.toString());
formData.append("linearize", parameters.linearize.toString());
if (parameters.lineArt) {
@@ -15,6 +15,8 @@ export const shouldProcessFilesSeparately = (
// Image to PDF with combineImages = false
((isImageFormat(parameters.fromExtension) || parameters.fromExtension === 'image') &&
parameters.toExtension === 'pdf' && !parameters.imageOptions.combineImages) ||
// SVG to PDF with combineIntoSinglePdf = false
(parameters.fromExtension === 'svg' && parameters.toExtension === 'pdf' && !parameters.imageOptions.combineImages) ||
// PDF to image conversions (each PDF should generate its own image file)
(parameters.fromExtension === 'pdf' && isImageFormat(parameters.toExtension)) ||
// PDF to PDF/A conversions (each PDF should be processed separately)
@@ -66,6 +68,8 @@ export const buildConvertFormData = (parameters: ConvertParameters, selectedFile
formData.append("fitOption", imageOptions.fitOption);
formData.append("colorType", imageOptions.colorType);
formData.append("autoRotate", imageOptions.autoRotate.toString());
} else if (fromExtension === 'svg' && toExtension === 'pdf') {
formData.append("combineIntoSinglePdf", imageOptions.combineImages.toString());
} else if ((fromExtension === 'html' || fromExtension === 'zip') && toExtension === 'pdf') {
formData.append("zoom", htmlOptions.zoomLevel.toString());
} else if ((fromExtension === 'eml' || fromExtension === 'msg') && toExtension === 'pdf') {
@@ -1,7 +1,7 @@
import { useTranslation } from 'react-i18next';
import { useToolOperation, ToolOperationConfig, ToolType } from '@app/hooks/tools/shared/useToolOperation';
import { createStandardErrorHandler } from '@app/utils/toolErrorHandler';
import { MergeParameters } from '@app/hooks/tools/merge/useMergeParameters';
import { MergeParameters, defaultParameters } from '@app/hooks/tools/merge/useMergeParameters';
const buildFormData = (parameters: MergeParameters, files: File[]): FormData => {
const formData = new FormData();
@@ -13,8 +13,8 @@ const buildFormData = (parameters: MergeParameters, files: File[]): FormData =>
const clientIds: string[] = files.map((f: any) => String((f as any).fileId || f.name));
formData.append('clientFileIds', JSON.stringify(clientIds));
formData.append("sortType", "orderProvided"); // Always use orderProvided since UI handles sorting
formData.append("removeCertSign", parameters.removeDigitalSignature.toString());
formData.append("generateToc", parameters.generateTableOfContents.toString());
formData.append("removeCertSign", (parameters.removeDigitalSignature ?? false).toString());
formData.append("generateToc", (parameters.generateTableOfContents ?? false).toString());
return formData;
};
@@ -26,6 +26,7 @@ export const mergeOperationConfig: ToolOperationConfig<MergeParameters> = {
operationType: 'merge',
endpoint: '/api/v1/general/merge-pdfs',
filePrefix: 'merged_',
defaultParameters,
};
export const useMergeOperation = () => {
@@ -44,11 +44,13 @@ export const buildOCRFormData = (parameters: OCRParameters, file: File): FormDat
parameters.languages.forEach((lang) => formData.append('languages', lang));
formData.append('ocrType', parameters.ocrType);
formData.append('ocrRenderType', parameters.ocrRenderType);
formData.append('sidecar', parameters.additionalOptions.includes('sidecar').toString());
formData.append('deskew', parameters.additionalOptions.includes('deskew').toString());
formData.append('clean', parameters.additionalOptions.includes('clean').toString());
formData.append('cleanFinal', parameters.additionalOptions.includes('cleanFinal').toString());
formData.append('removeImagesAfter', parameters.additionalOptions.includes('removeImagesAfter').toString());
const options = parameters.additionalOptions || [];
formData.append('sidecar', options.includes('sidecar').toString());
formData.append('deskew', options.includes('deskew').toString());
formData.append('clean', options.includes('clean').toString());
formData.append('cleanFinal', options.includes('cleanFinal').toString());
formData.append('removeImagesAfter', options.includes('removeImagesAfter').toString());
return formData;
};
@@ -9,12 +9,12 @@ export const buildSanitizeFormData = (parameters: SanitizeParameters, file: File
formData.append('fileInput', file);
// Add parameters
formData.append('removeJavaScript', parameters.removeJavaScript.toString());
formData.append('removeEmbeddedFiles', parameters.removeEmbeddedFiles.toString());
formData.append('removeXMPMetadata', parameters.removeXMPMetadata.toString());
formData.append('removeMetadata', parameters.removeMetadata.toString());
formData.append('removeLinks', parameters.removeLinks.toString());
formData.append('removeFonts', parameters.removeFonts.toString());
formData.append('removeJavaScript', (parameters.removeJavaScript ?? false).toString());
formData.append('removeEmbeddedFiles', (parameters.removeEmbeddedFiles ?? false).toString());
formData.append('removeXMPMetadata', (parameters.removeXMPMetadata ?? false).toString());
formData.append('removeMetadata', (parameters.removeMetadata ?? false).toString());
formData.append('removeLinks', (parameters.removeLinks ?? false).toString());
formData.append('removeFonts', (parameters.removeFonts ?? false).toString());
return formData;
};
@@ -71,6 +71,13 @@ interface BaseToolOperationConfig<TParams> {
/** Default parameter values for automation */
defaultParameters?: TParams;
/**
* For custom tools: if true, success implies all input files were successfully processed.
* Use this for tools like Automate or Merge where Many-to-One relationships exist
* and exact input-output mapping is difficult.
*/
consumesAllInputs?: boolean;
}
export interface SingleFileToolOperationConfig<TParams> extends BaseToolOperationConfig<TParams> {
@@ -19,7 +19,7 @@ export const buildSplitFormData = (parameters: SplitParameters, file: File): For
case SPLIT_METHODS.BY_SECTIONS:
formData.append("horizontalDivisions", parameters.hDiv);
formData.append("verticalDivisions", parameters.vDiv);
formData.append("merge", parameters.merge.toString());
formData.append("merge", (parameters.merge ?? false).toString());
formData.append("splitMode", parameters.splitMode || 'SPLIT_ALL');
if (parameters.splitMode === 'CUSTOM' && parameters.customPages) {
formData.append("pageNumbers", parameters.customPages);
@@ -39,11 +39,11 @@ export const buildSplitFormData = (parameters: SplitParameters, file: File): For
break;
case SPLIT_METHODS.BY_CHAPTERS:
formData.append("bookmarkLevel", parameters.bookmarkLevel);
formData.append("includeMetadata", parameters.includeMetadata.toString());
formData.append("allowDuplicates", parameters.allowDuplicates.toString());
formData.append("includeMetadata", (parameters.includeMetadata ?? false).toString());
formData.append("allowDuplicates", (parameters.allowDuplicates ?? false).toString());
break;
case SPLIT_METHODS.BY_PAGE_DIVIDER:
formData.append("duplexMode", parameters.duplexMode.toString());
formData.append("duplexMode", (parameters.duplexMode ?? false).toString());
break;
default:
throw new Error(`Unknown split method: ${parameters.method}`);
@@ -38,7 +38,7 @@ const FREE_LICENSE_INFO: LicenseInfo = {
const BASE_NO_LOGIN_CONFIG: AppConfig = {
enableAnalytics: true,
appVersion: '2.2.1',
appVersion: '2.3.0',
serverCertificateEnabled: false,
enableAlphaFunctionality: false,
serverPort: 8080,
@@ -155,18 +155,21 @@ export const executeToolOperationWithPrefix = async (
throw new Error(`Tool operation not supported: ${operationName}`);
}
// Merge with default parameters to ensure all required fields are present
const mergedParameters = { ...config.defaultParameters, ...parameters };
try {
// Check if tool uses custom processor (like Convert tool)
if (config.customProcessor) {
const result = await config.customProcessor(parameters, files);
const result = await config.customProcessor(mergedParameters, files);
return result.files;
}
// Execute based on tool type
if (config.toolType === ToolType.multiFile) {
return await executeMultiFileOperation(config, parameters, files, filePrefix);
return await executeMultiFileOperation(config, mergedParameters, files, filePrefix);
} else {
return await executeSingleFileOperation(config, parameters, files, filePrefix);
return await executeSingleFileOperation(config, mergedParameters, files, filePrefix);
}
} catch (error: any) {
+12 -8
View File
@@ -1,4 +1,4 @@
import {
import {
CONVERSION_ENDPOINTS,
ENDPOINT_NAMES,
EXTENSION_TO_ENDPOINT,
@@ -11,15 +11,15 @@ import {
*/
export const getEndpointName = (fromExtension: string, toExtension: string): string => {
if (!fromExtension || !toExtension) return '';
let endpointKey = EXTENSION_TO_ENDPOINT[fromExtension]?.[toExtension];
// If no explicit mapping exists and we're converting to PDF,
// If no explicit mapping exists and we're converting to PDF,
// fall back to 'any' which uses file-to-pdf endpoint
if (!endpointKey && toExtension === 'pdf' && fromExtension !== 'any') {
endpointKey = EXTENSION_TO_ENDPOINT['any']?.[toExtension];
}
return endpointKey || '';
};
@@ -29,7 +29,7 @@ export const getEndpointName = (fromExtension: string, toExtension: string): str
export const getEndpointUrl = (fromExtension: string, toExtension: string): string => {
const endpointName = getEndpointName(fromExtension, toExtension);
if (!endpointName) return '';
// Find the endpoint URL from CONVERSION_ENDPOINTS using the endpoint name
for (const [key, endpoint] of Object.entries(CONVERSION_ENDPOINTS)) {
if (ENDPOINT_NAMES[key as keyof typeof ENDPOINT_NAMES] === endpointName) {
@@ -50,7 +50,11 @@ export const isConversionSupported = (fromExtension: string, toExtension: string
* Checks if the given extension is an image format
*/
export const isImageFormat = (extension: string): boolean => {
return ['png', 'jpg', 'jpeg', 'gif', 'tiff', 'bmp', 'webp', 'svg'].includes(extension.toLowerCase());
return ['png', 'jpg', 'jpeg', 'gif', 'tiff', 'bmp', 'webp'].includes(extension.toLowerCase());
};
export const isSvgFormat = (extension: string): boolean => {
return extension.toLowerCase() === 'svg';
};
/**
@@ -99,4 +103,4 @@ export const getAvailableToExtensions = (fromExtension: string): Array<{value: s
return TO_FORMAT_OPTIONS.filter(option =>
supportedExtensions.includes(option.value)
);
};
};
@@ -194,7 +194,6 @@ export async function flattenSignatures(options: SignatureFlatteningOptions): Pr
if (imageDataUrl && typeof imageDataUrl === 'string' && imageDataUrl.startsWith('data:image')) {
try {
// Convert data URL to bytes
const base64Data = imageDataUrl.split(',')[1];
const imageBytes = Uint8Array.from(atob(base64Data), c => c.charCodeAt(0));
@@ -206,6 +205,7 @@ export async function flattenSignatures(options: SignatureFlatteningOptions): Pr
} else if (imageDataUrl.includes('data:image/png')) {
image = await pdfDoc.embedPng(imageBytes);
} else {
// Default to PNG for other formats (including converted SVGs)
image = await pdfDoc.embedPng(imageBytes);
}
@@ -48,7 +48,7 @@ const FREE_LICENSE_INFO: LicenseInfo = {
const BASE_NO_LOGIN_CONFIG: AppConfig = {
enableAnalytics: true,
appVersion: '2.2.1',
appVersion: '2.3.0',
serverCertificateEnabled: false,
enableAlphaFunctionality: false,
enableDesktopInstallSlide: true,
+21
View File
@@ -1,7 +1,28 @@
pluginManagement {
repositories {
var gradlePluginPortalUrl = System.getenv("MAVEN_PUBLIC_URL") ?: ""
if (!gradlePluginPortalUrl.isEmpty()){
maven {
url gradlePluginPortalUrl + "/gradle"
credentials(PasswordCredentials) {
username System.getenv('MAVEN_USER') ?: ""
password System.getenv('MAVEN_PASSWORD') ?: ""
}
authentication {
basic(BasicAuthentication)
}
allowInsecureProtocol true
}
}
gradlePluginPortal()
}
}
plugins {
// Apply the foojay-resolver plugin to allow automatic download of JDKs
id 'org.gradle.toolchains.foojay-resolver-convention' version '1.0.0'
}
rootProject.name = 'Stirling PDF'
include 'stirling-pdf', 'common', 'proprietary'