//
// This code is part of Document Solutions for PDF demos.
// Copyright (c) MESCIUS inc. All rights reserved.
//
using System;
using System.IO;
using System.Linq;
using System.Drawing;
using System.Collections.Generic;
using GrapeCity.Documents.Pdf;
using GrapeCity.Documents.Svg;
using GrapeCity.Documents.Text;
using GrapeCity.Documents.Drawing;
namespace DsPdfWeb.Demos.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. Finally, the last page of the loaded PDF
// is saved as SVGZ (compressed SVG).
// 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. " +
"Finally, the last page is saved as SVGZ (compressed SVG). " +
"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 = File.OpenRead(Path.Combine("Resources", "PDFs", "SlidePages.pdf"));
var docSrc = new GcPdfDocument();
docSrc.Load(fs);
// Save all pages of the loaded PDF as a multi-page TIFF:
var tf = Path.GetTempFileName();
docSrc.SaveAsTiff(tf);
var fspec = FileSpecification.FromEmbeddedFile(EmbeddedFileStream.FromFile(doc, tf));
fspec.File.FileName = "SlidePages.tiff";
doc.EmbeddedFiles.Add(fspec.File.FileName, fspec);
tfiles.Add(tf);
// Save each page of the loaded PDF as a JPEG:
foreach (var p in docSrc.Pages)
{
tf = Path.GetTempFileName();
p.SaveAsJpeg(tf);
fspec = FileSpecification.FromEmbeddedFile(EmbeddedFileStream.FromFile(doc, tf));
fspec.File.FileName = $"Page_{p.Index}.jpeg";
doc.EmbeddedFiles.Add(fspec.File.FileName, fspec);
tfiles.Add(tf);
}
// Finally, save the last page of the PDF as SVGZ (compressed SVG):
var bytes = docSrc.Pages.Last.ToSvgz(new SaveAsImageOptions() { BackColor = Color.Transparent });
fspec = FileSpecification.FromEmbeddedFile(EmbeddedFileStream.FromBytes(doc, bytes));
fspec.File.FileName = $"Page_{docSrc.Pages.Last.Index}.svgz";
doc.EmbeddedFiles.Add(fspec.File.FileName, fspec);
doc.Save(stream);
// Clean up:
tfiles.ForEach(tf_ => File.Delete(tf_));
// Done:
return doc.Pages.Count;
}
}
}