C# 将 pdf 文件转为图片

2023年10月25日 1521点热度 0人点赞 0条评论
内容目录

图片转换需要安装:https://ghostscript.com/

引入:

    <ItemGroup>
        <PackageReference Include="Magick.NET-Q16-AnyCPU" Version="13.4.0" />
        <PackageReference Include="Microsoft.IO.RecyclableMemoryStream" Version="2.3.2" />
    </ItemGroup>

定义转换配置:

    public class PdfConvertSetting
    {
        /// <summary>
        /// PDF 文件位置
        /// </summary>
        public string SourcePdfPath { get; init; }

        /// <summary>
        /// 分辨率,默认打印机 dpi 96
        /// </summary>
        public int Dpi { get; set; } = 300;

        /// <summary>
        /// 将 pdf 转为为何种类型
        /// </summary>
        public MagickFormat ImageType { get; set; } = ImageType.PNG;

        /// <summary>
        /// PDF 纸张大小
        /// </summary>
        public PageSizeType PageSize { get; set; } = PageSizeType.A4;
    }

然后根据文件,自动将每页 pdf 转为图片,然后将图片合并到 pdf 中。

        /// <summary>
        /// 将 pdf 打印为图片 pdf
        /// <param name="setting"></param>
        /// <returns></returns>
        public static async Task<string> PdfToPdf(PdfConvertSetting setting)
        {
            var imageExtension = ".png";  // 根据情况配置
            var ticks = DateTime.Now.Ticks.ToString();
            var imagesPath = Path.Combine("temp", DateTime.Now.Ticks.ToString());
            Directory.CreateDirectory(imagesPath);

            FileInfo fileInfo = new FileInfo(setting.SourcePdfPath);

            var settings = new MagickReadSettings
            {
                Density = new Density(setting.Dpi, setting.Dpi)
            };

            using var oldPdf = new MagickImageCollection();
            using var newPdf = new MagickImageCollection();

            oldPdf.Read(fileInfo, settings);

            int pageIndex = 0;
            foreach (var image in oldPdf)
            {
                image.Format = setting.ImageType;
                var fileName = Path.Combine(imagesPath, pageIndex.ToString() + imageExtension);
                await image.WriteAsync(fileName);
                newPdf.Add(new MagickImage(fileName));
                pageIndex++;
            }
            oldPdf.Dispose();
            var filename = Path.Combine(imagesPath, ticks + ".pdf");
            newPdf.Write(filename);
            return filename;
        }

将整个 pdf 合成一张图片:

        /// <summary>
        /// 整个 pdf 文件转为图片
        /// </summary>
        /// <param name="sourcePath"></param>
        /// <param name="dpi"></param>
        /// <param name="y">是否 y 轴拼接,可以选择↓→两种拼接方向</param>
        /// <returns></returns>
        public static async Task<string> PdfToImage(string sourcePath, int dpi = 300, bool y = false)
        {
            var ticks = DateTime.Now.Ticks.ToString();
            var imagesPath = Path.Combine(Constants.CurrentTempDir, DateTime.Now.Ticks.ToString());
            Directory.CreateDirectory(imagesPath);
            var imageFile = Path.Combine(imagesPath, ticks + ".png");
            var settings = new MagickReadSettings
            {
                Density = new Density(dpi)
            };

            using var images = new MagickImageCollection();
            images.Read(sourcePath, settings);

            if (y == true)
            {
                using var horizontal = images.AppendHorizontally();
                horizontal.Format = MagickFormat.Png;
                await horizontal.WriteAsync(imageFile);
            }
            else
            {
                using var vertical = images.AppendVertically();
                vertical.Format = MagickFormat.Png;
                await vertical.WriteAsync(imageFile);
            }

            return imageFile;
        }

痴者工良

高级程序员劝退师

文章评论