背景说明
现在流行使用电子发票,财务为了保存还是需要打印出来备份。我之前使用WPS合并PDF文件,然后打印合并以后文件,大大提高了效率。后来WPS合并PDF文件的功能对免费用户一次合并的pdf文件数量进行了限制,我平常也不怎么用WPS,也就没有充值。最近快过年了,写了个极其简单的PDF文件合并小工具,分享给需要的人。
关键代码
使用PDFsharp库,PDFsharp wiki官网:http://www.pdfsharp.net/wiki/MainPage.ashx
合并文件的代码:
class PdfSharpTool
{
public void CombinePdfFiles(string folderPath)
{
try
{
//读取文件夹中的文件夹
int fileCount = 0;
int pageCount = 0;
PdfDocument outPdfFile = new PdfDocument();
List<string> fileNameList = new List<string>();
List<string> fileError = new List<string>();
foreach(var filename in Directory.GetFiles(folderPath))
{
if (Path.GetExtension(filename) == ".pdf")
{
try
{
PdfDocument pdfFile = PdfReader.Open(filename, PdfDocumentOpenMode.Import);
fileCount++;
pageCount += pdfFile.PageCount;
foreach (var pdfPage in pdfFile.Pages)
{
outPdfFile.AddPage(pdfPage);
fileNameList.Add(string.Format("{0} {1}", Path.GetFileName(filename), pdfFile.PageCount));
}
}
catch (Exception ex)
{
fileError.Add(Path.GetFileName(filename));
}
}
}
string combineResult = "";
if (fileCount > 0)
{
//导出pdf文件
string timeTag = DateTime.Now.ToString("MMdd_HH_mm_ss");
SavePdfFile(folderPath + "\\合并", timeTag + ".pdf", outPdfFile);
fileNameList.Add(string.Format("共 {0} 个文件,共 {1} 页。", outPdfFile, pageCount));
if (fileError.Count > 0)
{
fileNameList.Add("合并失败文件:");
foreach (string p in fileError)
{
fileNameList.Add(p);
}
}
SaveTxtFile(folderPath + "\\合并", timeTag + ".txt", fileNameList);
}
combineResult = string.Format("合并文件数量:{0}", fileCount);
if (fileError.Count > 0)
{
combineResult += "\r\n";
combineResult += string.Format("合并失败文件数量:{0}", fileError.Count);
}
MessageBox.Show(combineResult);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void SavePdfFile(string folderPath, string fileName, PdfDocument pdfFile)
{
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
pdfFile.Save(folderPath + "\\" + fileName);
}
private void SaveTxtFile(string folderPath, string fileName,List<string> content)
{
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
string fileFullPath = folderPath + "\\" + fileName;
if (!File.Exists(fileFullPath))
{
var newFile = File.CreateText(fileFullPath);
newFile.Close();
}
using (StreamWriter sw = new StreamWriter(fileFullPath,true))
{
foreach (string line in content)
{
sw.WriteLine(line);
}
sw.Close();
}
}
}
调用:
PdfSharpTool pdfTool = new PdfSharpTool();
pdfTool.CombinePdfFiles(folderPath);//folderPath为pdf文件所在的文件夹
执行完以后会生成一个“合并”文件夹,在文件夹中有合并以后的pdf文件和合并文件的详细结果(TXT文件)。
代码分享
我新建了一个WindowForm项目,分享给需要的人,里面打包了一个自解压的exe文件。链接:
https://download.csdn.net/download/sleepingboy888/87378998