/// <summary> /// The method converts a PDF document with scanned images to Word. But it works only if the PDF document contains a hidden text atop of the images. /// </summary> /// <remarks> /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/from-customers-scanned-pdf-to-word-in-csharp-vb-net.php /// </remarks> static void ScannedPdfToWord() { // Actually there are a lot of PDF documents which looks like created using a scanner, // but they also contain a hidden text atop of the contents. // This hidden text duplicates the content of the scanned images. // This is made specially to have the ability to perform the 'find' operation. // Our steps: // 1. Load the PDF with the these settings: // - show hidden text; // - skip all images during the loading. // 2. Change the font color to the 'Black' for the all text. // 3. Save the document as DOCX. string inpFile = @"..\..\Scanned.pdf"; string outFile = @"Result.docx"; PdfLoadOptions pdfLO = new PdfLoadOptions() { PreserveEmbeddedFonts = true, PreserveImages = false, ShowInvisibleText = true, }; DocumentCore dc = DocumentCore.Load(inpFile, pdfLO); dc.DefaultCharacterFormat.FontColor = Color.Black; foreach (Element element in dc.GetChildElements(true, ElementType.Paragraph)) { foreach (Inline inline in (element as Paragraph).Inlines) { if (inline is Run) { (inline as Run).CharacterFormat.FontColor = Color.Black; } } (element as Paragraph).CharacterFormatForParagraphMark.FontColor = Color.Black; } dc.Save(outFile); // Open the result for demonstration purposes. System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true }); }
/// Load an existing document (*.docx, *.rtf, *.pdf, *.html, *.txt, *.pdf) and save it in a PDF document with the digital signature. public static void DigitalSignature() { // Path to a loadable document. string loadPath = @"..\..\..\..\..\..\Testing Files\digitalsignature.docx"; DocumentCore dc = DocumentCore.Load(loadPath); // Signature line added with MS Word -> Insert tab -> Signature Line button by default has description 'Microsoft Office Signature Line...'. ShapeBase signatureLine = dc.GetChildElements(true).OfType <ShapeBase>().FirstOrDefault(); // This picture symbolizes a handwritten signature Picture signature = new Picture(dc, @"..\..\..\..\..\..\Testing Files\signature.png"); // Signature in this document will be 4.5 cm right of TopLeft position of signature line // and 4.5 cm below of TopLeft position of signature line. signature.Layout = Layout.Floating( new HorizontalPosition(4.5, LengthUnit.Centimeter, HorizontalPositionAnchor.Page), new VerticalPosition(-4.5, LengthUnit.Centimeter, VerticalPositionAnchor.Page), signature.Layout.Size); //signature.Layout = Layout.Inline(signature.Layout.Size); PdfSaveOptions options = new PdfSaveOptions(); // Path to the certificate (*.pfx). options.DigitalSignature.CertificatePath = @"..\..\..\..\..\..\Testing Files\sautinsoft.pfx"; // Password of the certificate. options.DigitalSignature.CertificatePassword = "******"; // Additional information about the certificate. options.DigitalSignature.Location = "World Wide Web"; options.DigitalSignature.Reason = "Document.Net by SautiSoft"; options.DigitalSignature.ContactInfo = "*****@*****.**"; // Placeholder where signature should be visualized. options.DigitalSignature.SignatureLine = signatureLine; // Visual representation of digital signature. options.DigitalSignature.Signature = signature; string savePath = Path.ChangeExtension(loadPath, ".pdf"); dc.Save(savePath, options); ShowResult(savePath); }
/// <summary> /// Creates a new document and saves it as DOCX file. /// </summary> /// <remarks> /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/save-document.php /// </remarks> static void SaveToFile() { // Assume we already have a document 'dc'. DocumentCore dc = new DocumentCore(); dc.Content.End.Insert("Hey Guys and Girls!"); string filePath = @"Result.docx"; // The file format will be detected automatically from the file extension: ".docx". dc.Save(filePath); // Open the result for demonstration purposes. System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath) { UseShellExecute = true }); }
/// <summary> /// Saves and retrieves current character formatting on the stack. /// </summary> /// <remarks> /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/character-formatting-stack.php /// </remarks> static void FormattingOnStack() { DocumentCore dc = new DocumentCore(); DocumentBuilder db = new DocumentBuilder(dc); db.CharacterFormat.FontName = "Arial"; db.CharacterFormat.Size = 16; db.CharacterFormat.FontColor = Color.Blue; db.Writeln("This text contains formatting font name, size and color. Save the character formatting of this text in as first element of the stack."); db.PushCharacterFormat(); db.CharacterFormat.ClearFormatting(); db.CharacterFormat.Size = 26; db.CharacterFormat.FontColor = Color.Orange; db.CharacterFormat.Italic = true; db.Writeln("This text contains formatting for font size, color and italic. Save the character formatting of this text as second element of the stack."); db.PushCharacterFormat(); db.CharacterFormat.ClearFormatting(); // Insert the third way the character formatting of the text. db.CharacterFormat.Size = 14; db.CharacterFormat.FontColor = Color.Red; db.CharacterFormat.Bold = true; db.Writeln("This text contains formatting for font size, color and bold."); db.CharacterFormat.ClearFormatting(); // Retrieves text character formatting from the stack (the second element). db.PopCharacterFormat(); // Retrieves text character formatting from the stack (the first element). db.PopCharacterFormat(); db.Writeln("The character formatting of this text is extracted from the stack as first element."); // Save our document into DOCX format. string resultPath = @"result.docx"; dc.Save(resultPath, new DocxSaveOptions()); // Open the result for demonstration purposes. System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(resultPath) { UseShellExecute = true }); }
/// This sample shows how to merge multiple DOCX, RTF, PDF and Text files. public static void MergeMultipleDocuments() { // Path to our combined document. string singlePDFPath = "Single.pdf"; string[] supportedFiles = new string[] { @"..\..\..\..\..\..\Testing Files\example.pdf", @"..\..\..\..\..\..\Testing Files\example.docx" }; // Create single pdf. DocumentCore singlePDF = new DocumentCore(); foreach (string file in supportedFiles) { DocumentCore dc = DocumentCore.Load(file); Console.WriteLine("Adding: {0}...", Path.GetFileName(file)); // Create import session. ImportSession session = new ImportSession(dc, singlePDF, StyleImportingMode.KeepSourceFormatting); // Loop through all sections in the source document. foreach (Section sourceSection in dc.Sections) { // Because we are copying a section from one document to another, // it is required to import the Section into the destination document. // This adjusts any document-specific references to styles, bookmarks, etc. // // Importing a element creates a copy of the original element, but the copy // is ready to be inserted into the destination document. Section importedSection = singlePDF.Import <Section>(sourceSection, true, session); // First section start from new page. if (dc.Sections.IndexOf(sourceSection) == 0) { importedSection.PageSetup.SectionStart = SectionStart.NewPage; } // Now the new section can be appended to the destination document. singlePDF.Sections.Add(importedSection); } } // Save single PDF to a file. singlePDF.Save(singlePDFPath); ShowResult(singlePDFPath); }
public Stream DownloadDOCX(InternetPackage item) { MemoryStream stream = new MemoryStream(); DocumentCore docx = new DocumentCore(); Section section = new Section(docx); docx.Sections.Add(section); section.PageSetup.PaperType = PaperType.A4; section.Blocks.Add(new Paragraph(docx, string.Format("Информация предоставлена (UTC): {0}", DateTime.UtcNow))); section.Blocks.Add(new Paragraph(docx, string.Format("Название пакета интернет услуг: {0}", item.Name))); section.Blocks.Add(new Paragraph(docx, string.Format("Скорость приёма: {0}", item.DownloadSpeed))); section.Blocks.Add(new Paragraph(docx, string.Format("Скорость отдачи: {0}", item.UploadSpeed))); section.Blocks.Add(new Paragraph(docx, string.Format("Стоимость в месяц: {0}", item.Price))); docx.Save(stream, SaveOptions.DocxDefault); return(stream); }
static void SaveToTextStream() { // There variables are necessary only for demonstration purposes. byte[] fileData = null; string filePath = @"Result-stream.txt"; // Assume we already have a document 'dc'. DocumentCore dc = new DocumentCore(); dc.Content.End.Insert("Hey Guys and Girls!"); // Let's save our document to a MemoryStream. using (MemoryStream ms = new MemoryStream()) { dc.Save(ms, new TxtSaveOptions()); fileData = ms.ToArray(); } File.WriteAllBytes(filePath, fileData); }
/// <summary> /// Shows how to work with revisions. /// </summary> /// <remarks> /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/revision-track-changes-net-csharp-vb.php /// </remarks> static void Revision() { DocumentCore dc = DocumentCore.Load(@"..\..\example.docx"); // Accepting the deletion revision will assimilate it into the paragraph's inlines and remove them from the collection. dc.Revisions[0].Accept(); // The second insertion revision is now at index 0, which we can reject to ignore and discard it. dc.Revisions[0].Reject(); // Now we have two revisions in the list items, we accept them all. dc.Revisions.AcceptAll(); dc.Save(@"result.pdf"); System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(@"result.pdf") { UseShellExecute = true }); }
/// <summary> /// Creates a new document with a table. /// </summary> /// <remarks> /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/tables.php /// </remarks> static void CreateTable() { dc = new DocumentCore(); string filePath = @"Result-file.docx"; Table table = new Table(dc, 5, 5, NewCell); // Place the 'Table' at the start of the 'Document'. // By the way, we didn't create a 'Section' in our document. // As we're using 'Content' property, a 'Section' will be created automatically if necessary. dc.Content.Start.Insert(table.Content); dc.Save(filePath); System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath) { UseShellExecute = true }); }
/// <summary> /// Creates a document with different sections. /// </summary> /// <remarks> /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/sections-and-page-layout.php /// </remarks> static void Sections() { string documentPath = @"Sections.docx"; // Let's create a simple document with two Sections. DocumentCore dc = new DocumentCore(); // First Section, A4 - Portrait. Section s1 = new Section(dc); s1.PageSetup.PaperType = PaperType.A4; s1.PageSetup.Orientation = Orientation.Portrait; dc.Sections.Add(s1); // Add some text into section 1. s1.Content.Start.Insert("Text in section 1", new CharacterFormat() { FontName = "Times New Roman", Size = 60.0 }); // Second Section, Letter - Landscape. Section s2 = new Section(dc); s2.PageSetup.PaperType = PaperType.Letter; s2.PageSetup.Orientation = Orientation.Landscape; dc.Sections.Add(s2); // Add some text into section 2. s2.Content.Start.Insert("Text in section 2", new CharacterFormat() { FontName = "Arial", Size = 72.0, FontColor = new Color("DD55AA") }); // Save our document into DOCX format. dc.Save(documentPath); // Open the result for demonstration purposes. System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(documentPath) { UseShellExecute = true }); }
static void Main(string[] args) { Console.WriteLine("Processing..............."); DocumentCore dcObj = DocumentCore.Load(blankdoc); Shape signatureShape = new Shape(dcObj, Layout.Floating(new HorizontalPosition(0f, LengthUnit.Millimeter, HorizontalPositionAnchor.LeftMargin), new VerticalPosition(0f, LengthUnit.Millimeter, VerticalPositionAnchor.TopMargin), new Size(3, 3))); ((FloatingLayout)signatureShape.Layout).WrappingStyle = WrappingStyle.InFrontOfText; signatureShape.Outline.Fill.SetEmpty(); Paragraph firstPar = dcObj.GetChildElements(true).OfType <Paragraph>().FirstOrDefault(); firstPar.Inlines.Add(signatureShape); Picture signaturePict = new Picture(dcObj, sign); signaturePict.Layout = Layout.Floating( new HorizontalPosition(2.5, LengthUnit.Centimeter, HorizontalPositionAnchor.Page), new VerticalPosition(4.5, LengthUnit.Centimeter, VerticalPositionAnchor.Page), new Size(10, 5, LengthUnit.Centimeter)); PdfSaveOptions options = new PdfSaveOptions(); options.DigitalSignature.CertificatePath = @"..\..\sautinsoft.pfx"; options.DigitalSignature.CertificatePassword = "******"; options.DigitalSignature.SignatureLine = signatureShape; options.DigitalSignature.Signature = signaturePict; dcObj.Save(resultpdf, options); System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(resultpdf) { UseShellExecute = true }); }
public ActionResult FindText(HttpPostedFileBase upload, string existingText, string replaceText) { if (upload.ContentLength > 1) { string fileName = Path.GetFileName(upload.FileName); string fullFilePath = Path.Combine(Server.MapPath("~/App_Data"), fileName); if (System.IO.File.Exists(fullFilePath)) { var message = "This file already exist the system. Please change the file name"; ViewBag.Message = message.ToString(); return(View("ReplaceWordFile")); } else { upload.SaveAs(fullFilePath); DocumentCore dc = DocumentCore.Load(fullFilePath); int countDel = 0; Regex regex = new Regex("(?i)" + existingText.ToString()); foreach (ContentRange cr in dc.Content.Find(regex).Reverse()) { cr.Replace(replaceText.ToString()); countDel++; } var _ext = Path.GetExtension(upload.FileName); var FN = Path.GetFileNameWithoutExtension(fullFilePath); string _comPath = Path.Combine(Server.MapPath("~/App_Data"), FN); var path = _comPath + "_replace" + _ext; dc.Save(path); var message = "File saved in " + _comPath; ViewBag.Message = message.ToString(); } } return(View("ReplaceWordFile")); }
/// <summary> /// Insert a Line Break, Column Break, Page Break using DocumentBuilder. /// </summary> /// <remarks> /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/documentbuilder-inserting-break.php /// </remarks> static void InsertingBreak() { DocumentCore dc = new DocumentCore(); DocumentBuilder db = new DocumentBuilder(dc); string resultPath = @"result.docx"; db.PageSetup.TextColumns = new TextColumnCollection(2); // Insert the formatted text into the document using DocumentBuilder. db.CharacterFormat.FontName = "Verdana"; db.CharacterFormat.Size = 16.5f; db.CharacterFormat.AllCaps = true; db.CharacterFormat.Italic = true; db.CharacterFormat.FontColor = Color.Orange; db.ParagraphFormat.LeftIndentation = 30; db.Writeln("This paragraph has a Left Indentation of 30 points."); db.InsertSpecialCharacter(SpecialCharacterType.LineBreak); // Undo the previously applied formatting. db.ParagraphFormat.ClearFormatting(); db.CharacterFormat.ClearFormatting(); db.Writeln("After this paragraph insert a column break."); db.InsertSpecialCharacter(SpecialCharacterType.ColumnBreak); db.CharacterFormat.Italic = true; db.CharacterFormat.FontColor = Color.DarkBlue; db.CharacterFormat.Size = 20f; db.Writeln("After this paragraph insert a page break."); db.InsertSpecialCharacter(SpecialCharacterType.PageBreak); // Save the document to the file in DOCX format. dc.Save(resultPath); // Open the result for demonstration purposes. System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(resultPath) { UseShellExecute = true }); }
/// <summary> /// How to add a header and footer into PDF document. /// </summary> /// <remarks> /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/add-header-and-footer-in-pdf-net-csharp-vb.php /// </remarks> static void AddHeaderFooter() { string inpFile = @"..\..\shrek.pdf"; string outFile = "Shrek with header and footer.pdf"; DocumentCore dc = DocumentCore.Load(inpFile); // Create new header with formatted text. HeaderFooter header = new HeaderFooter(dc, HeaderFooterType.HeaderDefault); header.Content.Start.Insert("Shrek and Donkey", new CharacterFormat() { Size = 14.0, FontColor = Color.Brown }); foreach (Section s in dc.Sections) { s.HeadersFooters.Add(header.Clone(true)); } // Create new footer with formatted text. HeaderFooter footer = new HeaderFooter(dc, HeaderFooterType.FooterDefault); footer.Content.Start.Insert("Fiona.", new CharacterFormat() { Size = 14.0, FontColor = Color.Blue }); foreach (Section s in dc.Sections) { s.HeadersFooters.Add(footer.Clone(true)); } dc.Save(outFile); // Open the PDF documents for demonstration purposes. System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(inpFile) { UseShellExecute = true }); System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true }); }
/// Load an existing document (*.docx, *.rtf, *.pdf, *.html, *.txt, *.pdf) and save it as a PDF/A compliant version. public static void LoadAndSaveAsPDFA() { // Path to a loadable document. string loadPath = @"..\..\..\..\..\..\Testing Files\example.docx"; DocumentCore dc = DocumentCore.Load(loadPath); PdfSaveOptions options = new PdfSaveOptions() { // PdfComliance supports: PDF/A, PDF/1.5, etc. Compliance = PdfCompliance.PDF_A }; string savePath = Path.ChangeExtension(loadPath, ".pdf"); dc.Save(savePath, options); // Open file - example.pdf. ShowResult(savePath); }
/// <summary> /// Creates a new document and saves it as RTF file. /// </summary> /// <remarks> /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/save-document-as-rtf-net-csharp-vb.php /// </remarks> static void SaveToRtfFile() { // Assume we already have a document 'dc'. DocumentCore dc = new DocumentCore(); dc.Content.End.Insert("Hey Guys and Girls!\nFrom file.", new CharacterFormat() { FontColor = Color.Green, Size = 20 }); string filePath = @"Result-file.rtf"; dc.Save(filePath, new RtfSaveOptions()); // Open the result for demonstration purposes. System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath) { UseShellExecute = true }); }
/// <summary> /// Create file with Hello World. /// </summary> /// <remarks> /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/using-in-netcore.php /// </remarks> static void ExampleHelloWorld() { DocumentCore dc = new DocumentCore(); dc.Content.End.Insert("Hello World!", new CharacterFormat() { FontName = "Verdana", Size = 65.5d, FontColor = Color.DarkBlue }); // Save a document to a file in PDF format. string filePath = @"Result.pdf"; dc.Save(filePath); // Open the result for demonstration purposes. System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath) { UseShellExecute = true }); }
public IActionResult Send(LetterVIewModel model) { var docx = new DocumentCore(); foreach (var id in model.Ids.Split('.')) { var section = GetSectionForUser(docx, _context.Users.Single(x => x.Id == int.Parse(id))); var par = new Paragraph(docx); section.Blocks.Add(par); var separators = new List <char>(); for (var i = 0; i < 32; i++) { separators.Add((char)i); } for (var i = 0; i < 4; i++) { var run = new SpecialCharacter(docx, SpecialCharacterType.LineBreak); par.Inlines.Add(run); } var text = model.Text.Split(separators.ToArray(), StringSplitOptions.RemoveEmptyEntries); foreach (var str in text) { var run = new Run(docx, str); par.Inlines.Add(run); var @break = new SpecialCharacter(docx, SpecialCharacterType.LineBreak); par.Inlines.Add(@break); } par.ParagraphFormat.Alignment = HorizontalAlignment.Center; docx.Sections.Add(section); } var filename = Path.GetTempFileName(); docx.Save(filename, SaveOptions.DocxDefault); return(File(System.IO.File.ReadAllBytes(filename), "application/msword", "letter.docx")); }
public Stream DownloadDOCX(IEnumerable <TVChannel> items) { MemoryStream stream = new MemoryStream(); DocumentCore docx = new DocumentCore(); Section section = new Section(docx); docx.Sections.Add(section); section.PageSetup.PaperType = PaperType.A4; section.Blocks.Add(new Paragraph(docx, string.Format("Информация предоставлена (UTC): {0}", DateTime.UtcNow))); Table table = new Table(docx); table.TableFormat.Alignment = HorizontalAlignment.Left; TableRow tableRowHeader = new TableRow(docx); TableCell tableRowCellNameHeader = AddCellToDOCXTable("Название ТВ канала", ref docx, ref tableRowHeader); TableCell tableRowCellIPTVHeader = AddCellToDOCXTable("Наличие IPTV", ref docx, ref tableRowHeader); TableCell tableRowCellTVHeader = AddCellToDOCXTable("Наличие TV", ref docx, ref tableRowHeader); TableCell tableRowCellPackagesHeader = AddCellToDOCXTable("Входит в пакеты", ref docx, ref tableRowHeader); TableCell tableRowCellPriceHeader = AddCellToDOCXTable("Стоимость в месяц", ref docx, ref tableRowHeader); table.Rows.Add(tableRowHeader); foreach (TVChannel tvChannel in items) { TableRow tableRow = new TableRow(docx); string packages = string.Join(",", tvChannel.Packages.Select(item => item.Name)); TableCell tableRowCellName = AddCellToDOCXTable(tvChannel.Name, ref docx, ref tableRow); TableCell tableRowCellIPTV = AddCellToDOCXTable((tvChannel.IsIPTV ? "Да" : "Нет"), ref docx, ref tableRow); TableCell tableRowCellTV = AddCellToDOCXTable((tvChannel.IsIPTV ? "Да" : "Нет"), ref docx, ref tableRow); TableCell tableRowCellPackages = AddCellToDOCXTable(packages, ref docx, ref tableRow); TableCell tableRowCellPrice = AddCellToDOCXTable(tvChannel.Price.ToString(), ref docx, ref tableRow); table.Rows.Add(tableRow); } section.Blocks.Add(table); docx.Save(stream, SaveOptions.DocxDefault); return(stream); }
public void ExportToPDF() { var books = _bookService.GetAll() .Select(book => new { ID = book.Id + "\n", Name = book.Title + "\n" }) .OrderByDescending(book => book.ID) .ToList(); DocumentCore documentCore = new DocumentCore(); documentCore.Content.End .Insert("Books List: " + '\n', new CharacterFormat() { FontName = "Verdana", Size = 35.5f, FontColor = Color.Orange }); foreach (var book in books) { documentCore .Content .End .Insert("\n" + new string('-', 40) + '\n', new CharacterFormat() { FontName = "Verdana", Size = 7.5f, FontColor = Color.Orange }); documentCore.Content.End.Insert(book.ToString(), new CharacterFormat() { FontName = "Verdana", Size = 7.5f }); } string filePath = @"BookList.pdf"; documentCore.Save(filePath); System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath) { UseShellExecute = true }); }
/// <summary> /// Creates a new document and saves it as Text file. /// </summary> /// <remarks> /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/save-document-as-text-net-csharp-vb.php /// </remarks> static void SaveToTextFile() { // Assume we already have a document 'dc'. DocumentCore dc = new DocumentCore(); dc.Content.End.Insert("Hey Guys and Girls!"); string filePath = @"Result-file.txt"; dc.Save(filePath, new TxtSaveOptions() { Encoding = System.Text.Encoding.UTF8, ParagraphBreak = Environment.NewLine }); // Open the result for demonstration purposes. System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath) { UseShellExecute = true }); }
private void ConvertPdfToWord(string pdfFile, string docxFile, string docxPass) { try { PdfLoadOptions pdfOptions = new PdfLoadOptions(); pdfOptions.ConversionMode = PdfConversionMode.Flowing; pdfOptions.DetectTables = true; pdfOptions.RasterizeVectorGraphics = true; if (!string.IsNullOrEmpty(docxPass)) { pdfOptions.Password = docxPass; } DocumentCore pdf = DocumentCore.Load(pdfFile, pdfOptions); pdf.Save(docxFile); } catch (Exception ex) { throw ex; } }
/// <summary> /// Removes the old header/footer and inserts a new one into an existing PDF document. /// </summary> /// <remarks> /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/remove-header-and-footer-in-pdf-net-csharp-vb.php /// </remarks> static void ReplaceHeader() { string inpFile = @"..\..\somebody.pdf"; string outFile = "With new Header.pdf"; DocumentCore dc = DocumentCore.Load(inpFile); // Create new header with formatted text. HeaderFooter header = new HeaderFooter(dc, HeaderFooterType.HeaderDefault); header.Content.Start.Insert("Modified : 1 April 2020", new CharacterFormat() { Size = 14.0, FontColor = Color.DarkGreen }); // Add 10 mm from Top before new header. (header.Blocks[0] as Paragraph).ParagraphFormat.SpaceBefore = LengthUnitConverter.Convert(10, LengthUnit.Millimeter, LengthUnit.Point); foreach (Section s in dc.Sections) { // Find the first paragraph (Let's assume that it's the header) and remove it. if (s.Blocks.Count > 0) { s.Blocks.RemoveAt(0); } // Insert the new header into the each section. s.HeadersFooters.Add(header.Clone(true)); } dc.Save(outFile); // Open the results for demonstration purposes. System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(inpFile) { UseShellExecute = true }); System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true }); }
/// <summary> /// Inserting a plain text content control. /// </summary> /// <remarks> /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/content-controls-insert-plain-text-net-csharp-vb.php /// </remarks> static void InsertPlainText() { // Let's create a simple document. DocumentCore dc = new DocumentCore(); // Create a plain text content control. BlockContentControl pt = new BlockContentControl(dc, ContentControlType.PlainText); // Add a new section. dc.Sections.Add(new Section(dc, pt)); // Add the content control properties. pt.Properties.Title = "Title"; pt.Properties.Multiline = true; pt.Properties.Color = Color.Blue; pt.Document.DefaultCharacterFormat.FontColor = Color.Orange; // Add new paragraph with formatted text. pt.Blocks.Add(new Paragraph(dc, new Run(dc, "This is first paragraph with symbols added on a new line."), new SpecialCharacter(dc, SpecialCharacterType.LineBreak), new Run(dc, "This is a new line in the first paragraph."), new SpecialCharacter(dc, SpecialCharacterType.LineBreak), new Run(dc, "Insert the \"Wingdings\" font family with formatting."), new Run(dc, "\xFC" + "\xF0" + "\x32") { CharacterFormat = { FontName = "Wingdings", FontColor = new Color("#000000"), Size = 48 } })); // Save our document into DOCX format. string resultPath = @"result.docx"; dc.Save(resultPath, new DocxSaveOptions()); // Open the result for demonstration purposes. System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(resultPath) { UseShellExecute = true }); }
/// <summary> /// Load a PDF document and get missing fonts. /// </summary> /// <remarks> /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/load-pdf-document-get-missing-fonts-net-csharp-vb.php /// </remarks> static void LoadPDF() { string inpFile = @"..\..\fonts.pdf"; string outFile = "Result.docx"; // Some PDF documents can use rare fonts which isn't installed in your system. // During the loading of a PDF document the component tries to find all necessary // fonts installed in your system. // In case of the font is missing, you can find its name in the property 'MissingFonts' (after the loading process). DocumentCore dc = DocumentCore.Load(inpFile); if (SautinSoft.Document.FontSettings.MissingFonts.Count > 0) { Console.WriteLine("Missing Fonts:"); foreach (string fontFamily in SautinSoft.Document.FontSettings.MissingFonts) { Console.WriteLine(fontFamily); } } // Next, knowing missing fonts, you can install these fonts in your system. // Also, you can specify an extra folder where component should find fonts. SautinSoft.Document.FontSettings.UserFontsDirectory = @"d:\My Fonts"; // Furthermore, you can add font substitutes, to use alternative fonts. SautinSoft.Document.FontSettings.AddFontSubstitutes("Melvetika", "Segoe UI"); Console.WriteLine("We\'ve changed Melvetica font to Segoe UI"); // Load the document again. dc = DocumentCore.Load(inpFile); dc.Save(outFile); // Open the result for demonstration purposes. System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true }); Console.ReadKey(); }
/// <summary> /// Convert PDF to HTML (using Stream). /// </summary> /// <remarks> /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/convert-document.php /// </remarks> static void ConvertFromStream() { // We need files only for demonstration purposes. // The conversion process will be done completely in memory. string inpFile = @"..\..\example.pdf"; string outFile = @"Result.html"; byte[] inpData = File.ReadAllBytes(inpFile); byte[] outData = null; using (MemoryStream msInp = new MemoryStream(inpData)) { // Load a document. DocumentCore dc = DocumentCore.Load(msInp, new PdfLoadOptions() { PreserveGraphics = true, DetectTables = true }); // Save the document to HTML-fixed format. using (MemoryStream outMs = new MemoryStream()) { dc.Save(outMs, new HtmlFixedSaveOptions() { CssExportMode = CssExportMode.Inline, EmbedImages = true }); outData = outMs.ToArray(); } // Show the result for demonstration purposes. if (outData != null) { File.WriteAllBytes(outFile, outData); System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true }); } } }
/// <summary> /// Adds two paragraphs by different ways: using ContentRange and as Element. /// </summary> /// <remarks> /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/contentrange-manipulation.php /// </remarks> static void ContentRangeManipulation() { string filePath = @"Result.docx"; // Let's create a new document. DocumentCore dc = new DocumentCore(); // Way 1: Add new paragraph using the property Content (class ContentRange). Paragraph par = new Paragraph(dc, "This is paragraph. "); par.ParagraphFormat.BackgroundColor = Color.Yellow; // Note, our Paragraph will be cloned and the clone will be inserted. // The property Content (class ContentRange) each time clones the inserting object. dc.Content.End.Insert(par.Content); // Way 2: Add paragraph into the Block collection as Element. // Note, you can't insert the one Element two times. // The cloning does not occur here. par.ParagraphFormat.BackgroundColor = Color.Red; dc.Sections[0].Blocks.Add(par); // Again Way 1: Change Background color to blue and insert // the copy (clone) of our paragraph using Content (class ContentRange). par.ParagraphFormat.BackgroundColor = Color.Blue; dc.Content.End.Insert(par.Content); // Change background to 'Green' for the paragraph. // This affect only to the paragraph inserted by 'Way 2' - as Element. // Because in 'Way 1' we added clones using ContentRange. par.ParagraphFormat.BackgroundColor = Color.Green; // Save our document. dc.Save(filePath); // Open the result for demonstration purposes. System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePath) { UseShellExecute = true }); }
/// <summary> /// Get a Picture size, Change it and Save the document back. /// </summary> /// <remarks> /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/get-and-change-picture-size-in-docx-csharp-vb-net.php /// </remarks> public static void GetAndChangePictureSize() { // Path to a document where to extract pictures. string inpFile = @"..\..\example.docx"; string outFile = "Result.docx"; // Load the document. DocumentCore dc = DocumentCore.Load(inpFile); // Get the physical size of the first picture from the document. Picture pict = dc.GetChildElements(true, ElementType.Picture).FirstOrDefault() as Picture; Size size = pict.Layout.Size; Console.WriteLine("The 1st picture has this size:\r\n"); Console.WriteLine("W: {0}, H: {1} (In points)", size.Width, size.Height); Console.WriteLine("W: {0}, H: {1} (In pixels)", LengthUnitConverter.Convert(size.Width, LengthUnit.Point, LengthUnit.Pixel), LengthUnitConverter.Convert(size.Height, LengthUnit.Point, LengthUnit.Pixel)); Console.WriteLine("W: {0:F2}, H: {1:F2} (In mm)", LengthUnitConverter.Convert(size.Width, LengthUnit.Point, LengthUnit.Millimeter), LengthUnitConverter.Convert(size.Height, LengthUnit.Point, LengthUnit.Millimeter)); Console.WriteLine("W: {0:F2}, H: {1:F2} (In cm)", LengthUnitConverter.Convert(size.Width, LengthUnit.Point, LengthUnit.Centimeter), LengthUnitConverter.Convert(size.Height, LengthUnit.Point, LengthUnit.Centimeter)); Console.WriteLine("W: {0:F2}, H: {1:F2} (In inches)", LengthUnitConverter.Convert(size.Width, LengthUnit.Point, LengthUnit.Inch), LengthUnitConverter.Convert(size.Height, LengthUnit.Point, LengthUnit.Inch)); Console.WriteLine("\r\nNow let\'s increase the picture size in x1.5 times. Press any key ..."); Console.ReadKey(); // Note, we don't change the physical picture size we only scale/stretch the it. pict.Layout.Size = new Size(size.Width * 1.5, size.Height * 1.5); // Save the document as a new docx file. dc.Save(outFile); // Open the result for demonstration purposes. System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true }); }
/// <summary> /// Loads an existing DOCX document and calculates all 'Run' objects. /// </summary> /// <remarks> /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/run-element-text-in-docx-document-net-csharp-vb.php /// </remarks> static void CalculateRuns() { string filePath = @"..\..\example.docx"; DocumentCore dc = DocumentCore.Load(filePath); string filePathResult = @"Result-file.docx"; foreach (Paragraph par in dc.GetChildElements(true, ElementType.Paragraph)) { int totalRuns = par.GetChildElements(true, ElementType.Run).Count(); Run r = new Run(dc, "<<This paragraph contains " + totalRuns.ToString() + " Run(s)>>", new CharacterFormat() { BackgroundColor = Color.Yellow, Size = 10, FontColor = Color.Black }); par.Content.End.Insert(r.Content); } dc.Save(filePathResult); System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(filePathResult) { UseShellExecute = true }); }
public Stream DownloadDOCX(TVChannelPackage item) { MemoryStream stream = new MemoryStream(); DocumentCore docx = new DocumentCore(); Section section = new Section(docx); docx.Sections.Add(section); section.PageSetup.PaperType = PaperType.A4; section.Blocks.Add(new Paragraph(docx, string.Format("Информация предоставлена (UTC): {0}", DateTime.UtcNow))); section.Blocks.Add(new Paragraph(docx, string.Format("Название пакета ТВ: {0}", item.Name))); section.Blocks.Add(new Paragraph(docx, string.Format("Количество каналов в пакете: {0}", item.Channels.Count()))); section.Blocks.Add(new Paragraph(docx, string.Format("Стоимость в месяц: {0}", item.Price))); section.Blocks.Add(new Paragraph(docx, string.Format("Список каналов:"))); Table table = new Table(docx); table.TableFormat.Alignment = HorizontalAlignment.Left; TableRow tableRowHeader = new TableRow(docx); TableCell tableRowCellNameHeader = AddCellToDOCXTable("Название канала", ref docx, ref tableRowHeader); TableCell tableRowCellIPTVHeader = AddCellToDOCXTable("Наличие IPTV", ref docx, ref tableRowHeader); TableCell tableRowCellTVHeader = AddCellToDOCXTable("Наличие TV", ref docx, ref tableRowHeader); table.Rows.Add(tableRowHeader); foreach (TVChannel tvChannel in item.Channels) { TableRow tableRow = new TableRow(docx); TableCell tableRowCellName = AddCellToDOCXTable(tvChannel.Name, ref docx, ref tableRow); TableCell tableRowCellIPTV = AddCellToDOCXTable((tvChannel.IsIPTV ? "Да" : "Нет"), ref docx, ref tableRow); TableCell tableRowCellTV = AddCellToDOCXTable((tvChannel.IsTV ? "Да" : "Нет"), ref docx, ref tableRow); table.Rows.Add(tableRow); } section.Blocks.Add(table); docx.Save(stream, SaveOptions.DocxDefault); return(stream); }