GhostScript PDF to Image Conversion Results in Black Text On Black Background [SOLVED]

Posted on Monday, October 15, 2018 at 3:40 PM into code & gotcha by Steve Woods.
Roughly a 2 minute read.

I'm currently working on a massive project for one of my clients and part of the functionality dictates that we have to convert engineering drawings in PDF format, into JPG / PNG format for interaction on the screen.

For this I'm using a library called GhostScript which allows you to interact with PDFs via .NET.

However, in some cases the PDFs supplied by my clients customers is not "flat" - it comes in layers when exported from AutoCad or some other tool.

When importing into the application, there was sometimes a bug where by any text layers would be rasterised into the JPG as black text, but their placeholder would also be black - resulting in a black box where the text should be.

What didn't work

This C# code does not work - it outputs the JPG / PNG, but the black boxes remain.

            _lastInstalledVersion =
                        GhostscriptLicense.GPL | GhostscriptLicense.AFPL,
            _rasterizer = new GhostscriptRasterizer();

            _rasterizer.Open(inputPathAndFile, _lastInstalledVersion, true);

            if (_rasterizer.PageCount > 0)
                    Image img = _rasterizer.GetPage(desired_x_dpi, desired_y_dpi, 1);
                    img.Save(outputPathAndFile, ImageFormat.Png);

                    result = outputPathAndFile;

What DOES work

Here is the working C# code - you'll note that I am now using a GhostscriptPngDevice instead of the GhostscriptRasterizer - pay special attention to the first line where the PNG DeviceType is specified - I have set it to allow transparency, but have also specified that a background colour must be white.

GhostscriptPngDevice dev = new GhostscriptPngDevice(GhostscriptPngDeviceType.Png16m);
        dev.GraphicsAlphaBits = GhostscriptImageDeviceAlphaBits.V_4;
        dev.TextAlphaBits = GhostscriptImageDeviceAlphaBits.V_4;
        dev.BackgroundColor = Color.White;
        dev.ResolutionXY = new GhostscriptImageDeviceResolution(desired_x_dpi, desired_y_dpi);
        dev.Pdf.FirstPage = 1;
        dev.Pdf.LastPage = 1;
        dev.OutputPath = outputPathAndFile;


Please consider what you post!
Chillax if you're angry.