Snote
Snote

Reputation: 955

Bad size image in pdf created with itextsharp

I have a problem to create a pdf with itextsharp from images in .tiff. Here is some code :

        iTextSharp.text.Document d = new iTextSharp.text.Document();
        PdfWriter pw = PdfWriter.GetInstance(d, new FileStream(filename, FileMode.Create));
        d.Open();

        PdfContentByte cb = pw.DirectContent;
        foreach (Image img in imgs)
        {
            d.NewPage();
            d.SetPageSize(new iTextSharp.text.Rectangle(0, 0, img.Width, img.Height));
            iTextSharp.text.Image timg = iTextSharp.text.Image.GetInstance(img, iTextSharp.text.BaseColor.WHITE);
            timg.SetAbsolutePosition(0, 0);
            cb.AddImage(timg);
            cb.Stroke();
        }
        d.Close();

It creates the pdf with two pages but the image on the first page is to big.
The page have the size of the image but it zoom an the bottom left corner of the image. It does that only with the tiff image, if I take png, it works fine.

Any solution?

Upvotes: 2

Views: 2536

Answers (2)

janani
janani

Reputation: 123

use like this

string[] validFileTypes = {"tiff"};
string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
bool isValidFile = false;
if (!isValidFile)
{
Label.Text = "Invalid File. Please upload a File with extension " +
                       string.Join(",", validFileTypes);
}
 else
    {
        string pdfpath = Server.MapPath("pdf");
        Document doc = new Document(PageSize.A4, 0f, 0f, 0f, 0f);
        PdfWriter.GetInstance(doc, new FileStream(pdfpath + "/Images.pdf", FileMode.Create));
        doc.Open();

        string savePath = Server.MapPath("images\\");
        if (FileUpload1.PostedFile.ContentLength != 0)
          {
            string path = savePath + FileUpload1.FileName;
            FileUpload1.SaveAs(path);
            iTextSharp.text.Image tiff= iTextSharp.text.Image.GetInstance(path);
            tiff.ScaleToFit(doc.PageSize.Width, doc.PageSize.Height);
            tiff.SetAbsolutePosition(0,0);
            PdfPTable table = new PdfPTable(1);
            table.AddCell(new PdfPCell(tiff));
            doc.Add(table);
          }
         doc.Close();
      }

Upvotes: 0

Snote
Snote

Reputation: 955

Thanks to the comment of mkl, I found it. Set the page size (SetPageSize) before the new page command (NewPage)

Upvotes: 1

Related Questions