My task is to show the user a thumbnail of each page of his XPS document. I need all the images to be small, so I render them with dpi set to 72.0 (I have googled that size of an A4 sheet with dpi 72.0 is 635x896). Basically, I do the following:
List<BitmapImage> thumbnails = new List<BitmapImage>();
documentPaginator.ComputePageCount();
int pageCount = documentPaginator.PageCount;
for (int i = 0; i < pageCount; i++)
{
DocumentPage documentPage = documentPaginator.GetPage(i);
bool isLandscape = documentPage.Size.Width > documentPage.Size.Height;
Visual pageVisual = documentPage.Visual;
//I want all the documents to be less or equals to A4
//private const double A4_SHEET_WIDTH = 635;
//private const double A4_SHEET_HEIGHT = 896;
//A4 sheet size in px, considering 72 dpi
RenderTargetBitmap targetBitmap = new RenderTargetBitmap(
(int)(System.Math.Min(documentPage.Size.Width, A4_SHEET_WIDTH)),
(int)(System.Math.Min(documentPage.Size.Height, A4_SHEET_HEIGHT)),
72.0, 72.0,
PixelFormats.Pbgra32);
targetBitmap.Render(pageVisual);
BitmapFrame frame = BitmapFrame.Create(targetBitmap);
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(frame);
BitmapImage image = new BitmapImage();
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
encoder.Save(ms);
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = ms;
if (isLandscape)
{
image.Rotation = Rotation.Rotate270;
}
image.EndInit();
}
thumbnails.Add(image);
}
But when I render a document page (A4) its size is actually 846x1194 instead of the one I expected. I tried to make the dpi lower (48.0) and the image's size has grown even bigger (I guess, I just do not quite undrestand what dpi is and how it affects the document). I tried to make dpi=96.0, and the size went smaller. I set one of images from the collection of instances of the class BitmapImage
generated by the code above as source for the Image
control (I am creating a WPF application) and in case dpi is set to 96.0 my program looks like this:
As you can see, part of the page is not shown at all, it does not fit inside the Image
control, even though the size of the control is set to 635x896 that's why according to the code above, the image must be displayed correctly and all the text must fit.
What result do I expect in a nutshell: I am trying to create thumbnails of the pages of a document, but I want them to be smaller, relative to some number (I am sorry, I am not quite sure how do I say such stuff in English, basically if the document's page width is 1200 px I want it to be 1200/n
, where n is the "some number" that I mentioned earlier), but if the shrinked image's size is still bigger than 635x896 I want the size to be 635x896.
Thanks in advance. And also I am sorry for my bad English.