Niclas
Niclas

Reputation: 146

Draw rectangle with Ghostscript (using PostScript language)

I'm trying to draw a rectangle and output it to a PDF using Ghostscript. If I put the following PostScript code in a file named rect.eps, I get what I want:

newpath
100 100 moveto
0 100 rlineto
100 0 rlineto
0 -100 rlineto
-100 0 rlineto
closepath
gsave
0 0 0 setrgbcolor
fill
stroke
showpage

But if I try to include that PostScript into my Ghostscript-command, I just get a blank page:

gs -o rect.pdf -sDEVICE=pdfwrite -g300x300 -c "newpath 100 100 moveto 0 100 rlineto 100 0 rlineto 0 -100 rlineto -100 0 rlineto closepath gsave 0 0 0 setrgbcolor fill stroke showpage"

What am I doing wrong, shouldn't it be possible to draw a rectangle with Ghostscript?

Best Regards Niclas

Upvotes: 2

Views: 3153

Answers (1)

KenS
KenS

Reputation: 31199

Stefan's comment is effectively correct.

You have set a media size in pixels of 300x300. Now given that the pdfwrite device's default resolution is 720 dpi, and you haven't changed that, this means that the media size is less than half an inch in each direction.

You have then drawn a rectangle, staring at 100,100 units on the page, and extending by 100 units in each direction. PostScritp units are 1/72 of an inch, so your rectangle's lower left corner begins at just over 1 inch up and right.

That's outside the half-inch square defined by your media, so the result is simply that the rectangle is drawn off the page.

If you don't set the media size Ghostscript will use its default, either A4 or Letter depending, and you will see the output. As to why it works when you make an EPS file, I have no idea, I expect there is content in the EPS that you haven't shared which is making a difference.

When creating a PDF file, which is a resolution-independent format, its better to specify the media size in resolution-independent units, like PostScript units, than pixels.

Note that your code has an additional problem, also mentioned by Stefan, the dangling gsave, which looks like it ought to have a grestore before the stroke. As it is the stroke will do nothing, I suspect you want:

gsave
0 0 0 setrgbcolor
fill
grestore
stroke
showpage

Upvotes: 4

Related Questions