一、安裝
sudo yum install poppler-utils
pdftoppm -v
pdftoppm -png -r 300 a.pdf /tmp/page
運行效果:
PDF轉圖片工具 - 在線PDF轉PNG/JPG/TIFF轉換器 | 免費在線工具
后臺實現:
using System.Diagnostics;
using System.IO.Compression;namespace SaaS.OfficialWebSite.Web.Utils
{public class PdfTopPmService{private ILogger<PdfTopPmService> _logger;public PdfTopPmService(ILogger<PdfTopPmService> logger){_logger = logger;}public async Task<MemoryStream> ConvertToImagesAsync(MemoryStream pdfStream){// 臨時保存PDF文件(僅用于轉換過程)var tempPdfPath = Path.GetTempFileName();using (var fileStream = new FileStream(tempPdfPath, FileMode.Create)){pdfStream.Position = 0;await pdfStream.CopyToAsync(fileStream);fileStream.Flush();}// 使用pdftoppm轉換PDF為圖片var outputFiles = ConvertPdfToImages(tempPdfPath);// 創建ZIP文件(內存流)var zipStream = new MemoryStream();using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Create, true)){foreach (var imagePath in outputFiles){var entry = archive.CreateEntry(Path.GetFileName(imagePath));using (var entryStream = entry.Open()){using (var imageStream = System.IO.File.OpenRead(imagePath)){await imageStream.CopyToAsync(entryStream);}}// 刪除臨時圖片文件System.IO.File.Delete(imagePath);}}// 刪除臨時PDF文件System.IO.File.Delete(tempPdfPath);return zipStream;}private List<string> ConvertPdfToImages(string pdfPath){var outputFiles = new List<string>();var outputPattern = Path.Combine(Path.GetTempPath(), "page");// 使用pdftoppm命令行工具轉換PDFvar process = new Process{StartInfo = new ProcessStartInfo{FileName = "pdftoppm",Arguments = $"-png -r 300 {pdfPath} {outputPattern}",UseShellExecute = false,RedirectStandardOutput = true,CreateNoWindow = true}};process.Start();process.WaitForExit();// 獲取生成的圖片文件var tempFiles = Directory.GetFiles(Path.GetTempPath(), "page-*.png");outputFiles.AddRange(tempFiles);return outputFiles;}}
}