Java中修复缺失%%EOF标记的PostScript文件问题
问题背景
我用Fortran程序生成了PostScript文件,用ghost4j库加载时先报ERROR: %%EOF not found. File is not well-formed.,手动用echo %%EOF >> plotfile.001添加结束标记后,又报错ERROR: PostScript document is not valid。但修改前后的文件都能在Ubuntu文档查看器正常打开,文件首尾内容如下:
%!PS-Adobe-3.0 %%Creator: HGRAPH %%Title: PLOTFILE %%CreationDate: initgraphics ... stroke showpage
目标是将PS转成PNG格式,嵌入Swing应用,使用的Java代码如下:
public class SimpleRendererExample { public static void main(String[] args) { try { // load PS document PSDocument document = new PSDocument(); document.load(new File("plotfile.001")); // create renderer SimpleRenderer renderer = new SimpleRenderer(); // set resolution (in DPI) renderer.setResolution(300); // render List<Image> images = renderer.render(document); // write images to files to disk as PNG try { for (int i = 0; i < images.size(); i++) { ImageIO.write((RenderedImage) images.get(i), "png", new File((i + 1) + ".png")); } } catch (IOException e) { System.out.println("ERROR: " + e.getMessage()); } } catch (Exception e) { System.out.println("ERROR: " + e.getMessage()); } } }
修复方案
1. 修正%%EOF的添加方式
echo %%EOF >> plotfile.001会在文件末尾额外插入换行符,而PostScript规范要求%%EOF必须是文件的最后一行,不能有多余空白或换行。
操作方法:
- 用文本编辑器打开PS文件,在
showpage的下一行手动输入%%EOF,确保该行后面没有空行。 - 或者用Linux命令精准添加:
printf '%%EOF\n' >> plotfile.001
2. 补全PostScript头部字段
原文件的%%CreationDate:字段为空,虽然Ubuntu查看器能兼容,但ghost4j对PS规范的校验更严格,补全该字段可解决部分校验问题。
操作方法:
在头部添加合法的日期格式,比如:
%%CreationDate: 202405201430
格式采用YYYYMMDDHHMM即可,符合Adobe PostScript规范。
3. 绕过ghost4j校验,直接调用Ghostscript命令行
如果上述方法无效,直接调用系统中的Ghostscript命令行工具是更可靠的方案——ghost4j本质是Ghostscript的Java封装,但封装层的校验过于严格,原生Ghostscript对非标准PS文件的兼容性更好。
示例代码:
import java.io.IOException; public class GhostscriptPSConverter { public static void main(String[] args) { String psInput = "plotfile.001"; String pngOutput = "output.png"; int dpi = 300; // Ghostscript转换命令参数 String[] cmd = { "gs", "-dNOPAUSE", // 不暂停 "-dBATCH", // 处理完自动退出 "-sDEVICE=png16m", // 指定PNG设备(24位真彩色) "-r" + dpi, // 设置分辨率 "-sOutputFile=" + pngOutput, // 输出路径 psInput }; try { Process process = Runtime.getRuntime().exec(cmd); int exitCode = process.waitFor(); if (exitCode == 0) { System.out.println("转换完成,输出文件:" + pngOutput); // 后续可直接将该PNG加载到Swing的JLabel或ImageIcon中 } else { System.err.println("转换失败,退出码:" + exitCode); } } catch (IOException | InterruptedException e) { e.printStackTrace(); } } }
注意:确保系统已安装Ghostscript,Ubuntu下可通过sudo apt install ghostscript安装。
4. 排查PS文件的潜在问题
部分Fortran生成的PS文件可能存在编码问题或不规范的操作符,可通过原生Ghostscript排查:
- 在终端运行
gs -dNOPAUSE -dBATCH plotfile.001,查看具体报错信息,根据提示修复PS文件。 - 更新ghost4j到最新版本,确保其绑定的Ghostscript版本为较新的稳定版,提升兼容性。
内容的提问来源于stack exchange,提问作者TriJB

