Hi, I've been using iTextSharp PDF library for a while, but now want to do something tricky. At least it seems tricky.

I simply want to change the dimensions of a page in a PDF document I'm busy creating.. but change it *after* I've added content to it. In other words, kind of "crop" the page when I'm finished putting stuff on it, so the height of the page matches the top and bottom extents of the content (which I only know after the content is created).

Is that possible? SetPageSize() only seems to take effect when a new page is added, it doesn't affect the current page. Is there a "crop page" function of some kind?

One solution may be to add the content to a template, then do SetPageSize() and NewPage(), with the correct dimensions, adding the content to the new (2nd) page. But then the question is, how can I delete the first (unwanted) page?

Thanks if anyone can help!

You will have to alter the MediaBox of the current page if you want to resize the whole page.
In my code i needed to set the mediabox of a page same to the cropbox and here is what a part of what i did

PdfReader reader = new PdfReader(pdf)
PdfDictionary dict = reader.GetPageN(1);
PdfArray mediaBox = new PdfArray();
Rectangle cropBox = reader.GetCropBox(1);

mediaBox.Add(new PdfNumber(cropBox.Left));
mediaBox.Add(new PdfNumber(cropBox.Top));
mediaBox.Add(new PdfNumber(cropBox.Right));
mediaBox.Add(new PdfNumber(cropBox.Bottom));

dict.Put(PdfName.MEDIABOX, mediaBox);

then save it and you have your resized page...hope you get the idea

Brilliant, thanks.. a lot of objects there I don't know yet. Will try it out and see how it goes! Many thanks for that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.