form实现pdf文件转换成jpg文件

news2025/4/17 12:36:30

说明:
我希望将pdf文件转换成jpg文件
请去下载并安装 Ghostscript,gs10050w64.exe
配置环境变量:D:\Program Files\gs\gs10.05.0\bin
本地pdf路径:C:\Users\wangrusheng\Documents\name.pdf
输出文件目录:C:\Users\wangrusheng\Documents\PdfToJpgOutput
效果图:
在这里插入图片描述

step1:C:\Users\wangrusheng\RiderProjects\WinFormsApp18\WinFormsApp18\Form1.cs

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsApp18
{
    public partial class Form1 : Form
    {
        // 固定PDF路径配置 C:\Users\wangrusheng\Documents
        public const string FixedPdfPath = @"C:\Users\wangrusheng\Documents\age.pdf";
        private string _currentTempDir;

        // UI控件
        private TextBox txtSaveDir;
        private NumericUpDown numStartPage;
        private NumericUpDown numEndPage;
        private ComboBox cmbQuality;
        private CheckBox chkMerge;
        private ComboBox cmbOrientation;

        public Form1()
        {
            InitializeComponent();
            InitializeComponents();
            LoadSettings();
        }

        private void InitializeComponents()
        {
            // 固定PDF路径显示
            var lblFile = new Label
            {
                Text = "PDF文件路径:",
                Location = new Point(20, 20),
                AutoSize = true
            };

            var txtFixedPath = new TextBox
            {
                Text = FixedPdfPath,
                Location = new Point(120, 17),
                Width = 400,
                ReadOnly = true,
                BackColor = SystemColors.Window
            };

            // 保存目录区域
            var lblSaveDir = new Label
            {
                Text = "保存目录:",
                Location = new Point(20, 60),
                AutoSize = true
            };

            txtSaveDir = new TextBox
            {
                Text = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                    "PdfToJpgOutput"),
                Location = new Point(120, 57),
                Width = 400,
                ReadOnly = true
            };

            var btnSelectDir = new Button
            {
                Text = "浏览...",
                Location = new Point(530, 55),
                AutoSize = true
            };
            btnSelectDir.Click += BtnSelectDir_Click;

            // 页码选择
            var lblPages = new Label
            {
                Text = "页码范围:",
                Location = new Point(20, 100),
                AutoSize = true
            };

            numStartPage = new NumericUpDown
            {
                Location = new Point(120, 97),
                Minimum = 1,
                Maximum = 10000
            };

            numEndPage = new NumericUpDown
            {
                Location = new Point(220, 97),
                Minimum = 0,
                Maximum = 10000
            };

            // 质量选择
            var lblQuality = new Label
            {
                Text = "输出质量:",
                Location = new Point(20, 140),
                AutoSize = true
            };

            cmbQuality = new ComboBox
            {
                Location = new Point(120, 137),
                Items = { "300", "400", "500", "600" },
                SelectedIndex = 2
            };

            // 合并选项
            chkMerge = new CheckBox
            {
                Text = "合并为单文件",
                Location = new Point(20, 180),
                AutoSize = true
            };

            cmbOrientation = new ComboBox
            {
                Location = new Point(120, 177),
                Items = { "垂直拼接", "水平拼接" },
                SelectedIndex = 0
            };

            // 操作按钮
            var btnRun = new Button
            {
                Text = "开始转换",
                Location = new Point(20, 220),
                AutoSize = true
            };
            btnRun.Click += BtnRun_Click;

            // 添加所有控件
            Controls.AddRange(new Control[]
            {
                lblFile, txtFixedPath,
                lblSaveDir, txtSaveDir, btnSelectDir,
                lblPages, numStartPage, numEndPage,
                lblQuality, cmbQuality,
                chkMerge, cmbOrientation,
                btnRun
            });
        }

        private void BtnSelectDir_Click(object sender, EventArgs e)
        {
            using var dialog = new FolderBrowserDialog
            {
                SelectedPath = txtSaveDir.Text,
                Description = "选择保存目录"
            };

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                if (FileHelper.ValidatePath(dialog.SelectedPath))
                {
                    txtSaveDir.Text = dialog.SelectedPath;
                }
                else
                {
                    MessageBox.Show("选择的目录路径无效");
                }
            }
        }

        private async void BtnRun_Click(object sender, EventArgs e)
        {
            try
            {
                if (!ValidateInputs()) return;

                _currentTempDir = FileHelper.GetTempWorkspace();

                var result = await ConvertPdfToImagesAsync();

                if (result.Success)
                {
                    if (chkMerge.Checked)
                    {
                        await MergeImagesAsync();
                    }

                    MoveFinalFiles();
                    MessageBox.Show("转换成功完成");
                }
                else
                {
                    throw new Exception(result.ErrorMessage);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"操作失败: {ex.Message}");
            }
            finally
            {
                FileHelper.CleanTempFiles(_currentTempDir);
            }
        }

        private bool ValidateInputs()
        {
            if (!File.Exists(FixedPdfPath))
            {
                MessageBox.Show($"自动读取的PDF文件不存在:{FixedPdfPath}");
                return false;
            }

            if (numStartPage.Value > numEndPage.Value && numEndPage.Value != 0)
            {
                MessageBox.Show("起始页码不能大于结束页码");
                return false;
            }

            return true;
        }

        private async Task<(bool Success, string ErrorMessage)> ConvertPdfToImagesAsync()
        {
            var args = new List<string>
            {
                "-dNOSAFER",
                $"-r{cmbQuality.SelectedItem}",
                "-sDEVICE=jpeg",
                "-dBATCH",
                "-dNOPAUSE",
                "-dEPSCrop",
                $"-dFirstPage={numStartPage.Value}",
                numEndPage.Value > 0 ? $"-dLastPage={numEndPage.Value}" : "",
                $"-sOutputFile={Path.Combine(_currentTempDir, "page_%d.jpg")}",
                $"\"{FixedPdfPath}\""
            };

            var (success, output) = FileHelper.ExecuteCommand("gswin64c", string.Join(" ", args), _currentTempDir);
            return (success, output);
        }

        private async Task MergeImagesAsync()
        {
            var args = $"{Path.Combine(_currentTempDir, "page_*.jpg")} " +
                       $"{(cmbOrientation.SelectedIndex == 0 ? "-append" : "+append")} " +
                       $"{Path.Combine(_currentTempDir, "merged.jpg")}";

            var (success, output) = FileHelper.ExecuteCommand("magick", args, _currentTempDir);
            if (!success) throw new Exception(output);
        }

        private void MoveFinalFiles()
        {
            var destDir = txtSaveDir.Text;
            Directory.CreateDirectory(destDir);

            var filesToMove = chkMerge.Checked
                ? new[] { "merged.jpg" }
                : Directory.GetFiles(_currentTempDir, "page_*.jpg");

            foreach (var file in filesToMove)
            {
                var destPath = Path.Combine(destDir, Path.GetFileName(file));
                File.Move(file, destPath, true);
            }
        }

        private void LoadSettings()
        {
            // 可添加其他配置加载逻辑
            numStartPage.Value = 1;
            numEndPage.Value = 0;
        }

        private void SaveSettings()
        {
            // 可添加配置保存逻辑
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            SaveSettings();
            base.OnFormClosing(e);
        }
    }
}

