c# – 位图图形与WinForm控制图形

我只是使用名为 PdfiumViewer的Pdfium的.NET端口.它在WinForm控件中呈现时效果很好但是当我尝试在Bitmap上呈现它以在WPF窗口中显示(或者甚至保存到磁盘)时文字有问题.

var pdfDoc = PdfiumViewer.PdfDocument.Load(FileName);
int width = (int)(this.ActualWidth - 30) / 2;
int height = (int)this.ActualHeight - 30;            

var bitmap = new System.Drawing.Bitmap(width,height);

var g = system.drawing.graphics.FromImage(bitmap);

g.FillRegion(System.Drawing.Brushes.White,new System.Drawing.Region(
    new System.Drawing.RectangleF(0,width,height)));

pdfDoc.Render(1,g,g.DpiX,g.DpiY,new System.Drawing.Rectangle(0,height),false);

// Neither of these are readable
image.source = BitmapHelper.ToBitmapSource(bitmap);
bitmap.Save("test.bmp");

// Directly rendering to a System.Windows.Forms.Panel control works well
var controlGraphics = panel.CreateGraphics(); 
pdfDoc.Render(1,controlGraphics,controlGraphics.DpiX,controlGraphics.DpiY,false);

值得注意的是,我在Graphics对象上测试了几乎所有可能的选项,包括TextContrast,TextRenderingHint,SmoothingMode,PixelOffsetMode,……

我在Bitmap对象上缺少哪些配置导致这种情况?

enter image description here

编辑2

经过大量的搜索和@BoeseB提到后,我发现Pdfium通过提供第二种渲染方法FPDF_RenderPageBitmap来渲染设备句柄和位图,目前我正在努力将其原生BGRA位图格式转换为托管位图.

编辑

TextRenderingHint的不同模式

enter image description here

还尝试了Application.SetCompatibleTextRenderingDefault(false),没有明显的区别.

解决方法

不是你的 issue吗?
看看最近的 fix吧.
如您所见,存储库所有者提交了较新版本的PdfiumViewer.现在你可以这样写:

var pdfDoc = PdfDocument.Load(@"mydoc.pdf");
var pageImage = pdfDoc.Render(pageNum,height,dpiX,dpiY,isForPrinting);
pageImage.Save("test.png",ImageFormat.Png);

// to display it on WPF canvas
BitmapSource source = ImagetoBitmapSource(pageImage);
canvas.DrawImage(source,rect);     // canvas is instance of DrawingContext

这是将Image转换为ImageSource的常用方法

BitmapSource ImagetoBitmapSource(System.Drawing.Image image)
{
    using(MemoryStream memory = new MemoryStream())
    {
        image.Save(memory,ImageFormat.Bmp);
        memory.Position = 0;
        var source = new BitmapImage();
        source.BeginInit();
        source.StreamSource = memory;
        source.CacheOption = BitmapCacheOption.OnLoad;
        source.EndInit();

        return source;
    }
}

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...