首页 > 其他分享 >操作PDF的方法

操作PDF的方法

时间:2023-11-10 17:45:53浏览次数:40  
标签:Path new 操作 var PDF path document 方法 page

PDF的内容提取、转换见上篇

PDF操作:

  1. 旋转
  2. 删除
  3. 合并
  4. 拆分
  5. 转成图片
  6. 导出内嵌资源图片
  7. 两页合并成一页
  8. 添加、去除密码
  9. 添加水印

PDF旋转某一页 

 var document = pdfViewer1.Document;
 int page = pdfViewer1.Renderer.Page;
//判断pdf旋转方向 var rotate = (int)document.GetRotation(page); if (rotate < 3) rotate++; else rotate = 0; pdfViewer1.Document = null;
//向下一个方向旋转 document.RotatePage(page, (PdfRotation)rotate); var memoryStream = new MemoryStream(); document.Save(memoryStream); pdfViewer1.Document = PdfDocument.Load(this, memoryStream); pdfViewer1.Renderer.Page = page;
//如需要保存
//document.Save(路径);

PDF删除某一页

   int page = pdfViewer1.Renderer.Page;
   pdfViewer1.Document.DeletePage(page);

pdf合并 如需保存请直接保存文件

 var file = "";
 using (var form = new OpenFileDialog())
 {
     form.Filter = "PDF Files (*.pdf)|*.pdf|All Files (*.*)|*.*";
     form.RestoreDirectory = true;
     form.Title = "Open PDF File";

     if (form.ShowDialog(this) != DialogResult.OK)
     {
         Dispose();
         return;
     }
     file = form.FileName;
 }
 var document = pdfViewer1.Document;
 var doc = PdfSupport.MergePDF(document, OpenDocument(file));
 {
     if (doc != null)
     {
         pdfViewer1.Document = null;
         pdfViewer1.Document = doc;
     }
 }
//打开pdf
 private PdfDocument OpenDocument(string fileName)
 {
     try
     {   // Remove ReadOnly attribute from the copy.
         File.SetAttributes(fileName, File.GetAttributes(fileName) & ~FileAttributes.ReadOnly);
         return PdfDocument.Load(this, new MemoryStream(File.ReadAllBytes(fileName)));
     }
     catch (Exception ex)
     {
         MessageBox.Show(this, ex.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
         return null;
     }
 }

拆分PDF,拆分PDF支持指定拆分

 var path = Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName));
 if (!Directory.Exists(path))
 {
     Directory.CreateDirectory(path);
 }
 var document = pdfViewer1.Document;
 {
     for (int i = 0; i < document.PageCount; i++)
     {
         var filePath = Path.Combine(path, $"{i}.pdf");
      ///eg. "1,1,1,1" 4个1页
      /// "1-3" 第1页到第3页
      /// "1,3" 第1页、第3页 using (var doc = PdfSupport.GetPDFPage(document, i + 1)) { doc.Save(filePath); } } }

PDF转成图片

  var document = pdfViewer1.Document;
  var path = Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName));
  if (!Directory.Exists(path))
  {
      Directory.CreateDirectory(path);
  }
  var dpiX = 96 * 2;
  var dpiY = 96 * 2;
  for (int i = 0; i < document.PageCount; i++)
  {
      using (var image = document.Render(i, (int)document.PageSizes[i].Width * 4 / 3, (int)document.PageSizes[i].Height * 4 / 3, dpiX, dpiY, PdfRotation.Rotate0, PdfRenderFlags.Annotations | PdfRenderFlags.CorrectFromDpi))
      {
          image.Save(Path.Combine(path, i + ".png"));
      }
  }

