Friday, 21 February 2014

How to create or extract images from slides of PDF using Aspose.pdf ,C# ,DotNet

Creating images from slides of PDF:

#region "Description"
/*
    * PDF slides can be exported into images using CreateImagesFromPDF() method given below
    * Need to use Aspose.Pdf library reference
 */
#endregion

#region "Methods"


Method Name: CreateImagesFromPDF()
/// <summary>
/// Given Function takes input as pdf document stream, image saving folder path and returns created images path list
/// </summary>
/// <param name="SourceFileStream">PDF document file stream</param>
/// <param name="SavingPath">Image saving path</param>
/// <returns>List of paths for created images in order</returns>


public Dictionary<int, string> CreateImagesFromPDF(Stream SourceFileStream, string SavingPath)
{
    string docPath = SavingPath + "\\";
    string documentPath = "";
    Dictionary<int, string> pageImages = new Dictionary<int, string>();
    SourceFileStream.Position = 0;
    Aspose.Pdf.Document docPDF = new Aspose.Pdf.Document(SourceFileStream);
    string filename = docPDF.FileName;
    using (MemoryStream htmlStream = new MemoryStream())
    {
        for (int pageCount = 1; pageCount <= docPDF.Pages.Count; pageCount++)
        {
            documentPath = docPath + filename + "_image" + (pageCount - 1).ToString() + ".jpg";
            using (FileStream imageStream = new FileStream(documentPath, FileMode.Create))
            {
                //create JPEG device with specified attributes
                //Width, Height, Resolution, Quality
                //Quality [0-100], 100 is Maximum
                //create Resolution object
                Aspose.Pdf.Devices.Resolution resolution = new Aspose.Pdf.Devices.Resolution(100);
                //JpegDevice jpegDevice = new JpegDevice(500, 700, resolution, 100);
                Aspose.Pdf.Devices.JpegDevice jpegDevice = new Aspose.Pdf.Devices.JpegDevice(resolution, 100);
                //convert a particular page and save the image to stream
                jpegDevice.Process(docPDF.Pages[pageCount], imageStream);
                //close stream
                imageStream.Close();                       
                if (!pageImages.ContainsKey(pageCount - 1))
                    pageImages.Add(pageCount - 1, string.Empty);
                pageImages[pageCount - 1] = documentPath;
            }
        }
    }
    return pageImages;
}
#endregion


No comments:

Post a Comment