Created
July 25, 2024 20:24
-
-
Save CodeCouturiers/54265ac366e4319e248d1336e56c0130 to your computer and use it in GitHub Desktop.
Replace text in the document
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using Spire.Doc; | |
using Spire.Doc.Documents; | |
namespace doc_to_text | |
{ | |
public class DocxConverter | |
{ | |
public enum OutputFormat | |
{ | |
Text, | |
Xml, | |
} | |
public static void ConvertDocx(string inputPath, string outputPath, OutputFormat format, string textToReplace = null, string replacementText = null) | |
{ | |
try | |
{ | |
if (!File.Exists(inputPath)) | |
{ | |
throw new FileNotFoundException("Input file not found.", inputPath); | |
} | |
Document document = new Document(); | |
document.LoadFromFile(inputPath); | |
if (!string.IsNullOrEmpty(textToReplace) && !string.IsNullOrEmpty(replacementText)) | |
{ | |
// Replace text in the document | |
document.Replace(textToReplace, replacementText, true, true); | |
} | |
FileFormat saveFormat; | |
switch (format) | |
{ | |
case OutputFormat.Text: | |
saveFormat = FileFormat.Txt; | |
break; | |
case OutputFormat.Xml: | |
saveFormat = FileFormat.Docx2019; | |
break; | |
case OutputFormat.Pdf: | |
saveFormat = FileFormat.PDF; | |
break; | |
default: | |
throw new ArgumentException("Unsupported output format."); | |
} | |
document.SaveToFile(outputPath, saveFormat); | |
Console.WriteLine($"Conversion complete. File saved to {outputPath}"); | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine($"An error occurred: {ex.Message}"); | |
} | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// Convert to PDF and replace text | |
DocxConverter.ConvertDocx( | |
"input.docx", | |
"output.pdf", | |
DocxConverter.OutputFormat.Pdf, | |
"$cs_1_alpha_2$", | |
"EDITED" | |
); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment