static void Main() { // If using Professional version, put your serial key below. ComponentInfo.SetLicense("FREE-LIMITED-KEY"); var document = DocumentModel.Load("BookmarksTemplate.docx"); // Replace bookmark's content with plain text. document.Bookmarks["Company"].GetContent(false).LoadText("Acme Corporation"); // Replace bookmark's content with HTML text. document.Bookmarks["Address"].GetContent(false).LoadText( "<span style='font: italic 8pt Calibri; color: red;'>240 Old Country Road, Springfield, IL</span>", LoadOptions.HtmlDefault); // Insert hyperlink into a bookmark. var hyperlink = new Hyperlink(document, "mailto:[email protected]", "*****@*****.**"); document.Bookmarks["Contact"].GetContent(false).Set(hyperlink.Content); // Insert image into a bookmark. var picture = new Picture(document, "Acme.png"); document.Bookmarks["Logo"].GetContent(false).Set(picture.Content); // Insert text and table into a bookmark. ContentRange itemsRange = document.Bookmarks["Items"].GetContent(false); itemsRange = itemsRange.LoadText("Storage:"); var table = new Table(document, 6, 3, (r, c) => new TableCell(document, new Paragraph(document, $"Item {r}-{c}"))); itemsRange.End.InsertRange(table.Content); document.Save("Modified Bookmarks.docx"); }
static void Main() { // If using Professional version, put your serial key below. ComponentInfo.SetLicense("FREE-LIMITED-KEY"); var document = DocumentModel.Load("Reading.docx"); // Delete 1st paragraph's inlines. var paragraph1 = document.Sections[0].Blocks.Cast <Paragraph>(0); paragraph1.Inlines.Content.Delete(); // Delete 3rd and 4th run from the 2nd paragraph. var paragraph2 = document.Sections[0].Blocks.Cast <Paragraph>(1); var runsContent = new ContentRange( paragraph2.Inlines[2].Content.Start, paragraph2.Inlines[3].Content.End); runsContent.Delete(); // Delete specified text content. var bracketContent = document.Content.Find("(").First(); bracketContent.Delete(); document.Save("Delete Content.docx"); }
public async Task <Stream> DecryptInternal( Stream content, Metadata metadata, HttpRange originalRange, string receivedContentRange, bool async, CancellationToken cancellationToken) { ContentRange?contentRange = string.IsNullOrWhiteSpace(receivedContentRange) ? default : ContentRange.Parse(receivedContentRange); EncryptionData encryptionData = GetAndValidateEncryptionDataOrDefault(metadata); if (encryptionData == default) { return(await TrimStreamInternal(content, originalRange, contentRange, pulledOutIV : false, async, cancellationToken).ConfigureAwait(false)); } bool ivInStream = originalRange.Offset >= Constants.ClientSideEncryption.EncryptionBlockSize; // this method throws when key cannot be resolved. Blobs is intended to throw on this failure. var plaintext = await _decryptor.DecryptInternal( content, encryptionData, ivInStream, CanIgnorePadding(contentRange), async, cancellationToken).ConfigureAwait(false); return(await TrimStreamInternal(plaintext, originalRange, contentRange, ivInStream, async, cancellationToken).ConfigureAwait(false)); }
static void Main(string[] args) { // If using Professional version, put your serial key below. ComponentInfo.SetLicense("FREE-LIMITED-KEY"); DocumentModel document = new DocumentModel(); // Set the content for the whole document document.Content.LoadText("Paragraph 1\nParagraph 2\nParagraph 3\nParagraph 4\nParagraph 5"); var bold = new CharacterFormat() { Bold = true }; // Set the content for the 2nd paragraph document.Sections[0].Blocks[1].Content.LoadText("Bold paragraph 2", bold); // Set the content for 3rd and 4th paragraph to be the same as the content of 1st and 2nd paragraph var para3 = document.Sections[0].Blocks[2]; var para4 = document.Sections[0].Blocks[3]; var destinationRange = new ContentRange(para3.Content.Start, para4.Content.End); var para1 = document.Sections[0].Blocks[0]; var para2 = document.Sections[0].Blocks[1]; var sourceRange = new ContentRange(para1.Content.Start, para2.Content.End); destinationRange.Set(sourceRange); // Set content using HTML tags document.Sections[0].Blocks[4].Content.LoadText("Paragraph 5 <b>(part of this paragraph is bold)</b>", LoadOptions.HtmlDefault); document.Save("Set Content.docx"); }
/// <summary> /// Insert a picture to custom page and position into existing DOCX document. /// </summary> /// <remarks> /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/insert-picture-jpg-image-to-custom-docx-page-and-position-net-csharp-vb.php /// </remarks> static void InsertPictureToCustomPageAndPosition() { // In this example we'll insert the picture to 1st after the word "Sign:". string inpFile = @"..\..\example.docx"; string outFile = @"Result.docx"; string pictFile = @"..\..\picture.jpg"; DocumentCore dc = DocumentCore.Load(inpFile); DocumentPaginator dp = dc.GetPaginator(); // Find the text "Sign:" on the 1st page. ContentRange cr = dp.Pages[0].Content.Find("Sign:").LastOrDefault(); if (cr != null) { Picture pic = new Picture(dc, pictFile); cr.End.Insert(pic.Content); } // Save the document as new DOCX and open it. dc.Save(outFile); System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true }); }
public async Task Should_set_content_type_range_into_request() { await CreateHttp().Put("/some-resource") .WithBytes(new byte[100]) .ContentRange(100, 199) .SendAsync(); ClusterClientVerify.SentRequest !.Headers !.ContentRange.Should().Be("bytes 100-199/*"); }
public async Task Should_set_content_type_range_with_total_length_into_request(int from, int to, int total, string expectedValue) { await CreateHttp().Post("/some-resource") .WithBytes(new byte[to - from + 1]) .ContentRange(from, to, total) .SendAsync(); ClusterClientVerify.SentRequest !.Headers !.ContentRange.Should().Be(expectedValue); }
private HTTPRequest PreparePartialDownloadRequest(Uri requestUri, ContentRange range) { HTTPRequest partialRequest = new HTTPRequest(requestUri, OnDownloadFinish); partialRequest.UseStreaming = true; partialRequest.DisableCache = true; partialRequest.SetRangeHeader(range.start, range.end); return(partialRequest); }
private static ContentRange GetRange(WebResponse res) { ContentRange contentRange = new ContentRange(); string Content_Range = res.Headers["Content-Range"]; string RegexStr = @"bytes (?<start>[\d]+)-(?<end>[\d]+)/(?<total>[\d]+)"; Match matc = Regex.Match(Content_Range, RegexStr); contentRange.start = int.Parse(matc.Groups["start"].ToString()); contentRange.end = int.Parse(matc.Groups["end"].ToString()); contentRange.total = int.Parse(matc.Groups["total"].ToString()); return(contentRange); }
public override QueryRange <IContent> ExecuteQuery(IQueryParameters parameters) { var contentQueryParam = parameters as ContentQueryParameters; var searchRequest = SearchClient.Search <TContent>(); var searchPhrase = parameters.AllParameters["q"]; var hasFreeTextQuery = !string.IsNullOrWhiteSpace(searchPhrase) && searchPhrase != "*"; if (hasFreeTextQuery) { searchRequest = ApplyTextSearch(searchRequest, searchPhrase); } searchRequest = searchRequest.Filter(x => !x.MatchTypeHierarchy(typeof(ILocalizable)) | ((ILocalizable)x).Language.Name.Match(contentQueryParam.PreferredCulture.Name)); searchRequest = Filter(searchRequest, contentQueryParam); searchRequest = ApplyVisibilityFilter(searchRequest); if (contentQueryParam.SortColumns != null && contentQueryParam.SortColumns.Any()) { var sortColumn = contentQueryParam.SortColumns.FirstOrDefault(); searchRequest = ApplySorting(searchRequest, sortColumn); } if (parameters.Range.Start.HasValue && parameters.Range.End.HasValue) { searchRequest = searchRequest .Skip(parameters.Range.Start.Value) .Take(parameters.Range.End.Value); } try { var result = searchRequest.GetContentResult(); var itemRange = new ItemRange { Total = result.TotalMatching, Start = parameters.Range.Start, End = parameters.Range.End }; var contentRange = new ContentRange(result.OfType <IContent>(), itemRange); return(contentRange); } catch { return(new ContentRange(Enumerable.Empty <IContent>(), new ItemRange { Total = 0, Start = 0, End = 0 })); } }
public static void delete(DocumentModel document, string toDelete) { var blocks = document.Sections.ToList(); foreach (var item in blocks) { foreach (var item2 in item.Blocks) { var a = new ContentRange(item2.Content.Start, item2.Content.End); a.Delete(); } } }
public IActionResult GetBooksByRange([FromBody] ContentRange range) => Ok(_bookRepository .GetAll() .Include(p => p.Author) .Skip(range.First - 1) .Take(range.Last) .Select(item => new BookResponse { BookId = item.Id, BookTitle = item.Name, AuthorName = item.Author.Name, Description = item.Description, PublishYear = item.YearOfPublication }));
// division is 0-indexed private ContentRange GetContentRange(int division, int totalDivisions, long contentLength) { long divisionSize = contentLength / totalDivisions; long offset = divisionSize * (division); long remainingBytes = contentLength % totalDivisions; if (remainingBytes > 0 && division == totalDivisions - 1) // last division { divisionSize += remainingBytes; // get the last bytes (but sub 1 because index starts at 0) } ContentRange range = new ContentRange((int)offset, (int)(offset + divisionSize - 1)); return(range); }
public bool SignPhysically(string filePath, string firstnames, string surname, string certificateSerialNumber) { string fileResult = filePath + "/Dummy file (signed).pdf"; DocumentCore dc = DocumentCore.Load(filePath + "/Dummy file.pdf"); ContentRange cr = dc.Content.Find("_").FirstOrDefault(); if (cr != null) { cr.Start.Insert($"Digitaal getekend door {firstnames} {surname} op {DateTime.Now}. \n\r Serienummer certificaat: {certificateSerialNumber}"); dc.Save(fileResult); return(true); } return(false); }
static void Main(string[] args) { // If using Professional version, put your serial key below. ComponentInfo.SetLicense("FREE-LIMITED-KEY"); DocumentModel document = DocumentModel.Load("Reading.docx"); // Delete paragraph break between 1st and 2nd paragraph (concatenate 1st and 2nd paragraph) var blocks = document.Sections[0].Blocks; var paragraphBreakRange = new ContentRange(blocks[0].Content.End, blocks[1].Content.Start); paragraphBreakRange.Delete(); // Delete content of 2nd run blocks.Cast <Paragraph>(0).Inlines[1].Content.Delete(); document.Save("Delete Content.docx"); }
static void Example1() { var document = DocumentModel.Load("FindAndReplaceText.docx"); // The easiest way how you can find and replace text is with "Replace" method. document.Content.Replace("%FirstName%", "John"); document.Content.Replace("%LastName%", "Doe"); document.Content.Replace("%Date%", DateTime.Today.ToLongDateString()); // You can also find and highlight text by specifying "HighlightColor" of replacement text. document.Content.Replace("membership", "membership", new CharacterFormat() { HighlightColor = Color.Yellow }); // You can also search for placeholder text with "Find" method and then achieve more complex replacement. // The "Reverse" extension method is used when iterating through document's content // to avoid any possible invalid state when replacing the content within iteration. // Replace text with text that has different formatting. foreach (ContentRange searchedContent in document.Content.Find("%Price%").Reverse()) { ContentRange replacedContent = searchedContent.LoadText("$", new CharacterFormat() { Size = 14, FontColor = Color.Purple }); replacedContent.End.LoadText("100.00", new CharacterFormat() { Size = 11, FontColor = Color.Purple }); } // Replace text with hyperlink. foreach (ContentRange searchedContent in document.Content.Find("%Email%").Reverse()) { Hyperlink emailLink = new Hyperlink(document, "mailto:[email protected]", "*****@*****.**"); searchedContent.Set(emailLink.Content); } document.Save("FoundAndReplacedText.docx"); }
public async Task <Stream> DecryptInternal( Stream content, Metadata metadata, HttpRange originalRange, string receivedContentRange, bool async, CancellationToken cancellationToken) { ContentRange?contentRange = string.IsNullOrWhiteSpace(receivedContentRange) ? default : ContentRange.Parse(receivedContentRange); EncryptionData encryptionData = GetAndValidateEncryptionDataOrDefault(metadata); if (encryptionData == default) { return(await TrimStreamInternal(content, originalRange, contentRange, alreadyTrimmedOffsetAmount : 0, async, cancellationToken).ConfigureAwait(false)); } bool ivInStream = originalRange.Offset >= Constants.ClientSideEncryption.EncryptionBlockSize; // this method throws when key cannot be resolved. Blobs is intended to throw on this failure. var plaintext = await _decryptor.DecryptReadInternal( content, encryptionData, ivInStream, CanIgnorePadding(contentRange), async, cancellationToken).ConfigureAwait(false); int v2StartRegion0Indexed = (int)((contentRange?.Start / encryptionData.EncryptedRegionInfo?.GetTotalRegionLength()) ?? 0); int alreadyTrimmedOffset = encryptionData.EncryptionAgent.EncryptionVersion switch { ClientSideEncryptionVersion.V1_0 => ivInStream ? Constants.ClientSideEncryption.EncryptionBlockSize : 0, // first block is special case where we don't want to communicate a trim. Otherwise communicate nonce length * 1-indexed start region + tag length * 0-indexed region ClientSideEncryptionVersion.V2_0 => contentRange?.Start > 0 ? (-encryptionData.EncryptedRegionInfo.NonceLength * (v2StartRegion0Indexed)) - (Constants.ClientSideEncryption.V2.TagSize * v2StartRegion0Indexed) : 0, _ => throw Errors.ClientSideEncryption.ClientSideEncryptionVersionNotSupported() }; return(await TrimStreamInternal(plaintext, originalRange, contentRange, alreadyTrimmedOffset, async, cancellationToken).ConfigureAwait(false)); }
public void ShiftLineNumber(int amount) { LineNumber += amount; Range?.ShiftLineNumber(amount); CommentRange?.ShiftLineNumber(amount); ContentRange?.ShiftLineNumber(amount); IndentationRange?.ShiftLineNumber(amount); MatchedSyntax?.Result?.Matches?.ForEach(m => { var expression = (m as ExpressionParseMatch)?.Expression; if (expression != null) { expression.GetAllExpressions().ForEach(expr => expr.Range.ShiftLineNumber(amount)); } else { m.Range.ShiftLineNumber(amount); } }); }
private void ExecuteVideoDownload(HTTPRequest request, long contentSize, int connections) { AllocateMemory(); //Debug.Log("Downloading content at " + request.Uri.AbsoluteUri); mConnectionCount = connections; Uri requestUri = new Uri(request.Uri.AbsoluteUri); for (int i = 0; i < connections; i++) { ContentRange range = GetContentRange(i, connections, contentSize); //Debug.Log("Content range request: " + range.start + "-" + range.end); HTTPRequest finalizedPartialRequest = PreparePartialDownloadRequest(requestUri, range); AddRequest(finalizedPartialRequest); } for (int i = 0; i < mRequests.Count; i++) { OnRequestInitialize(mRequests[i]); } }
public async Task <IActionResult> GetBooksInRange(Page page) { var range = new ContentRange { First = 9 * (page.PageNumber - 1) + 1, Last = 9 * page.PageNumber }; var str = new StringContent(System.Text.Json.JsonSerializer.Serialize(range).ToString(), Encoding.UTF8, "application/json"); var response = await _client.PostAsync("https://localhost:44336/api/book/getBooksInRange", str); switch (response.StatusCode) { case HttpStatusCode.OK: { var result = JsonConvert.DeserializeObject <List <BookResponse> >(await response.Content.ReadAsStringAsync()); return(Ok(result)); } case HttpStatusCode.InternalServerError: return(StatusCode(500)); } return(BadRequest()); }
static void Main() { // If using Professional version, put your serial key below. ComponentInfo.SetLicense("FREE-LIMITED-KEY"); var document = DocumentModel.Load("Reading.docx"); // 1. The easiest way how to find and replace text. document.Content.Replace(".NET", "C# / VB.NET"); // 2. You can also find and highlight text by specifying the format of replacement text. var highlightText = "read, write, convert and print"; document.Content.Replace(highlightText, highlightText); document.Content.Replace(highlightText, highlightText, new CharacterFormat() { HighlightColor = Color.Yellow }); // 3. You can also search for specified text and achieve more complex replacements. // Notice the "Reverse" method usage for avoiding any possible invalid state due to replacements inside iteration. var searchText = "GemBox.Document"; foreach (ContentRange searchedContent in document.Content.Find(searchText).Reverse()) { var replaceText = "Word library from GemBox called "; ContentRange replacedContent = searchedContent.LoadText(replaceText, new CharacterFormat() { FontColor = new Color(237, 125, 49) }); var hyperlink = new Hyperlink(document, "https://www.gemboxsoftware.com/document", "GemBox.Document"); replacedContent.End.InsertRange(hyperlink.Content); } document.Save("Find and Replace.docx"); }
static void Main() { // If using Professional version, put your serial key below. ComponentInfo.SetLicense("FREE-LIMITED-KEY"); var document = new DocumentModel(); // Set the content for the whole document. document.Content.LoadText("First paragraph.\nSecond paragraph.\nThird paragraph.\nFourth paragraph.\nFifth paragraph."); var section = document.Sections[0]; // Set the content for 1st paragraph using plain text. section.Blocks[0].Content.LoadText("Paragraph with plain text."); // Set the content for 2nd paragraph using specified formatting. section.Blocks[1].Content.LoadText("Paragraph with red and bold text.", new CharacterFormat() { FontColor = Color.Red, Bold = true }); var sourceRange = new ContentRange( section.Blocks[0].Content.Start, section.Blocks[1].Content.End); var destinationRange = new ContentRange( section.Blocks[2].Content.Start, section.Blocks[3].Content.End); // Set the content for 3rd and 4th paragraph to be the same as the content of 1st and 2nd paragraph. destinationRange.Set(sourceRange); // Set the content for 5th paragraph using HTML text. section.Blocks[4].Content.LoadText("<p style='font:11pt Calibri;color:blue;'>Paragraph with blue text that has <i>italic part</i>.</p>", new HtmlLoadOptions()); document.Save("Set Content.docx"); }
public virtual ContentRange ExecuteQuery(ContentQueryParameters parameters) { var searchRequest = SearchClient.Search <TContent>() .FilterOnLanguages(new [] { parameters.PreferredCulture.Name }); var searchPhrase = parameters.AllParameters["q"]; var hasFreeTextQuery = !string.IsNullOrWhiteSpace(searchPhrase) && searchPhrase != "*"; if (hasFreeTextQuery) { searchRequest = ApplyTextSearch(searchRequest, searchPhrase); } searchRequest = Filter(searchRequest, parameters); searchRequest = ApplyVisibilityFilter(searchRequest); if (parameters.SortColumns != null && parameters.SortColumns.Any()) { var sortColumn = parameters.SortColumns.FirstOrDefault(); searchRequest = ApplySorting(searchRequest, sortColumn); } var result = searchRequest .Skip(parameters.Range.Start) .Take(parameters.Range.End) .GetContentResult(CacheForSeconds, true); var itemRange = new ItemRange { Total = result.TotalMatching, Start = parameters.Range.Start, End = parameters.Range.End }; var contentRange = new ContentRange(result.OfType <IContent>(), itemRange); return(contentRange); }
/// <summary> /// Insert a text into an existing PDF document in a specific position. /// </summary> /// <remarks> /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/insert-text-to-pdf-document-net-csharp-vb.php /// </remarks> static void InsertText() { string filePath = @"..\..\example.pdf"; string fileResult = @"Result.pdf"; DocumentCore dc = DocumentCore.Load(filePath); // Find a position to insert text. Before this text: "> in this position". ContentRange cr = dc.Content.Find("> in this position").FirstOrDefault(); // Insert new text. if (cr != null) { cr.Start.Insert("New text!"); } dc.Save(fileResult); System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath) { UseShellExecute = true }); System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(fileResult) { UseShellExecute = true }); }
public void Load(Stream stream, RichTextAreaFormat format) { SuppressSelectionChanged++; SuppressTextChanged++; var range = ContentRange; switch (format) { case RichTextAreaFormat.Rtf: range.Load(stream, sw.DataFormats.Rtf); break; case RichTextAreaFormat.PlainText: range.Load(stream, sw.DataFormats.Text); break; default: throw new NotSupportedException(); } SuppressTextChanged--; SuppressSelectionChanged--; Callback.OnTextChanged(Widget, EventArgs.Empty); Selection = Range.FromLength(ContentRange.GetLength(), 0); }
/// <summary> /// Create a new document with some content. /// </summary> /// <remarks> /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/insert-content-net-csharp-vb.php /// </remarks> public static void InsertContent() { string documentPath = @"InsertContent.pdf"; // Let's create a new document. DocumentCore dc = new DocumentCore(); // Add new section. Section section = new Section(dc); dc.Sections.Add(section); // You may add a new paragraph using a classic way: section.Blocks.Add(new Paragraph(dc, "This is the first line in 1st paragraph!")); Paragraph par1 = section.Blocks[0] as Paragraph; par1.ParagraphFormat.Alignment = HorizontalAlignment.Center; // But here, let's see how to do it using ContentRange: // 1. Insert a content as Text. dc.Content.End.Insert("\nThis is a first line in 2nd paragraph.", new CharacterFormat() { Size = 25, FontColor = Color.Blue, Bold = true }); // 2. Insert a content as HTML (at the start). dc.Content.Start.Insert("Hello from HTML!", new HtmlLoadOptions()); // 3. Insert a content as RTF. dc.Content.End.Insert(@"{\rtf1 \b The line from RTF\b0!\par}", new RtfLoadOptions()); // 4. Insert a content of SpecialCharacter. dc.Content.End.Insert(new SpecialCharacter(dc, SpecialCharacterType.LineBreak).Content); // 5. Insert a content as ContentRange. // Find first content of "HTML" and insert it at the end. ContentRange cr = dc.Content.Find("HTML").First(); dc.Content.End.Insert(cr); // 6. Insert the content of Paragraph at the end. Paragraph p = new Paragraph(dc); Run run = new Run(dc, "As summarize, you can insert content of any class " + "derived from Element: Table, Shape, Paragraph, Run, HeaderFooter and even a whole DocumentCore!"); run.CharacterFormat.FontColor = Color.DarkGreen; p.Inlines.Add(run); dc.Content.End.Insert(p.Content); // Save our document into PDF format. dc.Save(documentPath, new PdfSaveOptions() { Compliance = PdfCompliance.PDF_A1a }); // Open the result for demonstration purposes. System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(documentPath) { UseShellExecute = true }); }
/// <summary> /// Создание документа форд /// </summary> /// <param name="client">Массив с данными. для записи в Word</param> /// <param name="paht">paht Путь к файлу. Куда сохранять</param> /// <param name="nameClient">Id имя клиента </param> public void GetBoxCreateWordAndPdf(string[] client, string paht, int IdClient) { string hedstr = @" Касса №1 — сеть центров выдачи займов! kassaone.ru Сеть центров по выдаче денежных займов размещает условия предоставления денежных средств частным лицам." + Environment.NewLine; // создание ссылок дирикторий(папок для картинки). Корневая папка // var originalDirectory = new DirectoryInfo(string.Format(@"~Archive_Documents\\Uploads")); //Тест переменная string temp; string ext; string tempPahtImag; //Бесплатное Лицензия ComponentInfo.SetLicense("FREE-LIMITED-KEY"); // Создание нового дока. var document = new DocumentModel(); try { //Цикл для записи текста вфайл ворд for (int i = 0; i < client.Length; i++) { hedstr += (client[i] + Environment.NewLine); } ; document.Content.LoadText(hedstr); document.Save(paht + $@"\\Result_Client_{IdClient}.docx"); document.Save(paht + $@"\\Result_Client_{IdClient}.pdf"); //поиск и замена Картинки. ContentRange imagePlaceholder = document.Content.Find("#IMAGE").First(); //дергаем из Бд имя и путь картнки using (DBContext db = new DBContext()) { temp = db.clients.Find(IdClient).imagePathInDoc; } //получаем разширение ext = System.IO.Path.GetExtension(temp); //Получаем имя файла tempPahtImag = System.IO.Path.GetFileName(temp); //проверка разширения if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/png" && ext != "image/x-png") { } string pathCopy = paht + "\\" + tempPahtImag; File.Copy(temp, pathCopy, true); imagePlaceholder.Set(new Picture(document, paht + $"\\{tempPahtImag}").Content); //создаем документ в 2х форматах. *.docx и *.pdf document.Save(paht + $@"\\Result_Client_{IdClient.ToString()}.docx"); document.Save(paht + $@"\\Result_Client_{IdClient.ToString()}.pdf"); } catch (Exception ex) { JournalLog(ex.ToString()); //для лога ошибок } }
public void pdfOperataion() { string inputFolderPath = @"F:\Node_JS & Projects\InputFolder\Terms & Conditions.pdf"; //Getting All or only JPG Files and printing the name------------------------------------------------------------------- //string[] Files = Directory.GetFiles(@"C:\Users\VipulSingh\Downloads") //Reads all file string[] Files = Directory.GetFiles(@"C:\Users\VipulSingh\Downloads", "*.jpg"); // Reads only the jpg files foreach (string filename in Files) { Console.WriteLine(filename); } //Getting All or only JPG Files and printing the name------------------------------------------------------------------- //Inserting text in PDF File at a perticular place---------------------------------------------------------------------- DocumentCore dc = DocumentCore.Load(inputFolderPath); ContentRange cr = dc.Content.Find("Use of the Website&app").FirstOrDefault(); cr.Start.Insert("\n pankaj is here lets show him\n"); dc.Save(inputFolderPath); string str = dc.Content.ToString(); Console.WriteLine(str); Console.WriteLine("Above Content"); if (dc != null) { } //Inserting text in PDF File at a perticular place---------------------------------------------------------------------- string inputDirectory = @"F:\Node_JS & Projects\InputFolder\"; string outputFileName = @"F:\Node_JS & Projects\OutputFolder\output.pdf"; //Getting All PDF Files to be merged---------------------------------------------------------------------------------- DirectoryInfo di = new DirectoryInfo(inputDirectory); FileInfo[] fileinfo = di.GetFiles("*.pdf"); string[] fileNames = new string[fileinfo.Length]; int i = 0; foreach (var fileName in fileinfo) { fileNames[i] = fileName.FullName; i++; } //Getting All PDF Files to be merged---------------------------------------------------------------------------------- //Merging multiple PDF Files------------------------------------------------------------------------------------------- PdfDocument outputPdfDocument = new PdfDocument(); foreach (string fileName in fileNames) { PdfDocument inputPdfDocument = PdfReader.Open(fileName, PdfDocumentOpenMode.Import); int pages = inputPdfDocument.PageCount; for (int j = 0; j < pages; j++) { PdfPage page = inputPdfDocument.Pages[j]; outputPdfDocument.AddPage(page); } } outputPdfDocument.Save(outputFileName); //Merging multiple PDF Files------------------------------------------------------------------------------------------- Console.ReadKey(); }