step2:C:\Users\wangrusheng\RiderProjects\WinFormsApp18\WinFormsApp18\FileHelper.cs

using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;

namespace WinFormsApp18
{
    public static class FileHelper
    {
        private const string GhostscriptExeName = "gswin64c.exe";
        private static readonly string[] GhostscriptSearchPaths = 
        {
            @"D:\Program Files\gs"
        };

        public static string GetTempWorkspace()
        {
            var tempDir = Path.Combine(
                Path.GetTempPath(),
                "PdfToJpg",
                DateTime.Now.ToString("yyyyMMdd_HHmmss")
            );
            
            Directory.CreateDirectory(tempDir);
            return tempDir;
        }

        public static bool ValidatePath(string path)
        {
            try
            {
                var fullPath = Path.GetFullPath(path);
                
                if (path.IndexOfAny(Path.GetInvalidPathChars()) >= 0)
                    return false;

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    if (!fullPath.StartsWith(ApplicationInfo.AppRootPath, StringComparison.OrdinalIgnoreCase))
                        return false;
                }
                else
                {
                    if (!fullPath.StartsWith(ApplicationInfo.AppRootPath))
                        return false;
                }

                return true;
            }
            catch
            {
                return false;
            }
        }

        public static (bool Success, string Output) ExecuteCommand(string command, string args, string workingDir)
        {
            try
            {
                var fullCommandPath = command.Equals("gswin64c", StringComparison.OrdinalIgnoreCase)
                    ? FindGhostscriptPath()
                    : command;

                if (fullCommandPath == null)
                    throw new FileNotFoundException("Ghostscript not found. Please install from https://www.ghostscript.com/");

                var startInfo = new ProcessStartInfo
                {
                    FileName = fullCommandPath,
                    Arguments = args,
                    WorkingDirectory = workingDir,
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true
                };

                using var process = Process.Start(startInfo);
                var output = process.StandardOutput.ReadToEnd();
                var error = process.StandardError.ReadToEnd();
                
                if (!process.WaitForExit(30000))
                    throw new TimeoutException("Process execution timed out");

                return (
                    process.ExitCode == 0, 
                    $"Exit Code: {process.ExitCode}\nOutput:\n{output}\nErrors:\n{error}"
                );
            }
            catch (Exception ex)
            {
                return (false, ex.Message);
            }
        }

