Search code examples
abcpdf

Converting PDF to Grayscale pdf using ABC PDF


I am trying convert PDF to grayscale(Black/White) PDF using Websupergoo ABCpdf.
I am referring

http://www.websupergoo.com/helppdfnet/source/8-abcpdf.operations/3-recoloroperation/1-methods/recolor.htm?q=recoloroperation

        Doc theDoc = new Doc();
        theDoc.Read(Server.MapPath("src.pdf"));
        int pages = theDoc.PageCount;
       MyOp.Recolor(theDoc, (WebSupergoo.ABCpdf8.Objects.Page)theDoc.ObjectSoup[theDoc.Page]); //Here problem
      theDoc.Save(Server.MapPath("greyscale1.pdf"));
        theDoc.Clear();

Above code works fine for single page PDf.

This Code Converts only first page of PDF

When I tried to use a loop the below error is occurring

Code With error


Solution

  • Page Number is not the same as Page in abcPDF, so you cannot use the page number as an index into the object soup.

    Try something like this instead (untested):

    int pages = theDoc.PageCount;
    for(int i=0; i < pages; i++)
    {
        theDoc.PageNumber = i;
        MyOp.Recolor(theDoc, (WebSupergoo.ABCpdf8.Objects.Page)theDoc.ObjectSoup[theDoc.Page]);
    }
    

    Edit: The above apparently didn't work, but as the documentation you linked to shows, there's a method that takes a Doc object instead of a Page object. This should work if you change your MyOp.Recolor() method to this:

    public class MyOp
    {
      public static void Recolor(Doc doc) {
        RecolorOperation op = new RecolorOperation();
        op.DestinationColorSpace = new ColorSpace(doc.ObjectSoup, ColorSpaceType.DeviceGray);
        op.ConvertAnnotations = false;
        op.ProcessingObject += Recoloring;
        op.ProcessedObject += Recolored;
        op.Recolor(doc);
      }
    }
    

    I am not sure what you are doing (or need to do) in the Recoloring() method or Recolored() method, but that should not matter for the changes here.