Is there a way to flatten a .pdf image from the command line?
I found these 2 method via Google, in this thread titled: Re: Flattening PDF Files at the UNIX Command Line.
Method #1 - using Imagemagick's convert:$ convert -density 300 orig.pdf flattened.pdf
NOTE: The quality is reported to be so so with this approach.
Method #2 - Using pdf2ps -> ps2pdf:$ pdf2ps orig.pdf - | ps2pdf - flattened.pdf
NOTE: This method is reported to retain the image quality.
Ghostscript (gs) worked better than pdf2ps
and convert
for me. Quality was hardly degraded and file size is small.
gs -dSAFER -dBATCH -dNOPAUSE -dNOCACHE -sDEVICE=pdfwrite \
-sColorConversionStrategy=/LeaveColorUnchanged \
-dAutoFilterColorImages=true \
-dAutoFilterGrayImages=true \
-dDownsampleMonoImages=true \
-dDownsampleGrayImages=true \
-dDownsampleColorImages=true \
-sOutputFile=document_flat.pdf document_original.pdf
Found here: http://zeroset.mnim.org/2015/01/07/flatten-pdfs-with-ghostscript/
Although convert will keep the same file size I've found it to be slow.
The pdf2ps ps2pdf method is faster but I noticed for me it was increasing the file size.
pdftk is nice because it is not only fast but also retains a similar file size.
This is what I use to bulk flatten a directory.
function pdfflatten () {
pdftk "$1" output "$2" flatten
}
export pdfflatten
alias pdfflattenDIR='mkdir flattenedPDFs; for i in `seq $(ls *.pdf | wc -l)`; do a=`ls *.pdf | head -$i | tail -1`; pdfflatten "$a" flattenedPDFs/"$a"; done'