导出PDF内嵌资源

  var path = Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName));
  if (!Directory.Exists(path))
  {
      Directory.CreateDirectory(path);
  }
  using (var memoryStream = new MemoryStream())
  {
      pdfViewer1.Document.Save(memoryStream);
      var document = PdfReader.Open(memoryStream);
      var imageCount = 0;
      // Iterate the pages.
      foreach (var page in document.Pages)
      {
          // Get the resources dictionary.
          var resources = page.Elements.GetDictionary("/Resources");
          if (resources == null)
              continue;

          // Get the external objects dictionary.
          var xObjects = resources.Elements.GetDictionary("/XObject");
          if (xObjects == null)
              continue;

          var items = xObjects.Elements.Values;
          // Iterate the references to external objects.
          foreach (var item in items)
          {
              var reference = item as PdfReference;
              if (reference == null)
                  continue;

              var xObject = reference.Value as PdfDictionary;
              // Is external object an image?
              if (xObject != null && xObject.Elements.GetString("/Subtype") == "/Image")
              {
                  PDFHelper.ExportImage(xObject, path, ref imageCount);
              }
          }
      }
  }
               

两页合并成一页

  using (var stream = new MemoryStream())
  {
      pdfViewer1.Document.Save(stream);
      stream.Position = 0;

      // Create the output document.
      var outputDocument = new PdfSharp.Pdf.PdfDocument();
      var outputmemoryStream = new MemoryStream();
      // Show single pages.
      // (Note: one page contains two pages from the source document)
      outputDocument.PageLayout = PdfPageLayout.SinglePage;

      var font = new XFont("微软雅黑", 8, XFontStyle.Regular);
      var format = new XStringFormat();
      format.Alignment = XStringAlignment.Center;
      format.LineAlignment = XLineAlignment.Far;

      // Open the external document as XPdfForm object.
      var form = XPdfForm.FromStream(stream);

      for (var idx = 0; idx < form.PageCount; idx += 2)
      {
          // Add a new page to the output document.
          var page = outputDocument.AddPage();
          page.Orientation = PageOrientation.Landscape;
          double width = page.Width;
          double height = page.Height;

          var gfx = XGraphics.FromPdfPage(page);

          // Set the page number (which is one-based).
          form.PageNumber = idx + 1;

          var box = new XRect(0, 0, width / 2, height);
          // Draw the page identified by the page number like an image.
          gfx.DrawImage(form, box);

          // Write page number on each page.
          box.Inflate(0, -10);
          gfx.DrawString(String.Format("- {0} -", idx + 1),
              font, XBrushes.Red, box, format);

          if (idx + 1 >= form.PageCount)
              continue;

          // Set the page number (which is one-based).
          form.PageNumber = idx + 2;

          box = new XRect(width / 2, 0, width / 2, height);
          // Draw the page identified by the page number like an image.
          gfx.DrawImage(form, box);

          // Write page number on each page.
          box.Inflate(0, -10);
          gfx.DrawString(String.Format("- {0} -", idx + 2),
              font, XBrushes.Red, box, format);
      }
      outputDocument.Save(outputmemoryStream);
      pdfViewer1.Document = null;
      pdfViewer1.Document = PdfDocument.Load(this, outputmemoryStream);
  }
        

添加、去除密码

//添加密码
    using (var form = new PasswordForm())
    {
        if (form.ShowDialog(this) == DialogResult.OK)
        {
            var path = Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName));
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            var txt = form.Password;
            using (var stream = new MemoryStream())
            {
                pdfViewer1.Document.Save(stream);
                stream.Position = 0;
                // Open an existing document. Providing an unrequired password is ignored.
                var document = PdfReader.Open(stream);

                var securitySettings = document.SecuritySettings;

                // Setting one of the passwords automatically sets the security level to 
                // PdfDocumentSecurityLevel.Encrypted128Bit.
                securitySettings.UserPassword = txt;
                //securitySettings.OwnerPassword = "owner";

                // Don't use 40 bit encryption unless needed for compatibility.
                //securitySettings.DocumentSecurityLevel = PdfDocumentSecurityLevel.Encrypted40Bit;

                // Restrict some rights.
                securitySettings.PermitAccessibilityExtractContent = false;
                securitySettings.PermitAnnotations = false;
                securitySettings.PermitAssembleDocument = false;
                securitySettings.PermitExtractContent = false;
                securitySettings.PermitFormsFill = true;
                securitySettings.PermitFullQualityPrint = false;
                securitySettings.PermitModifyDocument = true;
                securitySettings.PermitPrint = false;

                // Save the document...
                document.Save(Path.Combine(path, Path.GetFileName(fileName)));
            }
        }
    }
