private void InsertCover(Section section) { ParagraphStyle small = new ParagraphStyle(section.Document); small.Name = "small"; small.CharacterFormat.FontName = "Arial"; small.CharacterFormat.FontSize = 9; small.CharacterFormat.TextColor = Color.Gray; section.Document.Styles.Add(small); Paragraph paragraph = section.AddParagraph(); paragraph.AppendText("The sample demonstrates how to insert a header and footer into a document."); paragraph.ApplyStyle(small.Name); Paragraph title = section.AddParagraph(); TextRange text = title.AppendText("Field Types Supported by Spire.Doc"); text.CharacterFormat.FontName = "Arial"; text.CharacterFormat.FontSize = 36; text.CharacterFormat.Bold = true; title.Format.BeforeSpacing = section.PageSetup.PageSize.Height / 2 - 3 * section.PageSetup.Margins.Top; title.Format.AfterSpacing = 8; title.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Right; paragraph = section.AddParagraph(); paragraph.AppendText("e-iceblue Spire.Doc team."); paragraph.ApplyStyle(small.Name); paragraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Right; }
public void TestCloning() { TextDocument document = new TextDocument(); document.New(); Paragraph paragraph = ParagraphBuilder.CreateStandardTextParagraph(document); paragraph.TextContent.Add(new SimpleText(document, "Some text")); Paragraph paragraphClone = (Paragraph)paragraph.Clone(); //Assert.AreEqual(paragraph.Node, paragraphClone.Node, "Should be cloned and not equal."); //Assert.AreEqual(paragraph.TextContent[0].GetType(), paragraphClone.TextContent[0].GetType(), "Should be cloned and equal."); ParagraphStyle paragraphStyle = new ParagraphStyle(document, "P1"); paragraphStyle.TextProperties.Bold = "bold"; //Add paragraph style to the document, //only automaticaly created styles will be added also automaticaly document.Styles.Add(paragraphStyle); paragraphClone.ParagraphStyle = paragraphStyle; //Clone the clone Paragraph paragraphClone2 = (Paragraph)paragraphClone.Clone(); Assert.AreNotEqual(paragraphClone2.Node, paragraphClone.Node, "Should be cloned and not equal."); Assert.AreEqual(paragraphClone2.TextContent[0].GetType(), paragraphClone.TextContent[0].GetType(), "Should be cloned and equal."); //Cloning of styles isn't supported! Assert.AreSame(paragraphClone2.ParagraphStyle, paragraphClone.ParagraphStyle, "Must be same style object. Styles have to be cloned explicitly."); document.Content.Add(paragraph); document.Content.Add(paragraphClone); document.Content.Add(paragraphClone2); using (IPackageWriter writer = new OnDiskPackageWriter()) { document.Save(AARunMeFirstAndOnce.outPutFolder + "clonedParagraphs.odt", new OpenDocumentTextExporter(writer)); } }
/// <override></override> public override void DrawThumbnail(Image image, int margin, Color transparentColor) { AutoSize = false; Text = "ab"; Size textSize = Size.Empty; // Create a ParameterStyle without padding ParagraphStyle paragraphStyle = new ParagraphStyle(); paragraphStyle.Alignment = ContentAlignment.TopLeft; paragraphStyle.Padding = new TextPadding(0); paragraphStyle.Trimming = StringTrimming.None; paragraphStyle.WordWrap = false; ParagraphStyle = paragraphStyle; textSize = TextMeasurer.MeasureText(Text, ToolCache.GetFont(CharacterStyle), textSize, ParagraphStyle); Width = textSize.Width; Height = textSize.Height; // If the linestyle is transparent, modify margin in order to improve the text's readability int marginCorrection = (LineStyle.ColorStyle.Transparency == 100) ? 3 : 0; base.DrawThumbnail(image, margin - marginCorrection, transparentColor); }
static void Main(string[] args) { // Nenhuma declaração de váriaveis tem que ter espaçamento // Criando um novo documento com o nome arquivos Document arquivos = new Document(); //Criando uma seção dentro do arquivos //A cada seção criada uma nova página é adcionada Section secaoCapa = arquivos.AddSection(); //Criando um paragrafo, dentro da classe Paragraph cria-se um título //Insira um título na primeira página Paragraph titulo = secaoCapa.AddParagraph(); //Insiro na minha váriavel títulos o valor da string Título muito Bonito //Coloca um texto dentro do arquivo // \n\n quebra de linha titulo.AppendText("Título muito Bonito\n\n"); // Da uma posição dentro do meu paragrafo //Alinha horizontalmente o título titulo.Format.HorizontalAlignment = HorizontalAlignment.Center; // Da um estilo para o paragrafo, dentro da minha classe arquivos ParagraphStyle estilo01 = new ParagraphStyle(arquivos); //Define o nome da classe estilo01 estilo01.Name = "Cor do título"; //Transforma a propriedade TextColor de Azul escuro estilo01.CharacterFormat.TextColor = Color.DarkBlue; //Transformar a propriedade Bold em true, negrito estilo01.CharacterFormat.Bold = true; // Adicionar o estilo e colocar como usável no nosso arquivo arquivos.Styles.Add(estilo01); titulo.ApplyStyle(estilo01.Name); // Salvar para um arquivo Paragraph texto = secaoCapa.AddParagraph(); texto.AppendText("Preconceito é uma opinião desfavorável que não é baseada em dados objetivos, mas que é baseada unicamente em um sentimento hostil motivado por hábitos de julgamento ou generalizações apressadas. A palavra também pode significar uma ideia ou conceito formado antecipadamente e sem fundamento sério ou imparcial.\n\n"); texto.Format.HorizontalAlignment = HorizontalAlignment.Center; ParagraphStyle texto02 = new ParagraphStyle(arquivos); texto02.Name = "cor do texto"; texto02.CharacterFormat.TextColor = Color.Aquamarine; arquivos.Styles.Add(texto02); texto.ApplyStyle(texto02.Name); arquivos.SaveToFile(@"Saida\exemploWord3.docx", FileFormat.Docx); // arquivos.SaveToFile(@"Saida\textoWord.docx",FileFormat.Docx); }
static void CreateNewLinkedStyle(RichEditDocumentServer server) { #region #CreateNewLinkedStyle Document document = server.Document; document.BeginUpdate(); document.AppendText("Line One\nLine Two\nLine Three"); document.EndUpdate(); ParagraphStyle lstyle = document.ParagraphStyles["MyLinkedStyle"]; if (lstyle == null) { document.BeginUpdate(); lstyle = document.ParagraphStyles.CreateNew(); lstyle.Name = "MyLinkedStyle"; lstyle.LineSpacingType = ParagraphLineSpacing.Double; lstyle.Alignment = ParagraphAlignment.Center; document.ParagraphStyles.Add(lstyle); CharacterStyle lcstyle = document.CharacterStyles.CreateNew(); lcstyle.Name = "MyLinkedCStyle"; document.CharacterStyles.Add(lcstyle); lcstyle.LinkedStyle = lstyle; lcstyle.ForeColor = System.Drawing.Color.DarkGreen; lcstyle.Strikeout = StrikeoutType.Single; lcstyle.FontSize = 24; document.EndUpdate(); document.SaveDocument("LinkedStyleSample.docx", DevExpress.XtraRichEdit.DocumentFormat.OpenXml); System.Diagnostics.Process.Start("explorer.exe", "/select," + "LinkedStyleSample.docx"); } #endregion #CreateNewLinkedStyle }
/// <summary> /// Creates the paragraph style. /// </summary> /// <param name="styleNode">The style node.</param> private void CreateParagraphStyle(XElement styleNode) { ParagraphStyle paragraphStyle = new ParagraphStyle(_document, styleNode); IPropertyCollection pCollection = new IPropertyCollection(); if (styleNode.HasElements) { foreach (XElement node in styleNode.Elements()) { IProperty property = GetProperty(paragraphStyle, new XElement(node)); if (property != null) { pCollection.Add(property); } } } paragraphStyle.Node.Value = ""; foreach (IProperty property in pCollection) { paragraphStyle.PropertyCollection.Add(property); } if (!_common) { _document.Styles.Add(paragraphStyle); } else { _document.CommonStyles.Add(paragraphStyle); } }
public Formatting.ParagraphModel Import(IExchangableText text, ParagraphStyle paragraphStyle) { var visitor = new Visitor(); visitor.BeginParagraph(_latinWordMetric, paragraphStyle); text.Accept(visitor); return visitor.EndParagraph(); }
static void Main(string[] args) { // Criando um novo documento com o nome documento Document doc = new Document(); // Criando uma seção dentro do documento // A cada seção criada uma nova página é adicionada Section secaoCapa = doc.AddSection(); Paragraph titulo = secaoCapa.AddParagraph(); titulo.AppendText("Título muito bonito\n\n"); titulo.Format.HorizontalAlignment = HorizontalAlignment.Center; ParagraphStyle estilo01 = new ParagraphStyle(doc); estilo01.Name = "Cor do título"; //Define o nome da classe estilo01 estilo01.CharacterFormat.TextColor = Color.DarkBlue; estilo01.CharacterFormat.Bold = true; doc.Styles.Add(estilo01); titulo.ApplyStyle(estilo01.Name); doc.SaveToFile(@"Saída\exemploWord.docx", FileFormat.Docx); }
/// <ToBeCompleted></ToBeCompleted> public void CreateStyle(Design design, StyleCategory category) { if (design == null) { throw new ArgumentNullException("design"); } Style style; switch (category) { case StyleCategory.CapStyle: style = new CapStyle(GetNewStyleName(design.CapStyles)); ((CapStyle)style).CapShape = CapShape.None; ((CapStyle)style).ColorStyle = design.ColorStyles.Black; break; case StyleCategory.CharacterStyle: style = new CharacterStyle(GetNewStyleName(design.CharacterStyles)); ((CharacterStyle)style).ColorStyle = design.ColorStyles.Black; break; case StyleCategory.ColorStyle: style = new ColorStyle(GetNewStyleName(design.ColorStyles)); ((ColorStyle)style).Color = Color.Black; ((ColorStyle)style).Transparency = 0; break; case StyleCategory.FillStyle: style = new FillStyle(GetNewStyleName(design.FillStyles)); ((FillStyle)style).AdditionalColorStyle = design.ColorStyles.White; ((FillStyle)style).BaseColorStyle = design.ColorStyles.Black; ((FillStyle)style).FillMode = FillMode.Gradient; ((FillStyle)style).ImageLayout = ImageLayoutMode.Fit; break; case StyleCategory.LineStyle: style = new LineStyle(GetNewStyleName(design.LineStyles)); ((LineStyle)style).ColorStyle = design.ColorStyles.Black; ((LineStyle)style).DashCap = System.Drawing.Drawing2D.DashCap.Round; ((LineStyle)style).DashType = DashType.Solid; ((LineStyle)style).LineJoin = System.Drawing.Drawing2D.LineJoin.Round; ((LineStyle)style).LineWidth = 1; break; case StyleCategory.ParagraphStyle: style = new ParagraphStyle(GetNewStyleName(design.ParagraphStyles)); ((ParagraphStyle)style).Alignment = ContentAlignment.MiddleCenter; ((ParagraphStyle)style).Padding = new TextPadding(3); ((ParagraphStyle)style).Trimming = StringTrimming.EllipsisCharacter; ((ParagraphStyle)style).WordWrap = false; break; default: throw new NShapeUnsupportedValueException(typeof(StyleCategory), category); } ICommand cmd = new CreateStyleCommand(design, style); project.ExecuteCommand(cmd); }
public static void CreateAndSavePageRange() { // ExStart:CreateAndSavePageRange // ExFor:Document // ExFor:Page // ExFor:Page.Title // ExFor:Title // ExFor:Title.TitleText // ExFor:Title.TitleDate // ExFor:Title.TitleTime // ExFor:RichText // ExFor:RichText.Text // ExFor:HtmlSaveOptions // ExFor:HtmlSaveOptions.PageCount // ExFor:HtmlSaveOptions.PageIndex // ExSummary:Shows how to create a document and save in html format specified range of pages. // The path to the documents directory. string dataDir = RunExamples.GetDataDir_LoadingAndSaving(); // Initialize OneNote document Document doc = new Document(); Aspose.Note.Page page = new Aspose.Note.Page(doc); // Default style for all text in the document. ParagraphStyle textStyle = new ParagraphStyle { FontColor = Color.Black, FontName = "Arial", FontSize = 10 }; page.Title = new Title(doc) { TitleText = new RichText(doc) { Text = "Title text.", ParagraphStyle = textStyle }, TitleDate = new RichText(doc) { Text = new DateTime(2011, 11, 11).ToString("D", CultureInfo.InvariantCulture), ParagraphStyle = textStyle }, TitleTime = new RichText(doc) { Text = "12:34", ParagraphStyle = textStyle } }; doc.AppendChildLast(page); // Save as HTML format dataDir = dataDir + "CreateAndSavePageRange_out.html"; doc.Save(dataDir, new HtmlSaveOptions { PageCount = 1, PageIndex = 0 }); // ExEnd:CreateAndSavePageRange Console.WriteLine("\nOneNote document created successfully and saved as page range.\nFile saved at " + dataDir); }
protected static void ApplyParagraphStyles(Paragraph paragraph, ParagraphStyle style) { if (style != null) { BindingOperations.SetBinding(paragraph, Paragraph.MarginProperty, CreateBinding(style, "Margin")); ApplyTextStyles(paragraph, style); } }
public ParagraphBuilder(ILatinWordMetric latinMetric, ParagraphStyle style) { _wordWrap = new WordWrapStrategy(); _advancing = new AdvancingStrategy(style.Indent); _latinMetric = latinMetric; _zwSize = style.FontSize; _rubyZwSize = style.FontSize * style.RubyFontSizeRatio; }
public void BeginParagraph(ILatinWordMetric latinMetric, ParagraphStyle style) { _builder = new Formatting.ParagraphBuilder(latinMetric, style); _builder.BeginParagraph(); _inRuby = false; _rubyBaseText = new UStringBuilder(16); _rubyText = null; }
public Formatting.ParagraphModel Import(IExchangableText text, ParagraphStyle paragraphStyle) { var visitor = new Visitor(); visitor.BeginParagraph(_latinWordMetric, paragraphStyle); text.Accept(visitor); return(visitor.EndParagraph()); }
public static void Run() { // ExStart:AddTextNodeWithTag // ExFor:NoteTagCore // ExFor:NoteTagCore.Icon // ExFor:NoteTag // ExFor:RichText // ExFor:RichText.Text // ExFor:RichText.ParagraphStyle // ExSummary:Shows how to add new paragraph with tag. // The path to the documents directory. string dataDir = RunExamples.GetDataDir_Tags(); // Create an object of the Document class Document doc = new Document(); // Initialize Page class object Aspose.Note.Page page = new Aspose.Note.Page(doc); // Initialize Outline class object Outline outline = new Outline(doc); // Initialize OutlineElement class object OutlineElement outlineElem = new OutlineElement(doc); ParagraphStyle textStyle = new ParagraphStyle { FontColor = Color.Black, FontName = "Arial", FontSize = 10 }; RichText text = new RichText(doc) { Text = "OneNote text.", ParagraphStyle = textStyle }; text.Tags.Add(new NoteTag { Icon = TagIcon.YellowStar, }); // Add text node outlineElem.AppendChildLast(text); // Add outline element node outline.AppendChildLast(outlineElem); // Add outline node page.AppendChildLast(outline); // Add page node doc.AppendChildLast(page); // Save OneNote document dataDir = dataDir + "AddTextNodeWithTag_out.one"; doc.Save(dataDir); // ExEnd:AddTextNodeWithTag Console.WriteLine("\nText node with tag added successfully.\nFile saved at " + dataDir); }
/// <summary> /// How the Styles Inheritance does work. /// </summary> /// <remarks> /// https://sautinsoft.com/products/document/help/net/developer-guide/styles-inheritance.php /// </remarks> static void StyleInheritance() { string docxPath = @"StylesInheritance.docx"; // Let's create document. DocumentCore dc = new DocumentCore(); dc.DefaultCharacterFormat.FontColor = Color.Blue; Section section = new Section(dc); section.Blocks.Add(new Paragraph(dc, new Run(dc, "The document has Default Character Format with 'Blue' color.", new CharacterFormat() { Size = 18 }))); dc.Sections.Add(section); // Create a new Paragraph and Style with 'Yellow' background. Paragraph par = new Paragraph(dc); ParagraphStyle styleYellowBg = new ParagraphStyle("YellowBackground"); styleYellowBg.CharacterFormat.BackgroundColor = Color.Yellow; dc.Styles.Add(styleYellowBg); par.ParagraphFormat.Style = styleYellowBg; par.Inlines.Add(new Run(dc, "This paragraph has Style 'Yellow Background' and it inherits 'Blue Color' from the document's DefaultCharacterFormat.")); par.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); Run run1 = new Run(dc, "This Run doesn't have a style, but it inherits 'Yellow Background' from the paragraph style and 'Blue Color' from the document's DefaultCharacterFormat."); run1.CharacterFormat.Italic = true; par.Inlines.Add(run1); par.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak)); Run run2 = new Run(dc, " This run has own Style with 'Green Color'."); CharacterStyle styleGreenText = new CharacterStyle("GreenText"); styleGreenText.CharacterFormat.FontColor = Color.Green; dc.Styles.Add(styleGreenText); run2.CharacterFormat.Style = styleGreenText; par.Inlines.Add(run2); Paragraph par2 = new Paragraph(dc); Run run3 = new Run(dc, "This is a new paragraph without a style. This is a Run also without style. " + "But they both inherit 'Blue Color' from their parent - the document."); par2.Inlines.Add(run3); section.Blocks.Add(par); section.Blocks.Add(par2); // Save our document into DOCX format. dc.Save(docxPath); // Open the result for demonstration purposes. System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(docxPath) { UseShellExecute = true }); }
private static void ToWord() { //Configure path. string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string filePath = desktopPath + @"\test.docx"; string picPath = desktopPath + @"\wang.jpg"; //Create a word document. Document doc = new Document(); //Add a section. Section section = doc.AddSection(); //Add a paragraph. Paragraph paragraph = section.AddParagraph(); paragraph.AppendText("Spire is me."); //Add a comment. string content = "CNblog:http://www.cnblogs.com/LanTianYou/"; Comment comment = paragraph.AppendComment(content); comment.Format.Author = "Tylan"; //Set font style for the paragraph. ParagraphStyle style = new ParagraphStyle(doc); style.Name = "TylanFontStyle"; style.CharacterFormat.FontName = "Batang"; style.CharacterFormat.FontSize = 36; style.CharacterFormat.TextColor = Color.Green; doc.Styles.Add(style); paragraph.ApplyStyle(style.Name); //Insert a picture. DocPicture pic = paragraph.AppendPicture(Image.FromFile(picPath)); pic.Width = 500; pic.Height = 500; //Add header. HeaderFooter header = doc.Sections[0].HeadersFooters.Header; Paragraph headerParagraph = header.AddParagraph(); TextRange headerText = headerParagraph.AppendText("Spire header"); headerText.CharacterFormat.FontSize = 18; headerText.CharacterFormat.TextColor = Color.Tomato; headerParagraph.Format.Borders.Bottom.BorderType = BorderStyle.ThinThinSmallGap; headerParagraph.Format.Borders.Bottom.Space = 0.15f; headerParagraph.Format.Borders.Color = Color.DarkGray; //Add footer. HeaderFooter footer = doc.Sections[0].HeadersFooters.Footer; Paragraph footerParagraph = footer.AddParagraph(); TextRange footerText = footerParagraph.AppendText("Spire footer"); footerText.CharacterFormat.FontSize = 18; footerText.CharacterFormat.TextColor = Color.Tomato; footerParagraph.Format.Borders.Top.BorderType = BorderStyle.ThinThinSmallGap; footerParagraph.Format.Borders.Top.Space = 0.15f; footerParagraph.Format.Borders.Color = Color.DarkGray; //Save the file. doc.SaveToFile(filePath, FileFormat.Docx); }
/// <summary> /// Gets the paragraph style as HTML. /// </summary> /// <param name="paragraphStyle">The paragraph style.</param> /// <returns></returns> public string GetParagraphStyleAsHtml(ParagraphStyle paragraphStyle) { string style = "style=\""; try { if (paragraphStyle != null) { if (paragraphStyle.ParagraphProperties != null) { if (paragraphStyle.ParagraphProperties.Alignment != null && paragraphStyle.ParagraphProperties.Alignment != "start") { style += "text-align: " + paragraphStyle.ParagraphProperties.Alignment + "; "; } if (paragraphStyle.ParagraphProperties.MarginLeft != null) { style += "text-indent: " + paragraphStyle.ParagraphProperties.MarginLeft + "; "; } if (paragraphStyle.ParagraphProperties.LineSpacing != null) { style += "line-height: " + paragraphStyle.ParagraphProperties.LineSpacing + "; "; } if (paragraphStyle.ParagraphProperties.Border != null && paragraphStyle.ParagraphProperties.Padding == null) { style += "border-width:1px; border-style:solid; padding: 0.5cm; "; } if (paragraphStyle.ParagraphProperties.Border != null && paragraphStyle.ParagraphProperties.Padding != null) { style += "border-width:1px; border-style:solid; padding:" + paragraphStyle.ParagraphProperties.Padding + "; "; } if (paragraphStyle.ParagraphProperties.BackgroundColor != null) { style += "background-color: " + paragraphStyle.ParagraphProperties.BackgroundColor + "; "; } } } } catch (Exception ex) { throw new AODLException("Exception while trying to build a HTML style string from a ParagraphStyle.", ex); } if (!style.EndsWith("; ")) { style = ""; } else { style += "\""; } return(style); }
public static void Run() { // ExStart:CreateDocWithSimpleRichText // ExFor:Document // ExFor:RichText // ExFor:RichText.Text // ExSummary:Shows how to create a document with a text. // The path to the documents directory. string dataDir = RunExamples.GetDataDir_LoadingAndSaving(); // Create an object of the Document class Document doc = new Document(); // Initialize Page class object Page page = new Page(doc); // Initialize Outline class object Outline outline = new Outline(doc); // Initialize OutlineElement class object OutlineElement outlineElem = new OutlineElement(doc); // Initialize TextStyle class object and set formatting properties ParagraphStyle textStyle = new ParagraphStyle { FontColor = Color.Black, FontName = "Arial", FontSize = 10 }; // Initialize RichText class object and apply text style RichText text = new RichText(doc) { Text = "Hello OneNote text!", ParagraphStyle = textStyle }; // Add RichText node outlineElem.AppendChildLast(text); // Add OutlineElement node outline.AppendChildLast(outlineElem); // Add Outline node page.AppendChildLast(outline); // Add Page node doc.AppendChildLast(page); // Save OneNote document dataDir = dataDir + "CreateDocWithSimpleRichText_out.one"; doc.Save(dataDir); // ExEnd:CreateDocWithSimpleRichText Console.WriteLine("\nOneNote document created successfully with simple rich text.\nFile saved at " + dataDir); }
public static void Run() { // ExStart:CreateDocWithPageTitle // ExFor:Document // ExFor:Page // ExFor:Page.Title // ExFor:Title // ExFor:Title.TitleText // ExFor:Title.TitleDate // ExFor:Title.TitleTime // ExSummary:Shows how to create a document with titled page. // The path to the documents directory. string dataDir = RunExamples.GetDataDir_LoadingAndSaving(); // Create an object of the Document class Document doc = new Aspose.Note.Document(); // Initialize Page class object Aspose.Note.Page page = new Aspose.Note.Page(doc); // Default style for all text in the document. ParagraphStyle textStyle = new ParagraphStyle { FontColor = Color.Black, FontName = "Arial", FontSize = 10 }; // Set page title properties page.Title = new Title(doc) { TitleText = new RichText(doc) { Text = "Title text.", ParagraphStyle = textStyle }, TitleDate = new RichText(doc) { Text = new DateTime(2011, 11, 11).ToString("D", CultureInfo.InvariantCulture), ParagraphStyle = textStyle }, TitleTime = new RichText(doc) { Text = "12:34", ParagraphStyle = textStyle } }; // Append Page node in the document doc.AppendChildLast(page); // Save OneNote document dataDir = dataDir + "CreateDocWithPageTitle_out.one"; doc.Save(dataDir); // ExEnd:CreateDocWithPageTitle Console.WriteLine("\nOneNote document created successfully with page title.\nFile saved at " + dataDir); }
static void Main(string[] args) { Console.WriteLine("Programa de Gerar nota fiscal \n"); Console.WriteLine("Digite o nome do usuário: "); string nome = Console.ReadLine(); Console.WriteLine("Digite o endereço: "); string endereco = Console.ReadLine(); Console.WriteLine("Digite o valor da compra: "); double valor = double.Parse(Console.ReadLine()); Document doc = new Document(); Section secao = doc.AddSection(); ParagraphStyle estilo = new ParagraphStyle(doc); Paragraph titulo = secao.AddParagraph(); titulo.AppendText("Gerador de Nota Fiscal\n"); Paragraph VarNome = secao.AddParagraph(); VarNome.AppendText("Nome: ").CharacterFormat.Bold = true; TextRange boldNome = VarNome.AppendText(nome); boldNome.CharacterFormat.Bold = false; Paragraph VarEndereco = secao.AddParagraph(); VarEndereco.AppendText("Endereço: ").CharacterFormat.Bold = true; TextRange boldEnd = VarEndereco.AppendText(endereco); boldEnd.CharacterFormat.Bold = false; Paragraph VarValor = secao.AddParagraph(); VarValor.AppendText("Valor: ").CharacterFormat.Bold = true; TextRange boldVal = VarValor.AppendText($"{valor} reais"); boldVal.CharacterFormat.Bold = false; DateTime data = DateTime.Now; Paragraph VarData = secao.AddParagraph(); VarData.AppendText("Data: ").CharacterFormat.Bold = true; TextRange boldData = VarData.AppendText(data.ToString("dd/MM/yyyy")); boldData.CharacterFormat.Bold = false; doc.SaveToFile(@"saida\exemplo.docx", FileFormat.Docx); }
internal void method_6(ParagraphStyle A_0) { if (this.list_1 == null) { this.list_1 = new List <ParagraphStyle>(); } if (!this.list_1.Contains(A_0)) { this.list_1.Add(A_0); } }
private void CreateStyles() { // Define basic style TableStyle tStyleNormal = richEditControl1.Document.TableStyles.CreateNew(); tStyleNormal.LineSpacingType = ParagraphLineSpacing.Single; tStyleNormal.FontName = "Verdana"; tStyleNormal.Alignment = ParagraphAlignment.Left; tStyleNormal.Name = "MyTableGridNormal"; richEditControl1.Document.TableStyles.Add(tStyleNormal); // Define Grid Eight style TableStyle tStyleGrid8 = richEditControl1.Document.TableStyles.CreateNew(); tStyleGrid8.Parent = tStyleNormal; TableBorders borders = tStyleGrid8.TableBorders; borders.Bottom.LineColor = Color.DarkBlue; borders.Bottom.LineStyle = TableBorderLineStyle.Single; borders.Bottom.LineThickness = 0.75f; borders.Left.LineColor = Color.DarkBlue; borders.Left.LineStyle = TableBorderLineStyle.Single; borders.Left.LineThickness = 0.75f; borders.Right.LineColor = Color.DarkBlue; borders.Right.LineStyle = TableBorderLineStyle.Single; borders.Right.LineThickness = 0.75f; borders.Top.LineColor = Color.DarkBlue; borders.Top.LineStyle = TableBorderLineStyle.Single; borders.Top.LineThickness = 0.75f; borders.InsideVerticalBorder.LineColor = Color.DarkBlue; borders.InsideVerticalBorder.LineStyle = TableBorderLineStyle.Single; borders.InsideVerticalBorder.LineThickness = 0.75f; borders.InsideHorizontalBorder.LineColor = Color.DarkBlue; borders.InsideHorizontalBorder.LineStyle = TableBorderLineStyle.Single; borders.InsideHorizontalBorder.LineThickness = 0.75f; tStyleGrid8.CellBackgroundColor = Color.Transparent; tStyleGrid8.Name = "MyTableGridNumberEight"; richEditControl1.Document.TableStyles.Add(tStyleGrid8); // Define Headings paragraph style ParagraphStyle pStyleHeadings = richEditControl1.Document.ParagraphStyles.CreateNew(); pStyleHeadings.Bold = true; pStyleHeadings.ForeColor = Color.White; pStyleHeadings.Name = "My Headings Style"; richEditControl1.Document.ParagraphStyles.Add(pStyleHeadings); }
/// <summary> /// Create the Paragraph. /// </summary> /// <param name="styleName">The style name.</param> private void Init(string styleName) { if (styleName != "Standard" && styleName != "Table_20_Contents" && styleName != "Text_20_body") { Style = new ParagraphStyle(Document, styleName); Document.Styles.Add(Style); } InitStandards(); StyleName = styleName; }
static void Main(string[] args) { string nome, cpf; // Recebendo o nome para o Certificado System.Console.WriteLine("Informe seu nome completo:"); nome = Console.ReadLine(); // Recebendo CPF do usuário System.Console.WriteLine("Informe o seu CPF:"); cpf = Console.ReadLine(); // Limpando a tela Console.Clear(); Document doc = new Document(); Section section = doc.AddSection(); Paragraph title = section.AddParagraph(); title.AppendText("CERTIFICADO"); ParagraphStyle s1 = new ParagraphStyle(doc); s1.Name = "TitleTextColor"; s1.CharacterFormat.TextColor = Color.Blue; s1.CharacterFormat.FontName = "Arial"; // s1.CharacterFormat.FontName = "Algerian"; s1.CharacterFormat.FontSize = 30; title.Format.HorizontalAlignment = HorizontalAlignment.Justify; doc.Styles.Add(s1); title.ApplyStyle(s1.Name); Paragraph texto = section.AddParagraph(); texto.AppendText($@"Certificamos que {nome}, portador(a) do CPF '{cpf}', está apto a utilizar a Spire.Doc para a manipulação de arquivos WORD."); doc.Styles.Add(s1); texto.ApplyStyle(s1.Name); System.Console.WriteLine("Certificado obtido com sucesso!"); // doc.SaveToFile(@"C:\Users\33747821839\Desktop\Certificado.docx"); doc.SaveToFile("Certificado.docx"); }
private void button1_Click(object sender, EventArgs e) { //Create a new document Document doc = new Document(); //Add the first section Section section1 = doc.AddSection(); //Set text direction for all text in a section section1.TextDirection = TextDirection.RightToLeft; //Set Font Style and Size ParagraphStyle style = new ParagraphStyle(doc); style.Name = "FontStyle"; style.CharacterFormat.FontName = "Arial"; style.CharacterFormat.FontSize = 15; doc.Styles.Add(style); //Add two paragraphs and apply the font style Paragraph p = section1.AddParagraph(); p.AppendText("Only Spire.Doc, no Microsoft Office automation"); p.ApplyStyle(style.Name); p = section1.AddParagraph(); p.AppendText("Convert file documents with high quality"); p.ApplyStyle(style.Name); //Set text direction for a part of text //Add the second section Section section2 = doc.AddSection(); //Add a table Table table = section2.AddTable(); table.ResetCells(1, 1); TableCell cell = table.Rows[0].Cells[0]; table.Rows[0].Height = 150; table.Rows[0].Cells[0].Width = 10; //Set vertical text direction of table cell.CellFormat.TextDirection = TextDirection.RightToLeftRotated; cell.AddParagraph().AppendText("This is vertical style"); //Add a paragraph and set horizontal text direction p = section2.AddParagraph(); p.AppendText("This is horizontal style"); p.ApplyStyle(style.Name); //Save and launch document string output = "SetTextDirection.docx"; doc.SaveToFile(output, FileFormat.Docx); Viewer(output); }
private void button1_Click(object sender, EventArgs e) { //Create a Word document Document document = new Document(); //Get the first section Section section = document.AddSection(); //Add paragraph style ParagraphStyle style = new ParagraphStyle(document); style.CharacterFormat.FontSize = 20f; style.CharacterFormat.Bold = true; style.CharacterFormat.TextColor = Color.CadetBlue; document.Styles.Add(style); //Create a paragraph and append text Paragraph para = section.AddParagraph(); para.AppendText("Table"); //Apply style para.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center; para.ApplyStyle(style.Name); //Load data DataSet ds = new DataSet(); ds.ReadXml(@"..\..\..\..\..\..\Data\dataTable.xml"); //Get the first data table DataTable dataTable = ds.Tables[0]; //Add a table Table table = section.AddTable(true); //Set its width table.PreferredWidth = new PreferredWidth(WidthType.Percentage, 100); //Fill table with the data of datatable FillTableUsingDataTable(table, dataTable); //Set table style table.TableFormat.Paddings.All = 5; table.FirstRow.RowFormat.BackColor = Color.CadetBlue; //Save the Word file string output = "AddTableUsingDataTable_out.docx"; document.SaveToFile(output, FileFormat.Docx2013); //Launch the file FileViewer(output); }
private void AddHeaderLine(string text, List <Request> requests, int header, bool newline = true) { if (newline) { AddTextLine(text, requests); } else { AddText(text, requests); } Request request = new Request(); UpdateParagraphStyleRequest updateParagraphStyleRequest = new UpdateParagraphStyleRequest(); Google.Apis.Docs.v1.Data.Range range = new Google.Apis.Docs.v1.Data.Range(); if (newline) { range.StartIndex = CurrentIndex - 1 - text.Length; } else { range.StartIndex = CurrentIndex - text.Length; } range.EndIndex = CurrentIndex; ParagraphStyle paragraphStyle = new ParagraphStyle(); switch (header) { case 1: paragraphStyle.NamedStyleType = "HEADING_1"; break; case 2: paragraphStyle.NamedStyleType = "HEADING_2"; break; case 3: paragraphStyle.NamedStyleType = "HEADING_3"; break; default: throw new Exception("Invalid header"); } updateParagraphStyleRequest.Range = range; updateParagraphStyleRequest.ParagraphStyle = paragraphStyle; updateParagraphStyleRequest.Fields = "*"; request.UpdateParagraphStyle = updateParagraphStyleRequest; requests.Add(request); }
static void Main(string[] args) { // criando um novo documento com um novo documento. Document documento = new Document(); // Criando uma sessão dentro do documento. // a cada sessão criada uma nova página é adicionada. Section sessaoCapa = documento.AddSection(); // insere um título na primeira página Paragraph titulo = sessaoCapa.AddParagraph(); // insere um paragrafo na primeira pagina Paragraph paragrafo = sessaoCapa.AddParagraph(); // insiro na minha variável o título, o valor da string "título muito bonito". // Ou seja, no meu documento aparecerá "título muito bonito".... titulo.AppendText("Título muito bonito\n\n"); paragrafo.AppendText("\n\n Este é apenas um parágrafo aleatório"); // alinha horizontalmente o título titulo.Format.HorizontalAlignment = HorizontalAlignment.Center; paragrafo.Format.HorizontalAlignment = HorizontalAlignment.Left; // instanciando a classe dentro do documento ParagraphStyle estilo01 = new ParagraphStyle(documento); ParagraphStyle estilo02 = new ParagraphStyle(documento); // Define um nome da classe estilo 01. estilo01.Name = "Cor do título"; estilo02.Name = "Cor do parágrafo"; // Colore a propriedade text-color para azul escuro. estilo01.CharacterFormat.TextColor = Color.DarkBlue; estilo02.CharacterFormat.TextColor = Color.Red; // Transforma a propriedade bold em verdadeiro (true). estilo01.CharacterFormat.Bold = true; // Adicionar e colocar como usável no documento. documento.Styles.Add(estilo01); documento.Styles.Add(estilo02); // Aplicação das propriedades no título. titulo.ApplyStyle(estilo01.Name); paragrafo.ApplyStyle(estilo02.Name); documento.SaveToFile(@"Saida\arquivo_novo.Docx", FileFormat.Docx); }
/// <summary> /// Creates a paragraph. /// </summary> /// <param name="text">The text.</param> /// <param name="style">The style.</param> /// <returns>A paragraph.</returns> private System.Windows.Documents.Paragraph CreateParagraph(string text, ParagraphStyle style) { var run = new Run { Text = text }; if (style != null) { SetStyle(run, style); } return(new System.Windows.Documents.Paragraph(run)); }
int numcol = 7; // how much column in a split table public Excel2Word() { //Initialize an instance of Document class and load template from file this.doc = new Document(); doc.LoadFromFile(tempPath); // Set Font Style and Size style = new ParagraphStyle(doc); style.Name = "FontStyle"; style.CharacterFormat.FontName = "Times New Roman"; style.CharacterFormat.FontSize = 12; doc.Styles.Add(style); }
private void InsertContent(Section section) { ParagraphStyle list = new ParagraphStyle(section.Document); list.Name = "list"; list.CharacterFormat.FontName = "Arial"; list.CharacterFormat.FontSize = 11; list.ParagraphFormat.LineSpacing = 1.5F * 12F; list.ParagraphFormat.LineSpacingRule = LineSpacingRule.Multiple; section.Document.Styles.Add(list); Paragraph title = section.AddParagraph(); //next page title.AppendBreak(BreakType.PageBreak); TextRange text = title.AppendText("Field type list:"); title.ApplyStyle(list.Name); bool first = true; foreach (FieldType type in Enum.GetValues(typeof(FieldType))) { if (type == FieldType.FieldUnknown || type == FieldType.FieldNone || type == FieldType.FieldEmpty) { continue; } Paragraph paragraph = section.AddParagraph(); paragraph.AppendText(String.Format("{0} is supported in Spire.Doc", type)); if (first) { paragraph.ListFormat.ApplyNumberedStyle(); first = false; } else { paragraph.ListFormat.ContinueListNumbering(); } paragraph.ApplyStyle(list.Name); } }
private Formatting.ParagraphModel BuildParagraph(UString line, int textIndent, int paragraphIndent) { line = ApplyLexers(line); var exchangableText = _converter.Convert(line); var paragraphStyle = new ParagraphStyle { FontSize = _fontSizeByPoint, RubyFontSizeRatio = 0.5F, //TODO: 共通化が必要 Indent = new ManualParagraphIndentStyle(textIndent, paragraphIndent) }; var paragraph = _exchangableTextImporter.Import(exchangableText, paragraphStyle); return paragraph; }
private void AddForm(Section section) { ParagraphStyle descriptionStyle = new ParagraphStyle(section.Document); descriptionStyle.Name = "description"; descriptionStyle.CharacterFormat.FontSize = 12; descriptionStyle.CharacterFormat.FontName = "Arial"; descriptionStyle.CharacterFormat.TextColor = Color.FromArgb(0x00, 0x45, 0x8e); section.Document.Styles.Add(descriptionStyle); Paragraph p1 = section.AddParagraph(); String text1 = "So that we can verify your identity and find your information, " + "please provide us with the following information. " + "This information will be used to create your online account. " + "Your information is not public, shared in anyway, or displayed on this site"; p1.AppendText(text1); p1.ApplyStyle(descriptionStyle.Name); Paragraph p2 = section.AddParagraph(); String text2 = "You must provide a real email address to which we will send your password."; p2.AppendText(text2); p2.ApplyStyle(descriptionStyle.Name); p2.Format.AfterSpacing = 8; //field group label style ParagraphStyle formFieldGroupLabelStyle = new ParagraphStyle(section.Document); formFieldGroupLabelStyle.Name = "formFieldGroupLabel"; formFieldGroupLabelStyle.ApplyBaseStyle("description"); formFieldGroupLabelStyle.CharacterFormat.Bold = true; formFieldGroupLabelStyle.CharacterFormat.TextColor = Color.White; section.Document.Styles.Add(formFieldGroupLabelStyle); //field label style ParagraphStyle formFieldLabelStyle = new ParagraphStyle(section.Document); formFieldLabelStyle.Name = "formFieldLabel"; formFieldLabelStyle.ApplyBaseStyle("description"); formFieldLabelStyle.ParagraphFormat.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Right; section.Document.Styles.Add(formFieldLabelStyle); //add table Table table = section.AddTable(); //2 columns of per row table.DefaultColumnsNumber = 2; //default height of row is 20point table.DefaultRowHeight = 20; //load form config data using (Stream stream = File.OpenRead(@"..\..\..\..\..\..\Data\Form.xml")) { XPathDocument xpathDoc = new XPathDocument(stream); XPathNodeIterator sectionNodes = xpathDoc.CreateNavigator().Select("/form/section"); foreach (XPathNavigator node in sectionNodes) { //create a row for field group label, does not copy format TableRow row = table.AddRow(false); row.Cells[0].CellFormat.BackColor = Color.FromArgb(0x00, 0x71, 0xb6); row.Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle; //label of field group Paragraph cellParagraph = row.Cells[0].AddParagraph(); cellParagraph.AppendText(node.GetAttribute("name", "")); cellParagraph.ApplyStyle(formFieldGroupLabelStyle.Name); XPathNodeIterator fieldNodes = node.Select("field"); foreach (XPathNavigator fieldNode in fieldNodes) { //create a row for field, does not copy format TableRow fieldRow = table.AddRow(false); //field label fieldRow.Cells[0].CellFormat.VerticalAlignment = VerticalAlignment.Middle; Paragraph labelParagraph = fieldRow.Cells[0].AddParagraph(); labelParagraph.AppendText(fieldNode.GetAttribute("label", "")); labelParagraph.ApplyStyle(formFieldLabelStyle.Name); fieldRow.Cells[1].CellFormat.VerticalAlignment = VerticalAlignment.Middle; Paragraph fieldParagraph = fieldRow.Cells[1].AddParagraph(); String fieldId = fieldNode.GetAttribute("id", ""); switch (fieldNode.GetAttribute("type", "")) { case "text": //add text input field TextFormField field = fieldParagraph.AppendField(fieldId, FieldType.FieldFormTextInput) as TextFormField; //set default text field.DefaultText = ""; field.Text = ""; break; case "list": //add dropdown field DropDownFormField list = fieldParagraph.AppendField(fieldId, FieldType.FieldFormDropDown) as DropDownFormField; //add items into dropdown. XPathNodeIterator itemNodes = fieldNode.Select("item"); foreach (XPathNavigator itemNode in itemNodes) { list.DropDownItems.Add(itemNode.SelectSingleNode("text()").Value); } break; case "checkbox": //add checkbox field fieldParagraph.AppendField(fieldId, FieldType.FieldFormCheckBox); break; } } //merge field group row. 2 columns to 1 column table.ApplyHorizontalMerge(row.GetRowIndex(), 0, 1); } } }
public ActionResult CameraReadySubmission([Bind(Include = "PaperId,ConferenceId,UserId,PaperTitle,AuthorList,Co_Author,Affiliation,Presenter,Abstract,PaperDescription,AbstractFile,FullPaperFile,CameraReadyPaperFile,Keywords,TopicId,Prefix,AbstractSubmissionDate,FullPaperSubmissionDate,CameraReadyPaperSubmissionDate,AbstractSubmissionNotification,TotalNumberOfPages,Marks")] Paper paper) { try { Conference conference = db.Conferences.FirstOrDefault(u => u.ConferenceId == paper.ConferenceId); AbstractFileFormat fileformat = db.AbstractFileFormats.FirstOrDefault(u => u.ConferenceId == paper.ConferenceId); string filePath = FileUrl(paper.CameraReadyPaperFile, paper.Prefix); string wordFilePath = WordFileUrl(paper.CameraReadyPaperFile, paper.Prefix); if (fileformat != null) { Document doc = new Document(); doc.LoadFromFile(wordFilePath); int count = 0; int styleName = 0; foreach (Section section in doc.Sections) { foreach (Paragraph paragraph in section.Paragraphs) { paragraph.Format.LineSpacing = (float)fileformat.LineSpacing; string text = paragraph.Text.ToLower(); if (text.Length > 0 && text.Equals("abstract")) { count = 1; } if (text.Length > 1 && count == 1) { ParagraphStyle style = new ParagraphStyle(doc); paragraph.Format.HorizontalAlignment = HorizontalAlignment.Left; style.Name = styleName.ToString(); style.CharacterFormat.FontName = fileformat.FontName.Name; style.CharacterFormat.FontSize = fileformat.FontSize; doc.Styles.Add(style); paragraph.ApplyStyle(style.Name); } styleName++; } section.PageSetup.Margins.Top = (float)fileformat.Margin_Top; section.PageSetup.Margins.Bottom = (float)fileformat.Margin_Bottom; section.PageSetup.Margins.Left = (float)fileformat.Margin_Left; section.PageSetup.Margins.Right = (float)fileformat.Margin_Right; } doc.SaveToFile(wordFilePath); } paper.CameraReadyPaperSubmissionDate = DateTime.Now.ToString(); paper.CameraReadyPaperFile = filePath; if (ModelState.IsValid) { db.Entry(paper).State = EntityState.Modified; db.SaveChanges(); } return RedirectToAction("CameraReadyIndex", new { id = paper.ConferenceId }); } catch { ViewBag.ConferenceId = new SelectList(db.Conferences, "ConferenceId", "Username", paper.ConferenceId); ViewBag.TopicId = new SelectList(db.Topics, "TopicId", "Name", paper.TopicId); ViewBag.UserId = new SelectList(db.Users, "UserId", "Email", paper.UserId); return View(paper); } }
public ActionResult Create([Bind(Include= "PaperTitle,AuthorList,Affiliation,Presenter,AbstractFile,Abstract,Keywords,TopicId,TotalNumberOfPages")] Paper paper) { try { int userId = (int)Session["sessionLoggedInUserId"]; var submission = new Paper(); submission.PaperTitle = paper.PaperTitle; submission.AuthorList = paper.AuthorList; submission.Affiliation = paper.Affiliation; submission.Presenter = paper.Presenter; submission.Abstract = paper.Abstract; submission.Keywords = paper.Keywords; submission.TopicId = paper.TopicId; submission.UserId = userId; submission.AbstractTotalNumberOfPages = paper.AbstractTotalNumberOfPages; submission.ConferenceId = (int)Session["ConferenceId"]; Conference conference = db.Conferences.FirstOrDefault(u => u.ConferenceId == submission.ConferenceId); AbstractFileFormat fileformat = db.AbstractFileFormats.FirstOrDefault(u => u.ConferenceId == submission.ConferenceId); Paper papers = db.Papers.FirstOrDefault(u => u.ConferenceId == submission.ConferenceId); if(papers == null) { submission.Prefix = conference.PaperPrefix + 1; } else { Paper last = db.Papers.OrderByDescending(u => u.PaperId).FirstOrDefault(u => u.ConferenceId == submission.ConferenceId); string[] word = last.Prefix.Split('-'); int paperNumber = Int32.Parse(word[1].ToString()) + 1; submission.Prefix = conference.PaperPrefix + paperNumber; } string filePath = FileUrl(paper.AbstractFile, submission.Prefix); string wordFilePath = WordFileUrl(paper.AbstractFile, submission.Prefix); if (fileformat != null) { Document doc = new Document(); doc.LoadFromFile(wordFilePath); submission.AbstractTotalNumberOfPages = doc.PageCount; int count = 0; int styleName = 0; foreach (Section section in doc.Sections) { foreach (Paragraph paragraph in section.Paragraphs) { paragraph.Format.LineSpacing = (float)fileformat.LineSpacing; string text = paragraph.Text.ToLower(); if (text.Length > 0 && text.Equals("abstract")) { count = 1; } if (text.Length > 1 && count == 1) { ParagraphStyle style = new ParagraphStyle(doc); paragraph.Format.HorizontalAlignment = HorizontalAlignment.Left; style.Name = styleName.ToString(); style.CharacterFormat.FontName = fileformat.FontName.Name; style.CharacterFormat.FontSize = fileformat.FontSize; doc.Styles.Add(style); paragraph.ApplyStyle(style.Name); } styleName++; } section.PageSetup.Margins.Top = (float)fileformat.Margin_Top; section.PageSetup.Margins.Bottom = (float)fileformat.Margin_Bottom; section.PageSetup.Margins.Left = (float)fileformat.Margin_Left; section.PageSetup.Margins.Right = (float)fileformat.Margin_Right; } doc.SaveToFile(wordFilePath); } submission.AbstractSubmissionDate = DateTime.Now.ToString(); submission.AbstractFile = filePath; db.Papers.Add(submission); db.SaveChanges(); return RedirectToAction("Index", new { id = submission.UserId }); } catch { ViewBag.ConferenceId = new SelectList(db.Conferences, "ConferenceId", "Username"); ViewBag.TopicId = new SelectList(db.Topics, "TopicId", "Name"); ViewBag.UserId = new SelectList(db.Users, "UserId", "Email"); return View(paper); } }
private void InitializesStyles() { _title1 = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Heading1, _innerDocument); _title1.CharacterFormat.FontName = "Segoe UI"; _title1.CharacterFormat.FontColor = new Color(18, 97, 225); _title2 = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Heading2, _innerDocument); _title2.CharacterFormat.FontName = "Segoe UI"; _title2.CharacterFormat.FontColor = new Color(59, 59, 59); _innerDocument.Styles.Add(_title1); _innerDocument.Styles.Add(_title2); _cellHeader = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Normal, _innerDocument); _cellHeader.Name = "MyHeaderCells"; _cellHeader.CharacterFormat.Bold = true; _cellHeader.CharacterFormat.FontName = "Segoe UI"; _innerDocument.Styles.Add(_cellHeader); _cellContent = (ParagraphStyle)Style.CreateStyle(StyleTemplateType.Normal, _innerDocument); _cellContent.Name = "MyContentCells"; _cellContent.CharacterFormat.FontName = "Segoe UI"; _innerDocument.Styles.Add(_cellContent); _tcfHeader = new TableCellFormat(); _tcfHeader.Borders.SetBorders(MultipleBorderTypes.Bottom, BorderStyle.Single, new Color(165, 172, 181), 1); _tcfHeader.Borders.SetBorders(MultipleBorderTypes.Left | MultipleBorderTypes.Right, BorderStyle.None, Color.White, 0); _tcfHeader.BackgroundColor = new Color(245, 247, 249); _tcfContent = new TableCellFormat(); _tcfContent.Borders.SetBorders(MultipleBorderTypes.All, BorderStyle.None, new Color(255, 255, 255), 0); _numberList = new ListStyle("NumberWithDot", ListTemplateType.NumberWithDot); _innerDocument.Styles.Add(_numberList); }
private void InsertContent(Section section) { //title Paragraph paragraph = section.AddParagraph(); TextRange title = paragraph.AppendText("Summary of Science"); title.CharacterFormat.Bold = true; title.CharacterFormat.FontName = "Arial"; title.CharacterFormat.FontSize = 14; paragraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center; paragraph.Format.AfterSpacing = 10; //style ParagraphStyle style1 = new ParagraphStyle(section.Document); style1.Name = "style1"; style1.CharacterFormat.FontName = "Arial"; style1.CharacterFormat.FontSize = 9; style1.ParagraphFormat.LineSpacing = 1.5F * 12F; style1.ParagraphFormat.LineSpacingRule = LineSpacingRule.Multiple; section.Document.Styles.Add(style1); ParagraphStyle style2 = new ParagraphStyle(section.Document); style2.Name = "style2"; style2.ApplyBaseStyle(style1.Name); style2.CharacterFormat.Font = new Font("Arial", 10f); section.Document.Styles.Add(style2); paragraph = section.AddParagraph(); paragraph.AppendText("(All text and pictures are from "); String link = "http://en.wikipedia.org/wiki/Science"; paragraph.AppendHyperlink(link, "Wikipedia", HyperlinkType.WebLink); paragraph.AppendText(", the free encyclopedia)"); paragraph.ApplyStyle(style1.Name); Paragraph paragraph1 = section.AddParagraph(); String str1 = "Science (from the Latin scientia, meaning \"knowledge\") " + "is an enterprise that builds and organizes knowledge in the form " + "of testable explanations and predictions about the natural world. " + "An older meaning still in use today is that of Aristotle, " + "for whom scientific knowledge was a body of reliable knowledge " + "that can be logically and rationally explained " + "(see \"History and etymology\" section below)."; paragraph1.AppendText(str1); //Insert a picture in the right of the paragraph1 DocPicture picture = paragraph1.AppendPicture(Image.FromFile(@"..\..\..\..\..\..\Data\Wikipedia_Science.png")); picture.TextWrappingStyle = TextWrappingStyle.Square; picture.TextWrappingType = TextWrappingType.Left; picture.VerticalOrigin = VerticalOrigin.Paragraph; picture.VerticalPosition = 0; picture.HorizontalOrigin = HorizontalOrigin.Column; picture.HorizontalAlignment = ShapeHorizontalAlignment.Right; paragraph1.ApplyStyle(style2.Name); Paragraph paragraph2 = section.AddParagraph(); String str2 = "Since classical antiquity science as a type of knowledge was closely linked " + "to philosophy, the way of life dedicated to discovering such knowledge. " + "And into early modern times the two words, \"science\" and \"philosophy\", " + "were sometimes used interchangeably in the English language. " + "By the 17th century, \"natural philosophy\" " + "(which is today called \"natural science\") could be considered separately " + "from \"philosophy\" in general. But \"science\" continued to also be used " + "in a broad sense denoting reliable knowledge about a topic, in the same way " + "it is still used in modern terms such as library science or political science."; paragraph2.AppendText(str2); paragraph2.ApplyStyle(style2.Name); Paragraph paragraph3 = section.AddParagraph(); String str3 = "The more narrow sense of \"science\" that is common today developed as a part " + "of science became a distinct enterprise of defining \"laws of nature\", " + "based on early examples such as Kepler's laws, Galileo's laws, and Newton's " + "laws of motion. In this period it became more common to refer to natural " + "philosophy as \"natural science\". Over the course of the 19th century, the word " + "\"science\" became increasingly associated with the disciplined study of the " + "natural world including physics, chemistry, geology and biology. This sometimes " + "left the study of human thought and society in a linguistic limbo, which was " + "resolved by classifying these areas of academic study as social science. " + "Similarly, several other major areas of disciplined study and knowledge " + "exist today under the general rubric of \"science\", such as formal science " + "and applied science."; paragraph3.AppendText(str3); paragraph3.ApplyStyle(style2.Name); }