ArtifexSoftware / Ghostscript.NET

Ghostscript.NET - managed wrapper around the Ghostscript library (32-bit & 64-bit)
https://ghostscript.com
GNU Affero General Public License v3.0
391 stars 152 forks source link

GhostScript.NET gives image which corresponds to some other page in pdf when it's used in TPL. #79

Closed NvVijayakumara closed 3 years ago

NvVijayakumara commented 4 years ago

Hi, when I use GhostScript.NET inside Task Parallel Library (TPL) as in below example, not getting desired output. Every time when I run the app, instead of giving me correct image for corresponding page, it gives me some other page image. But when i use same code inside for or foreach loop, it works fine.

I need suggestions to get valid images for corresponding pages..

var pageCount = 0; string inputFile = @"D:\vijay\input\test.pdf"; string outputFolder = @"D:\vijay\output\";

var xDpi = 300; //set the x DPI var yDpi = 300; //set the y DPI string binPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string gsDllPath = Path.Combine(binPath, Environment.Is64BitProcess ? "gsdll64.dll" : "gsdll32.dll");

using (var rasterizer = new GhostscriptRasterizer()) //create an instance for GhostscriptRasterizer { rasterizer.Open(inputFile, new GhostscriptVersionInfo(gsDllPath), true); //opens the PDF file for rasterizing pageCount = rasterizer.PageCount;

Parallel.For(1, pageCount + 1, /*new ParallelOptions { MaxDegreeOfParallelism = 16 },*/ pageNumber =>
//for(int pageNumber=1; pageNumber <= pageCount; pageNumber++)
{
    var outputPNGPath = Path.Combine(outputFolder, string.Format("{0}.png", pageNumber));

    //converts the PDF pages to png's 
    var pdf2PNG = rasterizer.GetPage(xDpi, yDpi, pageNumber);

    //save the png's
    pdf2PNG.Save(outputPNGPath, ImageFormat.Png);

    Console.WriteLine("Saved " + outputPNGPath);
}//);

}

jhabjan commented 3 years ago

You should not use Parallel to process different PDF pages for single PDF file. For instance, to get the last page from PDF, Ghostscript needs to read all pages before that page to get correct drawing state for the last page...