private static void PdfToImages() { int dpi = 96; var watch = new Stopwatch(); watch.Start(); using (var doc = PdfDocument.Load($"{_projectDir}\\Samples\\input.pdf")) { int pageCount = doc.Pages.Count; for (int index = 0; index < pageCount; index++) { var page = doc.Pages[index]; int width = (int)(page.Width / 72.0 * dpi); int height = (int)(page.Height / 72.0 * dpi); using (var bitmap = new PdfBitmap(width, height, true)) { bitmap.FillRect(0, 0, width, height, FS_COLOR.White); page.Render(bitmap, 0, 0, width, height, PageRotate.Normal, RenderFlags.FPDF_LCD_TEXT); bitmap.Image.Save($"{_projectDir}\\Samples\\outputs\\output_{index}.jpg", ImageFormat.Jpeg); } } watch.Stop(); Console.WriteLine($"Converting {pageCount} pages took {watch.Elapsed.TotalSeconds} seconds"); } }
public static Bitmap PDFRenderBitmap(PdfPage page, decimal dpiX, decimal dpiY) { try { int width = (int)(page.Width / 72 * Decimal.ToDouble(dpiX)); int height = (int)(page.Height / 72 * Decimal.ToDouble(dpiY)); using (PdfBitmap pdfBitmap = new PdfBitmap(width, height, true)) { pdfBitmap.FillRect(0, 0, width, height, Patagames.Pdf.FS_COLOR.White); page.Render(pdfBitmap, 0, 0, width, height, PageRotate.Normal, RenderFlags.FPDF_PRINTING); if (pdfBitmap.Image == null) { AppLogger.Warn("Failed to get image bitmap from PDFium image object."); return(null); } Bitmap newBitmap = new Bitmap(pdfBitmap.Image); newBitmap.SetResolution((float)dpiX, (float)dpiY); return(newBitmap); } } catch (Exception ex) { ex.Data.Add("p:pdfPage", page); throw; } }
protected Bitmap RenderArea(int pageIndex, System.Windows.Point lt, System.Windows.Point rb) { try { var page = Document.Pages[pageIndex]; var pageRenderRect = GetRenderRect(pageIndex); int scaledPageWidth = (int)pageRenderRect.Width; int scaledPageHeight = (int)pageRenderRect.Height; Bitmap fullRender; using (var bmp = new PdfBitmap(scaledPageWidth, scaledPageHeight, true)) { bmp.FillRect(0, 0, scaledPageWidth, scaledPageHeight, new FS_COLOR(PageBackColor.A, PageBackColor.R, PageBackColor.G, PageBackColor.B)); //Render part of page into bitmap; page.Render(bmp, 0, 0, scaledPageWidth, scaledPageHeight, page.Rotation, RenderFlags.FPDF_LCD_TEXT); fullRender = new Bitmap(bmp.Image); } var pt1 = page.PageToDeviceEx(0, 0, scaledPageWidth, scaledPageHeight, page.Rotation, (float)lt.X, (float)lt.Y); var pt2 = page.PageToDeviceEx(0, 0, scaledPageWidth, scaledPageHeight, page.Rotation, (float)rb.X, (float)rb.Y); if (pt1.X > pt2.X) { int tmpX = pt1.X; pt1.X = pt2.X; pt2.X = tmpX; } if (pt1.Y > pt2.Y) { int tmpY = pt1.Y; pt1.Y = pt2.Y; pt2.Y = tmpY; } return(fullRender.Clone( new Rectangle(pt1.X, pt1.Y, (int)(pt2.X - pt1.X), (int)(pt2.Y - pt1.Y)), fullRender.PixelFormat )); } catch (OutOfMemoryException ex) { LogTo.Warning(ex, $"Ran out of memory while rendering PDF area: page {pageIndex}, {lt}:{rb}"); return(null); } catch (Exception ex) { LogTo.Error(ex, $"Failed to render PDF area: page {pageIndex}, {lt}:{rb}"); return(null); } }