2

I'm using ghostscript to process some PDF files, and I would like to add a thin black border around the files. Is this something that can be done with ghostscript, or are there other (non-lossy) command-line tools that can do this?

2

Not sure if this is non-lossy enough for you, but you can use ImageMagick:

convert foo.pdf -bordercolor black -border 10 foo_with_a_10px_border.pdf

For a sure-to-be-non-lossy solution, you can build a one-page pdf document with just a border on a transparent background and apply it over each page of your document with pdftk's stamp command:

pdftk foo.pdf stamp border.pdf output foo_with_my_home-made_border.pdf
  • Avoid using ImageMagick on a PDF: it would rasterize it. – Gilles Dec 18 '16 at 22:29
2

Typically this can be done by converting the pdf to PostScript, adding to the start a small piece of PostScript code to override the end-of-page function showpage, and then printing this, or converting it to pdf.

You can convert to and from pdf with pdf2ps and ps2pdf which are usually packaged with ghostscript. This example PostScript code adds an A4 sized border:

%!PS
% A4 paper is  21.0 × 29.7 cm
/cm { 28.4 mul } bind def
/w 21.0 cm def
/h 29.7 cm def
/border 
{ 0.5 cm setlinewidth newpath
  0 0 moveto w 0 lineto w h lineto 0 h lineto closepath stroke
} bind def
/add-border { gsave initgraphics 0 setgray border grestore } def
/orig-showpage /showpage load def
/showpage { orig-showpage add-border } def
add-border

Put this in a file, say addborder.ps, then you can

pdf2ps a.pdf a.ps
cat addborder.ps a.ps >b.ps
ps2pdf b.ps b.pdf
gv b.pdf

For other paper sizes, edit the definition of /w and /h in centimetres. The example line width is 0.5 cm (or half this as the line is centred on the edge of the paper).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.