Skip to content

Instantly share code, notes, and snippets.

@headdetect
Created July 9, 2013 19:23
Show Gist options
  • Save headdetect/5960427 to your computer and use it in GitHub Desktop.
Save headdetect/5960427 to your computer and use it in GitHub Desktop.
Converts an image to a pdf using iTextSharp
using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
namespace Image2PDF
{
/// <summary>
/// Converts an image to a pdf
/// </summary>
public class Image2PDFConverter
{
private const int PAGE_WIDTH = 680;
private const int PAGE_HEIGHT = 772;
private const double PAGE_RATIO = (double)PAGE_WIDTH / (double)PAGE_HEIGHT;
// Page width -8px from each side //
private const int PAGE_WIDTH_WITH_PADDING = PAGE_WIDTH - 16;
// Page height -8px from top and bottom //
private const int PAGE_HEIGHT_WITH_PADDING = PAGE_HEIGHT - 16;
private string _image;
/// <summary>
/// Gets or sets the image to convert to a PDF
/// </summary>
public string Image
{
get
{
return _image;
}
set
{
if (!File.Exists(value))
{
throw new FileNotFoundException("file: \"" + value + "\" was not found.");
}
_image = value;
}
}
public string OutputPDF { get; set; }
public bool Overwrite { get; set; }
/// <summary>
/// Create a PDF based on the image specified
/// </summary>
/// <param name="image">image to convert</param>
public Image2PDFConverter(string image)
{
Image = image;
}
/// <summary>
/// Create an empty object
/// </summary>
public Image2PDFConverter()
{
}
/// <summary>
/// Converts the image to a PDF
/// </summary>
/// <param name="output">File to save it to</param>
public void Save(string output, bool overwrite = true)
{
if (File.Exists(output) && !overwrite)
throw new ArgumentException("\"" + output + "\" already exists. To overwrite, set parameter \"overwrite=true\"");
Document pdfdoc = new Document(new iTextSharp.text.Rectangle(PAGE_WIDTH, PAGE_HEIGHT), 4, 4, 4, 4);
FileStream fileStream = new FileStream(output, FileMode.Create);
// Creates a PDF document object in memory with the default settings //
PdfWriter.GetInstance(pdfdoc, fileStream);
// Convert our image to jpeg if not already //
Bitmap image = Bitmap.FromFile(_image) as Bitmap;
// Now we actually have some fun //
pdfdoc.Open();
foreach (var data in ConvertImage(image))
pdfdoc.Add(new Jpeg(data, PAGE_WIDTH, PAGE_HEIGHT));
pdfdoc.Close();
fileStream.Close();
image.Dispose();
}
/// <summary>
/// Converts the image to a PDF
/// </summary>
/// <remarks>Make sure you set Image, Output and Overwrite to your liking</remarks>
public void Save()
{
Save(OutputPDF, Overwrite);
}
private IEnumerable<byte[]> ConvertImage(Bitmap bitmap)
{
// Resize image to fit page //
int oX = bitmap.Width;
int oY = bitmap.Height;
int nX = Math.Min(PAGE_WIDTH, oX);
int nY = nX == PAGE_WIDTH ? (int)(oY * PAGE_RATIO) : oY;
int pageCount = oY / PAGE_HEIGHT;
// Spread images over multiple pages //
for (int i = 0; i <= pageCount; i++)
{
Bitmap map = new Bitmap(nX, PAGE_HEIGHT);
RectangleF dist = new RectangleF(0, 0, map.Width, map.Height);
RectangleF src = new RectangleF(0, i * PAGE_HEIGHT, bitmap.Width, Math.Min(PAGE_HEIGHT, bitmap.Height - (i * PAGE_HEIGHT)));
using (var graphics = Graphics.FromImage(map))
graphics.DrawImage(bitmap, dist, src, GraphicsUnit.Pixel);
// Finally convert to jpeg //
MemoryStream stream = new MemoryStream();
map.Save(stream, ImageFormat.Jpeg);
yield return stream.ToArray();
}
}
}
}
using Image2PDF;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestConsole
{
class Program
{
static void Main(string[] args)
{
string imageFile = null;
while (imageFile == null)
{
Console.WriteLine("Enter image to convert to PDF:");
string file = Console.ReadLine();
if (File.Exists(file))
{
imageFile = file;
continue;
}
Console.WriteLine("File: \"" + file + "\" doesn't exist!");
Console.WriteLine();
}
SaveFile(imageFile);
Console.WriteLine("Would you like to convert another image? [y/N]");
string isYes = Console.ReadLine().ToLower();
if (isYes.StartsWith("y"))
{
Console.Clear();
Main(args);
}
}
static void SaveFile(string imageFile)
{
Console.WriteLine("Enter file to save PDF to:");
string saveFile = Console.ReadLine();
if (File.Exists(saveFile))
{
Console.WriteLine("File already exists");
Console.WriteLine("Would you like to overwrite? [y/N]");
string isYes = Console.ReadLine().ToLower();
if (isYes.StartsWith("y"))
{
Console.WriteLine("Creating PDF...");
Image2PDFConverter overwriteConvert = new Image2PDFConverter(imageFile);
Stopwatch watch = new Stopwatch();
watch.Start();
overwriteConvert.Save(saveFile);
watch.Stop();
Console.WriteLine("Completed in: " + watch.Elapsed.TotalSeconds + " seconds");
return;
}
else
{
SaveFile(imageFile);
return;
}
}
Console.WriteLine("Creating PDF...");
Image2PDFConverter convert = new Image2PDFConverter(imageFile);
Stopwatch watched = new Stopwatch();
watched.Start();
convert.Save(saveFile);
watched.Stop();
Console.WriteLine("Completed in: " + watched.Elapsed.TotalSeconds + " seconds");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment