VB.Net Wrapper simple para Ghostscript Dll [cerrado]

Me encanta Ghostscript. Puedes usarlo para convertir archivos PDF a archivos gráficos, dividir y / o combinar archivos PDF, hacer miniaturas y un montón de otras cosas. Y, es gratis, software de código abierto!

Hay montones de publicaciones en sitios web sobre cómo usar Ghostscript desde la línea de comandos para todo tipo de plataformas. Pero, nunca pude encontrar unsencillo vb.net dll wrapper que usó la dll Ghostscript (gsdll32.dll) en lugar de iniciar un proceso para ejecutar la aplicación de línea de comandos Ghostscript.

Entonces, se me ocurrió este código. Lo estoy publicando aquí con la esperanza de que otros puedan evitar la frustración que sentí al buscar algo simple y directo. Evita las matrices tontas de objetos de matriz de bytes que ves en algún código. Tiene un mínimo manejo de errores, pero puede agregarse para adaptarse a su aplicación.

Coloque este código en un módulo llamado "GhostscriptDllLib".

Option Explicit On
Imports System.Runtime.InteropServices

'--- Simple VB.Net wrapper for Ghostscript gsdll32.dll

'    (Tested using Visual Studio 2010 and Ghostscript 9.06)

Module GhostscriptDllLib

  Private Declare Function gsapi_new_instance Lib "gsdll32.dll" _
    (ByRef instance As IntPtr, _
    ByVal caller_handle As IntPtr) As Integer

  Private Declare Function gsapi_set_stdio Lib "gsdll32.dll" _
    (ByVal instance As IntPtr, _
    ByVal gsdll_stdin As StdIOCallBack, _
    ByVal gsdll_stdout As StdIOCallBack, _
    ByVal gsdll_stderr As StdIOCallBack) As Integer

  Private Declare Function gsapi_init_with_args Lib "gsdll32.dll" _
    (ByVal instance As IntPtr, _
    ByVal argc As Integer, _
    <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.LPStr)> _
    ByVal argv() As String) As Integer

  Private Declare Function gsapi_exit Lib "gsdll32.dll" _
    (ByVal instance As IntPtr) As Integer

  Private Declare Sub gsapi_delete_instance Lib "gsdll32.dll" _
    (ByVal instance As IntPtr)

  '--- Run Ghostscript with specified arguments

  Public Function RunGS(ByVal ParamArray Args() As String) As Boolean

    Dim InstanceHndl As IntPtr
    Dim NumArgs As Integer
    Dim StdErrCallback As StdIOCallBack
    Dim StdInCallback As StdIOCallBack
    Dim StdOutCallback As StdIOCallBack

    NumArgs = Args.Count

    StdInCallback = AddressOf InOutErrCallBack
    StdOutCallback = AddressOf InOutErrCallBack
    StdErrCallback = AddressOf InOutErrCallBack

    '--- Shift arguments to begin at index 1 (Ghostscript requirement)

    ReDim Preserve Args(NumArgs)
    System.Array.Copy(Args, 0, Args, 1, NumArgs)

    '--- Start a new Ghostscript instance

    If gsapi_new_instance(InstanceHndl, 0) <> 0 Then
      Return False
      Exit Function
    End If

    '--- Set up dummy callbacks

    gsapi_set_stdio(InstanceHndl, StdInCallback, StdOutCallback, StdErrCallback)

    '--- Run Ghostscript using specified arguments

    gsapi_init_with_args(InstanceHndl, NumArgs + 1, Args)

    '--- Exit Ghostscript

    gsapi_exit(InstanceHndl)

    '--- Delete instance

    gsapi_delete_instance(InstanceHndl)

    Return True

  End Function

  '--- Delegate function for callbacks

  Private Delegate Function StdIOCallBack(ByVal handle As IntPtr, _
    ByVal Strz As IntPtr, ByVal Bytes As Integer) As Integer

  '--- Dummy callback for standard input, standard output, and errors

  Private Function InOutErrCallBack(ByVal handle As IntPtr, _
    ByVal Strz As IntPtr, ByVal Bytes As Integer) As Integer

    Return 0

  End Function

End Module

El archivo gsdll32.dll debe estar donde Windows lo pueda encontrar, mejor en "\ Windows \ System32" (o "\ Windows \ SysWOW64" en una máquina de 64 bits) o en la misma carpeta que su ensamblaje. No es el tipo de dll que se debe registrar (de hecho, no se puede registrar).

Luego puede ejecutar Ghostscript usando una matriz de parámetros como esta (este ejemplo convierte un archivo pdf en un archivo png de alta calidad):

Dim PdfFilePath As String = "<Your pdf file path>"
Dim PngFilePath As String = "<Your png file path>"

RunGS("-q", "-dNOPAUSE", "-dBATCH", "-dSAFER", "-sDEVICE=png16m", _
  "-r600", _"-dDownScaleFactor=6", "-dTextAlphaBits=4", "-dGraphicsAlphaBits=4", _
  "-sPAPERSIZE=letter", "-sOutputFile=" & PngFilePath, PdfFilePath)

O puede ejecutar el código usando una matriz de cadenas como esta (mejor si los argumentos se generan dinámicamente en tiempo de ejecución):

Dim PdfFilePath As String = "<Your pdf file path>"
Dim PngFilePath As String = "<Your png file path>"

Dim Args() As String = {"-q", "-dNOPAUSE", "-dBATCH", "-dSAFER", _
  "-sDEVICE=png16m", "-r600", "-dDownScaleFactor=6", "-dTextAlphaBits=4", _
  "-dGraphicsAlphaBits=4", "-sPAPERSIZE=letter", _
  "-sOutputFile=" & PngFilePath, PdfFilePath}

RunGS(Args)

Notas:

No incluya los nombres de los archivos de entrada o salida (rutas) entre comillas como lo haría para la aplicación de línea de comandosNo escape las barras inclinadas hacia atrás (es decir, "c: ruta \ archivo.pdf" está bien, "c: ruta \\ archivo.pdf" no lo está)No utilice el interruptor "-o" de Ghostscript; utilizar "sOutputFile ="

Respuestas a la pregunta(0)

Su respuesta a la pregunta