DEV Community

sunshey
sunshey

Posted on

How to Remove Blank Pages from PDF in the Browser with Vue 3 and pdf-lib

Removing blank pages from PDFs in the browser requires image analysis and page content detection. Here's how to build a browser-based blank page removal tool with Vue 3 and pdf-lib.

The challenge: Detecting blank pages

Blank page detection involves:

  1. Analyzing each page's visual content
  2. Distinguishing between truly blank and near-blank pages
  3. Handling different types of "blank" pages (white, faint, hidden content)
  4. Providing accurate detection with minimal false positives

The stack

  • Vue 3 with Composition API
  • pdf-lib for PDF manipulation
  • Canvas API for page rendering and analysis
  • Vite for bundling

The core implementation

<script setup lang="ts">
import { ref, computed } from 'vue'
import { PDFDocument } from 'pdf-lib'

const file = ref<File | null>(null)
const blankPages = ref<number[]>([])
const removing = ref(false)
const result = ref<Uint8Array | null>(null)

// Detect blank pages using Canvas rendering
async function detectBlankPages(): Promise<number[]> {
  if (!file.value) return []

  const arrayBuffer = await file.value.arrayBuffer()
  const pdf = await PDFDocument.load(arrayBuffer)
  const pages = pdf.getPages()
  const blankIndices: number[] = []

  for (let i = 0; i < pages.length; i++) {
    const page = pages[i]
    const isEmpty = await isPageBlank(page)
    if (isEmpty) {
      blankIndices.push(i)
    }
  }

  return blankIndices
}

// Check if a page is blank by rendering and analyzing
async function isPageBlank(page: any): Promise<boolean> {
  // Render page to canvas
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')!

  // Get page dimensions and render
  const width = page.getWidth()
  const height = page.getHeight()
  canvas.width = width
  canvas.height = height

  // Render page content (using pdf.js for rendering)
  // Then analyze pixel data for blankness

  const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
  const pixels = imageData.data

  // Count non-white pixels
  let nonWhitePixels = 0
  const totalPixels = pixels.length / 4
  const threshold = 240 // Pixel value threshold for "white"

  for (let i = 0; i < pixels.length; i += 4) {
    const r = pixels[i]
    const g = pixels[i + 1]
    const b = pixels[i + 2]

    // Check if pixel is white or near-white
    if (r < threshold || g < threshold || b < threshold) {
      nonWhitePixels++
    }
  }

  // Consider page blank if less than 1% non-white pixels
  return (nonWhitePixels / totalPixels) < 0.01
}

async function removeBlankPages() {
  if (!file.value || blankPages.value.length === 0) return
  removing.value = true

  const arrayBuffer = await file.value.arrayBuffer()
  const pdf = await PDFDocument.load(arrayBuffer)
  const pages = pdf.getPages()

  // Remove blank pages in reverse order to maintain indices
  const sortedBlankPages = [...blankPages.value].sort((a, b) => b - a)
  for (const index of sortedBlankPages) {
    pages[index].detach()
  }

  result.value = await pdf.save()
  removing.value = false
}
</script>
Enter fullscreen mode Exit fullscreen mode

Key implementation details

1. Canvas-based page analysis

Render each page to canvas and analyze pixel data:

const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
const pixels = imageData.data

// Count non-white pixels
for (let i = 0; i < pixels.length; i += 4) {
  if (r < threshold || g < threshold || b < threshold) {
    nonWhitePixels++
  }
}
Enter fullscreen mode Exit fullscreen mode

2. Blank detection threshold

Adjust sensitivity based on document type:

const isBlank = (nonWhitePixels / totalPixels) < blankThreshold
// blankThreshold: 0.01 = 1% non-white pixels
Enter fullscreen mode Exit fullscreen mode

3. Safe page removal

Remove pages in reverse order to maintain correct indices:

const sortedBlankPages = [...blankPages.value].sort((a, b) => b - a)
for (const index of sortedBlankPages) {
  pages[index].detach()
}
Enter fullscreen mode Exit fullscreen mode

4. Progress feedback

Show detection progress for large PDFs:

const progress = computed(() => {
  if (!pages.value.length) return 0
  return Math.round((blankPages.value.length / pages.value.length) * 100)
})
Enter fullscreen mode Exit fullscreen mode

Limitations

Rendering quality

Canvas rendering may not capture all page content accurately.

Solution: Use high-quality rendering settings and multiple detection methods.

Hidden content

Some "blank" pages may have hidden text or images.

Solution: Use advanced detection with multiple analysis methods.

Performance

Large PDFs with many pages may take time to analyze.

Solution: Process pages in batches or use Web Workers.

Summary

Building a browser-based blank page removal tool involves:

  1. Rendering each page to canvas
  2. Analyzing pixel data for blankness
  3. Collecting blank page indices
  4. Removing pages in reverse order
  5. Saving and downloading the cleaned PDF

Try it at en.sotool.top/remove-blank-pages.

Top comments (0)