itextsharp操作pdf——插入图片、二维码等

时间:2024-04-17 07:33:32

简单介绍

  业务需求,需要往pdf图纸上添加二维码功能,将实现过程记录下来

下载类库

直接下载

添加引用

 

 

添加命名空间

using System.IO;
using iTextSharp.text.pdf;

插入图片处理函数

        /// <summary>
        /// 向pdf中添加图片
        /// </summary>
        /// <param name="oldP">源pdf地址</param>
        /// <param name="imP">图片地址</param>
        /// <param name="x">x轴坐标</param>
        /// <param name="y">y轴坐标</param>
        protected void AddImg(string oldP, string imP, int x, int y)
        {
            string newP = Path.GetDirectoryName(oldP) + Path.GetFileNameWithoutExtension(oldP) + "_temp.pdf"; ;
            try
            {                
                using (Stream inputPdfStream = new FileStream(oldP, FileMode.Open, FileAccess.Read, FileShare.Read))
                using (Stream inputImageStream = new FileStream(imP, FileMode.Open, FileAccess.Read, FileShare.Read))
                using (Stream outputPdfStream = new FileStream(newP, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    var reader = new PdfReader(inputPdfStream);//读取原有pdf
                    var stamper = new PdfStamper(reader, outputPdfStream);
                    var pdfContentByte = stamper.GetOverContent(1);//获取第一页pdf内容
                    iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);//获取图片
                    image.ScalePercent(40);//设置图片比例
                    image.SetAbsolutePosition(x, y);//设置图片的绝对位置
                    pdfContentByte.AddImage(image);
                    stamper.Close();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                File.Copy(newP, oldP, true);
                File.Delete(newP);
            }
        }

实现

        private void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                string destPhysicalFile = @"C:\Users\Administrator\Desktop\K0000113_舱容图.pdf";
                string Img = @"C:\Users\Administrator\Desktop\1572568425.png";//图片文件路径
                AddImg(destPhysicalFile, Img, 129, 574);
                MessageBox.Show("ok");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

效果