当前位置: 移动技术网 > IT编程>开发语言>c# > C#的Process类调用第三方插件实现PDF文件转SWF文件

C#的Process类调用第三方插件实现PDF文件转SWF文件

2019年07月18日  | 移动技术网IT编程  | 我要评论
在项目开发过程中,有时会需要用到调用第三方程序实现本系统的某一些功能,例如本文中需要使用到的swftools插件,那么如何在程序中使用这个插件,并且该插件是如何将pdf文件

在项目开发过程中,有时会需要用到调用第三方程序实现本系统的某一些功能,例如本文中需要使用到的swftools插件,那么如何在程序中使用这个插件,并且该插件是如何将pdf文件转化为swf文件的呢?接下来就会做一个简单的介绍。

在.net平台中,对c#提供了一个操作对本地和远程的访问进程,使能够启动和停止系统进程。这个类就是system.diagnostics.process,我们首先来了解一下该类。

一.解析system.diagnostics.process类

在c#中使用process类可以提供对本地和远程的访问进程,使能够启动和停止系统进程,并且该类可以对系统进程进行管理。该类中的一些常用方法:start() ,kill(),waitforexit()等方法;startinfo,filename,createnowindow等属性。

1.start()方法:启动(或重用)此 process 组件的 startinfo 属性指定的进程资源,并将其与该组件关联。如果启动了进程资源,则为 true;如果没有启动新的进程资源(例如,如果重用了现有进程),则为 false。
具体介绍一下该方法的实现代码:

 /// <devdoc>
    ///  <para> 
    ///  <see cref='system.diagnostics.process'/>如果过程资源被重用而不是启动,重用的进程与此相关联<see cref ='system.diagnostics.process'/>零件。
    ///  </para>    
    /// </devdoc>
    [resourceexposure(resourcescope.none)]
    [resourceconsumption(resourcescope.machine, resourcescope.machine)] 
    public bool start() {
      close(); 
      processstartinfo startinfo = startinfo; 
      if (startinfo.filename.length == 0)
        throw new invalidoperationexception(sr.getstring(sr.filenamemissing)); 

      if (startinfo.useshellexecute) {
#if !feature_pal
        return startwithshellexecuteex(startinfo); 
#else
        throw new invalidoperationexception(sr.getstring(sr.net_perm_invalid_val, "startinfo.useshellexecute", true)); 
#endif // !feature_pal 
      } else {
        return startwithcreateprocess(startinfo); 
      }
    }

2.kill()方法:立即停止关联的进程。kill 强制终止进程,kill 方法将异步执行。 在调用 kill 方法后,请调用 waitforexit 方法等待进程退出,或者检查 hasexited 属性以确定进程是否已经退出。
具体介绍一下该方法的实现代码:

[resourceexposure(resourcescope.machine)] 
    [resourceconsumption(resourcescope.machine)]
    public void kill() { 
      safeprocesshandle handle = null;
      try {
        handle = getprocesshandle(nativemethods.process_terminate);
        if (!nativemethods.terminateprocess(handle, -1)) 
          throw new win32exception();
      } 
      finally { 
        releaseprocesshandle(handle);
      } 
    }
