convert Pdf to png create Black margin around image

874 Views Asked by At

I'm trying to convert pdf to image with ghostscript.net (1.2.1.0) and gs version is 9.22 x86.

my code:

using (_rasterizer = new GhostscriptRasterizer())
{
    _rasterizer.Open(inputPdfPath, _lastInstalledVersion, false);

    //_rasterizer.CustomSwitches.Add("-sDEVICE=pngalpha");
    //_rasterizer.CustomSwitches.Add("-dTextAlphaBits=4");
    //_rasterizer.CustomSwitches.Add("-dGraphicsAlphaBits=4");

    for (int pageNumber = 1; pageNumber <= _rasterizer.PageCount; pageNumber++)
    {
        var desiredDPI = 102;
        using (System.Drawing.Image img = _rasterizer.GetPage(desiredDPI, desiredDPI, pageNumber))
        {
            img.Save(pageNumber + ".png", ImageFormat.Png);
        }
    }
}

it works for some pages, but for some images, it create black margin and black background.

sample files: pdf => png

I test with gs command, it was ok. I tried following code. images was good but text was low quality.

public Image getImg(string inputFile, int pageNO, int resolution)
{
    GhostscriptPngDevice dev = new GhostscriptPngDevice(GhostscriptPngDeviceType.PngAlpha);
    dev.GraphicsAlphaBits = GhostscriptImageDeviceAlphaBits.V_4;
    dev.TextAlphaBits = GhostscriptImageDeviceAlphaBits.V_4;
    dev.ResolutionXY = new GhostscriptImageDeviceResolution(resolution, resolution);
    dev.InputFiles.Add(inputFile);
    dev.Pdf.FirstPage = pageNO;
    dev.Pdf.LastPage = pageNO;
    dev.CustomSwitches.Add("-dDOINTERPOLATE");
    dev.OutputPath = pageNO + ".png";
    dev.Process();

    return Image.FromFile(pageNO + ".png");
}
1

There are 1 best solutions below

0
On
 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.InputFiles.Add(inputPathAndFile);
        dev.Pdf.FirstPage = 1;
        dev.Pdf.LastPage = 1;
        dev.CustomSwitches.Add("-dDOINTERPOLATE");
        dev.OutputPath = outputPathAndFile;
        dev.Process();