Код: Выделить всё
private static File repairLinuxGhostScript(String filePath) throws IOException{
PerfLog.snapShot();
tempFile = createTempFileInTeradactorTempDirectory(filePath.substring(0,filePath.length()-4) + "-repaired", ".pdf");
CommandLine cmd = new CommandLine("gs");
cmd.addArgument("-o");
cmd.addArgument(tempFile.getAbsolutePath());
cmd.addArgument("-dPDFSETTINGS=/prepress"); //selects output similar to Acrobat Distiller "Prepress Optimized" (up to version X) setting. https://ghostscript.com/docs/9.54.0/VectorDevices.htm
cmd.addArgument("-sDEVICE=pdfwrite"); //The pdfwrite, ps2write and eps2write devices create PDF or PostScript files whose visual appearance should match, as closely as possible, the appearance of the original input file https://ghostscript.com/docs/9.54.0/VectorDevices.htm
cmd.addArgument("-dSubsetFonts=false"); //
cmd.addArgument(filePath);
DefaultExecutor exec = new DefaultExecutor();
ByteArrayOutputStream outputCapturer = new ByteArrayOutputStream();
exec.setStreamHandler(new PumpStreamHandler(outputCapturer, System.err));
System.out.println(cmd.toString());
int exitValue = exec.execute(cmd);
LOG.info(outputCapturer.toByteArray());
if(exitValue != 0) {
throw new ProcessorServiceException("Ghostscript gs exited with error code " + exitValue);
}
PerfLog.log(PerfLog.Phase.IMPORT, PerfLog.SubPhase.REPAIR,"PDF Repair","GhostScript","PdfRepairer");
return tempFile;
}
Код: Выделить всё
public static byte[] repairPDF(byte[] inputPDF) throws IOException {
// Prepare Ghostscript command
CommandLine cmd = new CommandLine("gs");
cmd.addArgument("-dPDFSETTINGS=/prepress");
cmd.addArgument("-sDEVICE=pdfwrite");
cmd.addArgument("-dSubsetFonts=false");
cmd.addArgument("-sOutputFile=%stdout"); // Output to stdout
cmd.addArgument("-");
// Set up input and output streams
ByteArrayInputStream inputStream = new ByteArrayInputStream(inputPDF);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream, inputStream);
DefaultExecutor executor = new DefaultExecutor();
executor.setStreamHandler(streamHandler);
// Execute Ghostscript command
try {
executor.execute(cmd); // Send input PDF via stdin
} catch (ExecuteException e) {
System.err.println("Execution failed: " + e.getMessage());
throw new IOException("Ghostscript execution failed", e);
} catch (IOException e) {
System.err.println("IO Error: " + e.getMessage());
throw new IOException("Error processing PDF", e);
}
// Handle errors if any
String errorOutput = errorStream.toString();
if (!errorOutput.isEmpty()) {
System.err.println("Ghostscript Error: " + errorOutput);
}
// Get the result as a byte array
return outputStream.toByteArray();
}
Я также где-то здесь читал о переполнении стека, что Ghostscript должен в любом случае прочитайте файлы с диска, поэтому на самом деле не имеет значения, удалю ли я временные файлы со своей стороны, поскольку они все равно создаются (источник: https://stackoverflow.com/a/49880072/12171869).< /p>
Мне интересно: есть ли способ добиться того же результата, что и исходный метод, без создания временных файлов? Я просмотрел PDF-окно, но не получил желаемого результата (обратите внимание, что я работаю с PDF-окном 1.8.11, начиная с устаревшего приложения)
Спасибо.
Подробнее здесь: https://stackoverflow.com/questions/788 ... amatically