Convert PDF to PNG using WPF

Convert PDF, WPF / XPS
8/10/2015

In this codesample we take a look how you can create PNG images from a PDF using the Windows Presentation Foundation.

Code sample to convert PDF to PNG

1 [STAThread] 2 static void Main(string[] args) 3 { 4 //read input from file 5 Document input; 6 using (FileStream fs = new FileStream(@"..\..\input.pdf", FileMode.Open, FileAccess.Read)) 7 { 8 input = new Document(fs); 9 } 10 11 //the font names in the pdf have a different name than in the windows system. 12 //the resolveFont event is raised whenever a font needs to be resolved 13 RenderSettings renderSettings = new RenderSettings(); 14 renderSettings.TextSettings.ResolveFont += new ResolveFontEventHandler(TextSettings_ResolveFont); 15 16 int count = input.Pages.Count; 17 double dpi = 300; 18 for (int i = 0; i < count; i++) 19 { 20 Page page = input.Pages[i]; 21 System.Windows.Documents.FixedPage fixedPage = page.ConvertToWpf(renderSettings, new ConvertToWpfOptions(), new Summary()); 22 23 // Create a new bitmap render target. 24 double width = page.Width * dpi / 72.0; 25 double height = page.Height * dpi / 72.0; 26 RenderTargetBitmap bmp = new RenderTargetBitmap((int)(width), (int)(height), dpi, dpi, System.Windows.Media.PixelFormats.Pbgra32); 27 28 // Render the fixed page into the bitmap target. 29 bmp.Render(fixedPage); 30 31 // Write the bitmap to file. 32 using (FileStream outStream = new FileStream(string.Format(@"..\..\output" + i + ".png"), FileMode.Create)) 33 { 34 PngBitmapEncoder enc = new PngBitmapEncoder(); 35 enc.Frames.Add(BitmapFrame.Create(bmp)); 36 enc.Save(outStream); 37 } 38 39 // For some PDF documents this samples has a memory usage pattern that appears to be affected by a garbage collection issue in the 40 // Large Object Heap. See https://www.simple-talk.com/dotnet/.net-framework/the-dangers-of-the-large-object-heap/ 41 // Strangely but true: calling GC.GetTotalMemory appears to be able to avoid that issue, so we do that here. 42 GC.GetTotalMemory(true); 43 } 44 } 45 46 static void TextSettings_ResolveFont(TextRenderSettings sender, ResolveFontEventArgs args) 47 { 48 System.Diagnostics.Trace.WriteLine(String.Format("font ({0}, {1}, {2})", args.PdfFontName, args.SystemFontName, args.FontPath)); 49 50 if (args.FontLocation != FontLocation.System) 51 { 52 switch (args.PdfFontName) 53 { 54 case "Times-Roman": 55 args.SystemFontName = "Times New Roman"; 56 break; 57 case "Times-Bold": 58 args.SystemFontName = "Times New Roman"; 59 args.Bold = true; 60 break; 61 case "Times-Italic": 62 args.SystemFontName = "Times New Roman"; 63 args.Italic = true; 64 break; 65 case "Helvetica": 66 args.SystemFontName = "Arial Unicode MS"; 67 break; 68 case "Helvetica-Bold": 69 args.SystemFontName = "Arial Unicode MS"; 70 args.Bold = true; 71 break; 72 case "Helvetica-Italic": 73 args.SystemFontName = "Arial Unicode MS"; 74 args.Italic = true; 75 break; 76 } 77 } 78 }