0

我正在使用 PDFiumSharp 使用以下代码将 PDF 文件转换为单个图像:

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;
    }
}

这在大多数情况下都可以正常工作,但是偶尔我会遇到一个特别大的 PDF 文件(40+ A4 页),然后img.Save(outputStream, ImageFormat.Jpeg)我得到A generic error occurred in GDI+.

Image 类或导致此行为的内存流是否存在限制,或者这里是否存在其他问题?

有没有办法在不分离页面的情况下解决这个问题(因为这是我目前正在处理的一个约束)?

4

0 回答 0