PDF格式的文档广泛应用于电子图书、产品说明、公司文告、网络资料、电子邮件等各种领域和场合。我们工作和学习中可能会遇到需要在文档中新插入一页来添加相应内容,或者删除文档中多出的空白页的情况。本篇文章将介绍如何实现以上文档操作。
示例要点
1.添加PDF空白页
1.1 在默认位置添加空白页(文档末)
1.2 在指定位置添加空白页
2.删除多余的空白页
工具使用
这里示例中使用的是免费版的.NET PDF控件 Free Spire.PDF for .NET 4.3(添加dll引用时,可在安装路径下的Bin文件夹中获取dll文件)
测试文档截图(文档包含两页内容):

1.添加PDF空白页
1.1 在默认位置,即文档末插入一张空白页
//创建PDF文档1,并加载测试文档
PdfDocument doc1 = new PdfDocument();
doc1.LoadFromFile("sample.pdf");
//添加一页空白页到文档(默认在文档最后一页添加)
doc1.Pages.Add();
//保存并打开文档
doc1.SaveToFile("result1.pdf");
System.Diagnostics.Process.Start("result1.pdf");
测试结果:

1.2 在指定位置插入空白页
//创建文档2,加载测试文档
PdfDocument doc2 = new PdfDocument();
doc2.LoadFromFile("sample.pdf");
//添加一页空白页作为第2页
doc2.Pages.Insert(1);
//保存并打开文档
doc2.SaveToFile("result2.pdf");
System.Diagnostics.Process.Start("result2.pdf");
测试结果:

2. 删除PDF空白页
这里的测试文档中,包含了两页空白页,一页空白页是没有任何内容的;另一页空白页是包含了空白图片的页面,看似没有内容,但是这样的页面实际上也是不需要的。

using Spire.Pdf;
using System.Drawing;
using Spire.Pdf.Graphics;
namespace DeleteBlankPage_PDF
{
class Program
{
static void Main(string[] args)
{
//应用许可证
Spire.License.LicenseProvider.SetLicenseFileName("license.elic.xml");
//创建PdfDocument类对象,并加载PDF文档
PdfDocument document = new PdfDocument();
document.LoadFromFile("Test.pdf");
//遍历文档中所有页面
for (int i = document.Pages.Count - 1; i >= 0; i--)
{
//诊断页面是否为空白页
if (document.Pages[i].IsBlank())
{
//删除空白页
document.Pages.RemoveAt(i);
}
else
{
//将PDF页转换为Bitmap图像
Image image = document.SaveAsImage(i, PdfImageType.Bitmap);
//诊断图片是否为空白图片
if (IsImageBlank(image))
{
//移除包含空白图片的页面
document.Pages.RemoveAt(i);
}
}
}
//保存并打开文档
document.SaveToFile("RemoveBlankPage.pdf", FileFormat.PDF);
System.Diagnostics.Process.Start("RemoveBlankPage.pdf");
}
//自定义方法IsImageBlank()诊断图片是否为空白图片
public static bool IsImageBlank(Image image)
{
//初始化Bitmap类实例,遍历文档中所有图片
Bitmap bitmap = new Bitmap(image);
for (int i = 0; i < bitmap.Width; i++)
{
for (int j = 0; j < bitmap.Height; j++)
{
Color pixel = bitmap.GetPixel(i, j);
if (pixel.R < 240 || pixel.G < 240 || pixel.B < 240)
{
return false;
}
}
}
return true;
}
}
}
测试结果:

(本文完)
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2557/viewspace-3157612/ ,如需转载,请注明出处,否则将追究法律责任。