Created
August 15, 2022 21:08
-
-
Save thomaslima/f9a26532e29142e9e1284571955842c5 to your computer and use it in GitHub Desktop.
Crop PDF figures with Latex (Macos, Linux)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# This extracts one page out of a multi-page PDF | |
# (such as the type exported from Powerpoint). | |
# Then it crops it to tight margins | |
# Suppose you have a powerpoint with some pages being paper figures | |
# and a LaTex project that references pdf figures by name | |
# Old workflow | |
# Export, open multi-page PDF, manually drag a crop box, copy, make new PDF, save that as a new file, change its name, click "yes, replace" | |
# New workflow | |
# 1. In Powerpoint, make some edits | |
# 2. In Powerpoint, export as PDF | |
# 3. In Terminal, run "multipagepdfcrop" with correct page and figure name | |
# 4. In LaTeX, recompile. The figure has updated. | |
# | |
# Usage: multipagepdfcrop infile page_number [outfile] | |
# | |
# Arguments: | |
# infile | |
# page number (1-indexed) | |
# outfile (optional): default is <infile>-<page>.pdf | |
# Author: Alex Tait (atait@ieee.org) | |
# Date: 9/18/2017 | |
# Option/argument handling | |
if [ $1 = "-h" ]; then | |
echo "$0: extracts and tight crops one page of a multi-page PDF" | |
echo "Usage: $0 infile page [outfile[.pdf]]" | |
echo "Page number is 1-indexed" | |
exit | |
fi | |
if [ $# -ne 2 ] && [ $# -ne 3 ]; then | |
echo "Wrong number of arguments, must be 2 or 3" | |
exit | |
fi | |
INFILE=$1 | |
PAGE=$2 | |
if [ $# -eq 3 ]; then | |
OUTFILE=$3 | |
else | |
# Get the input file without a possible .pdf suffix | |
# Then create the new output filename | |
inFileLength=${#INFILE} | |
if [ ${INFILE:inFileLength - 4} == ".pdf" ]; then | |
INFILEROOT=${INFILE:0:inFileLength - 4} | |
else | |
INFILEROOT=$INFILE | |
fi | |
OUTFILE="$INFILEROOT-$PAGE.pdf" | |
fi | |
# Ensure outfile ends with .pdf | |
inFileLength=${#OUTFILE} | |
if [ ${OUTFILE:outFileLength - 4} != ".pdf" ]; then | |
OUTFILE="$OUTFILE.pdf" | |
fi | |
# Extract single page | |
gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -dFirstPage=$PAGE -dLastPage=$PAGE -sOUTPUTFILE=$OUTFILE $INFILE | |
# Crop tight | |
pdfcrop $OUTFILE $OUTFILE > /dev/null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@atait I use this very very often. Putting it here for posterity.