        private static string FindGhostscriptPath()
        {
            // Check if ghostscript is in PATH
            var pathEnv = Environment.GetEnvironmentVariable("PATH") ?? "";
            foreach (var path in pathEnv.Split(Path.PathSeparator))
            {
                var fullPath = Path.Combine(path, GhostscriptExeName);
                if (File.Exists(fullPath))
                    return fullPath;
            }

            // Search common installation directories
            foreach (var basePath in GhostscriptSearchPaths)
            {
                if (!Directory.Exists(basePath)) continue;

                var versions = Directory.GetDirectories(basePath)
                    .OrderByDescending(d => d)
                    .ToList();

                foreach (var versionDir in versions)
                {
                    var exePath = Path.Combine(versionDir, "bin", GhostscriptExeName);
                    if (File.Exists(exePath))
                        return exePath;
                }
            }

            throw new FileNotFoundException($"Ghostscript executable ({GhostscriptExeName}) not found. " +
                "Please install from https://www.ghostscript.com/");
        }

        public static void CleanTempFiles(string tempDir)
        {
            try
            {
                if (Directory.Exists(tempDir))
                {
                    Directory.Delete(tempDir, true);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error cleaning temp files: {ex.Message}");
            }
        }
    }

    public static class ApplicationInfo
    {
        public static string AppRootPath => AppDomain.CurrentDomain.BaseDirectory;
    }
}

end

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2329484.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

STM32单片机入门学习——第13节: [6-1] TIM定时中断

写这个文章是用来学习的,记录一下我的学习过程。希望我能一直坚持下去,我只是一个小白,只是想好好学习,我知道这会很难&#xff0c;但我还是想去做&#xff01; 本文写于&#xff1a;2025.04.04 STM32开发板学习——第13节: [6-1] TIM定时中断 前言开发板说明引用解答和科普一…

【2】搭建k8s集群系列(二进制)之安装etcd数据库集群

一、etcd服务架构 Etcd 是一个分布式键值存储系统&#xff0c;Kubernetes 使用 Etcd 进行数据存储&#xff0c;所以先 准备一个 Etcd 数据库&#xff0c;为解决 Etcd 单点故障&#xff0c;应采用集群方式部署&#xff0c;这里使用 3 台组建集群&#xff0c;可容忍 1 台机器故障…

Linux常用命令详解:从基础到进阶

目录 一、引言 二、文件处理相关命令 &#xff08;一&#xff09;grep指令 &#xff08;二&#xff09;zip/unzip指令 ​编辑 &#xff08;三&#xff09;tar指令 &#xff08;四&#xff09;find指令 三、系统管理相关命令 &#xff08;一&#xff09;shutdown指…

基于spring boot的外卖系统的设计与实现【如何写论文思路与真正写出论文】

目录 系统开发实现链接&#xff1a; 背景与分析&#xff1a; 背景&#xff08;题目&#xff09;&#xff1a; 用户功能 配送员功能 管理员功能 分析&#xff1a; 过程&#xff08;主体展示为主&#xff0c;部分功能不一一展示&#xff09;&#xff1a; 目录 论文前面…

Kubernetes 存储 Downward API

1.介绍 1.提供容器元数据 比如我们 golang语言 我们说他会根据当前CPU的数量 以此去确认我们的进程 线程 和协程之间的关系 以此去释放我们当前CPU的更大的 这么一个并行任务的能力 但是这里会出现一个问题 容器它是把当前的应用 封装在我们固定的名称空间了 而且给它以特定的…

01人工智能基础入门

一、AI应用场景和发展历程 1.1行业应用 1、deepdream图像生成、yolo目标检测 2、知识图谱、画风迁移 3、语音识别、计算机视觉 4、用户画像 5、百度人工智能布局 1.2发展历程 人工智能的发展经历了 3 个阶段&#xff1a; 1980年代是正式成形期&#xff0c;尚不具备影响力。 …

进程和内存管理

目录 一.进程的基本信息 1.1进程的定义 1.2进程的特征 1.3进程的组成 1.4线程产生的背景 1.5线程的定义 1.6进程与线程的区别 1.7进程的类别 1.8进程的优先级 1.8.1进程优先级的概念 1.8.2PRI和NI 1.9僵尸进程 1.9.1僵尸进程的定义 1.9.2僵尸进程产生的原因 1.9…

React 项目使用 pdf.js 及 Elasticpdf 教程

摘要&#xff1a;本文章介绍如何在 React 中使用 pdf.js 及基于 pdf.js 的批注开发包 Elasticpdf。简单 5 步可完成集成部署&#xff0c;包括数据的云端同步&#xff0c;示例代码完善且简单&#xff0c;文末有集成代码分享。 1. 工具库介绍与 Demo 1.1 代码包结构 ElasticP…

