Scheduled maintenance — back soon.

~/blog/fix-pdf-file-for-epdfview

Fix PDF file for epdfview

14 Jan 2012

cat:linux

tags:#fix#ghostscript#pdf

I don't know why but there are PDF files which cannot be opened by app-text/epdfview. I found a solution which seems to fix PDF file in almost all the situations:

  • convert the PDF to PostScript file

  • convert the PostScript file back to PDF file

I am using the GhostScript for this but you can use also the pdf2ps and ps2pdf utilities for that. To reuse this logic later I have wrote a bash script (fixpdf) which automates these steps:

#!/bin/bash

out=$2
notify=1
ICON_RES="scalable"
ICON_EXT=".svg"

show_syntax()
{
	echo "Syntax error : $1."
	echo "Correct syntax :"
	echo "$(basename $0) inFile [outFile] , where :"
	echo " - inFile  : the input PDF file that have to be fixed"
	echo " - outFile : the new PDF file that will contains the fixed version of inFile"
	echo "Note: if outFile is omitted then outFile=inFile"
}

if [ -z "$1" ];then
	show_syntax "inFile not specified"
	exit 1
fi

filename=$(basename "$1")
extension=${filename##*.}
filename=${filename%.*}

if [ $extension != "pdf" ];then
	echo "Warning : inputFile has no .pdf extension. This is not a issue but maybe you have specified a wrong file."
fi

if [ -z $out ];then
	out=$1
	if [ $extension != "pdf" ];then
        	out="$out.pdf"
	fi
	if [ ! -w $out ];then
		err="Permission error : file $out is write-protected."
		echo $err
		if [ $notify -eq 1 ];then
			notify-send -i "/usr/share/icons/Tango/${ICON_RES}/actions/process-stop${ICON_EXT}" "Write error" "$err"
		fi
		exit 1
	fi
fi

if [ $notify -eq 1 ];then
	notify-send -i "/home/eugen/Pictures/icons/pdf-icon-48x48${ICON_EXT}" "$1" "Please wait while repairing the file.\nIt will be automatically opened with PDF Viewer."
fi

wait=". Please wait..."
ok="done!"

echo "[1/2] Convert $1 to PostScript format ($out.ps)$wait"
gs -q -sDEVICE=pswrite -sOutputFile=$out.ps -dNOPAUSE -dBATCH "$1"
echo $ok

echo "[2/2] Convert $out.ps back to PDF format ($out)$wait"
gs -q -sDEVICE=pdfwrite -sOutputFile=$out -dNOPAUSE -dBATCH $out.ps
echo $ok

rm $out.ps

Also, I have created a menu-context shortcut in the file explorer application I use in Xfce : thunar. For this I choose Edit->Configure custom action, I've added a new action with the following values:

  • name = Fix PDF file

  • command=fixpdf %f "" epdfview %f

Note: I've appended the """ epdfview %f" to the "fixpdf %f" command because I want that my PDF viewer (app-text/epdfview) to open the fixed file right after the file is fixed.

Comments

No comments yet

Be the first to leave a comment.

Leave a comment

Name and email required · moderated before publish · plain text only