文档半岛外围网上直营>>Spire.PDF教程-文档操作>>Spire.PDF 教程:如何在C#中检测和删除PDF中的空白页
Spire.PDF 教程:如何在C#中检测和删除PDF中的空白页
扫描双面打印纸张文档所创建的PDF可能包含空白页面。 也可以有意插入空白页面。 在本文中,您将学习如何使用C#使用Spire.PDF检测和删除PDF文件中的空白页面。
空白页面被广义地定义为不包含任何内容的页面。 Spire.PDF提供了一个方法IsBank来检测PDF页面是否绝对空白。 但是,一些“空白页”实际上可以包含白色图像,使用IsBank方法不会将其视为空白。 要检测这些白色但不是空白页面,我们使用在步骤1中定义的自定义方法IsImageBlank。
注意:此解决方案必须应用许可证才能完成,如果你没有授权请咨询。
Step 1: 创建一个自定义的方法来判断图像是否为空白。
public static bool IsImageBlank(Image image)
{
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;
}Step 2: 如上所述,该解决方案需要申请许可证,然后可以调用IsBlank方法和IsImageBlank方法来检测PDF页面是否为空白或包含空白图像,并使用Pages.RemoveAt(int index)方法删除空白页面。
static void Main(string[] args)
{
//apply license
Spire.License.LicenseProvider.SetLicenseFileName("license.elic.xml");
//create a PdfDocument object
PdfDocument document = new PdfDocument();
//load a sample file
document.LoadFromFile("sample.pdf");
//traverse each page in the document
for (int i = document.Pages.Count - 1; i >= 0; i--)
{
//detect if a page is blank
if (document.Pages[i].IsBlank())
{
//remove the blank page
document.Pages.RemoveAt(i);
}
else
{
//save PDF page as image
Image image = document.SaveAsImage(i, PdfImageType.Bitmap);
//detect if a page contains blank image
if (IsImageBlank(image))
{
//remove the page that contains blank image
document.Pages.RemoveAt(i);
}
}
}
//save to file
document.SaveToFile("RemoveBlankPage.pdf", FileFormat.PDF);
}输出:

完整C#代码
static void Main(string[] args)
{
//apply license
Spire.License.LicenseProvider.SetLicenseFileName("license.elic.xml");
//create a PdfDocument object
PdfDocument document = new PdfDocument();
//load a sample file
document.LoadFromFile("sample.pdf");
//traverse each page in the document
for (int i = document.Pages.Count - 1; i >= 0; i--)
{
//detect if a page is blank
if (document.Pages[i].IsBlank())
{
//remove the blank page
document.Pages.RemoveAt(i);
}
else
{
//save PDF page as image
Image image = document.SaveAsImage(i, PdfImageType.Bitmap);
//detect if a page contains blank image
if (IsImageBlank(image))
{
//remove the page that contains blank image
document.Pages.RemoveAt(i);
}
}
}
//save to file
document.SaveToFile("RemoveBlankPage.pdf", FileFormat.PDF);
}
//judge if an image is blank
public static bool IsImageBlank(Image image)
{
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;
}

QQ交谈
在线咨询

渝公网安备
50010702500608号

客服热线