//去除密码
   using (var form = new PasswordForm())
   {
       if (form.ShowDialog(this) == DialogResult.OK)
       {
           var path = Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName));
           if (!Directory.Exists(path))
           {
               Directory.CreateDirectory(path);
           }
           var txt = form.Password;
           using (var stream = new MemoryStream())
           {
               pdfViewer1.Document.Save(stream);
               stream.Position = 0;
               // Open an existing document. Providing an unrequired password is ignored.
               var document = PdfReader.Open(stream, txt, PdfDocumentOpenMode.Modify);
               document.SecuritySettings.DocumentSecurityLevel = PdfSharp.Pdf.Security.PdfDocumentSecurityLevel.None;
               document.Save(Path.Combine(path, Path.GetFileName(fileName)));
           }
       }
   }

添加水印

   using (var stream = new MemoryStream())
   {
       pdfViewer1.Document.Save(stream);
       stream.Position = 0;
       var font = new XFont("微软雅黑", fontsize, XFontStyle.Regular, XPdfFontOptions.UnicodeDefault);
       var document = PdfReader.Open(stream);

       // Set version to PDF 1.4 (Acrobat 5) because we use transparency.
       if (document.Version < 14)
           document.Version = 14;

       for (var idx = 0; idx < document.Pages.Count; idx++)
       {
           var page = document.Pages[idx];
           var gfx = XGraphics.FromPdfPage(page);
           var size = gfx.MeasureString(watermark, font);
           gfx.TranslateTransform(page.Width / 2, page.Height / 2);
           gfx.RotateTransform(-Math.Atan(page.Height / page.Width) * 180 / Math.PI);
           gfx.TranslateTransform(-page.Width / 2, -page.Height / 2);
           if (waterIndex == 0)
           {
               var format = new XStringFormat();
               format.Alignment = XStringAlignment.Near;
               format.LineAlignment = XLineAlignment.Near;
               XBrush brush = new XSolidBrush(XColor.FromArgb(color));
               gfx.DrawString(watermark, font, brush,
                   new XPoint((page.Width - size.Width) / 2, (page.Height - size.Height) / 2),
                   format);
           }
           else if (waterIndex == 1)
           {
               var path = new XGraphicsPath();
               var format = new XStringFormat();
               format.Alignment = XStringAlignment.Near;
               format.LineAlignment = XLineAlignment.Near;
               path.AddString(watermark, font.FontFamily, XFontStyle.BoldItalic, fontsize,
               new XPoint((page.Width - size.Width) / 2, (page.Height - size.Height) / 2),
                   format);
               var pen = new XPen(XColor.FromArgb(color), 2);
               gfx.DrawPath(pen, path);
           } 
           if (waterIndex == 2)
           {
               var path = new XGraphicsPath();
               var format = new XStringFormat();
               format.Alignment = XStringAlignment.Near;
               format.LineAlignment = XLineAlignment.Near;
               path.AddString(watermark, font.FontFamily, XFontStyle.BoldItalic, fontsize,
                   new XPoint((page.Width - size.Width) / 2, (page.Height - size.Height) / 2),
                   format);                 
               var pen = new XPen(XColor.FromArgb(50, 75, 0, 130), 3);
               XBrush brush = new XSolidBrush(XColor.FromArgb(color));
               gfx.DrawPath(pen, brush, path);
           }
       }
       var outputmemoryStream = new MemoryStream();
       document.Save(outputmemoryStream);
       pdfViewer1.Document = null;
       pdfViewer1.Document = PdfDocument.Load(this, outputmemoryStream);
   }

阿里云下载:https://www.aliyundrive.com/s/o4KTpMLQyU9
具体使用方法请仓库自取
欢迎Start、PR
源码地址

标签:Path,new,操作,var,PDF,path,document,方法,page
From: https://www.cnblogs.com/xiaohemiao/p/17824571.html

