Skip to content

Instantly share code, notes, and snippets.

@cosmez
Created October 18, 2023 04:59
Show Gist options
  • Save cosmez/42e364b459d9c9a8e93f9003f792874c to your computer and use it in GitHub Desktop.
Save cosmez/42e364b459d9c9a8e93f9003f792874c to your computer and use it in GitHub Desktop.
PdfiumCore + SDL2 in C#
/** packages to install
<ItemGroup>
<PackageReference Include="PDFiumCore" Version="120.0.6056" />
<PackageReference Include="ppy.SDL2-CS" Version="1.0.82" />
</ItemGroup>
*/
using PDFiumCore;
using static SDL2.SDL;
using static PDFiumCore.fpdfview;
namespace SDLMu;
internal class Program
{
static unsafe void Main(string[] args)
{
FPDF_InitLibrary();
if (SDL_Init(SDL_INIT_VIDEO) < 0)
return;
IntPtr window = SDL_CreateWindow("PDF Viewer", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1024, 768, 0);
IntPtr renderer = SDL_CreateRenderer(window, -1,SDL_RendererFlags.SDL_RENDERER_ACCELERATED);
var document = FPDF_LoadDocument("document.pdf", "");
var page = FPDF_LoadPage(document, 0);
using var pageSize = new FS_SIZEF_();
FPDF_GetPageSizeByIndexF(document, 0, pageSize);
var bitmap = FPDFBitmapCreateEx((int)pageSize.Width, (int)pageSize.Height,
(int)FPDFBitmapFormat.BGRA, IntPtr.Zero, 0);
if (bitmap == null) throw new Exception("failed to create a bitmap object");
uint color = uint.MaxValue;
FPDFBitmapFillRect(bitmap, 0, 0, (int)pageSize.Width, (int)pageSize.Height, color);
FPDF_RenderPageBitmap(bitmap, page, 0, 0, (int)pageSize.Width, (int)pageSize.Height, 0,
(int)RenderFlags.RenderAnnotations);
var scan0 = FPDFBitmapGetBuffer(bitmap);
var stride = FPDFBitmapGetStride(bitmap);
var texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, (int)SDL_TextureAccess.SDL_TEXTUREACCESS_STREAMING, (int)pageSize.Width, (int)pageSize.Height);
var rect = new SDL_Rect();
rect.h = (int)pageSize.Height; rect.w = (int)pageSize.Width;
rect.y = 0; rect.x = 0;
SDL_UpdateTexture(texture, ref rect, scan0, stride);
FPDFBitmapDestroy(bitmap);
FPDF_ClosePage(page);
bool quit = false;
while (!quit)
{
SDL_Event e;
while (SDL_PollEvent(out e) != 0)
{
if (e.type == SDL_EventType.SDL_QUIT)
{
quit = true;
}
}
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, ref rect, ref rect);
SDL_RenderPresent(renderer);
}
FPDF_CloseDocument(document);
FPDF_DestroyLibrary();
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment