c#pdf file home page batch adds photo watermarks and makes the pdf file name consistent with the subdirectory file name and adds a progress bar that can be terminated at any time
using Spire.Pdf; using Spire.Pdf.Annotations; using Spire.Pdf.Graphics; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml.Linq; using System.Threading; namespace WindowsFormsApp1 {<!-- --> public partial class Form1 : Form {<!-- --> private BackgroundWorker worker; private bool stopProgress; private bool isTerminated; public Form1() {<!-- --> InitializeComponent(); button1.Click + = new System.EventHandler(button1_Click); button2.Click + = new System.EventHandler(stopButton_Click); //Initialize BackgroundWorker worker = new BackgroundWorker(); worker.WorkerReportsProgress = true; worker.WorkerSupportsCancellation = true; //Set to support cancellation operation worker.DoWork + = Worker_DoWork; worker.ProgressChanged + = Worker_ProgressChanged; worker.RunWorkerCompleted + = Worker_RunWorkerCompleted; } //Watermark photo storage path string watermarkImagePath = "C:\Users\20755\Desktop\test\444.png"; //string watermarkImagePath = "C:\Users\\Administrator\Desktop\test\444.png"; //string extName = "*.pdf"; //List<string> nameList = new List<string>(); private void button1_Click(object sender, EventArgs e) {<!-- --> FolderBrowserDialog folder = new FolderBrowserDialog(); folder.Description = "Open Folder"; if (folder.ShowDialog() == DialogResult.OK) {<!-- --> // disable button button1.Enabled = false; //Start BackgroundWorker to perform background operations worker.RunWorkerAsync(folder.SelectedPath); } } // Background operation to generate watermarked function private void Worker_DoWork(object sender, DoWorkEventArgs e) {<!-- --> try {<!-- --> string folderPath = e.Argument as string; string[] pdfFiles = Directory.GetFiles(folderPath, "*.pdf", SearchOption.AllDirectories); int totalFiles = pdfFiles.Length; int processedFiles = 0; foreach (string pdfFile in pdfFiles) {<!-- --> if (worker.CancellationPending) {<!-- --> e.Cancel = true; return; } using (PdfDocument document = new PdfDocument()) {<!-- --> document.LoadFromFile(pdfFile); PdfPageBase firstPage = document.Pages[0]; // Get the first page //Add watermark Image image = Image.FromFile(watermarkImagePath); int imgWidth = image.Width; int imgHeight = image.Height; float pageWidth = firstPage.ActualSize.Width; float pageHeight = firstPage.ActualSize.Height; firstPage.BackgroundOpacity = 1f; firstPage.BackgroundImage = image; Rectangle rect = new Rectangle(200, 0, 200, 125); firstPage.BackgroundRegion = rect; //string outputFolder = "C:\Users\Administrator\Desktop\test\ ewDir"; string outputFolder = "C:\Users\20755\Desktop\test\\ ewDir"; Directory.CreateDirectory(outputFolder); // Relative path: get the directory name based on the location of the pdf and start intercepting from the folder location selected at the beginning //Equivalent to pdfFile= C:\Users\\Administrator\Desktop\test\111\1.pdf //relativePath =\test\111\1.pdf string relativePath = Path.GetDirectoryName(pdfFile).Substring(folderPath.Length); if (relativePath.StartsWith("\")) //If the path starts with \, then intercept it from position 2 //relativePath =111 The purpose of doing this is actually to get the directory folder name of the upper level of the pdf //If it is multi-level nesting, the logic of this place needs to be added. relativePath = relativePath.Substring(1); // Directory name Make sure the file name and directory name are consistent string dirName = Path.GetFileName(Path.GetDirectoryName(pdfFile)); // new folder string newFolderPath = Path.Combine(outputFolder, relativePath); Directory.CreateDirectory(newFolderPath); //Rename the file name according to the directory string newFileName = dirName + ".pdf"; string newFilePath = Path.Combine(newFolderPath, newFileName); //string outputFilePath = Path.Combine(newFolderPath, Path.GetFileName(pdfFile)); document.SaveToFile(newFilePath); document.Close(); processedFiles + + ; //Send progress report int progressPercentage = (int)((float)processedFiles / totalFiles * 100); worker.ReportProgress(progressPercentage); } } } catch(Exceptioner) {<!-- --> // Handle any exceptions } } // Progress report update UI private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e) {<!-- --> //Update the value of the progress bar progressBar1.Value = e.ProgressPercentage; } //Background operation completed private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {<!-- --> if (e.Cancelled) {<!-- --> MessageBox.Show("Progress has been terminated!"); } else if (e.Error != null) {<!-- --> MessageBox.Show("An error occurred:" + e.Error.Message); } else {<!-- --> MessageBox.Show("Watermark added successfully!"); } // enable button button1.Enabled = true; //End application Application.Exit(); } private void stopButton_Click(object sender, EventArgs e) {<!-- --> // Set flag variable to terminate progress stopProgress = true; // Terminate BackgroundWorker if (worker.IsBusy) {<!-- --> worker.CancelAsync(); } } } }