Adding Image to FixedPage in WPF

烈酒焚心 提交于 2019-12-02 07:04:46

问题


I want to be able to print images with other UIElements. I have a FixedPage instance and trying to add image like so

// Basic printing stuff
var printDialog = new PrintDialog();
var fixedDocument = new FixedDocument();
fixedDocument.DocumentPaginator.PageSize = new Size(printDialog.PrintableAreaWidth, printDialog.PrintableAreaHeight);

FixedPage page = new FixedPage();
page.Width = fixedDocument.DocumentPaginator.PageSize.Width;
page.Height = fixedDocument.DocumentPaginator.PageSize.Height;

Image img = new Image();

// PrintIt my project's name, Img folder
var uriImageSource = new Uri(@"/PrintIt;component/Img/Stuff.png", UriKind.RelativeOrAbsolute);
img.Source = new BitmapImage(uriImageSource);
img.Width = 100;
img.Height = 100;

page.Children.Add(img);

PageContent pageContent = new PageContent();
((IAddChild)pageContent).AddChild(page);

fixedDocument.Pages.Add(pageContent);

// Print me an image please!
_printDialog.PrintDocument(fixedDocument.DocumentPaginator, "Print");

It gives me a blank paper. I'm wondering why, because other UIElements (such as TextBox, Grid, Rect) appear with no problems. What am I missing?

Thanks!

PS OK, I've found another solution. I don't know why but with that Uri a picture loads properly

var uri = new Uri("pack://application:,,,/Img/Stuff.png");

回答1:


To be more clear on my Code

var bitImage = new BitmapImage();
bitImage.BeginInit();
bitImage.StreamSource = new FileStream(fileName, FileMode.Open, FileAccess.Read);
bitImage.DecodePixelWidth = 250;
bitImage.CacheOption = BitmapCacheOption.OnLoad;
bitImage.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
bitImage.EndInit();
bitImage.StreamSource.Seek(0, System.IO.SeekOrigin.Begin);
bitImage.Freeze();

var tempImage = new Image {Source = bitImage};
var imageObject = new ImageObject(tempImage, fileName);
bitImage.StreamSource.Dispose();
page.Children.Add(imageObject);



回答2:


First i would like to suggest that, see below.

Set the sourceStream of the Image for BitMap
    bitImage.StreamSource = new FileStream(fileName, FileMode.Open, FileAccess.Read);

Then freeze the BitMap Image, or it ll not be in the instance as render able image.

bitImage.StreamSource.Seek(0, System.IO.SeekOrigin.Begin);
bitImage.Freeze();

This should work, if not i personally think it is a bad idea to directly work with BitMaps, i use Bitmap to create image form file then copy it to the type Image(system.drawing iguess), something like below

var tempImage = new Image {Source = bitImage};
var imageObject = new ImageObject(tempImage, fileName);
bitImage.StreamSource.Dispose();

this tempImage can be added to ur page as regular UIElement. Hope it helps.



来源:https://stackoverflow.com/questions/11853096/adding-image-to-fixedpage-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!