Dynamically Resizing PDF Pages
Posted 2012-01-03
First article of 2012 :) One of my New Year's Resolutions is to be more active on the web site to help pull myself out of the current job situation (developer black hole) and find some interesting work. Since I don't get any kind of development experience at work, I've also started increasing my activity at stackoverflow.com. An interesting question popped up today - iTextSharp - PDF - Resize Document to Accomodate a Large Image.
There were two answers before mine, and both completely ignored the question's main point - how do you dynamically resize the Document page size. If you're too lazy to read the aforementioned link by iText's creator, the crucial point is:
"setting the page size only takes effect on the next page"
What made the question interesting was that I had never had the need to do anything like this, and didn't know off the top of my head how to answer the question. So after finding the link above, it wasn't too hard:
<%@ WebHandler Language="C#" Class="scaleDocToImageSize" %>
using System;
using System.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
public class scaleDocToImageSize : IHttpHandler {
public void ProcessRequest (HttpContext context) {
HttpServerUtility Server = context.Server;
HttpResponse Response = context.Response;
Response.ContentType = "application/pdf";
// add multiple images
string[] imagePaths = {
"./scaleDocToImageSize01.jpg", "./scaleDocToImageSize02.jpg"
};
// default page size, change to suit your needs
Rectangle defaultPageSize = PageSize.A4;
using (Document document = new Document()) {
PdfWriter.GetInstance(document, Response.OutputStream);
document.Open();
document.Add(new Paragraph("Page 1"));
foreach (string path in imagePaths) {
string imagePath = Server.MapPath(path);
Image img = Image.GetInstance(imagePath);
// if you don't account for the left/right margins, the image will
// exceed the document/page boundaries
var width = img.ScaledWidth
+ document.RightMargin
+ document.LeftMargin
;
// same for the top/bottom margins
var height = img.ScaledHeight
+ document.TopMargin
+ document.BottomMargin
;
Rectangle r = width > defaultPageSize.Width
|| height > defaultPageSize.Height
? new Rectangle(width, height)
: defaultPageSize
;
/*
* you __MUST__ call SetPageSize() __BEFORE__ calling NewPage()
* AND __BEFORE__ adding the image to the document
*/
document.SetPageSize(r);
document.NewPage();
document.Add(img);
}
}
}
public bool IsReusable { get { return false; } }
}
The inline comments explain everything. Download a working example. Just make sure to:
- Copy all files from the zip archive into an existing web project.
- Make sure you have the itextsharp.dll in the project's
~/bin directory.