简体   繁体   中英

Quickly rasterize parts of PDF with Ghostscript

In my C# application I am trying to show a PDF document in a navigatable window with options to zoom, pan, etc. I'm using Ghostscript.NET. It looks like for example Adobe Acrobat Reader is able to render just the given portion of a page, judging by the speed it is going at. I only found the means to rasterize entire page, which is not too practical, especially in high zoom levels. Is it possible to first crop out a rectangle (based on calculated corner coordinates) and then quickly rasterize it without the rest of the page?

I tried following command:

gswin64.exe -sDEVICE=pdfwrite -o C:/work/marked.pdf -dUseCropBox -c "[/CropBox [300 400 400 600] /PAGES pdfmark"  -f "c:\big boat.pdf"

Which works, technically speaking, but as far as i understood, the document must be defined without its own crop box, otherwise it won't work.

In order to add a CropBox (to a page) you can use an EndPage procedure, by sending a pdfmark at the end of the page, instead of the beginning, it should overwrite any pre-existing CropBox.

Or more simply, you can simply render a portion of the media directly, which sounds like what you want to do in the first place and avoids a (potentially lengthy) processing step.

Set the media size to the area you want to be rendered. For now lets assume you want a 2 inch square, 1 inch up from the bottom of the page. So we start by making the media size 2 inches square, and fixing it so any input can't change it:

-dDEVICEWIDTHPOINTS=144 -dDEVICEHEIGHTPOINTS=144 -dFIXEDMEDIA

If you add that to the command line you use to render the PDF file you will see that you get a 2 inch square rendered. Of course right now that's the bottom left corner of the page, so now we need to shift the media position so that the portion we want lies on the page. To do that we use PostScript, specifically the PageOffet key in the page device dictionary:

<</PageOffset [-72 0]>> setpagedevice

Note that we are shifting the bottom left corner of the page, which is why we use -72, we want the corner to go down.

because we are using PostScript we need to introduce it with the -c and -f switches:

-c "<</PageOffset [-72 0]>> setpagedevice" -f

So the whole command line becomes:

./gs -dDEVICEWIDTHPOINTS=144 -dDEVICEHEIGHTPOINTS=144 -dFIXEDMEDIA -c "<</PageOffset [-72 0]>> setpagedevice" -f input.pdf

If you really want to add a CropBox and produce a PDF file then you need to add an EndPage procedure, which will add a CropBox to every page individually:

./gs -sDEVICE=pdfwrite -o ./marked.pdf -c "<</EndPage {0 eq {[/CropBox [300 400 400 600] /PAGE pdfmark pop true}{pop false}ifelse}>>setpagedevice"  -f "c:\big boat.pdf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM