Skip to content

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

Honour LibreOffice removal in PDF to Office conversions (#8665)

ConnorYoh78bea24f2295
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 4e3b6b2294..f4e401d3b9 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
@@ -1332,7 +1332,7 @@ public class ExceptionUtils {
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."),
+ "LibreOffice is needed to convert .{0} files but is not available. Install LibreOffice and ensure it is on the system PATH, or ask an administrator to re-enable the LibreOffice tool group."),
// Validation errors
INVALID_ARGUMENT("E070", "error.invalidArgument", "Invalid argument ''{0}'': {1}"),
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 f0190b6a5d..f5d8e1461e 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
@@ -8,16 +8,19 @@ import java.util.Set;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.core.io.Resource;
+import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
+import org.springframework.web.server.ResponseStatusException;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
+import stirling.software.SPDF.config.EndpointConfiguration;
import stirling.software.SPDF.model.api.converters.PdfToPresentationRequest;
import stirling.software.SPDF.model.api.converters.PdfToTextOrRTFRequest;
import stirling.software.SPDF.model.api.converters.PdfToWordRequest;
@@ -33,6 +36,7 @@ import stirling.software.common.model.tool.ToolIO;
import stirling.software.common.model.tool.ToolIOCase;
import stirling.software.common.model.tool.ToolIOWhen;
import stirling.software.common.service.CustomPDFDocumentFactory;
+import stirling.software.common.util.ExceptionUtils;
import stirling.software.common.util.GeneralUtils;
import stirling.software.common.util.PDFToFile;
import stirling.software.common.util.TempFile;
@@ -47,6 +51,7 @@ public class ConvertPDFToOffice {
private final TempFileManager tempFileManager;
private final RuntimePathConfig runtimePathConfig;
private final OfficeConversionService officeConversionService;
+ private final EndpointConfiguration endpointConfiguration;
@AutoJobPostMapping(
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
@@ -70,8 +75,8 @@ public class ConvertPDFToOffice {
Set.of("ppt", "pptx", "odp"),
MediaType.APPLICATION_OCTET_STREAM);
}
- PDFToFile pdfToFile = new PDFToFile(tempFileManager, runtimePathConfig);
- return pdfToFile.processPdfToOfficeFormat(inputFile, outputFormat, "impress_pdf_import");
+ return convertWithLibreOffice(
+ inputFile, outputFormat, Set.of("ppt", "pptx", "odp"), "impress_pdf_import");
}
@AutoJobPostMapping(
@@ -96,6 +101,11 @@ public class ConvertPDFToOffice {
MultipartFile inputFile = request.getFileInput();
String outputFormat = request.getOutputFormat();
boolean plainText = "txt".equals(outputFormat);
+ // The interceptor only sees pdf-to-text; RTF has its own key, which removal must honour.
+ // Other formats are left to the 400 below.
+ if ("rtf".equals(outputFormat) && !endpointConfiguration.isEndpointEnabled("pdf-to-rtf")) {
+ throw new ResponseStatusException(HttpStatus.FORBIDDEN, "This endpoint is disabled");
+ }
// Legacy text came from PDFBox, not LibreOffice, so it never needs the fallback.
boolean officeConvert =
plainText
@@ -122,8 +132,8 @@ public class ConvertPDFToOffice {
}
return WebResponseUtils.fileToWebResponse(finalOut, fileName, MediaType.TEXT_PLAIN);
} else {
- PDFToFile pdfToFile = new PDFToFile(tempFileManager, runtimePathConfig);
- return pdfToFile.processPdfToOfficeFormat(inputFile, outputFormat, "writer_pdf_import");
+ return convertWithLibreOffice(
+ inputFile, outputFormat, Set.of("rtf"), "writer_pdf_import");
}
}
@@ -149,8 +159,8 @@ public class ConvertPDFToOffice {
Set.of("doc", "docx", "odt"),
MediaType.APPLICATION_OCTET_STREAM);
}
- PDFToFile pdfToFile = new PDFToFile(tempFileManager, runtimePathConfig);
- return pdfToFile.processPdfToOfficeFormat(inputFile, outputFormat, "writer_pdf_import");
+ return convertWithLibreOffice(
+ inputFile, outputFormat, Set.of("doc", "docx", "odt"), "writer_pdf_import");
}
@AutoJobPostMapping(
@@ -164,8 +174,26 @@ public class ConvertPDFToOffice {
public ResponseEntity<Resource> processPdfToXML(@ModelAttribute PDFFile file) throws Exception {
MultipartFile inputFile = file.getFileInput();
+ return convertWithLibreOffice(inputFile, "xml", Set.of("xml"), "writer_pdf_import");
+ }
+
+ /**
+ * Every LibreOffice run goes through here. The endpoint gate sees only the URL, so it cannot
+ * tell which formats a request asks for or that a caller picked LibreOffice over Stirling
+ * Office Convert; this keeps each endpoint to its own formats and refuses when the LibreOffice
+ * group is off.
+ */
+ private ResponseEntity<Resource> convertWithLibreOffice(
+ MultipartFile input, String format, Set<String> formats, String filter)
+ throws IOException, InterruptedException {
+ if (format == null || !formats.contains(format)) {
+ return ResponseEntity.badRequest().build();
+ }
+ if (!officeConversionService.libreOfficeAvailable()) {
+ throw ExceptionUtils.createLibreOfficeRequiredException("pdf");
+ }
PDFToFile pdfToFile = new PDFToFile(tempFileManager, runtimePathConfig);
- return pdfToFile.processPdfToOfficeFormat(inputFile, "xml", "writer_pdf_import");
+ return pdfToFile.processPdfToOfficeFormat(input, format, filter);
}
private ResponseEntity<Resource> convert(
@@ -173,7 +201,7 @@ public class ConvertPDFToOffice {
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)) {
+ if (format == null || !formats.contains(format) || !pdf && !"txt".equals(format)) {
return ResponseEntity.badRequest().build();
}
TempFile out = tempFileManager.createManagedTempFile("." + format);
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 034f9861a6..d034e38291 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
@@ -34,7 +34,9 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
+import org.springframework.web.server.ResponseStatusException;
+import stirling.software.SPDF.config.EndpointConfiguration;
import stirling.software.SPDF.model.api.converters.PdfToPresentationRequest;
import stirling.software.SPDF.model.api.converters.PdfToTextOrRTFRequest;
import stirling.software.SPDF.model.api.converters.PdfToWordRequest;
@@ -42,6 +44,7 @@ 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;
+import stirling.software.common.util.ExceptionUtils.ToolRequiredException;
import stirling.software.common.util.ProcessExecutor;
import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;
import stirling.software.common.util.TempFile;
@@ -63,6 +66,7 @@ class ConvertPDFToOfficeMoreTest {
@Mock private TempFileManager tempFileManager;
@Mock private OfficeConversionService officeConversionService;
@Mock private RuntimePathConfig runtimePathConfig;
+ @Mock private EndpointConfiguration endpointConfiguration;
@InjectMocks private ConvertPDFToOffice controller;
@@ -70,6 +74,8 @@ class ConvertPDFToOfficeMoreTest {
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(officeConversionService.libreOfficeAvailable()).thenReturn(true);
+ lenient().when(endpointConfiguration.isEndpointEnabled("pdf-to-rtf")).thenReturn(true);
// Real temp files backing TempFileManager so the file-backed response can be read back.
lenient()
.when(tempFileManager.createManagedTempFile(any()))
@@ -304,6 +310,121 @@ class ConvertPDFToOfficeMoreTest {
}
}
+ @Nested
+ @DisplayName("LibreOffice gate")
+ class LibreOfficeGate {
+
+ private PdfToTextOrRTFRequest textRequest(String format) {
+ PdfToTextOrRTFRequest request = new PdfToTextOrRTFRequest();
+ request.setFileInput(pdfFile());
+ request.setOutputFormat(format);
+ return request;
+ }
+
+ @Test
+ @DisplayName("rtf answers 403 when pdf-to-rtf is disabled, without running LibreOffice")
+ void rtfRefusedWhenItsEndpointIsDisabled() {
+ when(endpointConfiguration.isEndpointEnabled("pdf-to-rtf")).thenReturn(false);
+
+ try (MockedStatic<ProcessExecutor> mockedFactory = mockStatic(ProcessExecutor.class)) {
+ ResponseStatusException thrown =
+ assertThrows(
+ ResponseStatusException.class,
+ () -> controller.processPdfToRTForTXT(textRequest("rtf"), null));
+ assertEquals(HttpStatus.FORBIDDEN, thrown.getStatusCode());
+ mockedFactory.verifyNoInteractions();
+ }
+ }
+
+ @Test
+ @DisplayName("txt still converts when pdf-to-rtf is disabled")
+ void txtUnaffectedByRtfRemoval() throws Exception {
+ when(endpointConfiguration.isEndpointEnabled("pdf-to-rtf")).thenReturn(false);
+ PDDocument realDoc = new PDDocument();
+ realDoc.addPage(new PDPage());
+ when(pdfDocumentFactory.load(any(MockMultipartFile.class))).thenReturn(realDoc);
+
+ ResponseEntity<Resource> response =
+ controller.processPdfToRTForTXT(textRequest("txt"), null);
+
+ assertEquals(HttpStatus.OK, response.getStatusCode());
+ }
+
+ @Test
+ @DisplayName("an invalid format is still a 400 when pdf-to-rtf is disabled")
+ void invalidFormatIsBadRequestWhenRtfRemoved() throws Exception {
+ when(endpointConfiguration.isEndpointEnabled("pdf-to-rtf")).thenReturn(false);
+
+ try (MockedStatic<ProcessExecutor> mockedFactory = mockStatic(ProcessExecutor.class)) {
+ for (String format : new String[] {"docx", null}) {
+ assertEquals(
+ HttpStatus.BAD_REQUEST,
+ controller
+ .processPdfToRTForTXT(textRequest(format), null)
+ .getStatusCode(),
+ String.valueOf(format));
+ }
+ mockedFactory.verifyNoInteractions();
+ }
+ }
+
+ @Test
+ @DisplayName("text endpoint no longer serves the Word and XML formats")
+ void textEndpointRejectsOtherOfficeFormats() throws Exception {
+ try (MockedStatic<ProcessExecutor> mockedFactory = mockStatic(ProcessExecutor.class)) {
+ for (String format : new String[] {"doc", "docx", "odt", "xml"}) {
+ assertEquals(
+ HttpStatus.BAD_REQUEST,
+ controller
+ .processPdfToRTForTXT(textRequest(format), null)
+ .getStatusCode(),
+ format);
+ }
+ mockedFactory.verifyNoInteractions();
+ }
+ }
+
+ @Test
+ @DisplayName("word endpoint rejects xml")
+ void wordEndpointRejectsXml() throws Exception {
+ PdfToWordRequest request = new PdfToWordRequest();
+ request.setFileInput(pdfFile());
+ request.setOutputFormat("xml");
+
+ assertEquals(
+ HttpStatus.BAD_REQUEST,
+ controller.processPdfToWord(request, null).getStatusCode());
+ }
+
+ @Test
+ @DisplayName("every LibreOffice branch asks for LibreOffice when its group is off")
+ void libreOfficeBranchesRefuseWhenUnavailable() {
+ when(officeConversionService.libreOfficeAvailable()).thenReturn(false);
+ PdfToWordRequest word = new PdfToWordRequest();
+ word.setFileInput(pdfFile());
+ word.setOutputFormat("docx");
+ PdfToPresentationRequest presentation = new PdfToPresentationRequest();
+ presentation.setFileInput(pdfFile());
+ presentation.setOutputFormat("pptx");
+ PDFFile xml = new PDFFile();
+ xml.setFileInput(pdfFile());
+
+ try (MockedStatic<ProcessExecutor> mockedFactory = mockStatic(ProcessExecutor.class)) {
+ assertThrows(
+ ToolRequiredException.class,
+ () -> controller.processPdfToRTForTXT(textRequest("rtf"), null));
+ assertThrows(
+ ToolRequiredException.class,
+ () -> controller.processPdfToWord(word, false));
+ assertThrows(
+ ToolRequiredException.class,
+ () -> controller.processPdfToPresentation(presentation, false));
+ assertThrows(ToolRequiredException.class, () -> controller.processPdfToXML(xml));
+ mockedFactory.verifyNoInteractions();
+ }
+ }
+ }
+
@Nested
@DisplayName("XML conversion")
class XmlConversion {
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 0b2b13e90d..d1c542a8d9 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
@@ -27,6 +27,7 @@ import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
+import stirling.software.SPDF.config.EndpointConfiguration;
import stirling.software.SPDF.model.api.converters.PdfToPresentationRequest;
import stirling.software.SPDF.model.api.converters.PdfToTextOrRTFRequest;
import stirling.software.SPDF.model.api.converters.PdfToWordRequest;
@@ -58,6 +59,7 @@ class ConvertPDFToOfficeTest {
@Mock private TempFileManager tempFileManager;
@Mock private OfficeConversionService officeConversionService;
@Mock private RuntimePathConfig runtimePathConfig;
+ @Mock private EndpointConfiguration endpointConfiguration;
@InjectMocks private ConvertPDFToOffice controller;
@@ -65,6 +67,8 @@ class ConvertPDFToOfficeTest {
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(officeConversionService.libreOfficeAvailable()).thenReturn(true);
+ lenient().when(endpointConfiguration.isEndpointEnabled("pdf-to-rtf")).thenReturn(true);
lenient()
.when(tempFileManager.createManagedTempFile(anyString()))
.thenAnswer(
@@ -189,6 +193,17 @@ class ConvertPDFToOfficeTest {
.convert(any(PDDocument.class), any(), Mockito.eq("docx"), any());
}
+ @Test
+ void officeConvertWithoutOutputFormatIsBadRequest() throws Exception {
+ when(officeConversionService.replacesLibreOffice(null)).thenReturn(true);
+ PdfToWordRequest request = new PdfToWordRequest();
+ request.setFileInput(createPdfFile());
+
+ assertEquals(400, controller.processPdfToWord(request, null).getStatusCode().value());
+ Mockito.verify(officeConversionService, Mockito.never())
+ .convert(any(PDDocument.class), any(), any(), any());
+ }
+
@Test
void processPdfToRTForTXT_txtUsesOfficeConvertWhenNotLegacy() throws Exception {
when(officeConversionService.legacy(null)).thenReturn(false);
diff --git a/frontend/src/editor/core/constants/convertConstants.ts b/frontend/src/editor/core/constants/convertConstants.ts
index 8a6ef30f49..d26ebf7b49 100644
--- a/frontend/src/editor/core/constants/convertConstants.ts
+++ b/frontend/src/editor/core/constants/convertConstants.ts
@@ -25,6 +25,7 @@ export const CONVERSION_ENDPOINTS = {
"pdf-office-word": "/api/v1/convert/pdf/word",
"pdf-office-presentation": "/api/v1/convert/pdf/presentation",
"pdf-office-text": "/api/v1/convert/pdf/text",
+ "pdf-office-rtf": "/api/v1/convert/pdf/text",
"pdf-csv": "/api/v1/convert/pdf/csv",
"pdf-xlsx": "/api/v1/convert/pdf/xlsx",
"pdf-markdown": "/api/v1/convert/pdf/markdown",
@@ -51,6 +52,8 @@ export const ENDPOINT_NAMES = {
"pdf-office-word": "pdf-to-word",
"pdf-office-presentation": "pdf-to-presentation",
"pdf-office-text": "pdf-to-text",
+ // Same URL as text; RTF has its own endpoint key, which an admin can switch off on its own
+ "pdf-office-rtf": "pdf-to-rtf",
"pdf-csv": "pdf-to-csv",
"pdf-xlsx": "pdf-to-xlsx",
"pdf-markdown": "pdf-to-markdown",
@@ -76,6 +79,7 @@ export const ENDPOINT_I18N: Record<string, [string, string]> = {
"pdf-to-word": ["PDFToWord.header", "PDF → Word"],
"pdf-to-presentation": ["PDFToPresentation.header", "PDF → Presentation"],
"pdf-to-text": ["PDFToText.header", "PDF → Text"],
+ "pdf-to-rtf": ["PDFToText.header", "PDF → RTF"],
"pdf-to-csv": ["PDFToCSV.header", "PDF → CSV"],
"pdf-to-xlsx": ["PDFToXLSX.header", "PDF → Excel"],
"pdf-to-markdown": ["PDFToMarkdown.header", "PDF → Markdown"],
@@ -269,7 +273,7 @@ export const EXTENSION_TO_ENDPOINT: Record<string, Record<string, string>> = {
csv: "pdf-to-csv",
xlsx: "pdf-to-xlsx",
txt: "pdf-to-text",
- rtf: "pdf-to-text",
+ rtf: "pdf-to-rtf",
md: "pdf-to-markdown",
html: "pdf-to-html",
xml: "pdf-to-xml",
diff --git a/frontend/src/editor/core/data/useTranslatedToolRegistry.tsx b/frontend/src/editor/core/data/useTranslatedToolRegistry.tsx
index f5f2503856..f63e8a6acd 100644
--- a/frontend/src/editor/core/data/useTranslatedToolRegistry.tsx
+++ b/frontend/src/editor/core/data/useTranslatedToolRegistry.tsx
@@ -1192,6 +1192,7 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {
"pdf-to-word",
"pdf-to-presentation",
"pdf-to-text",
+ "pdf-to-rtf",
"pdf-to-html",
"pdf-to-xml",
"html-to-pdf",
diff --git a/frontend/src/editor/core/hooks/tools/convert/useConvertOperation.ts b/frontend/src/editor/core/hooks/tools/convert/useConvertOperation.ts
index d44ef7f8a7..f62c2af40f 100644
--- a/frontend/src/editor/core/hooks/tools/convert/useConvertOperation.ts
+++ b/frontend/src/editor/core/hooks/tools/convert/useConvertOperation.ts
@@ -293,6 +293,11 @@ export const convertProcessor = async (
if (!endpoint) {
throw new Error("Unsupported conversion format");
}
+ // PDF to text and to RTF share a URL, so desktop routing needs the key itself.
+ const requestConfig = {
+ responseType: "blob" as const,
+ endpointName: getEndpointName(parameters.fromExtension, actualToExtension),
+ };
// Convert-specific routing logic: decide batch vs individual processing
// For PDF/X, we want to treat it similar to PDF/A (separate processing)
@@ -306,9 +311,11 @@ export const convertProcessor = async (
for (const file of selectedFiles) {
try {
const formData = buildConvertFormData(parameters, [file]);
- const response = await apiClient.post(endpoint, formData, {
- responseType: "blob",
- });
+ const response = await apiClient.post(
+ endpoint,
+ formData,
+ requestConfig,
+ );
const convertedFile = createFileFromResponse(
response.data,
@@ -325,9 +332,7 @@ export const convertProcessor = async (
} else {
// Batch processing for simple cases (image→PDF combine)
const formData = buildConvertFormData(parameters, selectedFiles);
- const response = await apiClient.post(endpoint, formData, {
- responseType: "blob",
- });
+ const response = await apiClient.post(endpoint, formData, requestConfig);
const baseFilename =
selectedFiles.length === 1 ? selectedFiles[0].name : "converted_files";
diff --git a/frontend/src/editor/core/tests/convert/ConvertIntegration.test.tsx b/frontend/src/editor/core/tests/convert/ConvertIntegration.test.tsx
index 42459e85c9..21f85338c7 100644
--- a/frontend/src/editor/core/tests/convert/ConvertIntegration.test.tsx
+++ b/frontend/src/editor/core/tests/convert/ConvertIntegration.test.tsx
@@ -463,6 +463,7 @@ describe("Convert Tool Integration Tests", () => {
expect.any(FormData),
{
responseType: "blob",
+ endpointName: "pdf-to-img",
},
);
@@ -806,6 +807,7 @@ describe("Convert Tool Integration Tests", () => {
expect.any(FormData),
{
responseType: "blob",
+ endpointName: "pdf-to-csv",
},
);
diff --git a/frontend/src/editor/core/tests/convert/ConvertSmartDetectionIntegration.test.tsx b/frontend/src/editor/core/tests/convert/ConvertSmartDetectionIntegration.test.tsx
index e9e3a0ee5a..48e07792c0 100644
--- a/frontend/src/editor/core/tests/convert/ConvertSmartDetectionIntegration.test.tsx
+++ b/frontend/src/editor/core/tests/convert/ConvertSmartDetectionIntegration.test.tsx
@@ -182,6 +182,7 @@ describe("Convert Tool - Smart Detection Integration Tests", () => {
expect.any(FormData),
{
responseType: "blob",
+ endpointName: "file-to-pdf",
},
);
@@ -236,6 +237,7 @@ describe("Convert Tool - Smart Detection Integration Tests", () => {
expect.any(FormData),
{
responseType: "blob",
+ endpointName: "file-to-pdf",
},
);
});
@@ -291,6 +293,7 @@ describe("Convert Tool - Smart Detection Integration Tests", () => {
expect.any(FormData),
{
responseType: "blob",
+ endpointName: "img-to-pdf",
},
);
@@ -363,6 +366,7 @@ describe("Convert Tool - Smart Detection Integration Tests", () => {
expect.any(FormData),
{
responseType: "blob",
+ endpointName: "file-to-pdf",
},
);
});
@@ -417,6 +421,7 @@ describe("Convert Tool - Smart Detection Integration Tests", () => {
expect.any(FormData),
{
responseType: "blob",
+ endpointName: "html-to-pdf",
},
);
@@ -568,6 +573,7 @@ describe("Convert Tool - Smart Detection Integration Tests", () => {
expect.any(FormData),
{
responseType: "blob",
+ endpointName: "pdf-to-pdfa",
},
);
});
diff --git a/frontend/src/editor/core/tests/helpers/api-stubs.ts b/frontend/src/editor/core/tests/helpers/api-stubs.ts
index 6f71dfa08f..0ce12374fe 100644
--- a/frontend/src/editor/core/tests/helpers/api-stubs.ts
+++ b/frontend/src/editor/core/tests/helpers/api-stubs.ts
@@ -38,6 +38,7 @@ const ALL_BACKEND_ENDPOINTS = [
"pdf-to-word",
"file-to-pdf",
"pdf-to-text",
+ "pdf-to-rtf",
"pdf-to-html",
"pdf-to-xml",
"pdf-to-csv",
diff --git a/frontend/src/editor/core/utils/convertUtils.test.ts b/frontend/src/editor/core/utils/convertUtils.test.ts
index 20c63739cf..d763ca0bc1 100644
--- a/frontend/src/editor/core/utils/convertUtils.test.ts
+++ b/frontend/src/editor/core/utils/convertUtils.test.ts
@@ -9,6 +9,7 @@ import {
getEndpointUrl,
isConversionSupported,
isImageFormat,
+ usesOfficeEngine,
} from "@editor/utils/convertUtils";
describe("convertUtils", () => {
@@ -31,7 +32,7 @@ describe("convertUtils", () => {
// PDF to Data formats
expect(getEndpointName("pdf", "csv")).toBe("pdf-to-csv");
expect(getEndpointName("pdf", "txt")).toBe("pdf-to-text");
- expect(getEndpointName("pdf", "rtf")).toBe("pdf-to-text");
+ expect(getEndpointName("pdf", "rtf")).toBe("pdf-to-rtf");
expect(getEndpointName("pdf", "md")).toBe("pdf-to-markdown");
// PDF to Web formats
@@ -347,4 +348,12 @@ describe("convertUtils", () => {
expect(getEndpointName(longExtension, "pdf")).toBe("file-to-pdf"); // Fallback to file to pdf
});
});
+
+ describe("usesOfficeEngine", () => {
+ test("offers the engine choice for text and RTF output", () => {
+ expect(usesOfficeEngine("pdf", "txt")).toBe(true);
+ expect(usesOfficeEngine("pdf", "rtf")).toBe(true);
+ expect(usesOfficeEngine("pdf", "xml")).toBe(false);
+ });
+ });
});
diff --git a/frontend/src/editor/core/utils/convertUtils.ts b/frontend/src/editor/core/utils/convertUtils.ts
index 2534e12493..15e9b331fb 100644
--- a/frontend/src/editor/core/utils/convertUtils.ts
+++ b/frontend/src/editor/core/utils/convertUtils.ts
@@ -30,6 +30,7 @@ const OFFICE_ENGINE_ENDPOINTS = [
"pdf-to-word",
"pdf-to-presentation",
"pdf-to-text",
+ "pdf-to-rtf",
"pdf-to-xlsx",
];
diff --git a/frontend/src/editor/desktop/services/apiClientSetup.test.ts b/frontend/src/editor/desktop/services/apiClientSetup.test.ts
index d328068049..192869a21c 100644
--- a/frontend/src/editor/desktop/services/apiClientSetup.test.ts
+++ b/frontend/src/editor/desktop/services/apiClientSetup.test.ts
@@ -226,6 +226,7 @@ describe("desktop request interceptor - auth for SaaS-backend requests", () => {
url: string;
method: string;
headers: Record<string, string>;
+ endpointName?: string;
};
async function runRequestInterceptor(config: ReqConfig): Promise<ReqConfig> {
@@ -281,6 +282,23 @@ describe("desktop request interceptor - auth for SaaS-backend requests", () => {
}),
).rejects.toThrow("Sign in required");
});
+
+ test("routes by the request's endpoint key when it carries one", async () => {
+ await runRequestInterceptor({
+ url: "/api/v1/convert/pdf/text",
+ method: "post",
+ headers: {},
+ endpointName: "pdf-to-rtf",
+ });
+ expect(operationRouter.getBaseUrl).toHaveBeenCalledWith(
+ "/api/v1/convert/pdf/text",
+ "pdf-to-rtf",
+ );
+ expect(operationRouter.shouldSkipBackendReadyCheck).toHaveBeenCalledWith(
+ "/api/v1/convert/pdf/text",
+ "pdf-to-rtf",
+ );
+ });
});
describe("desktop getAuthHeaders (raw fetch / AI SSE stream)", () => {
diff --git a/frontend/src/editor/desktop/services/apiClientSetup.ts b/frontend/src/editor/desktop/services/apiClientSetup.ts
index ff1a4158d9..f3b62d2609 100644
--- a/frontend/src/editor/desktop/services/apiClientSetup.ts
+++ b/frontend/src/editor/desktop/services/apiClientSetup.ts
@@ -70,11 +70,17 @@ export function setupApiInterceptors(client: AxiosInstance): void {
const skipCheck = extendedConfig.skipBackendReadyCheck === true;
const skipForSaaSBackend =
- await operationRouter.shouldSkipBackendReadyCheck(originalUrl);
+ await operationRouter.shouldSkipBackendReadyCheck(
+ originalUrl,
+ extendedConfig.endpointName,
+ );
try {
// Get the appropriate base URL for this request
- const baseUrl = await operationRouter.getBaseUrl(originalUrl);
+ const baseUrl = await operationRouter.getBaseUrl(
+ originalUrl,
+ extendedConfig.endpointName,
+ );
// Build the full URL
if (extendedConfig.url && !extendedConfig.url.startsWith("http")) {
diff --git a/frontend/src/editor/desktop/services/operationRouter.test.ts b/frontend/src/editor/desktop/services/operationRouter.test.ts
index ab760c4332..b19b4e96c4 100644
--- a/frontend/src/editor/desktop/services/operationRouter.test.ts
+++ b/frontend/src/editor/desktop/services/operationRouter.test.ts
@@ -199,3 +199,30 @@ describe("operationRouter.getBaseUrl — SaaS mode cloud-only routing", () => {
).resolves.toBe(true);
});
});
+
+describe("operationRouter — URL shared by two endpoint keys", () => {
+ const url = "/api/v1/convert/pdf/text";
+
+ test("routes by the caller's endpoint key, not the first key for the URL", async () => {
+ const supportedLocally = vi.mocked(
+ endpointAvailabilityService.isEndpointSupportedLocally,
+ );
+ supportedLocally.mockImplementation(async (name) => name !== "pdf-to-rtf");
+ try {
+ await expect(operationRouter.getBaseUrl(url)).resolves.toBe(
+ "http://localhost:62994",
+ );
+ await expect(operationRouter.getBaseUrl(url, "pdf-to-rtf")).resolves.toBe(
+ SAAS_URL,
+ );
+ await expect(
+ operationRouter.shouldSkipBackendReadyCheck(url, "pdf-to-rtf"),
+ ).resolves.toBe(true);
+ await expect(
+ operationRouter.shouldSkipBackendReadyCheck(url),
+ ).resolves.toBe(false);
+ } finally {
+ supportedLocally.mockResolvedValue(true);
+ }
+ });
+});
diff --git a/frontend/src/editor/desktop/services/operationRouter.ts b/frontend/src/editor/desktop/services/operationRouter.ts
index 60eed32fb6..20cf1aa947 100644
--- a/frontend/src/editor/desktop/services/operationRouter.ts
+++ b/frontend/src/editor/desktop/services/operationRouter.ts
@@ -170,13 +170,19 @@ export class OperationRouter {
return endpoint;
}
+ /** The caller's endpoint key wins: one URL can serve several (PDF to text and to RTF). */
+ private capabilityKey(operation: string, endpointName?: string): string {
+ return endpointName || this.extractEndpointName(operation);
+ }
+
/**
* Gets the base URL for an operation based on execution target
* Enhanced with capability-based routing for tools not supported locally
* @param operation - The operation endpoint path (for endpoint classification)
+ * @param endpointName - Backend endpoint key, when the URL alone does not identify it
* @returns Base URL for API calls
*/
- async getBaseUrl(operation?: string): Promise<string> {
+ async getBaseUrl(operation?: string, endpointName?: string): Promise<string> {
if (await isLocalProcessingOnly()) {
if (operation && requiresOffDeviceProcessing(operation))
throw documentPrivacyError();
@@ -190,7 +196,7 @@ export class OperationRouter {
operation &&
this.isToolEndpoint(operation) &&
!(await endpointAvailabilityService.isEndpointSupportedLocally(
- this.extractEndpointName(operation),
+ this.capabilityKey(operation, endpointName),
localUrl,
))
) {
@@ -207,12 +213,12 @@ export class OperationRouter {
// Local-only mode: route everything to local backend; open settings if tool unavailable
if (mode === "local") {
if (operation && this.isToolEndpoint(operation)) {
- const endpointName = this.extractEndpointName(operation);
+ const endpointToCheck = this.capabilityKey(operation, endpointName);
const backendUrl = tauriBackendService.getBackendUrl();
if (backendUrl) {
const supportedLocally =
await endpointAvailabilityService.isEndpointSupportedLocally(
- endpointName,
+ endpointToCheck,
backendUrl,
);
if (!supportedLocally) {
@@ -254,7 +260,7 @@ export class OperationRouter {
// NEW: Check if local backend supports this tool endpoint
if (mode === "saas" && operation && this.isToolEndpoint(operation)) {
// Extract endpoint name for capability check (e.g., "/api/v1/misc/repair" -> "repair")
- const endpointToCheck = this.extractEndpointName(operation);
+ const endpointToCheck = this.capabilityKey(operation, endpointName);
console.debug(
`[operationRouter] Checking capability for ${operation} -> endpoint name: ${endpointToCheck}`,
);
@@ -323,12 +329,12 @@ export class OperationRouter {
if (mode === "selfhosted" && operation && this.isToolEndpoint(operation)) {
const { status } = selfHostedServerMonitor.getSnapshot();
if (status === "offline") {
- const endpointName = this.extractEndpointName(operation);
+ const endpointToCheck = this.capabilityKey(operation, endpointName);
const localUrl = tauriBackendService.getBackendUrl();
if (localUrl) {
const supportedLocally =
await endpointAvailabilityService.isEndpointSupportedLocally(
- endpointName,
+ endpointToCheck,
localUrl,
);
if (supportedLocally) {
@@ -342,7 +348,7 @@ export class OperationRouter {
i18n.t(
"selfHosted.offline.toolNotAvailableLocally",
'Your Stirling-PDF server is offline and "{{endpoint}}" is not available on the local backend.',
- { endpoint: endpointName },
+ { endpoint: endpointToCheck },
),
);
}
@@ -395,9 +401,13 @@ export class OperationRouter {
* Returns true if the endpoint routes to SaaS backend (not local backend)
* Enhanced to support capability-based routing
* @param endpoint - The endpoint path to check
+ * @param endpointName - Backend endpoint key, when the URL alone does not identify it
* @returns Promise<boolean> - true if endpoint should skip backend readiness check
*/
- async shouldSkipBackendReadyCheck(endpoint?: string): Promise<boolean> {
+ async shouldSkipBackendReadyCheck(
+ endpoint?: string,
+ endpointName?: string,
+ ): Promise<boolean> {
if (await isLocalProcessingOnly())
return Boolean(
endpoint &&
@@ -417,7 +427,7 @@ export class OperationRouter {
const backendUrl = tauriBackendService.getBackendUrl();
// Backend not ready — don't skip the readiness check; let it gate the request.
if (!backendUrl || !tauriBackendService.isOnline) return false;
- const endpointToCheck = this.extractEndpointName(endpoint);
+ const endpointToCheck = this.capabilityKey(endpoint, endpointName);
const supportedLocally =
await endpointAvailabilityService.isEndpointSupportedLocally(
endpointToCheck,
diff --git a/frontend/src/editor/desktop/services/tauriHttpClient.ts b/frontend/src/editor/desktop/services/tauriHttpClient.ts
index c5ffc7e064..e594d26274 100644
--- a/frontend/src/editor/desktop/services/tauriHttpClient.ts
+++ b/frontend/src/editor/desktop/services/tauriHttpClient.ts
@@ -36,6 +36,8 @@ export interface TauriHttpRequestConfig {
automationSession?: string;
skipBackendReadyCheck?: boolean;
skipAuthRedirect?: boolean;
+ /** Backend endpoint key for routing, when the URL serves more than one. */
+ endpointName?: string;
// Axios compatibility properties (ignored by Tauri HTTP)
suppressErrorToast?: boolean;
accountLinkBlockContext?: import("@editor/services/accountLinkBlock").AccountLinkBlockContext;
diff --git a/frontend/src/editor/proprietary/components/shared/config/configSections/server/EndpointManagementCard.tsx b/frontend/src/editor/proprietary/components/shared/config/configSections/server/EndpointManagementCard.tsx
index 3e0f88e2f7..bb8286411d 100644
--- a/frontend/src/editor/proprietary/components/shared/config/configSections/server/EndpointManagementCard.tsx
+++ b/frontend/src/editor/proprietary/components/shared/config/configSections/server/EndpointManagementCard.tsx
@@ -51,6 +51,7 @@ const commonEndpoints = [
"pdf-to-markdown",
"pdf-to-pdfa",
"pdf-to-presentation",
+ "pdf-to-rtf",
"pdf-to-single-page",
"pdf-to-text",
"pdf-to-word",
diff --git a/frontend/src/global.d.ts b/frontend/src/global.d.ts
index 89bc0ee03d..e05aa28e06 100644
--- a/frontend/src/global.d.ts
+++ b/frontend/src/global.d.ts
@@ -45,12 +45,15 @@ declare module "axios" {
accountLinkBlockContext?: import("@editor/services/accountLinkBlock").AccountLinkBlockContext;
skipAuthRedirect?: boolean;
skipBackendReadyCheck?: boolean;
+ /** Backend endpoint key for desktop routing, when the URL serves more than one. */
+ endpointName?: string;
}
export interface InternalAxiosRequestConfig<_D = unknown> {
suppressErrorToast?: boolean;
skipAuthRedirect?: boolean;
skipBackendReadyCheck?: boolean;
+ endpointName?: string;
}
}