文章标签 ‘PDF’
2010六月28

PDF在线阅读开发经验(FlexPaper+SWFTools+SaveAsPDFandXPS)

1、使用SaveAsPDFandXPS将office文档转换成PDF

http://www.microsoft.com/downloads/details.aspx?FamilyID=4d951911-3e7e-4ae6-b059-a2e79ed87041&displaylang=en

微软原计划让Office 2007直接支持保存为PDF格式,但引起了Adobe的不满,并被指责为垄断,最终被迫放弃,改为以插件的形式予以支持,插件大家都知道怎么回事儿,默认不装,要用你的自己找来装上。不过微软针对这件事情也做出了一个回应:发布XPS, XPS则是微软自己利用XML技术开发的新型文档格式。

该插件支持Office 2007的8个组件,包括Word、Excel、Access、PowerPoint、InfoPath、OneNote、Publisher和Visio。安装插件后,用户即可在上述组件中将相应文档存储为PDF格式或XPS格式,还可以方便地将文档保存为PDF/XPS格式的E-mail附件。

2、下载 SWFTools

SWFTools 是一组用来处理 Flash 的 swf 文件的工具包,包括:

1. 合并工具 swfcombine
2. 抽取工具 swfextract
3. PDF/JPEG/PNG/AVI/TTF/WAV 到 SWF 的转换工具 :pdf2swf, jpeg2swf, png2swf, avi2swf, font2swf, and wav2swf|
4. 文本解析工具 swfstrings
5. SWF 解析器 swfdump
6. SWF 读写库 rfxswflib

其中把pdf转成swf的工具就是pdf2swf了。在命令行中运行pdf2swf src.pdf des.swf一般能满足需求。而命令行参数可以通过pdf2swf -f得到:

-h , –help Print short help message and exit 打印帮助信息
-V , –version Print version info and exit 打印版本号
-o , –output file.swf Direct output to file.swf. If file.swf contains ‘13568621′ (file13568630.swf), then each page指定输出的swf文件名
-p , –pages range Convert only pages in range with range e.g. 1-20
or 1,4,6,9-11 or
指定转换的页面范围,使用的页码描述方法与打印机打印文件时候的选页一样

-P , –password password Use password for deciphering the pdf.指定打开pdf的密码
-v , –verbose Be verbose. Use more than one -v for greater effect.转换时输出详细的内容
-z , –zlib Use Flash 6 (MX) zlib compression.使用Flash 6的zlib压缩机制
-i , –ignore Allows pdf2swf to change the draw order of the pdf. This may make the generated允许程序修改pdf的绘制顺序,可能会导致结果与原来有差异
-j , –jpegquality quality Set quality of embedded jpeg pictures to quality. 0 is worst (small), 100 is best (big). (default:85)设置转换其中的jpeg图片的质量,从0到100,默认值是85。
-s , –set param=value Set a SWF encoder specific parameter. See pdf2swf -s help for more information. 设置SWF转码时候的参数,具体参数可以用pdf2swf -s help获取
-w , –samewindow When converting pdf hyperlinks, don’t make the links open a new window. 设置转换后的swf打开原pdf中的连接时使用相同的窗口
-t , –stop Insert a stop() command in each page. 在每页结尾添加一个stop()命令
-T , –flashversion num Set Flash Version in the SWF header to num. 设置SWF所使用的flash版本号
-F , –fontdir directory Add directory to the font search path. 指定字体文件所在路径
-b , –defaultviewer Link a standard viewer to the swf file. 指定默认的swf导航文件,用来翻页、放大缩小等等
-l , –defaultloader Link a standard preloader to the swf file which will be displayed while the main swf is loading. 指定默认的swf加载文件,用来显示加载进程效果
-B , –viewer filename Link viewer filename to the swf file. 指定swf导航文件,作用同-b
-L , –preloader filename Link preloader filename to the swf file. 指定swf加载文件,作用同-l
-q , –quiet Suppress normal messages. Use -qq to suppress warnings, also. 不打印普通信息,用-qq就不打印警告信息。
-S , –shapes Don’t use SWF Fonts, but store everything as shape. 不使用字体,所有都转为形状。
-f , –fonts Store full fonts in SWF. (Don’t reduce to used characters). 在swf中保存全部字体。
-G , –flatten Remove as many clip layers from file as possible. 在文件中尽量去除影片层,合并它们
-I , –info Don’t do actual conversion, just display a list of all pages in the PDF. 不做实际转换,仅显示PDF的信息。
-Q , –maxtime n Abort conversion after n seconds. Only available on Unix. 如果运行时间超时则退出。

3、java程序,实现上传PDF自动转换成SWF文件

