I have 10 System.Drawing.Image
. I need to add them to a FixedDocument
. I tried the below code and the fixed document is procuded with all the 10 pages consists of only first image.
FixedDocument doc = new FixedDocument();
BitmapSource[] bmaps = new BitmapSource[10];
System.Drawing.Image[] drawingimages = //I have System.Drawing.Image in a array
for (int i = 0; i < 10; i++)
{
Page currentPage = this.Pages[i];
System.Drawing.Image im = drawingimages[i];
im.Save(i + ".png");
Stream ms = new MemoryStream();
im.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
var decoder = BitmapDecoder.Create(ms, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnDemand);
ImageSource imgsource = decoder.Frames[0];
bmaps[i] = imgsource as BitmapSource;
}
foreach (BitmapSource b in bmaps)
{
PageContent page = new PageContent();
FixedPage fixedPage = CreateOneFixedPage(b);
((IAddChild)page).AddChild(fixedPage);
doc.Pages.Add(page);
}
Method for CreateOneFixedPage
private FixedPage CreateOneFixedPage(BitmapSource img)
{
FixedPage f = new FixedPage();
Image anImage = new Image();
anImage.BeginInit();
anImage.Source = img;
anImage.EndInit();
f.Children.Add(anImage);
return f;
}
When I try saving the System.Drawing.Image
to the local disk, all the 10 images are saved correctly.
What is the mistake in my code here?
Maybe not an answer to the question, but at least the code below shows a minimal working example. It loads all images from the Sample Pictures folder into a list of System.Drawing.Bitmap
objects. Then it converts all list elements to ImageSource
and adds each to a FixedDocment page.
Please not that it does not call BeginInit()
and EndInit()
on the Image controls. Also it sets the PageContent's Child
property, instead of calling IAddChild.AddChild()
.
var bitmaps = new List<System.Drawing.Bitmap>();
foreach (var file in Directory.EnumerateFiles(
@"C:\Users\Public\Pictures\Sample Pictures", "*.jpg"))
{
bitmaps.Add(new System.Drawing.Bitmap(file));
}
foreach (var bitmap in bitmaps)
{
ImageSource imageSource;
using (var stream = new MemoryStream())
{
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Position = 0;
imageSource = BitmapFrame.Create(stream,
BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
}
var page = new FixedPage();
page.Children.Add(new Image { Source = imageSource });
doc.Pages.Add(new PageContent { Child = page });
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With