性能测试之jmeter的基本使用

简介 Jmeter是Apache的开源项目&#xff0c;基于Java开发&#xff0c;主要用于进行压力测试。 优点&#xff1a;开源免费、支持多协议、轻量级、功能强大 官网&#xff1a;https://jmeter.apache.org/index.html 安装 安装步骤&#xff1a; 下载&#xff1a;进入jmeter的…

CAD插件实现:所有文字显示到列表、缩放、编辑——CAD-c#二次开发

当图中有大量文字&#xff0c;需要全部显示到一个列表时并缩放到需要的文字时&#xff0c;可采用插件实现&#xff0c;效果如下&#xff1a; 附部分代码如下&#xff1a; private void BtnSelectText_Click(object sender, EventArgs e){var doc Application.DocumentManager.…

Oracle数据库数据编程SQL<8 文本编辑器Notepad++和UltraEdit(UE)对比>

首先&#xff0c;用户界面方面。Notepad是开源的&#xff0c;界面看起来比较简洁&#xff0c;可能更适合喜欢轻量级工具的用户。而UltraEdit作为商业软件&#xff0c;界面可能更现代化&#xff0c;功能布局更复杂一些。不过&#xff0c;UltraEdit支持更多的主题和自定义选项&am…

Linux驱动开发练习案例

1 开发目标 1.1 架构图 操作系统&#xff1a;基于Linux5.10.10源码和STM32MP157开发板&#xff0c;完成tf-a(FSBL)、u-boot(SSBL)、uImage、dtbs的裁剪&#xff1b; 驱动层&#xff1a;为每个外设配置DTS并且单独封装外设驱动模块。其中电压ADC测试&#xff0c;采用linux内核…

Apache httpclient okhttp(1)

学习链接 Apache httpclient & okhttp&#xff08;1&#xff09; Apache httpclient & okhttp&#xff08;2&#xff09; httpcomponents-client github apache httpclient文档 apache httpclient文档详细使用 log4j日志官方文档 【Java基础】- HttpURLConnection…

微信小程序—路由

关于 app.json 中的配置 app.json 主要是对整个小程序进行一个全局的配置。 pages&#xff1a;在这个配置项目中&#xff0c;就可以配置小程序里面的页面&#xff0c;小程序默认显示 pages 数组中的第一个页面windows&#xff1a;主要配置和导航栏相关的 当然&#xff0c;在…

人工智能驱动的数据仓库优化:现状、挑战与未来趋势

1. 引言&#xff1a;数据仓库的演进与人工智能驱动优化的兴起 现代数据仓库的复杂性和规模正以前所未有的速度增长&#xff0c;这主要是由于数据量、种类和产生速度的急剧增加所致。传统的数据仓库技术在应对这些现代数据需求方面显得力不从心&#xff0c;这催生了对更先进解决…

LVS高可用负载均衡

一、项目图 二、主机规划 主机系统安装应用网络IPclientredhat 9.5无NAT192.168.72.115/24lvs-masterredhat 9.5ipvsadm&#xff0c;keepalivedNAT192.168.72.116/24 VIP 192.168.72.100/32lvs-backupredhat 9.5ipvsadm&#xff0c;keepalivedNAT192.168.72.117/24 VIP 192.168…

脑影像分析软件推荐 | JuSpace

目录 1. 软件界面 2.工具包功能简介 3.软件安装注意事项 参考文献&#xff1a; Dukart J, Holiga S, Rullmann M, Lanzenberger R, Hawkins PCT, Mehta MA, Hesse S, Barthel H, Sabri O, Jech R, Eickhoff SB. JuSpace: A tool for spatial correlation analyses of magne…

逛好公园的好处

逛公园和软件开发看似是两个不同的活动&#xff0c;但它们之间存在一些有趣的关联和相互促进的关系&#xff1a; 激发创造力&#xff1a;公园中的自然景观、多样的人群以及各种活动能为开发者带来新的灵感和创意。软件开发过程中&#xff0c;从公园中获得的创意可以帮助开发者设…

【网络安全】 防火墙技术

防火墙是网络安全防御的重要组成部分&#xff0c;它的主要任务是阻止或限制不安全的网络通信。在这篇文章中&#xff0c;我们将详细介绍防火墙的工作原理&#xff0c;类型以及如何配置和使用防火墙。我们将尽可能使用简单的语言和实例&#xff0c;以便于初学者理解。 一、什么…

文档的预解析

1. 预解析的核心目标 浏览器在正式解析&#xff08;Parsing&#xff09;HTML 前&#xff0c;会启动一个轻量级的 预解析器&#xff08;Pre-Parser&#xff09;&#xff0c;快速扫描文档内容&#xff0c;实现&#xff1a; 提前发现并加载关键资源&#xff08;如 CSS、JavaScrip…