//ajax方法,先解密传过来的文件名,根据判断生成SWF文件后跳转至FLASH页面

if (ajaxAction.equals("exeflash"))   //把PDF成SWF
        {
            String fn = DecodeUtil.Decrypt(StringUtil.null2String(request.getParameter("fn")).trim()).toLowerCase();
            try {
                if (!"".equals(fn) && fn.indexOf("/") > -1 && fn.indexOf(".pdf") > -1) {
                    Map webfileupmap = (Map) Globals.SYS_UPLOAD_CONFIG.get("webfile");
                    String webfilepath = StringUtil.null2String(webfileupmap.get("path")).replace("\\", "\\\\");
                    fn = fn.substring(fn.lastIndexOf("/") + 1);//aa.pdf
                    webfilepath = webfilepath + fn;
                    File f = new File(webfilepath);
                    if (!f.exists()) {
                        return "error";
                        //如果PDF文件不存在则退出
                    }
                    Map webupmap = (Map) Globals.SYS_UPLOAD_CONFIG.get("web");
                    String webpath = StringUtil.null2String(webupmap.get("path")).replace("\\", "\\\\");
                    String urlpath = StringUtil.null2String(webupmap.get("urlpath"));
                    String wname = fn.substring(0, fn.indexOf(".")) + ".swf";
                    webpath = webpath + wname;
                    String wurl = urlpath + wname;
                    boolean issc = false;
                    File f2 = new File(webpath);
                    if (!f2.exists()) {
                        issc = true;
                        //如果文件不存在则生成
                    }
                    if (issc) {
                        String cmd = "C:\\SWFTools\\pdf2swf " + webfilepath + " -o " + webpath + " -T 9";
                        if (StringUtil.executeCmdFlash(cmd) == false) {
                            return "error";
                        }
                        System.out.println("cmd::::::" + cmd);
                    }

                    File f1 = new File(webpath);
                    if (f1.exists()) {
                        ajaxstr = DecodeUtil.Encrypt(wurl);
                    }

                } else {
                    return "error";
                }
            } catch (Exception e) {
                Globals.Logger("发生错误:" + e, 2);
            }

        }

注意:

String cmd = “C:\\SWFTools\\pdf2swf ” + webfilepath + ” -o ” + webpath + ” -T 9″;

加 “-T 9” 参数,设置输出版本为flash9,解决PDF文件只有一页,生成的swf不能播放的问题。

另外,若PDF内表格元素过多,在转换时会抛出一堆异常错误。似乎还没有好的解决办法?

//java调用cmd命令行方法

/**
     * 运行可执行文件
     *
     * @param cmd
     * @return String
     */
    public static synchronized boolean executeCmdFlash(String cmd) {

        try {
            final Process process = Runtime.getRuntime().exec(cmd);
            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    process.destroy();
                }
            });
            InputStreamReader inputstreamreader = new InputStreamReader(process.getInputStream());
            char c = (char) inputstreamreader.read();
            if (c != '\uFFFF')
                stdout.append(c);
            while (c != '\uFFFF') {
                if (!inputstreamreader.ready()) {
                    System.out.println(stdout);
                    try {
                        process.exitValue();
                        break;
                    }
                    catch (IllegalThreadStateException _ex) {
                        try {
                            Thread.sleep(100L);
                        }
                        catch (InterruptedException _ex2) {
                        }
                    }
                } else {
                    c = (char) inputstreamreader.read();
                    stdout.append(c);
                }
            }
            try {
                inputstreamreader.close();
            }
            catch (IOException ioexception2) {
                System.err.println("RunCmd : Error closing InputStream " + ioexception2);
                return false;
            }
        } catch (Throwable e) {
            e.printStackTrace();
            Globals.Logger("发生错误:" + e, 2);
            return false;
        }

        return true;
    }

4、利用FlexPaper展示

FlexPaper是一个被设计用来与PDF2SWF一起使用,开源轻量级的在浏览器上显示各种文档的组件, 使在Flex中显示PDF成为可能,而这个过程并无需PDF软件环境的支持。它可以被当做Flex的库来使用。也可以通过将一些例如Word、PPT等文档转成PDF,然后实现在线浏览。

SwfFile : escape(host+"/upload/web/2010-05-24-10-21-51139.swf"),
      Scale : 0.6,
      ZoomTransition : "easeOut",
      ZoomTime : 0.5,
        ZoomInterval : 0.1,
        FitPageOnLoad : false,
        FitWidthOnLoad : true,
        PrintEnabled : false,
        FullScreenAsMaxWindow : true,
        localeChain: "zh_CN" //设置为中文
      };

5、演示地址

http://www.4th-games.org.cn/sis/public/info.html?doAction=scsg&bsdxid=1009&cdate=all