GithubHelp home page GithubHelp logo

artifexsoftware / ghostscript.net Goto Github PK

View Code? Open in Web Editor NEW
368.0 40.0 149.0 1.04 MB

Ghostscript.NET - managed wrapper around the Ghostscript library (32-bit & 64-bit)

Home Page: https://ghostscript.com

License: GNU Affero General Public License v3.0

C# 100.00%
csharp dotnet ghostscript pdf postscript viewer

ghostscript.net's Introduction

logo

Ghostscript.NET - (written in C#) is the most completed managed wrapper library around the Ghostscript library (32-bit & 64-bit), an interpreter for the PostScript language, PDF, related software and documentation.

NuGet: PM> Install-Package Ghostscript.NET

Contains

  • GhostscriptViewer - View PDF, EPS or multi-page PostScript files on the screen
  • GhostscriptRasterizer - Rasterize PDF, EPS or multi-page PostScript files to any common image format.
  • GhostscriptProcessor - An easy way to call a Ghostscript library with a custom arguments / switches.
  • GhostscriptInterpreter - The PostScript interpreter.

Other features

  • allows you to rasterize files in memory without storing the output to disk.
  • supports zoom-in and zoom-out.
  • supports progressive update.
  • allows you to run multiple Ghostscript instances simultaneously within a single process.
  • compatible with 32-bit and 64-bit Ghostscript native library.

Latest changes - 2021-03-09 - v.1.2.3.

  • fixed GhostscriptRasterizer/GhostscriptViewer and Ghostscript v.9.50+ compatibility issues.

Latest changes - 2021-02-04 - v.1.2.2.

  • fixed Ghostscript v.9.26 + (all later versions) compatibility.
  • fixed problem when opening path/file that contains non ASCII characters.
  • fixed "Arithmetic operation resulted in an overflow" when using multithread instance.
  • changed Y and Y DPI settings to match GhostscriptViewer.
  • fixed CurrentPage -> TotalPages logging.
  • fixed watermark transparency bug for PDF.

Samples built on the top of the Ghostscript.NET library

Direct postscript interpretation via Ghostscript.NET:

Ghostscript.NET.Display

Ghostscript.NET.Viewer (supports viewing of the PDF, EPS and multi-page PS files):

Ghostscript.NET.Viewer

License and Copyright

Available under both, open-source AGPL and commercial license agreements.

Please read the full text of the AGPL license agreement (which is also included here in file COPYING) to ensure that your use case complies with the guidelines of this license. If you determine you cannot meet the requirements of the AGPL, please contact Artifex for more information regarding a commercial license.

Artifex is the exclusive commercial licensing agent for Ghostscript.

ghostscript.net's People

Contributors

ajalex74 avatar alemararias avatar antonio-russo avatar crayjin avatar dfrankcw avatar filipowicz251 avatar guillaume-fr avatar jamie-lemon avatar jhabjan avatar kokeiro001 avatar mrantix avatar sandromastronardi avatar tilgovi avatar ummerland avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ghostscript.net's Issues

Print big PDF dont work correctly

I use Ghostscript.net to print PDF's from a folder, but it does not work as expected.

If i print a file with 2 Pages, it works fine and the layout is clean and readable.
But if i print a pdf with 73 Pages i got crazy results.

If i start the Print, ghostscript pops up many times (without -dNoCancel switch) and the layout is sometimes not readable and sometimes with many layout bugs.

What could i do to remove this behavior on big files?

My current Code:

private void print(string path)  
        {  
            string defaultPrinter = Configurations.getPrinter();  
            using (GhostscriptProcessor processor = new GhostscriptProcessor())  
            {  
                List<string> switches = new List<string>();  
                switches.Add("-empty");  
                switches.Add("-dPrinted");  
                switches.Add("-dBATCH");  
                switches.Add("-dNOPAUSE");  
                switches.Add("-dNOSAFER");  
                switches.Add("-dNumCopies=1");  
                switches.Add("-sDEVICE=mswinpr2");  
                switches.Add("-sPAPERSIZE#a4");  
                switches.Add("-dFIXEDMEDIA");  
                switches.Add("-dPDFFitPage");  
                switches.Add("-sOutputFile=%printer%" + defaultPrinter);  
                switches.Add("-f");  
                switches.Add(path);  
                processor.Completed += (object sender, GhostscriptProcessorEventArgs e) => this.printexited(sender, e, path);  
                processor.StartProcessing(switches.ToArray(), null);  
            }  
        }

Cannot open files with umlaut in path or filename

I'm not able to open any file with a umlaut (äöü) in the path or filename. i don't know if it is a ghostscript.net or a ghostscript bug.

I open a file like:
rasterizer.Open(inputFile); //opens the PDF file for rasterizing

There is already a conversion to utf8, and the string looks ok.
filePath = StringHelper.ToUtf8String(filePath);

// GSAPI: run the string
int rc_run = _gs.gsapi_run_string(_gs_instance, str, 0, out exit_code);

This line brings the error.

Transparency is not respected when rendering PDFs

https://github.com/jhabjan/Ghostscript.NET/blob/49a233f888eff8d3ac67786a602c5fe40b0da675/Ghostscript.NET/Viewer/FormatHandlers/GhostscriptViewerPdfFormatHandler.cs#L274

This line causes incorrect handling of PDFs with embedded transparent images.

Code that determines whether transparency is required on a given page is included in the procedure pdfshowpage_setpage. I'm not clear on what else that procedure does, but the rest of it might be important too.

Unless there is a specific reason that pdfshowpage_setpage is being omitted, it should be included here. Alternatively, this line could be simplified to

this.Execute("Page pdfshowpage");

... which calls pdfshowpage_init, pdfshowpage_setpage, and pdfshowpage_finish in succession (and has done so since at least 2007 for Ghostscript 8.56, and likely earlier).

Attached is an example of a PDF with a transparent image. Currently it is displayed as a black box on a gray background. It should be displayed as the word "hello", in black text on a gray background.

hellopng.pdf

GhostScript.NET v1.2.1 Library Load issue

As I answered someone else's problem, mine was still only partially solved.

I'm using the library on a website that allows multiple users to upload PDF's at the same time and needs to invoke the GS DLL simultaneously. What I found was this is not possible so instead I use this solution

static lock surrounds -> raster.Open(fileStream, _version, false);

This has been working fine for 99.5% of cases but now for the first time after several months on the server I see this rare-bird 4 times in an hour for a user that I cannot replicate:

System.Exception: Module could not be loaded.
at Microsoft.WinAny.Interop.DynamicNativeLibrary..ctor(String fileName)
at Ghostscript.NET.GhostscriptLibrary..ctor(GhostscriptVersionInfo version, Boolean fromMemory)
at Ghostscript.NET.Interpreter.GhostscriptInterpreter..ctor(GhostscriptVersionInfo version, Boolean fromMemory)
at Ghostscript.NET.Viewer.GhostscriptViewer.Open(String path, GhostscriptVersionInfo versionInfo, Boolean dllFromMemory)
at Ghostscript.NET.Viewer.GhostscriptViewer.Open(Stream stream, GhostscriptVersionInfo versionInfo, Boolean dllFromMemory)
at Ghostscript.NET.Rasterizer.GhostscriptRasterizer.Open(Stream stream, GhostscriptVersionInfo versionInfo, Boolean dllFromMemory)

I have no idea how to replicate it and she tried later with the exact same .pdf upload and this time it works again fine.

My guess is something about the DLL not being entirely in memory correctly, or else IIS recycling and losing the static lock -- but this should be a very rare thing in production and I'm wondering if something else weird is going on with the DLL.

Issue "An error occured when call to 'gsapi_init_with_args' is made: -100" While converting PDF to PDF/A

Public Sub Start()
        Dim gv As GhostscriptVersionInfo = New GhostscriptVersionInfo("C:\Program Files\gs\gs9.18\bin\gsdll64.dll")
        Dim proc As GhostscriptProcessor = New GhostscriptProcessor(gv)
        Dim switches As List(Of String) = New List(Of String)()

        switches.Add("-dPDFA=1")
        switches.Add("-dNoCancel")
        switches.Add("-dNOPAUSE")
        switches.Add("-dNOOUTERSAVE")
        switches.Add("-sProcessColorModel=DeviceRGB")
        switches.Add("-sDEVICE=pdfwrite")
        switches.Add("-sOutputFile=pdfa.pdf")
        switches.Add("PDFA_def.ps")
        switches.Add("-dPDFACompatibilityPolicy=1")
        switches.Add("teste.pdf")
       proc.StartProcessing(switches.ToArray, Nothing)
End Sub

If I switch the parameters to make conversion of PDF to JPEG, using the code below, that's ok.

switches.Add("-dSAFER")
switches.Add("-dBATCH")
switches.Add("-dNOPAUSE")
switches.Add("-sDEVICE=jpeg")
switches.Add("-sOutputFile=figure.jpg")
switches.Add("teste.pdf")

If I run the command below from CMD, that's works too.

gswin64 -dPDFA=1 -dNoCancel -dNOPAUSE -dNOOUTERSAVE -sProcessColorModel=DeviceRGB -sDEVICE=pdfwrite -sOutputFile=pdfa.pdf PDFA_def.ps -dPDFACompatibilityPolicy=1 teste.pdf

Any suggestion?

The nuget project site

Hi,
On the nuget gallery there is still the old codeplex used as the "project site". It took me some time before I realized there is an actual git repo.

An error occured when call to 'gsapi_new_instance' is made: -100

HI

I am developeing an asp.net MVC application intranet application

I want to get the print of pdf document, using the ghostscript dll. It works fine in localhost, but when i run in hosted environment, it throws the error as An error occured when call to 'gsapi_new_instance' is made: -100 .

Is this something related to admin rights?

Thanks
Sunny

Can't open files with specials unicode characters in filename

If the title has a special character (in my case "ê"), then :

GhostscriptRasterizer rasterizer = new GhostscriptRasterizer();
rasterizer.Open(pdfPath, bytearray);

returns "Input string was not in a correct format."

I looked a bit into it and could just see in GhostscriptStdIO -> gs_std_out ->

string output = Marshal.PtrToStringAnsi(pointer, count);

when output should return the list of pages it returns :
%GSNET_VIEWER_PDF_PAGES: Unrecoverable error: stackunderflow

Stack Overflow Exception when reading a bad PDF

When we try to open an invalid PDF (we just took out the first few lines of a PDF file), we get a stack overflow exception because of the code here in the GhostscriptViewerPdfFormatHandler.cs:

                case PDF_PAGES_TAG:
                    {
                        string[] pages = rest.Split(new char[] { ' ' });
                        this.FirstPageNumber = int.Parse(pages[0]);
                        this.LastPageNumber = int.Parse(pages[1]);
                    }

To resolve we added this to the GhostscriptViewerStdIOHandler.cs:
string line = _outputMessages.ToString().Substring(0, rIndex);
if(line.ToUpper().Contains("UNRECOVERABLE"))
{
rIndex = -1;
return;
}

Basically, it keeps throwing string format exception when trying to parse the pages until the stack overlfows. Let me know if you need additional information. I'd be happy to add my fix to your code, but you may know of a better way to resolve the issue.

"An error occured when call to 'gsapi_init_with_args' is made: -100"

I'm getting this error for same pdf file. Sometimes works sometimes throw this exception.

here is my code

public static void Export_Thumbnail_Png(string orginalfile, string thumbPath)
{
GhostscriptJpegDevice dev = new GhostscriptJpegDevice(GhostscriptJpegDeviceType.Jpeg);
dev.GraphicsAlphaBits = GhostscriptImageDeviceAlphaBits.V_4;
dev.TextAlphaBits = GhostscriptImageDeviceAlphaBits.V_4;
dev.ResolutionXY = new GhostscriptImageDeviceResolution(32, 32);
dev.JpegQuality = 90;
dev.InputFiles.Add(orginalfile);
dev.Pdf.FirstPage = 1;
dev.Pdf.LastPage = 3;
dev.OutputPath = thumbPath;
dev.Process();
}

image001

GhostScriptRasterizer shows a PageCount of 0 for all PDFs under GhostScript 9.27

Package version: 1.21
Ghostscript binary version: 9.27 x64
Platform: Windows 10 1809
Project: ASP.NET on .NET Framework 4.6.1, C#

Running the following code produces a GhostscriptRasterizer that has a PageCount of 0.

using (var rasterizer = new GhostscriptRasterizer())
{
    rasterizer.Open("<path to file>");
    // rasterizer.PageCount == 0
}

The same outcome occurs with any input PDF, regardless of contents. It also occurs when calling the Stream overload of Open() with a FileStream or MemoryStream.

Downgrading to Ghostscript 9.26 on the same system fixes the issue.

Apologies in advance if 9.27 is not supported by package version 1.21; I couldn't seem to find a compatibility table.

GhostscriptAPICallException: An error occured when call to 'gsapi_new_instance' is made: -100

I occasionally get this exception, any idea about the root cause?

GhostscriptAPICallException: An error occured when call to 'gsapi_new_instance' is made: -100,

stack trace:
Ghostscript.NET.Interpreter.GhostscriptInterpreter.Initialize():47
Ghostscript.NET.Interpreter.GhostscriptInterpreter..ctor(GhostscriptVersionInfo version, Boolean fromMemory):55
Ghostscript.NET.Viewer.GhostscriptViewer.Open(String path, GhostscriptVersionInfo versionInfo, Boolean dllFromMemory):47
Ghostscript.NET.Viewer.GhostscriptViewer.Open(Stream stream, GhostscriptVersionInfo versionInfo, Boolean dllFromMemory):47
Ghostscript.NET.Rasterizer.GhostscriptRasterizer.Open(Stream stream, GhostscriptVersionInfo versionInfo, Boolean dllFromMemory):36

Need to get image with precise resolution

Hi,

Need to check is their any way to get image with precise resolution than rounding off.

Iam currently using RasterizerSample1 for converting pdf to image using in memory. but rasterizer.GetPage(desired_x_dpi, desired_y_dpi, pageNumber) uses desired_x_dpi and desired_y_dpi as integer can we have sample with double has input parameter.

Please let me know if their is any other alternative to generate image with precise image resolution conversion.

Example is I need to pass in r426.5x426.44 has Width and Height.

if their is no alternative can you please change that input parameters to accept double instead of integer.

Thanks,
Pradeep

Error -100 PDF Marks

Howdy!

I have tried many, many combinations, but it seems pdf mark is not working.

Here is what I am trying to run:

var switches = new List<string> { "-dBATCH", "-dNOPAUSE", "-sDEVICE=pdfwrite", "-c", "\"[/Creator()/Author()/Subject()/Title()/Keywords() /DOCINFO pdfmark\"", $"-sOutputFile={pdfOutput}", pdfInput };

I always get -100 error.

Thanks in advance

System.Drawing.dll exception occurrs

PDF viewer is generated using GhostscriptViewer class. After closing GhostscriptViewer object , i display Message on PDF viewer through MessageBox.
It generates An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll
Exception and it automatically close the application.
How to handle this situation.

An error occured when call to 'gsapi_init_with_args' is made: -100

Following the Samples here I've created a test PDF which I hope to export to TIF. When I run the code below I get an error that so far internet searches have been unhelpful: An error occured when call to 'gsapi_init_with_args' is made: -100

If it helps, here is the Exception target site: Void StartProcessing(System.String[], Ghostscript.NET.GhostscriptStdIO)

Here is my code:

using (var ghostscript = new GhostscriptProcessor()) {
    ghostscript.Processing += Ghostscript_Processing;

    var switches = new string[] {
        "-dSAFER",
        "-dBATCH",
        "-dNOPAUSE",
        "-sDEVICE=tiffgray",
        "-sCompression=lzw",
        "-r150",
        @"-sOutputFile=C:\temp\test.tif",
        @"C:\temp\TESTDOC.pdf"
    };

    ghostscript.Process(switches);
}

Once I get past this error my goal is to combine multiple PDF files into one multi-page TIF file. I have successfully tested this using Ghostscript and the command line.

Thank you.

How to compile?

Hi,

I'm using Visual Studio 2013 to open the solution for VS2013 .
But I'm having lots of problem compiling it.
E.g. in streamhelper.cs, it says stream.CopyTo function in line 125, does not contain definition for 'CopyTo'

And many others where the definition cannot be found.
Is there some dependency that I miss?
Thanks.

REgards,
Long

A feature question--how to print multiple pdf files?

Thanks for the wrapper library!
I have a question, how can we print multiple pdf files? I've got a working arguments list but it doesn't work with your wrapper library;
$" -dPrinted -dBATCH -dNOPAUSE -dNOSAFER -q -sDEVICE=mswinpr2 -sOutputFile=\"\\\\spool\\{printerName}\" {pdfFileNames}"

Print pdf to printer from Web Service

Hello,
I'm trying to print a pdf file to printer directly from a Web service.
It works under IIS Express but in deployment machine it doesn't work.
Gives:
An error occured when call to 'gsapi_new_instance' is made: -100

The code is:

Using processor As New GhostscriptProcessor()
            Dim switches As New List(Of String)()
            switches.Add("-empty")
            switches.Add("-dPrinted")
            switches.Add("-dBATCH")
            switches.Add("-dNOPAUSE")
            switches.Add("-dNOSAFER")
            switches.Add("-dNumCopies=1")
            switches.Add("-sDEVICE=mswinpr2")
            switches.Add(Convert.ToString("-sOutputFile=%printer%") & printerName)
            switches.Add("-f")
            switches.Add(filename)

            processor.StartProcessing(switches.ToArray(), Nothing)
        End Using

IIS is running 64 bit.
ApplicationPool has an Administrator user identity.

Doesn't work on mono / .NET Core runtime

When running the code on Mono on Linux, calling .Open(...) on the GhostscriptRasterizer fails with an exception. It appears that the code is attempting to find the installation location of Ghostscript from the Registry (which in case of Linux installations is the Mono registry in e.g. /etc/mono/registry) but totally ignores that a valid Ghostscript library might already be in the path.

Unhandled Exception:
System.AggregateException: One or more errors occurred. ---> Ghostscript.NET.GhostscriptLibraryNotInstalledException: This managed library is running under 64-bit process and requires 64-bit Ghostscript native library installation on this machine! To download proper Ghostscript native library please visit: http://www.ghostscript.com/download/gsdnld.html
  at Ghostscript.NET.GhostscriptVersionInfo.GetLastInstalledVersion (Ghostscript.NET.GhostscriptLicense licenseType, Ghostscript.NET.GhostscriptLicense licensePriority) [0x00068] in <5f6fd62cf1d54aefb818afa45c4a7251>:0 
  at Ghostscript.NET.Rasterizer.GhostscriptRasterizer.Open (System.IO.Stream stream) [0x0000e] in <5f6fd62cf1d54aefb818afa45c4a7251>:0 
  at PdfExtract.Program.ExtractImages (System.IO.Stream stream, System.IO.DirectoryInfo outputPath, System.Int32 dpi, System.Int64 quality) [0x00072] in <1687eef90b70415191e0dd63b40d465f>:0
   --- End of inner exception stack trace ---
  at System.Threading.Tasks.Task.ThrowIfExceptional (System.Boolean includeTaskCanceledExceptions) [0x00011] in <204f770036d441bb8dfd3daba3550e83>:0 
  at System.Threading.Tasks.Task`1[TResult].GetResultCore (System.Boolean waitCompletionNotification) [0x0002b] in <204f770036d441bb8dfd3daba3550e83>:0 
  at System.Threading.Tasks.Task`1[TResult].get_Result () [0x0000f] in <204f770036d441bb8dfd3daba3550e83>:0 
  at Microsoft.Extensions.CommandLineUtils.CommandLineApplication+<>c__DisplayClass79_0.<OnExecute>b__0 () [0x0000b] in <af5004465019421ab8103642fc8570cf>:0 
  at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute (System.String[] args) [0x0035b] in <af5004465019421ab8103642fc8570cf>:0 
  at Everybag.PdfExtract.Program.Main (System.String[] args) [0x0010d] in <1687eef90b70415191e0dd63b40d465f>:0 
---> (Inner Exception #0) Ghostscript.NET.GhostscriptLibraryNotInstalledException: This managed library is running under 64-bit process and requires 64-bit Ghostscript native library installation on this machine! To download proper Ghostscript native library please visit: http://www.ghostscript.com/download/gsdnld.html
  at Ghostscript.NET.GhostscriptVersionInfo.GetLastInstalledVersion (Ghostscript.NET.GhostscriptLicense licenseType, Ghostscript.NET.GhostscriptLicense licensePriority) [0x00068] in <5f6fd62cf1d54aefb818afa45c4a7251>:0 
  at Ghostscript.NET.Rasterizer.GhostscriptRasterizer.Open (System.IO.Stream stream) [0x0000e] in <5f6fd62cf1d54aefb818afa45c4a7251>:0 
  at PdfExtract.Program.ExtractImages (System.IO.Stream stream, System.IO.DirectoryInfo outputPath, System.Int32 dpi, System.Int64 quality) [0x00072] in <1687eef90b70415191e0dd63b40d465f>:0 

I was trying to force it to use my system version by providing a GhostscriptVersionInfo to as .Open(..., gvi) as

var gvi = new GhostscriptVersionInfo("/usr/lib/x86_64-linux-gnu/libgs.so.9");

and

var gvi = new GhostscriptVersionInfo(new Version(9, 18), "/usr/lib/x86_64-linux-gnu/libgs.so.9", "/usr/lib/x86_64-linux-gnu/libgs.so.9", GhostscriptLicense.GPL);

but that led to another (misleading) exception:

System.AggregateException: One or more errors occurred. ---> System.BadImageFormatException: You are using native Ghostscript library (gsdll32.dll) compiled for 32bit systems in a 64bit process. You need to use gsdll64.dll. 64bit native Ghostscript library can be downloaded from http://www.ghostscript.com/download/gsdnld.html
  at Ghostscript.NET.GhostscriptLibrary.ThrowIncompatibileNativeGhostscriptLibraryException () [0x0000e] in <5f6fd62cf1d54aefb818afa45c4a7251>:0 
  at Ghostscript.NET.GhostscriptLibrary..ctor (Ghostscript.NET.GhostscriptVersionInfo version, System.Boolean fromMemory) [0x0004c] in <5f6fd62cf1d54aefb818afa45c4a7251>:0 
  at Ghostscript.NET.Interpreter.GhostscriptInterpreter..ctor (Ghostscript.NET.GhostscriptVersionInfo version, System.Boolean fromMemory) [0x0002a] in <5f6fd62cf1d54aefb818afa45c4a7251>:0 
  at Ghostscript.NET.Viewer.GhostscriptViewer.Open (System.String path, Ghostscript.NET.GhostscriptVersionInfo versionInfo, System.Boolean dllFromMemory) [0x0002f] in <5f6fd62cf1d54aefb818afa45c4a7251>:0 
  at Ghostscript.NET.Viewer.GhostscriptViewer.Open (System.IO.Stream stream, Ghostscript.NET.GhostscriptVersionInfo versionInfo, System.Boolean dllFromMemory) [0x0002f] in <5f6fd62cf1d54aefb818afa45c4a7251>:0 
  at Ghostscript.NET.Rasterizer.GhostscriptRasterizer.Open (System.IO.Stream stream, Ghostscript.NET.GhostscriptVersionInfo versionInfo, System.Boolean dllFromMemory) [0x00024] in <5f6fd62cf1d54aefb818afa45c4a7251>:0 
  at PdfExtract.Program.ExtractImages (System.IO.Stream stream, System.IO.DirectoryInfo outputPath, System.Int32 dpi, System.Int64 quality) [0x0008d] in /home/mmayer/dev/everybag/Everybag.PdfExtract/src/Everybag.PdfExtract/Program.cs:219
   --- End of inner exception stack trace ---
  at System.Threading.Tasks.Task.ThrowIfExceptional (System.Boolean includeTaskCanceledExceptions) [0x00011] in <204f770036d441bb8dfd3daba3550e83>:0 
  at System.Threading.Tasks.Task`1[TResult].GetResultCore (System.Boolean waitCompletionNotification) [0x0002b] in <204f770036d441bb8dfd3daba3550e83>:0 
  at System.Threading.Tasks.Task`1[TResult].get_Result () [0x0000f] in <204f770036d441bb8dfd3daba3550e83>:0 
  at Microsoft.Extensions.CommandLineUtils.CommandLineApplication+<>c__DisplayClass79_0.<OnExecute>b__0 () [0x0000b] in <af5004465019421ab8103642fc8570cf>:0 
  at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute (System.String[] args) [0x0035b] in <af5004465019421ab8103642fc8570cf>:0 
  at PdfExtract.Program.Main (System.String[] args) [0x0010d] in /home/mmayer/dev/everybag/Everybag.PdfExtract/src/Everybag.PdfExtract/Program.cs:42 
---> (Inner Exception #0) System.BadImageFormatException: You are using native Ghostscript library (gsdll32.dll) compiled for 32bit systems in a 64bit process. You need to use gsdll64.dll. 64bit native Ghostscript library can be downloaded from http://www.ghostscript.com/download/gsdnld.html
  at Ghostscript.NET.GhostscriptLibrary.ThrowIncompatibileNativeGhostscriptLibraryException () [0x0000e] in <5f6fd62cf1d54aefb818afa45c4a7251>:0 
  at Ghostscript.NET.GhostscriptLibrary..ctor (Ghostscript.NET.GhostscriptVersionInfo version, System.Boolean fromMemory) [0x0004c] in <5f6fd62cf1d54aefb818afa45c4a7251>:0 
  at Ghostscript.NET.Interpreter.GhostscriptInterpreter..ctor (Ghostscript.NET.GhostscriptVersionInfo version, System.Boolean fromMemory) [0x0002a] in <5f6fd62cf1d54aefb818afa45c4a7251>:0 
  at Ghostscript.NET.Viewer.GhostscriptViewer.Open (System.String path, Ghostscript.NET.GhostscriptVersionInfo versionInfo, System.Boolean dllFromMemory) [0x0002f] in <5f6fd62cf1d54aefb818afa45c4a7251>:0 
  at Ghostscript.NET.Viewer.GhostscriptViewer.Open (System.IO.Stream stream, Ghostscript.NET.GhostscriptVersionInfo versionInfo, System.Boolean dllFromMemory) [0x0002f] in <5f6fd62cf1d54aefb818afa45c4a7251>:0 
  at Ghostscript.NET.Rasterizer.GhostscriptRasterizer.Open (System.IO.Stream stream, Ghostscript.NET.GhostscriptVersionInfo versionInfo, System.Boolean dllFromMemory) [0x00024] in <5f6fd62cf1d54aefb818afa45c4a7251>:0 
  at PdfExtract.Program.ExtractImages (System.IO.Stream stream, System.IO.DirectoryInfo outputPath, System.Int32 dpi, System.Int64 quality) [0x0008d] in /home/mmayer/dev/everybag/Everybag.PdfExtract/src/Everybag.PdfExtract/Program.cs:219 

The file is a 64bit shared library indeed, but the assumptions in NativeLibraryHelper make it believe it's not, because it's not an NT DLL.

Umlaut

We are facing this umlaut Issue. I saw a fix in 49a233f. Can we expect a new release for nuget?

Addition:
commit 2d184de (from @Crayjin ) and 280268c are working properly with Umlaut.

647ccc7 (from @zys529 ) and 49a233f is not (latest commit in master)

Facing an Issue "An error occured when call to 'gsapi_init_with_args' is made: -100" While converting ps to PNG

        GhostscriptPipedOutput gsPipedOutput = new GhostscriptPipedOutput();
        string outputPipeHandle = "%handle%" + int.Parse(gsPipedOutput.ClientHandle).ToString("X2");
        using (GhostscriptProcessor processor = new GhostscriptProcessor())
        {
            List<string> switches = new List<string>();
            switches.Add("-empty");
            switches.Add("-dQUIET");
            switches.Add("-dSAFER");
            switches.Add("-dBATCH");
            switches.Add("-dNOPAUSE");
            switches.Add("-dNOPROMPT");
            switches.Add("-dNumCopies=1");
            switches.Add("-sDEVICE=pngalpha");
            switches.Add("-o" + outputPipeHandle);
            switches.Add("-sOutputFile=C:\\Converted.png");
            switches.Add(PSFile);
            processor.StartProcessing(switches.ToArray(), null);
          }

Use with Unity

Hi,

Can I use this through Unity3D and obtain the images (from the pdf) while displaying them as textures?
What platforms can I perform the conversion on at runtime?

Thanks,
Sidhant.

Works locally but fails on server

Hi hope you can help. I am pretty sure its a simple problem.

I have the service running via IIS Express (within Visual Studio) however when I deploy it on my dev server with IIS 8 nothing works.

I get the following error when I try to convert a PDF to an image

An error occured when call to 'gsapi_new_instance' is made: -100

I have my application running as an administrator account and I have installed the ghostscript library on the server and rebooted.

The code I use works fine locally. Is there anything else I need to install on the server?

tiff monochrome

Hi,
I don't see Tiff in the device list ,I wanted to convert my pdf to tiff , monochrome, 300X300 dpi , with no dithering , how can i accomplish that with this library?

Thanks!
Feruz

version 1.2.1 Arithmetic overflow error at DynamicNativeLibrary.FinalizeSections(MEMORY_MODULE* memory_module)

Hello I have been using GhostScript.net framework for last two weeks and it worked fine till today. I started getting error

"Microsoft.WinAny.Interop.DynamicNativeLibrary.FinalizeSections(MEMORY_MODULE* memory_module) at Microsoft.WinAny.Interop.DynamicNativeLibrary.MemoryLoadLibrary(Byte[] data) at Microsoft.WinAny.Interop.DynamicNativeLibrary..ctor(Byte[] buffer) at Ghostscript.NET.GhostscriptLibrary..ctor(GhostscriptVersionInfo version, Boolean fromMemory) at Ghostscript.NET.Processor.GhostscriptProcessor..ctor(GhostscriptVersionInfo version, Boolean fromMemory) "

And this is how I call Ghostscprit methods just like shown at example codes.

GhostscriptVersionInfo gv = GhostscriptVersionInfo.GetLastInstalledVersion();

            using (GhostscriptProcessor processor = new GhostscriptProcessor(gv, true))
            {
             }

GhostscriptProcessor(gv,true) throws the error above. What makes me worry is that this error persist and ghostscript does not work anymore.
How I can fix this issue ?

Pdf to image issue

Hello,
When i render a pdf page containing text and schematics to an image, the text looks correct but the schematics have a black background (original is white).

Do you have an idea please ?

Error in current page handling of Ghostscript Processor

Hi,

Running the following:
gswin64c -dNODISPLAY -q -sFile="test.PDF" pdf_info.ps

has the following output:


        test.PDF has 1 page.

Title: 120906_DACHSER_CMYK
Creator: Adobe Illustrator CS5
Producer: Adobe PDF library 9.90
CreationDate: D:20121017105900+02'00'
ModDate: D:20121017105900+02'00'

Page 1 MediaBox: [0.0 0.0 157.833 34.666] BleedBox: [0.0 0.0 157.833 34.666] TrimBox: [0.0 0.0 157.833 34.666] ArtBox: [2.76025 1.92285 155.824 31.4028]

No system fonts are needed.

The GhostScript processor throws an exception with the following stacktrace:

   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
   at Ghostscript.NET.Processor.GhostscriptProcessor.ProcessOutputLine(String line) in R:\EDENRED\Ghostscript.NET\Ghostscript.NET-master\Ghostscript.NET\Processor\GhostscriptProcessor.cs:line 462
   at Ghostscript.NET.Processor.GhostscriptProcessor.OnStdIoOutput(String output) in R:\EDENRED\Ghostscript.NET\Ghostscript.NET-master\Ghostscript.NET\Processor\GhostscriptProcessor.cs:line 407
   at Ghostscript.NET.Processor.GhostscriptProcessorInternalStdIOHandler.StdOut(String output) in R:\EDENRED\Ghostscript.NET\Ghostscript.NET-master\Ghostscript.NET\Processor\GhostscriptProcessorInternalStdIOHandler.cs:line 51
   at Ghostscript.NET.GhostscriptStdIO.gs_std_out(IntPtr handle, IntPtr pointer, Int32 count) in R:\EDENRED\Ghostscript.NET\Ghostscript.NET-master\Ghostscript.NET\GhostscriptStdIO.cs:line 173

Code sample:

using (GhostscriptProcessor processor = new GhostscriptProcessor(gv, true))
            {
                List<string> switches = new List<string>();
                switches.Add("-q");
                switches.Add("-dNODISPLAY");
                switches.Add(@"-sFile=" + fileName);
                switches.Add("pdf_info.ps");

                // if you don't want to handle stdio, you can pass 'null' value as the last parameter
                StdIOHandler stdio = new StdIOHandler(_output, _error);
                processor.StartProcessing(switches.ToArray(), stdio);

                string output = _output.ToString();
            }

The stdio class used is this:

    public class StdIOHandler : GhostscriptStdIO
    {
        private StringBuilder _output = null;
        private StringBuilder _error = null;

        public StdIOHandler(StringBuilder output, StringBuilder error)
            : base(true, true, true)
        {
            _output = output;
            _error = error;
        }

        public override void StdIn(out string input, int count)
        {
            input = null;
        }

        public override void StdOut(string output)
        {
            if (_output != null)
            {
                _output.Append(output);
            }
        }

        public override void StdError(string error)
        {
            if (_error != null)
            {
                _error.Append(error);
            }
        }
    }

The exception is due to the current page parsing algorithm used here:


        private void ProcessOutputLine(string line)
        {
            if (line.StartsWith("Processing pages"))
            {
                string[] chunks = line.Split(EMPTY_SPACE_SPLIT);
                _totalPages = int.Parse(chunks[chunks.Length - 1].TrimEnd('.'));
            }
            else if (line.StartsWith("Page"))
            {
                string[] chunks = line.Split(EMPTY_SPACE_SPLIT);
                int currentPage = int.Parse(chunks[chunks.Length - 1]);

                this.OnProcessing(new GhostscriptProcessorProcessingEventArgs(currentPage, _totalPages));
            }
        }

for the line:

Page 1 MediaBox: [0.0 0.0 157.833 34.666] BleedBox: [0.0 0.0 157.833 34.666] TrimBox: [0.0 0.0 157.833 34.666] ArtBox: [2.76025

The next token after 'Page' should be checked in this case.

Regards,
Mike

Should be input.Read rather than outputRead

I believe that this line should be input.Read rather than output.Read:

https://github.com/jhabjan/Ghostscript.NET/blob/280268c710427f0180e20f06bdabd3a1a01debcb/Ghostscript.NET/Helpers/StreamHelper.cs#L171

And, IMO, when you say GhostscriptRasterizer allows you to rasterize pdf and postscript files into the memory, I believe you should clarify that this works because this code is writing a temporary file, using it, and then deleting it. While this works, this approach could also leave confidential information vulnerable to compromise since it is not doing any kind of secure delete.

AccessViolationException when Temp path contains "á"

Whenever the TEMP/TMP ambient variables contains a character with the (´) diacritic, GhostScript.NET can't access the temp folder.

The user had both TEMP and TMP variables with:
%USERPROFILE%\AppData\Local\Temp
Which results in:
C:\Users\Usuário\AppData\Local\Temp

Changing the location to something else, like C:\AppData\Local\Temp solves this issue, but it's not the best solution.

This is the stack trace, abridged:

System.AccessViolationException 

at Ghostscript.NET.Interpreter.GhostscriptInterpreter.Dispose(Boolean) 
at Ghostscript.NET.Viewer.GhostscriptViewer.Close() 
at Ghostscript.NET.Viewer.GhostscriptViewer.Open(System.String, 
   Ghostscript.NET.GhostscriptVersionInfo, Boolean) 
at MyProject.PdfPrintViewer.EndInit() 

Selecting Paper Source

Is it possible to select a specific paper source/tray?

I have tried some Ghostscript command line arguments like -dManualFeed=true and -dMediaPosition=3. But not worked.

"Select Printer" dialog pops up even when printer selected

I'm using the following switches:

-empty
-dQUIET
-sPAPERSIZE=letter
-dFIXEDMEDIA
-dPrinted
-dBATCH
-dNOPAUSE
-dNOSAFER
-dPDFFitPage
-dNumCopies=1
-sDEVICE=mswinpr2
-sOutputFile="%printer%\printserver\printer name"
-f

(%printer% - two slashes - print server - one slash - printer name) github mangled the slashes in my post

However I keep getting the "select printer" dialog.

Am I specifying the print queue name incorrectly?

The print queue does have spaces in it's name.
Thanks!

Doesn't work in Windows Server 2012 R2

Hi, I am using Ghostscript.NET in my Project to print Pdf files using Network. Locally works fine, using Windows 10, version 64 bits and Ghostscript Driver to 32-Bit (Ghostscript 9.22 for Windows 32-Bit) downloaded from https://www.ghostscript.com/download/gsdnld.html. The motivation to install 32-Bit version is the exception,

Ghostscript.NET.GhostscriptLibraryNotInstalledException: This managed library is running under 32-Bit process and requires 32-Bit Ghostscript native library installation on this machine! To download proper Ghostscript native library please visit: http://www.ghostscript.com/download/gsdnld.html

, which occurs in my application log when using Ghostscript 64 bits Driver.

The target Operation System where I published my application is Windows Server 2012 R2. Using same Ghostscript Driver (Ghostscript 9.22 for Windows 32-Bit), print command loops indefinitely, without response to my application.

My application reads pdf file from disk and sends it to Network Printer using Ghostscript. For simulating the process I connect to client machine remotely using TeamViewer. So, I call a REST Web Service from this machine, which saves the file to disk and uses Ghostscript to print the document in a Network Printer.

try
                {
                    var task = Task.Run(() =>
                    {
                        using (GhostscriptProcessor processor = new GhostscriptProcessor(GhostscriptVersionInfo.GetLastInstalledVersion(), true))
                        {
                            List<string> switches = new List<string>();
                            switches.Add("-empty");
                            switches.Add("-dPrinted");
                            switches.Add("-dBATCH");
                            switches.Add("-dNOPAUSE");
                            switches.Add("-dNOSAFER");
                            switches.Add("-dPDFFitPage");
                            switches.Add("-dNumCopies=" + numCopias);
                            switches.Add("-sDEVICE=mswinpr2");
                            switches.Add("-sOutputFile=%printer%" + "\\\\" + printerIP + "\\" + printerNAME);
                            switches.Add("-f");
                            switches.Add(inputFile);

                            processor.StartProcessing(switches.ToArray(), null);
                        }
                    });

                    if (!task.Wait(TimeSpan.FromSeconds(Int32.Parse(ConfigurationManager.AppSettings["MAX_PRINTER_DELAY"]))))
                    {
                        Log.Info(String.Format("A impressão do arquivo ({0}) ({1}) foi encerrada porque ultrapassou MAX_PRINTER_DELAY = {2}!", inputFile, printerNAME, ConfigurationManager.AppSettings["MAX_PRINTER_DELAY"]));
                    }

                }
                catch (GhostscriptLibraryNotInstalledException e)
                {
                    Log.Info("O GhostScript não está instalado.");
                    Log.Error(e);
                }
                catch (GhostscriptException e)
                {
                    Log.Info("O GhostScript apresentou erro.");
                    Log.Error(e);
                }
                catch (Exception exception)
                {
                    Log.Error(exception);
                }

I am using Ghostscript.NET version 1.2.1.0.

Can someone help me?

@jhabjan @tilgovi @MrAntix

IO error when using reader

image

I'm using GhostScript 9.2.0 64bit with .NET 1.2.1
EDIT: tried GhostScript 9.2.6 - issue not fixed

I get 'IO error for file ... ' when using rasterizer.Open() ...

See image above - first line is string with path
Fourth line is message from exception... as you can see it has some weird characters.

I have tried using ToUtf8String from StringHelper but it didn't work

How to fix out about converting .eps to.png?

In my project ,when i wanna confer .eps to .png,there is an Exception about ImageMagick.MagickDelegateErrorException” ,and i don't how to use ghostscript to confer it?can you tell me how to fix it?
thank-you very much!

PDF signature is not within 32 bytes

I have a file generated in ReportLab that is not threated as a pdf.
The problem is that the signature is not within 32 bytes. In this case it it's 387 bytes but could be more.

The file starts with:
xxxxx xx line
xxxxxxxxxxxxxxxxxxxxxx 22 line
xxx xx Stockholm line
Organisationsnummer: xxxxxxxxxxx line
Momsregistreringsnummer: xxxxxxxxxxxxx line
Innehar F-skattebevis line
E-post: [email protected] line
line
line
%PDF-1.4

Ghostscript.Net fails to open a PDF file whose name includes strange whitespace character

Hello all,
I found a strange case. I was using a tool to split a large PDFs into individual sections by splitting the source PDF by the first level bookmark. Turns out the bookmark text had some whitespace characters in it that causes Ghostscript.Net to fail when trying to load the PDF.

Yes, I know technically this is not on you, but maybe you should consider cleaning up the strange whitespace characters as you are opening a PDF file.

The tool I was using split a PDF in sections by bookmarks created file names that looked like this: [FILENUMBER]-[BOOKMARK_NAME].

The runtime bookmark name extracted from the PDF contained a 0xA0 character in lieu of a 0x20 in a few places. I had a devil of a time trying to figure this out, every tool I used to examine the file name "correctly" showed the file name where the 0xA0 was as a single space. Only when I replaced the 0xA0 with a 0x20 did Ghostscript.Net successfully open the file.

Turns out 0xA0 is a non breaking white space (who knew there was such a thing in ASCII)
https://en.wikipedia.org/wiki/Non-breaking_space. So from a typesetting perspective having the section name flagged as being rendered as a unbroken line makes perfect sense. But allowing that nuance to cause Ghostscript.Net to fail to open the file might be worthy of look into.

Cheers...

Intermittent error concatenating .PDF's

I use the following method on a website to concatenate .PDF files. About one in fifty calls fails with an exception reading "An error occured when call to 'gsapi_new_instance' is made: -100". How can I determine more precisely what the issue is?

    private static string[] MergePDFBaseArgs = new string[] {
        "-dNOPAUSE",
        "-sDEVICE=pdfwrite",
        "-ohandle"
    };
    private const int MergePDFArgsOutputIndex = 2;

    public static Byte[] MergePDFs(params string[] PDFPaths)
    {
        // https://stackoverflow.com/questions/25240436/can-i-return-byte-with-ghostscriptprocessor
        GhostscriptPipedOutput gsPipedOutput = new GhostscriptPipedOutput();
        string outputPipeHandle = "%handle%" + int.Parse(gsPipedOutput.ClientHandle).ToString("X2");
        string[] args = new string[MergePDFBaseArgs.Length + PDFPaths.Length];
        MergePDFBaseArgs.CopyTo(args, 0);
        args[MergePDFArgsOutputIndex] = "-o" + outputPipeHandle;
        PDFPaths.CopyTo(args, MergePDFBaseArgs.Length);

        using (GhostscriptProcessor Processor = new GhostscriptProcessor())
        {
            Processor.StartProcessing(args, null);
            return gsPipedOutput.Data;
        }
    }

Convert pdf files to text

Is there any way that I can convert this pdf files to txt?
or
Can i write the
using (GhostscriptProcessor processor = new GhostscriptProcessor())
{

                List<string> switches = new List<string>();
                switches.Add("-empty");
                switches.Add("-dQUIET");
                switches.Add("-dSAFER");
                switches.Add("-dBATCH");
                switches.Add("-dNOPAUSE");
                switches.Add("-dNOPROMPT");
                switches.Add("-sDEVICE=pdfwrite");
                switches.Add("-o" + outputPipeHandle);
                switches.Add("-q");
                switches.Add("-f");
                switches.Add(inputFile);

                try
                {
                    processor.StartProcessing(switches.ToArray(), null);

                    byte[] rawDocumentData = gsPipedOutput.Data;

Can I write this by to txt file?

I tried many things like this

var random = new Random();
string tempFileName = random.Next(1,122121212).ToString();
File.WriteAllBytes(@"C:\PrinterPlusPlus\Temp" + tempFileName + ".pdf", rawDocumentData);
// File.WriteAllBytes(@"C:\PrinterPlusPlus\Temp" + tempFileName + ".txt", rawDocumentData.ToArray());
File.WriteAllText(@"C:\PrinterPlusPlus\Temp" + tempFileName + ".txt", result);

                    processor.StartProcessing(CreateTestArgs(@"C:\\PrinterPlusPlus\\Temp\\" + tempFileName + ".pdf", @"C:\\PrinterPlusPlus\\Temp\\" + random.Next(1, 122121212).ToString() + ".pdf"),null);

none of them are working. can you please guide me?

viewer.Dpi not available in nuget 1.2.0 version

Hi,

I've just discovered this great package and installed version 1.2.0 from Nuget. I see that the .Dpi property of the viewer object isn't available in Visual Studio (property does not exist). However, this property is available in the source code.
I've solved the problem in replacing the Ghostscript.NET.dll nuget version by the version downloaded here but it's just a workaround.

yvan

Visual Studio 2013 express / .NET 4.5 / Ghostscript 64bits 9.6 / VB.NET

DLL search in registry key not found in latest version

Hi

I have just installed the latest version (free) of GhostScript.
GhostScript.NET was unable to find it in registry as it was installed in the following location on my computer:
HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\GPL Ghostscript\9.19
I have a Windows 10, 64bit

Thanks
Shahar

PDF X portfolio fails to rasterize (kinda)

When attempting to rasterize a PDF X portfolio, only the "For the best experience, open this PDF portfolio in Acrobat X or Adobe Reader X, or later." page is rendered.

halp

pdf files with mixed portrait and landscape pages

I have a pdf file which contains both landscape and portrait images, the landscape images are returned as blank image (portrait pages are fine).

GhostscriptViewerViewEventArgs e in _view_DisplayOage event, the size of e.image looks ok, but it is an empty image.

did anybody have same issue?

thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.