How do I place an image in Itextsharp?

Asked

Viewed 2,058 times

0

I’m trying to put an image in the pdf, but it’s an error because Itextsharp’s Image class only accepts Uri, and what I have is an incoming stream that I’ve already converted to System.Drawing.Image.

 public static Document GeraPdf(Stream stream)
    {
        Document doc = new Document(PageSize.A4);
        doc.SetMargins(40, 40, 40, 80);
        doc.AddCreationDate();

        string caminho = @"C:\Users\ASUS\Desktop\eae.pdf";

        PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(caminho, FileMode.Create));

        doc.Open();

        string dados = "";
        System.Drawing.Image img1 = System.Drawing.Image.FromStream(stream);

       Image ImagemPdf= Image.GetInstance(img1,ImageFormat.Jpeg);//Aqui esta o Erro


        Paragraph paragrafo = new Paragraph(dados, new Font(Font.NORMAL, 14));

        paragrafo.Alignment = Element.ALIGN_JUSTIFIED;

        paragrafo.Add("TESTE TESTE TESTE");

        doc.Add(paragrafo);

        doc.Close();
        return doc;
    }

1 answer

1


It’s not just one URI, you can use the stream itself of the input parameter... but the System.Image.Image no error (if mime is correct). Finally I noticed that you did not add the image to the document.

   public static Document GeraPdf(Stream stream)
    {
        Document doc = new Document(PageSize.A4);
        doc.SetMargins(40, 40, 40, 80);
        doc.AddCreationDate();

        string caminho = @"C:\temp\eae.pdf";

        PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(caminho, FileMode.Create));

        doc.Open();

        string dados = "";       

        Image ImagemPdf = Image.GetInstance(stream);
        //Configura os atributos que achar pertinente;
        doc.Add(ImagemPdf);

        Paragraph paragrafo = new Paragraph(dados, new Font(Font.NORMAL, 14));

        paragrafo.Alignment = Element.ALIGN_JUSTIFIED;

        paragrafo.Add("TESTE TESTE TESTE");        
        doc.Add(paragrafo);

        doc.Close();
        return doc;
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.