↑ arvau

ArchWiki / PDF, PS and DjVu

es:PDF, PS and DjVu zh-hans:PDF、PS 与 DjVu This article covers software to view, edit and convert PDF, PostScript (PS), DjVu (déjà vu) and XPS files.

Engines

Viewers

Framebuffer

Graphical

Some web browsers can display PDF files, for example with PDF.js.

Comparison

  1. Optional dependency needs to be installed

PDF forms

The PDF forms column in the above table refers to AcroForms support. If you do not need your input to be directly extractable from the PDF, you can also use the applications in #Graphical PDF editing to put text on top of a PDF. PDF forms can be created with LibreOffice Writer (View > Toolbars > Form Controls) and the advanced PDF editors.

The proprietary and deprecated XFA format for forms is not fully supported by Popplerhttps://gitlab.freedesktop.org/poppler/poppler/issues/199https://gitlab.freedesktop.org/poppler/poppler/issues/530 and only supported by Adobe Reader and Master PDF Editor.

Alternatively, web browsers such as Firefox or Chromium feature a built-in PDF viewer capable of filling out forms.

Graphical PDF editing

Editors that can import PDF files

Basic editors

Cropping tools

Advanced editors

Comparison of advanced editors

PDF tools

See also Ghostscript.

Command snippets

Create a PDF from images

With GraphicsMagick:

$ gm convert 1.jpg 2.jpg 3.jpg out.pdf

With ImageMagick:

$ magick 1.jpg 2.jpg 3.jpg out.pdf

Note that ImageMagick's output is lossy. For lossless PDF creation from jpeg, use img2pdf.

Concatenate PDFs

With Ghostscript:

$ gs -dNOPAUSE -sDEVICE=pdfwrite -sOUTPUTFILE=out.pdf -dBATCH 1.pdf 2.pdf 3.pdf

With PDFtk:

$ pdftk 1.pdf 2.pdf 3.pdf cat output out.pdf

With Poppler:

$ pdfunite 1.pdf 2.pdf 3.pdf out.pdf

With QPDF:

$ qpdf --empty --pages 1.pdf 2.pdf 3.pdf -- out.pdf

Extract text from PDF

With Poppler and maintaining the layout:

$ pdftotext -layout in.pdf out.txt

See also pdftotext(1).

With calibre:

$ ebook-convert in.pdf out.txt

Results vary between applications, depending on the PDF file.

Decrypt a PDF

This section lists commands to decrypt a PDF to an unencrypted file. Note that most PDF viewers also support encrypted PDFs.

With PDFtk:

$ pdftk in.pdf input_pw password output out.pdf

With Poppler to PostScript:

$ pdftops -upw password in.pdf out.ps

With QPDF:

$ qpdf --decrypt --password=password in.pdf out.pdf

Forgotten passwords might be recovered with pdfcrack, see pdfcrack(1).

Encrypt a PDF

The user password is used for encryption, the owner password to restrict operations once the document is decrypted, for more information, see Wikipedia:PDF#Encryption and signatures.

With PDFtk:

$ pdftk in.pdf output out.pdf user_pw password

With PoDoFo:

$ podofoencrypt -u user_password -o owner_password in.pdf out.pdf

With QPDF:

$ qpdf --encrypt user_password owner_password key_length -- in.pdf out.pdf

where key_length can be 40, 128 or 256.

Extract images from a PDF

With poppler, saving images as JPEG:

$ pdfimages infile.pdf -j outfileroot

Extract page range from PDF, split multipage PDF document

With Ghostscript as a single filehttps://forums.freebsd.org/threads/split-pdf-file.58902/#post-336971

$ gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER -dFirstPage=first -dLastPage=last -sOutputFile=outfile.pdf infile.pdf

With PDFtk as a single file:

$ pdftk infile.pdf cat first-last output outfile.pdf

With Poppler as separate files:

$ pdfseparate -f first -l last infile.pdf outfileroot-%d.pdf

With QPDF as a single file:

$ qpdf --empty --pages infile.pdf first-last -- outfile.pdf

With mutool as a single file:

$ mutool clean -g infile.pdf outfile.pdf first-last

Impose a PDF (nup)

PDF Imposition is the process by which multiple input pages are combined into one output page, layed out into a rowsxcolumns grid.

It can be done with pdfjam (notice that wrapper scripts such as pdfnup and pdfbook are deprecated):

$ pdfjam --nup rowsxcolumns input.pdf --outfile output.pdf

