Compare commits

..
Author SHA1 Message Date
Anthony StirlingandGitHub 8343a6bd94 Configure allowed endpoints in Harden Runner
Added allowed endpoints for Harden Runner step.
2026-01-15 20:03:24 +00:00
89 changed files with 155 additions and 1786 deletions
@@ -153,14 +153,9 @@ jobs:
- name: Set up JDK 21
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
with:
java-version: "21"
java-version: "17"
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
@@ -168,11 +163,8 @@ jobs:
else
export DISABLE_ADDITIONAL_FEATURES=false
fi
./gradlew build
./gradlew clean 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
+3 -45
View File
@@ -68,17 +68,9 @@ 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 build -PnoSpotless
run: ./gradlew clean 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
@@ -143,17 +135,9 @@ 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
@@ -215,17 +199,8 @@ 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 checkLicense
env:
MAVEN_USER: ${{ secrets.MAVEN_USER }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
MAVEN_PUBLIC_URL: ${{ secrets.MAVEN_PUBLIC_URL }}
run: ./gradlew clean checkLicense
- name: FAILED - check the licenses for compatibility
if: failure()
@@ -269,11 +244,6 @@ 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
@@ -299,10 +269,6 @@ 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'
@@ -340,17 +306,9 @@ 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 build
run: ./gradlew clean 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,19 +336,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: Check licenses and generate report
id: license-check
run: |
./gradlew checkLicense generateLicenseReport || echo "LICENSE_CHECK_FAILED=true" >> $GITHUB_ENV
./gradlew clean 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
+8 -22
View File
@@ -50,8 +50,7 @@ jobs:
java-version: "21"
distribution: "temurin"
- name: Setup Gradle
uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
- uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
with:
gradle-version: 8.14
@@ -63,10 +62,6 @@ 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
@@ -123,8 +118,7 @@ jobs:
java-version: "21"
distribution: "temurin"
- name: Setup Gradle
uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
- uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
with:
gradle-version: 8.14
@@ -137,11 +131,8 @@ jobs:
cache-dependency-path: frontend/package-lock.json
- name: Build JAR
run: ./gradlew build ${{ matrix.variant.build_frontend && '-PbuildWithFrontend=true' || '' }} -x spotlessApply -x spotlessCheck -x test -x sonarqube
run: ./gradlew clean 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
@@ -174,7 +165,10 @@ jobs:
uses: step-security/harden-runner@20cf305ff2072d973412fa9b1e3a4f227bda3c76 # v2.14.0
with:
egress-policy: audit
allowed-endpoints: >
one.digicert.com:443
clientauth.one.digicert.com:443
- name: Checkout repository
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
@@ -203,18 +197,13 @@ 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 build -x spotlessApply -x spotlessCheck -x test -x sonarqube
./gradlew clean 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)
@@ -278,9 +267,6 @@ 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
+1 -10
View File
@@ -57,17 +57,8 @@ 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 build
env:
MAVEN_USER: ${{ secrets.MAVEN_USER }}
MAVEN_PASSWORD: ${{ secrets.MAVEN_PASSWORD }}
MAVEN_PUBLIC_URL: ${{ secrets.MAVEN_PUBLIC_URL }}
run: ./gradlew clean build
- name: git add
run: |
+1 -12
View File
@@ -45,8 +45,7 @@ jobs:
java-version: "21"
distribution: "temurin"
- name: Setup Gradle
uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
- uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
with:
gradle-version: 8.14
@@ -57,16 +56,6 @@ 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'
+1 -11
View File
@@ -39,10 +39,7 @@ jobs:
java-version: "21"
distribution: "temurin"
- name: Setup Gradle
uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
with:
gradle-version: 8.14
- uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
- name: Generate Swagger documentation
run: ./gradlew :stirling-pdf:generateOpenApiDocs
@@ -50,19 +47,12 @@ 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,9 +7,6 @@ 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"
+2 -10
View File
@@ -99,19 +99,14 @@ 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 bootJar --no-daemon
./gradlew build -x spotlessApply -x spotlessCheck -x test -x sonarqube
# STIRLING_PDF_DESKTOP_UI=false ./gradlew clean bootJar --no-daemon
./gradlew clean 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)
@@ -175,9 +170,6 @@ 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
+1 -4
View File
@@ -44,11 +44,8 @@ jobs:
gradle-version: 8.14
- name: Build with Gradle
run: ./gradlew build
run: ./gradlew clean 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
@@ -1,280 +0,0 @@
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;
}
}
+5 -3
View File
@@ -2,6 +2,11 @@ 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 {
@@ -86,9 +91,6 @@ 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"
@@ -1,244 +0,0 @@
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,12 +1,7 @@
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;
@@ -19,11 +14,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
@@ -37,63 +32,25 @@ 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. "
+ "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")
"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")
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();
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");
byte[] result =
PdfUtils.overlayImage(
pdfDocumentFactory, pdfBytes, imageBytes, x, y, everyPage);
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,6 +1,9 @@
package stirling.software.SPDF.controller.api.pipeline;
import java.io.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystemException;
import java.nio.file.FileVisitResult;
@@ -21,6 +24,7 @@ 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;
@@ -160,8 +164,7 @@ public class PipelineDirectoryProcessor {
postHogService.captureEvent("pipeline_directory_event", properties);
List<File> filesToProcess = prepareFilesForProcessing(files, processingDir);
try (PipelineResult result =
runPipelineAgainstFiles(filesToProcess, config, dir, processingDir)) {}
runPipelineAgainstFiles(filesToProcess, config, dir, processingDir);
}
}
@@ -300,14 +303,14 @@ public class PipelineDirectoryProcessor {
}
}
private PipelineResult runPipelineAgainstFiles(
private void 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 new PipelineResult();
return;
}
PipelineResult result = processor.runPipelineAgainstFiles(inputFiles, config);
@@ -318,11 +321,9 @@ 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();
}
}
@@ -349,9 +350,8 @@ public class PipelineDirectoryProcessor {
log.info("Created directory: {}", outputPath);
}
Path outputFile = outputPath.resolve(outputFileName);
try (OutputStream os = new FileOutputStream(outputFile.toFile());
InputStream is = resource.getInputStream()) {
is.transferTo(os);
try (OutputStream os = new FileOutputStream(outputFile.toFile())) {
os.write(((ByteArrayResource) resource).getByteArray());
}
log.info("File moved and renamed to {}", outputFile);
}
@@ -15,10 +15,9 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.ByteArrayResource;
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;
@@ -39,8 +38,6 @@ 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
@@ -52,17 +49,13 @@ public class PipelineProcessor {
private final ServletContext servletContext;
private final TempFileManager tempFileManager;
public PipelineProcessor(
ApiDocService apiDocService,
@Autowired(required = false) UserServiceInterface userService,
ServletContext servletContext,
TempFileManager tempFileManager) {
ServletContext servletContext) {
this.apiDocService = apiDocService;
this.userService = userService;
this.servletContext = servletContext;
this.tempFileManager = tempFileManager;
}
public static String removeTrailingNaming(String filename) {
@@ -144,18 +137,14 @@ public class PipelineProcessor {
body.add(entry.getKey(), entry.getValue());
}
}
ResponseEntity<Resource> response = sendWebRequest(url, body);
ResponseEntity<byte[]> 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().contentLength() == 0)) {
|| response.getBody().length == 0)) {
filtersApplied = true;
log.info("Skipping file due to filtering {}", operation);
continue;
@@ -165,7 +154,7 @@ public class PipelineProcessor {
hasErrors = true;
continue;
}
processOutputFiles(operation, response, newOutputFiles, result);
processOutputFiles(operation, response, newOutputFiles);
}
}
if (!hasInputFileType) {
@@ -226,13 +215,10 @@ public class PipelineProcessor {
body.add(entry.getKey(), entry.getValue());
}
}
ResponseEntity<Resource> response = sendWebRequest(url, body);
if (response.getBody() instanceof TempFileResource tempFileResource) {
result.addTempFile(tempFileResource.getTempFile());
}
ResponseEntity<byte[]> response = sendWebRequest(url, body);
// Handle the response
if (HttpStatus.OK.equals(response.getStatusCode())) {
processOutputFiles(operation, response, newOutputFiles, result);
processOutputFiles(operation, response, newOutputFiles);
} else {
// Log error if the response status is not OK
logPrintStream.println(
@@ -281,7 +267,7 @@ public class PipelineProcessor {
return result;
}
/* package */ ResponseEntity<Resource> sendWebRequest(
/* package */ ResponseEntity<byte[]> sendWebRequest(
String url, MultiValueMap<String, Object> body) {
RestTemplate restTemplate = new RestTemplate();
// Set up headers, including API key
@@ -289,37 +275,14 @@ public class PipelineProcessor {
String apiKey = getApiKeyForUser();
headers.add("X-API-KEY", apiKey);
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
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);
}
});
// 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);
}
private List<Resource> processOutputFiles(
String operation,
ResponseEntity<Resource> response,
List<Resource> newOutputFiles,
PipelineResult result)
String operation, ResponseEntity<byte[]> response, List<Resource> newOutputFiles)
throws IOException {
// Define filename
String newFilename;
@@ -335,14 +298,10 @@ 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(), result));
newOutputFiles.addAll(unzip(response.getBody()));
} else {
final Resource tempResource = response.getBody();
if (tempResource instanceof TempFileResource) {
result.addTempFile(((TempFileResource) tempResource).getTempFile());
}
Resource outputResource =
new FileSystemResource(tempResource.getFile()) {
new ByteArrayResource(response.getBody()) {
@Override
public String getFilename() {
@@ -354,7 +313,7 @@ public class PipelineProcessor {
return newOutputFiles;
}
public String extractFilename(ResponseEntity<Resource> response) {
public String extractFilename(ResponseEntity<byte[]> response) {
// Default filename if not found
String filename = "default-filename.ext";
HttpHeaders headers = response.getHeaders();
@@ -389,7 +348,14 @@ public class PipelineProcessor {
// debug statement
log.info("Reading file: {}", path);
if (Files.exists(path)) {
Resource fileResource = new FileSystemResource(file);
Resource fileResource =
new ByteArrayResource(Files.readAllBytes(path)) {
@Override
public String getFilename() {
return file.getName();
}
};
outputFiles.add(fileResource);
} else {
log.info("File not found: {}", path);
@@ -406,11 +372,8 @@ 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 FileSystemResource(tempFile.toFile()) {
new ByteArrayResource(file.getBytes()) {
@Override
public String getFilename() {
@@ -423,8 +386,8 @@ public class PipelineProcessor {
return outputFiles;
}
private boolean isZip(Resource data, String filename) throws IOException {
if (data == null || data.contentLength() < 4) {
private boolean isZip(byte[] data, String filename) {
if (data == null || data.length < 4) {
return false;
}
if (filename != null) {
@@ -435,41 +398,29 @@ public class PipelineProcessor {
}
}
// Check the first four bytes of the data against the standard zip magic number
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;
}
return data[0] == 0x50 && data[1] == 0x4B && data[2] == 0x03 && data[3] == 0x04;
}
private boolean isZip(Resource data) throws IOException {
private boolean isZip(byte[] data) {
return isZip(data, null);
}
private List<Resource> unzip(Resource data, PipelineResult result) throws IOException {
log.info("Unzipping data of length: {}", data.contentLength());
private List<Resource> unzip(byte[] data) throws IOException {
log.info("Unzipping data of length: {}", data.length);
List<Resource> unzippedFiles = new ArrayList<>();
try (InputStream bais = data.getInputStream();
try (ByteArrayInputStream bais = new ByteArrayInputStream(data);
ZipInputStream zis = ZipSecurity.createHardenedInputStream(bais)) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
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);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count;
while ((count = zis.read(buffer)) != -1) {
baos.write(buffer, 0, count);
}
final String filename = entry.getName();
Resource fileResource =
new FileSystemResource(tempFile.getFile()) {
new ByteArrayResource(baos.toByteArray()) {
@Override
public String getFilename() {
@@ -477,9 +428,9 @@ public class PipelineProcessor {
}
};
// If the unzipped file is a zip file, unzip it
if (isZip(fileResource, filename)) {
if (isZip(baos.toByteArray(), filename)) {
log.info("File {} is a zip file. Unzipping...", filename);
unzippedFiles.addAll(unzip(fileResource, result));
unzippedFiles.addAll(unzip(baos.toByteArray()));
} else {
unzippedFiles.add(fileResource);
}
@@ -488,17 +439,4 @@ 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,37 +1,14 @@
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
@Slf4j
public class PipelineResult implements AutoCloseable {
public class PipelineResult {
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();
}
}
@@ -1,29 +0,0 @@
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,10 +14,7 @@ import stirling.software.common.model.api.PDFFile;
public class OverlayImageRequest extends PDFFile {
@Schema(
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.",
description = "The image file to be overlaid onto the PDF.",
requiredMode = Schema.RequiredMode.REQUIRED,
format = "binary")
private MultipartFile imageFile;
@@ -1,97 +0,0 @@
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"));
}
}
@@ -1,234 +0,0 @@
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,8 +4,6 @@ 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;
@@ -15,7 +13,6 @@ 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;
@@ -27,7 +24,6 @@ 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 {
@@ -38,16 +34,11 @@ class PipelineProcessorTest {
@Mock ServletContext servletContext;
@Mock TempFileManager tempFileManager;
PipelineProcessor pipelineProcessor;
@BeforeEach
void setUp() {
pipelineProcessor =
spy(
new PipelineProcessor(
apiDocService, userService, servletContext, tempFileManager));
pipelineProcessor = spy(new PipelineProcessor(apiDocService, userService, servletContext));
}
@Test
@@ -68,18 +59,12 @@ class PipelineProcessorTest {
when(apiDocService.isValidOperation(eq("/api/v1/filter/filter-page-count"), anyMap()))
.thenReturn(true);
// 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))
doReturn(new ResponseEntity<>(new byte[0], 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");
@@ -87,45 +72,6 @@ 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:$bouncycastleVersion"
implementation 'org.bouncycastle:bcprov-jdk18on:1.83'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5:3.1.3.RELEASE'
api 'io.micrometer:micrometer-registry-prometheus'
+7 -26
View File
@@ -38,16 +38,6 @@ 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 {
@@ -65,6 +55,11 @@ springBoot {
mainClass = 'stirling.software.SPDF.SPDFApplication'
}
repositories {
mavenCentral()
maven { url = 'https://build.shibboleth.net/maven/releases' }
}
allprojects {
group = 'stirling.software'
version = '2.3.0'
@@ -140,27 +135,13 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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གདམ་ག།"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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 विकल्प"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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 へのオプション"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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로 옵션"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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 ആക്കാനുള്ള ഓപ്ഷനുകൾ"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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 选项"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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 选项"
@@ -1400,7 +1396,6 @@ 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,10 +1295,6 @@ 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 選項"
@@ -1400,7 +1396,6 @@ 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.3.0",
"version": "2.2.1",
"identifier": "stirling.pdf.dev",
"build": {
"frontendDist": "../dist",
@@ -77,26 +77,15 @@ export const ImageUploader: React.FC<ImageUploaderProps> = ({
setCurrentFile(file);
onImageChange(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);
});
}
const originalDataUrl = await new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => resolve(e.target?.result as string);
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(file);
});
setOriginalImageData(dataUrlToProcess);
await processImage(dataUrlToProcess, removeBackground);
setOriginalImageData(originalDataUrl);
await processImage(file, removeBackground);
} catch (error) {
console.error('Error processing image file:', error);
}
@@ -109,115 +98,6 @@ 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, SVG, or other image file to place on the PDF. SVG files will be converted to PNG for compatibility."
hint="Upload a PNG, JPG, or other image file to place on the PDF"
/>
</Stack>
</BaseAnnotationTool>
@@ -41,16 +41,13 @@ 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({ ...defaultParams, ...tool.parameters });
setParameters(tool.parameters);
} else {
// Fallback to default parameters if none provided
setParameters({ ...defaultParams });
// Fallback to empty parameters if none provided
setParameters({});
}
}, [tool.parameters, tool.operation, toolRegistry]);
}, [tool.parameters, tool.operation]);
// Render the settings component
const renderToolSettings = () => {
@@ -1,41 +0,0 @@
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,7 +20,6 @@ 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 {
@@ -332,18 +331,6 @@ 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,7 +21,6 @@ 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',
@@ -47,7 +46,6 @@ 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',
@@ -173,8 +171,7 @@ 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': 'svg-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' },
'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 (defaults merged in automationExecutor)
// Required parameters with correct formatting
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 ?? false).toString());
formData.append("alphabet", parameters.alphabet);
formData.append("customColor", parameters.customColor);
formData.append("convertPDFToImage", parameters.convertPDFToImage.toString());
return formData;
};
@@ -38,7 +38,7 @@ export function useAutomateOperation() {
console.log(`✅ Automation completed, returning ${finalResults.length} files`);
return {
files: finalResults,
consumedAllInputs: true,
consumedAllInputs: false,
};
}, [toolRegistry]);
@@ -46,6 +46,5 @@ 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' ? { ...getToolDefaultParameters(operation), ...(op.parameters || {}) } : getToolDefaultParameters(operation)
parameters: typeof op === 'object' ? op.parameters || {} : {}
};
});
@@ -68,7 +68,7 @@ export function useAutomationForm({ mode, existingAutomation, toolRegistry }: Us
}));
setSelectedTools(defaultTools);
}
}, [mode, existingAutomation, t, getToolName, getToolDefaultParameters]);
}, [mode, existingAutomation, t, getToolName]);
const addTool = (operation: string) => {
const toolEntry = toolRegistry[operation as ToolId];
@@ -3,12 +3,11 @@ 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) => {
if (!parameters) return [];
return Object.entries(parameters).map(([key, value]) =>
[key, (value ?? false).toString()]
) as string[][];
});
export const getFormData = ((parameters: ChangePermissionsParameters) =>
Object.entries(parameters).map(([key, value]) =>
[key, value.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 ?? false).toString());
formData.append("grayscale", parameters.grayscale.toString());
formData.append("lineArt", parameters.lineArt.toString());
formData.append("linearize", parameters.linearize.toString());
if (parameters.lineArt) {
@@ -15,8 +15,6 @@ 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)
@@ -68,8 +66,6 @@ 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, defaultParameters } from '@app/hooks/tools/merge/useMergeParameters';
import { MergeParameters } 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 ?? false).toString());
formData.append("generateToc", (parameters.generateTableOfContents ?? false).toString());
formData.append("removeCertSign", parameters.removeDigitalSignature.toString());
formData.append("generateToc", parameters.generateTableOfContents.toString());
return formData;
};
@@ -26,7 +26,6 @@ export const mergeOperationConfig: ToolOperationConfig<MergeParameters> = {
operationType: 'merge',
endpoint: '/api/v1/general/merge-pdfs',
filePrefix: 'merged_',
defaultParameters,
};
export const useMergeOperation = () => {
@@ -44,13 +44,11 @@ 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);
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());
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());
return formData;
};
@@ -9,12 +9,12 @@ export const buildSanitizeFormData = (parameters: SanitizeParameters, file: File
formData.append('fileInput', file);
// Add parameters
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());
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());
return formData;
};
@@ -71,13 +71,6 @@ 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 ?? false).toString());
formData.append("merge", parameters.merge.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 ?? false).toString());
formData.append("allowDuplicates", (parameters.allowDuplicates ?? false).toString());
formData.append("includeMetadata", parameters.includeMetadata.toString());
formData.append("allowDuplicates", parameters.allowDuplicates.toString());
break;
case SPLIT_METHODS.BY_PAGE_DIVIDER:
formData.append("duplexMode", (parameters.duplexMode ?? false).toString());
formData.append("duplexMode", parameters.duplexMode.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.3.0',
appVersion: '2.2.1',
serverCertificateEnabled: false,
enableAlphaFunctionality: false,
serverPort: 8080,
@@ -155,21 +155,18 @@ 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(mergedParameters, files);
const result = await config.customProcessor(parameters, files);
return result.files;
}
// Execute based on tool type
if (config.toolType === ToolType.multiFile) {
return await executeMultiFileOperation(config, mergedParameters, files, filePrefix);
return await executeMultiFileOperation(config, parameters, files, filePrefix);
} else {
return await executeSingleFileOperation(config, mergedParameters, files, filePrefix);
return await executeSingleFileOperation(config, parameters, files, filePrefix);
}
} catch (error: any) {
+8 -12
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,11 +50,7 @@ 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'].includes(extension.toLowerCase());
};
export const isSvgFormat = (extension: string): boolean => {
return extension.toLowerCase() === 'svg';
return ['png', 'jpg', 'jpeg', 'gif', 'tiff', 'bmp', 'webp', 'svg'].includes(extension.toLowerCase());
};
/**
@@ -103,4 +99,4 @@ export const getAvailableToExtensions = (fromExtension: string): Array<{value: s
return TO_FORMAT_OPTIONS.filter(option =>
supportedExtensions.includes(option.value)
);
};
};
@@ -194,6 +194,7 @@ 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));
@@ -205,7 +206,6 @@ 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.3.0',
appVersion: '2.2.1',
serverCertificateEnabled: false,
enableAlphaFunctionality: false,
enableDesktopInstallSlide: true,
-21
View File
@@ -1,28 +1,7 @@
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'