I got it. I used a MemoryStream to disconnect the Image from the XImage/XGraphics work. This allowed me to move through the original multi-page image using SelectActiveFrame without any problems or reloading the image for each page. I based this on some earlier work I did with iTextSharp.
Here is my new method:
Code:
private string ConvertTifToBase64ViaPdf3(string docUrl)
{
var filePath = Server.MapPath(docUrl);
using (var myImage = Image.FromFile(filePath))
{
var doc = new PdfDocument();
var totalPages = myImage.GetFrameCount(FrameDimension.Page);
for (var pageIndex = 0; pageIndex < totalPages; ++pageIndex)
{
myImage.SelectActiveFrame(FrameDimension.Page, pageIndex);
XImage img;
using (var mem = new MemoryStream())
{
myImage.Save(mem, ImageFormat.Png);
img = XImage.FromStream(mem);
}
var page = new PdfPage
{
Orientation = img.PixelWidth > img.PixelHeight ?
PageOrientation.Landscape : PageOrientation.Portrait,
/*
* Set width/height to scale page to image.
*/
Width = XUnit.FromInch(img.PixelWidth / img.HorizontalResolution),
Height = XUnit.FromInch(img.PixelHeight / img.VerticalResolution)
};
doc.Pages.Add(page);
var xgr = XGraphics.FromPdfPage(doc.Pages[pageIndex], XGraphicsPdfPageOptions.Replace);
xgr.DrawImage(img, 0, 0);
}
var memStream = new MemoryStream();
doc.Save(memStream);
memStream.Seek(0, SeekOrigin.Begin);
var fileBytes = memStream.ToArray();
doc.Close();
return Convert.ToBase64String(fileBytes);
}
}
I need to return a Base64 encoded string in this particular application, but this would work without doing the final bits to accomplish that.