static void Search() { //open document Document pdfDocument = new Document(Config.TestPdf); string keyword = "pattern"; //create TextAbsorber object to find all instances of the input search phrase TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(keyword); //accept the absorber for all the pages pdfDocument.Pages.Accept(textFragmentAbsorber); //get the extracted text fragments TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; //loop through the fragments foreach (TextFragment textFragment in textFragmentCollection) { Console.WriteLine("Page Number : {0} ", textFragment.Page.Number); //Console.WriteLine("Text : {0} ", textFragment.Text); //Console.WriteLine("Position : {0} ", textFragment.Position); //Console.WriteLine("XIndent : {0} ", textFragment.Position.XIndent); //Console.WriteLine("YIndent : {0} ", textFragment.Position.YIndent); //Console.WriteLine("Font - Name : {0}", textFragment.TextState.Font.FontName); //Console.WriteLine("Font - IsAccessible : {0} ", textFragment.TextState.Font.IsAccessible); //Console.WriteLine("Font - IsEmbedded : {0} ", textFragment.TextState.Font.IsEmbedded); //Console.WriteLine("Font - IsSubset : {0} ", textFragment.TextState.Font.IsSubset); //Console.WriteLine("Font Size : {0} ", textFragment.TextState.FontSize); //Console.WriteLine("Foreground Color : {0} ", textFragment.TextState.ForegroundColor); } }
/// <summary> /// Written by Fredio /// </summary> /// <param name="path"></param> /// <param name="phrase"></param> /// <returns></returns> public System.IO.MemoryStream SearcText(string path, string phrase) { InjectAsposeLicemse(); Aspose.Pdf.Document document = new Aspose.Pdf.Document(path); string searchTextValue = string.Format("(?i){0}", phrase); TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(searchTextValue, new TextSearchOptions(true)); //TextSearchOptions textSearchOptions = new TextSearchOptions(true); //textFragmentAbsorber.TextSearchOptions = textSearchOptions; document.Pages.Accept(textFragmentAbsorber); TextFragmentCollection textFragmentCollection1 = textFragmentAbsorber.TextFragments; if (textFragmentCollection1.Count > 0) { foreach (TextFragment textFragment in textFragmentCollection1) { Aspose.Pdf.Annotations.HighlightAnnotation freeText = new Aspose.Pdf.Annotations.HighlightAnnotation(textFragment.Page, new Aspose.Pdf.Rectangle(textFragment.Position.XIndent, textFragment.Position.YIndent, textFragment.Position.XIndent + textFragment.Rectangle.Width, textFragment.Position.YIndent + textFragment.Rectangle.Height)); freeText.Opacity = 0.5; //freeText.Color = Aspose.Pdf.Color.FromRgb(0.6, 0.8, 0.98); freeText.Color = Aspose.Pdf.Color.Yellow; textFragment.Page.Annotations.Add(freeText); } } System.IO.MemoryStream ms = new System.IO.MemoryStream(); document.Save(ms); return(ms); }
public static void Run() { // ExStart:ReplaceTextAll // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); // Open document Document pdfDocument = new Document(dataDir + "ReplaceTextAll.pdf"); // Create TextAbsorber object to find all instances of the input search phrase TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("text"); // Accept the absorber for all the pages pdfDocument.Pages.Accept(textFragmentAbsorber); // Get the extracted text fragments TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; // Loop through the fragments foreach (TextFragment textFragment in textFragmentCollection) { // Update text and other properties textFragment.Text = "TEXT"; textFragment.TextState.Font = FontRepository.FindFont("Verdana"); textFragment.TextState.FontSize = 22; textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Blue); textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Green); } dataDir = dataDir + "ReplaceTextAll_out_.pdf"; // Save resulting PDF document. pdfDocument.Save(dataDir); // ExEnd:ReplaceTextAll Console.WriteLine("\nText replaced successfully.\nFile saved at " + dataDir); }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //open document Document pdfDocument = new Document(dataDir + "input.pdf"); //create TextAbsorber object to find all instances of the input search phrase TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("text"); //accept the absorber for all the pages pdfDocument.Pages.Accept(textFragmentAbsorber); //get the extracted text fragments TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; //loop through the fragments foreach (TextFragment textFragment in textFragmentCollection) { //update text and other properties textFragment.Text = "TEXT"; textFragment.TextState.Font = FontRepository.FindFont("Verdana"); textFragment.TextState.FontSize = 22; textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Blue); textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Green); } // Save resulting PDF document. pdfDocument.Save(dataDir + "output.pdf"); // Let user know about the outcome of the processing. System.Console.WriteLine("Text replaced successfully!"); }
public ActionResult DownloadCertificate() { string dataDir = Server.MapPath("~/Images/test.pdf"); // Open document Document pdfDocument = new Document(dataDir); // Create TextAbsorber object to find all instances of the input search phrase TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("Name"); // Accept the absorber for all the pages pdfDocument.Pages.Accept(textFragmentAbsorber); // Get the extracted text fragments TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; // Loop through the fragments foreach (TextFragment textFragment in textFragmentCollection) { // Update text and other properties textFragment.Text = "HIYA HIYA HIYA"; } dataDir = dataDir + "test3.pdf"; // Save resulting PDF document. pdfDocument.Save(dataDir); return(View()); }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //open document Document pdfDocument = new Document(dataDir + "input.pdf"); //create TextAbsorber object to find all instances of the input search phrase TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("text"); //accept the absorber for all the pages pdfDocument.Pages.Accept(textFragmentAbsorber); //get the extracted text fragments TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; //loop through the fragments foreach (TextFragment textFragment in textFragmentCollection) { foreach (TextSegment textSegment in textFragment.Segments) { Console.WriteLine("Text : {0} ", textSegment.Text); Console.WriteLine("Position : {0} ", textSegment.Position); Console.WriteLine("XIndent : {0} ", textSegment.Position.XIndent); Console.WriteLine("YIndent : {0} ", textSegment.Position.YIndent); Console.WriteLine("Font - Name : {0}", textSegment.TextState.Font.FontName); Console.WriteLine("Font - IsAccessible : {0} ", textSegment.TextState.Font.IsAccessible); Console.WriteLine("Font - IsEmbedded : {0} ", textSegment.TextState.Font.IsEmbedded); Console.WriteLine("Font - IsSubset : {0} ", textSegment.TextState.Font.IsSubset); Console.WriteLine("Font Size : {0} ", textSegment.TextState.FontSize); Console.WriteLine("Foreground Color : {0} ", textSegment.TextState.ForegroundColor); } } }
public static void Run() { // ExStart:ReplaceFirstOccurrence // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); // Open document Document pdfDocument = new Document(dataDir + "ReplaceTextPage.pdf"); // Create TextAbsorber object to find all instances of the input search phrase TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("text"); // Accept the absorber for all the pages pdfDocument.Pages.Accept(textFragmentAbsorber); // Get the extracted text fragments TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; if (textFragmentCollection.Count > 0) { // Get first occurance of text and replace TextFragment textFragment = textFragmentCollection[1]; // Update text and other properties textFragment.Text = "New Phrase"; textFragment.TextState.Font = FontRepository.FindFont("Verdana"); textFragment.TextState.FontSize = 22; textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Blue); dataDir = dataDir + "ReplaceFirstOccurrence_out_.pdf"; pdfDocument.Save(dataDir); Console.WriteLine("\nText replaced successfully.\nFile saved at " + dataDir); } // ExEnd:ReplaceFirstOccurrence }
public IHttpActionResult DownloadCertificate(string idEvent, string nameParticipant) { string dataDir = "http://localhost:49661/Images/test.pdf"; //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(dataDir); //HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //Stream receiveStream = response.GetResponseStream(); HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(dataDir); WebResponse myResp = myReq.GetResponse(); StreamReader reader = new StreamReader(myResp.GetResponseStream()); Document pdfDocument = new Document(reader.BaseStream); TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("Name"); pdfDocument.Pages.Accept(textFragmentAbsorber); TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; foreach (TextFragment textFragment in textFragmentCollection) { // Update text and other properties textFragment.Text = nameParticipant; } dataDir = dataDir + "/Images/" + idEvent + "_" + nameParticipant + ".pdf"; pdfDocument.Save(dataDir); return(Ok(dataDir)); }
public static void Run() { // ExStart:SearchAndGetTextAll // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); // Open document Document pdfDocument = new Document(dataDir + "SearchAndGetTextFromAll.pdf"); // Create TextAbsorber object to find all instances of the input search phrase TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("text"); // Accept the absorber for all the pages pdfDocument.Pages.Accept(textFragmentAbsorber); // Get the extracted text fragments TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; // Loop through the fragments foreach (TextFragment textFragment in textFragmentCollection) { Console.WriteLine("Text : {0} ", textFragment.Text); Console.WriteLine("Position : {0} ", textFragment.Position); Console.WriteLine("XIndent : {0} ", textFragment.Position.XIndent); Console.WriteLine("YIndent : {0} ", textFragment.Position.YIndent); Console.WriteLine("Font - Name : {0}", textFragment.TextState.Font.FontName); Console.WriteLine("Font - IsAccessible : {0} ", textFragment.TextState.Font.IsAccessible); Console.WriteLine("Font - IsEmbedded : {0} ", textFragment.TextState.Font.IsEmbedded); Console.WriteLine("Font - IsSubset : {0} ", textFragment.TextState.Font.IsSubset); Console.WriteLine("Font Size : {0} ", textFragment.TextState.FontSize); Console.WriteLine("Foreground Color : {0} ", textFragment.TextState.ForegroundColor); } // ExEnd:SearchAndGetTextAll }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); //open document Document pdfDocument = new Document(dataDir + "ReplaceTextPage.pdf"); //create TextAbsorber object to find all instances of the input search phrase TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("text"); //accept the absorber for a particular page pdfDocument.Pages[2].Accept(textFragmentAbsorber); //get the extracted text fragments TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; //loop through the fragments foreach (TextFragment textFragment in textFragmentCollection) { //update text and other properties textFragment.Text = "New Phrase"; textFragment.TextState.Font = FontRepository.FindFont("Verdana"); textFragment.TextState.FontSize = 22; textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Blue); textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Green); } pdfDocument.Save(dataDir + "ReplaceTextPage_out.pdf"); }
public static void Run() { //ExStart: SearchTextWithDotNetRegex string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); // Create Regex object to find all words System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"[\S]+"); // Open document Aspose.Pdf.Document document = new Aspose.Pdf.Document(dataDir + "SearchTextRegex.pdf"); // Get a particular page Page page = document.Pages[1]; // Create TextAbsorber object to find all instances of the input regex TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(regex); textFragmentAbsorber.TextSearchOptions.IsRegularExpressionUsed = true; // Accept the absorber for the page page.Accept(textFragmentAbsorber); // Get the extracted text fragments TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; // Loop through the fragments foreach (TextFragment textFragment in textFragmentCollection) { Console.WriteLine(textFragment.Text); } //ExEnd: SearchTextWithDotNetRegex }
public static void Run() { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Annotations(); Document doc = new Document(dataDir + "ExtractHighlightedText.pdf"); // Loop through all the annotations foreach (Annotation annotation in doc.Pages[1].Annotations) { // Filter TextMarkupAnnotation if (annotation is TextMarkupAnnotation) { TextMarkupAnnotation highlightedAnnotation = annotation as TextMarkupAnnotation; // Retrieve highlighted text fragments TextFragmentCollection collection = highlightedAnnotation.GetMarkedTextFragments(); foreach (TextFragment tf in collection) { // Display highlighted text Console.WriteLine(tf.Text); } } } // ExEnd:1 }
static void SearchWithRegularExpression() { //open document Document pdfDocument = new Document(Config.TestPdf); //create TextAbsorber object to find all the phrases matching the regular expression TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("\\d{4}-\\d{4}"); //like 1999-2000 //###set text search option to specify regular expression usage TextSearchOptions textSearchOptions = new TextSearchOptions(true); textFragmentAbsorber.TextSearchOptions = textSearchOptions; //accept the absorber for all the pages pdfDocument.Pages.Accept(textFragmentAbsorber); //get the extracted text fragments TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; //loop through the fragments foreach (TextFragment textFragment in textFragmentCollection) { Console.WriteLine("Text : {0} ", textFragment.Text); //Console.WriteLine("Position : {0} ", textFragment.Position); //Console.WriteLine("XIndent : {0} ", textFragment.Position.XIndent); //Console.WriteLine("YIndent : {0} ", textFragment.Position.YIndent); //Console.WriteLine("Font - Name : {0}", textFragment.TextState.Font.FontName); //Console.WriteLine("Font - IsAccessible : {0} ", textFragment.TextState.Font.IsAccessible); //Console.WriteLine("Font - IsEmbedded : {0} ", textFragment.TextState.Font.IsEmbedded); //Console.WriteLine("Font - IsSubset : {0} ", textFragment.TextState.Font.IsSubset); //Console.WriteLine("Font Size : {0} ", textFragment.TextState.FontSize); //Console.WriteLine("Foreground Color : {0} ", textFragment.TextState.ForegroundColor); } }
public static void Run() { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); string outputFile = dataDir + "Tooltip_out.pdf"; // Create sample document with text Document doc = new Document(); doc.Pages.Add().Paragraphs.Add(new TextFragment("Move the mouse cursor here to display a tooltip")); doc.Pages[1].Paragraphs.Add(new TextFragment("Move the mouse cursor here to display a very long tooltip")); doc.Save(outputFile); // Open document with text Document document = new Document(outputFile); // Create TextAbsorber object to find all the phrases matching the regular expression TextFragmentAbsorber absorber = new TextFragmentAbsorber("Move the mouse cursor here to display a tooltip"); // Accept the absorber for the document pages document.Pages.Accept(absorber); // Get the extracted text fragments TextFragmentCollection textFragments = absorber.TextFragments; // Loop through the fragments foreach (TextFragment fragment in textFragments) { // Create invisible button on text fragment position ButtonField field = new ButtonField(fragment.Page, fragment.Rectangle); // AlternateName value will be displayed as tooltip by a viewer application field.AlternateName = "Tooltip for text."; // Add button field to the document document.Form.Add(field); } // Next will be sapmle of very long tooltip absorber = new TextFragmentAbsorber("Move the mouse cursor here to display a very long tooltip"); document.Pages.Accept(absorber); textFragments = absorber.TextFragments; foreach (TextFragment fragment in textFragments) { ButtonField field = new ButtonField(fragment.Page, fragment.Rectangle); // Set very long text field.AlternateName = "Lorem ipsum dolor sit amet, consectetur adipiscing elit," + " sed do eiusmod tempor incididunt ut labore et dolore magna" + " aliqua. Ut enim ad minim veniam, quis nostrud exercitation" + " ullamco laboris nisi ut aliquip ex ea commodo consequat." + " Duis aute irure dolor in reprehenderit in voluptate velit" + " esse cillum dolore eu fugiat nulla pariatur. Excepteur sint" + " occaecat cupidatat non proident, sunt in culpa qui officia" + " deserunt mollit anim id est laborum."; document.Form.Add(field); } // Save document document.Save(outputFile); // ExEnd:1 }
public IHttpActionResult ReplaceText(ReplaceTextModel replaceTextModel) { var documentFileName = System.IO.Path.Combine(Config.Configuration.WorkingDirectory, "Editor", replaceTextModel.documentId, "document.pdf"); try { Document doc = new Document(documentFileName); // TODO: Imporve alghorithm //create TextAbsorber object to find all instances of the input search phrase //TextFragmentAbsorber textFragmentAbsorber = // new TextFragmentAbsorber("(?i)" + replaceTextModel.txtFind, new TextSearchOptions(true)) // { // TextReplaceOptions = // { // ReplaceAdjustmentAction = TextReplaceOptions.ReplaceAdjustment.WholeWordsHyphenation // } // }; TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(replaceTextModel.txtFind); doc.Pages.Accept(textFragmentAbsorber); //get the extracted text fragments TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; //loop through the fragments foreach (TextFragment textFragment in textFragmentCollection) { //update text and other properties textFragment.Text = replaceTextModel.txtReplace; } doc.Save(documentFileName); //doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf")); var downloadedMessageInfo = new DirectoryInfo(Path.GetDirectoryName(documentFileName)); foreach (FileInfo file in downloadedMessageInfo.GetFiles("*.png")) { file.Delete(); } var model = new DocStatusModel { d = ImageConverter(documentFileName), Path = replaceTextModel.documentId }; return(Ok(replaceTextModel)); } catch (Exception ex) { return(InternalServerError(ex)); } }
public void HideHeader(string fileName, string newFileName, Document pdfDocument) { TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("Employment History"); pdfDocument.Pages[1].Accept(textFragmentAbsorber); TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; if (textFragmentCollection.Any()) { foreach (TextFragment textFragment in textFragmentCollection) { textFragment.TextState.Invisible = true; } } }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); //open document Document pdfDocument = new Document(dataDir + "SearchRegularExpressionPage.pdf"); //create TextAbsorber object to find all the phrases matching the regular expression TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("\\d{4}-\\d{4}"); //like 1999-2000 //set text search option to specify regular expression usage TextSearchOptions textSearchOptions = new TextSearchOptions(true); textFragmentAbsorber.TextSearchOptions = textSearchOptions; //accept the absorber for a single page pdfDocument.Pages[1].Accept(textFragmentAbsorber); //get the extracted text fragments TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; //loop through the fragments foreach (TextFragment textFragment in textFragmentCollection) { Console.WriteLine("Text : {0} ", textFragment.Text); Console.WriteLine("Position : {0} ", textFragment.Position); Console.WriteLine("XIndent : {0} ", textFragment.Position.XIndent); Console.WriteLine("YIndent : {0} ", textFragment.Position.YIndent); Console.WriteLine("Font - Name : {0}", textFragment.TextState.Font.FontName); Console.WriteLine("Font - IsAccessible : {0} ", textFragment.TextState.Font.IsAccessible); Console.WriteLine("Font - IsEmbedded : {0} ", textFragment.TextState.Font.IsEmbedded); Console.WriteLine("Font - IsSubset : {0} ", textFragment.TextState.Font.IsSubset); Console.WriteLine("Font Size : {0} ", textFragment.TextState.FontSize); Console.WriteLine("Foreground Color : {0} ", textFragment.TextState.ForegroundColor); } }
public IHttpActionResult DownloadCertificate(string idEvent, string nameParticipant) { string dataDir = HttpContext.Current.Request.UserHostName; Document pdfDocument = new Document(dataDir + "/Images/test.pdf"); TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("Name"); pdfDocument.Pages.Accept(textFragmentAbsorber); TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; foreach (TextFragment textFragment in textFragmentCollection) { // Update text and other properties textFragment.Text = nameParticipant; } dataDir = dataDir + "/Images/" + idEvent + "_" + nameParticipant + ".pdf"; pdfDocument.Save(dataDir); return(Ok()); }
public int Highlight(Document pdfDocument, List <string> highlightPhrases) { int highlights = 0; TextFragmentAbsorber textAbsorder; foreach (string higlightPhrase in highlightPhrases) { textAbsorder = new TextFragmentAbsorber("(?i)" + higlightPhrase, new TextSearchOptions(true)); TextFragmentCollection txtFragmentCollection = textAbsorder.TextFragments; pdfDocument.Pages.Accept(textAbsorder); highlights += txtFragmentCollection.Count; foreach (TextFragment tf in txtFragmentCollection) { tf.TextState.BackgroundColor = Color.Yellow; } } return(highlights); }
public static void Run() { // ExStart:ReplaceTextonRegularExpression // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); // Open document Document pdfDocument = new Document(dataDir + "SearchRegularExpressionPage.pdf"); // Create TextAbsorber object to find all the phrases matching the regular expression TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("\\d{4}-\\d{4}"); //like 1999-2000 // Set text search option to specify regular expression usage TextSearchOptions textSearchOptions = new TextSearchOptions(true); textFragmentAbsorber.TextSearchOptions = textSearchOptions; // Accept the absorber for a single page pdfDocument.Pages[1].Accept(textFragmentAbsorber); // Get the extracted text fragments TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; // Loop through the fragments foreach (TextFragment textFragment in textFragmentCollection) { // Update text and other properties textFragment.Text = "New Phrase"; // Set to an instance of an object. textFragment.TextState.Font = FontRepository.FindFont("Verdana"); textFragment.TextState.FontSize = 22; textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Blue); textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Green); } dataDir = dataDir + "ReplaceTextonRegularExpression_out_.pdf"; pdfDocument.Save(dataDir); // ExEnd:ReplaceTextonRegularExpression Console.WriteLine("\nText replaced successfully based on a regular expression.\nFile saved at " + dataDir); }
public static void Run() { // ExStart:ExtractColumnsText // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); // Open document Document pdfDocument = new Document(dataDir + "ExtractTextPage.pdf"); TextFragmentAbsorber tfa = new TextFragmentAbsorber(); pdfDocument.Pages.Accept(tfa); TextFragmentCollection tfc = tfa.TextFragments; foreach (TextFragment tf in tfc) { // Need to reduce font size at least for 70% tf.TextState.FontSize = tf.TextState.FontSize * 0.7f; } Stream st = new MemoryStream(); pdfDocument.Save(st); pdfDocument = new Document(st); TextAbsorber textAbsorber = new TextAbsorber(); pdfDocument.Pages.Accept(textAbsorber); String extractedText = textAbsorber.Text; textAbsorber.Visit(pdfDocument); dataDir = dataDir + "ExtractColumnsText_out.txt"; System.IO.File.WriteAllText(dataDir, extractedText); // ExEnd:ExtractColumnsText Console.WriteLine("\nColumns text extracted successfully from Pages of PDF Document.\nFile saved at " + dataDir); }
public static string ReplaceText(string txtFind, string txtReplace, string[] pageList) { try { Document doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf")); //create TextAbsorber object to find all instances of the input search phrase TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("(?i)" + txtFind, new Aspose.Pdf.Text.TextOptions.TextSearchOptions(true)); textFragmentAbsorber.TextReplaceOptions.ReplaceAdjustmentAction = TextReplaceOptions.ReplaceAdjustment.WholeWordsHyphenation; //accept the absorber for all the pages doc.Pages.Accept(textFragmentAbsorber); //get the extracted text fragments TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; //loop through the fragments foreach (TextFragment textFragment in textFragmentCollection) { //update text and other properties textFragment.Text = txtReplace; } doc.Save(HttpContext.Current.Server.MapPath("Convert/output.pdf")); doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf")); System.IO.DirectoryInfo downloadedMessageInfo = new DirectoryInfo(HttpContext.Current.Server.MapPath("Input/")); foreach (FileInfo file in downloadedMessageInfo.GetFiles()) { file.Delete(); } for (int pageCount = 1; pageCount <= doc.Pages.Count; pageCount++) { string filename = "Input/" + pageList[pageCount - 1]; filename = filename.Replace("image", "image-1"); using (FileStream imageStream = new FileStream(HttpContext.Current.Server.MapPath(filename), FileMode.Create)) { //Create Resolution object Resolution resolution = new Resolution(300); //create PNG device with specified attributes PngDevice pngDevice = new PngDevice(); //Convert a particular page and save the image to stream pngDevice.Process(doc.Pages[pageCount], imageStream); //Close stream imageStream.Close(); System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(filename)); string height = ""; string Aratio = ""; ScaleImage(image, 1138, 760, HttpContext.Current.Server.MapPath(filename.Replace("image-1", "image")), out height, out Aratio); image.Dispose(); } } } catch (Exception exp) { } return("success"); }
public static string SearchData(string searchText, string[] pageList) { string name = DateTime.Now.Millisecond.ToString(); System.IO.DirectoryInfo downloadedMessageInfo = new DirectoryInfo(HttpContext.Current.Server.MapPath("search/")); foreach (FileInfo file in downloadedMessageInfo.GetFiles()) { file.Delete(); } foreach (DirectoryInfo dir in downloadedMessageInfo.GetDirectories()) { dir.Delete(true); } System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("search/" + name)); Document doc = new Document(HttpContext.Current.Server.MapPath("Convert/output.pdf")); for (int i = 1; i <= doc.Pages.Count; i++) { string filename = "Input/" + pageList[i - 1]; filename = filename.Replace("image", "image-1"); Bitmap bmp = (Bitmap)Bitmap.FromFile(HttpContext.Current.Server.MapPath(filename)); using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp)) { float scale = 150 / 72f; gr.Transform = new System.Drawing.Drawing2D.Matrix(scale, 0, 0, -scale, 0, bmp.Height); Aspose.Pdf.Page page = doc.Pages[i]; //create TextAbsorber object to find all words TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(searchText); // textFragmentAbsorber.TextSearchOptions.IsRegularExpressionUsed = true; page.Accept(textFragmentAbsorber); //get the extracted text fragments TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; Brush brush = new SolidBrush(System.Drawing.Color.FromArgb(50, 255, 255, 0)); //loop through the fragments foreach (TextFragment textFragment in textFragmentCollection) { // if (i == 0) { gr.FillRectangle( // gr.DrawRectangle( brush, (float)(textFragment.Position.XIndent), (float)(textFragment.Position.YIndent), (float)(textFragment.Rectangle.Width), (float)(textFragment.Rectangle.Height)); for (int segNum = 1; segNum <= textFragment.Segments.Count; segNum++) { TextSegment segment = textFragment.Segments[segNum]; gr.DrawRectangle( Pens.Green, (float)segment.Rectangle.LLX, (float)segment.Rectangle.LLY, (float)segment.Rectangle.Width, (float)segment.Rectangle.Height); } } } gr.Dispose(); } bmp.Save(HttpContext.Current.Server.MapPath(filename.Replace("image-1", "image_search")), System.Drawing.Imaging.ImageFormat.Png); bmp.Dispose(); string height = ""; string Aratio = ""; System.Drawing.Image image = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(filename.Replace("image-1", "image_search"))); ScaleImage(image, 1138, 760, HttpContext.Current.Server.MapPath("search/" + name + "/" + pageList[i - 1]), out height, out Aratio); image.Dispose(); // System.IO.File.Copy(HttpContext.Current.Server.MapPath("Input/image_search" + i + ".png"), HttpContext.Current.Server.MapPath("Input/image" + i + ".png")); } return(name); }
public static void Run() { try { // ExStart:HighlightCharacterInPDF // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); int resolution = 150; Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(dataDir + "input.pdf"); using (MemoryStream ms = new MemoryStream()) { PdfConverter conv = new PdfConverter(pdfDocument); conv.Resolution = new Resolution(resolution, resolution); conv.GetNextImage(ms, System.Drawing.Imaging.ImageFormat.Png); Bitmap bmp = (Bitmap)Bitmap.FromStream(ms); using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp)) { float scale = resolution / 72f; gr.Transform = new System.Drawing.Drawing2D.Matrix(scale, 0, 0, -scale, 0, bmp.Height); for (int i = 0; i < pdfDocument.Pages.Count; i++) { Page page = pdfDocument.Pages[1]; // Create TextAbsorber object to find all words TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(@"[\S]+"); textFragmentAbsorber.TextSearchOptions.IsRegularExpressionUsed = true; page.Accept(textFragmentAbsorber); // Get the extracted text fragments TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; // Loop through the fragments foreach (TextFragment textFragment in textFragmentCollection) { if (i == 0) { gr.DrawRectangle( Pens.Yellow, (float)textFragment.Position.XIndent, (float)textFragment.Position.YIndent, (float)textFragment.Rectangle.Width, (float)textFragment.Rectangle.Height); for (int segNum = 1; segNum <= textFragment.Segments.Count; segNum++) { TextSegment segment = textFragment.Segments[segNum]; for (int charNum = 1; charNum <= segment.Characters.Count; charNum++) { CharInfo characterInfo = segment.Characters[charNum]; Aspose.Pdf.Rectangle rect = page.GetPageRect(true); Console.WriteLine("TextFragment = " + textFragment.Text + " Page URY = " + rect.URY + " TextFragment URY = " + textFragment.Rectangle.URY); gr.DrawRectangle( Pens.Black, (float)characterInfo.Rectangle.LLX, (float)characterInfo.Rectangle.LLY, (float)characterInfo.Rectangle.Width, (float)characterInfo.Rectangle.Height); } gr.DrawRectangle( Pens.Green, (float)segment.Rectangle.LLX, (float)segment.Rectangle.LLY, (float)segment.Rectangle.Width, (float)segment.Rectangle.Height); } } } } } dataDir = dataDir + "HighlightCharacterInPDF_out.png"; bmp.Save(dataDir, System.Drawing.Imaging.ImageFormat.Png); } // ExEnd:HighlightCharacterInPDF Console.WriteLine("\nCharacters highlighted successfully in pdf document.\nFile saved at " + dataDir); } catch (Exception ex) { Console.WriteLine(ex.Message + "\nThis example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http:// Www.aspose.com/purchase/default.aspx."); } }
private void btnCreate_Click(object sender, EventArgs e) { if (txtFilePath.Text != String.Empty) { Document doc = new Document(txtFilePath.Text); Document newDoc = new Document(); if (rdoRange.Checked) { for (decimal i = txtFrom.Value; i <= txtTo.Value; i++) { newDoc.Pages.Add(doc.Pages[Convert.ToInt32(i)]); } newDoc.Save("output_" + DateTime.Now.Millisecond + ".pdf"); MessageBox.Show("Document has been created.", "Success"); } else if (rdoNumber.Checked) { try { string[] pages = txtPageNumbers.Text.Split(','); foreach (string s in pages) { newDoc.Pages.Add(doc.Pages[Convert.ToInt32(s)]); } newDoc.Save("output_" + DateTime.Now.Millisecond + ".pdf"); MessageBox.Show("Document has been created.", "Success"); } catch (Exception ex) { MessageBox.Show("Error in processing Page Numbers. Some values are not in correct format.\n" + ex.Message, "Error"); } } else { if (txtSearchText.Text != String.Empty) { TextFragmentAbsorber absorber = new TextFragmentAbsorber(txtSearchText.Text, new TextSearchOptions(true)); doc.Pages.Accept(absorber); TextFragmentCollection collection = absorber.TextFragments; List <int> pagenumbers = new List <int>(); if (collection.Count > 0) { foreach (TextFragment textFragment in collection) { if (pagenumbers.Contains(textFragment.Page.Number)) { continue; } else { pagenumbers.Add(textFragment.Page.Number); } } foreach (int s in pagenumbers) { newDoc.Pages.Add(doc.Pages[s]); } newDoc.Save("output_" + DateTime.Now.Millisecond + ".pdf"); MessageBox.Show("Document has been created.", "Success"); } else { MessageBox.Show("No Results found against Search.", "No Results"); } } else { MessageBox.Show("Please Enter a Search Term.", "No Search Term"); } } } else { MessageBox.Show("Please Select a PDF File First.", "File Not Found"); } }
static void Main(string[] args) { //License license = new Aspose.Pdf.License(); //license.SetLicense("Aspose.Pdf.lic"); SqlConnection con = new SqlConnection(constr); con.Open(); SqlCommand cmd = new SqlCommand("spconfiguration", con); cmd.CommandType = CommandType.StoredProcedure; SqlDataReader dr = cmd.ExecuteReader(); dr.Read(); source = dr["FTPURLSource"].ToString(); destination = dr["FTPURLDestination"].ToString(); dr.Close(); con.Close(); string mydir = source + @"\"; string[] myfiles = Directory.GetFiles(mydir + "").Select(Path.GetFileName).ToArray(); foreach (var i in myfiles) { if (i.Contains("HSBC")) { string sub = "HSBC SA " + i.Split(' ', '.')[2]; string sub1 = i.Split(' ', '.')[2]; //string sub = str.Substring(8, 6); //string sub1 = rowString.Substring(0, 3); //string sub = rowString.Replace('"', ' ').Trim(); if (sub.Contains("DPM")) { Document pdfDocument = new Document(mydir + i); //create TextAbsorber object to find all instances of the input search phrase TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(sub); //accept the absorber for all the pages pdfDocument.Pages.Accept(textFragmentAbsorber); SqlCommand com1 = new SqlCommand("spGetMaster", con); con.Open(); com1.CommandType = CommandType.StoredProcedure; com1.Parameters.Add("@masked", SqlDbType.VarChar).Value = sub1; com1.ExecuteNonQuery(); SqlDataReader reader = com1.ExecuteReader(); reader.Read(); if (reader.HasRows) { //update text and other properties CustName = reader["de_masked"].ToString(); reader.Close(); //get the extracted text fragments TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments; //loop through the fragments foreach (TextFragment textFragment in textFragmentCollection) { //string str = "select de_masked from master where Masked='" + sub.ToString() + "'"; SqlCommand com = new SqlCommand("spGetMaster", con); com.CommandType = CommandType.StoredProcedure; com.Parameters.Add("@masked", SqlDbType.VarChar).Value = sub1; com.ExecuteNonQuery(); SqlDataReader reader1 = com.ExecuteReader(); reader1.Read(); //update text and other properties string CustName1 = reader1["de_masked"].ToString(); textFragment.Text = CustName1; reader1.Close(); } //setting password to pdf SqlCommand cmd1 = new SqlCommand("spGetMaster", con); cmd1.CommandType = CommandType.StoredProcedure; cmd1.Parameters.Add("masked", SqlDbType.VarChar).Value = sub1; cmd1.ExecuteNonQuery(); SqlDataReader rd = cmd1.ExecuteReader(); rd.Read(); string pass = rd["pdfpassword"].ToString(); custEmail = rd["Email"].ToString(); ccemail = rd["ccemail"].ToString(); pdfDocument.Encrypt(pass, "", 0, CryptoAlgorithm.RC4x128); rd.Close(); newfilename = i + ".pdf"; pdfDocument.Save(destination + @"\" + newfilename); sendEmail(); insertdata(); //setpass(); string oldfile = mydir + i; File.Delete(oldfile); } con.Close(); } } } }
public static void Run() { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_Text(); string outputFile = dataDir + "TextBlock_HideShow_MouseOverOut_out.pdf"; // Create sample document with text Document doc = new Document(); doc.Pages.Add().Paragraphs.Add(new TextFragment("Move the mouse cursor here to display floating text")); doc.Save(outputFile); // Open document with text Document document = new Document(outputFile); // Create TextAbsorber object to find all the phrases matching the regular expression TextFragmentAbsorber absorber = new TextFragmentAbsorber("Move the mouse cursor here to display floating text"); // Accept the absorber for the document pages document.Pages.Accept(absorber); // Get the first extracted text fragment TextFragmentCollection textFragments = absorber.TextFragments; TextFragment fragment = textFragments[1]; // Create hidden text field for floating text in the specified rectangle of the page TextBoxField floatingField = new TextBoxField(fragment.Page, new Rectangle(100, 700, 220, 740)); // Set text to be displayed as field value floatingField.Value = "This is the \"floating text field\"."; // We recommend to make field 'readonly' for this scenario floatingField.ReadOnly = true; // Set 'hidden' flag to make field invisible on document opening floatingField.Flags |= AnnotationFlags.Hidden; // Setting a unique field name isn't necessary but allowed floatingField.PartialName = "FloatingField_1"; // Setting characteristics of field appearance isn't necessary but makes it better floatingField.DefaultAppearance = new DefaultAppearance("Helv", 10, System.Drawing.Color.Blue); floatingField.Characteristics.Background = System.Drawing.Color.LightBlue; floatingField.Characteristics.Border = System.Drawing.Color.DarkBlue; floatingField.Border = new Border(floatingField); floatingField.Border.Width = 1; floatingField.Multiline = true; // Add text field to the document document.Form.Add(floatingField); // Create invisible button on text fragment position ButtonField buttonField = new ButtonField(fragment.Page, fragment.Rectangle); // Create new hide action for specified field (annotation) and invisibility flag. // (You also may reffer floating field by the name if you specified it above.) // Add actions on mouse enter/exit at the invisible button field buttonField.Actions.OnEnter = new HideAction(floatingField, false); buttonField.Actions.OnExit = new HideAction(floatingField); // Add button field to the document document.Form.Add(buttonField); // Save document document.Save(outputFile); // ExEnd:1 }