PDF crop even-odd pages with PHP + GhostScript

不羁岁月 提交于 2019-12-02 03:46:07

You can't set a 'CropBox' in PostScript, because CropBox isn't part of the PostScript language, its PDF-specific.

You need to send a /PAGE pdfmark with a /CropBox, as the first post you reference says. You don't set a /Install.

Laura

GhostScript can process PostScript files and PostScript commands passed through -c parameter at command line. So, for achieve things non trivial, you should understand at least the basics of this language.

Get the relevant documentation fom the sources: PostScript Language Reference Manual, 3rd ed. and the PostScript Language Tutorial and Cookbook if you have not seen PostScript in your life (as is mi case).

KenS pointed me:

You need a /EndPage procedure (which does get passed to setpagedevice) and that procedure needs to call the pdfmark.

The docs states that EndPage is

A procedure to be executed at the end of each page. Before calling the procedure, the interpreter pushes two integers on the operand stack—a count of previous showpage executions for this device and a reason code indicating the circumstances under which this call is being made:

0 - During showpage or (LanguageLevel 3) copypage

1 - During copypage (LanguageLevel 2 only)

2 - At device deactivation

The procedure must return a boolean value specifying whether to transmit the page image to the physical output device.

So, this fragment of code (from KenS' previous answer)

<</EndPage {0 eq {[/CropBox [0 0 612 792] /PAGE pdfmark true}{false}ifelse}>> setpagedevice

passes a CropBox for current page -with coordinates specified- everytime EndPage is invoked with reason 0 (showpage) and returns true. Otherwise, nothing is done and returns false. This reason code is the first item in operands stack, and after it is "consumed" in operation 0 eq {true block}{false block} ifelse (is equal to 0?), there is no more in the stack.

So, the next value in the stack is the number of pages processed. We expand the code with another ifelse inside the true part of code shown above:

{2 mod 0 eq {[/CropBox [0 0 612 792] /PAGE pdfmark true} 
{[/CropBox [50 0 612 792] /PAGE pdfmark true} ifelse}

This performs modulus between current page (at top of stack) and 2, then tests if equals 0 (i.e. tests for odd/even page). If even (modulus = 0) passes the first CropBox, else the second, and returns true in both cases.

So, the full piece of PostScript code:

"<</EndPage {0 eq {2 mod 0 eq {[/CropBox [0 0 612 792] /PAGE pdfmark true}
{[/CropBox [50 0 612 792] /PAGE pdfmark true} ifelse}{false}ifelse}>> setpagedevice"

when passed in GhostScript as -c parameter allow us to crop differently even and odd pages of a PDF document, i.e. if we want to supress the extra space for binding of original.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!