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


    简单介绍

      业务需求,需要往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:UsersAdministratorDesktopK0000113_舱容图.pdf";
                    string Img = @"C:UsersAdministratorDesktop1572568425.png";//图片文件路径
                    AddImg(destPhysicalFile, Img, 129, 574);
                    MessageBox.Show("ok");
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

    效果

  • 相关阅读:
    Visual Studio各版本区别
    调试ASP.NET网站IIS环境问题解决方法汇总
    关于Webpage Not Found问题解决~~~
    SpringCloud+vue搭建的商城项目
    springcloud实现限流
    ReentrantLock
    栈和堆的特点
    你用对锁了吗?浅谈 Java “锁” 事
    ReentrantReadWriteLock读写锁的使用
    OAuth2
  • 原文地址:https://www.cnblogs.com/chenyanbin/p/11775108.html
Copyright © 2020-2023  润新知