我的任务是向用户显示 XPS 文档每一页的缩略图。我需要所有图像都很小,所以我用dpi设置为 72.0(我在 google 上搜索到 dpi 72.0 的 A4 纸的尺寸为 635x896)。基本上,我执行以下操作:
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);
}
但是当我渲染文档页面(A4)时,它的大小实际上是846x1194而不是我所期望的。我试图降低 dpi (48.0),但图像的尺寸变得更大(我想,我只是不太明白 dpi 是什么以及它如何影响文档)。我试着做dpi=96.0,而且尺寸变小了。我从该类的实例集合中设置了一张图像BitmapImage
由上面的代码生成作为源Image
控件(我正在创建一个 WPF 应用程序),如果 dpi 设置为 96.0,我的程序如下所示:
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.