I am trying to convert a pdf page to .NET Bitmapusing Pdfium . I want to use it directly in WPF, so WinForm methods are not intended. I already asked this question (based on my initial understanding), as I tried to do this with help FPDF_RenderPage. From what I have learned so far from the SDK and its only .NET port ( PdfViewer ) there are two ways to render to a bitmap.
I want to know if I am taking the steps in the first method correctly, especially in the context of the memory device, and what is needed to correctly enter the native bitmap in .NET in the second method.
Using FPDF_RenderPageby supplying a memory device context
var hMemDC = NativeMethods.CreateCompatibleDC(IntPtr.Zero);
IntPtr hDC = NativeMethods.GetDC(IntPtr.Zero);
var hBitmap = NativeMethods.CreateCompatibleBitmap(hDC, width, height);
hBitmap = NativeMethods.SelectObject(hMemDC, hBitmap);
IntPtr brush = NativeMethods.CreateSolidBrush((int)ColorTranslator.ToWin32(Color.White));
NativeMethods.FillRgn(hMemDC, NativeMethods.CreateRectRgn(0, 0, width, height), brush);
bool success = _file.RenderPDFPageToDC(
page,
hMemDC,
(int)dpiX, (int)dpiY,
bounds.X, bounds.Y, bounds.Width, bounds.Height,
true ,
true ,
true ,
true ,
true ,
forPrinting
);
hBitmap = NativeMethods.SelectObject(hMemDC, hBitmap);
Bitmap myBitmap = Bitmap.FromHbitmap(hBitmap);
Using FPDF_RenderPageBitmap
IntPtr bitmapHandle = NativeMethods.FPDFBitmap_Create(bounds.Width, bounds.Height, 0);
bool success = _file.RenderPDFPageToBitmap(
page,
bitmapHandle,
(int)dpiX, (int)dpiY,
bounds.X, bounds.Y, bounds.Width, bounds.Height,
true ,
true ,
true ,
true ,
true ,
forPrinting
);
if (!success)
throw new Win32Exception();
else
{
byte[] bytes = new byte[bounds.Width * bounds.Height * 4];
Marshal.Copy(bitmapHandle, bytes, 0, bytes.Length);
bitmap = Convert_BGRA_TO_ARGB(bytes, bounds.Width, bounds.Height);
}
// Convert BGRA to ARGB
public Bitmap Convert_BGRA_TO_ARGB(byte[] DATA, int width, int height)
{
Bitmap Bm = new Bitmap(width, height, PixelFormat.Format32bppArgb);
int index;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
// BGRA TO ARGB
index = 4 * (x + (y * width));
Color c = Color.FromArgb(
DATA[index + 3],
DATA[index + 2],
DATA[index + 1],
DATA[index + 0]);
Bm.SetPixel(x, y, c);
}
}
return Bm;
}
Render:

source
share