or with pdfsak:

$ pdfsak --input-file input.pdf --output output.pdf --nup rows columns

Inspect metadata

With ExifTool:

$ exiftool -All file.pdf

With Poppler:

$ pdfinfo file.pdf

Remove metadata

Using ExifTool

With ExifTool:

$ exiftool -All= -overwrite_original input.pdf
$ mv input.pdf /tmp/temp.pdf
$ qpdf --linearize /tmp/temp.pdf input.pdf

The linearize step is needed to prevent recovery of deleted metadata. See this SuperUser question and the related ExifTool forum thread.

Using pdftk

Many PDFs store document metadata using both an Info dictionary (old school) and an XMP stream (new school). This pdftk command remove the XMP stream from the PDF altogether. It does not remove the Info dictionary.

Note that objects inside the PDF might have their own, separate XMP metadata streams, and that this command does not remove those. It only removes the PDF’s document‐level XMP stream.

$ pdftk input.pdf drop_xmp output output.pdf

Reduce size of a PDF

PDF size can be reduced by setting an appropriate optimization or compression level.

With Ghostscript one of:

$ ps2pdf -dPDFSETTINGS=/screen in.pdf out.pdf

or

$ gs -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/printer -sOutputFile=out.pdf in.pdf

For different settings see the documentation.

There is also shrinkpdf, a script wrapping gs.

Rasterize a PDF

These commands will convert your PDF into images.

With GraphicsMagick to convert a specific page into an image file:

$ gm convert -density dpi infile.pdf[page] outfile.jpg

With ImageMagick to convert a specific page into an image file:

$ magick convert -density dpi infile.pdf[page] outfile.jpg

With ImageMagick to convert all pages into another PDF file composed by an image file per page:

$ magick convert -density dpi infile.pdf outfile.pdf

This will increase the file size of your PDF substantially. Use it for example if your printer is not able to print your PDF correctly.

With Poppler to convert all pages into one image file per page:

$ pdftoppm -jpeg -r dpi infile.pdf outfileroot

With Poppler to convert a specific page into an image file:

$ pdftoppm -jpeg -r dpi -f page -singlefile infile.pdf outfileroot

Split PDF pages

With mupdf-tools to split every page vertically into two pages:

$ mutool poster -y 2 in.pdf out.pdf

Can be used to undo simple imposition.

Add an image

Adding an image to any location in a PDF can be done

Details on these and other solutions can be found on StackExchange.

Add digital signature to PDF

jsignpdf can digitally sign PDF files with X.509 certificates in GUI and CLI.

Readers such as Okular and MuPDF can sign PDFs with digital signatures. This requires a PFX certificate, which can be created with an OpenSSL command:

$ openssl req -x509 -days 365 -newkey rsa:2048 -keyout cert.pem -out cert.pem
$ openssl pkcs12 -export -in cert.pem -out cert.pfx

MuPDF users can then sign PDFs with the cert.pfx using the graphical interface, or its mutool-sign tool.

Okular users must import cert.pfx into a certificate store such as the one in the default Firefox profile.https://docs.kde.org/trunk5/en/okular/okular/signatures.html With Firefox this is done through Settings > Privacy & Security > View Certificates > Your Certificates > Import and selecting cert.pfx. Afterwards Okular will offer this certificate to be used when signing PDFs.

Libreoffice can also sign PDFs.https://help.libreoffice.org/6.3/en-US/text/shared/guide/digital_signatures.html

Removing annotations from a PDF

With pdftk https://stackoverflow.com/questions/49598797/remove-pdf-annotations-via-command-line/49614525#49614525:

$ pdftk in.pdf output - uncompress | sed '/^\/Annots/d' | pdftk - output out.pdf compress

With perl-cam-pdf:

$ rewritepdf.pl -C in.pdf out.pdf

See https://superuser.com/a/1051543 for more information.

Add page numbers

With pdfsak:

$ pdfsak --input-file input.pdf --output output.pdf --text "\large \$page/\$pages" br 0.99 0.99 --latex-engine xelatex --font "Noto Regular"

Add page labels

Page labels are logical page numbers shown in the navigation bar of your PDF reader. They are useful for example if the first pages of the PDF are indices numbered with roman numbers (I, II, etc.), while the page numbered "1" corresponds to a PDF page greater than 1, and you want the page number shown in the navigation bar to corresponds to the page number shown in the physical page.

