Invólucro VB.Net simples para Ghostscript Dll [closed]
Eu amo o Ghostscript. Você pode usá-lo para converter arquivos pdf para arquivos gráficos, dividir e / ou mesclar arquivos pdf, criar miniaturas e um monte de outras coisas. E é um software livre e de código aberto!
Existem várias postagens em sites sobre como usar o Ghostscript na linha de comando para todos os tipos de plataformas. Mas eu nunca consegui encontrar umsimples vb.net dll wrapper que usou a dll Ghostscript (gsdll32.dll) em vez de iniciar um processo para executar o aplicativo de linha de comando do Ghostscript.
Então, eu inventei esse código. Estou postando aqui na esperança de que os outros possam evitar a frustração que eu senti procurando algo simples e direto. Isso evita aquelas matrizes patetas de objetos de matriz de bytes que você vê em algum código. Ele tem um tratamento de erros mínimo, mas pode ser adicionado para se adequar ao seu aplicativo.
Coloque este código em um módulo chamado "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
O arquivo gsdll32.dll deve estar onde o Windows pode encontrá-lo, melhor em "\ Windows \ System32" (ou "\ Windows \ SysWOW64" em uma máquina de 64 bits) ou na mesma pasta que o seu assembly. Não é o tipo de dll que deve ser registrado (na verdade, não pode ser registrado).
Você pode então executar o Ghostscript usando uma matriz de parâmetros como esta (este exemplo converte um arquivo pdf em um arquivo png de alta qualidade):
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)
Ou você pode executar o código usando uma matriz de cadeias como esta (melhor se os argumentos forem gerados dinamicamente no tempo de execução):
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:
Não coloque nomes de arquivos de entrada ou saída (caminhos) entre aspas como faria para o aplicativo de linha de comandosNão escape de barras invertidas (por exemplo, "c: path \ file.pdf" está ok, "c: path \\ file.pdf" não está)Não use a opção "-o" do Ghostscript; use "sOutputFile ="