I’m using iTextSharp to convert large images to PDF documents.
This works, but the images appear cropped, because they exceed boundaries of the generated document.
So the question is – how to make the document same size as the image being inserted into it?
I’m using the following code:
Document doc = new Document(PageSize.LETTER.Rotate());
try
{
PdfWriter.GetInstance(doc, new FileStream(saveFileDialog1.FileName,FileMode.Create));
doc.Open();
doc.Add(new Paragraph());
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imagePath);
doc.Add(img);
}
catch
{
// add some code here incase you have an exception
}
finally
{
//Free the instance of the created doc as well
doc.Close();
}
The
Documentobject in iText and iTextSharp is an abstraction that takes care of various spacings, paddings and margins for you automatically. Unfortunately for you, this also means that when you calldoc.Add()it takes into account existing margins of the document. (Also, if you happen to add anything else the image will be added relative to that, too.)One solution would be to just remove the margins:
Instead, it’s easier to add the image directly to the
PdfWriterobject which you get from callingPdfWriter.GetInstance(). You’re currently throwing away and not storing that object but you can easily change your line to:Then you can access the
DirectContentproperty of thePdfWriterand call itsAddImage()method:Before doing this you must also absolutely position the image by calling:
Below is a full working C# 2010 WinForms app targeting iTextSharp 5.1.1.0 that shows the
DirectContentmethod above. It dynamically creates two images of different sizes with two red arrows stretching across both vertically and horizontally. Your code would obviously just use standard image loading and could thus omit a lot of this but I wanted to deliver a full working example. See the notes in the code for more details.