Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Add Stirling Office Convert as an opt-in Office converter (#8219)

Anthony Stirling9e41da2ef48e
diff --git a/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java b/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java
index a4d8fb96f2..8aaeba37e8 100644
--- a/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java
+++ b/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java
@@ -613,6 +613,14 @@ public class EndpointConfiguration {
// file-to-pdf has multiple implementations
addEndpointAlternative("file-to-pdf", "LibreOffice");
addEndpointAlternative("file-to-pdf", "Unoconvert");
+ // Stirling Office Convert, when enabled, keeps Office conversions working without
+ // LibreOffice
+ if (applicationProperties.getSystem().isStirlingOfficeConversion()) {
+ addEndpointAlternative("file-to-pdf", "Java");
+ addEndpointAlternative("pdf-to-word", "Java");
+ addEndpointAlternative("pdf-to-presentation", "Java");
+ addEndpointAlternative("pdf-to-rtf", "Java");
+ }
// pdf-to-html and pdf-to-markdown can use either LibreOffice or Pdftohtml
addEndpointAlternative("pdf-to-html", "LibreOffice");
diff --git a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
index 67eb901e45..296ce99b27 100644
--- a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
+++ b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
@@ -1339,6 +1339,7 @@ public class ApplicationProperties {
private boolean enableEasterEggs = true;
private Datasource datasource;
private boolean disableSanitize;
+ private boolean stirlingOfficeConversion;
private int maxDPI = 500;
private boolean enableUrlToPDF;
private Html html = new Html();
diff --git a/app/common/src/main/java/stirling/software/common/util/ExceptionUtils.java b/app/common/src/main/java/stirling/software/common/util/ExceptionUtils.java
index 3e54030d5a..c48a918f71 100644
--- a/app/common/src/main/java/stirling/software/common/util/ExceptionUtils.java
+++ b/app/common/src/main/java/stirling/software/common/util/ExceptionUtils.java
@@ -786,6 +786,16 @@ public class ExceptionUtils {
return new ToolRequiredException(message, ErrorCode.GHOSTSCRIPT_REQUIRED.getCode());
}
+ public static ToolRequiredException createLibreOfficeRequiredException(String extension) {
+ requireNonNull(extension, "extension");
+ String message =
+ getMessage(
+ ErrorCode.LIBREOFFICE_REQUIRED.getMessageKey(),
+ ErrorCode.LIBREOFFICE_REQUIRED.getDefaultMessage(),
+ extension);
+ return new ToolRequiredException(message, ErrorCode.LIBREOFFICE_REQUIRED.getCode());
+ }
+
public static ToolRequiredException createPythonRequiredForWebpException() {
String message = getMessage(ErrorCode.PYTHON_REQUIRED_WEBP);
return new ToolRequiredException(message, ErrorCode.PYTHON_REQUIRED_WEBP.getCode());
@@ -1296,6 +1306,10 @@ public class ExceptionUtils {
"E064",
"error.ghostscriptRequired",
"Ghostscript must be installed for {0}. Install Ghostscript and ensure it is available on the system PATH."),
+ LIBREOFFICE_REQUIRED(
+ "E082",
+ "error.libreOfficeRequired",
+ "LibreOffice must be installed to convert .{0} files to PDF. Install LibreOffice and ensure it is available on the system PATH."),
// Validation errors
INVALID_ARGUMENT("E070", "error.invalidArgument", "Invalid argument ''{0}'': {1}"),
diff --git a/app/common/src/test/java/stirling/software/common/util/ExceptionUtilsCodedFactoriesTest.java b/app/common/src/test/java/stirling/software/common/util/ExceptionUtilsCodedFactoriesTest.java
index 3da1683527..1f5aa94d99 100644
--- a/app/common/src/test/java/stirling/software/common/util/ExceptionUtilsCodedFactoriesTest.java
+++ b/app/common/src/test/java/stirling/software/common/util/ExceptionUtilsCodedFactoriesTest.java
@@ -54,6 +54,10 @@ class ExceptionUtilsCodedFactoriesTest {
"E064",
() -> ExceptionUtils.createGhostscriptRequiredException("PDF/X"),
IOException.class),
+ coded(
+ "E082",
+ () -> ExceptionUtils.createLibreOfficeRequiredException("html"),
+ IOException.class),
coded(
"E040",
ExceptionUtils::createOcrLanguageRequiredException,
diff --git a/app/core/build.gradle b/app/core/build.gradle
index 05c69bcdce..26965ed614 100644
--- a/app/core/build.gradle
+++ b/app/core/build.gradle
@@ -46,6 +46,11 @@ dependencies {
implementation "org.commonmark:commonmark:$commonmarkVersion" // https://mvnrepository.com/artifact/org.commonmark/commonmark
implementation "org.commonmark:commonmark-ext-gfm-tables:$commonmarkVersion"
+ // Stirling Office Convert: PDF to Office, legacy .ppt output, and Office to PDF without LibreOffice.
+ implementation "com.stirling:stirling-office-convert:$officeConvertVersion"
+ implementation "com.stirling:stirling-office-convert-legacy:$officeConvertVersion"
+ implementation "com.stirling:stirling-office-convert-topdf:$officeConvertVersion"
+
// General PDF dependencies
implementation "org.apache.pdfbox:preflight:$pdfboxVersion"
implementation "org.apache.pdfbox:xmpbox:$pdfboxVersion"
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeController.java
index 7482791b42..cdd43afabe 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeController.java
@@ -17,6 +17,7 @@ import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ModelAttribute;
+import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import io.github.pixee.security.Filenames;
@@ -26,6 +27,8 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.config.EndpointConfiguration;
+import stirling.software.SPDF.service.OfficeConversionService;
+import stirling.software.SPDF.service.OfficeToPdfService;
import stirling.software.common.annotations.AutoJobPostMapping;
import stirling.software.common.annotations.api.ConvertApi;
import stirling.software.common.configuration.RuntimePathConfig;
@@ -56,6 +59,8 @@ public class ConvertOfficeController {
private final OfficeDocumentSanitizer officeDocumentSanitizer;
private final EndpointConfiguration endpointConfiguration;
private final TempFileManager tempFileManager;
+ private final OfficeConversionService officeConversionService;
+ private final OfficeToPdfService officeToPdfService;
private boolean isUnoconvertAvailable() {
return endpointConfiguration.isGroupEnabled("Unoconvert")
@@ -63,6 +68,11 @@ public class ConvertOfficeController {
}
public File convertToPdf(MultipartFile inputFile) throws IOException, InterruptedException {
+ return convertToPdf(inputFile, null);
+ }
+
+ public File convertToPdf(MultipartFile inputFile, Boolean useStirlingOfficeConvert)
+ throws IOException, InterruptedException {
// Check for valid file extension and sanitize filename
String originalFilename = Filenames.toSimpleFileName(inputFile.getOriginalFilename());
if (originalFilename == null || originalFilename.isBlank()) {
@@ -87,6 +97,15 @@ public class ConvertOfficeController {
Path inputPath = workDir.resolve(baseName + "." + extensionLower);
Path outputPath = workDir.resolve(baseName + ".pdf");
+ if (officeToPdfService.handles(extensionLower, useStirlingOfficeConvert)) {
+ if (convertInProcess(inputFile, extensionLower, workDir, inputPath, outputPath)) {
+ return outputPath.toFile();
+ }
+ } else if (!officeConversionService.libreOfficeAvailable()) {
+ FileUtils.deleteQuietly(workDir.toFile());
+ throw ExceptionUtils.createLibreOfficeRequiredException(extensionLower);
+ }
+
// Sanitize input before LibreOffice sees it so embedded URLs can't trigger SSRF.
if ("html".equals(extensionLower) || "htm".equals(extensionLower)) {
String htmlContent = new String(inputFile.getBytes(), StandardCharsets.UTF_8);
@@ -200,6 +219,48 @@ public class ConvertOfficeController {
}
}
+ /** False when LibreOffice should retry the file; the original upload is converted as is. */
+ private boolean convertInProcess(
+ MultipartFile inputFile,
+ String extension,
+ Path workDir,
+ Path inputPath,
+ Path outputPath)
+ throws IOException {
+ try {
+ // Same sanitizing and ZIP budget as the LibreOffice path; a refused file never falls
+ // back.
+ if (officeDocumentSanitizer.isSanitizableExtension(extension)) {
+ Files.write(
+ inputPath,
+ officeDocumentSanitizer.sanitize(inputFile.getBytes(), extension));
+ } else {
+ Files.copy(
+ inputFile.getInputStream(), inputPath, StandardCopyOption.REPLACE_EXISTING);
+ }
+ } catch (IOException | RuntimeException e) {
+ FileUtils.deleteQuietly(workDir.toFile());
+ throw e;
+ }
+ try {
+ officeToPdfService.convert(inputPath, outputPath);
+ return true;
+ } catch (IOException | RuntimeException e) {
+ if (!officeToPdfService.canFallBack(e)) {
+ FileUtils.deleteQuietly(workDir.toFile());
+ throw e;
+ }
+ log.warn(
+ "Stirling Office Convert could not convert {} ({}); retrying with LibreOffice",
+ inputPath.getFileName(),
+ e.getMessage());
+ Files.deleteIfExists(outputPath);
+ return false;
+ } finally {
+ Files.deleteIfExists(inputPath);
+ }
+ }
+
private boolean isValidFileExtension(String fileExtension) {
return RegexPatternUtils.getInstance()
.getFileExtensionValidationPattern()
@@ -213,15 +274,20 @@ public class ConvertOfficeController {
resourceWeight = ResourceWeight.LARGE_WEIGHT)
@ToolIO(accepts = ToolFormat.ANY, produces = ToolFormat.PDF)
@Operation(
- summary = "Convert a file to a PDF using LibreOffice",
- description = "This endpoint converts a given file to a PDF using LibreOffice API")
- public ResponseEntity<Resource> processFileToPDF(@ModelAttribute GeneralFile generalFile)
+ summary = "Convert a file to a PDF",
+ description =
+ "This endpoint converts a given file to a PDF using Stirling Office Convert or"
+ + " LibreOffice")
+ public ResponseEntity<Resource> processFileToPDF(
+ @ModelAttribute GeneralFile generalFile,
+ @RequestParam(value = "useStirlingOfficeConvert", required = false)
+ Boolean useStirlingOfficeConvert)
throws Exception {
MultipartFile inputFile = generalFile.getFileInput();
File file = null;
TempFile tempOut = null;
try {
- file = convertToPdf(inputFile);
+ file = convertToPdf(inputFile, useStirlingOfficeConvert);
tempOut = tempFileManager.createManagedTempFile(".pdf");
try (PDDocument doc = pdfDocumentFactory.load(file)) {
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToExcelController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToExcelController.java
index f747ce7447..4c0dee7813 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToExcelController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToExcelController.java
@@ -1,7 +1,9 @@
package stirling.software.SPDF.controller.api.converters;
+import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.List;
import java.util.Locale;
@@ -16,6 +18,7 @@ import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ModelAttribute;
+import org.springframework.web.bind.annotation.RequestParam;
import io.swagger.v3.oas.annotations.Operation;
@@ -23,6 +26,7 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.model.api.PDFWithPageNums;
+import stirling.software.SPDF.service.OfficeConversionService;
import stirling.software.common.annotations.AutoJobPostMapping;
import stirling.software.common.annotations.api.ConvertApi;
import stirling.software.common.enumeration.ResourceWeight;
@@ -33,6 +37,8 @@ import stirling.software.common.util.GeneralUtils;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
+import stirling.software.officeconvert.OfficeConvert;
+import stirling.software.officeconvert.PdfToXlsx;
import technology.tabula.ObjectExtractor;
import technology.tabula.Page;
@@ -47,6 +53,7 @@ public class ConvertPDFToExcelController {
private final CustomPDFDocumentFactory pdfDocumentFactory;
private final TempFileManager tempFileManager;
+ private final OfficeConversionService officeConversionService;
@AutoJobPostMapping(
value = "/pdf/xlsx",
@@ -58,17 +65,40 @@ public class ConvertPDFToExcelController {
description =
"Extracts tabular data from each page of a PDF and writes it into an Excel"
+ " workbook, one sheet per table.")
- public ResponseEntity<Resource> pdfToExcel(@ModelAttribute PDFWithPageNums request)
+ public ResponseEntity<Resource> pdfToExcel(
+ @ModelAttribute PDFWithPageNums request,
+ @RequestParam(value = "useStirlingOfficeConvert", required = false)
+ Boolean useStirlingOfficeConvert)
throws Exception {
String baseName =
GeneralUtils.removeExtension(request.getFileInput().getOriginalFilename());
TempFile tempOut = tempFileManager.createManagedTempFile(".xlsx");
- try (PDDocument document = pdfDocumentFactory.load(request);
- XSSFWorkbook workbook = new XSSFWorkbook();
- ObjectExtractor extractor = new ObjectExtractor(document)) {
-
+ try (PDDocument document = pdfDocumentFactory.load(request)) {
List<Integer> pages = request.getPageNumbersList(document, true);
+ boolean written =
+ officeConversionService.legacy(useStirlingOfficeConvert)
+ ? writeTabula(document, pages, tempOut.getPath())
+ : writeOfficeConvert(document, pages, tempOut.getPath());
+ if (!written) {
+ tempOut.close();
+ return ResponseEntity.noContent().build();
+ }
+ } catch (Exception e) {
+ tempOut.close();
+ throw e;
+ }
+
+ MediaType mediaType =
+ MediaType.parseMediaType(
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
+ return WebResponseUtils.fileToWebResponse(tempOut, baseName + ".xlsx", mediaType);
+ }
+
+ private boolean writeTabula(PDDocument document, List<Integer> pages, Path out)
+ throws IOException {
+ try (XSSFWorkbook workbook = new XSSFWorkbook();
+ ObjectExtractor extractor = new ObjectExtractor(document)) {
SpreadsheetExtractionAlgorithm sea = new SpreadsheetExtractionAlgorithm();
int sheetCount = 0;
@@ -101,22 +131,44 @@ public class ConvertPDFToExcelController {
}
if (sheetCount == 0) {
- tempOut.close();
- return ResponseEntity.noContent().build();
+ return false;
}
-
- try (OutputStream os = Files.newOutputStream(tempOut.getPath())) {
+ try (OutputStream os = Files.newOutputStream(out)) {
workbook.write(os);
}
- } catch (Exception e) {
- tempOut.close();
- throw e;
+ return true;
}
+ }
- MediaType mediaType =
- MediaType.parseMediaType(
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
- return WebResponseUtils.fileToWebResponse(tempOut, baseName + ".xlsx", mediaType);
+ private boolean writeOfficeConvert(PDDocument document, List<Integer> pages, Path out)
+ throws IOException {
+ if (pages.isEmpty()) {
+ return false;
+ }
+ OfficeConvert.Settings settings =
+ officeConversionService.settings().sheets(PdfToXlsx.Sheets.TABLE);
+ if (consecutive(pages)) {
+ // A run of pages converts in place, so sheet names keep the PDF's page numbers.
+ officeConversionService.convert(
+ document, out, "xlsx", settings.pages(pages.getFirst(), pages.getLast()));
+ } else {
+ try (PDDocument chosen = new PDDocument()) {
+ for (int page : pages) {
+ chosen.importPage(document.getPage(page - 1));
+ }
+ officeConversionService.convert(chosen, out, "xlsx", settings);
+ }
+ }
+ return OfficeConversionService.hasCells(out);
+ }
+
+ private static boolean consecutive(List<Integer> pages) {
+ for (int i = 1; i < pages.size(); i++) {
+ if (pages.get(i) != pages.get(i - 1) + 1) {
+ return false;
+ }
+ }
+ return true;
}
private String getUniqueSheetName(Workbook workbook, String baseName) {
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToOffice.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToOffice.java
index fd6218de0d..f0190b6a5d 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToOffice.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToOffice.java
@@ -3,6 +3,7 @@ package stirling.software.SPDF.controller.api.converters;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
+import java.util.Set;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
@@ -10,6 +11,7 @@ import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ModelAttribute;
+import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation;
@@ -19,6 +21,7 @@ import lombok.RequiredArgsConstructor;
import stirling.software.SPDF.model.api.converters.PdfToPresentationRequest;
import stirling.software.SPDF.model.api.converters.PdfToTextOrRTFRequest;
import stirling.software.SPDF.model.api.converters.PdfToWordRequest;
+import stirling.software.SPDF.service.OfficeConversionService;
import stirling.software.common.annotations.AutoJobPostMapping;
import stirling.software.common.annotations.api.ConvertApi;
import stirling.software.common.configuration.RuntimePathConfig;
@@ -43,6 +46,7 @@ public class ConvertPDFToOffice {
private final CustomPDFDocumentFactory pdfDocumentFactory;
private final TempFileManager tempFileManager;
private final RuntimePathConfig runtimePathConfig;
+ private final OfficeConversionService officeConversionService;
@AutoJobPostMapping(
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
@@ -53,10 +57,19 @@ public class ConvertPDFToOffice {
summary = "Convert PDF to Presentation format",
description = "This endpoint converts a given PDF file to a Presentation format.")
public ResponseEntity<Resource> processPdfToPresentation(
- @ModelAttribute PdfToPresentationRequest request)
+ @ModelAttribute PdfToPresentationRequest request,
+ @RequestParam(value = "useStirlingOfficeConvert", required = false)
+ Boolean useStirlingOfficeConvert)
throws IOException, InterruptedException {
MultipartFile inputFile = request.getFileInput();
String outputFormat = request.getOutputFormat();
+ if (officeConversionService.replacesLibreOffice(useStirlingOfficeConvert)) {
+ return convert(
+ inputFile,
+ outputFormat,
+ Set.of("ppt", "pptx", "odp"),
+ MediaType.APPLICATION_OCTET_STREAM);
+ }
PDFToFile pdfToFile = new PDFToFile(tempFileManager, runtimePathConfig);
return pdfToFile.processPdfToOfficeFormat(inputFile, outputFormat, "impress_pdf_import");
}
@@ -76,11 +89,26 @@ public class ConvertPDFToOffice {
summary = "Convert PDF to Text or RTF format",
description = "This endpoint converts a given PDF file to Text or RTF format.")
public ResponseEntity<Resource> processPdfToRTForTXT(
- @ModelAttribute PdfToTextOrRTFRequest request)
+ @ModelAttribute PdfToTextOrRTFRequest request,
+ @RequestParam(value = "useStirlingOfficeConvert", required = false)
+ Boolean useStirlingOfficeConvert)
throws IOException, InterruptedException {
MultipartFile inputFile = request.getFileInput();
String outputFormat = request.getOutputFormat();
- if ("txt".equals(request.getOutputFormat())) {
+ boolean plainText = "txt".equals(outputFormat);
+ // Legacy text came from PDFBox, not LibreOffice, so it never needs the fallback.
+ boolean officeConvert =
+ plainText
+ ? !officeConversionService.legacy(useStirlingOfficeConvert)
+ : officeConversionService.replacesLibreOffice(useStirlingOfficeConvert);
+ if (officeConvert) {
+ return convert(
+ inputFile,
+ outputFormat,
+ Set.of("rtf", "txt"),
+ plainText ? MediaType.TEXT_PLAIN : MediaType.APPLICATION_OCTET_STREAM);
+ }
+ if (plainText) {
String fileName =
GeneralUtils.generateFilename(inputFile.getOriginalFilename(), ".txt");
TempFile finalOut = tempFileManager.createManagedTempFile(".txt");
@@ -107,10 +135,20 @@ public class ConvertPDFToOffice {
@Operation(
summary = "Convert PDF to Word document",
description = "This endpoint converts a given PDF file to a Word document format.")
- public ResponseEntity<Resource> processPdfToWord(@ModelAttribute PdfToWordRequest request)
+ public ResponseEntity<Resource> processPdfToWord(
+ @ModelAttribute PdfToWordRequest request,
+ @RequestParam(value = "useStirlingOfficeConvert", required = false)
+ Boolean useStirlingOfficeConvert)
throws IOException, InterruptedException {
MultipartFile inputFile = request.getFileInput();
String outputFormat = request.getOutputFormat();
+ if (officeConversionService.replacesLibreOffice(useStirlingOfficeConvert)) {
+ return convert(
+ inputFile,
+ outputFormat,
+ Set.of("doc", "docx", "odt"),
+ MediaType.APPLICATION_OCTET_STREAM);
+ }
PDFToFile pdfToFile = new PDFToFile(tempFileManager, runtimePathConfig);
return pdfToFile.processPdfToOfficeFormat(inputFile, outputFormat, "writer_pdf_import");
}
@@ -129,4 +167,24 @@ public class ConvertPDFToOffice {
PDFToFile pdfToFile = new PDFToFile(tempFileManager, runtimePathConfig);
return pdfToFile.processPdfToOfficeFormat(inputFile, "xml", "writer_pdf_import");
}
+
+ private ResponseEntity<Resource> convert(
+ MultipartFile input, String format, Set<String> formats, MediaType type)
+ throws IOException {
+ // Text reads any upload; every other format takes only an upload typed as a PDF.
+ boolean pdf = MediaType.APPLICATION_PDF_VALUE.equals(input.getContentType());
+ if (!formats.contains(format) || !pdf && !"txt".equals(format)) {
+ return ResponseEntity.badRequest().build();
+ }
+ TempFile out = tempFileManager.createManagedTempFile("." + format);
+ try (PDDocument document = pdfDocumentFactory.load(input)) {
+ officeConversionService.convert(
+ document, out.getPath(), format, officeConversionService.settings());
+ } catch (Exception e) {
+ out.close();
+ throw e;
+ }
+ String fileName = GeneralUtils.generateFilename(input.getOriginalFilename(), "." + format);
+ return WebResponseUtils.fileToWebResponse(out, fileName, type);
+ }
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java
index 820494a0a3..2c207d522d 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/ConfigController.java
@@ -322,6 +322,9 @@ public class ConfigController {
configData.put(
"enableAlphaFunctionality",
applicationProperties.getSystem().isEnableAlphaFunctionality());
+ configData.put(
+ "stirlingOfficeConversion",
+ applicationProperties.getSystem().isStirlingOfficeConversion());
boolean shouldShowUpdate =
applicationProperties.getSystem().isShowUpdate()
&& (showAdmin == null || showAdmin.getShowUpdateOnlyAdmins());
diff --git a/app/core/src/main/java/stirling/software/SPDF/service/OfficeConversionService.java b/app/core/src/main/java/stirling/software/SPDF/service/OfficeConversionService.java
new file mode 100644
index 0000000000..9cb9898caa
--- /dev/null
+++ b/app/core/src/main/java/stirling/software/SPDF/service/OfficeConversionService.java
@@ -0,0 +1,142 @@
+package stirling.software.SPDF.service;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Duration;
+import java.util.Enumeration;
+import java.util.Map;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.springframework.stereotype.Service;
+
+import lombok.RequiredArgsConstructor;
+
+import stirling.software.SPDF.config.EndpointConfiguration;
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.officeconvert.OfficeConvert;
+import stirling.software.officeconvert.PdfToPptx;
+import stirling.software.officeconvert.legacy.PdfToPpt;
+
+/**
+ * PDF to Office in process through Stirling Office Convert, and the switch between it and the
+ * legacy converters. Conversions are stopped at the LibreOffice timeout.
+ */
+@Service
+@RequiredArgsConstructor
+public class OfficeConversionService {
+
+ /** Output formats by extension; a .doc is RTF, which Word opens as a document. */
+ private static final Map<String, OfficeConvert.Format> FORMATS =
+ Map.of(
+ "docx", OfficeConvert.Format.DOCX,
+ "doc", OfficeConvert.Format.RTF,
+ "odt", OfficeConvert.Format.ODT,
+ "rtf", OfficeConvert.Format.RTF,
+ "txt", OfficeConvert.Format.TXT,
+ "pptx", OfficeConvert.Format.PPTX,
+ "odp", OfficeConvert.Format.ODP,
+ "xlsx", OfficeConvert.Format.XLSX,
+ "ods", OfficeConvert.Format.ODS);
+
+ private final ApplicationProperties applicationProperties;
+ private final EndpointConfiguration endpointConfiguration;
+
+ public static boolean supports(String format) {
+ return FORMATS.containsKey(format) || "ppt".equals(format);
+ }
+
+ /** Whether the legacy converters (LibreOffice, Tabula, plain text) apply. */
+ public boolean legacy() {
+ return legacy(null);
+ }
+
+ /** {@code choice} is the caller's per-request pick; null follows the admin setting. */
+ public boolean legacy(Boolean choice) {
+ return choice != null
+ ? !choice
+ : !applicationProperties.getSystem().isStirlingOfficeConversion();
+ }
+
+ public boolean libreOfficeAvailable() {
+ return endpointConfiguration.isGroupEnabled("LibreOffice");
+ }
+
+ /** Stirling Office Convert replaces LibreOffice only when the admin enables it. */
+ public boolean replacesLibreOffice() {
+ return !legacy();
+ }
+
+ public boolean replacesLibreOffice(Boolean choice) {
+ return !legacy(choice);
+ }
+
+ public OfficeConvert.Settings settings() {
+ long minutes =
+ applicationProperties
+ .getProcessExecutor()
+ .getTimeoutMinutes()
+ .getLibreOfficeTimeoutMinutes();
+ return OfficeConvert.Settings.defaults().timeout(Duration.ofMinutes(minutes));
+ }
+
+ /**
+ * Writes {@code document} to {@code target} as {@code format}, one {@link #supports} accepts.
+ */
+ public void convert(
+ PDDocument document, Path target, String format, OfficeConvert.Settings settings)
+ throws IOException {
+ if (!supports(format)) {
+ throw new IllegalArgumentException("No PDF to Office conversion to " + format);
+ }
+ try (OutputStream out = Files.newOutputStream(target)) {
+ if ("ppt".equals(format)) {
+ // Binary PowerPoint comes from the legacy module, outside OfficeConvert's timeout.
+ PdfToPpt.convert(document, out, slides(settings));
+ } else {
+ OfficeConvert.convert(document, out, FORMATS.get(format), settings);
+ }
+ }
+ }
+
+ /**
+ * Whether a workbook holds any cell. With no table found, a sheet-per-table workbook is a
+ * single empty sheet.
+ */
+ public static boolean hasCells(Path xlsx) throws IOException {
+ try (ZipFile zip = new ZipFile(xlsx.toFile())) {
+ Enumeration<? extends ZipEntry> entries = zip.entries();
+ while (entries.hasMoreElements()) {
+ ZipEntry entry = entries.nextElement();
+ if (!entry.getName().startsWith("xl/worksheets/")) {
+ continue;
+ }
+ try (InputStream in = zip.getInputStream(entry)) {
+ // A sheet's first cell follows its short header, well within the first
+ // megabyte.
+ if (new String(in.readNBytes(1 << 20), StandardCharsets.ISO_8859_1)
+ .contains("<c ")) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ private static PdfToPptx.Options slides(OfficeConvert.Settings s) {
+ return new PdfToPptx.Options(
+ s.firstPage(),
+ s.lastPage(),
+ s.tables(),
+ s.figureDpi(),
+ s.password(),
+ s.pictureFallback(),
+ s.pictures());
+ }
+}
diff --git a/app/core/src/main/java/stirling/software/SPDF/service/OfficeToPdfService.java b/app/core/src/main/java/stirling/software/SPDF/service/OfficeToPdfService.java
new file mode 100644
index 0000000000..849de1078e
--- /dev/null
+++ b/app/core/src/main/java/stirling/software/SPDF/service/OfficeToPdfService.java
@@ -0,0 +1,97 @@
+package stirling.software.SPDF.service;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import java.time.Duration;
+
+import org.springframework.boot.context.event.ApplicationReadyEvent;
+import org.springframework.context.event.EventListener;
+import org.springframework.stereotype.Service;
+
+import jakarta.annotation.PostConstruct;
+
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.officeconvert.memory.Admission;
+import stirling.software.officeconvert.topdf.OfficeToPdf;
+import stirling.software.officeconvert.topdf.io.PoiXml;
+
+/** Office to PDF in process through Stirling Office Convert, with LibreOffice as the fallback. */
+@Slf4j
+@Service
+@RequiredArgsConstructor
+public class OfficeToPdfService {
+
+ private final OfficeConversionService officeConversionService;
+ private final ApplicationProperties applicationProperties;
+
+ /** POI needs the XML limits Java 24 lowered for deep or large slides. */
+ @PostConstruct
+ void raiseXmlLimits() {
+ PoiXml.raiseProcessLimits();
+ }
+
+ /** Loads the converter and scans fonts off the request path, so a first conversion is fast. */
+ @EventListener(ApplicationReadyEvent.class)
+ public void warmUp() {
+ if (officeConversionService.replacesLibreOffice()) {
+ Thread.ofPlatform()
+ .name("office-to-pdf-warm-up")
+ .daemon()
+ .start(
+ () ->
+ // PPTX is left out: POI logs errors for the warm-up deck.
+ OfficeToPdf.warmUp(
+ OfficeToPdf.Format.DOCX, OfficeToPdf.Format.XLSX));
+ }
+ }
+
+ /** Whether files with this extension convert in process rather than with LibreOffice. */
+ public boolean handles(String extension) {
+ return handles(extension, null);
+ }
+
+ public boolean handles(String extension, Boolean choice) {
+ return officeConversionService.replacesLibreOffice(choice)
+ && OfficeToPdf.Format.recognises(Path.of("file." + extension));
+ }
+
+ public void convert(Path in, Path out) throws IOException {
+ long minutes =
+ applicationProperties
+ .getProcessExecutor()
+ .getTimeoutMinutes()
+ .getLibreOfficeTimeoutMinutes();
+ OfficeToPdf.Result result =
+ OfficeToPdf.convert(
+ in,
+ out,
+ OfficeToPdf.Options.defaults().timeout(Duration.ofMinutes(minutes)));
+ log.debug(
+ "Converted {} to PDF in process: {} pages, {} warnings",
+ in.getFileName(),
+ result.pages(),
+ result.warnings().size());
+ if (result.truncated() && officeConversionService.libreOfficeAvailable()) {
+ // Lost content is worth a LibreOffice retry; without it, partial output beats none.
+ throw new IOException("Only part of " + in.getFileName() + " could be converted");
+ }
+ }
+
+ /** A timeout or a memory stop would only repeat, more slowly, in LibreOffice. */
+ public boolean canFallBack(Throwable failure) {
+ if (!officeConversionService.libreOfficeAvailable()) {
+ return false;
+ }
+ for (Throwable t = failure; t != null; t = t.getCause()) {
+ if (t instanceof OfficeToPdf.TimedOut
+ || t instanceof Admission.Stopped
+ || t instanceof OutOfMemoryError) {
+ return false;
+ }
+ }
+ return true;
+ }
+}
diff --git a/app/core/src/main/resources/settings.yml.template b/app/core/src/main/resources/settings.yml.template
index 012822aee0..0fe589164f 100644
--- a/app/core/src/main/resources/settings.yml.template
+++ b/app/core/src/main/resources/settings.yml.template
@@ -184,6 +184,7 @@ system:
enableScarf: null # Enable Scarf tracking pixel: set to 'true' to enable, 'false' to disable, or 'null' to enable by default when analytics is enabled
enableUrlToPDF: false # Set to 'true' to enable URL to PDF, INTERNAL ONLY, known security issues, should not be used externally
disableSanitize: false # set to true to disable Sanitize HTML; (can lead to injections in HTML)
+ stirlingOfficeConversion: false # Beta: set to 'true' to convert Office files with the built-in Stirling Office Convert (better, faster conversions using less memory) instead of LibreOffice
maxDPI: 500 # Maximum allowed DPI for PDF to image conversion
corsAllowedOrigins: [] # List of allowed origins for CORS (e.g. ['http://localhost:5173', 'https://app.example.com']). WARNING: leaving this empty falls back to allowing ALL origins (with credentials), it does NOT disable CORS. Set explicit origins to lock it down.
backendUrl: "" # Backend base URL for SAML/OAuth/API callbacks (e.g. 'http://localhost:8080' for dev, 'https://api.example.com' for production). REQUIRED for SSO authentication to work correctly. This is where your IdP will send SAML responses and OAuth callbacks. Leave empty to default to 'http://localhost:8080' in development.
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeControllerTest.java
index 14c49b351a..a4c28305c5 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeControllerTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeControllerTest.java
@@ -38,10 +38,13 @@ import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
import stirling.software.SPDF.config.EndpointConfiguration;
+import stirling.software.SPDF.service.OfficeConversionService;
+import stirling.software.SPDF.service.OfficeToPdfService;
import stirling.software.common.configuration.RuntimePathConfig;
import stirling.software.common.model.api.GeneralFile;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.CustomHtmlSanitizer;
+import stirling.software.common.util.ExceptionUtils.ToolRequiredException;
import stirling.software.common.util.GeneralUtils;
import stirling.software.common.util.OfficeDocumentSanitizer;
import stirling.software.common.util.ProcessExecutor;
@@ -50,6 +53,7 @@ import stirling.software.common.util.ProcessExecutor.Processes;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
+import stirling.software.common.util.ZipBombGuard;
/**
* Unit tests for {@link ConvertOfficeController}. The external LibreOffice/unoconvert boundary is
@@ -68,6 +72,8 @@ class ConvertOfficeControllerTest {
@Mock private OfficeDocumentSanitizer officeDocumentSanitizer;
@Mock private EndpointConfiguration endpointConfiguration;
@Mock private TempFileManager tempFileManager;
+ @Mock private OfficeConversionService officeConversionService;
+ @Mock private OfficeToPdfService officeToPdfService;
private ConvertOfficeController controller;
@@ -78,7 +84,9 @@ class ConvertOfficeControllerTest {
customHtmlSanitizer,
officeDocumentSanitizer,
endpointConfiguration,
- tempFileManager);
+ tempFileManager,
+ officeConversionService,
+ officeToPdfService);
}
@BeforeEach
@@ -86,6 +94,7 @@ class ConvertOfficeControllerTest {
controller = newController();
lenient().when(runtimePathConfig.getSOfficePath()).thenReturn("soffice");
lenient().when(runtimePathConfig.getUnoConvertPath()).thenReturn("unoconvert");
+ lenient().when(officeConversionService.libreOfficeAvailable()).thenReturn(true);
}
private static ResponseEntity<Resource> streamingOk(byte[] bytes) {
@@ -183,6 +192,115 @@ class ConvertOfficeControllerTest {
}
}
+ @Nested
+ @DisplayName("Stirling Office Convert")
+ class InProcess {
+
+ @Test
+ @DisplayName("converts handled formats without LibreOffice")
+ void convertsInProcess() throws Exception {
+ when(officeToPdfService.handles("docx", null)).thenReturn(true);
+ when(officeDocumentSanitizer.isSanitizableExtension("docx")).thenReturn(true);
+ when(officeDocumentSanitizer.sanitize(any(byte[].class), anyString()))
+ .thenAnswer(inv -> inv.getArgument(0));
+ Mockito.doAnswer(
+ inv -> {
+ Files.writeString(inv.getArgument(1), "%PDF in process");
+ return null;
+ })
+ .when(officeToPdfService)
+ .convert(any(Path.class), any(Path.class));
+
+ try (MockedStatic<ProcessExecutor> pe = Mockito.mockStatic(ProcessExecutor.class)) {
+ File pdf = controller.convertToPdf(docxFile("real-docx".getBytes()));
+
+ assertThat(Files.readString(pdf.toPath())).isEqualTo("%PDF in process");
+ pe.verifyNoInteractions();
+ Mockito.verify(officeDocumentSanitizer).sanitize(any(byte[].class), anyString());
+ deleteWorkdir(pdf);
+ }
+ }
+
+ @Test
+ @DisplayName("a file the sanitizer refuses reaches neither converter")
+ void refusedBySanitizer() throws Exception {
+ when(officeToPdfService.handles("docx", null)).thenReturn(true);
+ when(officeDocumentSanitizer.isSanitizableExtension("docx")).thenReturn(true);
+ when(officeDocumentSanitizer.sanitize(any(byte[].class), anyString()))
+ .thenThrow(new ZipBombGuard.ZipBombException("too big"));
+
+ try (MockedStatic<ProcessExecutor> pe = Mockito.mockStatic(ProcessExecutor.class)) {
+ assertThatThrownBy(() -> controller.convertToPdf(docxFile("x".getBytes())))
+ .isInstanceOf(ZipBombGuard.ZipBombException.class);
+ pe.verifyNoInteractions();
+ Mockito.verify(officeToPdfService, Mockito.never())
+ .convert(any(Path.class), any(Path.class));
+ }
+ }
+
+ @Test
+ @DisplayName("retries with LibreOffice when the in-process conversion fails")
+ void fallsBackToLibreOffice() throws Exception {
+ when(officeToPdfService.handles("docx", null)).thenReturn(true);
+ Mockito.doThrow(new IOException("unreadable"))
+ .when(officeToPdfService)
+ .convert(any(Path.class), any(Path.class));
+ when(officeToPdfService.canFallBack(any())).thenReturn(true);
+ when(officeDocumentSanitizer.isSanitizableExtension("docx")).thenReturn(true);
+ when(officeDocumentSanitizer.sanitize(any(byte[].class), anyString()))
+ .thenAnswer(inv -> inv.getArgument(0));
+
+ try (MockedStatic<ProcessExecutor> pe = Mockito.mockStatic(ProcessExecutor.class)) {
+ ProcessExecutorResult result = mockExecutor(pe, 0);
+ ProcessExecutor executor = ProcessExecutor.getInstance(Processes.LIBRE_OFFICE);
+ when(executor.runCommandWithOutputHandling(any()))
+ .thenAnswer(
+ inv -> {
+ List<String> command = inv.getArgument(0);
+ Path out =
+ Path.of(command.getLast()).resolveSibling("report.pdf");
+ Files.writeString(out, "%PDF soffice");
+ return result;
+ });
+
+ File pdf = controller.convertToPdf(docxFile("real-docx".getBytes()));
+
+ assertThat(Files.readString(pdf.toPath())).isEqualTo("%PDF soffice");
+ deleteWorkdir(pdf);
+ }
+ }
+
+ @Test
+ @DisplayName("rethrows when LibreOffice cannot take over")
+ void noFallback() throws Exception {
+ when(officeToPdfService.handles("docx", null)).thenReturn(true);
+ Mockito.doThrow(new IOException("unreadable"))
+ .when(officeToPdfService)
+ .convert(any(Path.class), any(Path.class));
+ when(officeToPdfService.canFallBack(any())).thenReturn(false);
+
+ try (MockedStatic<ProcessExecutor> pe = Mockito.mockStatic(ProcessExecutor.class)) {
+ assertThatThrownBy(() -> controller.convertToPdf(docxFile("x".getBytes())))
+ .isInstanceOf(IOException.class)
+ .hasMessage("unreadable");
+ pe.verifyNoInteractions();
+ }
+ }
+
+ @Test
+ @DisplayName("asks for LibreOffice for formats only it converts")
+ void libreOfficeRequired() {
+ when(officeConversionService.libreOfficeAvailable()).thenReturn(false);
+ MockMultipartFile html =
+ new MockMultipartFile(
+ "fileInput", "page.html", "text/html", "<p>hi</p>".getBytes());
+
+ assertThatThrownBy(() -> controller.convertToPdf(html))
+ .isInstanceOf(ToolRequiredException.class)
+ .hasMessageContaining(".html");
+ }
+ }
+
@Nested
@DisplayName("convertToPdf conversion paths")
class ConversionPaths {
@@ -412,7 +530,7 @@ class ConvertOfficeControllerTest {
any(TempFile.class), anyString()))
.thenReturn(expected);
- ResponseEntity<Resource> response = controller.processFileToPDF(generalFile);
+ ResponseEntity<Resource> response = controller.processFileToPDF(generalFile, null);
assertThat(response).isSameAs(expected);
wr.verify(
@@ -441,7 +559,7 @@ class ConvertOfficeControllerTest {
ProcessExecutor executor = ProcessExecutor.getInstance(Processes.LIBRE_OFFICE);
when(executor.runCommandWithOutputHandling(any(List.class))).thenReturn(result);
- assertThatThrownBy(() -> controller.processFileToPDF(generalFile))
+ assertThatThrownBy(() -> controller.processFileToPDF(generalFile, null))
.isInstanceOf(IllegalStateException.class);
// a failed conversion never reaches the document factory
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToExcelControllerMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToExcelControllerMoreTest.java
index f0e8c08d79..d7bf89ec9e 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToExcelControllerMoreTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToExcelControllerMoreTest.java
@@ -31,6 +31,7 @@ import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
import stirling.software.SPDF.model.api.PDFWithPageNums;
+import stirling.software.SPDF.service.OfficeConversionService;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
@@ -46,11 +47,14 @@ class ConvertPDFToExcelControllerMoreTest {
@Mock private CustomPDFDocumentFactory pdfDocumentFactory;
@Mock private TempFileManager tempFileManager;
+ @Mock private OfficeConversionService officeConversionService;
@InjectMocks private ConvertPDFToExcelController controller;
@BeforeEach
void setUp() throws Exception {
+ // These cover the legacy converters; Stirling Office Convert has its own tests.
+ lenient().when(officeConversionService.legacy(null)).thenReturn(true);
lenient()
.when(tempFileManager.createManagedTempFile(anyString()))
.thenAnswer(
@@ -135,7 +139,7 @@ class ConvertPDFToExcelControllerMoreTest {
when(pdfDocumentFactory.load(request)).thenReturn(blankPages(1));
- ResponseEntity<Resource> response = controller.pdfToExcel(request);
+ ResponseEntity<Resource> response = controller.pdfToExcel(request, null);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
}
@@ -149,7 +153,7 @@ class ConvertPDFToExcelControllerMoreTest {
when(pdfDocumentFactory.load(request)).thenReturn(blankPages(3));
- ResponseEntity<Resource> response = controller.pdfToExcel(request);
+ ResponseEntity<Resource> response = controller.pdfToExcel(request, null);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
}
@@ -169,7 +173,7 @@ class ConvertPDFToExcelControllerMoreTest {
when(pdfDocumentFactory.load(request)).thenReturn(borderedTableDoc());
- ResponseEntity<Resource> response = controller.pdfToExcel(request);
+ ResponseEntity<Resource> response = controller.pdfToExcel(request, null);
// Lattice detection depends on the Tabula build; accept either outcome but assert the
// success path produced a real, non-empty xlsx body.
@@ -198,7 +202,7 @@ class ConvertPDFToExcelControllerMoreTest {
when(pdfDocumentFactory.load(request)).thenThrow(new java.io.IOException("load boom"));
- assertThatThrownBy(() -> controller.pdfToExcel(request))
+ assertThatThrownBy(() -> controller.pdfToExcel(request, null))
.isInstanceOf(java.io.IOException.class);
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToExcelControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToExcelControllerTest.java
index 3a37bd6160..4e51986395 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToExcelControllerTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToExcelControllerTest.java
@@ -26,6 +26,7 @@ import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
import stirling.software.SPDF.model.api.PDFWithPageNums;
+import stirling.software.SPDF.service.OfficeConversionService;
import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.GeneralUtils;
import stirling.software.common.util.TempFile;
@@ -36,11 +37,14 @@ class ConvertPDFToExcelControllerTest {
@Mock private CustomPDFDocumentFactory pdfDocumentFactory;
@Mock private TempFileManager tempFileManager;
+ @Mock private OfficeConversionService officeConversionService;
@InjectMocks private ConvertPDFToExcelController controller;
@BeforeEach
void setUp() throws Exception {
+ // These cover the legacy converters; Stirling Office Convert has its own tests.
+ lenient().when(officeConversionService.legacy(null)).thenReturn(true);
lenient()
.when(tempFileManager.createManagedTempFile(anyString()))
.thenAnswer(
@@ -81,7 +85,7 @@ class ConvertPDFToExcelControllerTest {
Mockito.eq(true)))
.thenReturn(List.of(1));
- ResponseEntity<Resource> response = controller.pdfToExcel(request);
+ ResponseEntity<Resource> response = controller.pdfToExcel(request, null);
// tabula may or may not find tables in an empty page
assertNotNull(response);
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToOfficeMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToOfficeMoreTest.java
index be524e6aa0..034f9861a6 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToOfficeMoreTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToOfficeMoreTest.java
@@ -38,6 +38,7 @@ import org.springframework.mock.web.MockMultipartFile;
import stirling.software.SPDF.model.api.converters.PdfToPresentationRequest;
import stirling.software.SPDF.model.api.converters.PdfToTextOrRTFRequest;
import stirling.software.SPDF.model.api.converters.PdfToWordRequest;
+import stirling.software.SPDF.service.OfficeConversionService;
import stirling.software.common.configuration.RuntimePathConfig;
import stirling.software.common.model.api.PDFFile;
import stirling.software.common.service.CustomPDFDocumentFactory;
@@ -60,12 +61,15 @@ class ConvertPDFToOfficeMoreTest {
@Mock private CustomPDFDocumentFactory pdfDocumentFactory;
@Mock private TempFileManager tempFileManager;
+ @Mock private OfficeConversionService officeConversionService;
@Mock private RuntimePathConfig runtimePathConfig;
@InjectMocks private ConvertPDFToOffice controller;
@BeforeEach
void setUp() throws Exception {
+ // These cover the legacy converters; Stirling Office Convert has its own tests.
+ lenient().when(officeConversionService.legacy(null)).thenReturn(true);
// Real temp files backing TempFileManager so the file-backed response can be read back.
lenient()
.when(tempFileManager.createManagedTempFile(any()))
@@ -165,7 +169,8 @@ class ConvertPDFToOfficeMoreTest {
try (MockedStatic<ProcessExecutor> mockedFactory = mockStatic(ProcessExecutor.class)) {
stubLibreOfficeWritesOutput(mockedFactory, "pptx");
- ResponseEntity<Resource> response = controller.processPdfToPresentation(request);
+ ResponseEntity<Resource> response =
+ controller.processPdfToPresentation(request, null);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue(readResource(response.getBody()).length > 0);
@@ -179,7 +184,7 @@ class ConvertPDFToOfficeMoreTest {
request.setFileInput(nonPdfFile());
request.setOutputFormat("pptx");
- ResponseEntity<Resource> response = controller.processPdfToPresentation(request);
+ ResponseEntity<Resource> response = controller.processPdfToPresentation(request, null);
assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
}
@@ -202,7 +207,9 @@ class ConvertPDFToOfficeMoreTest {
ProcessExecutor.Processes.LIBRE_OFFICE))
.thenReturn(executor);
- assertThrows(IOException.class, () -> controller.processPdfToPresentation(request));
+ assertThrows(
+ IOException.class,
+ () -> controller.processPdfToPresentation(request, null));
}
}
}
@@ -221,7 +228,7 @@ class ConvertPDFToOfficeMoreTest {
try (MockedStatic<ProcessExecutor> mockedFactory = mockStatic(ProcessExecutor.class)) {
stubLibreOfficeWritesOutput(mockedFactory, "docx");
- ResponseEntity<Resource> response = controller.processPdfToWord(request);
+ ResponseEntity<Resource> response = controller.processPdfToWord(request, null);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue(readResource(response.getBody()).length > 0);
@@ -235,7 +242,7 @@ class ConvertPDFToOfficeMoreTest {
request.setFileInput(pdfFile());
request.setOutputFormat("bogus");
- ResponseEntity<Resource> response = controller.processPdfToWord(request);
+ ResponseEntity<Resource> response = controller.processPdfToWord(request, null);
assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
}
@@ -256,7 +263,7 @@ class ConvertPDFToOfficeMoreTest {
realDoc.addPage(new PDPage());
when(pdfDocumentFactory.load(any(MockMultipartFile.class))).thenReturn(realDoc);
- ResponseEntity<Resource> response = controller.processPdfToRTForTXT(request);
+ ResponseEntity<Resource> response = controller.processPdfToRTForTXT(request, null);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(MediaType.TEXT_PLAIN, response.getHeaders().getContentType());
@@ -272,7 +279,7 @@ class ConvertPDFToOfficeMoreTest {
try (MockedStatic<ProcessExecutor> mockedFactory = mockStatic(ProcessExecutor.class)) {
stubLibreOfficeWritesOutput(mockedFactory, "rtf");
- ResponseEntity<Resource> response = controller.processPdfToRTForTXT(request);
+ ResponseEntity<Resource> response = controller.processPdfToRTForTXT(request, null);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue(readResource(response.getBody()).length > 0);
@@ -290,7 +297,9 @@ class ConvertPDFToOfficeMoreTest {
.thenThrow(new IOException("cannot parse pdf"));
IOException thrown =
- assertThrows(IOException.class, () -> controller.processPdfToRTForTXT(request));
+ assertThrows(
+ IOException.class,
+ () -> controller.processPdfToRTForTXT(request, null));
assertEquals("cannot parse pdf", thrown.getMessage());
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToOfficeTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToOfficeTest.java
index 0bedd8f72a..0b2b13e90d 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToOfficeTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToOfficeTest.java
@@ -30,6 +30,7 @@ import org.springframework.mock.web.MockMultipartFile;
import stirling.software.SPDF.model.api.converters.PdfToPresentationRequest;
import stirling.software.SPDF.model.api.converters.PdfToTextOrRTFRequest;
import stirling.software.SPDF.model.api.converters.PdfToWordRequest;
+import stirling.software.SPDF.service.OfficeConversionService;
import stirling.software.common.configuration.RuntimePathConfig;
import stirling.software.common.model.api.PDFFile;
import stirling.software.common.service.CustomPDFDocumentFactory;
@@ -55,12 +56,15 @@ class ConvertPDFToOfficeTest {
@Mock private CustomPDFDocumentFactory pdfDocumentFactory;
@Mock private TempFileManager tempFileManager;
+ @Mock private OfficeConversionService officeConversionService;
@Mock private RuntimePathConfig runtimePathConfig;
@InjectMocks private ConvertPDFToOffice controller;
@BeforeEach
void setUp() throws Exception {
+ // These cover the legacy converters; Stirling Office Convert has its own tests.
+ lenient().when(officeConversionService.legacy(null)).thenReturn(true);
lenient()
.when(tempFileManager.createManagedTempFile(anyString()))
.thenAnswer(
@@ -131,7 +135,7 @@ class ConvertPDFToOfficeTest {
any(TempFile.class), anyString(), any(MediaType.class)))
.thenReturn(expectedResponse);
- ResponseEntity<Resource> response = controller.processPdfToRTForTXT(request);
+ ResponseEntity<Resource> response = controller.processPdfToRTForTXT(request, null);
assertSame(expectedResponse, response);
}
@@ -165,4 +169,42 @@ class ConvertPDFToOfficeTest {
file.setFileInput(pdfFile);
assertNotNull(file.getFileInput());
}
+
+ @Test
+ void processPdfToWord_usesOfficeConvertUnlessLegacy() throws Exception {
+ when(officeConversionService.replacesLibreOffice(null)).thenReturn(true);
+ MockMultipartFile pdfFile = createPdfFile();
+ when(pdfDocumentFactory.load(pdfFile)).thenReturn(new PDDocument());
+ PdfToWordRequest request = new PdfToWordRequest();
+ request.setFileInput(pdfFile);
+ request.setOutputFormat("docx");
+
+ try (MockedStatic<WebResponseUtils> wr = Mockito.mockStatic(WebResponseUtils.class)) {
+ wr.when(() -> WebResponseUtils.fileToWebResponse(any(), anyString(), any()))
+ .thenReturn(streamingOk("docx".getBytes()));
+
+ assertEquals(200, controller.processPdfToWord(request, null).getStatusCode().value());
+ }
+ Mockito.verify(officeConversionService)
+ .convert(any(PDDocument.class), any(), Mockito.eq("docx"), any());
+ }
+
+ @Test
+ void processPdfToRTForTXT_txtUsesOfficeConvertWhenNotLegacy() throws Exception {
+ when(officeConversionService.legacy(null)).thenReturn(false);
+ MockMultipartFile pdfFile = createPdfFile();
+ when(pdfDocumentFactory.load(pdfFile)).thenReturn(new PDDocument());
+ PdfToTextOrRTFRequest request = new PdfToTextOrRTFRequest();
+ request.setFileInput(pdfFile);
+ request.setOutputFormat("txt");
+
+ try (MockedStatic<WebResponseUtils> wr = Mockito.mockStatic(WebResponseUtils.class)) {
+ wr.when(() -> WebResponseUtils.fileToWebResponse(any(), anyString(), any()))
+ .thenReturn(streamingOk("txt".getBytes()));
+
+ controller.processPdfToRTForTXT(request, null);
+ }
+ Mockito.verify(officeConversionService)
+ .convert(any(PDDocument.class), any(), Mockito.eq("txt"), any());
+ }
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/service/OfficeConversionServiceTest.java b/app/core/src/test/java/stirling/software/SPDF/service/OfficeConversionServiceTest.java
new file mode 100644
index 0000000000..c084ae1314
--- /dev/null
+++ b/app/core/src/test/java/stirling/software/SPDF/service/OfficeConversionServiceTest.java
@@ -0,0 +1,133 @@
+package stirling.software.SPDF.service;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.zip.ZipFile;
+
+import org.apache.pdfbox.Loader;
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.PDPage;
+import org.apache.pdfbox.pdmodel.PDPageContentStream;
+import org.apache.pdfbox.pdmodel.font.PDType1Font;
+import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
+import org.apache.poi.xwpf.usermodel.XWPFDocument;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+
+import stirling.software.SPDF.config.EndpointConfiguration;
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.officeconvert.topdf.OfficeToPdf;
+
+class OfficeConversionServiceTest {
+
+ @TempDir Path dir;
+
+ private final ApplicationProperties properties = new ApplicationProperties();
+ private final EndpointConfiguration endpoints = mock(EndpointConfiguration.class);
+ private OfficeConversionService service;
+
+ @BeforeEach
+ void setUp() {
+ service = new OfficeConversionService(properties, endpoints);
+ }
+
+ @ParameterizedTest(name = "legacy={0}, LibreOffice={1} -> Stirling Office Convert {2}")
+ @CsvSource({"false,true,true", "false,false,true", "true,true,false", "true,false,false"})
+ void onlyTheFlagSwitchesToStirlingOfficeConvert(
+ boolean legacy, boolean libreOffice, boolean expected) {
+ properties.getSystem().setStirlingOfficeConversion(!legacy);
+ when(endpoints.isGroupEnabled("LibreOffice")).thenReturn(libreOffice);
+
+ assertThat(service.replacesLibreOffice()).isEqualTo(expected);
+ }
+
+ @Test
+ void aPerRequestChoiceOverridesTheSetting() {
+ assertThat(service.replacesLibreOffice(true)).isTrue();
+ assertThat(service.replacesLibreOffice(null)).isFalse();
+ properties.getSystem().setStirlingOfficeConversion(true);
+ assertThat(service.replacesLibreOffice(false)).isFalse();
+ assertThat(service.replacesLibreOffice(null)).isTrue();
+ }
+
+ @Test
+ void convertsPdfToWord() throws Exception {
+ Path docx = dir.resolve("out.docx");
+ try (PDDocument pdf = textPdf("Hello from Stirling")) {
+ service.convert(pdf, docx, "docx", service.settings());
+ }
+
+ try (ZipFile zip = new ZipFile(docx.toFile())) {
+ String body =
+ new String(
+ zip.getInputStream(zip.getEntry("word/document.xml")).readAllBytes());
+ assertThat(body).contains("Hello from Stirling");
+ }
+ }
+
+ @Test
+ void convertsWordToPdf() throws Exception {
+ Path docx = dir.resolve("in.docx");
+ try (XWPFDocument word = new XWPFDocument();
+ OutputStream out = Files.newOutputStream(docx)) {
+ word.createParagraph().createRun().setText("Office to PDF");
+ word.write(out);
+ }
+ Path pdf = dir.resolve("out.pdf");
+ properties.getSystem().setStirlingOfficeConversion(true);
+ OfficeToPdfService toPdf = new OfficeToPdfService(service, properties);
+
+ assertThat(toPdf.handles("docx")).isTrue();
+ toPdf.convert(docx, pdf);
+
+ try (PDDocument result = Loader.loadPDF(pdf.toFile())) {
+ assertThat(result.getNumberOfPages()).isEqualTo(1);
+ }
+ }
+
+ @Test
+ void leavesUnknownFormatsAndLegacyToLibreOffice() {
+ OfficeToPdfService toPdf = new OfficeToPdfService(service, properties);
+ assertThat(toPdf.handles("html")).isFalse();
+
+ properties.getSystem().setStirlingOfficeConversion(false);
+ when(endpoints.isGroupEnabled("LibreOffice")).thenReturn(true);
+ assertThat(toPdf.handles("docx")).isFalse();
+ }
+
+ @Test
+ void fallsBackOnlyWhenLibreOfficeCanHelp() {
+ OfficeToPdfService toPdf = new OfficeToPdfService(service, properties);
+ when(endpoints.isGroupEnabled("LibreOffice")).thenReturn(true);
+
+ assertThat(toPdf.canFallBack(new IOException("bad file"))).isTrue();
+ assertThat(toPdf.canFallBack(new IOException("wrapped", mock(OfficeToPdf.TimedOut.class))))
+ .isFalse();
+
+ when(endpoints.isGroupEnabled("LibreOffice")).thenReturn(false);
+ assertThat(toPdf.canFallBack(new IOException("bad file"))).isFalse();
+ }
+
+ private static PDDocument textPdf(String text) throws Exception {
+ PDDocument pdf = new PDDocument();
+ PDPage page = new PDPage();
+ pdf.addPage(page);
+ try (PDPageContentStream content = new PDPageContentStream(pdf, page)) {
+ content.beginText();
+ content.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12);
+ content.newLineAtOffset(72, 700);
+ content.showText(text);
+ content.endText();
+ }
+ return pdf;
+ }
+}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.java b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.java
index 97465d3805..044ac34b75 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/failure/FailureKind.java
@@ -168,7 +168,7 @@ public enum FailureKind {
FailureScope.SERVER,
// E080 (MD5 unavailable) is deliberately not claimed: its one thrower has no throws
// clause and its caller swallows it for a fallback hash, so it cannot reach a run.
- errorCodes("E042", "E062", "E063", "E064"),
+ errorCodes("E042", "E062", "E063", "E064", "E082"),
fallback("This server is missing software the step needs, so it could not be run."),
// Nothing for an owner to press: their document is fine, and a retry fails the same
// way until someone installs the binary.
diff --git a/build.gradle b/build.gradle
index 051e1246c8..bc0dd65195 100644
--- a/build.gradle
+++ b/build.gradle
@@ -23,6 +23,7 @@ import stirling.software.gradle.ModuleLicenseOverrideFilter
ext {
springBootVersion = "4.1.1"
pdfboxVersion = "3.0.8"
+ officeConvertVersion = "0.2.2"
imageioVersion = "3.15.2"
lombokVersion = "1.18.46"
bouncycastleVersion = "1.85"
diff --git a/engine/src/stirling/models/tool_models.py b/engine/src/stirling/models/tool_models.py
index b587d8bbd5..362149632e 100644
--- a/engine/src/stirling/models/tool_models.py
+++ b/engine/src/stirling/models/tool_models.py
@@ -648,9 +648,11 @@ class ExtractSingleAttachmentParams(ApiModel):
class FileToPdfParams(ApiModel):
"""
- This endpoint converts a given file to a PDF using LibreOffice API Input:ANY Output:PDF Type:SISO
+ This endpoint converts a given file to a PDF using Stirling Office Convert or LibreOffice Input:ANY Output:PDF Type:SISO
"""
+ use_stirling_office_convert: bool | None = None
+
class FlattenParams(ApiModel):
"""
@@ -1080,6 +1082,7 @@ class PdfToPresentationParams(ApiModel):
"""
output_format: OutputFormat2 = Field(..., description="The output Presentation format")
+ use_stirling_office_convert: bool | None = None
class PdfToSinglePageParams(ApiModel):
@@ -1103,6 +1106,7 @@ class PdfToTextParams(ApiModel):
"""
output_format: OutputFormat3 = Field(..., description="The output Text or RTF format")
+ use_stirling_office_convert: bool | None = None
class ExistingTags(StrEnum):
@@ -1213,6 +1217,7 @@ class PdfToWordParams(ApiModel):
"""
output_format: OutputFormat5 = Field(..., description="The output Word document format")
+ use_stirling_office_convert: bool | None = None
class PdfToXlsxParams(ApiModel):
@@ -1224,6 +1229,7 @@ class PdfToXlsxParams(ApiModel):
"all",
description="The pages to select, Supports ranges (e.g., '1,3,5-9'), or 'all' or functions in the format 'an+b' where 'a' is the multiplier of the page number 'n', and 'b' is a constant (e.g., '2n+1', '3n', '6n-5')",
)
+ use_stirling_office_convert: bool | None = None
class PdfToXmlParams(ApiModel):
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index f351f1fb38..977e46189c 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -667,6 +667,10 @@ label = "Session Limit"
description = "Maximum execution time"
label = "Timeout (minutes)"
+[admin.settings.advanced.stirlingOfficeConversion]
+description = "Stirling Office Convert is in beta. It offers better conversions, faster and with less memory than LibreOffice."
+label = "Use new Stirling Office conversion"
+
[admin.settings.advanced.tempFileManagement]
description = "Configure temporary file storage and cleanup behavior"
label = "Temp File Management"
@@ -4126,6 +4130,8 @@ selectSourceFormatFirst = "Choose a source format first"
settings = "Settings"
single = "Single"
sourceFormatPlaceholder = "Source format"
+stirlingOfficeConvert = "Use Stirling Office Convert (beta)"
+stirlingOfficeConvertDescription = "Better, faster conversions with less memory. Turn off to use the standard converter."
strictMode = "Strict Mode"
strictModeDesc = "Error if conversion is not perfect (uses VeraPDF verification)"
svgPdfOptions = "SVG to PDF Options"
diff --git a/frontend/editor/src/core/components/tools/convert/ConvertOfficeEngineSettings.tsx b/frontend/editor/src/core/components/tools/convert/ConvertOfficeEngineSettings.tsx
new file mode 100644
index 0000000000..a0ff343c3c
--- /dev/null
+++ b/frontend/editor/src/core/components/tools/convert/ConvertOfficeEngineSettings.tsx
@@ -0,0 +1,51 @@
+import { Switch } from "@mantine/core";
+import { useTranslation } from "react-i18next";
+import { useAppConfig } from "@app/contexts/AppConfigContext";
+import { ConvertParameters } from "@app/hooks/tools/convert/useConvertParameters";
+
+interface ConvertOfficeEngineSettingsProps {
+ parameters: ConvertParameters;
+ onParameterChange: <K extends keyof ConvertParameters>(
+ key: K,
+ value: ConvertParameters[K],
+ ) => void;
+ disabled?: boolean;
+}
+
+/** Picks Stirling Office Convert or LibreOffice for this conversion; starts from the server setting. */
+const ConvertOfficeEngineSettings = ({
+ parameters,
+ onParameterChange,
+ disabled = false,
+}: ConvertOfficeEngineSettingsProps) => {
+ const { t } = useTranslation();
+ const { config } = useAppConfig();
+ const checked =
+ parameters.useStirlingOfficeConvert ??
+ config?.stirlingOfficeConversion ??
+ false;
+
+ return (
+ <Switch
+ data-testid="stirling-office-convert-switch"
+ label={t(
+ "convert.stirlingOfficeConvert",
+ "Use Stirling Office Convert (beta)",
+ )}
+ description={t(
+ "convert.stirlingOfficeConvertDescription",
+ "Better, faster conversions with less memory. Turn off to use the standard converter.",
+ )}
+ checked={checked}
+ onChange={(event) =>
+ onParameterChange(
+ "useStirlingOfficeConvert",
+ event.currentTarget.checked,
+ )
+ }
+ disabled={disabled}
+ />
+ );
+};
+
+export default ConvertOfficeEngineSettings;
diff --git a/frontend/editor/src/core/components/tools/convert/ConvertSettings.tsx b/frontend/editor/src/core/components/tools/convert/ConvertSettings.tsx
index 581d679304..1b1667e1b0 100644
--- a/frontend/editor/src/core/components/tools/convert/ConvertSettings.tsx
+++ b/frontend/editor/src/core/components/tools/convert/ConvertSettings.tsx
@@ -8,6 +8,7 @@ import {
isImageFormat,
isWebFormat,
getAvailableToExtensions as defaultGetAvailableToExtensions,
+ usesOfficeEngine,
} from "@app/utils/convertUtils";
import { getConversionEndpoints } from "@app/data/toolsTaxonomy";
import { usePreferences } from "@app/contexts/PreferencesContext";
@@ -27,6 +28,7 @@ import ConvertToCbrSettings from "@app/components/tools/convert/ConvertToCbrSett
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 ConvertOfficeEngineSettings from "@app/components/tools/convert/ConvertOfficeEngineSettings";
import { ConvertParameters } from "@app/hooks/tools/convert/useConvertParameters";
import {
FROM_FORMAT_OPTIONS,
@@ -523,6 +525,18 @@ const ConvertSettings = ({
</>
)}
+ {/* Stirling Office Convert or LibreOffice */}
+ {usesOfficeEngine(parameters.fromExtension, parameters.toExtension) && (
+ <>
+ <Divider />
+ <ConvertOfficeEngineSettings
+ parameters={parameters}
+ onParameterChange={onParameterChange}
+ disabled={disabled}
+ />
+ </>
+ )}
+
{/* PDF to EPUB/AZW3 options */}
{parameters.fromExtension === "pdf" &&
["epub", "azw3"].includes(parameters.toExtension) && (
diff --git a/frontend/editor/src/core/hooks/tools/convert/useConvertOperation.ts b/frontend/editor/src/core/hooks/tools/convert/useConvertOperation.ts
index 4d54b438f4..59c367f105 100644
--- a/frontend/editor/src/core/hooks/tools/convert/useConvertOperation.ts
+++ b/frontend/editor/src/core/hooks/tools/convert/useConvertOperation.ts
@@ -18,6 +18,7 @@ import {
isImageFormat,
isWebFormat,
isOfficeFormat,
+ usesOfficeEngine,
} from "@app/utils/convertUtils";
import {
isToolEndpoint,
@@ -112,6 +113,16 @@ export const buildConvertFormData = (
formData.append("fileInput", file);
});
+ if (
+ parameters.useStirlingOfficeConvert !== undefined &&
+ usesOfficeEngine(fromExtension, toExtension)
+ ) {
+ formData.append(
+ "useStirlingOfficeConvert",
+ String(parameters.useStirlingOfficeConvert),
+ );
+ }
+
if (isImageFormat(toExtension)) {
formData.append("imageFormat", toExtension);
formData.append("colorType", imageOptions.colorType);
diff --git a/frontend/editor/src/core/hooks/tools/convert/useConvertParameters.ts b/frontend/editor/src/core/hooks/tools/convert/useConvertParameters.ts
index 6c4d1ffe9e..0f85b06707 100644
--- a/frontend/editor/src/core/hooks/tools/convert/useConvertParameters.ts
+++ b/frontend/editor/src/core/hooks/tools/convert/useConvertParameters.ts
@@ -81,6 +81,8 @@ export interface ConvertParameters extends BaseParameters {
targetDevice: string;
outputFormat: string;
};
+ /** Per-request engine pick; undefined follows the server setting. */
+ useStirlingOfficeConvert?: boolean;
isSmartDetection: boolean;
smartDetectionType: "mixed" | "images" | "web" | "none";
}
diff --git a/frontend/editor/src/core/services/notificationRetry.ts b/frontend/editor/src/core/services/notificationRetry.ts
index 883be4d6e2..7008b6a985 100644
--- a/frontend/editor/src/core/services/notificationRetry.ts
+++ b/frontend/editor/src/core/services/notificationRetry.ts
@@ -54,7 +54,7 @@ export const KIND_ERROR_CODES: Record<string, readonly string[]> = {
INPUT_UNREADABLE: ["E010", "E015", "E021", "E034"],
INPUT_EMPTY: ["E005", "E012", "E016", "E020", "E032"],
INPUT_UNAVAILABLE: ["E030", "E033"],
- TOOL_NOT_INSTALLED: ["E042", "E062", "E063", "E064"],
+ TOOL_NOT_INSTALLED: ["E042", "E062", "E063", "E064", "E082"],
STEP_CANNOT_RENDER_PAGE: ["E054"],
STEP_TOOL_FAILED: ["E044", "E051", "E052", "E060"],
STEP_INTERRUPTED: ["E053"],
diff --git a/frontend/editor/src/core/types/appConfig.ts b/frontend/editor/src/core/types/appConfig.ts
index 3b840ebd70..e47b909bd4 100644
--- a/frontend/editor/src/core/types/appConfig.ts
+++ b/frontend/editor/src/core/types/appConfig.ts
@@ -14,6 +14,7 @@ export interface AppConfig {
isAdmin?: boolean;
shouldShowUpdate?: boolean;
enableAlphaFunctionality?: boolean;
+ stirlingOfficeConversion?: boolean;
enableAnalytics?: boolean | null;
enablePosthog?: boolean | null;
enableScarf?: boolean | null;
diff --git a/frontend/editor/src/core/types/toolApiTypes.ts b/frontend/editor/src/core/types/toolApiTypes.ts
index 04eed03fec..95ea5d6073 100644
--- a/frontend/editor/src/core/types/toolApiTypes.ts
+++ b/frontend/editor/src/core/types/toolApiTypes.ts
@@ -577,7 +577,9 @@ export interface FormFormDetectionDetectRequest {
confThreshold?: number;
}
export type GeneralExtractBookmarksRequest = Record<string, never>;
-export type GeneralFile = Record<string, never>;
+export interface GeneralFile {
+ useStirlingOfficeConvert?: boolean;
+}
export type GeneralPdfToSinglePageRequest = Record<string, never>;
export type GeneralRemoveImagePdfRequest = Record<string, never>;
export interface HTMLToPdfRequest {
@@ -1019,18 +1021,21 @@ export interface PdfToPresentationRequest {
* The output Presentation format
*/
outputFormat: "ppt" | "pptx" | "odp";
+ useStirlingOfficeConvert?: boolean;
}
export interface PdfToTextOrRTFRequest {
/**
* The output Text or RTF format
*/
outputFormat: "rtf" | "txt";
+ useStirlingOfficeConvert?: boolean;
}
export interface PdfToWordRequest {
/**
* The output Word document format
*/
outputFormat: "doc" | "docx" | "odt";
+ useStirlingOfficeConvert?: boolean;
}
export interface PdfVectorExportRequest {
/**
diff --git a/frontend/editor/src/core/types/toolIO.ts b/frontend/editor/src/core/types/toolIO.ts
index 6a27f7129a..c2add8f07d 100644
--- a/frontend/editor/src/core/types/toolIO.ts
+++ b/frontend/editor/src/core/types/toolIO.ts
@@ -192,11 +192,16 @@ export const TOOL_IO: ToolIOTable = {
"emf",
"gif",
"ico",
+ "j2c",
+ "j2k",
"jb2",
"jbig2",
"jp2",
+ "jpc",
"jpeg",
+ "jpf",
"jpg",
+ "jpx",
"pbm",
"pcx",
"pgm",
diff --git a/frontend/editor/src/core/utils/convertUtils.ts b/frontend/editor/src/core/utils/convertUtils.ts
index 8086986621..0a6f0b57aa 100644
--- a/frontend/editor/src/core/utils/convertUtils.ts
+++ b/frontend/editor/src/core/utils/convertUtils.ts
@@ -26,6 +26,40 @@ export const getEndpointName = (
return endpointKey || "";
};
+const OFFICE_ENGINE_ENDPOINTS = [
+ "pdf-to-word",
+ "pdf-to-presentation",
+ "pdf-to-text",
+ "pdf-to-xlsx",
+];
+
+const OFFICE_EXTENSIONS = [
+ "doc",
+ "docx",
+ "odt",
+ "rtf",
+ "txt",
+ "xls",
+ "xlsx",
+ "ods",
+ "csv",
+ "ppt",
+ "pptx",
+ "odp",
+];
+
+/** Whether the conversion can run on Stirling Office Convert instead of LibreOffice. */
+export const usesOfficeEngine = (
+ fromExtension: string,
+ toExtension: string,
+): boolean => {
+ const endpoint = getEndpointName(fromExtension, toExtension);
+ if (endpoint === "file-to-pdf") {
+ return OFFICE_EXTENSIONS.includes(fromExtension);
+ }
+ return OFFICE_ENGINE_ENDPOINTS.includes(endpoint);
+};
+
/**
* Resolves the full endpoint URL for a given conversion
*/
diff --git a/frontend/editor/src/core/utils/officeEngine.test.ts b/frontend/editor/src/core/utils/officeEngine.test.ts
new file mode 100644
index 0000000000..83bff8f7f7
--- /dev/null
+++ b/frontend/editor/src/core/utils/officeEngine.test.ts
@@ -0,0 +1,40 @@
+import { describe, test, expect } from "vitest";
+import { usesOfficeEngine } from "@app/utils/convertUtils";
+import { buildConvertFormData } from "@app/hooks/tools/convert/useConvertOperation";
+import { defaultParameters } from "@app/hooks/tools/convert/useConvertParameters";
+
+describe("Stirling Office Convert switch", () => {
+ test("applies to Office conversions only", () => {
+ expect(usesOfficeEngine("pdf", "docx")).toBe(true);
+ expect(usesOfficeEngine("pdf", "pptx")).toBe(true);
+ expect(usesOfficeEngine("pdf", "xlsx")).toBe(true);
+ expect(usesOfficeEngine("docx", "pdf")).toBe(true);
+ expect(usesOfficeEngine("html", "pdf")).toBe(false);
+ expect(usesOfficeEngine("pdf", "png")).toBe(false);
+ });
+
+ test("sends the choice only when one was made", () => {
+ const file = new File(["x"], "a.pdf", { type: "application/pdf" });
+ const base = {
+ ...defaultParameters,
+ fromExtension: "pdf",
+ toExtension: "docx",
+ };
+ expect(
+ buildConvertFormData(base, [file]).has("useStirlingOfficeConvert"),
+ ).toBe(false);
+ const chosen = buildConvertFormData(
+ { ...base, useStirlingOfficeConvert: true },
+ [file],
+ );
+ expect(chosen.get("useStirlingOfficeConvert")).toBe("true");
+ const image = {
+ ...base,
+ toExtension: "png",
+ useStirlingOfficeConvert: true,
+ };
+ expect(
+ buildConvertFormData(image, [file]).has("useStirlingOfficeConvert"),
+ ).toBe(false);
+ });
+});
diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdminAdvancedPage.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdminAdvancedPage.tsx
index 51f8322373..92028fd0d0 100644
--- a/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdminAdvancedPage.tsx
+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdminAdvancedPage.tsx
@@ -64,6 +64,7 @@ export default function AdminAdvancedPage() {
enableUrlToPDF: systemData.enableUrlToPDF || false,
tessdataDir: systemData.tessdataDir || "",
disableSanitize: systemData.disableSanitize || false,
+ stirlingOfficeConversion: systemData.stirlingOfficeConversion || false,
tempFileManagement: systemData.tempFileManagement || {
baseTmpDir: "",
libreofficeDir: "",
@@ -95,6 +96,10 @@ export default function AdminAdvancedPage() {
if (systemData._pending?.disableSanitize !== undefined) {
pendingBlock.disableSanitize = systemData._pending.disableSanitize;
}
+ if (systemData._pending?.stirlingOfficeConversion !== undefined) {
+ pendingBlock.stirlingOfficeConversion =
+ systemData._pending.stirlingOfficeConversion;
+ }
if (systemData._pending?.tempFileManagement) {
pendingBlock.tempFileManagement =
systemData._pending.tempFileManagement;
@@ -116,6 +121,7 @@ export default function AdminAdvancedPage() {
"system.enableUrlToPDF": settings.enableUrlToPDF,
"system.tessdataDir": settings.tessdataDir,
"system.disableSanitize": settings.disableSanitize,
+ "system.stirlingOfficeConversion": settings.stirlingOfficeConversion,
};
// Add temp file management settings
diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdvancedFeatureFlagsCard.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdvancedFeatureFlagsCard.tsx
index f5315a0f39..0ce5a73241 100644
--- a/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdvancedFeatureFlagsCard.tsx
+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/AdvancedFeatureFlagsCard.tsx
@@ -4,7 +4,7 @@ import { Stack, Paper } from "@mantine/core";
import { useLoginRequired } from "@app/hooks/useLoginRequired";
import type { AdvancedCardProps } from "@app/components/shared/config/configSections/advanced/advancedCardProps";
-/** Server-wide switches. All three need a restart to take effect. */
+/** Server-wide switches. All need a restart to take effect. */
export function AdvancedFeatureFlagsCard({
settings,
setSettings,
@@ -82,6 +82,28 @@ export function AdvancedFeatureFlagsCard({
disabled={!loginEnabled}
styles={getDisabledStyles()}
/>
+
+ <SettingsToggleRow
+ label={t(
+ "admin.settings.advanced.stirlingOfficeConversion.label",
+ "Use new Stirling Office conversion",
+ )}
+ info={t(
+ "admin.settings.advanced.stirlingOfficeConversion.description",
+ "Stirling Office Convert is in beta. It offers better conversions, faster and with less memory than LibreOffice.",
+ )}
+ pending={isFieldPending("stirlingOfficeConversion")}
+ checked={settings.stirlingOfficeConversion || false}
+ onChange={(checked) => {
+ if (!loginEnabled) return;
+ setSettings({
+ ...settings,
+ stirlingOfficeConversion: checked,
+ });
+ }}
+ disabled={!loginEnabled}
+ styles={getDisabledStyles()}
+ />
</Stack>
</Paper>
);
diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/advancedSettings.ts b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/advancedSettings.ts
index 5ed9e8f3a7..ea29002704 100644
--- a/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/advancedSettings.ts
+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/advanced/advancedSettings.ts
@@ -42,6 +42,7 @@ export interface AdvancedSettingsData {
enableUrlToPDF?: boolean;
tessdataDir?: string;
disableSanitize?: boolean;
+ stirlingOfficeConversion?: boolean;
tempFileManagement?: {
baseTmpDir?: string;
libreofficeDir?: string;
diff --git a/testing/failure-kind-codes.json b/testing/failure-kind-codes.json
index 658573e935..028496dca2 100644
--- a/testing/failure-kind-codes.json
+++ b/testing/failure-kind-codes.json
@@ -15,7 +15,7 @@
"INPUT_UNREADABLE": ["E010", "E015", "E021", "E034"],
"INPUT_EMPTY": ["E005", "E012", "E016", "E020", "E032"],
"INPUT_UNAVAILABLE": ["E030", "E033"],
- "TOOL_NOT_INSTALLED": ["E042", "E062", "E063", "E064"],
+ "TOOL_NOT_INSTALLED": ["E042", "E062", "E063", "E064", "E082"],
"STEP_CANNOT_RENDER_PAGE": ["E054"],
"STEP_TOOL_FAILED": ["E044", "E051", "E052", "E060"],
"STEP_INTERRUPTED": ["E053"],