问题
I'm just using a .NET port of Pdfium
named PdfiumViewer. It just works very well once rendered in the WinForm controls but when I try to render it on a Bitmap
to show in the WPF windows (or even saving to disk) the rendered text has problem.
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, 0, width, height)));
pdfDoc.Render(1, g, g.DpiX, g.DpiY, new System.Drawing.Rectangle(0, 0, width, 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,
new System.Drawing.Rectangle(0, 0, width, height), false);
It's notable to say that I tested almost every possible options on the Graphics
object including TextContrast
,TextRenderingHint
,SmoothingMode
,PixelOffsetMode
, ...
Which configurations I'm missing on the Bitmap
object that cause this?
Edit 2
After lots of searching and as @BoeseB mentioned I just found that Pdfium render device handle and bitmaps differently by providing a second render method FPDF_RenderPageBitmap and currently I'm struggling to convert its native BGRA bitmap format to managed Bitmap
.
Edit
Different modes of TextRenderingHint
Also tried Application.SetCompatibleTextRenderingDefault(false)
with no noticeable difference.
回答1:
Isn't it your issue ? Look recent fix for it. As you can see, repository owner commited newer version of PdfiumViewer. Now you can write this way:
var pdfDoc = PdfDocument.Load(@"mydoc.pdf");
var pageImage = pdfDoc.Render(pageNum, width, 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
Here is a popular approach to convert Image to 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;
}
}
来源:https://stackoverflow.com/questions/28411460/bitmap-graphics-vs-winform-control-graphics