当前位置: 首页 > news >正文

使用C#和 aspose.total 实现替换pdf中的文字(外语:捷克语言的pdf),并生成新的pdf导出到指定路径

程序主入口:

Program.cs

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace PdfEditor
{public  class Program{static void Main(string[] args){#region 单例模式Process[] allProcess = Process.GetProcesses();List<Process> prolist = new List<Process>();foreach (Process p in allProcess){if (p.ProcessName.ToLower() == "pdfeditor"){Console.WriteLine(p.StartTime.ToString() + p.ProcessName);prolist.Add(p);}}Console.WriteLine("当前启动程序进程数:" + prolist.Count);if (prolist.Count > 1){for (int m = 0; m < prolist.Count - 1; m++){try{for (int i = 0; i < prolist[m].Threads.Count; i++)prolist[m].Threads[i].Dispose();prolist[m].Kill();}catch (Exception ex){Console.WriteLine(ex.ToString());continue;}}}Console.WriteLine("启动中~~~请稍等~~");System.Threading.Thread.Sleep(10000);Process[] allProcess1 = Process.GetProcesses();List<Process> prolist1 = new List<Process>();foreach (Process p1 in allProcess1){if (p1.ProcessName.ToLower() == "pdfeditor"){Console.WriteLine(p1.StartTime.ToString() + p1.ProcessName);prolist1.Add(p1);}}Console.WriteLine("进程杀死后,当前启动程序进程数:" + prolist1.Count);Console.WriteLine("线程开始 " + DateTime.Now.ToString());Console.WriteLine("开始删除无用的日志文件完成" + DateTime.Now.ToString());Log.DelateLog();Console.WriteLine("删除无用的日志文件完成" + DateTime.Now.ToString());#endregiontry{//执行主业务逻辑HandlePdf.HandlePdfContent();}catch (Exception exception){//任务失败,重启程序Log.WriteLog("run", exception.ToString());DateTime now = DateTime.Now;int SleepTime = int.Parse(ConfigurationManager.AppSettings["SleepTime"].ToString());Log.WriteLog("run", "替换出现异常,开始休眠" + SleepTime + "分钟.............." + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));while (DateTime.Now.AddMilliseconds(-60000.0 * SleepTime).CompareTo(now) <= 0){}try{Process.Start("pdfeditor");}catch (Exception ex){Log.WriteLog("run", ex.ToString());}}}}
}

pdf处理方法:

using Aspose.Pdf.Facades;
using Newtonsoft.Json;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace PdfEditor
{public class HandlePdf{//休眠时间public static int SleepTime = int.Parse(ConfigurationManager.AppSettings["SleepTime"].ToString());public static string pdfpath = ConfigurationManager.AppSettings["pdfpath"];public static string newpdfpath = ConfigurationManager.AppSettings["newpdfpath"];public static string newpdftohtmlpath = ConfigurationManager.AppSettings["htmlpath"];public static string firstContent = ConfigurationManager.AppSettings["firstContent"];public static string secondContent = ConfigurationManager.AppSettings["secondContent"];public static string thirdContent = ConfigurationManager.AppSettings["thirdContent"];public static string fourthContent = ConfigurationManager.AppSettings["fourthContent"];/// <summary>/// 每到设定好的时间都会自动执行此程序/// </summary>public static void HandlePdfContent(){Log.WriteLog("run", "————————————————————————————————————");Log.WriteLog("run", "************开始替换pdf数据************");Task[] tasks = new Task[1];tasks[0] = Task.Factory.StartNew(() => ExcuteHandle());Task.WaitAll(tasks);Log.WriteLog("run", "pdf数据替换完成,开始休眠" + SleepTime + "分钟..............");DateTime now = DateTime.Now;while (DateTime.Now.AddMilliseconds(-60000.0 * SleepTime).CompareTo(now) <= 0){}#region 重复执行try{HandlePdfContent();}catch (Exception exception){//任务失败,重启程序Log.WriteLog("run", exception.ToString());DateTime now1 = DateTime.Now;Log.WriteLog("run", "pdf替换出现异常,开始休眠" + SleepTime + "分钟.............." + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));while (DateTime.Now.AddMilliseconds(-60000.0 * SleepTime).CompareTo(now1) <= 0){}try{Process.Start("pdfeditor");}catch (Exception ex){Log.WriteLog("run", ex.ToString());}}#endregion}private static void ExcuteHandle(){List<string> resultList = GetAllFiles(pdfpath, null, ".pdf");if (resultList != null){Log.WriteLog("run", "总共获取到符合条件的pdf文件有" + resultList.Count + "个");Log.WriteLog("run", "符合条件的pdf文件路径如下:【" + JsonConvert.SerializeObject(resultList) + "】");List<List<string>> arrays = new List<List<string>>();List<string> contains_str = new List<string>();foreach (var temp in resultList){string FileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(temp);string queryCondition = FileNameWithoutExtension.Split('-')[0] + "-" + FileNameWithoutExtension.Split('-')[1]+ "-" + FileNameWithoutExtension.Split('-')[2];// +"-" + FileNameWithoutExtension.Split('-')[3];if (!contains_str.Contains(queryCondition)){contains_str.Add(queryCondition);}}foreach (var item in contains_str){var queryResults =from n in resultListwhere n.Contains(item)orderby nselect n;arrays.Add(queryResults.ToList());}foreach (var item in arrays){//添加文本域,返回新文件路径string newpdfpath = AddTextField(item[0], item[1]);//EditPdfFiled(newpdfpath);EditPdfFiled(item[1]);}}}private static string AddTextField(string item0, string item1){string filenamewithoutextension = System.IO.Path.GetFileNameWithoutExtension(item1);string date = filenamewithoutextension.Split('-')[2];DateTime dt = DateTime.ParseExact(date, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);string number = filenamewithoutextension.Split('-')[4];string newfilepath = pdfpath + newpdfpath;if (!Directory.Exists(newfilepath)){Directory.CreateDirectory(newfilepath);}string newfilename = System.IO.Path.GetFileName(item0);Spire.Pdf.PdfDocument document = new Spire.Pdf.PdfDocument();try{System.IO.TextReader tr = new StreamReader(System.AppDomain.CurrentDomain.BaseDirectory + ConfigurationManager.AppSettings["replaceTextPath"], Encoding.UTF8, true);document.LoadFromFile(item0);//新建黑色的画笔PdfPageBase page = document.Pages[0];PdfSolidBrush brush = new PdfSolidBrush(new PdfRGBColor(System.Drawing.Color.Black));//定义字体格式Spire.Pdf.Graphics.PdfTrueTypeFont font = new Spire.Pdf.Graphics.PdfTrueTypeFont(new Font("Arial", 10, System.Drawing.FontStyle.Bold), true);String strLine;while ((strLine = tr.ReadLine()) != null){if (strLine.Contains("bylo")){//获取文本所在区域System.Drawing.RectangleF rec = new System.Drawing.Rectangle(350, 70, 200, 200);System.Drawing.PointF position = new System.Drawing.Point(350, 70);//填充修改后的文本到文本域page.Canvas.DrawString(strLine, font, brush, position);}if (strLine.Contains("dne")){//获取文本所在区域System.Drawing.RectangleF rec = new System.Drawing.Rectangle(350, 83, 200, 200);System.Drawing.PointF position = new System.Drawing.Point(350, 83);string str = strLine.Split(':')[0] + ": " + dt.ToString("dd") + "." + dt.ToString("MM") + "." + dt.ToString("yyyy");//填充修改后的文本到文本域page.Canvas.DrawString(str, font, brush, position);}if (strLine.Contains("DSId")){//获取文本所在区域System.Drawing.RectangleF rec = new System.Drawing.Rectangle(350, 94, 400, 200);System.Drawing.PointF position = new System.Drawing.Point(350, 94);string str = strLine.Split(':')[0] + ": " + strLine.Split(':')[1] + number;//填充修改后的文本到文本域page.Canvas.DrawString(str, font, brush, position);}if (strLine.Contains("Stav")){//获取文本所在区域System.Drawing.RectangleF rec = new System.Drawing.Rectangle(350, 105, 200, 200);System.Drawing.PointF position = new System.Drawing.Point(350, 105);string str = strLine.Split(':')[0] + ": " + strLine.Split(':')[1];//填充修改后的文本到文本域page.Canvas.DrawString(str, font, brush, position);}}//保存文档document.SaveToFile(newfilepath + newfilename, FileFormat.PDF);}catch (Exception ex){Log.WriteLog("run", "出现异常,异常信息为:【" + ex.Message + "】");} document.Dispose();document.Close();return newfilepath + newfilename;}public static void EditPdfFiled(string pdffilepath){try{string Key = "zhaowohuoqu";new Aspose.Pdf.License().SetLicense(new MemoryStream(Convert.FromBase64String(Key)));string filename = System.IO.Path.GetFileName(pdffilepath);string newfilepath = pdfpath + newpdfpath;if (!Directory.Exists(newfilepath)){Directory.CreateDirectory(newfilepath);}PdfContentEditor pdfContentEditor = new PdfContentEditor();pdfContentEditor.BindPdf(pdffilepath); pdfContentEditor.ReplaceText("Beijing Tianyouyida Management Consulting Ltd Co", firstContent); pdfContentEditor.ReplaceText("9 9 9 9 9 9 9 9 9 9", secondContent); pdfContentEditor.ReplaceText("T i a n y o u  Z h o u / O p r á v n e n á  o s o b a", thirdContent); pdfContentEditor.ReplaceText("T i a n y o u  Z h o u / a g e n t", fourthContent);pdfContentEditor.Save(newfilepath + filename); }catch (Exception ex){Log.WriteLog("run", "出现异常,异常信息为:【" + ex.Message + "】");}}private static List<string> GetAllFiles(string path, List<string> resultList, string extension){if (resultList == null){resultList = new List<string>();}System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(path);System.IO.FileInfo[] files = di.GetFiles();foreach (System.IO.FileInfo fi in files){if (fi.Extension.ToLower() == extension){resultList.Add(fi.FullName);}}DirectoryInfo[] dirinfo = di.GetDirectories();for (int i = 0; i < dirinfo.Length; i++){if (!dirinfo[i].FullName.Contains("newpdf")){GetAllFiles(dirinfo[i].FullName, resultList, ".pdf");}}return resultList;}}
}

配置文件:

<?xml version="1.0" encoding="utf-8"?>
<configuration><appSettings><!--pdf存放路径--><add key="pdfpath" value="C:\Users\Administrator\Desktop\pdfeditor" /><!--休眠时间--><add key="SleepTime" value="60" /><!--被替换pdf存放路径--><add key="newpdfpath" value="/newpdf/" /> <!--要替换的内容--><add key="firstContent" value="Tianjin caiwu guanli gongsi" /><add key="secondContent" value="8888888888" /><add key="thirdContent" value="Mary Zhou/Agent" /><add key="fourthContent" value="Mary Zhou/Agent" /><add key="replaceTextPath" value="/需要添加文字.txt" /></appSettings><startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" /></startup><runtime><assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><dependentAssembly><assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" /><bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="BouncyCastle.Crypto" publicKeyToken="0e99375e54769942" culture="neutral" /><bindingRedirect oldVersion="0.0.0.0-1.8.9.0" newVersion="1.8.9.0" /></dependentAssembly></assemblyBinding></runtime>
</configuration>

相关文章:

使用C#和 aspose.total 实现替换pdf中的文字(外语:捷克语言的pdf),并生成新的pdf导出到指定路径

程序主入口&#xff1a; Program.cs &#xfeff;using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks;namespace PdfEditor {public class Progra…...

【Material-UI】Autocomplete中的高亮功能(Highlights)详解

文章目录 一、简介二、实现高亮功能示例代码代码解释 三、实际应用场景1. 搜索功能2. 表单自动完成 四、总结 在现代Web开发中&#xff0c;提供清晰的用户反馈是提升用户体验的重要组成部分。Material-UI的Autocomplete组件通过高亮功能&#xff0c;帮助用户快速识别搜索结果中…...

Android 11(R)启动流程 初版

启动流程 bootloader会去启动android第一个进程Idle&#xff0c;pid为0&#xff0c;会对进程 内存管理等进行初始化。Idle还被称作swapper。Idle会去创建两个进程&#xff0c;一个是init&#xff0c;另外一个是kthread。 kthread会去启动内核&#xff0c;用户是由init进行启动。…...

从零安装pytorch

背景介绍 目前主流使用的工具有Facebook搞的pythorch和谷歌开发的tensorflow两种&#xff0c;二者在实现理念上有一定区别&#xff0c;pytorch和人的思维模式与变成习惯更像&#xff0c;而tensorflow则是先构建整体结构&#xff0c;然后整体运行&#xff0c;开发调试过程较为繁…...

2024.07.28 校招 实习 内推 面经

绿*泡*泡VX&#xff1a; neituijunsir 交流*裙 &#xff0c;内推/实习/校招汇总表格 1、自动驾驶一周资讯 - 特斯拉FSD年底入华&#xff1f;理想成立“端到端”实体组织&#xff1b;小马智行或最快于今年9月赴美IPO 自动驾驶一周资讯 - 特斯拉FSD年底入华&#xff1f;理想…...

python实现小游戏——植物大战僵尸(魔改版本)

制作一款DIY的‘植物大战僵尸’游戏引起了很多人的兴趣。在这里&#xff0c;我将分享一个使用Python语言在PyCharm环境中开发的初始状态版本。这个版本主要应用了pygame库来完成&#xff0c;是一个充满创意和趣味的魔改版本。 文章目录 前言一、开发环境准备二、代码1.main方法…...

基于K210智能人脸识别+车牌识别系统(完整工程资料源码)

运行效果&#xff1a; 基于K210的智能人脸与车牌识别系统工程 目录&#xff1a; 运行效果&#xff1a; 目录&#xff1a; 前言&#xff1a; 一、国内外研究现状与发展趋势 二、相关技术基础 2.1 人脸识别技术 2.2 车牌识别技术 三、智能小区门禁系统设计 3.1 系统设计方案 3.2 …...

8.怎么配嵌套子路由,以及它的作用

作用 配嵌套子路由,就是可以通过同一个页面,让不同的位置发生变化,其他的位置不会发生变化,而做到一个局部刷新 例子 红线框住的部分,头部和导航栏是不会发生变化的,变化的只有中间的内容 子路由的操作步骤 将这个页面的头部和导航栏部分的样式和风格,移到主路由上(<tem…...

【海贼王航海日志:前端技术探索】HTML你学会了吗?(二)

目录 1 -> HTML常见标签 1.1 -> 表格标签 1.1.1 -> 基本使用 1.1.2 -> 合并单元格 1.2 -> 列表标签 1.3 -> 表单标签 1.3.1 -> form标签 1.3.2 -> input标签 1.4 -> label标签 1.5 -> select标签 1.6 -> textarea标签 1.7 -> …...

体系结构论文导读(三十一)(下):Soft errors in DNN accelerators: A comprehensive review

第五部分&#xff1a;DNN加速器中的软错误 本部分回顾和分析了有关人工神经网络&#xff08;ANN&#xff09;可靠性的研究。特别是关注通过DNN加速器解决DNN可靠性的研究&#xff0c;从软错误的角度进行探讨。许多前期工作声称ANN本身对故障具有固有的容错能力。然而&#xff…...

Python在指定文件夹下创建虚拟环境

基于不同python版本和第三方包版本开发的项目&#xff0c;为了方便学习和管理python环境&#xff0c;可以在指定的文件夹里创建项目所需的虚拟环境。具体流程如下&#xff1a; (1) 以管理员身份打开Ananconda Prompt&#xff0c;查看当前虚拟环境&#xff0c;输入命令如下&…...

【SpringBoot】 定时任务之任务执行和调度及使用指南

【SpringBoot】 定时任务之任务执行和调度及使用指南 Spring框架分别通过TaskExecutor和TaskScheduler接口为任务的异步执行和调度提供了抽象。Spring还提供了支持应用程序服务器环境中的线程池或CommonJ委托的那些接口的实现。最终&#xff0c;在公共接口后面使用这些实现&…...

理解 Objective-C 中 +load 方法的执行顺序

在 Objective-C 中&#xff0c;load 方法是在类或分类&#xff08;category&#xff09;被加载到内存时调用的。它的执行顺序非常严格&#xff0c;并且在应用启动过程中可能会导致一些令人困惑的行为。理解 load 方法的执行顺序对调试和控制应用的初始化过程非常重要。 load 方…...

切面条问题算法的详解

切面条问题是一个经典的动态规划问题&#xff0c;也称为切钢条问题。问题描述为&#xff1a;给定一根长度为n的钢条和一个价格表P[i]&#xff0c;表示长度为i的钢条的价格。求解如何切割钢条使得收益最大。 解决这个问题的关键是找到一个最优子结构和递推关系。 首先&#xf…...

JNDI注入

&#x1f3bc;个人主页&#xff1a;金灰 &#x1f60e;作者简介:一名简单的大一学生;易编橙终身成长社群的嘉宾.✨ 专注网络空间安全服务,期待与您的交流分享~ 感谢您的点赞、关注、评论、收藏、是对我最大的认可和支持&#xff01;❤️ &#x1f34a;易编橙终身成长社群&#…...

SQL Server数据库文件过大而无法直接导出解决方案

目录 1. 使用分割备份 (Split Backup) 2. 使用文件和文件组备份 (File and Filegroup Backup) 3. 使用压缩备份 (Compressed Backup) 4. 逻辑备份 (BCP工具) 5. 使用导出工具 (SQL Server Management Studio) 6. 部分备份 (Partial Backup) 7. 使用第三方工具 1. 使用分割…...

学习日志8.4--DHCP攻击防范

目录 DHCP饿死攻击 DHCP Sever仿冒攻击 DHCP攻击防范 DHCP动态主机配置协议&#xff0c;是给主机提供自动获取IP地址等配置信息的服务。在主机对DHCP服务器发送DHCP Discover请求之后&#xff0c;服务器回复offer&#xff0c;主机再回复request&#xff0c;最后服务器回复AC…...

解决多个Jenkins Master实例共享Jenkins_home目录的问题(加锁解锁机制)

在Jenkins的持续集成和持续部署&#xff08;CI/CD&#xff09;环境中&#xff0c;JENKINS_HOME目录扮演着至关重要的角色。它存储了Jenkins的配置、插件、作业历史记录等核心数据。然而&#xff0c;在某些场景下&#xff0c;我们可能面临多个Jenkins master实例需要共享同一个J…...

postgresql array 反向截取

postgresql array 反向截取 array_to_string((string_to_array(REPLACE(delcell.小区网管名称,‘‘,’-‘),’-‘))[:array_length(string_to_array(REPLACE(delcell.小区网管名称,’’,‘-’),‘-’),1)-1],‘-’) as 基站名称 在PostgreSQL中&#xff0c;如果你想要对数组进…...

最新口型同步技术EchoMimic部署

EchoMimic是由蚂蚁集团推出的一个 AI 驱动的口型同步技术项目&#xff0c;能够通过人像面部特征和音频来帮助人物“对口型”&#xff0c;生成逼真的动态肖像视频。 EchoMimic的技术亮点在于其创新的动画生成方法&#xff0c;它不仅能够通过音频和面部关键点单独驱动图像动画&a…...

downkyi全链路解决方案:从视频获取到专业处理的一站式视频工作流指南

downkyi全链路解决方案&#xff1a;从视频获取到专业处理的一站式视频工作流指南 【免费下载链接】downkyi 哔哩下载姬downkyi&#xff0c;哔哩哔哩网站视频下载工具&#xff0c;支持批量下载&#xff0c;支持8K、HDR、杜比视界&#xff0c;提供工具箱&#xff08;音视频提取、…...

提升效率:用快马ai生成ubuntu一键自动化安装openclaw的脚本

最近在Ubuntu上安装OpenClaw时&#xff0c;发现手动操作既耗时又容易出错。经过一番摸索&#xff0c;我总结出一套自动化方案&#xff0c;用脚本把整个流程优化到了极致。这里分享下具体实现思路和效率提升的关键点。 环境检测与适配 脚本首先会检查Ubuntu版本和架构&#xff0…...

基于多模态图像融合与深度学习算法的轴承故障诊断模型——GADF+Swin-CNN-GAM与GA...

基于 GADFSwin-CNN-GAM 的高创新轴承故障诊断模型 基于GADFTransformer的轴承故障诊断模型&#xff0c;附说明文件及相关论文&#xff0c;代码一定能跑通&#xff0c;有格拉姆角场GADF&#xff0c;小波变换DWT还有短时傅立叶变换STFT多种转二维图像的方式轴承故障诊断这事儿吧&…...

丹青识画快速部署:开箱即用,体验智能影像理解与书法生成

丹青识画快速部署&#xff1a;开箱即用&#xff0c;体验智能影像理解与书法生成 1. 产品概览&#xff1a;当AI遇见东方美学 丹青识画是一款融合深度学习与东方美学的智能影像理解系统。它能够像一位精通诗书画的文人雅士般&#xff0c;精准解读画面内容&#xff0c;并以行云流…...

如何用LangChain开发一个Agent,20分钟包教包会!

26年一定是一个 Agent 大年&#xff0c;我这边持续出系列文章&#xff0c;帮助大家更好的落地 Agent&#xff0c;今天的重点是程序员最常用的 Agent 框架 LangChain。 只不过这东西可能由于 AI Coding 的成熟&#xff0c;由给人看变成给 AI 看的。 LangChain 既是一个开源的A…...

ROS2 Humble实战:用QoS解决机器人通信丢包,保姆级代码配置避坑

ROS2 Humble实战&#xff1a;用QoS策略解决机器人通信丢包问题 当你的移动机器人在执行SLAM建图任务时突然出现地图撕裂&#xff0c;或者机械臂协同控制时发生指令延迟&#xff0c;这些看似随机的问题背后往往隐藏着一个共同的元凶——通信丢包。ROS2的QoS&#xff08;Quality …...

Java原生互操作终极方案(JEP 454/459/460深度落地):银行系统JNI迁移真实压测数据全披露

第一章&#xff1a;Java原生互操作终极方案&#xff08;JEP 454/459/460深度落地&#xff09;&#xff1a;银行系统JNI迁移真实压测数据全披露在某国有大型商业银行核心支付清算子系统中&#xff0c;我们完成了从传统JNI到JEP 454&#xff08;Foreign Function & Memory AP…...

OpenClaw+Phi-3-vision-128k-instruct数据标注:半自动生成图像标签训练集

OpenClawPhi-3-vision-128k-instruct数据标注&#xff1a;半自动生成图像标签训练集 1. 为什么需要半自动数据标注 去年我在做一个宠物品种识别项目时&#xff0c;最头疼的就是数据标注环节。手动给5000多张猫狗图片打标签&#xff0c;不仅耗时耗力&#xff0c;还容易因为疲劳…...

证书配置与资源拦截全攻略:res-downloader高效使用指南

证书配置与资源拦截全攻略&#xff1a;res-downloader高效使用指南 【免费下载链接】res-downloader 视频号、小程序、抖音、快手、小红书、直播流、m3u8、酷狗、QQ音乐等常见网络资源下载! 项目地址: https://gitcode.com/GitHub_Trending/re/res-downloader res-downl…...

tao-8k Embedding模型实操手册:从文本输入到向量相似度计算完整流程

tao-8k Embedding模型实操手册&#xff1a;从文本输入到向量相似度计算完整流程 你是不是经常遇到这样的问题&#xff1a;想要比较两段文字的相似度&#xff0c;却不知道从何下手&#xff1f;或者需要处理超长文本&#xff0c;但现有的工具总是力不从心&#xff1f;今天我要介…...