Monday, April 9, 2012

Create PDF with different size pages based on input file

While adding the Image to itextsharp document please set the page size (Same code applicable for all the document types)


//input image document path
string imagePath = Server.MapPath(strinputDocumentPath);
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imagePath);

//Getting Width of the image width adding the page right & left margin
var width = img.ScaledWidth
                  + pdfdoc.RightMargin
                  + pdfdoc.LeftMargin;
               
//Getting Height of the image height adding the page top & bottom margin
var height = img.ScaledHeight
                  + pdfdoc.TopMargin
                  + pdfdoc.BottomMargin;
              
               
//Creating pdf rectangle with the specified height & width for page size declaration
iTextSharp.text.Rectangle r = new iTextSharp.text.Rectangle(width, height);
               
/*you __MUST__ call SetPageSize() __BEFORE__ calling NewPage()
* AND __BEFORE__ adding the image to the document
*/

//Changing the page size of the pdf document based on the rectangle defined
pdfdoc.SetPageSize(r);
pdfdoc.NewPage();
pdfdoc.Add(img);

On creating every new page in document please set the page size as follows based on the page needs, you can also specify the height and width of the pdf rectangle

//To set the page size of the document
pdfdoc.SetPageSize(new iTextSharp.text.Rectangle(PageSize.A4));
pdfdoc.NewPage();

2 comments:

  1. Thank you. right now im using your method. But the PDF generated DPI is set as 72 DPI. how i can make it followed the image DPI?

    ReplyDelete