当前位置: 首页 > 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>

http://www.lryc.cn/news/415101.html

相关文章:

  • 【Material-UI】Autocomplete中的高亮功能(Highlights)详解
  • Android 11(R)启动流程 初版
  • 从零安装pytorch
  • 2024.07.28 校招 实习 内推 面经
  • python实现小游戏——植物大战僵尸(魔改版本)
  • 基于K210智能人脸识别+车牌识别系统(完整工程资料源码)
  • 8.怎么配嵌套子路由,以及它的作用
  • 【海贼王航海日志:前端技术探索】HTML你学会了吗?(二)
  • 体系结构论文导读(三十一)(下):Soft errors in DNN accelerators: A comprehensive review
  • Python在指定文件夹下创建虚拟环境
  • 【SpringBoot】 定时任务之任务执行和调度及使用指南
  • 理解 Objective-C 中 +load 方法的执行顺序
  • 切面条问题算法的详解
  • JNDI注入
  • SQL Server数据库文件过大而无法直接导出解决方案
  • 学习日志8.4--DHCP攻击防范
  • 解决多个Jenkins Master实例共享Jenkins_home目录的问题(加锁解锁机制)
  • postgresql array 反向截取
  • 最新口型同步技术EchoMimic部署
  • 程序设计基础(c语言)_补充_1
  • 8.4 day bug
  • 【Material-UI】Autocomplete中的禁用选项:Disabled options
  • Pytest测试报告生成专题
  • QT 笔记
  • 【redis 第七篇章】动态字符串
  • rk3588 部署yolov8.rknn
  • 【正点原子i.MX93开发板试用连载体验】中文提示词的训练
  • WordPress资源下载类主题 CeoMax-Pro_v7.6绕授权开心版
  • 使用GCC编译Notepad++的插件
  • 技术周总结 2024.07.29 ~ 08.04周日(MyBatis, 极限编程)