写一个合并PDF的工具
2024-01-21 本文已影响0人
zhouf_cq
经常需要处理一些PDF合并的场景,虽然也有在线的工具可以使用,也想着可以练练手,便试一下
使用场景
- Windows环境
- 命令行方式
- 命令行参数传递要合并的pdf文件
准备在VS2022中用C#写一个控制台程序,运行时通过命令行参数传入待处理的pdf
创建项目
创建C#控制台项目,并导入iTextSharp库,此处使用的是5.5.13.3版本的
完成合并代码
代码主要是调用iTextShap的功能进行合并,功能包含处理参数,处理输出文件名,调用方法合并,代码量也不多,具体如下
static void Main(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("请提供至少两个PDF文件用于合并。");
return;
}
string[] fileNames = args;
string outputFileName = GetOutputFileName(fileNames[0]);
try
{
MergePDFs(fileNames, outputFileName);
Console.WriteLine($"PDF files merged successfully. Merged file: {outputFileName}");
}
catch (Exception ex)
{
Console.WriteLine($"Error merging PDF files: {ex.Message}");
}
}
// 处理生成文件名
static string GetOutputFileName(string firstFileName)
{
string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
string fileName = Path.GetFileNameWithoutExtension(firstFileName);
return $"【合并文件】{fileName}_{timestamp}.pdf";
}
// 处理合并操作
public static void MergePDFs(string[] fileNames, string outFile)
{
Document document = new Document();
using (FileStream newFileStream = new FileStream(outFile, FileMode.Create))
{
PdfCopy writer = new PdfCopy(document, newFileStream);
document.Open();
foreach (string fileName in fileNames)
{
PdfReader reader = new PdfReader(fileName);
PdfReader.unethicalreading = true;
reader.ConsolidateNamedDestinations();
writer.AddDocument(reader);
reader.Close();
}
writer.Close();
document.Close();
}
}
编译生成exe文件,就可以调用了
配置运行
可以直接将exe所在的目录配置在系统的Path环境变量里,就可以在任何目录中使用了。本机电脑上已配置了一个脚本目录,就在里面加一个批处理,调用此exe,就不用在Path变量中加太多的内容了,批处理命名为mergepdf.bat
,内容如下
@echo off
set EXE_PATH=D:\path\to\your\MergePDF.exe
if not exist %EXE_PATH% (
echo Error: Executable not found.
exit /b 1
)
if "%~1"=="" (
echo Usage: %0 file1.pdf file2.pdf ...
exit /b 1
)
%EXE_PATH% %*
后面就可以在pdf所在目录调用此批处理完成对pdf文件的合并操作啦。今天又完成了一个小任务,记录一下。