要将 PDF 页面转换为图片,可以使用 Ghostscript 和 ImageMagick。以下是 .NET Core 5.0 中使用这些工具的示例代码:

  1. 安装 Ghostscript 和 ImageMagick

在安装 Ghostscript 和 ImageMagick 之前,请确保您的计算机上已安装 .NET Core 5.0。然后,按照以下步骤安装这些工具:

  • 安装 Ghostscript:从 Ghostscript 官方网站下载并安装 Ghostscript。
  • 安装 ImageMagick:从 ImageMagick 官方网站下载并安装 ImageMagick。
  1. 创建一个 PDF 转换器类

在 .NET Core 5.0 中,您可以使用 Process 类来运行外部命令。以下是一个 PDF 转换器类的示例代码,它将 PDF 页面转换为 PNG 图像:

using System.Diagnostics;

public class PdfToImageConverter
{
    private readonly string ghostscriptPath;
    private readonly string imageMagickPath;

    public PdfToImageConverter(string ghostscriptPath, string imageMagickPath)
    {
        this.ghostscriptPath = ghostscriptPath;
        this.imageMagickPath = imageMagickPath;
    }

    public void ConvertToImage(string pdfFilePath, string outputImagePath)
    {
        // 使用 Ghostscript 将 PDF 页面转换为 PNG 图像
        var ghostscriptArgs = $"-dNOPAUSE -dBATCH -sDEVICE=pngalpha -r300 -dFirstPage=1 -dLastPage=1 -sOutputFile={outputImagePath} {pdfFilePath}";
        var ghostscriptProcess = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = ghostscriptPath,
                Arguments = ghostscriptArgs,
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            }
        };
        ghostscriptProcess.Start();
        ghostscriptProcess.WaitForExit();

        // 使用 ImageMagick 调整 PNG 图像大小
        var imageMagickArgs = $"{outputImagePath} -resize 800x800 {outputImagePath}";
        var imageMagickProcess = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = imageMagickPath,
                Arguments = imageMagickArgs,
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            }
        };
        imageMagickProcess.Start();
        imageMagickProcess.WaitForExit();
    }
}
  1. 使用 PdfToImageConverter 类

现在,您可以使用 PdfToImageConverter 类将 PDF 页面转换为 PNG 图像。以下是在 ASP.NET Core 控制器中使用该类的示例代码:

[HttpGet("/pdf-to-image")]
public IActionResult ConvertPdfToImage()
{
    var converter = new PdfToImageConverter("C:/Program Files/gs/gs9.53.3/bin/gswin64c.exe", "C:/Program Files/ImageMagick-7.0.11-Q16-HDRI/magick.exe");
    converter.ConvertToImage("C:/temp/document.pdf", "C:/temp/document-1.png");
    return Ok("PDF page converted to image.");
}

在上面的示例中,PdfToImageConverter 类使用 Ghostscript 和 ImageMagick 将 C:/temp/document.pdf 的第一页转换为 C:/temp/document-1.png。如果转换成功,将返回“PDF page converted to image.”消息。

.NET Core 5.0 PDF 页面转换为图片教程:使用 Ghostscript 和 ImageMagick

原文地址: https://www.cveoy.top/t/topic/okzX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录