static void ProcessElements(ElementReader reader, ElementWriter writer, ElementBuilder builder, XSet visited, string layerName, bool changeColor)
{
Element element;
while ((element = reader.Next()) != null) // Read page contents
{
switch (element.GetType())
{
case Element.Type.e_path:
{
if(changeColor)
{
var gs = element.GetGState();
gs.SetFillColorSpace(ColorSpace.CreateDeviceRGB());
gs.SetFillColor(new ColorPt(1, 0, 0));
gs.SetStrokeColorSpace(ColorSpace.CreateDeviceRGB());
gs.SetStrokeColor(new ColorPt(1, 0, 0));
}
writer.WriteElement(element);
break;
}
case Element.Type.e_form:
{
writer.WriteElement(element); // write Form XObject reference to current stream
Obj form_obj = element.GetXObject();
if (!visited.Contains(form_obj.GetObjNum())) // if this XObject has not been processed
{
bool changeColorVal = false;
var ocObj = form_obj.FindObj("OC");
if (ocObj != null)
{
changeColorVal = ocObj.FindObj("Name").GetAsPDFText().CompareTo(layerName) == 0;
}
// recursively process the Form XObject
visited.Add(form_obj.GetObjNum());
ElementWriter new_writer = new ElementWriter();
reader.FormBegin();
new_writer.Begin(form_obj, true);
ProcessElements(reader, new_writer, builder, visited, layerName, changeColorVal);
new_writer.End();
reader.End();
}
break;
}
default:
writer.WriteElement(element);
break;
}
}
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
PDFNet.Initialize();
// Relative path to the folder containing test files.
string input_path = "../../../../TestFiles/";
string output_path = "../../../../TestFiles/Output/";
string input_filename = "newsletter.pdf";
string output_filename = "newsletter_edited.pdf";
try
{
Console.WriteLine("Opening the input file...");
using (PDFDoc doc = new PDFDoc(output_path + "pdf_layers.pdf"))
{
doc.InitSecurityHandler();
ElementWriter writer = new ElementWriter();
ElementReader reader = new ElementReader();
ElementBuilder builder = new ElementBuilder();
XSet visited = new XSet();
PageIterator itr = doc.GetPageIterator();
while (itr.HasNext())
{
Page page = itr.Current();
visited.Add(page.GetSDFObj().GetObjNum());
reader.Begin(page);
writer.Begin(page, ElementWriter.WriteMode.e_replacement, false);
ProcessElements(reader, writer, builder, visited, "Vector Layer", false);
writer.End();
reader.End();
itr.Next();
}
doc.Save(output_path + output_filename, SDFDoc.SaveOptions.e_remove_unused);
Console.WriteLine("Done. Result saved in {0}...", output_filename);
}
}
catch (PDFNetException e)
{
Console.WriteLine(e.Message);
}
}