空白页面被广义地定义为不包含任何内容的页面。 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 blankpublic 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;}
Spire.PDF
标签:PDF
声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!