-
Notifications
You must be signed in to change notification settings - Fork 10.2k
feat(api): add text-to-outlines endpoint (Ghostscript -dNoOutputFonts) #8201
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
110 changes: 110 additions & 0 deletions
110
...re/src/main/java/stirling/software/SPDF/controller/api/misc/TextToOutlinesController.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,110 @@ | ||
| package stirling.software.SPDF.controller.api.misc; | ||
|
|
||
| import java.io.IOException; | ||
| import java.util.List; | ||
|
|
||
| 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.multipart.MultipartFile; | ||
|
|
||
| import io.swagger.v3.oas.annotations.Operation; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
|
|
||
| import stirling.software.SPDF.config.EndpointConfiguration; | ||
| import stirling.software.common.annotations.AutoJobPostMapping; | ||
| import stirling.software.common.annotations.api.MiscApi; | ||
| 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.ExceptionUtils; | ||
| import stirling.software.common.util.GeneralUtils; | ||
| import stirling.software.common.util.ProcessExecutor; | ||
| 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; | ||
|
|
||
| @MiscApi | ||
| @RequiredArgsConstructor | ||
| @Slf4j | ||
| public class TextToOutlinesController { | ||
|
|
||
| private final TempFileManager tempFileManager; | ||
| private final EndpointConfiguration endpointConfiguration; | ||
|
|
||
| @AutoJobPostMapping( | ||
| value = "/text-to-outlines", | ||
| consumes = MediaType.MULTIPART_FORM_DATA_VALUE, | ||
| resourceWeight = ResourceWeight.MEDIUM_WEIGHT) | ||
| @ToolIO(produces = ToolFormat.PDF) | ||
| @Operation( | ||
| summary = "Convert text to outlines", | ||
| description = | ||
| "Converts all text in the PDF to vector outlines using Ghostscript" | ||
| + " (-dNoOutputFonts), removing font dependencies for prepress" | ||
| + " workflows.") | ||
| public ResponseEntity<Resource> textToOutlines(@ModelAttribute PDFFile request) | ||
| throws IOException { | ||
| if (!endpointConfiguration.isGroupEnabled("Ghostscript")) { | ||
| throw ExceptionUtils.createGhostscriptRequiredException("text-to-outlines"); | ||
| } | ||
| MultipartFile inputFile = request.getFileInput(); | ||
| if (inputFile == null || inputFile.isEmpty()) { | ||
| throw ExceptionUtils.createFileNullOrEmptyException(); | ||
| } | ||
|
|
||
| TempFile tempOutputFile = null; | ||
| try (TempFile tempInputFile = tempFileManager.createManagedTempFile(".pdf")) { | ||
| inputFile.transferTo(tempInputFile.getFile()); | ||
| tempOutputFile = tempFileManager.createManagedTempFile(".pdf"); | ||
|
|
||
| ProcessExecutor processExecutor = | ||
| ProcessExecutor.getInstance(ProcessExecutor.Processes.GHOSTSCRIPT); | ||
| List<String> command = | ||
| List.of( | ||
| "gs", | ||
| "-sDEVICE=pdfwrite", | ||
| "-dCompatibilityLevel=1.5", | ||
| "-dNoOutputFonts", | ||
| "-dNOPAUSE", | ||
| "-dQUIET", | ||
| "-dBATCH", | ||
| "-o", | ||
| tempOutputFile.getAbsolutePath(), | ||
| tempInputFile.getAbsolutePath()); | ||
|
|
||
| try { | ||
| ProcessExecutorResult result = | ||
| processExecutor.runCommandWithOutputHandling(command); | ||
| String gsOutput = result.getMessages(); | ||
| ExceptionUtils.GhostscriptException criticalError = | ||
| ExceptionUtils.detectGhostscriptCriticalError(gsOutput); | ||
| if (criticalError != null) { | ||
| throw criticalError; | ||
| } | ||
| if (result.getRc() != 0) { | ||
| throw ExceptionUtils.createGhostscriptCompressionException(gsOutput); | ||
| } | ||
| } catch (InterruptedException e) { | ||
| Thread.currentThread().interrupt(); | ||
| throw ExceptionUtils.createProcessingInterruptedException("Ghostscript", e); | ||
| } | ||
|
|
||
| TempFile out = tempOutputFile; | ||
| tempOutputFile = null; // ownership transferred to response Resource | ||
| return WebResponseUtils.pdfFileToWebResponse( | ||
| out, | ||
| GeneralUtils.generateFilename( | ||
| inputFile.getOriginalFilename(), "_outlined.pdf")); | ||
| } finally { | ||
| if (tempOutputFile != null) { | ||
| tempOutputFile.close(); | ||
| } | ||
| } | ||
| } | ||
| } | ||
154 changes: 154 additions & 0 deletions
154
...rc/test/java/stirling/software/SPDF/controller/api/misc/TextToOutlinesControllerTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,154 @@ | ||
| package stirling.software.SPDF.controller.api.misc; | ||
|
|
||
| import static org.junit.jupiter.api.Assertions.*; | ||
| import static org.mockito.ArgumentMatchers.any; | ||
| import static org.mockito.ArgumentMatchers.anyString; | ||
| import static org.mockito.Mockito.*; | ||
|
|
||
| import java.io.IOException; | ||
| import java.nio.file.Files; | ||
| import java.nio.file.Path; | ||
| import java.util.List; | ||
|
|
||
| import org.apache.pdfbox.pdmodel.PDDocument; | ||
| import org.apache.pdfbox.pdmodel.PDPage; | ||
| import org.apache.pdfbox.pdmodel.PDPageContentStream; | ||
| import org.apache.pdfbox.pdmodel.common.PDRectangle; | ||
| import org.apache.pdfbox.pdmodel.font.PDType1Font; | ||
| import org.apache.pdfbox.pdmodel.font.Standard14Fonts; | ||
| import org.junit.jupiter.api.BeforeEach; | ||
| import org.junit.jupiter.api.DisplayName; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.junit.jupiter.api.extension.ExtendWith; | ||
| import org.junit.jupiter.api.io.TempDir; | ||
| import org.mockito.ArgumentCaptor; | ||
| import org.mockito.InjectMocks; | ||
| import org.mockito.Mock; | ||
| import org.mockito.MockedStatic; | ||
| import org.mockito.Mockito; | ||
| import org.mockito.junit.jupiter.MockitoExtension; | ||
| import org.springframework.core.io.Resource; | ||
| 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.common.model.api.PDFFile; | ||
| import stirling.software.common.util.ExceptionUtils; | ||
| import stirling.software.common.util.ProcessExecutor; | ||
| import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult; | ||
| import stirling.software.common.util.TempFile; | ||
| import stirling.software.common.util.TempFileManager; | ||
|
|
||
| @ExtendWith(MockitoExtension.class) | ||
| class TextToOutlinesControllerTest { | ||
|
|
||
| @TempDir Path tempDir; | ||
| @Mock private TempFileManager tempFileManager; | ||
| @Mock private EndpointConfiguration endpointConfiguration; | ||
| @InjectMocks private TextToOutlinesController controller; | ||
|
|
||
| @BeforeEach | ||
| void setUp() throws IOException { | ||
| lenient() | ||
| .when(tempFileManager.createManagedTempFile(anyString())) | ||
| .thenAnswer( | ||
| inv -> { | ||
| java.io.File f = | ||
| Files.createTempFile("test", inv.<String>getArgument(0)) | ||
| .toFile(); | ||
| TempFile tf = mock(TempFile.class); | ||
| lenient().when(tf.getFile()).thenReturn(f); | ||
| lenient().when(tf.getPath()).thenReturn(f.toPath()); | ||
| lenient().when(tf.getAbsolutePath()).thenReturn(f.getAbsolutePath()); | ||
| return tf; | ||
| }); | ||
| } | ||
|
|
||
| private MockMultipartFile createPdfWithText() throws IOException { | ||
| Path pdfPath = tempDir.resolve("text.pdf"); | ||
| try (PDDocument doc = new PDDocument()) { | ||
| PDPage page = new PDPage(PDRectangle.A4); | ||
| doc.addPage(page); | ||
| try (PDPageContentStream stream = new PDPageContentStream(doc, page)) { | ||
| stream.beginText(); | ||
| stream.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12); | ||
| stream.newLineAtOffset(50, 700); | ||
| stream.showText("outlines"); | ||
| stream.endText(); | ||
| } | ||
| doc.save(pdfPath.toFile()); | ||
| } | ||
| return new MockMultipartFile( | ||
| "fileInput", | ||
| "text.pdf", | ||
| MediaType.APPLICATION_PDF_VALUE, | ||
| Files.readAllBytes(pdfPath)); | ||
| } | ||
|
|
||
| private PDFFile requestFor(MockMultipartFile file) { | ||
| PDFFile request = new PDFFile(); | ||
| request.setFileInput(file); | ||
| return request; | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("Throws ToolRequiredException when Ghostscript is disabled") | ||
| void throwsWhenGhostscriptDisabled() throws IOException { | ||
| when(endpointConfiguration.isGroupEnabled("Ghostscript")).thenReturn(false); | ||
|
|
||
| assertThrows( | ||
| ExceptionUtils.ToolRequiredException.class, | ||
| () -> controller.textToOutlines(requestFor(createPdfWithText()))); | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("Invokes Ghostscript with -dNoOutputFonts") | ||
| void invokesGhostscriptWithNoOutputFonts() throws Exception { | ||
| when(endpointConfiguration.isGroupEnabled("Ghostscript")).thenReturn(true); | ||
|
|
||
| ProcessExecutor executor = mock(ProcessExecutor.class); | ||
| ProcessExecutorResult result = mock(ProcessExecutorResult.class); | ||
| when(result.getRc()).thenReturn(0); | ||
| when(result.getMessages()).thenReturn(""); | ||
|
|
||
| try (MockedStatic<ProcessExecutor> pe = Mockito.mockStatic(ProcessExecutor.class)) { | ||
| pe.when(() -> ProcessExecutor.getInstance(ProcessExecutor.Processes.GHOSTSCRIPT)) | ||
| .thenReturn(executor); | ||
| when(executor.runCommandWithOutputHandling(any())).thenReturn(result); | ||
|
|
||
| ResponseEntity<Resource> response = | ||
| controller.textToOutlines(requestFor(createPdfWithText())); | ||
|
|
||
| assertEquals(200, response.getStatusCode().value()); | ||
|
|
||
| @SuppressWarnings("unchecked") | ||
| ArgumentCaptor<List<String>> captor = ArgumentCaptor.forClass(List.class); | ||
| verify(executor).runCommandWithOutputHandling(captor.capture()); | ||
| List<String> command = captor.getValue(); | ||
| assertTrue(command.contains("-dNoOutputFonts")); | ||
| assertTrue(command.contains("-sDEVICE=pdfwrite")); | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| @DisplayName("Ghostscript failure surfaces as an exception") | ||
| void ghostscriptFailureSurfaces() throws Exception { | ||
| when(endpointConfiguration.isGroupEnabled("Ghostscript")).thenReturn(true); | ||
|
|
||
| ProcessExecutor executor = mock(ProcessExecutor.class); | ||
| ProcessExecutorResult result = mock(ProcessExecutorResult.class); | ||
| when(result.getRc()).thenReturn(1); | ||
| when(result.getMessages()).thenReturn("gs error"); | ||
|
|
||
| try (MockedStatic<ProcessExecutor> pe = Mockito.mockStatic(ProcessExecutor.class)) { | ||
| pe.when(() -> ProcessExecutor.getInstance(ProcessExecutor.Processes.GHOSTSCRIPT)) | ||
| .thenReturn(executor); | ||
| when(executor.runCommandWithOutputHandling(any())).thenReturn(result); | ||
|
|
||
| assertThrows( | ||
| ExceptionUtils.GhostscriptException.class, | ||
| () -> controller.textToOutlines(requestFor(createPdfWithText()))); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Qualify the vector-outlines claim.
For a PDF that uses bitmapped fonts, Ghostscript’s
-dNoOutputFontsemits bitmaps rather than vector outlines. The description promises vector outlines for all text. State this limitation so prepress users do not treat bitmap text as vector output. (ghostscript.readthedocs.io)🤖 Prompt for AI Agents