SaveAsImage.cs
//
// This code is part of GrapeCity Documents for PDF samples.
// Copyright (c) GrapeCity, Inc. All rights reserved.
//
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using GrapeCity.Documents.Pdf;
using GrapeCity.Documents.Text;
using GrapeCity.Documents.Drawing;

namespace GcPdfWeb.Samples.Basics
{
    // This sample shows how to save pages of an existing PDF as images.
    // It loads a PDF generated by the SlidePages sample, then saves
    // the whole PDF as a multi-page TIFF. It also saves each of the pages
    // as a separate JPEG image.
    // All generated images are attached to the resulting PDF.
    // 
    // Other image formats that are also supported: PNG, BMP, GIF.
    public class SaveAsImage
    {
        public int CreatePDF(Stream stream)
        {
            var doc = new GcPdfDocument();
            var page = doc.NewPage();

            Common.Util.AddNote(
                "We load the PDF generated by the 'Slide Pages' sample, " +
                "and save the whole PDF as a multi-page TIFF. " +
                "We also save each of the pages as a separate JPEG image. " +
                "All created images are then attached to this document.",
                page);

            // Keep track of temp files, delete them on exit:
            var tfiles = new List<string>();

            using (var fs = new FileStream(Path.Combine("Resources", "PDFs", "SlidePages.pdf"), FileMode.Open, FileAccess.Read))
            {
                var origDoc = new GcPdfDocument();
                origDoc.Load(fs);
                // Save all pages of the loaded PDF as a multi-page TIFF:
                var tf = Path.GetTempFileName();
                origDoc.SaveAsTiff(tf);
                var fspec = FileSpecification.FromEmbeddedFile(EmbeddedFileStream.FromFile(doc, tf));
                fspec.File.FileName = "SlidePages.tiff";
                doc.EmbeddedFiles.Add(tf, fspec);
                tfiles.Add(tf);

                // Save each page of the loaded PDF as a JPEG:
                foreach (var p in origDoc.Pages)
                {
                    tf = Path.GetTempFileName();
                    p.SaveAsJpeg(tf);
                    fspec = FileSpecification.FromEmbeddedFile(EmbeddedFileStream.FromFile(doc, tf));
                    fspec.File.FileName = $"Page_{p.Index}.jpeg";
                    doc.EmbeddedFiles.Add(tf, fspec);
                    tfiles.Add(tf);
                }
            }
            doc.Save(stream);
            // Clean up:
            tfiles.ForEach(tf_ => File.Delete(tf_));
            // Done:
            return doc.Pages.Count;
        }
    }
}