Skip to content

Instantly share code, notes, and snippets.

@Gro-Tsen
Created October 21, 2021 14:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gro-Tsen/f24f02e7d1e8c13ee3a56916646046ca to your computer and use it in GitHub Desktop.
Save Gro-Tsen/f24f02e7d1e8c13ee3a56916646046ca to your computer and use it in GitHub Desktop.
Blank out part of PDF file
## Problem: how to produce a PDF that erases a rectangle in a page of an input PDF (without rasterizing)?
## I will assume for example that we need to erase the rectangle with origin at (5mm,148.5mm) and size (200mm,143.5mm)
## in page 42 of `input.pdf` and save to `output.pdf` - maybe also assuming that all pages are A4.
## NB: this is for printing only. Text below the rectangle WILL NOT be erased, merely obscured!
# Use Cairo Perl module tu create PDF file with white rectangle at specified position and dimension:
perl -e 'use Cairo; $surf = Cairo::PdfSurface->create("white.pdf", 210/25.4*72, 297/25.4*72); $cr = Cairo::Context->create($surf); $cr->rectangle(5/25.4*72,148.5/25.4*72,200/25.4*72,143.5/25.4*72); $cr->set_source_rgb(1,1,1); $cr->fill; $cr->show_page;'
# Use pdftk to extract pages before, at and after page 42:
pdftk input.pdf cat 1-41 output before.pdf
pdftk input.pdf cat 42 output tostamp.pdf
pdftk input.pdf cat 43-end output after.pdf
# Use pdftk to stamp the page with the white rectangle:
pdftk tostamp.pdf stamp white.pdf output stamped.pdf
# Reconstruct the PDF with from the parts:
pdftk before.pdf stamped.pdf after.pdf output output.pdf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment