I'm using iTextSharp. I'm working on a PDF which has what I call many "layers".
So when I open my PDF, I can make my "layers" visible or invisible by clicking on the little eye on the left of the layer's name.
I know how to activate/deactivate layer, with this code:
FileStream outStream = null;
PdfReader pdfReader = null;
PdfStamper stamper = null;
Exception exceptionOccured = null;
try
{
outStream = new FileStream(destFile, FileMode.Create);
pdfReader = new PdfReader(sourceFile);
stamper = new PdfStamper(pdfReader, outStream);
Dictionary<String, PdfLayer> layers = null;
try
{
layers = stamper.GetPdfLayers();
}
catch (Exception)
{
}
if (layers != null)
{
layersToRemove = addSpecialLayerChars(layersToRemove);
foreach (KeyValuePair<String, PdfLayer> layer in layers)
{
//Encodage UTF-16 BE 'þÿ' retirer les \0
String layerName = layer.Key;
String layerNameComp = layerName.Replace("\0", "");
layerNameComp = layerNameComp.Replace("þÿ", "");
Boolean remove = false;
//Si(!layerName.equals("textes")) Alors remove = true; // On efface toute les couches qui ne contiennent pas de texte
foreach (String layerToRemove in layersToRemove)
{
if (layerNameComp.ToLowerInvariant() == layerToRemove.ToLowerInvariant())
{
remove = true;
}
else if (layerToRemove[layerToRemove.Length - 1] == '*')
{
if (layerNameComp.ToLowerInvariant().StartsWith(layerToRemove.Substring(0, layerToRemove.Length - 1).ToLowerInvariant()))
{
remove = true;
}
}
}
if (remove)
{
if (writeToConsole)
Console.WriteLine("Removing layer: " + layerName);
try
{
layers[layerName].On = false;
}
catch (Exception ex)
{
if (writeToConsole)
Console.WriteLine("Exception: " + ex.Message);
}
}
}
}
}
catch (Exception ex)
{
exceptionOccured = ex;
}
finally
{
try
{
if (stamper != null)
stamper.Close();
if (pdfReader != null)
pdfReader.Close();
if (outStream != null)
outStream.Close();
if (exceptionOccured != null)
throw exceptionOccured;
}
catch (Exception ex)
{
if (exceptionOccured != null)
throw exceptionOccured;
}
}
But when I want to convert my PDF (with the deactivated layers) into a PNG, my new image contains all the layers, even those I deactivated.
That's why I would like to totally remove layers.