【问题标题】:Bad size image in pdf created with itextsharp使用 itextsharp 创建的 pdf 中尺寸错误的图像
【发布时间】:2012-10-24 09:48:02
【问题描述】:

我在使用 itextsharp 从 .tiff 中的图像创建 pdf 时遇到问题。 这是一些代码:

        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();

它创建包含两页的 pdf,但第一页上的图像太大。
该页面具有图像的大小,但它会缩放图像的左下角。 它只对 tiff 图像执行此操作,如果我使用 png,它可以正常工作。

有什么办法吗?

【问题讨论】:

  • 创建新页面之前不应该设置页面大小吗?如果我没记错的话,一旦创建了一个页面,它的大小就是固定的。

标签: c# itextsharp


【解决方案1】:

感谢mkl的评论,我找到了。 在新建页面命令(NewPage)之前设置页面大小(SetPageSize)

【讨论】:

    【解决方案2】:

    这样使用

    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();
          }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-23
      • 1970-01-01
      • 1970-01-01
      • 2012-03-16
      相关资源
      最近更新 更多