Here we recolor one page out of a document. We pick up the
ProcessingObject
events so that we can store the source color space for all the
PixMap objects which are processed. We do not want to convert CMYK
pixmaps so we set the Cancel property to true if we find these.
We then pick up the ProcessedObject
events so that we can recompress the PixMap objects after they have
been recolored. We vary the recompression method used dependent on
the source color space and the size of the image.
Here we use standard delegates for backwards compatibility with
older code. However anonymous delegates will provide a more compact
solution.
using (Doc doc = new Doc()) {
doc.Read(Server.MapPath("../mypics/sample.pdf"));
MyOp.Recolor(doc, (Page)doc.ObjectSoup[doc.Page]);
doc.Save(Server.MapPath("RecolorOperation.pdf"));
}
Using doc As New Doc()
doc.Read(Server.MapPath("../mypics/sample.pdf"))
MyOp.Recolor(doc, DirectCast(doc.ObjectSoup(doc.Page), Page))
doc.Save(Server.MapPath("RecolorOperation.pdf"))
End Using
class MyOp {
public static void Recolor(Doc doc, Page page) {
RecolorOperation op = new RecolorOperation();
op.DestinationColorSpace = new ColorSpace(doc.ObjectSoup, ColorSpaceType.DeviceGray);
op.ConvertAnnotations = false;
op.ProcessingObject += Recoloring;
op.ProcessedObject += Recolored;
op.Recolor(page);
}
public static void Recoloring(object sender, ProcessingObjectEventArgs e) {
PixMap pm = e.Object as PixMap;
if (pm != null) {
ColorSpaceType cs = pm.ColorSpaceType;
if (cs == ColorSpaceType.DeviceCMYK)
e.Cancel = true;
e.Tag = cs;
}
}
public static void Recolored(object sender, ProcessedObjectEventArgs e) {
if (e.Successful) {
PixMap pm = e.Object as PixMap;
if (pm != null) {
ColorSpaceType cs = (ColorSpaceType)e.Tag;
if (pm.Width > 1000)
pm.CompressJpx(30);
else if (cs == ColorSpaceType.DeviceRGB)
pm.CompressJpeg(30);
else
pm.Compress(); // Flate
}
}
}
}
Private Class MyOp
Public Shared Sub Recolor(doc As Doc, page As Page)
Dim op As New RecolorOperation()
op.DestinationColorSpace = New ColorSpace(doc.ObjectSoup, ColorSpaceType.DeviceGray)
op.ConvertAnnotations = False
op.ProcessingObject += Recoloring
op.ProcessedObject += Recolored
op.Recolor(page)
End Sub
Public Shared Sub Recoloring(sender As Object, e As ProcessingObjectEventArgs)
Dim pm As PixMap = TryCast(e.[Object], PixMap)
If pm <> Nothing Then
Dim cs As ColorSpaceType = pm.ColorSpaceType
If cs = ColorSpaceType.DeviceCMYK Then
e.Cancel = True
End If
e.Tag = cs
End If
End Sub
Public Shared Sub Recolored(sender As Object, e As ProcessedObjectEventArgs)
If e.Successful Then
Dim pm As PixMap = TryCast(e.[Object], PixMap)
If pm <> Nothing Then
Dim cs As ColorSpaceType = DirectCast(e.Tag, ColorSpaceType)
If pm.Width > 1000 Then
pm.CompressJpx(30)
ElseIf cs = ColorSpaceType.DeviceRGB Then
pm.CompressJpeg(30)
Else
pm.Compress()
' Flate
End If
End If
End If
End Sub
End Class
|