C# Save Bitmap as PDF With iTextSharp

16,270

You can try this

System.Drawing.Image image = System.Drawing.Image.FromFile("Your image file path");
Document doc = new Document(PageSize.A4);
PdfWriter.GetInstance(doc, new FileStream("image.pdf", FileMode.Create));
doc.Open();
iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Jpeg);
doc.Add(pdfImage);
doc.Close();

Referenced from here

Share:
16,270
Glen
Author by

Glen

Updated on June 05, 2022

Comments

  • Glen
    Glen almost 2 years

    The following code creates a bitmap from a control on the form, and then shows a save dialog to save as a JPEG. Can anyone help with the code to save the Bitmap bm as a PDF with iTextSharp?

     Bitmap bm = null;
     bm = new Bitmap(this.RCofactorTBS.SelectedTab.Width, this.RCofactorTBS.SelectedTab.Height);
     this.RCofactorTBS.SelectedTab.DrawToBitmap(bm, this.RCofactorTBS.SelectedTab.ClientRectangle);
    
     SaveFileDialog dialog = new SaveFileDialog();
     dialog.Filter = "JPEG|*.jpeg";
     dialog.Title = "Save Test As Jpeg";
     dialog.ShowDialog();
    
     if (dialog.FileName != "" && bm != null)
     {
        bm.Save(dialog.FileName);
     }
    
  • Glen
    Glen almost 11 years
    the idea is not to save the image to a file first. i want to save the "bm" object to the pdf without saving to a file first
  • Jibran Khan
    Jibran Khan almost 11 years
    You can directly pass the bitmap to the image.
  • Glen
    Glen almost 11 years
    your using PdfWriter there, im using iTextSharp ?
  • Glen
    Glen almost 11 years
    OK i got this working. But, the image doesn't fit inside the pdf document. Any idea how i can make it fit?
  • Jibran Khan
    Jibran Khan almost 11 years
    You have to play with formatting of the document. if you get this answer helpful then mark as accepted for future help to community.
  • Jibran Khan
    Jibran Khan almost 11 years
    You can go through this link to check the display formatting stackoverflow.com/questions/4325151/…
  • Nathan Tuggy
    Nathan Tuggy almost 9 years
    Could you please edit in an explanation (in English; the Spanish comments here will be difficult for most users to make any use of) of why this code answers the question? Code-only answers are discouraged, because they don't teach the solution.
  • JB06
    JB06 over 8 years
    @NathanTuggy Here's the comment in English - //here I passed a bitmapped image