This should not be confused with adding page numbers into a physical page. See section 12.4.2 of PDF reference to better understand page labels.

Using pagelabels-py, let's say we have a PDF named my_document.pdf, that has 12 pages.

  • Pages 1 to 4 should be labelled Intro I to Intro IV.

  • Pages 5 to 9 should be labelled 2 to 6.

  • Pages 10 to 12 should be labelled Appendix A to Appendix C

  • We can issue the following list of commands:

    $ python3 -m pagelabels --delete "my_document.pdf"
    $ python3 -m pagelabels --startpage 1 --prefix "Intro " --type "roman uppercase" "my_document.pdf"
    $ python3 -m pagelabels --startpage 5 --firstpagenum 2 "my_document.pdf"
    $ python3 -m pagelabels --startpage 10 --prefix "Appendix " --type "letters uppercase" "my_document.pdf" 
  • pagelabels-py will convert your file to PDF 1.3 specification

  • Using pdftk, create a metadata.txt file with labels:

    PageLabelBegin
    PageLabelNewIndex: 1
    PageLabelStart: 1
    PageLabelPrefix: Cover
    PageLabelNumStyle: NoNumber
    PageLabelBegin
    PageLabelNewIndex: 2
    PageLabelStart: 1
    PageLabelPrefix: Back Cover
    PageLabelNumStyle: NoNumber
    PageLabelBegin
    PageLabelNewIndex: 3
    PageLabelStart: 1
    PageLabelNumStyle: LowercaseRomanNumerals
    PageLabelBegin
    PageLabelNewIndex: 27
    PageLabelStart: 1
    PageLabelNumStyle: DecimalArabicNumerals 
  • Where:

    1. PageLabelBegin: signal a new page label definition will follow

    2. PageLabelNewIndex: is the PDF page index from which the numbering style applies, counting from one. The numbering style will continue until the next page label or, if there are no more page labels, until the end of the document.

    3. PageLabelStart: is the starting number. For example, if you specify 5 here, the pages will be numbered 5, 6, 7, ...

    4. PageLabelPrefix: a text to put before the number in page labels.

    5. PageLabelNumStyle: can be DecimalArabicNumerals, UppercaseRomanNumerals, LowercaseRomanNumerals, UppercaseLetters, LowercaseLetters or NoNumber.

    Then use:

    pdftk book.pdf update_info_utf8 metadata.txt output book-with-metadata.pdf

See this SuperUser question for more details.

Extract bookmarks

With pdftk:

$ pdftk file.pdf dump_data_utf8 | grep '^Bookmark'

With qpdf:

$ qpdf --json --json-key=outlines file.pdf

See https://unix.stackexchange.com/questions/143886/how-to-extract-bookmarks-from-a-pdf-file for more information.

Add bookmarks

With pdftk

Create a text file bookmark_definitions.txt with bookmark definitions in the following format:


BookmarkBegin
BookmarkTitle: Chapter 1
BookmarkLevel: 1
BookmarkPageNumber: 1
BookmarkBegin
BookmarkTitle: Chapter 1.1
BookmarkLevel: 2
BookmarkPageNumber: 2
BookmarkBegin
BookmarkTitle: Chapter 1.2
BookmarkLevel: 2
BookmarkPageNumber: 3
BookmarkBegin
BookmarkTitle: Chapter 1.3
BookmarkLevel: 2
BookmarkPageNumber: 4
BookmarkBegin
BookmarkTitle: Chapter 1.3.1
BookmarkLevel: 3
BookmarkPageNumber: 5
BookmarkBegin
BookmarkTitle: Chapter 2
BookmarkLevel: 1
BookmarkPageNumber: 6

Where

  1. BookmarkBegin: signal a new bookmark definition

  2. BookmarkTitle: the title of the bookmark

  3. BookmarkLevel: the level of the bookmark in the hierarchy

  4. BookmarkPageNumber: the page number the bookmark redirects to

In this example, the above file will create the following bookmark structure:

Chapter 1

  • Chapter 1.1

  • Chapter 1.2

Chapter 1.3

  • Chapter 1.3.1

  • Chapter 2

Apply the bookmarks with the following command:

$ pdftk input.pdf update_info_utf8 bookmark_definitions.txt output output.pdf

Extract pages contained within a bookmark

To extract the pages contained within a bookmark, you can use pdf_extbook-git.

With pdf_extbook file you will be prompted on what bookmark whose pages you want to extract and where to save it. To extract all bookmarks of a given hierarchical level:

