3
votes

I am attempting to insert an image into a newly created PDF document using iTextSharp - although I am not sure I am going about it in the correct manner. I have created an image object and then attempted to add it to the page - but no image shows up - although the text I inserted does appear in the PDF document.

Does anyone have any ideas?

public bool createPDF(string batchNumber, string userName, string path)
{
    // step 1: creation of a document-object
    Document myDocument = new Document(PageSize.A4.Rotate());

    try
    {
        // step 2:
        // Now create a writer that listens to this doucment and writes the document to desired Stream.
        PdfWriter.GetInstance(myDocument, new FileStream(path, FileMode.Create));

        // step 3:  Open the document now using
        myDocument.Open();

        // step 4: Now add some contents to the document
        // batch Header e.g. Batch Sheet
        myDocument.Add(new Paragraph("Number: " + batchNumber));
        myDocument.Add(new Paragraph("Created By: " + userName));

        iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance("code39-barcode.png");
        PdfPCell cell = new PdfPCell(logo);
        myDocument.Add(cell);
    }
    catch (DocumentException de)
    {
        Console.Error.WriteLine(de.Message);
    }
    catch (IOException ioe)
    {
        Console.Error.WriteLine(ioe.Message);
    }

    // step 5: Remember to close the document
    myDocument.Close();

    return true;
}
2

2 Answers

2
votes

Read this to know how to add image

However, I think you miss something with table.

You should have a table and use table.addCell to add the cell

PdfPTable table = new PdfPTable(3);

PdfPCell cell = new PdfPCell(new Phrase("Header spanning 3 columns"));

Read this to know how to use table

0
votes

Remove this:

PdfPCell cell = new PdfPCell(logo);
myDocument.Add(cell);

And use this:

myDocument.Add(logo);

And it works :)