safeprocesshandle getprocesshandle(int access) {
      return getprocesshandle(access, true); 
    }

    /// <devdoc>
    /// 获取进程的短期句柄,具有给定的访问权限。
     ///如果句柄存储在当前进程对象中,则使用它。
     ///注意,我们存储在当前进程对象中的句柄将具有我们需要的所有访问权限。
    /// </devdoc> 
    /// <internalonly/> 
    [resourceexposure(resourcescope.none)]
    [resourceconsumption(resourcescope.machine, resourcescope.machine)] 
    safeprocesshandle getprocesshandle(int access, bool throwifexited) {
      debug.writelineif(processtracing.traceverbose, "getprocesshandle(access = 0x" + access.tostring("x8", cultureinfo.invariantculture) + ", throwifexited = " + throwifexited + ")");
#if debug
      if (processtracing.traceverbose) { 
        stackframe calledfrom = new stacktrace(true).getframe(0);
        debug.writeline("  called from " + calledfrom.getfilename() + ", line " + calledfrom.getfilelinenumber()); 
      } 
#endif
      if (haveprocesshandle) { 
        if (throwifexited) {
          //因为hasprocesshandle是true,我们知道我们有进程句柄
           //打开时至少要有synchronize访问,所以我们可以等待它
           // zero timeout以查看进程是否已退出。
          processwaithandle waithandle = null;
          try { 
            waithandle = new processwaithandle(m_processhandle); 
            if (waithandle.waitone(0, false)) {
              if (haveprocessid) 
                throw new invalidoperationexception(sr.getstring(sr.processhasexited, processid.tostring(cultureinfo.currentculture)));
              else
                throw new invalidoperationexception(sr.getstring(sr.processhasexitednoid));
            } 
          }
          finally { 
            if( waithandle != null) { 
              waithandle.close();
            } 
          }
        }
        return m_processhandle;
      } 
      else {
        ensurestate(state.haveid | state.islocal); 
        safeprocesshandle handle = safeprocesshandle.invalidhandle; 
#if !feature_pal
        handle = processmanager.openprocess(processid, access, throwifexited); 
#else
        intptr pseudohandle = nativemethods.getcurrentprocess();
        // get a real handle
        if (!nativemethods.duplicatehandle (new handleref(this, pseudohandle), 
                          new handleref(this, pseudohandle),
                          new handleref(this, pseudohandle), 
                          out handle, 
                          0,
                          false, 
                          nativemethods.duplicate_same_access |
                          nativemethods.duplicate_close_source)) {
          throw new win32exception();
        } 
#endif // !feature_pal
        if (throwifexited && (access & nativemethods.process_query_information) != 0) { 
          if (nativemethods.getexitcodeprocess(handle, out exitcode) && exitcode != nativemethods.still_active) { 
            throw new invalidoperationexception(sr.getstring(sr.processhasexited, processid.tostring(cultureinfo.currentculture)));
          } 
        }
        return handle;
      }
 
    }

3.waitforexit()方法:指示<see cref ='system.diagnostics.process'/>组件等待指定的毫秒数,以使相关联的进程退出。

具体介绍一下该方法的实现代码:

public bool waitforexit(int milliseconds) { 
      safeprocesshandle handle = null; 
     bool exited;
      processwaithandle processwaithandle = null; 
      try {
        handle = getprocesshandle(nativemethods.synchronize, false);
        if (handle.isinvalid) {
          exited = true; 
        }
        else { 
          processwaithandle = new processwaithandle(handle); 
          if( processwaithandle.waitone(milliseconds, false)) {
            exited = true; 
            signaled = true;
          }
          else {
            exited = false; 
            signaled = false;
          } 
        } 
      }
      finally { 
        if( processwaithandle != null) {
          processwaithandle.close();
        }
 
        // if we have a hard timeout, we cannot wait for the streams
        if( output != null && milliseconds == -1) { 
          output.waitutileof(); 
        }
 
        if( error != null && milliseconds == -1) {
          error.waitutileof();
        }
 
        releaseprocesshandle(handle);
 
      } 

      if (exited && watchforexit) { 
        raiseonexited();
      }
      
      return exited; 
    }
internal processwaithandle( safeprocesshandle processhandle): base() {
      safewaithandle waithandle = null; 
      bool succeeded = nativemethods.duplicatehandle(
        new handleref(this, nativemethods.getcurrentprocess()), 
        processhandle, 
        new handleref(this, nativemethods.getcurrentprocess()),
        out waithandle, 
        0,
        false,
        nativemethods.duplicate_same_access);
 
      if (!succeeded) {
        marshal.throwexceptionforhr(marshal.gethrforlastwin32error()); 
      } 

      this.safewaithandle = waithandle; 
    }

4.startinfo属性:获取或设置要传递给 process 的 start 方法的属性。startinfo 表示用于启动进程的一组参数。 调用 start 时,startinfo 用于指定要启动的进程。 唯一必须设置的 startinfo 成员是 filename 属性。

具体介绍一下该方法的实现代码:
 

 [browsable(false), designerserializationvisibility(designerserializationvisibility.content), monitoringdescription(sr.processstartinfo)] 
    public processstartinfo startinfo {
      get { 
        if (startinfo == null) { 
          startinfo = new processstartinfo(this);
        } 
        return startinfo;
      }
      [resourceexposure(resourcescope.machine)]
      set { 
        if (value == null) {
          throw new argumentnullexception("value"); 
        } 
        startinfo = value;
      } 
    }

5.createnowindow属性:获取或设置指示是否在新窗口中启动该进程的值。

具体介绍一下该方法的实现代码:

[
    defaultvalue(false),
    monitoringdescription(sr.processcreatenowindow),
    notifyparentproperty(true) 
    ]
    public bool createnowindow { 
      get { return createnowindow; } 
      set { createnowindow = value; }
    }

 以上简单介绍了该类的三种常用方法和两种常用属性,在实际的开发项目中无须对每个属性方法和属性的底层实现做全面的了解,但建议在学习该类的时候,适当的了解一下某一些类的方法实现,有助于我们很好的掌握该类。

