I'm using PDFiumSharp to convert a PDF file to a single image, using the following code:
using System;
using System.IO;
using System.Linq;
using PDFiumSharp;
using System.Drawing.Imaging;
using System.Drawing;
using PDFiumSharp.Types;
public class ImageFromPDF
{
private readonly int DPI = 200;
private readonly int PPI = 72;
private int PointsToPixels(double points)
{
return (int)Math.Ceiling(points / PPI * DPI);
}
public MemoryStream Convert(MemoryStream stream)
{
var outputStream = new MemoryStream();
using (var doc = new PdfDocument(stream.ToArray()))
{
var totalHeight = PointsToPixels(doc.Pages.Sum(bm => bm.Height));
var maxWidth = PointsToPixels(doc.Pages.Max(bm => bm.Width));
using (var img = new Bitmap(maxWidth, totalHeight, PixelFormat.Format32bppArgb))
{
img.SetResolution(DPI, DPI);
using (var g = Graphics.FromImage(img))
{
var heightOffset = 0;
foreach (var page in doc.Pages)
{
using (var bitmap = new PDFiumBitmap(PointsToPixels(page.Width), PointsToPixels(page.Height), false))
{
bitmap.Fill(new FPDF_COLOR(255, 255, 255, 255));
page.Render(bitmap);
using (var bmStream = bitmap.AsBmpStream(DPI, DPI))
{
var widthOffset = (maxWidth - bitmap.Width) / 2;
using (var fromStream = Image.FromStream(bmStream, true))
{
g.DrawImage(fromStream, new Point(widthOffset, heightOffset));
heightOffset += bitmap.Height;
}
}
}
}
}
img.Save(outputStream, ImageFormat.Jpeg);
}
}
return outputStream;
}
}
This works fine most of the times, however occasionally I come across a particularly large PDF file (40+ A4 pages) and then the time comes to img.Save(outputStream, ImageFormat.Jpeg)
I get A generic error occurred in GDI+
.
Is there a limitation either on the Image class or the memory stream that is causing this behaviour, or is there another problem going on here?
And is there a way to solve this without separating the pages (as that is a constraint I'm working under at the moment)?