$ pdf_extbook file -a level output_file_stem

Remove blank pages

One can use the following script to remove blank pages from a PDF file (credit: SuperUser post):


#!/bin/sh

IN="$1"
filename=$(basename "${IN}")
filename="${filename%.*}"
PAGES=$(pdfinfo "$IN" | grep ^Pages: | tr -dc '0-9')

non_blank() {
	for i in $(seq 1 $PAGES); do
		PERCENT=$(gs -o - -dFirstPage=${i} -dLastPage=${i} -sDEVICE=ink_cov "$IN" | grep CMYK | nawk 'BEGIN { sum=0; } {sum += $1 + $2 + $3 + $4;} END { printf "%.5f\n", sum } ')
		if [ $(echo "$PERCENT > 0.001" | bc) -eq 1 ]; then
			echo $i
			#echo $i 1>&2
		fi
		echo -n . 1>&2
	done | tee "$filename.tmp"
	echo 1>&2
}

set +x
pdftk "${IN}" cat $(non_blank) output "${filename}_noblanks.pdf"

Use it like pdf_remove_blank_pages input.pdf.

The script needs pdftk, nawk and ghostscript.

Find fonts used in a PDF

The pdffonts(1) command (from poppler), can be used to find which fonts a PDF uses and if they have been embedded in it or not:


name                                 type              encoding         emb sub uni object ID
------------------------------------ ----------------- ---------------- --- --- --- ---------
Times-Roman                          Type 1            Custom           no  no  no       8  0
Times-Italic                         Type 1            Standard         no  no  no       9  0
Times-Bold                           Type 1            Standard         no  no  no       7  0
Helvetica                            Type 1            Standard         no  no  no      34  0
Helvetica-Bold                       Type 1            Standard         no  no  no      35  0
$ pdffonts file.pdf

This can be used when having issues displaying properly the text in a PDF, to determine if missing fonts or their metric-compatible equivalent need to be installed.

Repair broken PDF file

With ghostscript:

$ gs -o repaired.pdf -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress corrupted.pdf

With poppler:

$ pdftocairo -pdf corrupted.pdf repaired.pdf

With mupdf-tools:

$ mutool clean corrupted.pdf repaired.pdf

Reference: https://superuser.com/q/278562

Convert PDF to PDF/A standard

With ocrmypdf:

$ ocrmypdf --tesseract-timeout=0 --remove-background document.pdf document_pdfa.pdf

Reference: https://ocrmypdf.readthedocs.io/en/latest/cookbook.html#don-t-actually-ocr-my-pdf

Validate PDF/A compliance

Using verapdf you can validate the compliance of your PDF to different flavours of the PDF/A standard:

$ verapdf --flavour 1a --format text document.pdf

DjVu tools

Convert DjVu to images

Break Djvu into separate pages:

$ djvmcvt -i input.djvu /path/to/out/dir output-index.djvu

Convert Djvu pages into images:

$ ddjvu --format=tiff page.djvu page.tiff

Convert Djvu pages into PDF:

$ ddjvu --format=pdf inputfile.djvu ouputfile.pdf

You can also use --page to export specific pages:

$ ddjvu --format=tiff --page=1-10 input.djvu output.tiff

this will convert pages from 1 to 10 into one tiff file.

Processing images

You can use scantailor-advanced to:

  • fix orientation

  • split pages

  • deskew

  • crop

  • adjust margins

Make DjVu from images

There is a useful script img2djvu-git.

$ img2djvu -c1 -d600 -v1 ./out

it will create 600 DPI out.djvu from all files in ./out directory.

Alternatively, you can try didjvu, which seems to create smaller files especially on images with well defined background.

PostScript tools

ps2pdf

ps2pdf is a wrapper around ghostscript to convert PostScript to PDF:

$ ps2pdf -sPAPERSIZE=a4 -dOptimize=true -dEmbedAllFonts=true YourPSFile.ps

Explanation:

You cannot choose the paper orientation in ps2pdf. If your input PS file is healthy, it already contains the orientation information. If you are trying to use an Encapsulated PS file, you will have problems, if it does not fit in the -sPAPERSIZE you specified, because EPS files usually do not contain paper orientation information. A workaround is creating a new paper in ghostscript settings (call it e.g. "slide") and use it as -sPAPERSIZE=slide.

Libraries

C/C++

Python

Java

See also

PDF References