如何删除PDF文档里的空白页

来源:互联网 发布:淘宝贷款没还会上门 编辑:程序博客网 时间:2024/04/30 06:30

日常工作生活中我们经常使用PDF,有时候你会发现PDF文档里面有一页或者好几页空白文档,很多人不知道如何删除这些空白页。网上众多的解决方案中,能解决这个问题的软件大都是收费软件。最近我发现了一个简单利落的免费控件——Free Spire.PDF,不仅免费,而且软件占用内存非常小。下面我跟大家分享一下如何在C#中使用免费控件FreeSpire.PDF来删除PDF文档中的空白页。

 

需要添加的命名空间:

using Spire.Pdf; using System.Drawing;

原PDF文件截图:


详细步骤和代码片段如下:


步骤1:创建一个新的PDF文档并加载文件。

PdfDocument document = new PdfDocument();document.LoadFromFile("Tornado.pdf");


步骤2:遍历PDF页面,检测页面内容,判断其是否为空白页,如果是空白页,则删除空白页。

for (int i = 0; i < document.Pages.Count; i++){    PdfPageBase originalPage = document.Pages[i];    if (originalPage.IsBlank())    {       document.Pages.Remove(originalPage);        i--;     }}

步骤3:保存并重新打开PDF文档。

document.SaveToFile("Tornadowithoutblankpage.pdf", FileFormat.PDF);System.Diagnostics.Process.Start("Tornadowithoutblankpage.pdf");

效果图:


全部代码:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using Spire.Pdf;using Spire.Pdf.Graphics;using System.Drawing;namespace Tornado{    class Program    {        static void Main(string[] args)        {            PdfDocument document = new PdfDocument();            document.LoadFromFile("Tornado.pdf");            for (int i = 0; i < document.Pages.Count; i++)            {                PdfPageBase originalPage = document.Pages[i];                if (originalPage.IsBlank())                {                    document.Pages.Remove(originalPage);                    i--;                }            }            document.SaveToFile("Tornadowithoutblankpage.pdf", FileFormat.PDF);            System.Diagnostics.Process.Start("Tornadowithoutblankpage.pdf");        }    }}


0 0