LoginSignup
1
3

PDF文書の空白ページをどうやって削除しますか

Last updated at Posted at 2019-04-23

日常の仕事生活ではよくPDFを使いますが、PDF文書の中には一ページか何ページかの空白の文書があります。多くの人はこれらの空白のページをどうやって削除するか分かりません。ここでは、無料コントロール [Free Spire.PDF] (https://www.e-iceblue.com/Introduce/free-pdf-component.html)を使って、PDFドキュメントの空白ページを削除する方法を紹介します。

空白のページは通常、何も含まないページとして定義されます。Free Spire.PDFはPDFページが絶対的に空白かどうかを検出する方法を提供している。しかし、いくつかの「空白ページ」は実際に白い画像を含むことができます。IsBank()方法を使って、空白とは見なされません。これらの白を検出するには、空白ページではないので、カスタムメソッドIsImageBlank()が作成されました。

追加する名前空間が必要です:

using Spire.Pdf;
using System.Drawing;
using Spire.Pdf.Graphics;

完全コード:

namespace PDF
{
    class Program
    {
        static void Main(string[] args)
        {
            // PDF文書を読み込む
            PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile("Sample.pdf");

            //ページを巡回
            for (int i = 0; i < pdf.Pages.Count; i++)
            {
                //空白ページかどうかを判断する
                if (pdf.Pages[i].IsBlank())
                {
                    //空白のページを削除
                    pdf.Pages.RemoveAt(i);
                }
                else
                {
                    //空白のページでない場合は、ページを画像に変換します
                    Image image = pdf.SaveAsImage(i, PdfImageType.Bitmap);

                    //画像が空白かどうかを判断します
                    if (IsImageBlank(image))
                    {
                        //画像が空白の場合、対応するPDFページを削除します
                        pdf.Pages.RemoveAt(i);
                    }
                }
            }
            
            pdf.SaveToFile("Result.pdf", FileFormat.PDF);      
         }
        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;
        }
    }
}

サンプルドキュメント:
Sample.png
効果図:
Result.png

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3