Skip to content

Instantly share code, notes, and snippets.

@dranger003
Created June 3, 2024 02:00
Show Gist options
  • Save dranger003/e6999d04164f6337b2da1ba06a54c3a3 to your computer and use it in GitHub Desktop.
Save dranger003/e6999d04164f6337b2da1ba06a54c3a3 to your computer and use it in GitHub Desktop.
Convert PDF to images using C# and the Windows Runtime (no third party dependencies).
// csproj:
// <TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
// <ItemGroup><PackageReference Include="System.Drawing.Common" Version="8.0.6" /></ItemGroup>
using System.Drawing;
using System.Drawing.Imaging;
using Windows.Data.Pdf;
using Windows.Storage;
using Windows.Storage.Streams;
internal class PDF
{
public static async Task ConvertToImagesAsync(string path)
{
var folder = Path.GetFileNameWithoutExtension(path);
Directory.CreateDirectory(folder);
var file = await StorageFile.GetFileFromPathAsync(path);
var doc = await PdfDocument.LoadFromFileAsync(file);
for (uint i = 0; i < doc.PageCount; i++)
{
var page = doc.GetPage(i);
using var stream = new InMemoryRandomAccessStream();
await page.RenderToStreamAsync(stream);
using var image = new Bitmap(stream.AsStream());
image.Save(Path.Combine(folder, $"{Path.GetFileName(path)}_{i}.png"), ImageFormat.Png);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment