使用LiveCycle / ITextSharp动态插入图像到PDF

时间:2013-02-07 15:10:27

标签: c# asp.net-mvc-3 pdf itextsharp livecycle

我有一个使用LiveCycle Designer创建的pdf模板。在其中,我创建了3个图像字段,ImageField1,ImageField2,ImageField3。图像位于网址上,我们称之为“http://images.com/img/IMAGENAME.jpg”,用户在生成pdf之前选择图像,在这种情况下,我将图像名称存储在字符串数组中。

是否可以通过编程方式将这些图像添加到图像字段中?到目前为止我尝试过的方法只导致了一个无法打开的pdf损坏。

public string Foo(int id)
    {
        try
        {

            var file = string.Empty;
            var property = ((IRepositoryBase)PropertyRepository).GetById<Property>(id);
            var purchase = ((IRepositoryBase)PropertyRepository).GetByPropertyId<PropertyPurchase>(id);
            var inspection = ((IRepositoryBase)PropertyRepository).GetByPropertyId<PropertyInspection>(id);
            file = HttpContext.Current.Server.MapPath("\\Assets\\documents\\originals\\Brochure.pdf");
            var tmp = HttpContext.Current.Server.MapPath("\\Assets\\documents\\temps\\");



            tmp += string.Format("{0}-Brochure.pdf", property.Id);

            var pdfReader = new PdfReader(file);
            var pdfStamper = new PdfStamper(pdfReader, new FileStream(tmp, FileMode.Create));
            var pdfFormFields = pdfStamper.AcroFields;
            var pht = property.BrochurePhoto;
            string[] photos = pht.Split(' ');
            PdfContentByte cB = new PdfContentByte(pdfStamper.Writer);



            if (photos[0] != null)
            {
                iTextSharp.text.Image photoToPdf1 = iTextSharp.text.Image.GetInstance(new Uri("http://images.com/img/" + photos[0].ToString() + ".jpg"));
                cB.AddImage(photoToPdf1);
            }
            if (photos[1] != null)
            {
                iTextSharp.text.Image photoToPdf2 = iTextSharp.text.Image.GetInstance(new Uri("http://images.com/img/" + photos[1].ToString() + ".jpg"));
                cB.AddImage(photoToPdf2);
            }
            if (photos[2] != null)
            {
                iTextSharp.text.Image photoToPdf3 = iTextSharp.text.Image.GetInstance(new Uri("http://images.com/img/" + photos[2].ToString() + ".jpg"));
                cB.AddImage(photoToPdf3);
            }

            pdfStamper.FormFlattening = false;
            pdfStamper.Close();
            return string.Format("{0}-Brochure.pdf", property.Id);

        }
        catch (Exception ex)
        {
            Log.Error(ex);
            return string.Empty;


        }

    }

0 个答案:

没有答案