Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split one PDF page into two

Tags:

java

pdf

itext

i want to split one wide PDF page into two PDF pages. My original page is wide as two A4 page size but height is normal(for A4). I trying to use IText but with no effects. Thanks for attention.

like image 492
gohohgle Avatar asked Oct 27 '10 12:10

gohohgle


People also ask

Can you split a page in half in PDF?

Choose “Organize Pages” > “Split.” Choose how you want to split a single file or multiple files. Name and save: Click “Output Options” to decide where to save, what to name, and how to split your file. Split your PDF: Click “OK” and then “Split” to finish.


2 Answers

I don't know the iText API, but you can follow these steps to get there:

Create two new copies of the existing page. This means that you have the same Resources, the same ContentStream, etc.

Get the MediaBox for the first page which is an array laid out as [llx lly urx ury].

if MediaBox[2] - MediaBox[0] == long edge of A4 page then
    HalfPageWidth = MediaBox[2] - MediaBox[0];
    PageCopy1.CropBox = [MediaBox[0] MediaBox[1] (MediaBox[0] + HalfPageWidth) MediaBox[3]]
    PageCopy2.CropBox = [(MediaBox[0] + HalfPageWidth) MediaBox[1] MediaBox[2] MediaBox[3]]
else
    HalfPageHeight = MediaBox[3] - MediaBox[1];
    PageCopy1.CropBox = [MediaBox[0] MediaBox[1] MediaBox[2] (MediaBox[1] + HalfPageHeight)]
    PageCopy2.CropBox = [MediaBox[0] (MediaBox[1] + HalfPageHeight)] MediaBox[2] MediaBox[3]]

Remove the original page and save these two pages. Basically, you're making two identical copies of the page and cropped each to half the page. You may also need to set the page rotation.

like image 140
plinth Avatar answered Oct 06 '22 00:10

plinth


You can also use Ghostscript (with the addition of a PostScript code snippet to the call) for that. Commandlines required:

Output the left side:

 gs \
   -o left-half.pdf \
   -sDEVICE=pdfwrite \
   -g5950x8420 \
   -dFIXEDMEDIA \
   -PDFFitPage \
   -dAutoRotatePages=/None \
   -c "<</PageOffset [0 0]>> setpagedevice" \
    doubleup.pdf

Output the right side:

 gs \
   -o left-half.pdf \
   -sDEVICE=pdfwrite \
   -g5950x8420 \
   -dFIXEDMEDIA \
   -PDFFitPage \
   -dAutoRotatePages=/None \
   -c "<</PageOffset [-595 0]>> setpagedevice" \
    doubleup.pdf

These commandlines can easily be translated into Java or whatever code to use the appropriate GS API calls...

like image 35
Kurt Pfeifle Avatar answered Oct 05 '22 22:10

Kurt Pfeifle