用C#写个PDF批量合并工具简化日常工作
一. 前言
由于项目需要编写大量的材料,以及各种签字表格、文书等,最后以PDF作为材料交付的文档格式,过程文档时有变化或补充,故此处理PDF文档已经成为日常工作的一部分。
网上有各种PDF处理工具,总是感觉用得不跟手。最后回顾自己的需求总结为以下几项:
1.可以便捷、快速的对多份PDF进行合并。
2.可以从源PDF选取指定页码进行合并。
3.可以从单个PDF提取特定页码(拆分PDF)。
4.对多个PDF分组,合并作为最终PDF的导航书签,可快速定位。
5.统一合成后PDF页面尺寸,如统一为A4幅面。
6.操作尽量简便,支持文件拖放,不需要花巧的东西。
二、最终效果
首先,我们看看最终成品:
①.可以批量添加多个PDF到列表框中,也可以资料管理器将文件批量拖进来实现添加。
②.[可选]定义分组标题对文件进行分组,也作为合并后PDF的书签。
③.将列表中PDF批量合并到一个文件中。如果只有PDF,而且定义了页码范围,则转换为拆分功能。
④.显示PDF总页数,如果只需提取部分内容,可以定义页码范围。
⑤.可以更改合并后PDF页面的尺寸,统一为A4、B4或A5幅面。
三、功能实现
搜索发现github有个开源的PdfBinder1.2(https://github.com/schourode/pdfbinder)比较接近想要的效果,本着能省即省、成本最低、能效更高的原则,直接以此为基础进行扩展,开发自身所需的功能。
1.添加文件
这个比较简单,点击按钮后弹出选择对话框,将选择的文件逐一加到ListBox中。
private void addFileButton_Click(object sender, EventArgs e)
{
if (addFileDialog.ShowDialog() == DialogResult.OK)
{
foreach (string file in addFileDialog.FileNames)
{
AddInputFile(file);
}
UpdateUI();
}
}
其中AddInputFile函数单独编写是为了在拖放事件中复用。
public void AddInputFile(string file)
{
int Pages = 0;
switch (Combiner.TestSourceFile(file, out Pages))
{
case Combiner.SourceTestResult.Unreadable:
MessageBox.Show(string.Format(resources.GetString("Error.Unreadable.Text"), file), resources.GetString("Error.Unreadable.Title"), MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
case Combiner.SourceTestResult.Protected:
MessageBox.Show(string.Format(resources.GetString("Error.Protected.Text"), file), resources.GetString("Error.Protected.Title"), MessageBoxButtons.OK, MessageBoxIcon.Hand);
break;
case Combiner.SourceTestResult.Ok:
FileListBox.Items.Add(new PdfInfo() { Fullname = file, Filename = Path.GetFileName(file), Ranges = "", TotalPages = Pages });
break;
}
}
这里对PDF文件有效性进行了检查,而且添加到ListBox的是PdfInfo对象,它还记录了总页数、提取的页面范围等信息。
文件拖放的实现:
private void FileListBox_DragEnter(object sender, DragEventArgs e)
{
e.Effect = e.Data.GetDataPresent(DataFormats.FileDrop, false) ? DragDropEffects.All : DragDropEffects.None;
}
private void FileListBox_DragDrop(object sender, DragEventArgs e)
{
var fileNames = (string[])e.Data.GetData(DataFormats.FileDrop);
Array.Sort(fileNames);
foreach (var file in fileNames)
{
AddInputFile(file);
}
UpdateUI();
}
2.文件分组(书签)
using BookmarkName = System.String;
private void addBookmarkButton_Click(object sender, EventArgs e)
{
//未添加文件不处理
if (FileListBox.SelectedIndex < 0) return;
//如果选择的书签(组名),读取名称供修改
BookmarkName bookmark = "";
if (FileListBox.SelectedItem is BookmarkName)
bookmark = (BookmarkName)FileListBox.SelectedItem;
else
{
//如果选择的是文件,提取文件名作默认值
bookmark = ((PdfInfo)FileListBox.SelectedItem).Filename;
if (bookmark.Contains("."))
bookmark = bookmark.Substring(0, bookmark.LastIndexOf("."));
}
//如果输入有效,添加书签(组名)
BookmarkName newName = Interaction.InputBox(resources.GetString("SetBookmark.Prompt"), resources.GetString("SetBookmark.Title"), bookmark);
if (newName != "")
{
if (FileListBox.SelectedItem is BookmarkName)
FileListBox.Items[FileListBox.SelectedIndex] = newName;
else
{
FileListBox.Items.Insert(FileListBox.SelectedIndex, newName);
BookmarkCounter++;
}
}
}
3.定义页码范围
没有定义页码范围表示整个PDF进行合并。定义了页面范围,合并时只提取相应的页面进行合并。
页码范围的格式与常见的打印功能的页码定义相一致,如:1,2,3,6-9。
这个操作放在右键弹出菜单中实现。
private void mnuSetPageRange_Click(object sender, EventArgs e)
{
PdfInfo item = ((PdfInfo)FileListBox.SelectedItem);
string range = Interaction.InputBox(resources.GetString("SetPageRange.Prompt"), resources.GetString("SetPageRange.Title"), item.Ranges);
//内容未变更的不用处理
if (range != item.Ranges)
{
if (range == "")
{
((PdfInfo)FileListBox.Items[FileListBox.SelectedIndex]).Ranges = "";
return;
}
//针对逗号和空格做处理
string[] arr = range.Replace(",", ",").Replace(" ", "").Split(',');
range = "";
for (int i = 0; i < arr.Length; i++)
{
//用正则表达式判断有效性
if ("" == arr[i]) continue;
if (Regex.IsMatch(arr[i], @"^\d+$") || Regex.IsMatch(arr[i], @"^\d+-\d+$"))
range += ("" == range ? "" : ",") + arr[i];
else
{
MessageBox.Show(resources.GetString("Error.RangeValid"));
return;
}
}
//输入有效,更新
((PdfInfo)FileListBox.Items[FileListBox.SelectedIndex]).Ranges = range;
UpdateUI();
}
}
4.自定义显示
为了在ListBox中显示书签、总页数和提取页码范围,需要接管ListBox的绘制事件。
private void FileListBox_DrawItem(object sender, DrawItemEventArgs e)
{
...
StringFormat Formater = new StringFormat();
Formater.Alignment = StringAlignment.Near;
Formater.LineAlignment = StringAlignment.Center;
Formater.Trimming = StringTrimming.EllipsisPath;
Formater.FormatFlags = StringFormatFlags.NoWrap;
//绘制书签(分组名)
if (FileListBox.Items[e.Index] is BookmarkName)
{
//绘书签(分组名)图标
e.Graphics.DrawImage(addBookmarkButton.Image, e.Bounds.X, e.Bounds.Y + ((e.Bounds.Height - addBookmarkButton.Image.Height) /2));
//绘书签(分组名)
e.Graphics.DrawString((BookmarkName)FileListBox.Items[e.Index], e.Font, Brushes.Black
, new Rectangle(e.Bounds.X + addBookmarkButton.Image.Width, e.Bounds.Y, e.Bounds.Width - RIGHT_MARGIN, e.Bounds.Height), Formater);
return;
}
//绘制PDF文件名
PdfInfo item = (PdfInfo)FileListBox.Items[e.Index];
e.Graphics.DrawString(showNameButton.Checked ? item.Fullname : item.Filename, e.Font, Brushes.Black
, new Rectangle(e.Bounds.X + (BookmarkCounter > 0 ? (int)(addBookmarkButton.Image.Width * 1.5) : 0), e.Bounds.Y, e.Bounds.Width - RIGHT_MARGIN, e.Bounds.Height), Formater);
//绘制页码
Formater.Alignment = StringAlignment.Far;
e.Graphics.DrawString((item.Ranges == "" ? "" : item.Ranges + " | ")
+ string.Format(item.TotalPages>1 ? resources.GetString("Pages"): resources.GetString("Page"), item.TotalPages)
, e.Font, Brushes.Gray, e.Bounds, Formater);
}
5.定义页面尺寸
默认是原始尺寸(不做调整),可根据需要选择为A4、A5、B4。
private void OnPageSizeChanged(object sender, EventArgs e)
{
PageSizeButton.Tag = ((ToolStripMenuItem)sender).Tag;
mnuPageSize_Original.Checked = sender == mnuPageSize_Original;
mnuPageSize_A4.Checked = sender == mnuPageSize_A4;
mnuPageSize_A5.Checked = sender == mnuPageSize_A5;
mnuPageSize_B4.Checked = sender == mnuPageSize_B4;
if (mnuPageSize_Original.Checked)
PageSizeButton.Text = resources.GetString("PageSizeButton.Text");
else
PageSizeButton.Text = resources.GetString("PageSizeButton.Text") + ":" + ((ToolStripMenuItem)sender).Text;
}
6.PDF批量合并
这个比较长,有兴趣的可以到https://github.com/kacarton/PDFBinder2下载源码自己看,以下摘录核心部分。
private void combineButton_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
using (var combiner = new Combiner(saveFileDialog.FileName, (PDFBinder.PageSize)PageSizeButton.Tag))
{
progressBar.Visible = true;
this.Enabled = false;
for (int i = 0; i < FileListBox.Items.Count; i++)
{
if (FileListBox.Items[i] is BookmarkName)
combiner.AddBookmark((string)FileListBox.Items[i]);
else
combiner.AddFile(((PdfInfo)FileListBox.Items[i]).Fullname, ((PdfInfo)FileListBox.Items[i]).Ranges);
//刷新进度
progressBar.Value = (int)(((i + 1) / (double)FileListBox.Items.Count) * 100);
}
this.Enabled = true;
progressBar.Visible = false;
}
System.Diagnostics.Process.Start(saveFileDialog.FileName);
}
}
class Combiner : IDisposable
{
public void AddFile(string fileName, string range)
{
var reader = new PdfReader(fileName);
....
_document.NewPage();
//添加书签
if (!string.IsNullOrEmpty(this.BookMarkName))
{
Chapter _chapter = new Chapter("", 1);
_chapter.BookmarkTitle = this.BookMarkName;
_chapter.BookmarkOpen = true;
_document.Add(_chapter);
this.BookMarkName = null;
}
if (_newPageSize == PageSize.Original)
{
var page = _pdfCopy.GetImportedPage(reader, i);
_pdfCopy.AddPage(page);
}
else
{
var page = _writer.GetImportedPage(reader, i);
_document.Add(iTextSharp.text.Image.GetInstance(page));
}
reader.Close();
}
}
7.其他
UI同步、文件移除、上移、下移、排序、多语言支持这些比较简单就不展开了。
四、代码开源
源码已发布在github上,网址:PDFBinder2 https://github.com/kacarton/PDFBinder2,欢迎交流。
用C#写个PDF批量合并工具简化日常工作的更多相关文章
- word文档批量合并工具
#NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases. ; #Warn ; En ...
- 用python写图片格式批量处理工具
一.思路分析 其实,照片处理要求很简单,主要是两个方面:一个是调整图片尺寸(即宽x高),另一个是调整图片的大小(即压缩).为了实现这两个功能,利用python中的PIL库即可,其安装方法如下: pip ...
- —用python写图片格式批量处理工具
python爬取微博评论(无重复数据) 前言 一.整体思路 二.获取微博地址 1.获取ajax地址 2.解析页面中的微博地址 3.获取指定用户微博地址 三.获取主评论 四.获取子评论 1.解析子评论 ...
- 简化日常工作之三:自己写一个CI脚手架
程序员是诗人,应该写一些有思想意义的code,而不是每天重复造轮子,写一些低成本的业务逻辑. ---------------------------------一个脚本仔的心声 由于目前公司使用CI框 ...
- GIS地理工具案例教程——批量合并影像-批量镶嵌栅格
GIS地理工具案例教程--批量合并影像-批量镶嵌栅格 商务合作,科技咨询,版权转让:向日葵,135-4855__4328,xiexiaokui#qq.com 关键词:批量.迭代.循环.自动.智能.地理 ...
- GIS地理工具案例教程——批量合并影像
GIS地理工具案例教程——批量合并影像 商务合作,科技咨询,版权转让:向日葵,135—4855__4328,xiexiaokui#qq.com 描述:合并目录下的所有影像 功能:对指定工作空间下的栅格 ...
- 使用Python批量合并PDF文件(带书签功能)
网上找了几个合并pdf的软件,发现不是很好用,一般都没有添加书签的功能. 又去找了下python合并pdf的脚本,发现也没有添加书签的功能的. 于是自己动手编写了一个小工具,使用了PyPDF2. 下面 ...
- 极客工具,PDF合并工具
前言 这两天一番花两天的时间,重新用python和python图形化开发工具tkinter,完善了下PDF合并小工具,终于可以发布了. 工具目前基本功能已经完善,后期如果有反馈可以修复部分bug或完善 ...
- Python 写了一个批量生成文件夹和批量重命名的工具
Python 写了一个批量生成文件夹和批量重命名的工具 目录 Python 写了一个批量生成文件夹和批量重命名的工具 演示 功能 1. 可以读取excel内容,使用excel单元格内容进行新建文件夹, ...
- 用Java写一个PDF,Word文件转换工具
前言 前段时间一直使用到word文档转pdf或者pdf转word,寻思着用Java应该是可以实现的,于是花了点时间写了个文件转换工具 源码weloe/FileConversion (github.co ...
随机推荐
- oeasy教您玩转python - 9 - # 换行字符
换行字符 回忆上次内容 数制可以转化 bin(n)可以把数字转化为 2进制 hex(n)可以把数字转化为 16进制 int(n)可以把数字转化为 10进制 编码和解码可以转化 encode 编码 ...
- 学习笔记--Java方法基础
Java方法基础 那么什么是方法呢? public class MethodTest01{ public static void main(String[] args){ // 需求1:编写程序计算 ...
- 有向图_节点间路径路径--python数据结构
字典创建有向图,查找图节点之间的路径,最短路径,所有路径 """ 参考文档: https://www.python.org/doc/essays/graphs/ &quo ...
- JavaScript小面试~什么是深拷贝,什么是浅拷贝,深拷贝和浅拷贝的区别,如何实现深拷贝
深拷贝:就是在复制数据或者对象的时候,将其内存中值复制过来. 浅拷贝:就是在复制数据或者对象的时候,是将其引用复制过来. 深拷贝和浅拷贝的区别:深拷贝复制的是被复制数据或者对象的值,复制的数据或对象会 ...
- vue小知识~注入provide!
注入表示的是将该组件的相关值,方法,实例向后代组件注入. 祖先元素中定义注入: export default { provide() { return { provideName: provideVa ...
- Python 实现行为驱动开发 (BDD) 自动化测试详解
在当今的软件开发领域,行为驱动开发(Behavior Driven Development,BDD)作为一种新兴的测试方法,逐渐受到越来越多开发者的关注和青睐.Python作为一门功能强大且易于使 ...
- Springboot + Vue ElementUI 实现MySQL可视化
一.功能展示: 效果如图: DB连接配置维护: Schema功能:集成Screw生成文档,导出库的表结构,导出表结构和数据 表对象操作:翻页查询,查看创建SQL,生成代码 可以单个代码文件下载,也 ...
- 国产显卡如何正确打开 —— Windows平台下使用驱动精灵为国产显卡更新驱动(兆芯平台)
买了一个国产的电脑,全国产,CPU慢些也就忍了,软件兼容性差.稳定性差也忍了,大不了就用来上网看电影嘛,关键问题是这个国产显卡放电影居然有些卡,播放电影的时候存在明显的卡顿感,这简直是把国产电脑在我脑 ...
- B站基于Apache DolphinScheduler的一站式大数据集群管理平台(BMR)初窥
一.背景 大数据服务是数据平台建设的基座,随着B站业务的快速发展,其大数据的规模和复杂度也突飞猛进,技术的追求也同样不会有止境. B站一站式大数据集群管理平台(BMR),在千呼万唤中孕育而生.本文简单 ...
- 数字名片工具 BBlog:使用一个链接,快速创建和分享你的信息主页和数字花园
数字名片 BBlog:使用一个链接,快速创建和分享你的信息主页和数字花园 随着移动互联网技术的快速发展,数字名片产品已成为现代社交和网络营销的重要工具.数字名片可以帮助个人和企业在各种场合中展示和分享 ...