Convert images to a PDF with iTextSharp

I just finished working on a project that required multiple images to be combined into a single PDF document. I used iTextSharp to create the PDF, and I’m pretty happy with the solution that I came up with. There were only two functions required: one that converts an image to a smaller size & lesser quality and one that combines the images into PDF.

Here’s the code:

/// <summary>
/// Takes a collection of BMP files and converts them into a PDF document
/// </summary>
/// <param name="bmpFilePaths"></param>
/// <returns></returns>
private byte[] CreatePdf(string[] bmpFilePaths)
{
    using (var ms = new MemoryStream())
    {
        var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER.Rotate(), 0, 0, 0, 0);
        iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms).SetFullCompression();
        document.Open();
        foreach (var path in bmpFilePaths)
        {
            var imgStream = GetImageStream(path);
            var image = iTextSharp.text.Image.GetInstance(imgStream);
            image.ScaleToFit(document.PageSize.Width, document.PageSize.Height);
            document.Add(image);
        }
        document.Close();
        return ms.ToArray();
    }
}

/// <summary>
/// Gets the image at the specified path, shrinks it, converts to JPG, and returns as a stream
/// </summary>
/// <param name="imagePath"></param>
/// <returns></returns>
private Stream GetImageStream(string imagePath)
{
    var ms = new MemoryStream();
    using (var img = Image.FromFile(imagePath))
    {
        var jpegCodec = ImageCodecInfo.GetImageEncoders()
            .Where(x => x.MimeType == "image/jpeg")
            .FirstOrDefault();

        var encoderParams = new EncoderParameters(1);
        encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, (long)20);

        int dpi = 175;
        var thumb = img.GetThumbnailImage((int)(11 * dpi), (int)(8.5 * dpi), null, IntPtr.Zero);
        thumb.Save(ms, jpegCodec, encoderParams);
    }
    ms.Seek(0, SeekOrigin.Begin);
    return ms;
}
Advertisement

Author: Adam Prescott

I'm enthusiastic and passionate about creating intuitive, great-looking software. I strive to find the simplest solutions to complex problems, and I embrace agile principles and test-driven development.

4 thoughts on “Convert images to a PDF with iTextSharp”

    1. Vijay,

      The sample above doesn’t save the document to disk. It creates a byte array in memory. Use a FileStream to write the bytes to disk. (You’ll specify the location in the FileStream’s constructor.)

  1. Hi Adam

    That’s really awesome!!! it worked for as well.

    But I have a question for you,

    I am receiving a poor quality image while downloading. may i know what to do to increase the quality of the image in PDF. waiting for your reply

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: