`

PDF瘦身利器-Ghostscript

 
阅读更多

文件压缩或图片瘦身的工具遍地都是,但 PDF 文件减肥的工具却是很难找到,更别想用 JAVA 直接调用了。 Acrobat 中的优化工具可以将 150M 的 pdf 文件压缩至 1.5M,且效果几乎不打折。可是程序却不能直接控制 acrobat 中的功能,即使用 SDK 能写 IAC 程序,但很难嵌入到小小的客户端软件中去。

 

苦苦寻找可用的工具,国内基本没有,国外的有几款,但都要付费,并且无法真正用 shell 方式运行。有代表性的 A-PDF Image Downsample,novapp,pdftk_server,verypdf-pdfcompressor,PDF-Tools。

 

偶然搜索到了 Ghostscript,安装后一试,哇,碉堡了。150M的文件减少到600K,体验还不错。继续挖掘,得到一款 Ghost4j 的项目。

 

看起来真的找到了。

 

Ghost4j 调用也并非顺利,经过多次尝试后终于可以压缩成功。

 

import org.ghost4j.Ghostscript;
import org.ghost4j.GhostscriptException;
 
/**
 * Example showing how to convert a Postscript file to PDF.
 * @author Gilles Grousset (gi.grousset@gmail.com)
 */
public class PDFCompressExample {
 
     public static void main(String[] args) {
 
        //get Ghostscript instance
        Ghostscript gs = Ghostscript.getInstance();
 
        //prepare Ghostscript interpreter parameters
        //refer to Ghostscript documentation for parameter usage
        String[] gsArgs = new String[13];
        gsArgs[0] = "-dQUIET";
        gsArgs[1] = "-dNOPAUSE";
        gsArgs[2] = "-dBATCH";
        gsArgs[3] = "-dSAFER";
        gsArgs[4] = "-sDEVICE=pdfwrite";
        gsArgs[5] = "-dDownsampleColorImages=true";
        gsArgs[6] = "-dDownsampleGrayImages=true";
        gsArgs[7] = "-dDownsampleMonoImages=true";
        gsArgs[8] = "-dColorImageResolution=150";
        gsArgs[9] = "-dGrayImageResolution=150";
        gsArgs[10] = "-dMonoImageResolution=300";
       gsArgs[11] = "-sOutputFile=C:\\temp\\o3.pdf";
       gsArgs[12] = "C:\\temp\\G.pdf";

        //execute and exit interpreter
        try {
 
            gs.initialize(gsArgs);
            gs.exit();
 
        } catch (GhostscriptException e) {
            System.out.println("ERROR: " + e.getMessage());
        }
     }
 
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics