将Pdf转换为png会在图像周围创建黑色边距

时间:2017-12-07 22:59:35

标签: c# png ghostscript.net

我正在尝试使用ghostscript.net(1.2.1.0)将pdf转换为图像,并且gs版本为9.22 x86。

我的代码:

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);
        }
    }
}

适用于某些页面,但对于某些图像,它会创建黑色边距和黑色背景。

示例文件: pdf =&gt; png

我用gs命令测试,没关系。 我试过以下代码。图像很好,但文字质量很差。

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 个答案:

答案 0 :(得分:1)

 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();