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
源码地址

操作PDF的方法的更多相关文章

  1. ASP.Net中实现上传过程中将文本文件转换成PDF的方法

    iTextSharp是一个常用的PDF库,我们可以使用它来创建.修改PDF文件或对PDF文件进行一些其他额外的操作.本文讲述了如何在上传过程中将文本文件转换成PDF的方法. 基本工作 在开始之前,我们 ...

  2. 【译】在Asp.Net中操作PDF - iTextSharp - 利用列进行排版

    原文 [译]在Asp.Net中操作PDF - iTextSharp - 利用列进行排版 在使用iTextSharp通过ASP.Net生成PDF的系列文章中,前面的文章已经讲述了iTextSharp所涵 ...

  3. 【译】在Asp.Net中操作PDF - iTextSharp - 绘制矢量图

    原文 [译]在Asp.Net中操作PDF - iTextSharp - 绘制矢量图 在上一篇iTextSharp文章中讲述了如何将现有的图片插入PDF中并对其进行操作.但有时,你需要在PDF中绘制不依 ...

  4. 【译】在Asp.Net中操作PDF – iTextSharp - 操作图片

    原文 [译]在Asp.Net中操作PDF – iTextSharp - 操作图片 作为我的iTextSharp系列的文章的第七篇,开始探索使用iTextSharp在PDF中操作图片,理解本篇文章需要看 ...

  5. 【译】在Asp.Net中操作PDF – iTextSharp - 使用表格

    原文 [译]在Asp.Net中操作PDF – iTextSharp - 使用表格 使用Asp.Net生成PDF最常用的元素应该是表格,表格可以帮助比如订单或者发票类型的文档更加格式化和美观.本篇文章并 ...

  6. 【译】在Asp.Net中操作PDF – iTextSharp - 使用链接和书签

    原文 [译]在Asp.Net中操作PDF – iTextSharp - 使用链接和书签 用户和PDF文档的交互可以通过锚(链接)和书签进行,接着我前面iTextSharp的系列文章,本篇文章主要讲通过 ...

  7. 【译】在Asp.Net中操作PDF – iTextSharp-列表

    原文 [译]在Asp.Net中操作PDF – iTextSharp-列表 在前文中,我们已经知道了如何利用iTextSharp创建PDF文档,设置字体样式和风格.本文开始讲述iTextSharp中的有 ...

  8. 【译】在Asp.Net中操作PDF – iTextSharp -利用块,短语,段落添加文本

    原文 [译]在Asp.Net中操作PDF – iTextSharp -利用块,短语,段落添加文本 本篇文章是讲述使用iTextSharp这个开源组件的系列文章的第三篇,iTextSharp可以通过As ...

  9. 【译】在Asp.Net中操作PDF - iTextSharp - 使用字体

    原文 [译]在Asp.Net中操作PDF - iTextSharp - 使用字体 紧接着前面我对iTextSharp简介博文,iTextSharp是一个免费的允许Asp.Net对PDF进行操作的第三方 ...

  10. 操作PDF文档功能的相关开源项目探索——iTextSharp 和PDFBox

    原文 操作PDF文档功能的相关开源项目探索——iTextSharp 和PDFBox 很久没自己写写心得日志与大家分享了,一方面是自己有点忙,一方面是自己有点懒,没有及时总结.因为实践是经验的来源,总结 ...

随机推荐

  1. Linux内核笔记(三)内核编程语言和环境

    学习概要: Linux内核使用的编程语言.目标文件格式.编译环境.内联汇编.语句表达式.寄存器变量.内联函数 c和汇编函数之间的相互调用机制Makefile文件的使用方法. as86汇编语言语法 汇编 ...

  2. 层叠样式表(CSS)3

    三.层叠样式表属性 1.文字属性 font-size:字体大小 line-height:行高 font-family:字体 font-weight:粗细程度 .......等等很多,可自行学习 2.文 ...

  3. 文心一言 VS 讯飞星火 VS chatgpt (68)-- 算法导论6.5 7题

    文心一言 VS 讯飞星火 VS chatgpt (68)-- 算法导论6.5 7题 七.试说明如何使用优先队列来实现一个先进先出队列,以及如何使用优先队列来实现栈(队列和栈的定义见 10.1 节.) ...

  4. Vue报错: Property or method "changeLoginType" is not defined on the instance but referenced during render

    原因 我这里是因为我代码中的方法不存在,我漏写了,后补充上就好了 解决方案 在methods中添加如下代码: // 修改登录状态 changeLoginType(bool){ this.loginTy ...

  5. 【技术积累】Linux中的命令行【理论篇】【二】

    ag命令 命令介绍 ag命令是一个用于在Linux系统中进行文本搜索的工具.它是基于Silver Searcher的改进版本,具有更快的搜索速度和更强大的功能. ag命令的基本用法是在指定的目录中搜索 ...

  6. 青少年CTF平台-Web-Flag在哪里

    平台名称:青少年CTF训练平台 题目名称:Flag在哪里? 解题过程: 启动环境,需要等待大概20秒左右的时间. 访问,页面显示Flag反正不在这. 右键网页,发现无法使用右键. 那么我们直接F12 ...

  7. React中setState的使用与同步异步

    在react中,修改状态如果直接使用this.state,不会引起组件的重新渲染,需要通过 this.setState来对组件的属性进行修改. 1.this.setState的两种定义方式 定义初始状 ...

  8. TensorRT 模型加密杂谈

    在大多数项目交付场景中,经常需要对部署模型进行加密.模型加密一方面可以防止泄密,一方面可以便于模型跟踪管理,防止混淆. 由于博主使用的部署模型多为TensorRT格式,这里以TensorRT模型为例, ...

  9. Web通用漏洞--文件上传

    Web通用漏洞--文件上传 概述 文件上传安全指的是攻击者通过利用上传实现后门的写入连接后门进行权限控制的安全问题,对于如何确保这类安全问题,一般会从原生态功能中的文件内容,文件后缀,文件类型等方面判 ...

  10. ArcMap时间滑块绘制遥感影像的动态变化过程

      本文介绍基于ArcMap软件,利用时间滑块功能,对大量多时相栅格遥感影像数据进行动态显示,并生成视频或动图的方法.   首先,我们需要在ArcMap软件中新建一个镶嵌数据集,并将全部的多时像遥感影 ...