Skip to content

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

Upgrade Office Convert to 0.3.3 and extend native conversion options (#8761)

Anthony Stirling7fce14399ef2
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 4eff80f180..8de7cac0e3 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
@@ -612,24 +612,11 @@ 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");
addEndpointAlternative("pdf-to-html", "Pdftohtml");
addEndpointAlternative("pdf-to-markdown", "Pdftohtml");
- // markdown-to-pdf can use either Weasyprint or Java
- addEndpointAlternative("markdown-to-pdf", "Weasyprint");
- addEndpointAlternative("markdown-to-pdf", "Java");
-
// Weasyprint dependent endpoints
addEndpointToGroup("Weasyprint", "html-to-pdf");
addEndpointToGroup("Weasyprint", "url-to-pdf");
diff --git a/app/common/src/main/java/stirling/software/common/model/api/converters/EmlToPdfRequest.java b/app/common/src/main/java/stirling/software/common/model/api/converters/EmlToPdfRequest.java
index b6425a99f7..c1407e5bc2 100644
--- a/app/common/src/main/java/stirling/software/common/model/api/converters/EmlToPdfRequest.java
+++ b/app/common/src/main/java/stirling/software/common/model/api/converters/EmlToPdfRequest.java
@@ -11,7 +11,8 @@ import stirling.software.common.model.api.PDFFile;
@EqualsAndHashCode(callSuper = true)
public class EmlToPdfRequest extends PDFFile {
- // fileInput is inherited from PDFFile
+ @Schema(description = "Use Stirling Office Convert; when omitted, follow the server setting")
+ private Boolean useStirlingOfficeConvert;
@Schema(
description = "Include email attachments in the PDF output",
diff --git a/app/common/src/main/java/stirling/software/common/model/api/converters/HTMLToPdfRequest.java b/app/common/src/main/java/stirling/software/common/model/api/converters/HTMLToPdfRequest.java
index cedf892747..931100858b 100644
--- a/app/common/src/main/java/stirling/software/common/model/api/converters/HTMLToPdfRequest.java
+++ b/app/common/src/main/java/stirling/software/common/model/api/converters/HTMLToPdfRequest.java
@@ -16,4 +16,7 @@ public class HTMLToPdfRequest extends PDFFile {
requiredMode = Schema.RequiredMode.REQUIRED,
defaultValue = "1")
private float zoom = 1;
+
+ @Schema(description = "Use Stirling Office Convert; when omitted, follow the server setting")
+ private Boolean useStirlingOfficeConvert;
}
diff --git a/app/common/src/main/java/stirling/software/common/util/EmlToPdf.java b/app/common/src/main/java/stirling/software/common/util/EmlToPdf.java
index 0c4269eb6f..364cbb19de 100644
--- a/app/common/src/main/java/stirling/software/common/util/EmlToPdf.java
+++ b/app/common/src/main/java/stirling/software/common/util/EmlToPdf.java
@@ -11,6 +11,12 @@ import stirling.software.common.service.CustomPDFDocumentFactory;
@UtilityClass
public class EmlToPdf {
+ /** Renders sanitized email HTML while preserving interruption for request cancellation. */
+ @FunctionalInterface
+ public interface HtmlToPdfRenderer {
+ byte[] render(String html) throws IOException, InterruptedException;
+ }
+
public static String convertEmlToHtml(byte[] emlBytes, EmlToPdfRequest request)
throws IOException {
return convertEmlToHtml(emlBytes, request, null);
@@ -37,6 +43,29 @@ public class EmlToPdf {
CustomHtmlSanitizer customHtmlSanitizer)
throws IOException, InterruptedException {
+ return convertEmlToPdf(
+ request,
+ emlBytes,
+ pdfDocumentFactory,
+ customHtmlSanitizer,
+ html ->
+ convertHtmlToPdf(
+ weasyprintPath,
+ request,
+ html,
+ tempFileManager,
+ customHtmlSanitizer));
+ }
+
+ /** Keeps parsing, sanitization and attachment rules independent of the PDF renderer. */
+ public static byte[] convertEmlToPdf(
+ EmlToPdfRequest request,
+ byte[] emlBytes,
+ CustomPDFDocumentFactory pdfDocumentFactory,
+ CustomHtmlSanitizer customHtmlSanitizer,
+ HtmlToPdfRenderer renderer)
+ throws IOException, InterruptedException {
+
EmlProcessingUtils.validateEmlInput(emlBytes);
try {
@@ -47,13 +76,7 @@ public class EmlToPdf {
EmlProcessingUtils.generateEnhancedEmailHtml(
emailContent, request, customHtmlSanitizer);
- byte[] pdfBytes =
- convertHtmlToPdf(
- weasyprintPath,
- request,
- htmlContent,
- tempFileManager,
- customHtmlSanitizer);
+ byte[] pdfBytes = renderer.render(htmlContent);
if (shouldAttachFiles(emailContent, request)) {
pdfBytes =
diff --git a/app/common/src/test/java/stirling/software/SPDF/config/EndpointConfigurationTest.java b/app/common/src/test/java/stirling/software/SPDF/config/EndpointConfigurationTest.java
index 6c827ffc2b..3f76db764d 100644
--- a/app/common/src/test/java/stirling/software/SPDF/config/EndpointConfigurationTest.java
+++ b/app/common/src/test/java/stirling/software/SPDF/config/EndpointConfigurationTest.java
@@ -1,12 +1,59 @@
package stirling.software.SPDF.config;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.List;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import stirling.software.common.model.ApplicationProperties;
class EndpointConfigurationTest {
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void officeEngineRemainsOptionalWhenStandardConvertersAreUnavailable(boolean officeConversion) {
+ ApplicationProperties properties = new ApplicationProperties();
+ properties.getSystem().setStirlingOfficeConversion(officeConversion);
+ EndpointConfiguration endpoints = new EndpointConfiguration(properties, false, null);
+ List<String> standardConverters =
+ List.of("LibreOffice", "Unoconvert", "Weasyprint", "Pdftohtml", "Calibre");
+ List<String> conversions =
+ List.of(
+ "file-to-pdf",
+ "pdf-to-word",
+ "pdf-to-presentation",
+ "pdf-to-rtf",
+ "pdf-to-html",
+ "pdf-to-xml",
+ "pdf-to-markdown",
+ "html-to-pdf",
+ "eml-to-pdf",
+ "markdown-to-pdf",
+ "pdf-to-epub",
+ "ebook-to-pdf",
+ "pdf-to-pdfa");
+ for (String group : standardConverters) {
+ endpoints.disableGroup(group);
+ }
+ for (String endpoint : conversions) {
+ assertFalse(endpoints.isEndpointEnabled(endpoint), endpoint);
+ }
+ for (String group : standardConverters) {
+ endpoints.enableGroup(group);
+ }
+ for (String endpoint : conversions) {
+ assertTrue(endpoints.isEndpointEnabled(endpoint), endpoint);
+ endpoints.disableEndpoint(endpoint);
+ assertFalse(endpoints.isEndpointEnabled(endpoint), endpoint);
+ }
+ }
+
@Test
void endpointKeyForUriExtractsSimpleKebab() {
assertEquals(
diff --git a/app/core/build.gradle b/app/core/build.gradle
index 8a79cdb749..8b82d39d6a 100644
--- a/app/core/build.gradle
+++ b/app/core/build.gradle
@@ -51,6 +51,7 @@ dependencies {
implementation "com.stirling:stirling-office-convert:$officeConvertVersion"
implementation "com.stirling:stirling-office-convert-legacy:$officeConvertVersion"
implementation "com.stirling:stirling-office-convert-topdf:$officeConvertVersion"
+ implementation "com.stirling:stirling-office-convert-pdfa:$officeConvertVersion"
// General PDF dependencies
implementation "org.apache.pdfbox:preflight:$pdfboxVersion"
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertEbookToPDFController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertEbookToPDFController.java
index 5f1347470e..f773263fa9 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertEbookToPDFController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertEbookToPDFController.java
@@ -26,6 +26,8 @@ import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.config.EndpointConfiguration;
import stirling.software.SPDF.model.api.converters.ConvertEbookToPdfRequest;
+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;
@@ -54,6 +56,8 @@ public class ConvertEbookToPDFController {
private final EndpointConfiguration endpointConfiguration;
private final OfficeDocumentSanitizer officeDocumentSanitizer;
private final RuntimePathConfig runtimePathConfig;
+ private final OfficeConversionService officeConversionService;
+ private final OfficeToPdfService officeToPdfService;
private boolean isCalibreEnabled() {
return endpointConfiguration.isGroupEnabled("Calibre");
@@ -72,10 +76,12 @@ public class ConvertEbookToPDFController {
summary = "Convert an eBook file to PDF",
description =
"This endpoint converts common eBook formats (EPUB, MOBI, AZW3, FB2, TXT, DOCX)"
- + " to PDF using Calibre.")
+ + " to PDF using Calibre or Stirling Office Convert.")
public ResponseEntity<Resource> convertEbookToPdf(
@ModelAttribute ConvertEbookToPdfRequest request) throws Exception {
- if (!isCalibreEnabled()) {
+ boolean officeConvert =
+ officeConversionService.replacesLibreOffice(request.getUseStirlingOfficeConvert());
+ if (!officeConvert && !isCalibreEnabled()) {
throw new IllegalStateException("Calibre support is disabled");
}
@@ -130,27 +136,37 @@ public class ConvertEbookToPDFController {
}
}
- List<String> command =
- buildCalibreCommand(
- inputPath,
- outputPath,
- embedAllFonts,
- includeTableOfContents,
- includePageNumbers);
- ProcessExecutorResult result =
- ProcessExecutor.getInstance(ProcessExecutor.Processes.CALIBRE)
- .runCommandWithOutputHandling(command, workingDirectory.toFile());
-
- if (result == null) {
- throw new IllegalStateException("Calibre conversion returned no result");
- }
+ if (officeConvert) {
+ officeToPdfService.convert(
+ inputPath,
+ outputPath,
+ officeToPdfService
+ .options()
+ .tableOfContents(includeTableOfContents)
+ .pageNumbers(includePageNumbers));
+ } else {
+ List<String> command =
+ buildCalibreCommand(
+ inputPath,
+ outputPath,
+ embedAllFonts,
+ includeTableOfContents,
+ includePageNumbers);
+ ProcessExecutorResult result =
+ ProcessExecutor.getInstance(ProcessExecutor.Processes.CALIBRE)
+ .runCommandWithOutputHandling(command, workingDirectory.toFile());
+
+ if (result == null) {
+ throw new IllegalStateException("Calibre conversion returned no result");
+ }
- if (result.getRc() != 0) {
- throw new IllegalStateException("Calibre conversion failed");
+ if (result.getRc() != 0) {
+ throw new IllegalStateException("Calibre conversion failed");
+ }
}
if (!Files.exists(outputPath) || Files.size(outputPath) == 0L) {
- throw new IllegalStateException("Calibre did not produce a PDF output");
+ throw new IllegalStateException("The ebook converter did not produce a PDF output");
}
String outputFilename =
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertEmlToPDF.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertEmlToPDF.java
index c8a7b710f5..cf9caa7974 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertEmlToPDF.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertEmlToPDF.java
@@ -22,6 +22,8 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.config.swagger.StandardPdfResponse;
+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;
@@ -45,6 +47,8 @@ public class ConvertEmlToPDF {
private final RuntimePathConfig runtimePathConfig;
private final TempFileManager tempFileManager;
private final CustomHtmlSanitizer customHtmlSanitizer;
+ private final OfficeConversionService officeConversionService;
+ private final OfficeToPdfService officeToPdfService;
@AutoJobPostMapping(
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
@@ -112,17 +116,27 @@ public class ConvertEmlToPDF {
}
}
- // Convert EML/MSG to PDF with enhanced options
try {
byte[] pdfBytes =
- EmlToPdf.convertEmlToPdf(
- runtimePathConfig.getWeasyPrintPath(),
- request,
- fileBytes,
- originalFilename,
- pdfDocumentFactory,
- tempFileManager,
- customHtmlSanitizer);
+ officeConversionService.replacesLibreOffice(
+ request.getUseStirlingOfficeConvert())
+ ? EmlToPdf.convertEmlToPdf(
+ request,
+ fileBytes,
+ pdfDocumentFactory,
+ customHtmlSanitizer,
+ html ->
+ officeToPdfService.convertHtml(
+ html.getBytes(StandardCharsets.UTF_8),
+ false))
+ : EmlToPdf.convertEmlToPdf(
+ runtimePathConfig.getWeasyPrintPath(),
+ request,
+ fileBytes,
+ originalFilename,
+ pdfDocumentFactory,
+ tempFileManager,
+ customHtmlSanitizer);
if (pdfBytes == null || pdfBytes.length == 0) {
log.error("PDF conversion failed - empty output for {}", originalFilename);
@@ -153,7 +167,7 @@ public class ConvertEmlToPDF {
errorMessage,
e);
return errorResponse(HttpStatus.INTERNAL_SERVER_ERROR, errorMessage);
- } catch (RuntimeException e) {
+ } catch (IOException | RuntimeException e) {
String errorMessage = buildErrorMessage(e, originalFilename);
log.error(
"Email to PDF conversion failed for {}: {}",
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertHtmlToPDF.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertHtmlToPDF.java
index 536d0562ef..9a54b688ce 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertHtmlToPDF.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertHtmlToPDF.java
@@ -14,6 +14,8 @@ import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import stirling.software.SPDF.config.swagger.StandardPdfResponse;
+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;
@@ -33,9 +35,12 @@ public class ConvertHtmlToPDF {
private final RuntimePathConfig runtimePathConfig;
private final TempFileManager tempFileManager;
+ private final OfficeConversionService officeConversionService;
+ private final OfficeToPdfService officeToPdfService;
private final CustomHtmlSanitizer customHtmlSanitizer;
+ /** Zoom applies to the standard converter; Office Convert ignores it. */
@AutoJobPostMapping(
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
value = "/html/pdf",
@@ -65,14 +70,19 @@ public class ConvertHtmlToPDF {
"error.fileFormatRequired", "File must be in {0} format", ".html or .zip");
}
+ boolean officeConvert =
+ officeConversionService.replacesLibreOffice(request.getUseStirlingOfficeConvert());
byte[] pdfBytes =
- FileToPdf.convertHtmlToPdf(
- runtimePathConfig.getWeasyPrintPath(),
- request,
- fileInput.getBytes(),
- originalFilename,
- tempFileManager,
- customHtmlSanitizer);
+ officeConvert
+ ? officeToPdfService.convertHtml(
+ fileInput.getBytes(), originalFilename.endsWith(".zip"))
+ : FileToPdf.convertHtmlToPdf(
+ runtimePathConfig.getWeasyPrintPath(),
+ request,
+ fileInput.getBytes(),
+ originalFilename,
+ tempFileManager,
+ customHtmlSanitizer);
pdfBytes = pdfDocumentFactory.createNewBytesBasedOnOldDocument(pdfBytes);
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertMarkdownToPdf.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertMarkdownToPdf.java
index 7e85143d17..24b030da7e 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertMarkdownToPdf.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertMarkdownToPdf.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;
@@ -25,6 +26,8 @@ import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import stirling.software.SPDF.config.swagger.StandardPdfResponse;
+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;
@@ -55,6 +58,8 @@ public class ConvertMarkdownToPdf {
private final RuntimePathConfig runtimePathConfig;
private final TempFileManager tempFileManager;
+ private final OfficeConversionService officeConversionService;
+ private final OfficeToPdfService officeToPdfService;
private final CustomHtmlSanitizer customHtmlSanitizer;
@@ -73,7 +78,10 @@ public class ConvertMarkdownToPdf {
description =
"This endpoint takes a Markdown file or ZIP (containing Markdown + images)"
+ " input, converts it to HTML, and then to PDF format.")
- public ResponseEntity<Resource> markdownToPdf(@ModelAttribute GeneralFile generalFile)
+ public ResponseEntity<Resource> markdownToPdf(
+ @ModelAttribute GeneralFile generalFile,
+ @RequestParam(value = "useStirlingOfficeConvert", required = false)
+ Boolean useStirlingOfficeConvert)
throws Exception {
MultipartFile fileInput = generalFile.getFileInput();
@@ -96,6 +104,8 @@ public class ConvertMarkdownToPdf {
"error.fileFormatRequired", "File must be in {0} format", ".md or .zip");
}
+ boolean officeConvert =
+ officeConversionService.replacesLibreOffice(useStirlingOfficeConvert);
byte[] pdfBytes;
String outputFilename;
@@ -140,15 +150,7 @@ public class ConvertMarkdownToPdf {
// Create a new ZIP with HTML + images for WeasyPrint
byte[] htmlZipBytes = createHtmlZip(htmlContent, tempDirPath.toFile());
- // Use FileToPdf which already supports ZIP files with images
- pdfBytes =
- FileToPdf.convertHtmlToPdf(
- runtimePathConfig.getWeasyPrintPath(),
- null,
- htmlZipBytes,
- "package.zip",
- tempFileManager,
- customHtmlSanitizer);
+ pdfBytes = convertHtml(htmlZipBytes, true, officeConvert);
outputFilename =
GeneralUtils.generateFilename(
@@ -161,13 +163,7 @@ public class ConvertMarkdownToPdf {
renderHtml(new String(fileInput.getBytes(), StandardCharsets.UTF_8));
pdfBytes =
- FileToPdf.convertHtmlToPdf(
- runtimePathConfig.getWeasyPrintPath(),
- null,
- htmlContent.getBytes(StandardCharsets.UTF_8),
- "converted.html",
- tempFileManager,
- customHtmlSanitizer);
+ convertHtml(htmlContent.getBytes(StandardCharsets.UTF_8), false, officeConvert);
outputFilename = GeneralUtils.generateFilename(originalFilename, ".pdf");
}
@@ -184,6 +180,20 @@ public class ConvertMarkdownToPdf {
return WebResponseUtils.pdfFileToWebResponse(tempOut, outputFilename);
}
+ private byte[] convertHtml(byte[] html, boolean packaged, boolean officeConvert)
+ throws Exception {
+ if (officeConvert) {
+ return officeToPdfService.convertHtml(html, packaged);
+ }
+ return FileToPdf.convertHtmlToPdf(
+ runtimePathConfig.getWeasyPrintPath(),
+ null,
+ html,
+ packaged ? "package.zip" : "converted.html",
+ tempFileManager,
+ customHtmlSanitizer);
+ }
+
static String renderHtml(String markdown) {
return HTML_RENDERER.render(MARKDOWN_PARSER.parse(markdown));
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToEpubController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToEpubController.java
index 40fa359a3e..98bedf092d 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToEpubController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToEpubController.java
@@ -25,6 +25,7 @@ import stirling.software.SPDF.config.EndpointConfiguration;
import stirling.software.SPDF.model.api.converters.ConvertPdfToEpubRequest;
import stirling.software.SPDF.model.api.converters.ConvertPdfToEpubRequest.OutputFormat;
import stirling.software.SPDF.model.api.converters.ConvertPdfToEpubRequest.TargetDevice;
+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;
@@ -37,6 +38,7 @@ import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;
import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
+import stirling.software.officeconvert.EbookOptions;
@ConvertApi
@RequiredArgsConstructor
@@ -53,6 +55,7 @@ public class ConvertPDFToEpubController {
private final TempFileManager tempFileManager;
private final EndpointConfiguration endpointConfiguration;
private final RuntimePathConfig runtimePathConfig;
+ private final OfficeConversionService officeConversionService;
private List<String> buildCalibreCommand(
Path inputPath, Path outputPath, boolean detectChapters, TargetDevice targetDevice) {
@@ -96,11 +99,14 @@ public class ConvertPDFToEpubController {
@ToolIO(produces = ToolFormat.EBOOK)
@Operation(
summary = "Convert PDF to EPUB/AZW3",
- description = "Convert a PDF file to a high-quality EPUB or AZW3 ebook using Calibre.")
+ description =
+ "Convert a PDF file to an EPUB or AZW3 ebook using Calibre or Stirling Office Convert.")
public ResponseEntity<Resource> convertPdfToEpub(
@ModelAttribute ConvertPdfToEpubRequest request) throws Exception {
- if (!endpointConfiguration.isGroupEnabled(CALIBRE_GROUP)) {
+ boolean officeConvert =
+ officeConversionService.replacesLibreOffice(request.getUseStirlingOfficeConvert());
+ if (!officeConvert && !endpointConfiguration.isGroupEnabled(CALIBRE_GROUP)) {
throw new IllegalStateException(
"Calibre support is disabled. Enable the Calibre group or install Calibre to use"
+ " this feature.");
@@ -133,6 +139,21 @@ public class ConvertPDFToEpubController {
throw new IllegalArgumentException("Input file must be a PDF");
}
+ if (officeConvert) {
+ EbookOptions ebook =
+ EbookOptions.defaults()
+ .chapters(detectChapters)
+ .device(
+ targetDevice == TargetDevice.KINDLE_EINK_TEXT
+ ? EbookOptions.Device.KINDLE
+ : EbookOptions.Device.TABLET);
+ return officeConversionService.convert(
+ inputFile,
+ outputFormat.getExtension(),
+ MediaType.valueOf(outputFormat.getMediaType()),
+ officeConversionService.settings().ebook(ebook));
+ }
+
String baseName = FilenameUtils.getBaseName(originalFilename);
if (baseName == null || baseName.isBlank()) {
baseName = "document";
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToHtml.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToHtml.java
index 8f9819c0e4..b736b71f50 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToHtml.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToHtml.java
@@ -1,15 +1,21 @@
package stirling.software.SPDF.controller.api.converters;
+import java.nio.file.Files;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
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;
import lombok.RequiredArgsConstructor;
+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;
@@ -17,14 +23,19 @@ import stirling.software.common.enumeration.ResourceWeight;
import stirling.software.common.model.api.PDFFile;
import stirling.software.common.model.tool.ToolFormat;
import stirling.software.common.model.tool.ToolIO;
+import stirling.software.common.util.GeneralUtils;
import stirling.software.common.util.PDFToFile;
+import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
+import stirling.software.common.util.WebResponseUtils;
@ConvertApi
@RequiredArgsConstructor
public class ConvertPDFToHtml {
private final TempFileManager tempFileManager;
+ private final OfficeConversionService officeConversionService;
+
private final RuntimePathConfig runtimePathConfig;
@AutoJobPostMapping(
@@ -35,9 +46,34 @@ public class ConvertPDFToHtml {
@Operation(
summary = "Convert PDF to HTML",
description = "This endpoint converts a PDF file to HTML format.")
- public ResponseEntity<Resource> processPdfToHTML(@ModelAttribute PDFFile file)
+ public ResponseEntity<Resource> processPdfToHTML(
+ @ModelAttribute PDFFile file,
+ @RequestParam(value = "useStirlingOfficeConvert", required = false)
+ Boolean useStirlingOfficeConvert)
throws Exception {
MultipartFile inputFile = file.getFileInput();
+ if (officeConversionService.replacesLibreOffice(useStirlingOfficeConvert)) {
+ ResponseEntity<Resource> html =
+ officeConversionService.convert(
+ inputFile,
+ "html",
+ MediaType.TEXT_HTML,
+ officeConversionService.settings());
+ TempFile zip = tempFileManager.createManagedTempFile(".zip");
+ try (var in = html.getBody().getInputStream();
+ var out = new ZipOutputStream(Files.newOutputStream(zip.getPath()))) {
+ out.putNextEntry(new ZipEntry("index.html"));
+ in.transferTo(out);
+ out.closeEntry();
+ } catch (Exception e) {
+ zip.close();
+ throw e;
+ }
+ return WebResponseUtils.fileToWebResponse(
+ zip,
+ GeneralUtils.generateFilename(inputFile.getOriginalFilename(), ".zip"),
+ MediaType.valueOf("application/zip"));
+ }
PDFToFile pdfToFile = new PDFToFile(tempFileManager, runtimePathConfig);
return pdfToFile.processPdfToHtml(inputFile);
}
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 f5d8e1461e..66d2c40cbd 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
@@ -171,9 +171,16 @@ public class ConvertPDFToOffice {
@Operation(
summary = "Convert PDF to XML",
description = "This endpoint converts a PDF file to an XML file.")
- public ResponseEntity<Resource> processPdfToXML(@ModelAttribute PDFFile file) throws Exception {
+ public ResponseEntity<Resource> processPdfToXML(
+ @ModelAttribute PDFFile file,
+ @RequestParam(value = "useStirlingOfficeConvert", required = false)
+ Boolean useStirlingOfficeConvert)
+ throws Exception {
MultipartFile inputFile = file.getFileInput();
+ if (officeConversionService.replacesLibreOffice(useStirlingOfficeConvert)) {
+ return convert(inputFile, "xml", Set.of("xml"), MediaType.APPLICATION_XML);
+ }
return convertWithLibreOffice(inputFile, "xml", Set.of("xml"), "writer_pdf_import");
}
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFA.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFA.java
index a9674fd100..7f5d237315 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFA.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFA.java
@@ -89,6 +89,7 @@ import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import stirling.software.SPDF.model.api.converters.PdfToPdfARequest;
+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;
@@ -105,6 +106,8 @@ import stirling.software.common.util.TempFile;
import stirling.software.common.util.TempFileManager;
import stirling.software.common.util.WebResponseUtils;
import stirling.software.common.util.XmpUtils;
+import stirling.software.officeconvert.pdfa.PdfALevel;
+import stirling.software.officeconvert.pdfa.PdfToPdfA;
@ConvertApi
@Slf4j
@@ -118,14 +121,17 @@ public class ConvertPDFToPDFA {
private final TempFileManager tempFileManager;
// The sanitizer adds content streams to every page, all held in memory until the save
private final int maxConversionPages;
+ private final OfficeConversionService officeConversionService;
public ConvertPDFToPDFA(
RuntimePathConfig runtimePathConfig,
stirling.software.SPDF.service.VeraPDFService veraPDFService,
@Autowired(required = false) PdfaLevelAServiceInterface pdfaLevelAService,
TempFileManager tempFileManager,
- ApplicationProperties applicationProperties) {
+ ApplicationProperties applicationProperties,
+ OfficeConversionService officeConversionService) {
this.runtimePathConfig = runtimePathConfig;
+ this.officeConversionService = officeConversionService;
this.veraPDFService = veraPDFService;
this.pdfaLevelAService = pdfaLevelAService;
this.tempFileManager = tempFileManager;
@@ -605,7 +611,7 @@ public class ConvertPDFToPDFA {
@Operation(
summary = "Convert a PDF to a PDF/A or PDF/X",
description =
- "This endpoint converts a PDF file to a PDF/A or PDF/X file using Ghostscript"
+ "This endpoint converts a PDF file to PDF/A using Stirling Office Convert, or to a PDF/A or PDF/X file using Ghostscript"
+ " (preferred) or PDFBox/LibreOffice (fallback). PDF/A is a format designed for"
+ " long-term archiving, while PDF/X is optimized for print production.")
public ResponseEntity<Resource> pdfToPdfA(@ModelAttribute PdfToPdfARequest request)
@@ -629,7 +635,8 @@ public class ConvertPDFToPDFA {
inputFile,
outputFormat,
request.getStrict() != null && request.getStrict(),
- request.getPdfUa() != null && request.getPdfUa());
+ request.getPdfUa() != null && request.getPdfUa(),
+ request.getUseStirlingOfficeConvert());
}
}
@@ -1830,7 +1837,11 @@ public class ConvertPDFToPDFA {
}
private ResponseEntity<Resource> handlePdfAConversion(
- MultipartFile inputFile, String outputFormat, boolean strict, boolean declarePdfUa)
+ MultipartFile inputFile,
+ String outputFormat,
+ boolean strict,
+ boolean declarePdfUa,
+ Boolean useStirlingOfficeConvert)
throws Exception {
PdfaProfile profile = PdfaProfile.fromRequest(outputFormat);
@@ -1851,6 +1862,44 @@ public class ConvertPDFToPDFA {
try {
byte[] converted;
+ if (officeConversionService.replacesLibreOffice(useStirlingOfficeConvert)) {
+ Path output = workingDir.resolve("office-pdfa.pdf");
+ PdfALevel level =
+ switch (profile.getPart()) {
+ case 1 -> PdfALevel.A1B;
+ case 2 -> PdfALevel.A2B;
+ case 3 -> PdfALevel.A3B;
+ default -> throw new IllegalArgumentException("Unsupported PDF/A part");
+ };
+ PdfToPdfA.convert(
+ inputPath,
+ output,
+ PdfToPdfA.Options.defaults()
+ .level(level)
+ .timeout(officeConversionService.settings().timeout())
+ .maxPages(maxConversionPages));
+ var levelA =
+ applyLevelA(
+ Files.readAllBytes(output),
+ inputPath,
+ profile,
+ baseFileName,
+ declarePdfUa);
+ converted = levelA.pdfBytes();
+ if (strict) {
+ verifyStrictCompliance(converted, profile, levelA.levelA());
+ }
+ TempFile tempOut = tempFileManager.createManagedTempFile(".pdf");
+ try {
+ Files.write(tempOut.getPath(), converted);
+ } catch (Exception e) {
+ tempOut.close();
+ throw e;
+ }
+ return WebResponseUtils.pdfFileToWebResponse(
+ tempOut, baseFileName + profile.outputSuffix(levelA.levelA()));
+ }
+
// Try Ghostscript first (preferred method)
if (isGhostscriptAvailable()) {
log.info("Using Ghostscript for PDF/A conversion to {}", profile.getDisplayName());
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/converters/ConvertEbookToPdfRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/converters/ConvertEbookToPdfRequest.java
index 636cb4646a..79f7d35927 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/converters/ConvertEbookToPdfRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/converters/ConvertEbookToPdfRequest.java
@@ -11,6 +11,9 @@ import lombok.EqualsAndHashCode;
@EqualsAndHashCode
public class ConvertEbookToPdfRequest {
+ @Schema(description = "Use Stirling Office Convert; when omitted, follow the server setting")
+ private Boolean useStirlingOfficeConvert;
+
@Schema(
description =
"The input eBook file to be converted to a PDF file (EPUB, MOBI, AZW3, FB2,"
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/converters/ConvertPDFToMarkdown.java b/app/core/src/main/java/stirling/software/SPDF/model/api/converters/ConvertPDFToMarkdown.java
index 99f5e04867..510bdf5700 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/converters/ConvertPDFToMarkdown.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/converters/ConvertPDFToMarkdown.java
@@ -5,6 +5,7 @@ import java.nio.charset.StandardCharsets;
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;
@@ -13,6 +14,7 @@ import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import stirling.software.SPDF.config.swagger.MarkdownConversionResponse;
+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;
@@ -31,6 +33,7 @@ public class ConvertPDFToMarkdown {
private final TempFileManager tempFileManager;
private final PdfMarkdownExtractor markdownExtractor;
+ private final OfficeConversionService officeConversionService;
@AutoJobPostMapping(
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
@@ -41,10 +44,25 @@ public class ConvertPDFToMarkdown {
@Operation(
summary = "Convert PDF to Markdown",
description = "This endpoint converts a PDF file to Markdown format.")
- public ResponseEntity<byte[]> processPdfToMarkdown(@ModelAttribute PDFFile file)
+ public ResponseEntity<byte[]> processPdfToMarkdown(
+ @ModelAttribute PDFFile file,
+ @RequestParam(value = "useStirlingOfficeConvert", required = false)
+ Boolean useStirlingOfficeConvert)
throws Exception {
MultipartFile inputFile = file.getFileInput();
+ if (officeConversionService.replacesLibreOffice(useStirlingOfficeConvert)) {
+ var response =
+ officeConversionService.convert(
+ inputFile,
+ "md",
+ MediaType.valueOf("text/markdown"),
+ officeConversionService.settings());
+ try (var in = response.getBody().getInputStream()) {
+ return ResponseEntity.ok().headers(response.getHeaders()).body(in.readAllBytes());
+ }
+ }
+
String originalName = Filenames.toSimpleFileName(inputFile.getOriginalFilename());
String baseName =
originalName.contains(".")
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/converters/ConvertPdfToEpubRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/converters/ConvertPdfToEpubRequest.java
index f9da520119..55053f7b6d 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/converters/ConvertPdfToEpubRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/converters/ConvertPdfToEpubRequest.java
@@ -12,6 +12,9 @@ import stirling.software.common.model.api.PDFFile;
@EqualsAndHashCode(callSuper = true)
public class ConvertPdfToEpubRequest extends PDFFile {
+ @Schema(description = "Use Stirling Office Convert; when omitted, follow the server setting")
+ private Boolean useStirlingOfficeConvert;
+
@Schema(
description = "Detect headings that look like chapters and insert EPUB page breaks.",
allowableValues = {"true", "false"},
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/converters/PdfToPdfARequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/converters/PdfToPdfARequest.java
index 77e4cb9816..3baad6351f 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/converters/PdfToPdfARequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/converters/PdfToPdfARequest.java
@@ -11,6 +11,9 @@ import stirling.software.common.model.api.PDFFile;
@EqualsAndHashCode(callSuper = true)
public class PdfToPdfARequest extends PDFFile {
+ @Schema(description = "Use Stirling Office Convert; when omitted, follow the server setting")
+ private Boolean useStirlingOfficeConvert;
+
@Schema(
description = "The output format type (PDF/A or PDF/X)",
requiredMode = Schema.RequiredMode.REQUIRED,
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
index 90caf773de..cac715a7f2 100644
--- a/app/core/src/main/java/stirling/software/SPDF/service/OfficeConversionService.java
+++ b/app/core/src/main/java/stirling/software/SPDF/service/OfficeConversionService.java
@@ -17,13 +17,22 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.pdfbox.pdmodel.PDDocument;
+import org.springframework.core.io.Resource;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
import lombok.RequiredArgsConstructor;
import stirling.software.SPDF.config.EndpointConfiguration;
import stirling.software.common.model.ApplicationProperties;
+import stirling.software.common.service.CustomPDFDocumentFactory;
import stirling.software.common.util.ExceptionUtils;
+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.PdfToPptx;
import stirling.software.officeconvert.legacy.PdfToPpt;
@@ -38,19 +47,43 @@ 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);
+ Map.ofEntries(
+ Map.entry("docx", OfficeConvert.Format.DOCX),
+ Map.entry("doc", OfficeConvert.Format.RTF),
+ Map.entry("odt", OfficeConvert.Format.ODT),
+ Map.entry("rtf", OfficeConvert.Format.RTF),
+ Map.entry("txt", OfficeConvert.Format.TXT),
+ Map.entry("pptx", OfficeConvert.Format.PPTX),
+ Map.entry("odp", OfficeConvert.Format.ODP),
+ Map.entry("xlsx", OfficeConvert.Format.XLSX),
+ Map.entry("ods", OfficeConvert.Format.ODS),
+ Map.entry("html", OfficeConvert.Format.HTML),
+ Map.entry("md", OfficeConvert.Format.MARKDOWN),
+ Map.entry("xml", OfficeConvert.Format.XML),
+ Map.entry("epub", OfficeConvert.Format.EPUB),
+ Map.entry("azw3", OfficeConvert.Format.AZW3));
private final ApplicationProperties applicationProperties;
private final EndpointConfiguration endpointConfiguration;
+ private final CustomPDFDocumentFactory pdfDocumentFactory;
+ private final TempFileManager tempFileManager;
+
+ /** The response owns the output file; failed conversions release it before returning. */
+ public ResponseEntity<Resource> convert(
+ MultipartFile input, String format, MediaType type, OfficeConvert.Settings settings)
+ throws IOException {
+ TempFile out = tempFileManager.createManagedTempFile("." + format);
+ try (PDDocument document = pdfDocumentFactory.load(input)) {
+ convert(document, out.getPath(), format, settings);
+ } catch (Exception e) {
+ out.close();
+ throw e;
+ }
+ return WebResponseUtils.fileToWebResponse(
+ out,
+ GeneralUtils.generateFilename(input.getOriginalFilename(), "." + format),
+ type);
+ }
public static boolean supports(String format) {
return FORMATS.containsKey(format) || "ppt".equals(format);
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
index 849de1078e..46469c4d3a 100644
--- a/app/core/src/main/java/stirling/software/SPDF/service/OfficeToPdfService.java
+++ b/app/core/src/main/java/stirling/software/SPDF/service/OfficeToPdfService.java
@@ -1,6 +1,7 @@
package stirling.software.SPDF.service;
import java.io.IOException;
+import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
@@ -14,6 +15,8 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.ApplicationProperties;
+import stirling.software.common.util.TempFile;
+import stirling.software.common.util.TempFileManager;
import stirling.software.officeconvert.memory.Admission;
import stirling.software.officeconvert.topdf.OfficeToPdf;
import stirling.software.officeconvert.topdf.io.PoiXml;
@@ -26,6 +29,17 @@ public class OfficeToPdfService {
private final OfficeConversionService officeConversionService;
private final ApplicationProperties applicationProperties;
+ private final TempFileManager tempFileManager;
+
+ /** Packages may use their own assets; local files and network resources remain inaccessible. */
+ public byte[] convertHtml(byte[] html, boolean packaged) throws IOException {
+ try (TempFile in = new TempFile(tempFileManager, packaged ? ".zip" : ".html");
+ TempFile out = new TempFile(tempFileManager, ".pdf")) {
+ Files.write(in.getPath(), html);
+ convert(in.getPath(), out.getPath(), options().allowPackages(packaged));
+ return Files.readAllBytes(out.getPath());
+ }
+ }
/** POI needs the XML limits Java 24 lowered for deep or large slides. */
@PostConstruct
@@ -58,24 +72,30 @@ public class OfficeToPdfService {
&& OfficeToPdf.Format.recognises(Path.of("file." + extension));
}
+ /** Uses the server timeout and rejects incomplete output even without a fallback installed. */
public void convert(Path in, Path out) throws IOException {
+ convert(in, out, options());
+ }
+
+ /** Uses the server timeout; callers may add format-specific options. */
+ public OfficeToPdf.Options options() {
long minutes =
applicationProperties
.getProcessExecutor()
.getTimeoutMinutes()
.getLibreOfficeTimeoutMinutes();
- OfficeToPdf.Result result =
- OfficeToPdf.convert(
- in,
- out,
- OfficeToPdf.Options.defaults().timeout(Duration.ofMinutes(minutes)));
+ return OfficeToPdf.Options.defaults().timeout(Duration.ofMinutes(minutes));
+ }
+
+ /** Rejects incomplete or page-limited output; callers may retry with another converter. */
+ public void convert(Path in, Path out, OfficeToPdf.Options options) throws IOException {
+ OfficeToPdf.Result result = OfficeToPdf.convert(in, out, options);
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.
+ if (result.truncated() || result.pageLimitReached()) {
throw new IOException("Only part of " + in.getFileName() + " could be converted");
}
}
diff --git a/app/core/src/main/resources/static/3rdPartyLicenses.json b/app/core/src/main/resources/static/3rdPartyLicenses.json
index 0246a606ac..ea10d684c7 100644
--- a/app/core/src/main/resources/static/3rdPartyLicenses.json
+++ b/app/core/src/main/resources/static/3rdPartyLicenses.json
@@ -440,21 +440,28 @@
{
"moduleName": "com.stirling:stirling-office-convert",
"moduleUrl": "https://github.com/Stirling-Tools/Stirling-Office-Convert",
- "moduleVersion": "0.2.2",
+ "moduleVersion": "0.3.3",
"moduleLicense": "MIT License",
"moduleLicenseUrl": "https://opensource.org/licenses/MIT"
},
{
"moduleName": "com.stirling:stirling-office-convert-legacy",
"moduleUrl": "https://github.com/Stirling-Tools/Stirling-Office-Convert",
- "moduleVersion": "0.2.2",
+ "moduleVersion": "0.3.3",
+ "moduleLicense": "MIT License",
+ "moduleLicenseUrl": "https://opensource.org/licenses/MIT"
+ },
+ {
+ "moduleName": "com.stirling:stirling-office-convert-pdfa",
+ "moduleUrl": "https://github.com/Stirling-Tools/Stirling-Office-Convert",
+ "moduleVersion": "0.3.3",
"moduleLicense": "MIT License",
"moduleLicenseUrl": "https://opensource.org/licenses/MIT"
},
{
"moduleName": "com.stirling:stirling-office-convert-topdf",
"moduleUrl": "https://github.com/Stirling-Tools/Stirling-Office-Convert",
- "moduleVersion": "0.2.2",
+ "moduleVersion": "0.3.3",
"moduleLicense": "MIT License",
"moduleLicenseUrl": "https://opensource.org/licenses/MIT"
},
@@ -3031,7 +3038,5 @@
"moduleLicenseUrl": "http://www.apache.org/licenses/LICENSE-2.0.txt"
}
],
- "importedModules": [
-
- ]
-}
\ No newline at end of file
+ "importedModules": []
+}
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertEbookToPDFControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertEbookToPDFControllerTest.java
index bc77b727da..832e23094d 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertEbookToPDFControllerTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertEbookToPDFControllerTest.java
@@ -72,6 +72,9 @@ class ConvertEbookToPDFControllerTest {
private static final String CALIBRE_PATH = "/opt/calibre/ebook-convert";
+ @Mock private stirling.software.SPDF.service.OfficeConversionService officeConversionService;
+ @Mock private stirling.software.SPDF.service.OfficeToPdfService officeToPdfService;
+
@InjectMocks private ConvertEbookToPDFController controller;
@BeforeEach
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertEmlToPDFTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertEmlToPDFTest.java
index 605c4edce8..bd3b6e8604 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertEmlToPDFTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertEmlToPDFTest.java
@@ -31,6 +31,8 @@ import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
+import stirling.software.SPDF.service.OfficeConversionService;
+import stirling.software.SPDF.service.OfficeToPdfService;
import stirling.software.common.configuration.RuntimePathConfig;
import stirling.software.common.model.api.converters.EmlToPdfRequest;
import stirling.software.common.service.CustomPDFDocumentFactory;
@@ -58,6 +60,8 @@ class ConvertEmlToPDFTest {
@Mock private RuntimePathConfig runtimePathConfig;
@Mock private TempFileManager tempFileManager;
@Mock private CustomHtmlSanitizer customHtmlSanitizer;
+ @Mock private OfficeConversionService officeConversionService;
+ @Mock private OfficeToPdfService officeToPdfService;
@InjectMocks private ConvertEmlToPDF controller;
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertHtmlToPDFTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertHtmlToPDFTest.java
index 4b9be15fe0..775180e39d 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertHtmlToPDFTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertHtmlToPDFTest.java
@@ -55,6 +55,9 @@ class ConvertHtmlToPDFTest {
@Mock private TempFileManager tempFileManager;
@Mock private CustomHtmlSanitizer customHtmlSanitizer;
+ @Mock private stirling.software.SPDF.service.OfficeConversionService officeConversionService;
+ @Mock private stirling.software.SPDF.service.OfficeToPdfService officeToPdfService;
+
@InjectMocks private ConvertHtmlToPDF controller;
@BeforeEach
@@ -92,7 +95,7 @@ class ConvertHtmlToPDFTest {
}
@Test
- void htmlToPdf_validHtmlFile() throws Exception {
+ void htmlToPdf_standardConverterPreservesZoom() throws Exception {
byte[] htmlContent = "<html><body>Hello</body></html>".getBytes();
byte[] pdfBytes = "pdf-content".getBytes();
byte[] processedPdf = "processed-pdf".getBytes();
@@ -101,6 +104,8 @@ class ConvertHtmlToPDFTest {
new MockMultipartFile("fileInput", "test.html", "text/html", htmlContent);
HTMLToPdfRequest request = new HTMLToPdfRequest();
request.setFileInput(file);
+ request.setUseStirlingOfficeConvert(false);
+ request.setZoom(1.5f);
when(runtimePathConfig.getWeasyPrintPath()).thenReturn("/usr/bin/weasyprint");
when(pdfDocumentFactory.createNewBytesBasedOnOldDocument(pdfBytes))
@@ -136,6 +141,7 @@ class ConvertHtmlToPDFTest {
ResponseEntity<Resource> response = controller.HtmlToPdf(request);
assertEquals(HttpStatus.OK, response.getStatusCode());
+ assertEquals(1.5f, request.getZoom());
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertMarkdownToPdfMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertMarkdownToPdfMoreTest.java
index 15e2705e7a..7b63d915b3 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertMarkdownToPdfMoreTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertMarkdownToPdfMoreTest.java
@@ -59,6 +59,9 @@ class ConvertMarkdownToPdfMoreTest {
@Mock private TempFileManager tempFileManager;
@Mock private CustomHtmlSanitizer customHtmlSanitizer;
+ @Mock private stirling.software.SPDF.service.OfficeConversionService officeConversionService;
+ @Mock private stirling.software.SPDF.service.OfficeToPdfService officeToPdfService;
+
@InjectMocks private ConvertMarkdownToPdf controller;
@BeforeEach
@@ -128,7 +131,7 @@ class ConvertMarkdownToPdfMoreTest {
any(TempFile.class), anyString()))
.thenReturn(cannedResponse());
- ResponseEntity<Resource> response = controller.markdownToPdf(gf);
+ ResponseEntity<Resource> response = controller.markdownToPdf(gf, null);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
String html = new String(htmlBytes.getValue(), StandardCharsets.UTF_8);
@@ -155,7 +158,7 @@ class ConvertMarkdownToPdfMoreTest {
any(CustomHtmlSanitizer.class)))
.thenThrow(new java.io.IOException("weasyprint failed"));
- assertThatThrownBy(() -> controller.markdownToPdf(gf))
+ assertThatThrownBy(() -> controller.markdownToPdf(gf, null))
.isInstanceOf(java.io.IOException.class);
}
}
@@ -206,7 +209,7 @@ class ConvertMarkdownToPdfMoreTest {
any(TempFile.class), anyString()))
.thenReturn(cannedResponse());
- ResponseEntity<Resource> response = controller.markdownToPdf(gf);
+ ResponseEntity<Resource> response = controller.markdownToPdf(gf, null);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
ftp.verify(
@@ -230,7 +233,7 @@ class ConvertMarkdownToPdfMoreTest {
GeneralFile gf = generalFileOf("bundle.zip", "application/zip", zip);
- assertThatThrownBy(() -> controller.markdownToPdf(gf))
+ assertThatThrownBy(() -> controller.markdownToPdf(gf, null))
.isInstanceOf(IllegalArgumentException.class);
}
}
@@ -245,7 +248,7 @@ class ConvertMarkdownToPdfMoreTest {
GeneralFile gf = new GeneralFile();
gf.setFileInput(null);
- assertThatThrownBy(() -> controller.markdownToPdf(gf))
+ assertThatThrownBy(() -> controller.markdownToPdf(gf, null))
.isInstanceOf(IllegalArgumentException.class);
}
@@ -254,7 +257,7 @@ class ConvertMarkdownToPdfMoreTest {
void wrongExtension() {
GeneralFile gf = generalFileOf("notes.txt", "text/plain", "hello".getBytes());
- assertThatThrownBy(() -> controller.markdownToPdf(gf))
+ assertThatThrownBy(() -> controller.markdownToPdf(gf, null))
.isInstanceOf(IllegalArgumentException.class);
}
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertMarkdownToPdfTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertMarkdownToPdfTest.java
index a222be13d3..97699e34d3 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertMarkdownToPdfTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertMarkdownToPdfTest.java
@@ -61,6 +61,9 @@ class ConvertMarkdownToPdfTest {
@Mock private TempFileManager tempFileManager;
@Mock private CustomHtmlSanitizer customHtmlSanitizer;
+ @Mock private stirling.software.SPDF.service.OfficeConversionService officeConversionService;
+ @Mock private stirling.software.SPDF.service.OfficeToPdfService officeToPdfService;
+
@InjectMocks private ConvertMarkdownToPdf controller;
@BeforeEach
@@ -84,7 +87,7 @@ class ConvertMarkdownToPdfTest {
GeneralFile generalFile = new GeneralFile();
generalFile.setFileInput(null);
- assertThrows(Exception.class, () -> controller.markdownToPdf(generalFile));
+ assertThrows(Exception.class, () -> controller.markdownToPdf(generalFile, null));
}
@Test
@@ -94,7 +97,7 @@ class ConvertMarkdownToPdfTest {
GeneralFile generalFile = new GeneralFile();
generalFile.setFileInput(file);
- assertThrows(Exception.class, () -> controller.markdownToPdf(generalFile));
+ assertThrows(Exception.class, () -> controller.markdownToPdf(generalFile, null));
}
@Test
@@ -139,7 +142,7 @@ class ConvertMarkdownToPdfTest {
any(TempFile.class), anyString()))
.thenReturn(expectedResponse);
- ResponseEntity<Resource> response = controller.markdownToPdf(generalFile);
+ ResponseEntity<Resource> response = controller.markdownToPdf(generalFile, null);
assertEquals(HttpStatus.OK, response.getStatusCode());
}
@@ -152,7 +155,7 @@ class ConvertMarkdownToPdfTest {
GeneralFile generalFile = new GeneralFile();
generalFile.setFileInput(file);
- assertThrows(Exception.class, () -> controller.markdownToPdf(generalFile));
+ assertThrows(Exception.class, () -> controller.markdownToPdf(generalFile, null));
}
@Test
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToEpubControllerTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToEpubControllerTest.java
index c4aa4002b4..6e1d130d5f 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToEpubControllerTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToEpubControllerTest.java
@@ -70,6 +70,9 @@ class ConvertPDFToEpubControllerTest {
private static final String CALIBRE_PATH = "/opt/calibre/ebook-convert";
+ @Mock private stirling.software.SPDF.service.OfficeConversionService officeConversionService;
+ @Mock private stirling.software.SPDF.service.OfficeToPdfService officeToPdfService;
+
@InjectMocks private ConvertPDFToEpubController controller;
@BeforeEach
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 d034e38291..f69e66cdf8 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
@@ -419,7 +419,8 @@ class ConvertPDFToOfficeMoreTest {
assertThrows(
ToolRequiredException.class,
() -> controller.processPdfToPresentation(presentation, false));
- assertThrows(ToolRequiredException.class, () -> controller.processPdfToXML(xml));
+ assertThrows(
+ ToolRequiredException.class, () -> controller.processPdfToXML(xml, null));
mockedFactory.verifyNoInteractions();
}
}
@@ -438,7 +439,7 @@ class ConvertPDFToOfficeMoreTest {
try (MockedStatic<ProcessExecutor> mockedFactory = mockStatic(ProcessExecutor.class)) {
stubLibreOfficeWritesOutput(mockedFactory, "xml");
- ResponseEntity<Resource> response = controller.processPdfToXML(file);
+ ResponseEntity<Resource> response = controller.processPdfToXML(file, null);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue(readResource(response.getBody()).length > 0);
@@ -451,7 +452,7 @@ class ConvertPDFToOfficeMoreTest {
PDFFile file = new PDFFile();
file.setFileInput(nonPdfFile());
- ResponseEntity<Resource> response = controller.processPdfToXML(file);
+ ResponseEntity<Resource> response = controller.processPdfToXML(file, null);
assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
}
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFAGapTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFAGapTest.java
index 5a11a73f73..9361bb60b6 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFAGapTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFAGapTest.java
@@ -92,7 +92,8 @@ class ConvertPDFToPDFAGapTest {
veraPDFService,
pdfaLevelAService,
tempFileManager,
- new ApplicationProperties());
+ new ApplicationProperties(),
+ mock(stirling.software.SPDF.service.OfficeConversionService.class));
}
// ---- reflection helpers ----------------------------------------------------------------
@@ -1135,7 +1136,8 @@ class ConvertPDFToPDFAGapTest {
veraPDFService,
pdfaLevelAService,
tempFileManager,
- properties);
+ properties,
+ mock(stirling.software.SPDF.service.OfficeConversionService.class));
assertThatThrownBy(
() ->
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFAMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFAMoreTest.java
index ecff558184..b5fd1992cf 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFAMoreTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/ConvertPDFToPDFAMoreTest.java
@@ -75,7 +75,8 @@ class ConvertPDFToPDFAMoreTest {
veraPDFService,
pdfaLevelAService,
tempFileManager,
- new ApplicationProperties());
+ new ApplicationProperties(),
+ mock(stirling.software.SPDF.service.OfficeConversionService.class));
}
private static ResponseEntity<Resource> streamingOk(byte[] bytes) {
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/OfficeConvertIntegrationTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/OfficeConvertIntegrationTest.java
new file mode 100644
index 0000000000..189951df41
--- /dev/null
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/OfficeConvertIntegrationTest.java
@@ -0,0 +1,499 @@
+package stirling.software.SPDF.controller.api.converters;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Map;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+import java.util.zip.ZipOutputStream;
+
+import org.apache.pdfbox.Loader;
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.PDDocumentNameDictionary;
+import org.apache.pdfbox.pdmodel.PDEmbeddedFilesNameTreeNode;
+import org.apache.pdfbox.pdmodel.PDPage;
+import org.apache.pdfbox.pdmodel.PDPageContentStream;
+import org.apache.pdfbox.pdmodel.common.filespecification.PDComplexFileSpecification;
+import org.apache.pdfbox.pdmodel.common.filespecification.PDEmbeddedFile;
+import org.apache.pdfbox.pdmodel.font.PDType1Font;
+import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
+import org.apache.pdfbox.text.PDFTextStripper;
+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 org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.MockedStatic;
+import org.springframework.context.support.StaticMessageSource;
+import org.springframework.core.io.Resource;
+import org.springframework.http.ResponseEntity;
+import org.springframework.mock.env.MockEnvironment;
+import org.springframework.mock.web.MockMultipartFile;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import stirling.software.SPDF.config.EndpointConfiguration;
+import stirling.software.SPDF.exception.GlobalExceptionHandler;
+import stirling.software.SPDF.model.api.converters.ConvertEbookToPdfRequest;
+import stirling.software.SPDF.model.api.converters.ConvertPDFToMarkdown;
+import stirling.software.SPDF.model.api.converters.ConvertPdfToEpubRequest;
+import stirling.software.SPDF.model.api.converters.PdfToPdfARequest;
+import stirling.software.SPDF.service.OfficeConversionService;
+import stirling.software.SPDF.service.OfficeToPdfService;
+import stirling.software.SPDF.service.VeraPDFService;
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.common.model.api.GeneralFile;
+import stirling.software.common.model.api.PDFFile;
+import stirling.software.common.model.api.converters.HTMLToPdfRequest;
+import stirling.software.common.service.CustomPDFDocumentFactory;
+import stirling.software.common.util.OfficeDocumentSanitizer;
+import stirling.software.common.util.TempFileManager;
+import stirling.software.common.util.TempFileRegistry;
+import stirling.software.officeconvert.topdf.OfficeToPdf;
+
+class OfficeConvertIntegrationTest {
+ private static final String TEXT = "Stirling conversion content";
+ @TempDir Path dir;
+ private final ApplicationProperties properties = new ApplicationProperties();
+ private final EndpointConfiguration endpoints = mock(EndpointConfiguration.class);
+ private final CustomPDFDocumentFactory factory =
+ new CustomPDFDocumentFactory(
+ mock(stirling.software.common.service.PdfMetadataService.class));
+ private TempFileManager tempFiles;
+ private OfficeConversionService office;
+ private OfficeToPdfService toPdf;
+
+ @BeforeEach
+ void setUp() {
+ properties.getSystem().getTempFileManagement().setBaseTmpDir(dir.toString());
+ tempFiles = new TempFileManager(new TempFileRegistry(), properties);
+ office = new OfficeConversionService(properties, endpoints, factory, tempFiles);
+ toPdf = new OfficeToPdfService(office, properties, tempFiles);
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {"docx", "odt", "rtf", "xml", "pptx", "odp", "xlsx", "ods", "epub", "azw3"})
+ void convertsEveryEditableFormatAndReadsItBack(String format) throws Exception {
+ Path output = dir.resolve("output." + format);
+ try (PDDocument pdf = document()) {
+ office.convert(pdf, output, format, office.settings());
+ }
+ assertThat(Files.size(output)).isPositive();
+ Path restored = dir.resolve("restored.pdf");
+ toPdf.convert(output, restored);
+ assertPdfText(Files.readAllBytes(restored));
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"txt", "md", "html", "doc"})
+ void writesTextFormatsWithContent(String format) throws Exception {
+ Path output = dir.resolve("output." + format);
+ try (PDDocument pdf = document()) {
+ office.convert(pdf, output, format, office.settings());
+ }
+ assertThat(Files.readString(output)).contains(TEXT);
+ }
+
+ @Test
+ void htmlOutputRemainsAZipAndConvertsBackWithoutWeasyprint() throws Exception {
+ var controller = new ConvertPDFToHtml(tempFiles, office, null);
+ PDFFile request = new PDFFile();
+ request.setFileInput(uploadPdf());
+ byte[] zip = body(controller.processPdfToHTML(request, true));
+ try (var in = new ZipInputStream(new ByteArrayInputStream(zip))) {
+ assertThat(in.getNextEntry().getName()).isEqualTo("index.html");
+ assertThat(new String(in.readAllBytes(), StandardCharsets.UTF_8)).contains(TEXT);
+ }
+ HTMLToPdfRequest html = new HTMLToPdfRequest();
+ html.setFileInput(new MockMultipartFile("fileInput", "page.zip", "application/zip", zip));
+ html.setUseStirlingOfficeConvert(true);
+ var toHtml = new ConvertHtmlToPDF(factory, null, tempFiles, office, toPdf, null);
+ assertPdfText(body(toHtml.HtmlToPdf(html)));
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void markdownConvertsInBothDirections(boolean packaged) throws Exception {
+ var toMarkdown = new ConvertPDFToMarkdown(tempFiles, null, office);
+ PDFFile pdf = new PDFFile();
+ pdf.setFileInput(uploadPdf());
+ byte[] markdown = toMarkdown.processPdfToMarkdown(pdf, true).getBody();
+ assertThat(new String(markdown, StandardCharsets.UTF_8)).contains(TEXT);
+ GeneralFile request = new GeneralFile();
+ request.setFileInput(
+ new MockMultipartFile(
+ "fileInput",
+ packaged ? "notes.zip" : "notes.md",
+ "application/octet-stream",
+ packaged ? zip("index.md", markdown) : markdown));
+ var controller = new ConvertMarkdownToPdf(factory, null, tempFiles, office, toPdf, null);
+ assertPdfText(body(controller.markdownToPdf(request, true)));
+ }
+
+ @ParameterizedTest
+ @CsvSource({"html,true,", "zip,true,", "html,false,true", "zip,false,true"})
+ void officeHtmlIgnoresSavedZoomForExplicitAndServerDefaultChoices(
+ String format, boolean serverDefault, Boolean choice) throws Exception {
+ properties.getSystem().setStirlingOfficeConversion(serverDefault);
+ byte[] html =
+ ("<html><body><p>" + TEXT + "</p></body></html>").getBytes(StandardCharsets.UTF_8);
+ HTMLToPdfRequest request = new HTMLToPdfRequest();
+ request.setFileInput(
+ new MockMultipartFile(
+ "fileInput",
+ "page." + format,
+ "application/octet-stream",
+ format.equals("zip") ? zip("index.html", html) : html));
+ request.setUseStirlingOfficeConvert(choice);
+ request.setZoom(1.5f);
+ var controller = new ConvertHtmlToPDF(factory, null, tempFiles, office, toPdf, null);
+
+ assertPdfText(body(controller.HtmlToPdf(request)));
+ }
+
+ @ParameterizedTest
+ @CsvSource({"true,false", "false,true"})
+ void ebookIncompleteOutputReturnsTheReasonToTheClient(boolean truncated, boolean pageLimited)
+ throws Exception {
+ var controller =
+ new ConvertEbookToPDFController(
+ factory,
+ tempFiles,
+ endpoints,
+ mock(OfficeDocumentSanitizer.class),
+ null,
+ office,
+ toPdf);
+ var mvc =
+ MockMvcBuilders.standaloneSetup(controller)
+ .setControllerAdvice(
+ new GlobalExceptionHandler(
+ new StaticMessageSource(), new MockEnvironment()))
+ .build();
+ try (MockedStatic<OfficeToPdf> engine = mockStatic(OfficeToPdf.class)) {
+ engine.when(
+ () ->
+ OfficeToPdf.convert(
+ any(Path.class),
+ any(Path.class),
+ any(OfficeToPdf.Options.class)))
+ .thenReturn(new OfficeToPdf.Result(1, truncated, List.of(), pageLimited));
+
+ mvc.perform(
+ multipart("/api/v1/convert/ebook/pdf")
+ .file(
+ new MockMultipartFile(
+ "fileInput",
+ "book.epub",
+ "application/epub+zip",
+ new byte[] {1}))
+ .param("useStirlingOfficeConvert", "true"))
+ .andExpect(status().isInternalServerError())
+ .andExpect(
+ jsonPath("$.detail")
+ .value("Only part of book.epub could be converted"));
+ }
+ try (var files = Files.list(dir)) {
+ assertThat(files).isEmpty();
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"EPUB", "AZW3"})
+ void ebooksConvertInBothDirectionsWithoutCalibre(String format) throws Exception {
+ ConvertPdfToEpubRequest request = new ConvertPdfToEpubRequest();
+ request.setFileInput(uploadPdf());
+ request.setOutputFormat(ConvertPdfToEpubRequest.OutputFormat.valueOf(format));
+ request.setUseStirlingOfficeConvert(true);
+ request.setDetectChapters(false);
+ request.setTargetDevice(ConvertPdfToEpubRequest.TargetDevice.KINDLE_EINK_TEXT);
+ var writer = new ConvertPDFToEpubController(tempFiles, endpoints, null, office);
+ byte[] ebook = body(writer.convertPdfToEpub(request));
+ ConvertEbookToPdfRequest read = new ConvertEbookToPdfRequest();
+ read.setUseStirlingOfficeConvert(true);
+ read.setIncludePageNumbers(true);
+ read.setIncludeTableOfContents(true);
+ read.setFileInput(
+ new MockMultipartFile(
+ "fileInput",
+ "book." + format.toLowerCase(),
+ "application/octet-stream",
+ ebook));
+ var reader =
+ new ConvertEbookToPDFController(
+ factory,
+ tempFiles,
+ endpoints,
+ mock(OfficeDocumentSanitizer.class),
+ null,
+ office,
+ toPdf);
+ assertPdfText(body(reader.convertEbookToPdf(read)));
+ read.setUseStirlingOfficeConvert(false);
+ assertThatThrownBy(() -> reader.convertEbookToPdf(read))
+ .isInstanceOf(IllegalStateException.class);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"pdfa-1", "pdfa-2b", "pdfa-3b"})
+ void pdfaPassesStrictVeraPdfValidationAndKeepsEligibleAttachments(String format)
+ throws Exception {
+ VeraPDFService validator = new VeraPDFService();
+ validator.initialize();
+ var controller = new ConvertPDFToPDFA(null, validator, null, tempFiles, properties, office);
+ PdfToPdfARequest request = new PdfToPdfARequest();
+ request.setOutputFormat(format);
+ request.setStrict(true);
+ request.setUseStirlingOfficeConvert(true);
+ request.setFileInput(uploadPdf());
+ byte[] output = body(controller.pdfToPdfA(request));
+ assertPdfText(output);
+ if (format.equals("pdfa-3b")) {
+ try (PDDocument pdf = Loader.loadPDF(output)) {
+ var files = pdf.getDocumentCatalog().getNames().getEmbeddedFiles().getNames();
+ assertThat(files.get("source.txt").getEmbeddedFileUnicode().toByteArray())
+ .isEqualTo(TEXT.getBytes(StandardCharsets.UTF_8));
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"docx", "xlsx", "pptx", "odt", "ods", "odp", "rtf"})
+ void fileToPdfEndpointUsesTheNativeConverterAfterSanitizing(String format) throws Exception {
+ Path input = dir.resolve("source." + format);
+ try (PDDocument pdf = document()) {
+ office.convert(pdf, input, format, office.settings());
+ }
+ var sanitizer =
+ new OfficeDocumentSanitizer(
+ mock(stirling.software.common.service.SsrfProtectionService.class),
+ properties);
+ var controller =
+ new ConvertOfficeController(
+ factory, null, null, sanitizer, endpoints, tempFiles, office, toPdf);
+ var mvc =
+ org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup(
+ controller)
+ .build();
+ var response =
+ mvc.perform(
+ org.springframework.test.web.servlet.request.MockMvcRequestBuilders
+ .multipart("/api/v1/convert/file/pdf")
+ .file(
+ new MockMultipartFile(
+ "fileInput",
+ "source." + format,
+ "application/octet-stream",
+ Files.readAllBytes(input)))
+ .param("useStirlingOfficeConvert", "true"))
+ .andReturn()
+ .getResponse();
+ assertThat(response.getStatus()).isEqualTo(200);
+ assertPdfText(response.getContentAsByteArray());
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"mobi", "fb2"})
+ void readsAdditionalEbookFormats(String format) throws Exception {
+ byte[] input;
+ if (format.equals("fb2")) {
+ input =
+ ("<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ + "<FictionBook xmlns=\"http://www.gribuser.ru/xml/fictionbook/2.0\">"
+ + "<body><section><p>"
+ + TEXT
+ + "</p></section></body></FictionBook>")
+ .getBytes(StandardCharsets.UTF_8);
+ } else {
+ Path ebook = dir.resolve("book.azw3");
+ try (PDDocument pdf = document()) {
+ office.convert(pdf, ebook, "azw3", office.settings());
+ }
+ input = Files.readAllBytes(ebook);
+ }
+ ConvertEbookToPdfRequest request = new ConvertEbookToPdfRequest();
+ request.setUseStirlingOfficeConvert(true);
+ request.setFileInput(
+ new MockMultipartFile(
+ "fileInput", "book." + format, "application/octet-stream", input));
+ var controller =
+ new ConvertEbookToPDFController(
+ factory,
+ tempFiles,
+ endpoints,
+ mock(OfficeDocumentSanitizer.class),
+ null,
+ office,
+ toPdf);
+ assertPdfText(body(controller.convertEbookToPdf(request)));
+ }
+
+ @ParameterizedTest
+ @org.junit.jupiter.params.provider.CsvSource({
+ "word,docx",
+ "word,doc",
+ "word,odt",
+ "presentation,ppt",
+ "presentation,pptx",
+ "presentation,odp",
+ "text,txt",
+ "text,rtf",
+ "xml,xml"
+ })
+ void existingPdfEndpointsBindThePerRequestChoice(String endpoint, String format)
+ throws Exception {
+ org.mockito.Mockito.when(endpoints.isEndpointEnabled("pdf-to-rtf")).thenReturn(true);
+ var controller = new ConvertPDFToOffice(factory, tempFiles, null, office, endpoints);
+ var mvc =
+ org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup(
+ controller)
+ .build();
+ var response =
+ mvc.perform(
+ org.springframework.test.web.servlet.request.MockMvcRequestBuilders
+ .multipart("/api/v1/convert/pdf/" + endpoint)
+ .file(uploadPdf())
+ .param("outputFormat", format)
+ .param("useStirlingOfficeConvert", "true"))
+ .andReturn()
+ .getResponse();
+ assertThat(response.getStatus()).isEqualTo(200);
+ assertThat(response.getContentAsByteArray()).isNotEmpty();
+ assertThat(response.getHeader("Content-Disposition")).contains("." + format);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"1", "1-2", "1,3"})
+ void excelEndpointHonoursPageSelections(String pages) throws Exception {
+ byte[] input;
+ try (PDDocument pdf = new PDDocument();
+ var out = new ByteArrayOutputStream()) {
+ for (int number = 1; number <= 3; number++) {
+ PDPage page = new PDPage();
+ pdf.addPage(page);
+ try (var content = new PDPageContentStream(pdf, page)) {
+ for (int x = 72; x <= 272; x += 100) {
+ content.moveTo(x, 550);
+ content.lineTo(x, 650);
+ }
+ for (int y = 550; y <= 650; y += 50) {
+ content.moveTo(72, y);
+ content.lineTo(272, y);
+ }
+ content.stroke();
+ content.beginText();
+ content.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12);
+ content.newLineAtOffset(82, 625);
+ content.showText("Page" + number);
+ content.newLineAtOffset(100, 0);
+ content.showText("Value");
+ content.newLineAtOffset(-100, -50);
+ content.showText("Row");
+ content.newLineAtOffset(100, 0);
+ content.showText("42");
+ content.endText();
+ }
+ }
+ pdf.save(out);
+ input = out.toByteArray();
+ }
+ var request = new stirling.software.SPDF.model.api.PDFWithPageNums();
+ request.setPageNumbers(pages);
+ request.setFileInput(
+ new MockMultipartFile("fileInput", "tables.pdf", "application/pdf", input));
+ var controller = new ConvertPDFToExcelController(factory, tempFiles, office);
+ byte[] output = body(controller.pdfToExcel(request, true));
+ StringBuilder cells = new StringBuilder();
+ try (var workbook =
+ new org.apache.poi.xssf.usermodel.XSSFWorkbook(new ByteArrayInputStream(output))) {
+ for (var sheet : workbook) {
+ for (var row : sheet) {
+ for (var cell : row) {
+ cells.append(cell).append(' ');
+ }
+ }
+ }
+ }
+ assertThat(cells.toString()).contains("Page1");
+ if (pages.equals("1,3")) {
+ assertThat(cells.toString()).contains("Page3").doesNotContain("Page2");
+ } else if (pages.equals("1-2")) {
+ assertThat(cells.toString()).contains("Page2").doesNotContain("Page3");
+ } else {
+ assertThat(cells.toString()).doesNotContain("Page2", "Page3");
+ }
+ }
+
+ private MockMultipartFile uploadPdf() throws Exception {
+ try (PDDocument pdf = document();
+ var out = new ByteArrayOutputStream()) {
+ var attachment = new PDComplexFileSpecification();
+ attachment.setFile("source.txt");
+ attachment.setFileUnicode("source.txt");
+ var payload =
+ new PDEmbeddedFile(
+ pdf, new ByteArrayInputStream(TEXT.getBytes(StandardCharsets.UTF_8)));
+ payload.setSubtype("text/plain");
+ attachment.setEmbeddedFileUnicode(payload);
+ attachment.setEmbeddedFile(payload);
+ var files = new PDEmbeddedFilesNameTreeNode();
+ files.setNames(Map.of("source.txt", attachment));
+ var names = new PDDocumentNameDictionary(pdf.getDocumentCatalog());
+ names.setEmbeddedFiles(files);
+ pdf.getDocumentCatalog().setNames(names);
+ pdf.save(out);
+ return new MockMultipartFile(
+ "fileInput", "sample.pdf", "application/pdf", out.toByteArray());
+ }
+ }
+
+ private static PDDocument document() throws Exception {
+ PDDocument pdf = new PDDocument();
+ PDPage page = new PDPage();
+ pdf.addPage(page);
+ try (var 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;
+ }
+
+ private static byte[] zip(String name, byte[] bytes) throws Exception {
+ var out = new ByteArrayOutputStream();
+ try (var zip = new ZipOutputStream(out)) {
+ zip.putNextEntry(new ZipEntry(name));
+ zip.write(bytes);
+ zip.closeEntry();
+ }
+ return out.toByteArray();
+ }
+
+ private static byte[] body(ResponseEntity<Resource> response) throws Exception {
+ try (var in = response.getBody().getInputStream()) {
+ return in.readAllBytes();
+ }
+ }
+
+ private static void assertPdfText(byte[] bytes) throws Exception {
+ try (PDDocument pdf = Loader.loadPDF(bytes)) {
+ assertThat(new PDFTextStripper().getText(pdf)).contains(TEXT);
+ }
+ }
+}
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/OfficeEmailConversionTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/OfficeEmailConversionTest.java
new file mode 100644
index 0000000000..cae6c0067f
--- /dev/null
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/converters/OfficeEmailConversionTest.java
@@ -0,0 +1,238 @@
+package stirling.software.SPDF.controller.api.converters;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
+import java.util.Base64;
+
+import org.apache.pdfbox.Loader;
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.PDPage;
+import org.apache.pdfbox.text.PDFTextStripper;
+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 org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.ArgumentCaptor;
+import org.springframework.core.io.Resource;
+import org.springframework.http.HttpStatus;
+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.service.OfficeConversionService;
+import stirling.software.SPDF.service.OfficeToPdfService;
+import stirling.software.common.configuration.RuntimePathConfig;
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.common.model.api.converters.EmlToPdfRequest;
+import stirling.software.common.service.CustomPDFDocumentFactory;
+import stirling.software.common.service.PdfMetadataService;
+import stirling.software.common.service.SsrfProtectionService;
+import stirling.software.common.util.CustomHtmlSanitizer;
+import stirling.software.common.util.EmlParser;
+import stirling.software.common.util.FileToPdf;
+import stirling.software.common.util.TempFileManager;
+import stirling.software.common.util.TempFileRegistry;
+
+class OfficeEmailConversionTest {
+ @TempDir Path dir;
+ private final ApplicationProperties properties = new ApplicationProperties();
+ private final CustomPDFDocumentFactory factory =
+ new CustomPDFDocumentFactory(mock(PdfMetadataService.class));
+ private OfficeToPdfService toPdf;
+ private ConvertEmlToPDF controller;
+
+ @BeforeEach
+ void setUp() {
+ properties.getSystem().getTempFileManagement().setBaseTmpDir(dir.toString());
+ var tempFiles = new TempFileManager(new TempFileRegistry(), properties);
+ var office =
+ new OfficeConversionService(
+ properties, mock(EndpointConfiguration.class), factory, tempFiles);
+ toPdf = spy(new OfficeToPdfService(office, properties, tempFiles));
+ var paths = mock(RuntimePathConfig.class);
+ when(paths.getWeasyPrintPath()).thenReturn("weasyprint");
+ controller =
+ new ConvertEmlToPDF(
+ factory,
+ paths,
+ tempFiles,
+ new CustomHtmlSanitizer(mock(SsrfProtectionService.class), properties),
+ office,
+ toPdf);
+ }
+
+ @ParameterizedTest
+ @CsvSource({"eml,true,", "msg,true,", "eml,false,true", "msg,false,true"})
+ void rendersBothFormatsWithExplicitAndInheritedChoices(
+ String format, boolean serverDefault, Boolean choice) throws Exception {
+ properties.getSystem().setStirlingOfficeConversion(serverDefault);
+ byte[] input = email(new byte[0]);
+ if (format.equals("msg")) {
+ try (var stream = getClass().getResourceAsStream("/eml/example.msg")) {
+ assertThat(stream).isNotNull();
+ input = stream.readAllBytes();
+ }
+ }
+ var request = request(input, format);
+ request.setUseStirlingOfficeConvert(choice);
+ String subject = EmlParser.extractEmailContent(input, request, null).getSubject();
+
+ try (var pdf = Loader.loadPDF(body(controller.convertEmlToPdf(request)))) {
+ assertThat(pdf.getNumberOfPages()).isPositive();
+ assertThat(new PDFTextStripper().getText(pdf)).contains(subject);
+ }
+ }
+
+ @ParameterizedTest
+ @CsvSource({"false,", "true,false"})
+ void preservesTheStandardRendererAndAnExplicitOptOut(boolean serverDefault, Boolean choice)
+ throws Exception {
+ properties.getSystem().setStirlingOfficeConversion(serverDefault);
+ var request = request(email(new byte[0]), "eml");
+ request.setUseStirlingOfficeConvert(choice);
+ byte[] expected;
+ try (var pdf = new PDDocument();
+ var output = new ByteArrayOutputStream()) {
+ pdf.addPage(new PDPage());
+ pdf.save(output);
+ expected = output.toByteArray();
+ }
+ try (var standard = mockStatic(FileToPdf.class)) {
+ standard.when(
+ () ->
+ FileToPdf.convertHtmlToPdf(
+ eq("weasyprint"),
+ any(),
+ any(),
+ anyString(),
+ any(),
+ any()))
+ .thenReturn(expected);
+
+ assertThat(body(controller.convertEmlToPdf(request))).isEqualTo(expected);
+ standard.verify(
+ () ->
+ FileToPdf.convertHtmlToPdf(
+ eq("weasyprint"), any(), any(), anyString(), any(), any()));
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void respectsAttachmentChoices(boolean include) throws Exception {
+ var request = request(email("attached note".getBytes(StandardCharsets.UTF_8)), "eml");
+ request.setUseStirlingOfficeConvert(true);
+ request.setIncludeAttachments(include);
+ try (var pdf = Loader.loadPDF(body(controller.convertEmlToPdf(request)))) {
+ String text = new PDFTextStripper().getText(pdf);
+ assertThat(text).contains("Email conversion content");
+ assertThat(text).contains("[email protected]", "[email protected]");
+ var names = pdf.getDocumentCatalog().getNames();
+ if (include) {
+ var attachments = names.getEmbeddedFiles().getNames();
+ assertThat(attachments).containsKey("note.txt");
+ assertThat(attachments.get("note.txt").getEmbeddedFile().toByteArray())
+ .isEqualTo("attached note".getBytes(StandardCharsets.UTF_8));
+ } else {
+ assertThat(names == null || names.getEmbeddedFiles() == null).isTrue();
+ }
+ }
+ }
+
+ @Test
+ void excludesAttachmentsExceedingTheSelectedLimit() throws Exception {
+ var request = request(email(new byte[1024 * 1024 + 1]), "eml");
+ request.setUseStirlingOfficeConvert(true);
+ request.setIncludeAttachments(true);
+ request.setMaxAttachmentSizeMB(1);
+ try (var pdf = Loader.loadPDF(body(controller.convertEmlToPdf(request)))) {
+ var names = pdf.getDocumentCatalog().getNames();
+ assertThat(names == null || names.getEmbeddedFiles() == null).isTrue();
+ }
+ }
+
+ @Test
+ void keepsHtmlDownloadAndSanitizationIndependentOfTheRenderer() throws Exception {
+ var request = request(email(new byte[0]), "eml");
+ request.setUseStirlingOfficeConvert(true);
+ request.setDownloadHtml(true);
+ var response = controller.convertEmlToPdf(request);
+ assertThat(response.getHeaders().getContentType()).isEqualTo(MediaType.TEXT_HTML);
+ assertThat(new String(body(response), StandardCharsets.UTF_8))
+ .contains("Email conversion content")
+ .doesNotContain("<script", "http://127.0.0.1");
+ org.mockito.Mockito.verifyNoInteractions(toPdf);
+
+ request.setDownloadHtml(false);
+ body(controller.convertEmlToPdf(request));
+ var html = ArgumentCaptor.forClass(byte[].class);
+ verify(toPdf).convertHtml(html.capture(), eq(false));
+ assertThat(new String(html.getValue(), StandardCharsets.UTF_8))
+ .doesNotContain("<script", "http://127.0.0.1");
+ }
+
+ @Test
+ void rendererFailureReturnsTheConversionReason() throws Exception {
+ var request = request(email(new byte[0]), "eml");
+ request.setUseStirlingOfficeConvert(true);
+ doThrow(new IOException("Only part of email content could be converted"))
+ .when(toPdf)
+ .convertHtml(any(), eq(false));
+
+ var response = controller.convertEmlToPdf(request);
+
+ assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
+ try (var stream = response.getBody().getInputStream()) {
+ assertThat(new String(stream.readAllBytes(), StandardCharsets.UTF_8))
+ .contains("Only part of email content could be converted");
+ }
+ }
+
+ private static EmlToPdfRequest request(byte[] input, String extension) {
+ var request = new EmlToPdfRequest();
+ request.setFileInput(
+ new MockMultipartFile(
+ "fileInput", "message." + extension, "application/octet-stream", input));
+ return request;
+ }
+
+ private static byte[] body(ResponseEntity<Resource> response) throws Exception {
+ assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
+ try (var stream = response.getBody().getInputStream()) {
+ return stream.readAllBytes();
+ }
+ }
+
+ private static byte[] email(byte[] attachment) {
+ String message =
+ + "Subject: Office email conversion\r\nMIME-Version: 1.0\r\n"
+ + "Content-Type: multipart/mixed; boundary=mail-boundary\r\n\r\n"
+ + "--mail-boundary\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n"
+ + "<p>Email conversion content</p><script>alert('unsafe')</script>"
+ + "<img src=\"http://127.0.0.1/private\">\r\n"
+ + "--mail-boundary\r\nContent-Type: text/plain; name=note.txt\r\n"
+ + "Content-Disposition: attachment; filename=note.txt\r\n"
+ + "Content-Transfer-Encoding: base64\r\n\r\n"
+ + Base64.getMimeEncoder().encodeToString(attachment)
+ + "\r\n--mail-boundary--\r\n";
+ return message.getBytes(StandardCharsets.UTF_8);
+ }
+}
diff --git a/app/core/src/test/java/stirling/software/SPDF/model/api/converters/ConvertPDFToMarkdownTest.java b/app/core/src/test/java/stirling/software/SPDF/model/api/converters/ConvertPDFToMarkdownTest.java
index 6d5395b2fa..fba5224ea2 100644
--- a/app/core/src/test/java/stirling/software/SPDF/model/api/converters/ConvertPDFToMarkdownTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/model/api/converters/ConvertPDFToMarkdownTest.java
@@ -30,7 +30,11 @@ import stirling.software.jpdfium.PdfDocument;
class ConvertPDFToMarkdownTest {
private MockMvc mockMvc(PdfMarkdownExtractor extractor) {
- return MockMvcBuilders.standaloneSetup(new ConvertPDFToMarkdown(null, extractor))
+ return MockMvcBuilders.standaloneSetup(
+ new ConvertPDFToMarkdown(
+ null,
+ extractor,
+ mock(stirling.software.SPDF.service.OfficeConversionService.class)))
.setControllerAdvice(new GlobalErrorHandler())
.build();
}
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
index fbcac8d181..9f359be369 100644
--- a/app/core/src/test/java/stirling/software/SPDF/service/OfficeConversionServiceTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/service/OfficeConversionServiceTest.java
@@ -40,7 +40,7 @@ class OfficeConversionServiceTest {
@BeforeEach
void setUp() {
- service = new OfficeConversionService(properties, endpoints);
+ service = new OfficeConversionService(properties, endpoints, null, null);
}
@ParameterizedTest(name = "legacy={0}, LibreOffice={1} -> Stirling Office Convert {2}")
@@ -105,7 +105,7 @@ class OfficeConversionServiceTest {
}
Path pdf = dir.resolve("out.pdf");
properties.getSystem().setStirlingOfficeConversion(true);
- OfficeToPdfService toPdf = new OfficeToPdfService(service, properties);
+ OfficeToPdfService toPdf = new OfficeToPdfService(service, properties, null);
assertThat(toPdf.handles("docx")).isTrue();
toPdf.convert(docx, pdf);
@@ -117,7 +117,7 @@ class OfficeConversionServiceTest {
@Test
void leavesUnknownFormatsAndLegacyToLibreOffice() {
- OfficeToPdfService toPdf = new OfficeToPdfService(service, properties);
+ OfficeToPdfService toPdf = new OfficeToPdfService(service, properties, null);
assertThat(toPdf.handles("html")).isFalse();
properties.getSystem().setStirlingOfficeConversion(false);
@@ -127,7 +127,7 @@ class OfficeConversionServiceTest {
@Test
void fallsBackOnlyWhenLibreOfficeCanHelp() {
- OfficeToPdfService toPdf = new OfficeToPdfService(service, properties);
+ OfficeToPdfService toPdf = new OfficeToPdfService(service, properties, null);
when(endpoints.isGroupEnabled("LibreOffice")).thenReturn(true);
assertThat(toPdf.canFallBack(new IOException("bad file"))).isTrue();
diff --git a/app/core/src/test/java/stirling/software/SPDF/service/OfficeToPdfServiceTest.java b/app/core/src/test/java/stirling/software/SPDF/service/OfficeToPdfServiceTest.java
new file mode 100644
index 0000000000..e074b22355
--- /dev/null
+++ b/app/core/src/test/java/stirling/software/SPDF/service/OfficeToPdfServiceTest.java
@@ -0,0 +1,56 @@
+package stirling.software.SPDF.service;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.List;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.mockito.MockedStatic;
+
+import stirling.software.common.model.ApplicationProperties;
+import stirling.software.officeconvert.topdf.OfficeToPdf;
+
+class OfficeToPdfServiceTest {
+ private final OfficeConversionService conversions = mock(OfficeConversionService.class);
+ private final OfficeToPdfService service =
+ new OfficeToPdfService(conversions, new ApplicationProperties(), null);
+ private final Path input = Path.of("document.docx");
+ private final Path output = Path.of("document.pdf");
+
+ @ParameterizedTest
+ @CsvSource({"true,false,false", "true,false,true", "false,true,false", "false,true,true"})
+ void incompleteOutputFailsAndOnlyAnAvailableLibreOfficeCanRetry(
+ boolean truncated, boolean pageLimitReached, boolean libreOffice) throws Exception {
+ var options = service.options();
+ when(conversions.libreOfficeAvailable()).thenReturn(libreOffice);
+ try (MockedStatic<OfficeToPdf> engine = mockStatic(OfficeToPdf.class)) {
+ engine.when(() -> OfficeToPdf.convert(input, output, options))
+ .thenReturn(new OfficeToPdf.Result(1, truncated, List.of(), pageLimitReached));
+
+ IOException failure =
+ assertThrows(IOException.class, () -> service.convert(input, output, options));
+
+ assertThat(failure).hasMessage("Only part of document.docx could be converted");
+ assertThat(service.canFallBack(failure)).isEqualTo(libreOffice);
+ }
+ }
+
+ @Test
+ void completeOutputIsAccepted() throws Exception {
+ var options = service.options();
+ try (MockedStatic<OfficeToPdf> engine = mockStatic(OfficeToPdf.class)) {
+ engine.when(() -> OfficeToPdf.convert(input, output, options))
+ .thenReturn(new OfficeToPdf.Result(1, false, List.of(), false));
+
+ service.convert(input, output, options);
+ }
+ }
+}
diff --git a/app/core/src/test/resources/eml/example.msg b/app/core/src/test/resources/eml/example.msg
new file mode 100644
index 0000000000..ffb7f03983
Binary files /dev/null and b/app/core/src/test/resources/eml/example.msg differ
diff --git a/build.gradle b/build.gradle
index 741897cd74..d6667a3bb6 100644
--- a/build.gradle
+++ b/build.gradle
@@ -23,7 +23,7 @@ import stirling.software.gradle.ModuleLicenseOverrideFilter
ext {
springBootVersion = "4.1.2"
pdfboxVersion = "3.0.8"
- officeConvertVersion = "0.2.2"
+ officeConvertVersion = "0.3.3"
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 7ad7dc30ca..a36c6969f7 100644
--- a/engine/src/stirling/models/tool_models.py
+++ b/engine/src/stirling/models/tool_models.py
@@ -531,7 +531,7 @@ class OptimizeForEbook(Enum):
class EbookToPdfParams(ApiModel):
"""
- This endpoint converts common eBook formats (EPUB, MOBI, AZW3, FB2, TXT, DOCX) to PDF using Calibre. Input:EBOOK Output:PDF Type:SISO
+ This endpoint converts common eBook formats (EPUB, MOBI, AZW3, FB2, TXT, DOCX) to PDF using Calibre or Stirling Office Convert. Input:EBOOK Output:PDF Type:SISO
"""
embed_all_fonts: EmbedAllFonts = Field(
@@ -547,6 +547,9 @@ class EbookToPdfParams(ApiModel):
OptimizeForEbook.boolean_false,
description="Optimize the PDF for eBook reading (smaller file size, better rendering on eInk devices)",
)
+ use_stirling_office_convert: bool | None = Field(
+ None, description="Use Stirling Office Convert; when omitted, follow the server setting"
+ )
class EditTableOfContentsParams(ApiModel):
@@ -587,6 +590,9 @@ class EmlToPdfParams(ApiModel):
ge=1,
le=100,
)
+ use_stirling_office_convert: bool | None = Field(
+ None, description="Use Stirling Office Convert; when omitted, follow the server setting"
+ )
class ExtractAttachmentsParams(ApiModel):
@@ -665,6 +671,9 @@ class HtmlToPdfParams(ApiModel):
This endpoint takes an HTML or ZIP file input and converts it to a PDF format. Input:HTML/ZIP Output:PDF Type:SISO
"""
+ use_stirling_office_convert: bool | None = Field(
+ None, description="Use Stirling Office Convert; when omitted, follow the server setting"
+ )
zoom: float = Field(1, description="Zoom level for displaying the website. Default is '1'.")
@@ -720,6 +729,8 @@ class MarkdownToPdfParams(ApiModel):
This endpoint takes a Markdown file or ZIP (containing Markdown + images) input, converts it to HTML, and then to PDF format. Input:MARKDOWN/ZIP Output:PDF Type:SISO
"""
+ use_stirling_office_convert: bool | None = None
+
class SortType(StrEnum):
"""
@@ -960,7 +971,7 @@ class TargetDevice(StrEnum):
class PdfToEpubParams(ApiModel):
"""
- Convert a PDF file to a high-quality EPUB or AZW3 ebook using Calibre. Input:PDF Output:EBOOK Type:SISO
+ Convert a PDF file to an EPUB or AZW3 ebook using Calibre or Stirling Office Convert. Input:PDF Output:EBOOK Type:SISO
"""
detect_chapters: DetectChapters = Field(
@@ -970,6 +981,9 @@ class PdfToEpubParams(ApiModel):
target_device: TargetDevice = Field(
TargetDevice.tablet_phone_images, description="Choose an output profile optimized for the reader device."
)
+ use_stirling_office_convert: bool | None = Field(
+ None, description="Use Stirling Office Convert; when omitted, follow the server setting"
+ )
class PdfToHtmlParams(ApiModel):
@@ -977,6 +991,8 @@ class PdfToHtmlParams(ApiModel):
This endpoint converts a PDF file to HTML format. Input:PDF Output:ZIP Type:SISO
"""
+ use_stirling_office_convert: bool | None = None
+
class ImageFormat(StrEnum):
"""
@@ -1023,6 +1039,8 @@ class PdfToMarkdownParams(ApiModel):
This endpoint converts a PDF file to Markdown format. Input:PDF Output:MARKDOWN Type:SISO
"""
+ use_stirling_office_convert: bool | None = None
+
class OutputFormat1(StrEnum):
"""
@@ -1043,7 +1061,7 @@ class OutputFormat1(StrEnum):
class PdfToPdfaParams(ApiModel):
"""
- This endpoint converts a PDF file to a PDF/A or PDF/X file using Ghostscript (preferred) or PDFBox/LibreOffice (fallback). PDF/A is a format designed for long-term archiving, while PDF/X is optimized for print production. Input:PDF Output:PDF Type:SISO
+ This endpoint converts a PDF file to PDF/A using Stirling Office Convert, or to a PDF/A or PDF/X file using Ghostscript (preferred) or PDFBox/LibreOffice (fallback). PDF/A is a format designed for long-term archiving, while PDF/X is optimized for print production. Input:PDF Output:PDF Type:SISO
"""
output_format: OutputFormat1 = Field(..., description="The output format type (PDF/A or PDF/X)")
@@ -1054,6 +1072,9 @@ class PdfToPdfaParams(ApiModel):
strict: bool | None = Field(
None, description="If true, the conversion will fail if the output is not perfectly compliant"
)
+ use_stirling_office_convert: bool | None = Field(
+ None, description="Use Stirling Office Convert; when omitted, follow the server setting"
+ )
class OutputFormat2(StrEnum):
@@ -1227,6 +1248,8 @@ class PdfToXmlParams(ApiModel):
This endpoint converts a PDF file to an XML file. Input:PDF Output:XML Type:SISO
"""
+ use_stirling_office_convert: bool | None = None
+
class CustomMode(StrEnum):
"""
diff --git a/frontend/src/editor/core/components/tools/convert/ConvertOfficeEngineSettings.test.tsx b/frontend/src/editor/core/components/tools/convert/ConvertOfficeEngineSettings.test.tsx
new file mode 100644
index 0000000000..d1f3a9dcae
--- /dev/null
+++ b/frontend/src/editor/core/components/tools/convert/ConvertOfficeEngineSettings.test.tsx
@@ -0,0 +1,59 @@
+import { MantineProvider } from "@mantine/core";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { describe, expect, test, vi } from "vitest";
+import ConvertOfficeEngineSettings from "@editor/components/tools/convert/ConvertOfficeEngineSettings";
+import { defaultParameters } from "@editor/hooks/tools/convert/useConvertParameters";
+
+const config = vi.hoisted(() => ({ stirlingOfficeConversion: false }));
+vi.mock("@editor/contexts/AppConfigContext", () => ({
+ useAppConfig: () => ({ config }),
+}));
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (_key: string, fallback: string) => fallback }),
+}));
+
+describe("Office conversion engine setting", () => {
+ test.each([
+ [false, undefined, false],
+ [true, undefined, true],
+ [true, false, false],
+ [false, true, true],
+ ])("server=%s, choice=%s gives checked=%s", (server, choice, checked) => {
+ config.stirlingOfficeConversion = server;
+ const onParameterChange = vi.fn();
+ render(
+ <MantineProvider>
+ <ConvertOfficeEngineSettings
+ parameters={{
+ ...defaultParameters,
+ useStirlingOfficeConvert: choice,
+ }}
+ onParameterChange={onParameterChange}
+ />
+ </MantineProvider>,
+ );
+ const control = screen.getByTestId("stirling-office-convert-switch");
+ expect(control).toHaveProperty("checked", checked);
+ fireEvent.click(control);
+ expect(onParameterChange).toHaveBeenCalledWith(
+ "useStirlingOfficeConvert",
+ !checked,
+ );
+ });
+
+ test("disables the choice during processing", () => {
+ render(
+ <MantineProvider>
+ <ConvertOfficeEngineSettings
+ parameters={defaultParameters}
+ onParameterChange={vi.fn()}
+ disabled
+ />
+ </MantineProvider>,
+ );
+ expect(screen.getByTestId("stirling-office-convert-switch")).toHaveProperty(
+ "disabled",
+ true,
+ );
+ });
+});
diff --git a/frontend/src/editor/core/components/tools/convert/ConvertOfficeEngineSettings.tsx b/frontend/src/editor/core/components/tools/convert/ConvertOfficeEngineSettings.tsx
index 924c84f4a4..812f1904dc 100644
--- a/frontend/src/editor/core/components/tools/convert/ConvertOfficeEngineSettings.tsx
+++ b/frontend/src/editor/core/components/tools/convert/ConvertOfficeEngineSettings.tsx
@@ -1,29 +1,25 @@
import { Switch } from "@mantine/core";
import { useTranslation } from "react-i18next";
-import { useAppConfig } from "@editor/contexts/AppConfigContext";
+import { useOfficeConversionDefault } from "@editor/hooks/useOfficeConversionDefault";
import { ConvertParameters } from "@editor/hooks/tools/convert/useConvertParameters";
interface ConvertOfficeEngineSettingsProps {
- parameters: ConvertParameters;
- onParameterChange: <K extends keyof ConvertParameters>(
- key: K,
- value: ConvertParameters[K],
- ) => void;
+ parameters: Pick<ConvertParameters, "useStirlingOfficeConvert">;
+ onParameterChange: (key: "useStirlingOfficeConvert", value: boolean) => void;
disabled?: boolean;
+ endpointName?: string;
}
-/** Picks Stirling Office Convert or LibreOffice for this conversion; starts from the server setting. */
+/** Picks Stirling Office Convert or the standard converter; starts from the server setting. */
const ConvertOfficeEngineSettings = ({
parameters,
onParameterChange,
disabled = false,
+ endpointName,
}: ConvertOfficeEngineSettingsProps) => {
const { t } = useTranslation();
- const { config } = useAppConfig();
- const checked =
- parameters.useStirlingOfficeConvert ??
- config?.stirlingOfficeConversion ??
- false;
+ const serverDefault = useOfficeConversionDefault(endpointName);
+ const checked = parameters.useStirlingOfficeConvert ?? serverDefault;
return (
<Switch
diff --git a/frontend/src/editor/core/components/tools/convert/ConvertSettings.tsx b/frontend/src/editor/core/components/tools/convert/ConvertSettings.tsx
index eb4fddfe7e..919db13443 100644
--- a/frontend/src/editor/core/components/tools/convert/ConvertSettings.tsx
+++ b/frontend/src/editor/core/components/tools/convert/ConvertSettings.tsx
@@ -1,4 +1,5 @@
import { useMemo } from "react";
+import { useOfficeConversionDefault } from "@editor/hooks/useOfficeConversionDefault";
import { Stack, Text, Group, Divider, useMantineTheme } from "@mantine/core";
import { Button } from "@editor/ui/Button";
import { Icon } from "@editor/ui/Icon";
@@ -9,6 +10,7 @@ import {
isWebFormat,
getAvailableToExtensions as defaultGetAvailableToExtensions,
usesOfficeEngine,
+ getEndpointName,
} from "@editor/utils/convertUtils";
import { getConversionEndpoints } from "@editor/data/toolsTaxonomy";
import { usePreferences } from "@editor/contexts/PreferencesContext";
@@ -69,6 +71,12 @@ const ConvertSettings = ({
}: ConvertSettingsProps) => {
const { t } = useTranslation();
const theme = useMantineTheme();
+ const endpointName = getEndpointName(
+ parameters.fromExtension,
+ parameters.toExtension,
+ );
+ const serverDefault = useOfficeConversionDefault(endpointName);
+ const officeConvert = parameters.useStirlingOfficeConvert ?? serverDefault;
const { preferences } = usePreferences();
const localProcessingOnly = useLocalProcessingOnly();
const hideUnavailableConversions =
@@ -392,10 +400,11 @@ const ConvertSettings = ({
)}
{/* Web to PDF options */}
- {(isWebFormat(parameters.fromExtension) &&
+ {!officeConvert &&
+ ((isWebFormat(parameters.fromExtension) &&
parameters.toExtension === "pdf") ||
- (parameters.isSmartDetection &&
- parameters.smartDetectionType === "web") ? (
+ (parameters.isSmartDetection &&
+ parameters.smartDetectionType === "web")) ? (
<>
<Divider />
<ConvertFromWebSettings
@@ -527,17 +536,21 @@ const ConvertSettings = ({
</>
)}
- {/* Stirling Office Convert or LibreOffice */}
- {usesOfficeEngine(parameters.fromExtension, parameters.toExtension) && (
+ {usesOfficeEngine(parameters.fromExtension, parameters.toExtension) &&
+ !(
+ ["eml", "msg"].includes(parameters.fromExtension) &&
+ parameters.emailOptions.downloadHtml
+ ) ? (
<>
<Divider />
<ConvertOfficeEngineSettings
+ endpointName={endpointName}
parameters={parameters}
onParameterChange={onParameterChange}
disabled={disabled}
/>
</>
- )}
+ ) : null}
{/* PDF to EPUB/AZW3 options */}
{parameters.fromExtension === "pdf" &&
diff --git a/frontend/src/editor/core/hooks/tools/convert/convertErrors.test.ts b/frontend/src/editor/core/hooks/tools/convert/convertErrors.test.ts
new file mode 100644
index 0000000000..992d19f773
--- /dev/null
+++ b/frontend/src/editor/core/hooks/tools/convert/convertErrors.test.ts
@@ -0,0 +1,118 @@
+import { AxiosError } from "axios";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { convertProcessor } from "@editor/hooks/tools/convert/useConvertOperation";
+import { defaultParameters } from "@editor/hooks/tools/convert/useConvertParameters";
+import { expectConsole } from "@editor/tests/failOnConsole";
+
+const api = vi.hoisted(() => ({ post: vi.fn() }));
+vi.mock("@editor/services/apiClient", () => ({
+ default: {
+ post: api.post,
+ get: vi.fn(),
+ put: vi.fn(),
+ delete: vi.fn(),
+ interceptors: { response: { use: vi.fn() } },
+ },
+}));
+
+const parameters = {
+ ...defaultParameters,
+ fromExtension: "epub",
+ toExtension: "pdf",
+ useStirlingOfficeConvert: true,
+};
+const ebook = (name: string) =>
+ new File(["ebook"], name, { type: "application/epub+zip" });
+const reason = "Only part of book.epub could be converted";
+
+const failedResponse = () => ({
+ status: 500,
+ statusText: "Internal Server Error",
+ headers: {},
+ config: { headers: {} },
+ data: new Blob([JSON.stringify({ detail: reason })], {
+ type: "application/problem+json",
+ }),
+});
+
+beforeEach(() => {
+ api.post.mockReset();
+});
+
+describe("conversion failure reasons", () => {
+ test.each(["browser", "desktop"])(
+ "preserves the backend reason and HTTP metadata for %s errors",
+ async (kind) => {
+ const error =
+ kind === "browser"
+ ? Object.assign(
+ new AxiosError("Request failed with status code 500"),
+ { response: failedResponse() },
+ )
+ : {
+ isAxiosError: true,
+ message: "Request failed with status code 500",
+ response: failedResponse(),
+ };
+ const payload = error.response?.data;
+ api.post.mockRejectedValueOnce(error);
+
+ await expect(
+ convertProcessor(parameters, [ebook("book.epub")]),
+ ).rejects.toBe(error);
+
+ expect(error.message).toBe(reason);
+ expect(error.response?.status).toBe(500);
+ expect(error.response?.data).toBe(payload);
+ },
+ );
+
+ test("reports the first server reason when every ebook fails", async () => {
+ expectConsole.warn(/Failed to convert file book.epub/);
+ expectConsole.warn(/Failed to convert file other.epub/);
+ const error = Object.assign(new AxiosError("Request failed"), {
+ response: failedResponse(),
+ });
+ api.post
+ .mockRejectedValueOnce(error)
+ .mockRejectedValueOnce(new Error("Second conversion failed"));
+
+ await expect(
+ convertProcessor(parameters, [ebook("book.epub"), ebook("other.epub")]),
+ ).rejects.toBe(error);
+
+ expect(error.message).toBe(reason);
+ expect(api.post).toHaveBeenCalledTimes(2);
+ });
+
+ test("keeps a successful ebook when another conversion fails", async () => {
+ expectConsole.warn(/Failed to convert file other.epub/);
+ api.post
+ .mockResolvedValueOnce({
+ data: new Blob(["%PDF"], { type: "application/pdf" }),
+ headers: {},
+ })
+ .mockRejectedValueOnce(
+ Object.assign(new AxiosError("Request failed"), {
+ response: failedResponse(),
+ }),
+ );
+
+ const result = await convertProcessor(parameters, [
+ ebook("book.epub"),
+ ebook("other.epub"),
+ ]);
+
+ expect(result.files).toHaveLength(1);
+ expect(result.files[0].name).toBe("book.pdf");
+ });
+
+ test("preserves network failures that have no server response", async () => {
+ const error = new Error("Network unavailable");
+ api.post.mockRejectedValueOnce(error);
+
+ await expect(
+ convertProcessor(parameters, [ebook("book.epub")]),
+ ).rejects.toBe(error);
+ });
+});
diff --git a/frontend/src/editor/core/hooks/tools/convert/officeConversionRequests.test.ts b/frontend/src/editor/core/hooks/tools/convert/officeConversionRequests.test.ts
new file mode 100644
index 0000000000..60fd7f5af9
--- /dev/null
+++ b/frontend/src/editor/core/hooks/tools/convert/officeConversionRequests.test.ts
@@ -0,0 +1,108 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import {
+ convertFromApiParams,
+ convertProcessor,
+ convertToApiParams,
+} from "@editor/hooks/tools/convert/useConvertOperation";
+import { defaultParameters } from "@editor/hooks/tools/convert/useConvertParameters";
+
+const api = vi.hoisted(() => ({ post: vi.fn() }));
+vi.mock("@editor/services/apiClient", () => ({
+ default: {
+ post: api.post,
+ get: vi.fn(),
+ put: vi.fn(),
+ delete: vi.fn(),
+ interceptors: { response: { use: vi.fn() } },
+ },
+}));
+
+const OFFICE_ROUTES = [
+ ["pdf", "docx", "pdf/word", "pdf-to-word"],
+ ["pdf", "odt", "pdf/word", "pdf-to-word"],
+ ["pdf", "pptx", "pdf/presentation", "pdf-to-presentation"],
+ ["pdf", "odp", "pdf/presentation", "pdf-to-presentation"],
+ ["pdf", "txt", "pdf/text", "pdf-to-text"],
+ ["pdf", "rtf", "pdf/text", "pdf-to-rtf"],
+ ["pdf", "xlsx", "pdf/xlsx", "pdf-to-xlsx"],
+ ["pdf", "html", "pdf/html", "pdf-to-html"],
+ ["pdf", "md", "pdf/markdown", "pdf-to-markdown"],
+ ["pdf", "xml", "pdf/xml", "pdf-to-xml"],
+ ["pdf", "pdfa", "pdf/pdfa", "pdf-to-pdfa"],
+ ["pdf", "epub", "pdf/epub", "pdf-to-epub"],
+ ["pdf", "azw3", "pdf/epub", "pdf-to-epub"],
+ ["docx", "pdf", "file/pdf", "file-to-pdf"],
+ ["doc", "pdf", "file/pdf", "file-to-pdf"],
+ ["odt", "pdf", "file/pdf", "file-to-pdf"],
+ ["xlsx", "pdf", "file/pdf", "file-to-pdf"],
+ ["xls", "pdf", "file/pdf", "file-to-pdf"],
+ ["ods", "pdf", "file/pdf", "file-to-pdf"],
+ ["pptx", "pdf", "file/pdf", "file-to-pdf"],
+ ["ppt", "pdf", "file/pdf", "file-to-pdf"],
+ ["odp", "pdf", "file/pdf", "file-to-pdf"],
+ ["rtf", "pdf", "file/pdf", "file-to-pdf"],
+ ["txt", "pdf", "file/pdf", "file-to-pdf"],
+ ["file-vsdx", "pdf", "file/pdf", "file-to-pdf"],
+ ["html", "pdf", "html/pdf", "html-to-pdf"],
+ ["zip", "pdf", "html/pdf", "html-to-pdf"],
+ ["md", "pdf", "markdown/pdf", "markdown-to-pdf"],
+ ["eml", "pdf", "eml/pdf", "eml-to-pdf"],
+ ["msg", "pdf", "eml/pdf", "eml-to-pdf"],
+ ["epub", "pdf", "ebook/pdf", "ebook-to-pdf"],
+ ["mobi", "pdf", "ebook/pdf", "ebook-to-pdf"],
+ ["azw3", "pdf", "ebook/pdf", "ebook-to-pdf"],
+ ["fb2", "pdf", "ebook/pdf", "ebook-to-pdf"],
+];
+
+beforeEach(() => {
+ api.post
+ .mockReset()
+ .mockResolvedValue({ data: new Blob(["converted"]), headers: {} });
+});
+
+describe.each([true, false, undefined])(
+ "Office conversion requests with choice %s",
+ (choice) => {
+ test.each(OFFICE_ROUTES)(
+ "%s to %s sends the selected Office engine to %s",
+ async (fromExtension, toExtension, path, endpointName) => {
+ const parameters = {
+ ...defaultParameters,
+ fromExtension,
+ toExtension,
+ useStirlingOfficeConvert: choice,
+ };
+ const files = ["first"].map(
+ (name) =>
+ new File([name], `${name}.${fromExtension.replace("file-", "")}`),
+ );
+
+ const result = await convertProcessor(parameters, files);
+
+ expect(result.files).toHaveLength(1);
+ expect(api.post).toHaveBeenCalledTimes(1);
+ for (let index = 0; index < files.length; index++) {
+ const [url, form, config] = api.post.mock.calls[index];
+ expect(url).toBe(`/api/v1/convert/${path}`);
+ expect(config.endpointName).toBe(endpointName);
+ expect(form.getAll("fileInput")).toEqual([files[index]]);
+ expect(form.get("useStirlingOfficeConvert")).toBe(
+ choice === undefined ? null : String(choice),
+ );
+ }
+
+ const saved = convertToApiParams(parameters);
+ expect(convertFromApiParams(saved).useStirlingOfficeConvert).toBe(
+ choice,
+ );
+ if (choice !== undefined) {
+ expect(
+ convertFromApiParams(
+ Object.assign(saved, { useStirlingOfficeConvert: choice }),
+ ).useStirlingOfficeConvert,
+ ).toBe(choice);
+ }
+ },
+ );
+ },
+);
diff --git a/frontend/src/editor/core/hooks/tools/convert/useConvertOperation.ts b/frontend/src/editor/core/hooks/tools/convert/useConvertOperation.ts
index f62c2af40f..af6add70ae 100644
--- a/frontend/src/editor/core/hooks/tools/convert/useConvertOperation.ts
+++ b/frontend/src/editor/core/hooks/tools/convert/useConvertOperation.ts
@@ -1,5 +1,7 @@
import { useCallback, useMemo } from "react";
+import axios from "axios";
import apiClient from "@editor/services/apiClient";
+import { serverErrorReason } from "@editor/services/errorUtils";
import { useTranslation } from "react-i18next";
import {
validateConvertParameters,
@@ -19,6 +21,7 @@ import {
isWebFormat,
isOfficeFormat,
usesOfficeEngine,
+ parseOfficeEngineChoice,
} from "@editor/utils/convertUtils";
import {
isToolEndpoint,
@@ -150,7 +153,12 @@ export const buildConvertFormData = (
(fromExtension === "html" || fromExtension === "zip") &&
toExtension === "pdf"
) {
- formData.append("zoom", htmlOptions.zoomLevel.toString());
+ formData.append(
+ "zoom",
+ parameters.useStirlingOfficeConvert
+ ? "1"
+ : htmlOptions.zoomLevel.toString(),
+ );
} else if (
(fromExtension === "eml" || fromExtension === "msg") &&
toExtension === "pdf"
@@ -277,13 +285,26 @@ const withoutCrossFileAltText = (
}
: parameters;
-// Static processor that can be used by both the hook and automation executor
+const rethrowWithServerReason = async (error: unknown): Promise<never> => {
+ const reason = await serverErrorReason(error);
+ if (reason && axios.isAxiosError(error)) {
+ // Preserve HTTP status and payload for authentication and corrupt-file handling.
+ error.message = reason;
+ }
+ throw error;
+};
+
+/**
+ * Keeps successful files after partial batch failures. If every file fails, rethrows the first
+ * error with the server's reason while preserving its HTTP metadata.
+ */
export const convertProcessor = async (
rawParameters: ConvertParameters,
selectedFiles: File[],
): Promise<CustomProcessorResult> => {
const parameters = withoutCrossFileAltText(rawParameters, selectedFiles);
const processedFiles: File[] = [];
+ let firstFailure: unknown;
// Map PDF/X to use PDF/A endpoint
const actualToExtension =
@@ -311,11 +332,9 @@ export const convertProcessor = async (
for (const file of selectedFiles) {
try {
const formData = buildConvertFormData(parameters, [file]);
- const response = await apiClient.post(
- endpoint,
- formData,
- requestConfig,
- );
+ const response = await apiClient
+ .post(endpoint, formData, requestConfig)
+ .catch(rethrowWithServerReason);
const convertedFile = createFileFromResponse(
response.data,
@@ -326,13 +345,19 @@ export const convertProcessor = async (
processedFiles.push(convertedFile);
} catch (error) {
+ firstFailure ??= error;
console.warn(`Failed to convert file ${file.name}:`, error);
}
}
+ if (processedFiles.length === 0 && firstFailure !== undefined) {
+ throw firstFailure;
+ }
} else {
// Batch processing for simple cases (image→PDF combine)
const formData = buildConvertFormData(parameters, selectedFiles);
- const response = await apiClient.post(endpoint, formData, requestConfig);
+ const response = await apiClient
+ .post(endpoint, formData, requestConfig)
+ .catch(rethrowWithServerReason);
const baseFilename =
selectedFiles.length === 1 ? selectedFiles[0].name : "converted_files";
@@ -596,9 +621,14 @@ export const convertFromApiParams = (
// Each reader reads only its own endpoint's fields; the runtime endpoint is just a string, so
// readOptions is looked up per-endpoint (undefined when the pair has no reader).
const readOptions = endpoint ? CONVERT_OPTION_READERS[endpoint] : undefined;
+ const officeChoice = parseOfficeEngineChoice(body.useStirlingOfficeConvert);
return {
fromExtension,
toExtension,
+ ...(usesOfficeEngine(fromExtension, toExtension) &&
+ officeChoice !== undefined
+ ? { useStirlingOfficeConvert: officeChoice }
+ : {}),
...(readOptions ? readOptions(body, toExtension) : {}),
};
};
diff --git a/frontend/src/editor/core/hooks/useOfficeConversionDefault.ts b/frontend/src/editor/core/hooks/useOfficeConversionDefault.ts
new file mode 100644
index 0000000000..af962f9fb9
--- /dev/null
+++ b/frontend/src/editor/core/hooks/useOfficeConversionDefault.ts
@@ -0,0 +1,7 @@
+import { useAppConfig } from "@editor/contexts/AppConfigContext";
+
+/** The executing server's default; omitting the endpoint selects the connected policy server. */
+export function useOfficeConversionDefault(_endpointName?: string): boolean {
+ const { config } = useAppConfig();
+ return Boolean(config?.stirlingOfficeConversion);
+}
diff --git a/frontend/src/editor/core/tests/stubbed/convert.spec.ts b/frontend/src/editor/core/tests/stubbed/convert.spec.ts
index 7841eaa01a..525ee4c72e 100644
--- a/frontend/src/editor/core/tests/stubbed/convert.spec.ts
+++ b/frontend/src/editor/core/tests/stubbed/convert.spec.ts
@@ -77,6 +77,42 @@ test.describe("Convert Tool", () => {
});
});
+ test("offers Office Convert for supported document outputs", async ({
+ page,
+ }, testInfo) => {
+ await uploadFile(page, SAMPLE_PDF);
+ await navigateToConvert(page);
+ for (const format of [
+ "docx",
+ "pptx",
+ "xlsx",
+ "txt",
+ "rtf",
+ "md",
+ "xml",
+ "html",
+ "epub",
+ "azw3",
+ "pdfa",
+ ]) {
+ await selectToFormat(page, format);
+ const choice = page.getByTestId("stirling-office-convert-switch");
+ await expect(choice).toBeVisible();
+ await choice.check();
+ await expect(choice).toBeChecked();
+ await choice.uncheck();
+ }
+ await page.screenshot({
+ path: testInfo.outputPath("office-convert-options.png"),
+ });
+ for (const format of ["png", "pdfx"]) {
+ await selectToFormat(page, format);
+ await expect(
+ page.getByTestId("stirling-office-convert-switch"),
+ ).toHaveCount(0);
+ }
+ });
+
test("convert button is disabled before a TO format is selected", async ({
page,
}) => {
@@ -89,6 +125,55 @@ test.describe("Convert Tool", () => {
await expect(convertBtn).toBeDisabled();
});
+ for (const format of ["eml", "msg"]) {
+ test(`offers Office Convert for ${format.toUpperCase()} while retaining email settings`, async ({
+ page,
+ }) => {
+ await page.route("**/api/v1/convert/eml/pdf", (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: "application/pdf",
+ headers: {
+ "Content-Disposition": 'attachment; filename="email.pdf"',
+ },
+ path: SAMPLE_PDF,
+ }),
+ );
+ await page.getByTestId("files-button").click();
+ await page.getByTestId("file-input").setInputFiles(
+ format === "msg"
+ ? path.resolve("../app/common/src/test/resources/eml/example.msg")
+ : {
+ name: "email.eml",
+ mimeType: "message/rfc822",
+ buffer: Buffer.from(
+ "From: [email protected]\r\nSubject: Email\r\n\r\nEmail content",
+ ),
+ },
+ );
+ await navigateToConvert(page);
+ await selectToFormat(page, "pdf");
+ await expect(page.getByTestId("email-settings")).toBeVisible();
+ const choice = page.getByTestId("stirling-office-convert-switch");
+ await choice.check();
+ await expect(choice).toBeChecked();
+ await page.getByTestId("download-html-checkbox").check();
+ await expect(choice).toHaveCount(0);
+ await page.getByTestId("download-html-checkbox").uncheck();
+ await expect(choice).toBeChecked();
+ await page.getByTestId("include-attachments-checkbox").check();
+ await page.getByTestId("include-all-recipients-checkbox").uncheck();
+ await dismissTourTooltip(page);
+ const request = page.waitForRequest("**/api/v1/convert/eml/pdf");
+ await page.getByTestId("convert-button").click();
+ const payload = (await request).postData() ?? "";
+ expect(payload).toMatch(/name="useStirlingOfficeConvert"\r\n\r\ntrue/);
+ expect(payload).toMatch(/name="includeAttachments"\r\n\r\ntrue/);
+ expect(payload).toMatch(/name="includeAllRecipients"\r\n\r\nfalse/);
+ await expect(page.getByTestId("download-result-button")).toBeVisible();
+ });
+ }
+
test("successful PDF to PNG conversion shows download option", async ({
page,
}) => {
diff --git a/frontend/src/editor/core/types/toolApiTypes.ts b/frontend/src/editor/core/types/toolApiTypes.ts
index 5cae40053a..2ca9920058 100644
--- a/frontend/src/editor/core/types/toolApiTypes.ts
+++ b/frontend/src/editor/core/types/toolApiTypes.ts
@@ -337,9 +337,17 @@ export interface ConvertEbookToPdfRequest {
* Optimize the PDF for eBook reading (smaller file size, better rendering on eInk devices)
*/
optimizeForEbook?: true | false;
+ /**
+ * Use Stirling Office Convert; when omitted, follow the server setting
+ */
+ useStirlingOfficeConvert?: boolean;
+}
+export interface ConvertPdfHtmlRequest {
+ useStirlingOfficeConvert?: boolean;
+}
+export interface ConvertPdfMarkdownRequest {
+ useStirlingOfficeConvert?: boolean;
}
-export type ConvertPdfHtmlRequest = Record<string, never>;
-export type ConvertPdfMarkdownRequest = Record<string, never>;
export interface ConvertPdfToCbrRequest {
/**
* The DPI (Dots Per Inch) for rendering PDF pages as images
@@ -365,8 +373,14 @@ export interface ConvertPdfToEpubRequest {
* Choose an output profile optimized for the reader device.
*/
targetDevice?: "TABLET_PHONE_IMAGES" | "KINDLE_EINK_TEXT";
+ /**
+ * Use Stirling Office Convert; when omitted, follow the server setting
+ */
+ useStirlingOfficeConvert?: boolean;
+}
+export interface ConvertPdfXmlRequest {
+ useStirlingOfficeConvert?: boolean;
}
-export type ConvertPdfXmlRequest = Record<string, never>;
export interface ConvertToImageRequest {
/**
* The color type of the output image(s)
@@ -484,6 +498,10 @@ export interface EmlToPdfRequest {
* Maximum attachment size in MB to include (default 10MB, range: 1-100)
*/
maxAttachmentSizeMB?: number;
+ /**
+ * Use Stirling Office Convert; when omitted, follow the server setting
+ */
+ useStirlingOfficeConvert?: boolean;
}
export type ExtractAttachmentsRequest = Record<string, never>;
export interface ExtractHeaderRequest {
@@ -552,6 +570,10 @@ export interface GeneralFile {
export type GeneralPdfToSinglePageRequest = Record<string, never>;
export type GeneralRemoveImagePdfRequest = Record<string, never>;
export interface HTMLToPdfRequest {
+ /**
+ * Use Stirling Office Convert; when omitted, follow the server setting
+ */
+ useStirlingOfficeConvert?: boolean;
/**
* Zoom level for displaying the website. Default is '1'.
*/
@@ -944,6 +966,10 @@ export interface PdfToPdfARequest {
* If true, the conversion will fail if the output is not perfectly compliant
*/
strict?: boolean;
+ /**
+ * Use Stirling Office Convert; when omitted, follow the server setting
+ */
+ useStirlingOfficeConvert?: boolean;
}
export interface PdfToPdfUaRequest {
/**
diff --git a/frontend/src/editor/core/utils/convertUtils.test.ts b/frontend/src/editor/core/utils/convertUtils.test.ts
index d763ca0bc1..47948d71f5 100644
--- a/frontend/src/editor/core/utils/convertUtils.test.ts
+++ b/frontend/src/editor/core/utils/convertUtils.test.ts
@@ -353,7 +353,7 @@ describe("convertUtils", () => {
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);
+ expect(usesOfficeEngine("pdf", "xml")).toBe(true);
});
});
});
diff --git a/frontend/src/editor/core/utils/convertUtils.ts b/frontend/src/editor/core/utils/convertUtils.ts
index 15e9b331fb..51463e6645 100644
--- a/frontend/src/editor/core/utils/convertUtils.ts
+++ b/frontend/src/editor/core/utils/convertUtils.ts
@@ -32,6 +32,15 @@ const OFFICE_ENGINE_ENDPOINTS = [
"pdf-to-text",
"pdf-to-rtf",
"pdf-to-xlsx",
+ "pdf-to-html",
+ "pdf-to-markdown",
+ "pdf-to-xml",
+ "pdf-to-epub",
+ "pdf-to-pdfa",
+ "html-to-pdf",
+ "markdown-to-pdf",
+ "ebook-to-pdf",
+ "eml-to-pdf",
];
const OFFICE_EXTENSIONS = [
@@ -47,20 +56,110 @@ const OFFICE_EXTENSIONS = [
"ppt",
"pptx",
"odp",
+ "docm",
+ "dot",
+ "dotx",
+ "dotm",
+ "ott",
+ "fodt",
+ "odm",
+ "xlsm",
+ "xlt",
+ "xltx",
+ "xltm",
+ "xlsb",
+ "ots",
+ "fods",
+ "tsv",
+ "tab",
+ "pptm",
+ "pps",
+ "ppsx",
+ "ppsm",
+ "pot",
+ "potx",
+ "potm",
+ "otp",
+ "fodp",
+ "odg",
+ "otg",
+ "fodg",
+ "xml",
+ "sxw",
+ "stw",
+ "sxc",
+ "stc",
+ "sxi",
+ "sti",
+ "sxd",
+ "std",
+ "vsdx",
+ "vsdm",
+ "vssx",
+ "vssm",
+ "vstx",
+ "vstm",
+ "vsd",
+ "vss",
+ "vst",
+ "vsw",
+ "slk",
+ "sylk",
+ "dif",
+ "dbf",
+ "wk1",
+ "wks",
+ "wk3",
+ "wk4",
+ "123",
+ "pages",
+ "numbers",
+ "key",
+ "pub",
+ "text",
+ "log",
+ "asc",
+ "json",
+ "html",
+ "htm",
+ "xhtml",
+ "mobi",
+ "azw3",
+ "azw",
+ "prc",
+ "fb2",
+ "fbz",
+ "htmlz",
];
-/** Whether the conversion can run on Stirling Office Convert instead of LibreOffice. */
+/** Whether the conversion can run on Stirling Office Convert instead of its standard converter. */
export const usesOfficeEngine = (
fromExtension: string,
toExtension: string,
): boolean => {
+ if (toExtension === "pdfx") return false;
const endpoint = getEndpointName(fromExtension, toExtension);
if (endpoint === "file-to-pdf") {
- return OFFICE_EXTENSIONS.includes(fromExtension);
+ return (
+ fromExtension === "any" ||
+ OFFICE_EXTENSIONS.includes(
+ fromExtension.replace(/^file-/, "").toLowerCase(),
+ )
+ );
}
return OFFICE_ENGINE_ENDPOINTS.includes(endpoint);
};
+/** Stored choices may be JSON booleans or multipart strings; absent or invalid values inherit the server setting. */
+export const parseOfficeEngineChoice = (
+ value: unknown,
+): boolean | undefined => {
+ if (typeof value === "boolean") return value;
+ if (value === "true") return true;
+ if (value === "false") return false;
+ return undefined;
+};
+
/**
* Resolves the full endpoint URL for a given conversion
*/
diff --git a/frontend/src/editor/core/utils/officeEngine.test.ts b/frontend/src/editor/core/utils/officeEngine.test.ts
index 76236d2576..d2b6ea837b 100644
--- a/frontend/src/editor/core/utils/officeEngine.test.ts
+++ b/frontend/src/editor/core/utils/officeEngine.test.ts
@@ -1,18 +1,101 @@
import { describe, test, expect } from "vitest";
import { usesOfficeEngine } from "@editor/utils/convertUtils";
-import { buildConvertFormData } from "@editor/hooks/tools/convert/useConvertOperation";
+import {
+ buildConvertFormData,
+ convertFromApiParams,
+ convertToApiParams,
+} from "@editor/hooks/tools/convert/useConvertOperation";
import { defaultParameters } from "@editor/hooks/tools/convert/useConvertParameters";
describe("Stirling Office Convert switch", () => {
- test("applies to Office conversions only", () => {
+ test("applies to supported document conversions", () => {
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("html", "pdf")).toBe(true);
+ expect(usesOfficeEngine("pdf", "md")).toBe(true);
+ expect(usesOfficeEngine("pdf", "xml")).toBe(true);
+ expect(usesOfficeEngine("pdf", "html")).toBe(true);
+ expect(usesOfficeEngine("pdf", "pdfa")).toBe(true);
+ expect(usesOfficeEngine("pdf", "epub")).toBe(true);
+ expect(usesOfficeEngine("pdf", "azw3")).toBe(true);
+ expect(usesOfficeEngine("epub", "pdf")).toBe(true);
+ expect(usesOfficeEngine("file-vsdx", "pdf")).toBe(true);
+ expect(usesOfficeEngine("file-htmlz", "pdf")).toBe(true);
+ expect(usesOfficeEngine("eml", "pdf")).toBe(true);
+ expect(usesOfficeEngine("msg", "pdf")).toBe(true);
+ expect(usesOfficeEngine("pdf", "pdfx")).toBe(false);
expect(usesOfficeEngine("pdf", "png")).toBe(false);
});
+ test.each([
+ ["pdf", "docx"],
+ ["pdf", "pptx"],
+ ["pdf", "xlsx"],
+ ["pdf", "txt"],
+ ["pdf", "rtf"],
+ ["pdf", "md"],
+ ["pdf", "xml"],
+ ["pdf", "html"],
+ ["pdf", "pdfa"],
+ ["pdf", "epub"],
+ ["pdf", "azw3"],
+ ["html", "pdf"],
+ ["zip", "pdf"],
+ ["md", "pdf"],
+ ["epub", "pdf"],
+ ["mobi", "pdf"],
+ ["azw3", "pdf"],
+ ["fb2", "pdf"],
+ ["eml", "pdf"],
+ ["msg", "pdf"],
+ ["file-vsdx", "pdf"],
+ ])(
+ "serializes both engine choices for %s to %s",
+ (fromExtension, toExtension) => {
+ const file = new File(["x"], `input.${fromExtension}`);
+ for (const choice of [true, false]) {
+ const data = buildConvertFormData(
+ {
+ ...defaultParameters,
+ fromExtension,
+ toExtension,
+ useStirlingOfficeConvert: choice,
+ },
+ [file],
+ );
+ expect(data.get("useStirlingOfficeConvert")).toBe(String(choice));
+ }
+ },
+ );
+
+ test.each(["eml", "msg"])(
+ "preserves %s email options and converter choices in saved steps",
+ (fromExtension) => {
+ for (const choice of [true, false, undefined]) {
+ const parameters = {
+ ...defaultParameters,
+ fromExtension,
+ toExtension: "pdf",
+ useStirlingOfficeConvert: choice,
+ emailOptions: {
+ includeAttachments: true,
+ maxAttachmentSizeMB: 3,
+ downloadHtml: false,
+ includeAllRecipients: false,
+ },
+ };
+ expect(convertFromApiParams(convertToApiParams(parameters))).toEqual({
+ fromExtension,
+ toExtension: "pdf",
+ ...(choice !== undefined ? { useStirlingOfficeConvert: choice } : {}),
+ emailOptions: parameters.emailOptions,
+ });
+ }
+ },
+ );
+
test("sends the choice only when one was made", () => {
const file = new File(["x"], "a.pdf", { type: "application/pdf" });
const base = {
diff --git a/frontend/src/editor/desktop/components/tools/convert/ConvertSettings.test.tsx b/frontend/src/editor/desktop/components/tools/convert/ConvertSettings.test.tsx
index 68ccf14631..5c6d52eb2a 100644
--- a/frontend/src/editor/desktop/components/tools/convert/ConvertSettings.test.tsx
+++ b/frontend/src/editor/desktop/components/tools/convert/ConvertSettings.test.tsx
@@ -5,6 +5,9 @@ import ConvertSettings from "@editor/components/tools/convert/ConvertSettings";
import { defaultParameters } from "@editor/hooks/tools/convert/useConvertParameters";
const state = vi.hoisted(() => ({ localOnly: true }));
+vi.mock("@editor/hooks/useOfficeConversionDefault", () => ({
+ useOfficeConversionDefault: () => false,
+}));
vi.mock("@editor/hooks/useLocalProcessingOnly", () => ({
useLocalProcessingOnly: () => state.localOnly,
}));
diff --git a/frontend/src/editor/desktop/hooks/useOfficeConversionDefault.test.ts b/frontend/src/editor/desktop/hooks/useOfficeConversionDefault.test.ts
new file mode 100644
index 0000000000..8ee96f17b1
--- /dev/null
+++ b/frontend/src/editor/desktop/hooks/useOfficeConversionDefault.test.ts
@@ -0,0 +1,50 @@
+import { renderHook } from "@testing-library/react";
+import { describe, expect, test, vi } from "vitest";
+import { useOfficeConversionDefault } from "@editor/hooks/useOfficeConversionDefault";
+
+const state = vi.hoisted(() => ({
+ local: false,
+ cloud: true,
+ saas: false,
+ routed: false,
+ localOnly: false,
+}));
+const remote = vi.hoisted(() => vi.fn());
+vi.mock("@editor/contexts/AppConfigContext", () => ({
+ useAppConfig: () => ({ config: { stirlingOfficeConversion: state.local } }),
+}));
+vi.mock("@editor/hooks/useSaaSMode", () => ({ useSaaSMode: () => state.saas }));
+vi.mock("@editor/hooks/useLocalProcessingOnly", () => ({
+ useLocalProcessingOnly: () => state.localOnly,
+}));
+vi.mock("@editor/hooks/useToolCloudStatus", () => ({
+ useToolCloudStatus: () => state.routed,
+}));
+vi.mock("@editor/hooks/useSaasAppConfig", () => ({
+ useSaasAppConfig: (enabled: boolean) => {
+ remote(enabled);
+ return enabled ? { stirlingOfficeConversion: state.cloud } : null;
+ },
+}));
+
+describe("desktop Office Convert default", () => {
+ test.each([
+ [false, false, false, false, true, "html-to-pdf", false, false],
+ [false, false, false, true, false, "html-to-pdf", true, false],
+ [true, false, false, true, false, "html-to-pdf", true, false],
+ [true, true, false, false, true, "html-to-pdf", true, true],
+ [true, true, false, true, false, "html-to-pdf", false, true],
+ [true, true, true, false, true, "html-to-pdf", false, false],
+ [true, false, false, false, true, undefined, true, true],
+ [true, false, true, false, true, undefined, false, false],
+ ] as const)(
+ "saas=%s routed=%s localOnly=%s local=%s cloud=%s endpoint=%s",
+ (saas, routed, localOnly, local, cloud, endpoint, expected, fetchCloud) => {
+ Object.assign(state, { saas, routed, localOnly, local, cloud });
+ remote.mockClear();
+ const { result } = renderHook(() => useOfficeConversionDefault(endpoint));
+ expect(result.current).toBe(expected);
+ expect(remote).toHaveBeenLastCalledWith(fetchCloud);
+ },
+ );
+});
diff --git a/frontend/src/editor/desktop/hooks/useOfficeConversionDefault.ts b/frontend/src/editor/desktop/hooks/useOfficeConversionDefault.ts
new file mode 100644
index 0000000000..15ae0b4824
--- /dev/null
+++ b/frontend/src/editor/desktop/hooks/useOfficeConversionDefault.ts
@@ -0,0 +1,17 @@
+import { useAppConfig } from "@editor/contexts/AppConfigContext";
+import { useLocalProcessingOnly } from "@editor/hooks/useLocalProcessingOnly";
+import { useSaasAppConfig } from "@editor/hooks/useSaasAppConfig";
+import { useSaaSMode } from "@editor/hooks/useSaaSMode";
+import { useToolCloudStatus } from "@editor/hooks/useToolCloudStatus";
+
+/** Local tools follow local config; cloud-routed tools and SaaS policies follow cloud config. */
+export function useOfficeConversionDefault(endpointName?: string): boolean {
+ const { config } = useAppConfig();
+ const localOnly = useLocalProcessingOnly();
+ const saas = useSaaSMode();
+ const routedToCloud = useToolCloudStatus(endpointName);
+ const cloud =
+ !localOnly && saas && (endpointName === undefined || routedToCloud);
+ const cloudConfig = useSaasAppConfig(cloud);
+ return Boolean((cloud ? cloudConfig : config)?.stirlingOfficeConversion);
+}
diff --git a/frontend/src/editor/desktop/hooks/useSaasAppConfig.test.ts b/frontend/src/editor/desktop/hooks/useSaasAppConfig.test.ts
new file mode 100644
index 0000000000..e3df4b65e1
--- /dev/null
+++ b/frontend/src/editor/desktop/hooks/useSaasAppConfig.test.ts
@@ -0,0 +1,55 @@
+import { renderHook, waitFor } from "@testing-library/react";
+import { beforeEach, expect, test, vi } from "vitest";
+import { useSaasAppConfig } from "@editor/hooks/useSaasAppConfig";
+
+const api = vi.hoisted(() => ({
+ getConfig: vi.fn(),
+ clearCache: vi.fn(),
+ subscribe: vi.fn(),
+ unsubscribe: vi.fn(),
+}));
+vi.mock("@editor/services/saasAppConfigService", () => ({
+ saasAppConfigService: {
+ getConfig: api.getConfig,
+ clearCache: api.clearCache,
+ },
+}));
+vi.mock("@editor/services/connectionModeService", () => ({
+ connectionModeService: { subscribeToModeChanges: api.subscribe },
+}));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ api.getConfig.mockResolvedValue({ stirlingOfficeConversion: true });
+ api.subscribe.mockReturnValue(api.unsubscribe);
+});
+
+test("disabled consumers never fetch or subscribe, and stop listening when disabled again", async () => {
+ const { result, rerender } = renderHook(
+ ({ enabled }) => useSaasAppConfig(enabled),
+ { initialProps: { enabled: false } },
+ );
+ expect(result.current).toBeNull();
+ expect(api.getConfig).not.toHaveBeenCalled();
+ expect(api.subscribe).not.toHaveBeenCalled();
+
+ rerender({ enabled: true });
+ await waitFor(() =>
+ expect(result.current?.stirlingOfficeConversion).toBe(true),
+ );
+ expect(api.getConfig).toHaveBeenCalledTimes(1);
+ expect(api.subscribe).toHaveBeenCalledTimes(1);
+
+ rerender({ enabled: false });
+ expect(result.current).toBeNull();
+ expect(api.unsubscribe).toHaveBeenCalledTimes(1);
+ expect(api.getConfig).toHaveBeenCalledTimes(1);
+});
+
+test("existing consumers without an enabled argument still load the cloud config", async () => {
+ const { result } = renderHook(() => useSaasAppConfig());
+ await waitFor(() =>
+ expect(result.current?.stirlingOfficeConversion).toBe(true),
+ );
+ expect(api.getConfig).toHaveBeenCalledTimes(1);
+});
diff --git a/frontend/src/editor/desktop/hooks/useSaasAppConfig.ts b/frontend/src/editor/desktop/hooks/useSaasAppConfig.ts
index b3c5171051..7a2e94b955 100644
--- a/frontend/src/editor/desktop/hooks/useSaasAppConfig.ts
+++ b/frontend/src/editor/desktop/hooks/useSaasAppConfig.ts
@@ -10,11 +10,16 @@ import type { AppConfig } from "@editor/types/appConfig";
* `useSaasAppConfig()?.aiEngineEnabled`, `?.premiumEnabled`). Reloads when the
* connection mode changes, so switching into/out of SaaS updates the flags
* (and a server-side flag flip is picked up on the next load).
+ * Disabled callers return null without fetching or subscribing to connection changes.
*/
-export function useSaasAppConfig(): AppConfig | null {
+export function useSaasAppConfig(enabled = true): AppConfig | null {
const [config, setConfig] = useState<AppConfig | null>(null);
useEffect(() => {
+ if (!enabled) {
+ setConfig(null);
+ return;
+ }
let alive = true;
const load = () => {
void saasAppConfigService.getConfig().then((c) => {
@@ -30,7 +35,7 @@ export function useSaasAppConfig(): AppConfig | null {
alive = false;
unsubscribe?.();
};
- }, []);
+ }, [enabled]);
- return config;
+ return enabled ? config : null;
}
diff --git a/frontend/src/editor/proprietary/components/policies/PolicyPdfaConfig.test.tsx b/frontend/src/editor/proprietary/components/policies/PolicyPdfaConfig.test.tsx
new file mode 100644
index 0000000000..f841cc3646
--- /dev/null
+++ b/frontend/src/editor/proprietary/components/policies/PolicyPdfaConfig.test.tsx
@@ -0,0 +1,44 @@
+import { MantineProvider } from "@mantine/core";
+import { fireEvent, render, screen } from "@testing-library/react";
+import { describe, expect, test, vi } from "vitest";
+import { PolicyPdfaConfig } from "@editor/components/policies/PolicyPdfaConfig";
+
+const config = vi.hoisted(() => ({ stirlingOfficeConversion: false }));
+vi.mock("@editor/contexts/AppConfigContext", () => ({
+ useAppConfig: () => ({ config }),
+}));
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({
+ t: (key: string, fallback?: string) => fallback ?? key,
+ }),
+}));
+
+describe("PDF/A policy converter choice", () => {
+ test.each([
+ [false, undefined, false],
+ [true, undefined, true],
+ [true, false, false],
+ [false, true, true],
+ ])("server=%s choice=%s gives checked=%s", (server, choice, checked) => {
+ config.stirlingOfficeConversion = server;
+ const onChange = vi.fn();
+ render(
+ <MantineProvider>
+ <PolicyPdfaConfig
+ parameters={{
+ outputFormat: "pdfa-3b",
+ useStirlingOfficeConvert: choice,
+ }}
+ onChange={onChange}
+ />
+ </MantineProvider>,
+ );
+ const control = screen.getByTestId("stirling-office-convert-switch");
+ expect(control).toHaveProperty("checked", checked);
+ fireEvent.click(control);
+ expect(onChange).toHaveBeenCalledWith({
+ outputFormat: "pdfa-3b",
+ useStirlingOfficeConvert: !checked,
+ });
+ });
+});
diff --git a/frontend/src/editor/proprietary/components/policies/PolicyPdfaConfig.tsx b/frontend/src/editor/proprietary/components/policies/PolicyPdfaConfig.tsx
index 84383733ec..c7105d15a6 100644
--- a/frontend/src/editor/proprietary/components/policies/PolicyPdfaConfig.tsx
+++ b/frontend/src/editor/proprietary/components/policies/PolicyPdfaConfig.tsx
@@ -1,5 +1,6 @@
import { useTranslation } from "react-i18next";
import { FormField, Select } from "@editor/ui";
+import ConvertOfficeEngineSettings from "@editor/components/tools/convert/ConvertOfficeEngineSettings";
import {
PDFA_OUTPUT_FORMATS,
type PdfaOutputFormat,
@@ -41,6 +42,12 @@ export function PolicyPdfaConfig({
}
/>
</FormField>
+ <ConvertOfficeEngineSettings
+ parameters={parameters}
+ onParameterChange={(key, value) =>
+ onChange({ ...parameters, [key]: value })
+ }
+ />
</div>
);
}
diff --git a/frontend/src/editor/proprietary/policies/operations.test.ts b/frontend/src/editor/proprietary/policies/operations.test.ts
index 09f4c83249..2a68cc2517 100644
--- a/frontend/src/editor/proprietary/policies/operations.test.ts
+++ b/frontend/src/editor/proprietary/policies/operations.test.ts
@@ -124,6 +124,25 @@ describe("wire conversion", () => {
});
describe("compliance steps", () => {
+ test.each([true, false, "true", "false"])(
+ "pdfa retains a stored office choice %s",
+ (choice) => {
+ const step = policyStepFromWire({
+ operation: "/api/v1/convert/pdf/pdfa",
+ parameters: {
+ outputFormat: "pdfa-3b",
+ useStirlingOfficeConvert: choice,
+ },
+ });
+ expect(step?.toolId).toBe("pdfa");
+ if (!step) throw new Error("PDF/A policy step was not recognized");
+ expect(policyStepToWire(step).parameters).toEqual({
+ outputFormat: "pdfa-3b",
+ useStirlingOfficeConvert: choice === true || choice === "true",
+ });
+ },
+ );
+
test("pdfa sends the archival profile the backend expects", () => {
const wire = policyStepToWire(
policyStep("pdfa", { outputFormat: "pdfa-3b" }),
diff --git a/frontend/src/editor/proprietary/policies/pdfaOperation.ts b/frontend/src/editor/proprietary/policies/pdfaOperation.ts
index a9eb9bc404..44bb3556bd 100644
--- a/frontend/src/editor/proprietary/policies/pdfaOperation.ts
+++ b/frontend/src/editor/proprietary/policies/pdfaOperation.ts
@@ -1,10 +1,11 @@
/**
* Policy-facing binding for the PDF/A endpoint. The Convert tool's config spans every conversion;
- * a policy step needs only these two parameters, typed against the generated request model.
+ * a policy step uses archival profiles and the converter choice from the generated request model.
*/
import type { BidirectionalToolConfig } from "@editor/hooks/tools/shared/toolOperationDescriptor";
import type { ToolApiParams, ToolEndpoint } from "@editor/types/toolApiTypes";
+import { parseOfficeEngineChoice } from "@editor/utils/convertUtils";
const ENDPOINT = "/api/v1/convert/pdf/pdfa" satisfies ToolEndpoint;
type PdfaApiParams = ToolApiParams[typeof ENDPOINT];
@@ -23,6 +24,7 @@ export type PdfaOutputFormat = (typeof PDFA_OUTPUT_FORMATS)[number];
export interface PdfaPolicyParameters {
outputFormat: PdfaOutputFormat;
+ useStirlingOfficeConvert?: PdfaApiParams["useStirlingOfficeConvert"];
}
/** PDF/A-2b: the widest-supported archival profile, and what most retention policies ask for. */
@@ -49,10 +51,17 @@ export const pdfaOperationConfig: BidirectionalToolConfig<
// an uncoded 400 rather than the gate's classified failure.
toApiParams: (parameters: PdfaPolicyParameters): PdfaApiParams => ({
outputFormat: parameters.outputFormat,
+ ...(parameters.useStirlingOfficeConvert !== undefined
+ ? { useStirlingOfficeConvert: parameters.useStirlingOfficeConvert }
+ : {}),
}),
// A stored step may name a profile this policy UI no longer offers (or nothing at all); clamp to
// a known archival profile rather than re-sending a value the picker cannot render.
- fromApiParams: (apiParams: PdfaApiParams): Partial<PdfaPolicyParameters> => ({
- outputFormat: toOutputFormat(apiParams.outputFormat),
- }),
+ fromApiParams: (apiParams: PdfaApiParams): Partial<PdfaPolicyParameters> => {
+ const choice = parseOfficeEngineChoice(apiParams.useStirlingOfficeConvert);
+ return {
+ outputFormat: toOutputFormat(apiParams.outputFormat),
+ ...(choice !== undefined ? { useStirlingOfficeConvert: choice } : {}),
+ };
+ },
};