using it.stefanochizzolini.clown.bytes;
using it.stefanochizzolini.clown.documents;
using filesit.stefanochizzolini.clown.files;
using it.stefanochizzolini.clown.objects;
using System;
using System.IO;
namespace it.stefanochizzolini.clown.samples{
/**
<summary>This sample demonstrates how to extract XObject images from a PDF file.</summary>
<remarks>
<para>Inline images are ignored.</para>
<para>XObject images other than JPEG aren't currently supported for handling.</para>
</remarks>
*/
public class ImageExtractionSample
: ISample
{
#region dynamic
#region interface
#region public
#region ISample
public void Run(
SampleLoader loader
)
{
// (boilerplate user choice -- ignore it)
string filePath = loader.GetPdfFileChoice("Please select a PDF file");
// 1. Open the PDF file!
files::File file = new files::File(filePath);
// 2.1. Iterating through the indirect object collection...
int index = 0;
foreach(PdfIndirectObject indirectObject in file.IndirectObjects)
{
// Get the data object associated to the indirect object!
PdfDataObject dataObject = indirectObject.DataObject;
// Is this data object a stream?
if(dataObject is PdfStream)
{
PdfDictionary header = ((PdfStream)dataObject).Header;
// Is this stream an image?
if(header.ContainsKey(PdfName.Type)
&& header[PdfName.Type].Equals(PdfName.XObject)
&& header[PdfName.Subtype].Equals(PdfName.Image))
{
// 2.1.1. Is this image a pass-through JPEG image?
if(header[PdfName.Filter].Equals(PdfName.DCTDecode)) // JPEG image.
{
// Get the image data (keeping it encoded)!
IBuffer body = ((PdfStream)dataObject).GetBody(false);
// Export the image!
ExportImage(
body,
loader.OutputPath + Path.DirectorySeparatorChar + "ImageExtractionSample_" + (index++) + ".jpg"
);
}
else // Unsupported image.
{
Console.WriteLine("Image XObject " + indirectObject.Reference + " couldn't be extracted (filter: " + header[PdfName.Filter] + ")");
}
}
}
}
}
#endregion
#endregion
#region private
private void ExportImage(
IBuffer data,
string outputPath
)
{
FileStream outputStream;
try
{outputStream = new FileStream(outputPath, FileMode.CreateNew);}
catch(Exception e)
{throw new Exception(outputPath + " file couldn't be created.",e);}
try
{
BinaryWriter writer = new BinaryWriter(outputStream);
writer.Write(data.ToByteArray());
writer.Close();
outputStream.Close();
}
catch(Exception e)
{throw new Exception(outputPath + " file writing has failed.",e);}
Console.WriteLine("Output: " + outputPath);
}
#endregion
#endregion
#endregion
}
}
|