Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPG to PDF Convertor in C#

Tags:

I would like to convert from an image (like jpg or png) to PDF.

I've checked out ImageMagickNET, but it is far too complex for my needs.

What other .NET solutions or code are there for converting an image to a PDF?

like image 474
Coppermill Avatar asked Oct 29 '09 08:10

Coppermill


People also ask

How do I convert a JPEG image to PDF?

Drag and drop an image file (JPG, PNG, BMP, and more) to use our PDF converter. Select an image file (JPG, PNG, BMP, and more) to use our PDF converter. Drag and drop an image file (JPG, PNG, BMP, and more) to use our PDF converter. Your file will be securely uploaded to Adobe cloud storage.


2 Answers

Easy with iTextSharp:

class Program {     static void Main(string[] args)     {         Document document = new Document();         using (var stream = new FileStream("test.pdf", FileMode.Create, FileAccess.Write, FileShare.None))         {             PdfWriter.GetInstance(document, stream);             document.Open();             using (var imageStream = new FileStream("test.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))             {                 var image = Image.GetInstance(imageStream);                 document.Add(image);             }             document.Close();         }     } } 
like image 78
Darin Dimitrov Avatar answered Sep 30 '22 13:09

Darin Dimitrov


iTextSharp does it pretty cleanly and is open source. Also, it has a very good accompanying book by the author which I recommend if you end up doing more interesting things like managing forms. For normal usage, there are plenty resources on mailing lists and newsgroups for samples of how to do common things.

EDIT: as alluded to in @Chirag's comment, @Darin's answer has code that definitely compiles with current versions.

Example usage:

public static void ImagesToPdf(string[] imagepaths, string pdfpath) {     using(var doc = new iTextSharp.text.Document())     {         iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(pdfpath, FileMode.Create));         doc.Open();         foreach (var item in imagepaths)         {             iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(item);             doc.Add(image);         }     } } 

like image 29
Ruben Bartelink Avatar answered Sep 30 '22 14:09

Ruben Bartelink