二.如何实现pdf文件转化为swf文件

在项目如果需要将pdf文件转换为swf文件,可以在项目中引入swftools插件,该插件的主要功能:pdf到swf转换器。 每页生成一帧。 使您能够在flash movie中拥有完全格式化的文本,包括表格,公式,图形等。 它基于derek b. noonburg的xpdf pdf解析器。

简单介绍一下该插件的常用参数:

-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 , –password password       use password for deciphering the pdf.指定打开pdf的密码

-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的绘制顺序,可能会导致结果与原来有差异

以上是几种常用的参数,具体擦参数列表详见:。

对实现本次操作的类和插件做了一个简单的介绍,接下来提供一个具体实现该功能的操作方法:
 

 /// <summary>
    /// pdf格式转为swf
    /// </summary>
    /// <param name="pdfpathparameter">原视频文件地址,如/a/b/c.pdf</param>
    /// <param name="swfpathparameter">生成后的flv文件地址,如/a/b/c.swf</param>
    /// <param name="beginpage">转换开始页</param>
    /// <param name="endpage">转换结束页</param>
    /// <param name="photoquality">照片质量</param>
    /// <returns></returns>
    public static bool pdfconversionswf(string pdfpathparameter, string swfpathparameter, int beginpage, int endpage, int photoquality)
    {
      if (string.isnullorempty(pdfpathparameter))
      {
        throw new argumentnullexception(pdfpathparameter);
      }
      if (string.isnullorempty(swfpathparameter))
      {
        throw new argumentnullexception(swfpathparameter);
      }
      if (endpage < beginpage)
      {
        throw new argumentexception("起始页数大于结束页数");
      }
      if (photoquality <= 0)
      {
        throw new argumentexception("照片质量错误");
      }
      var exe = httpcontext.current.server.mappath("~/tools/swftools-2013-04-09-1007.exe");
      var pdfpath = httpcontext.current.server.mappath(pdfpathparameter);
      var swfpath = httpcontext.current.server.mappath(swfpathparameter);
      process p = null;
      try
      {
        if (!file.exists(exe) || !file.exists(pdfpath))
        {
          return false;
        }
        if (file.exists(swfpath))
        {
          file.delete(swfpath);
        }
        var sb = new stringbuilder();
        sb.append(" \"" + pdfpath + "\"");
        sb.append(" -o \"" + swfpath + "\"");
        sb.append(" -s flashversion=9");
        sb.append(" -s disablelinks");
        if (endpage > getpagecount(pdfpath))
        {
          endpage = getpagecount(pdfpath);
        }
        sb.append(" -p " + "\"" + beginpage + "" + "-" + endpage + "\"");
        //swf中的图片质量
        sb.append(" -j " + photoquality);
        var command = sb.tostring();
        //process提供对本地和远程的访问进程,使能够启动和停止系统进程。
        p = new process
        {
          startinfo =
          {
            filename = exe,
            arguments = command,
            workingdirectory = httpcontext.current.server.mappath("~/bin/"),
            useshellexecute = false,
            redirectstandarderror = true,
            createnowindow = false
          }
        };
        //启动线程
        p.start();
        //开始异步读取
        p.beginerrorreadline();
        //等待完成
        p.waitforexit();
        //开始同步读取
        //p.standarderror.readtoend();        
        if (!file.exists(swfpath))
          return false;
        return true;
      }
      catch (ioexception ioex)
      {
        throw new ioexception(ioex.message);
      }
      catch (exception ex)
      {
        throw new exception(ex.message);
      }
      finally
      {
        if (p != null)
        {
          //关闭进程
          p.close();
          //释放资源
          p.dispose();
        }
      }

    }

三.小结

在本文中介绍了在c#中如何操作外部程序和线程的类system.diagnostics.process,并介绍了该类的一些常用方法的底层实现代码,如果需要对该类进行详细的了解,可以根据msdn和.net底层源码的相关注释和文章进行细致的学习。在介绍完实现操作的类的同时,也对swftools插件做了一个说明,并列举了相关的参数,如果在项目中有较高的要求,可以根据官方提供的api文档进行重构。

在项目开发中,任何一个功能是无法做法完成所有的功能,在编码功能时,只能尽可能的考虑到方法的通用性,在理解了某一个类和某一个插件的基本原理和使用方法后,可以根据对应的api进行添加新功能。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网