相关文章

  • 以下哪些Array对象的方法不会更改原有数组?
    以下哪些Array对象的方法不会更改原有数组?Aconcat()Bsplice()Cmap()Dsort()正确答案:AC会改变数组的方法:push()pop()shift()unshift()splice()sort()reverse()forEach()不会改变数组的方法:filter()concat()slice()map()concat函数连接多个array,不改变原arr......
  • 类的所有实例方法均定义在类的原型对象上
    执行以下程序,下列选项中,说法错误的是()classPhone{constructor(brand){this.brand=brand;}call(){}...①}functionplayGame(){console.log("我可以打游戏")};functionphoto(){console.log("我可以拍照")};console.log(typeofPhone);...②varp=newPhone(......
  • 一文带你玩转SQL中的DML(数据操作)语言:从概念到常见操作大解析!数据操作不再难!
    前面我们介绍了SQL语句中数据定义语言(DDL)的概念以及它的常用语句,那么DML又是什么呢?二者有什么区别呢?本篇文章将为你讲述。一、DML简介DML是指数据操作语言,英文全称是DataManipulationLanguage,用来对数据库中表的数据记录进行更新。它创建的模式(表)使用数据操作语言来填充。DD......
  • 纯前端操作文件?
    事情是这样的我发现vscode在线版居然可以打开文件目录和文件,还能保存文件。兼容性一般目前谷歌edgeOpera支持其他均不支持vscode.dev/查了一下MDN发现增加新的API了developer.mozilla.org/zh-CN/docs/…showDirectoryPicker这是一项实验性技术未来版本可能会发生变化作用......
  • JAVA应用OOM OutOfMemoryError排查方法分享
    JAVA应用OOMOutOfMemoryError排查方法分享本地IDE场景如果OOM能在本地IDE复现,那对于调试来说是再方便不过了.添加jvm参数,帮助排查问题#限制内存不要给太大,使得有问题的代码容易暴露并调试。#HeapDumpOnOutOfMemoryError的意义为发生oom的时候,导出一份堆内存的快照。根......
  • 我心中的分布式操作系统
    这是一位网友发给我的文字,我原样复制粘贴发出来给大家,他的观点我不过多评论,也不代表公司和研发团队的立场,但是最后一段本人不同意,因为Laxcus分布式操作系统已经发布了六个版本,在很多领域广泛部署使用。目前Laxcus分布式操作系统正经历类似微软的Windows3.x到Windows95的过渡,即摆......
  • LiteCVR安防监控平台RTMP推流平台级联到上级的方法
    随着摄像头和显示设备技术的不断进步,视频监控系统将朝着更高的分辨率方向发展。高清和超高清画质可以提供更清晰、细节丰富的图像,有助于提升监控的效果和应用价值。有用户反馈,现场的设备是运动相机,不支持国标和其他协议接入LiteCVR平台,只能通过rtmp_push推送到LiteCVR平台。但是......
  • 13,zabbix web.page.regexp方法
    zabbix-agent#登录agent端,检查页面正常访问时的状态Copy]#curl-i10.117.x.x/path/login.jspHTTP/1.1200OK...#寻找正常页面返回中具有代表性的字符串zabbix-server#通过web.page.regexp匹配字符串检查状态Copy]#zabbix_get-s10.117.x.x-p10050-kweb.page.......
  • 创建型模式-工厂方法模式
    1什么是工厂方法模式工厂方法模式(FactoryMethodPattern)是一种创建型设计模式,它定义了一个用于创建对象的接口,但将对象的实际创建延迟到子类中。这样,客户端代码使用工厂方法来创建对象,而不需要了解具体对象的创建细节,从而实现了对象的解耦和灵活性。工厂方法模式的核心思想是......
  • Vue3 路由查询参数更新后,执行更新方法
    import{ref,defineComponent,watch,getCurrentInstance}from"vue";import{useRoute}from'vue-router';exportdefaultdefineComponent({setup(){consttable=ref({key:'spec_id',......