iTextSharp添加图片生成PDF文件

public void iTextSharpCreatPDF()
        {
            string pdfpath = System.Web.HttpContext.Current.Server.MapPath("~/log/DPD/");
            string imagepath = System.Web.HttpContext.Current.Server.MapPath("~/log/DPD/");
            Document doc = new Document(new Rectangle(390, 400), 0, 0, 0, 0); //new Rectangle(1000,1000)
            //指定文件预设开档时的缩放为100%
            //PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f);
            try
            {
                PdfWriter.GetInstance(doc, new FileStream(pdfpath + "/DPD_15505984238198.pdf", FileMode.Create));
                doc.Open();

                //下面对图片进行操作
                Image image = Image.GetInstance(imagepath + "/DPD_15505984238198.jpg");
                float percentage = 1;
                //这里都是图片最原始的宽度与高度
                float resizedWidht = image.Width;
                float resizedHeight = image.Height;

                这时判断图片宽度是否大于页面宽度减去也边距,如果是,那么缩小,如果还大,继续缩小,
                这样这个缩小的百分比percentage会越来越小
                //while (resizedWidht > (doc.PageSize.Width - doc.LeftMargin - doc.RightMargin) * 0.8)
                //{
                //    percentage = percentage * 0.9f;
                //    resizedHeight = image.Height * percentage;
                //    resizedWidht = image.Width * percentage;
                //}
                There is a 0.8 here. If the height of the image is too close to the page size height,
                the image will seem so big
                //while (resizedHeight > (doc.PageSize.Height - doc.TopMargin - doc.BottomMargin) * 0.8)
                //{
                //    percentage = percentage * 0.9f;
                //    resizedHeight = image.Height * percentage;
                //    resizedWidht = image.Width * percentage;
                //}

                这里用计算出来的百分比来缩小图片
                image.ScalePercent(percentage * 100);
                //让图片的中心点与页面的中心店进行重合
                image.SetAbsolutePosition(doc.PageSize.Width / 2 - resizedWidht / 2, doc.PageSize.Height / 2 - resizedHeight / 2);
                doc.Add(image);

            }
            catch (DocumentException dex)
            {
                System.Web.HttpContext.Current.Response.Write(dex.Message);
            }
            catch (IOException ioex)
            {
                System.Web.HttpContext.Current.Response.Write(ioex.Message);
            }

            catch (Exception ex)
            {
                System.Web.HttpContext.Current.Response.Write(ex.Message);
            }
            finally
            {
                doc.Close();
            }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值