/// <summary> /// Shows how to set the different preferred width settings. /// </summary> private static void SetPreferredWidthSettings(string dataDir) { // ExStart:SetPreferredWidthSettings Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert a table row made up of three cells which have different preferred widths. Table table = builder.StartTable(); // Insert an absolute sized cell. builder.InsertCell(); builder.CellFormat.PreferredWidth = PreferredWidth.FromPoints(40); builder.CellFormat.Shading.BackgroundPatternColor = Color.LightYellow; builder.Writeln("Cell at 40 points width"); // Insert a relative (percent) sized cell. builder.InsertCell(); builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(20); builder.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue; builder.Writeln("Cell at 20% width"); // Insert a auto sized cell. builder.InsertCell(); builder.CellFormat.PreferredWidth = PreferredWidth.Auto; builder.CellFormat.Shading.BackgroundPatternColor = Color.LightGreen; builder.Writeln("Cell automatically sized. The size of this cell is calculated from the table preferred width."); builder.Writeln("In this case the cell will fill up the rest of the available space."); dataDir = dataDir + "Table.CellPreferredWidths_out.doc"; // Save the document to disk. doc.Save(dataDir); // ExEnd:SetPreferredWidthSettings Console.WriteLine("\nDifferent preferred width settings set successfully.\nFile saved at " + dataDir); }
public void Bidi() { //ExStart //ExFor:Font.Bidi //ExFor:Font.NameBi //ExFor:Font.SizeBi //ExFor:Font.ItalicBi //ExFor:Font.BoldBi //ExFor:Font.LocaleIdBi //ExSummary:Shows how to insert and format right-to-left text. DocumentBuilder builder = new DocumentBuilder(); // Signal to Microsoft Word that this run of text contains right-to-left text. builder.Font.Bidi = true; // Specify the font and font size to be used for the right-to-left text. builder.Font.NameBi = "Andalus"; builder.Font.SizeBi = 48; // Specify that the right-to-left text in this run is bold and italic. builder.Font.ItalicBi = true; builder.Font.BoldBi = true; // Specify the locale so Microsoft Word recognizes this text as Arabic - Saudi Arabia. // For the list of locale identifiers see http://www.microsoft.com/globaldev/reference/lcid-all.mspx builder.Font.LocaleIdBi = 1025; // Insert some Arabic text. builder.Writeln("مرحبًا"); builder.Document.Save(ExDir + "Font.Bidi Out.doc"); //ExEnd }
/// <summary> /// Adds an image to a page using the supplied paragraph. /// </summary> /// <param name="para">The paragraph to an an image to.</param> /// <param name="page">The page number the paragraph appears on.</param> public static void AddImageToPage(Paragraph para, int page) { Document doc = (Document)para.Document; DocumentBuilder builder = new DocumentBuilder(doc); builder.MoveTo(para); // Add a logo to the top left of the page. The image is placed infront of all other text. Shape shape = builder.InsertImage(gDataDir + "Aspose Logo.png", RelativeHorizontalPosition.Page, 60, RelativeVerticalPosition.Page, 60, -1, -1, WrapType.None); // Add a textbox next to the image which contains some text consisting of the page number. Shape textBox = new Shape(doc, ShapeType.TextBox); // We want a floating shape relative to the page. textBox.WrapType = WrapType.None; textBox.RelativeHorizontalPosition = RelativeHorizontalPosition.Page; textBox.RelativeVerticalPosition = RelativeVerticalPosition.Page; // Set the textbox position. textBox.Height = 30; textBox.Width = 200; textBox.Left = 150; textBox.Top = 80; // Add the textbox and set text. textBox.AppendChild(new Paragraph(doc)); builder.InsertNode(textBox); builder.MoveTo(textBox.FirstChild); builder.Writeln("This is a custom note for page " + page); }
static void Main(string[] args) { string FilePath = @"..\..\..\..\Sample Files\"; string File = FilePath + "Create and add a paragraph style - Aspose.docx"; // Open the new document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Set font formatting properties Aspose.Words.Font font = builder.Font; font.Bold = true; font.Color = System.Drawing.Color.Red; font.Italic = true; font.Name = "Arial"; font.Size = 24; font.Spacing = 5; font.Underline = Underline.Double; // Output formatted text builder.MoveToDocumentEnd(); builder.Writeln("I'm a very nice formatted string."); string txt = builder.CurrentParagraph.GetText(); doc.Save(File); }
/// <summary> /// Shows how to set a table to auto fit to 50% of the page width. /// </summary> private static void AutoFitToPageWidth(string dataDir) { // ExStart:AutoFitToPageWidth Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert a table with a width that takes up half the page width. Table table = builder.StartTable(); // Insert a few cells builder.InsertCell(); table.PreferredWidth = PreferredWidth.FromPercent(50); builder.Writeln("Cell #1"); builder.InsertCell(); builder.Writeln("Cell #2"); builder.InsertCell(); builder.Writeln("Cell #3"); dataDir = dataDir + "Table.PreferredWidth_out.doc"; // Save the document to disk. doc.Save(dataDir); // ExEnd:AutoFitToPageWidth Console.WriteLine("\nTable autofit successfully to 50% of the page width.\nFile saved at " + dataDir); }
/// <summary> /// Compare the two documents using Aspose.Words and save the result as a Word document /// </summary> /// <param name="document1">First document</param> /// <param name="document2">Second document</param> /// <param name="comparisonDocument">Comparison document</param> public void Compare(string document1, string document2, string comparisonDocument, ref int added, ref int deleted) { added = 0; deleted = 0; // Load both documents in Aspose.Words Document doc1 = new Document(document1); Document doc2 = new Document(document2); Document docComp = new Document(document1); DocumentBuilder builder = new DocumentBuilder(docComp); doc1.Compare(doc2, "a", DateTime.Now); foreach (Revision revision in doc1.Revisions) { switch (revision.RevisionType) { case RevisionType.Insertion: added++; break; case RevisionType.Deletion: deleted++; break; } Console.WriteLine(revision.RevisionType + ": " + revision.ParentNode); } Debug.WriteLine("Revisions: " + doc1.Revisions.Count); doc1.Save(comparisonDocument); }
public StudentBasicInfo(DocumentBuilder builder) { InitializeField(); _builder = builder; _builder.Document.MailMerge.MergeField += new Aspose.Words.Reporting.MergeFieldEventHandler(MailMerge_MergeField); }
public static void Run() { // ExStart:CreateChartUsingShape // The path to the documents directory. string dataDir = RunExamples.GetDataDir_WorkingWithCharts(); Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); Shape shape = builder.InsertChart(ChartType.Line, 432, 252); Chart chart = shape.Chart; // Determines whether the title shall be shown for this chart. Default is true. chart.Title.Show = true; // Setting chart Title. chart.Title.Text = "Sample Line Chart Title"; // Determines whether other chart elements shall be allowed to overlap title. chart.Title.Overlay = false; // Please note if null or empty value is specified as title text, auto generated title will be shown. // Determines how legend shall be shown for this chart. chart.Legend.Position = LegendPosition.Left; chart.Legend.Overlay = true; dataDir = dataDir + @"SimpleLineChart_out.docx"; doc.Save(dataDir); // ExEnd:CreateChartUsingShape Console.WriteLine("\nSimple line chart created successfully.\nFile saved at " + dataDir); }
/// <summary> /// Called for every merge field encountered in the document. /// We can either return some data to the mail merge engine or do something /// Else with the document. In this case we modify cell formatting. /// </summary> void IFieldMergingCallback.FieldMerging(FieldMergingArgs e) { if (mBuilder == null) mBuilder = new DocumentBuilder(e.Document); // This way we catch the beginning of a new row. if (e.FieldName.Equals("CompanyName")) { // Select the color depending on whether the row number is even or odd. Color rowColor; if (IsOdd(mRowIdx)) rowColor = Color.FromArgb(213, 227, 235); else rowColor = Color.FromArgb(242, 242, 242); // There is no way to set cell properties for the whole row at the moment, // So we have to iterate over all cells in the row. for (int colIdx = 0; colIdx < 4; colIdx++) { mBuilder.MoveToCell(0, mRowIdx, colIdx, 0); mBuilder.CellFormat.Shading.BackgroundPatternColor = rowColor; } mRowIdx++; } }
public static void Run() { // ExStart:InsertTableFromHtml // The path to the documents directory. string dataDir = RunExamples.GetDataDir_WorkingWithTables(); Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert the table from HTML. Note that AutoFitSettings does not apply to tables // Inserted from HTML. builder.InsertHtml("<table>" + "<tr>" + "<td>Row 1, Cell 1</td>" + "<td>Row 1, Cell 2</td>" + "</tr>" + "<tr>" + "<td>Row 2, Cell 2</td>" + "<td>Row 2, Cell 2</td>" + "</tr>" + "</table>"); dataDir = dataDir + "DocumentBuilder.InsertTableFromHtml_out.doc"; // Save the document to disk. doc.Save(dataDir); // ExEnd:InsertTableFromHtml Console.WriteLine("\nTable inserted successfully from html.\nFile saved at " + dataDir); }
public void ClearFormatting() { //ExStart //ExFor:DocumentBuilder.PageSetup //ExFor:DocumentBuilder.InsertBreak //ExFor:DocumentBuilder.Document //ExFor:PageSetup //ExFor:PageSetup.Orientation //ExFor:PageSetup.VerticalAlignment //ExFor:PageSetup.ClearFormatting //ExFor:Orientation //ExFor:PageVerticalAlignment //ExFor:BreakType //ExSummary:Shows how to insert sections using DocumentBuilder, specify page setup for a section and reset page setup to defaults. DocumentBuilder builder = new DocumentBuilder(); // Modify the first section in the document. builder.PageSetup.Orientation = Orientation.Landscape; builder.PageSetup.VerticalAlignment = PageVerticalAlignment.Center; builder.Writeln("Section 1, landscape oriented and text vertically centered."); // Start a new section and reset its formatting to defaults. builder.InsertBreak(BreakType.SectionBreakNewPage); builder.PageSetup.ClearFormatting(); builder.Writeln("Section 2, back to default Letter paper size, portrait orientation and top alignment."); builder.Document.Save(MyDir + "PageSetup.ClearFormatting Out.doc"); //ExEnd }
protected override void Context() { var builder = new DocumentBuilder(); var mapping = LuceneMapper.GetMappingForType(typeof (TestObject)); var item = new TestObject() { Id = Guid.NewGuid(), IgnoredProperty = "Property", LongId = 123456, ValidProperty = "Valid property", Text = "Abc def ghi ijkl mno pqr stuv"}; _document = builder.BuildDocumentForMapping(item, mapping); }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_WorkingWithFields(); Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert a few page breaks (just for testing) for (int i = 0; i < 5; i++) builder.InsertBreak(BreakType.PageBreak); // Move the DocumentBuilder cursor into the primary footer. builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary); // We want to insert a field like this: // { IF {PAGE} <> {NUMPAGES} "See Next Page" "Last Page" } Field field = builder.InsertField(@"IF "); builder.MoveTo(field.Separator); builder.InsertField("PAGE"); builder.Write(" <> "); builder.InsertField("NUMPAGES"); builder.Write(" \"See Next Page\" \"Last Page\" "); // Finally update the outer field to recalcaluate the final value. Doing this will automatically update // the inner fields at the same time. field.Update(); doc.Save(dataDir + "InsertNestedFields Out.docx"); Console.WriteLine("\nInserted nested fields in the document successfully.\nFile saved at " + dataDir + "InsertNestedFields Out.docx"); }
public void VerticalMerge() { //ExStart //ExFor:DocumentBuilder.InsertCell //ExFor:DocumentBuilder.EndRow //ExFor:CellMerge //ExFor:CellFormat.VerticalMerge //ExId:VerticalMerge //ExSummary:Creates a table with two columns with cells merged vertically in the first column. Aspose.Words.Document doc = new Aspose.Words.Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.InsertCell(); builder.CellFormat.VerticalMerge = CellMerge.First; builder.Write("Text in merged cells."); builder.InsertCell(); builder.CellFormat.VerticalMerge = CellMerge.None; builder.Write("Text in one cell"); builder.EndRow(); builder.InsertCell(); // This cell is vertically merged to the cell above and should be empty. builder.CellFormat.VerticalMerge = CellMerge.Previous; builder.InsertCell(); builder.CellFormat.VerticalMerge = CellMerge.None; builder.Write("Text in another cell"); builder.EndRow(); builder.EndTable(); //ExEnd }
public void DifferentHeaders() { //ExStart //ExFor:PageSetup.DifferentFirstPageHeaderFooter //ExFor:PageSetup.OddAndEvenPagesHeaderFooter //ExSummary:Creates headers and footers different for first, even and odd pages using DocumentBuilder. DocumentBuilder builder = new DocumentBuilder(); PageSetup ps = builder.PageSetup; ps.DifferentFirstPageHeaderFooter = true; ps.OddAndEvenPagesHeaderFooter = true; builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst); builder.Writeln("First page header."); builder.MoveToHeaderFooter(HeaderFooterType.HeaderEven); builder.Writeln("Even pages header."); builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary); builder.Writeln("Odd pages header."); // Move back to the main story of the first section. builder.MoveToSection(0); builder.Writeln("Text page 1."); builder.InsertBreak(BreakType.PageBreak); builder.Writeln("Text page 2."); builder.InsertBreak(BreakType.PageBreak); builder.Writeln("Text page 3."); builder.Document.Save(MyDir + @"\Artifacts\PageSetup.DifferentHeaders.doc"); //ExEnd }
/// <summary> /// This handler is called for every mail merge field found in the document, /// for every record found in the data source. /// </summary> void IFieldMergingCallback.FieldMerging(FieldMergingArgs e) { if (mBuilder == null) mBuilder = new DocumentBuilder(e.Document); // We decided that we want all boolean values to be output as check box form fields. if (e.FieldValue is bool) { // Move the "cursor" to the current merge field. mBuilder.MoveToMergeField(e.FieldName); // It is nice to give names to check boxes. Lets generate a name such as MyField21 or so. string checkBoxName = string.Format("{0}{1}", e.FieldName, e.RecordIndex); // Insert a check box. mBuilder.InsertCheckBox(checkBoxName, (bool)e.FieldValue, 0); // Nothing else to do for this field. return; } // Another example, we want the Subject field to come out as text input form field. if (e.FieldName == "Subject") { mBuilder.MoveToMergeField(e.FieldName); string textInputName = string.Format("{0}{1}", e.FieldName, e.RecordIndex); mBuilder.InsertTextInput(textInputName, TextFormFieldType.Regular, "", (string)e.FieldValue, 0); } }
public void HorizontalMerge() { //ExStart //ExFor:CellMerge //ExFor:CellFormat.HorizontalMerge //ExId:HorizontalMerge //ExSummary:Creates a table with two rows with cells in the first row horizontally merged. Aspose.Words.Document doc = new Aspose.Words.Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.InsertCell(); builder.CellFormat.HorizontalMerge = CellMerge.First; builder.Write("Text in merged cells."); builder.InsertCell(); // This cell is merged to the previous and should be empty. builder.CellFormat.HorizontalMerge = CellMerge.Previous; builder.EndRow(); builder.InsertCell(); builder.CellFormat.HorizontalMerge = CellMerge.None; builder.Write("Text in one cell."); builder.InsertCell(); builder.Write("Text in another cell."); builder.EndRow(); builder.EndTable(); //ExEnd }
static void Main(string[] args) { // Check for license and apply if exists string licenseFile = AppDomain.CurrentDomain.BaseDirectory + "Aspose.Words.lic"; if (File.Exists(licenseFile)) { // Apply Aspose.Words API License Aspose.Words.License license = new Aspose.Words.License(); // Place license file in Bin/Debug/ Folder license.SetLicense("Aspose.Words.lic"); } Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Write("Image Before ReSize"); //insert image from disk Shape shape = builder.InsertImage(@"../../data/aspose_Words-for-net.jpg"); // write text in document builder.Write("Image After ReSize "); //insert image from disk for resize shape = builder.InsertImage(@"../../data/aspose_Words-for-net.jpg"); // To change the shape size. ( ConvertUtil Provides helper functions to convert between various measurement units. like Converts inches to points.) shape.Width = ConvertUtil.InchToPoint(0.5); shape.Height = ConvertUtil.InchToPoint(0.5); // save new document builder.Document.Save("ImageReSize.doc"); }
/// <summary> /// Create new document with text /// </summary> internal static Document CreateDocumentFillWithDummyText() { Document doc = new Document(); //Remove the previous changes of the document doc.RemoveAllChildren(); //Set the document author doc.BuiltInDocumentProperties.Author = "Test Author"; DocumentBuilder builder = new DocumentBuilder(doc); //Insert new table with two rows and two cells InsertTable(doc); builder.Writeln("Hello World!"); // Continued on page 2 of the document content builder.InsertBreak(BreakType.PageBreak); //Insert TOC entries InsertToc(doc); return doc; }
public static void Run() { // ExStart:DocumentBuilderInsertParagraph // The path to the documents directory. string dataDir = RunExamples.GetDataDir_WorkingWithDocument(); // Initialize document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Specify font formatting Font font = builder.Font; font.Size = 16; font.Bold = true; font.Color = System.Drawing.Color.Blue; font.Name = "Arial"; font.Underline = Underline.Dash; // Specify paragraph formatting ParagraphFormat paragraphFormat = builder.ParagraphFormat; paragraphFormat.FirstLineIndent = 8; paragraphFormat.Alignment = ParagraphAlignment.Justify; paragraphFormat.KeepTogether = true; builder.Writeln("A whole paragraph."); dataDir = dataDir + "DocumentBuilderInsertParagraph_out.doc"; doc.Save(dataDir); // ExEnd:DocumentBuilderInsertParagraph Console.WriteLine("\nParagraph inserted successfully into the document using DocumentBuilder.\nFile saved at " + dataDir); }
public void PixelToPointEx() { //ExStart //ExFor:ConvertUtil.PixelToPoint(double) //ExFor:ConvertUtil.PixelToPoint(double, double) //ExSummary:Shows how to specify page properties in pixels with default and custom resolution. Aspose.Words.Document doc = new Aspose.Words.Document(); DocumentBuilder builder = new DocumentBuilder(doc); Aspose.Words.PageSetup pageSetupNoDpi = builder.PageSetup; pageSetupNoDpi.TopMargin = Aspose.Words.ConvertUtil.PixelToPoint(100.0); pageSetupNoDpi.BottomMargin = Aspose.Words.ConvertUtil.PixelToPoint(100.0); pageSetupNoDpi.LeftMargin = Aspose.Words.ConvertUtil.PixelToPoint(150.0); pageSetupNoDpi.RightMargin = Aspose.Words.ConvertUtil.PixelToPoint(150.0); pageSetupNoDpi.HeaderDistance = Aspose.Words.ConvertUtil.PixelToPoint(20.0); pageSetupNoDpi.FooterDistance = Aspose.Words.ConvertUtil.PixelToPoint(20.0); builder.Writeln("Hello world."); builder.Document.Save(MyDir + "PageSetup.PageMargins.DefaultResolution Out.doc"); double myDpi = 150.0; Aspose.Words.PageSetup pageSetupWithDpi = builder.PageSetup; pageSetupWithDpi.TopMargin = Aspose.Words.ConvertUtil.PixelToPoint(100.0, myDpi); pageSetupWithDpi.BottomMargin = Aspose.Words.ConvertUtil.PixelToPoint(100.0, myDpi); pageSetupWithDpi.LeftMargin = Aspose.Words.ConvertUtil.PixelToPoint(150.0, myDpi); pageSetupWithDpi.RightMargin = Aspose.Words.ConvertUtil.PixelToPoint(150.0, myDpi); pageSetupWithDpi.HeaderDistance = Aspose.Words.ConvertUtil.PixelToPoint(20.0, myDpi); pageSetupWithDpi.FooterDistance = Aspose.Words.ConvertUtil.PixelToPoint(20.0, myDpi); builder.Document.Save(MyDir + "PageSetup.PageMargins.CustomResolution Out.doc"); //ExEnd }
public static void Main() { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //ExStart //ExFor:DocumentBuilder.InsertField(string) //ExId:DocumentBuilderInsertNestedFields //ExSummary:Demonstrates how to insert fields nested within another field using DocumentBuilder. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert a few page breaks (just for testing) for (int i = 0; i < 5; i++) builder.InsertBreak(BreakType.PageBreak); // Move the DocumentBuilder cursor into the primary footer. builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary); // We want to insert a field like this: // { IF {PAGE} <> {NUMPAGES} "See Next Page" "Last Page" } Field field = builder.InsertField(@"IF "); builder.MoveTo(field.Separator); builder.InsertField("PAGE"); builder.Write(" <> "); builder.InsertField("NUMPAGES"); builder.Write(" \"See Next Page\" \"Last Page\" "); // Finally update the outer field to recalcaluate the final value. Doing this will automatically update // the inner fields at the same time. field.Update(); doc.Save(dataDir + "InsertNestedFields Out.docx"); //ExEnd }
public static void Run() { //ExStart:DigitallySignedPdf // The path to the documents directory. string dataDir = RunExamples.GetDataDir_LoadingAndSaving(); // Create a simple document from scratch. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Writeln("Test Signed PDF."); // Load the certificate from disk. // The other constructor overloads can be used to load certificates from different locations. X509Certificate2 cert = new X509Certificate2( dataDir + "signature.pfx", "signature"); // Pass the certificate and details to the save options class to sign with. PdfSaveOptions options = new PdfSaveOptions(); options.DigitalSignatureDetails = new PdfDigitalSignatureDetails( cert, "Test Signing", "Aspose Office", DateTime.Now); dataDir = dataDir + "Document.Signed_out_.pdf"; // Save the document as PDF with the digital signature set. doc.Save(dataDir, options); //ExEnd:DigitallySignedPdf Console.WriteLine("\nDigitally signed PDF file created successfully.\nFile saved at " + dataDir); }
public static void Run() { // ExStart:ChangeFieldUpdateCultureSource // The path to the documents directory. string dataDir = RunExamples.GetDataDir_WorkingWithFields(); // We will test this functionality creating a document with two fields with date formatting // ExStart:DocumentBuilderInsertField Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert content with German locale. builder.Font.LocaleId = 1031; builder.InsertField("MERGEFIELD Date1 \\@ \"dddd, d MMMM yyyy\""); builder.Write(" - "); builder.InsertField("MERGEFIELD Date2 \\@ \"dddd, d MMMM yyyy\""); // ExEnd:DocumentBuilderInsertField // Shows how to specify where the culture used for date formatting during field update and mail merge is chosen from. // Set the culture used during field update to the culture used by the field. doc.FieldOptions.FieldUpdateCultureSource = FieldUpdateCultureSource.FieldCode; doc.MailMerge.Execute(new string[] { "Date2" }, new object[] { new DateTime(2011, 1, 01) }); dataDir = dataDir + "Field.ChangeFieldUpdateCultureSource_out.doc"; doc.Save(dataDir); // ExEnd:ChangeFieldUpdateCultureSource Console.WriteLine("\nCulture changed successfully used in formatting fields during update.\nFile saved at " + dataDir); }
public void CreateFloatingPositionSize() { //ExStart //ExFor:ShapeBase.Left //ExFor:ShapeBase.Top //ExFor:ShapeBase.Width //ExFor:ShapeBase.Height //ExFor:DocumentBuilder.CurrentSection //ExFor:PageSetup.PageWidth //ExSummary:Shows how to insert a floating image and specify its position and size. // This creates a builder and also an empty document inside the builder. DocumentBuilder builder = new DocumentBuilder(); // By default, the image is inline. Shape shape = builder.InsertImage(ExDir + "Hammer.wmf"); // Make the image float, put it behind text and center on the page. shape.WrapType = WrapType.None; // Make position relative to the page. shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page; shape.RelativeVerticalPosition = RelativeVerticalPosition.Page; // Make the shape occupy a band 50 points high at the very top of the page. shape.Left = 0; shape.Top = 0; shape.Width = builder.CurrentSection.PageSetup.PageWidth; shape.Height = 50; builder.Document.Save(ExDir + "Image.CreateFloatingPositionSize Out.doc"); //ExEnd }
static void Main(string[] args) { Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // We call this method to start building the table. builder.StartTable(); builder.InsertCell(); builder.Write("Row 1, Cell 1 Content."); // Build the second cell builder.InsertCell(); builder.Write("Row 1, Cell 2 Content."); // Call the following method to end the row and start a new row. builder.EndRow(); // Build the first cell of the second row. builder.InsertCell(); builder.Write("Row 2, Cell 1 Content"); // Build the second cell. builder.InsertCell(); builder.Write("Row 2, Cell 2 Content."); builder.EndRow(); // Signal that we have finished building the table. builder.EndTable(); // Save the document to disk. doc.Save("DocumentBuilder.CreateSimpleTable Out.doc"); }
// ExEnd:PrintCellMergeType public static void VerticalMerge( string dataDir) { // ExStart:VerticalMerge Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.InsertCell(); builder.CellFormat.VerticalMerge = CellMerge.First; builder.Write("Text in merged cells."); builder.InsertCell(); builder.CellFormat.VerticalMerge = CellMerge.None; builder.Write("Text in one cell"); builder.EndRow(); builder.InsertCell(); // This cell is vertically merged to the cell above and should be empty. builder.CellFormat.VerticalMerge = CellMerge.Previous; builder.InsertCell(); builder.CellFormat.VerticalMerge = CellMerge.None; builder.Write("Text in another cell"); builder.EndRow(); builder.EndTable(); dataDir = dataDir + "Table.VerticalMerge_out.doc"; // Save the document to disk. doc.Save(dataDir); // ExEnd:VerticalMerge Console.WriteLine("\nTable created successfully with two columns with cells merged vertically in the first column.\nFile saved at " + dataDir); }
public void CreateFloatingPageCenter() { //ExStart //ExFor:DocumentBuilder.InsertImage(string) //ExFor:Shape //ExFor:ShapeBase //ExFor:ShapeBase.WrapType //ExFor:ShapeBase.BehindText //ExFor:ShapeBase.RelativeHorizontalPosition //ExFor:ShapeBase.RelativeVerticalPosition //ExFor:ShapeBase.HorizontalAlignment //ExFor:ShapeBase.VerticalAlignment //ExFor:WrapType //ExFor:RelativeHorizontalPosition //ExFor:RelativeVerticalPosition //ExFor:HorizontalAlignment //ExFor:VerticalAlignment //ExSummary:Shows how to insert a floating image in the middle of a page. // This creates a builder and also an empty document inside the builder. DocumentBuilder builder = new DocumentBuilder(); // By default, the image is inline. Shape shape = builder.InsertImage(ExDir + "Aspose.Words.gif"); // Make the image float, put it behind text and center on the page. shape.WrapType = WrapType.None; shape.BehindText = true; shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page; shape.HorizontalAlignment = HorizontalAlignment.Center; shape.RelativeVerticalPosition = RelativeVerticalPosition.Page; shape.VerticalAlignment = VerticalAlignment.Center; builder.Document.Save(ExDir + "Image.CreateFloatingPageCenter Out.doc"); //ExEnd }
public static void HeadersAndFooters(string dataDir) { // ExStart:DocumentBuilderHeadersAndFooters // Create a blank document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Specify that we want headers and footers different for first, even and odd pages. builder.PageSetup.DifferentFirstPageHeaderFooter = true; builder.PageSetup.OddAndEvenPagesHeaderFooter = true; // Create the headers. builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst); builder.Write("Header First"); builder.MoveToHeaderFooter(HeaderFooterType.HeaderEven); builder.Write("Header Even"); builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary); builder.Write("Header Odd"); // Create three pages in the document. builder.MoveToSection(0); builder.Writeln("Page1"); builder.InsertBreak(BreakType.PageBreak); builder.Writeln("Page2"); builder.InsertBreak(BreakType.PageBreak); builder.Writeln("Page3"); dataDir = dataDir + "DocumentBuilder.HeadersAndFooters_out.doc"; doc.Save(dataDir); // ExEnd:DocumentBuilderHeadersAndFooters Console.WriteLine("\nHeaders and footers created successfully using DocumentBuilder.\nFile saved at " + dataDir); }
override public void Execute() { DocumentPackage superDuperPackage = PackageBuilder.NewPackageNamed("QRCodeExample: " + DateTime.Now) .DescribedAs("This is a package created using the e-SignLive SDK") .WithEmailMessage("This message should be delivered to all signers") .WithSigner(SignerBuilder.NewSignerWithEmail(email1) .WithCustomId("Client1") .WithFirstName("John") .WithLastName("Smith") .WithTitle("Managing Director") .WithCompany("Acme Inc.")) .WithDocument(DocumentBuilder.NewDocumentNamed("First Document") .WithId(DOCUMENT_ID) .FromStream(fileStream1, DocumentType.PDF) .WithSignature(SignatureBuilder.SignatureFor(email1) .OnPage(0) .AtPosition(100, 100)) .WithQRCode(FieldBuilder.QRCode() .WithId(qrCodeId1) .OnPage(0) .AtPosition(400, 100))) .Build(); packageId = eslClient.CreatePackage(superDuperPackage); Field qrCode2 = FieldBuilder.QRCode() .OnPage(0) .AtPosition(500, 100) .Build(); // Add a second QR code to document qrCodeId2 = eslClient.QrCodeService.AddQRCode(packageId, DOCUMENT_ID, qrCode2); // Get the added QR codes addedQRCode1 = eslClient.QrCodeService.GetQRCode(packageId, DOCUMENT_ID, qrCodeId1); addedQRCode2 = eslClient.QrCodeService.GetQRCode(packageId, DOCUMENT_ID, qrCodeId2); // Modify the first QR code Field modifiedQRCode = FieldBuilder.QRCode() .WithId(qrCodeId1) .OnPage(0) .AtPosition(400, 500) .Build(); eslClient.QrCodeService.ModifyQRCode(packageId, DOCUMENT_ID, modifiedQRCode); modifiedQRCodeList = eslClient.GetPackage(packageId).Documents[DOCUMENT_NAME].QRCodes; // Delete the second QR code eslClient.QrCodeService.DeleteQRCode(packageId, DOCUMENT_ID, qrCodeId2); deletedQRCodeList = eslClient.GetPackage(packageId).Documents[DOCUMENT_NAME].QRCodes; // Update all the QR codes in the document with the provided list of fields Field updatedQRCode1 = FieldBuilder.QRCode() .WithId(qrCodeId1) .OnPage(0) .AtPosition(200, 600) .Build(); Field updatedQRCode2 = FieldBuilder.QRCode() .WithId(qrCodeId2) .OnPage(0) .AtPosition(300, 600) .Build(); IList <Silanis.ESL.SDK.Field> qrCodeList = new List <Silanis.ESL.SDK.Field>(); qrCodeList.Add(updatedQRCode1); qrCodeList.Add(updatedQRCode2); eslClient.QrCodeService.UpdateQRCodes(packageId, DOCUMENT_ID, qrCodeList); updatedQRCodeList = eslClient.GetPackage(packageId).Documents[DOCUMENT_NAME].QRCodes; }
/// <summary> /// txt转换成word /// </summary> /// <param name="folder"></param> public void TxtToWord(string folder) { string contentPath = string.Empty, imgPath = string.Empty; contentPath = folder + @"\内容.txt"; if (!Directory.Exists(folder)) { return; } DirectoryInfo dir = new DirectoryInfo(folder); string wordTitle = dir.Name; try { List <string> imgNameList = myUtils.GetImgs(folder); string contentStr = File.ReadAllText(contentPath); string newcontent = string.Empty; //newcontent = UseApi(contentStr); //if (string.IsNullOrEmpty(newcontent)) newcontent = contentStr; string[] contentArr = myUtils.SplitByStr(newcontent, "\r\n"); Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); Font font = builder.Font; if (wordTitle.Length > 30 || wordTitle.Length < 6) { font.Color = Color.Red; } builder.Writeln(wordTitle); font.Color = Color.Black; foreach (var content in contentArr) { try { string resStr = CheckIsImage(imgNameList, content); if (string.IsNullOrEmpty(resStr)) { builder.Writeln(content); } else { imgPath = folder + @"\" + resStr; builder.InsertImage(imgPath); builder.Write("\r\n"); } } catch (Exception ex) { myUtils.WriteLog("插入文字或者图片时出错" + ex); } } string savePath = targetPath + @"\" + wordTitle + ".docx"; doc.Save(savePath); ChangeWordColor(savePath); this.dataGridView1.Invoke(new Action(() => { this.dataGridView1.Rows.Add(wordTitle, "成功"); this.dataGridView1.Rows[dataGridView1.Rows.Count - 2].Cells["Column2"].Style.ForeColor = Color.Blue; this.dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.Rows[dataGridView1.Rows.Count - 2].Index; })); currentfolderCount++; this.label9.Invoke(new Action(() => { this.label9.Text = currentfolderCount + "/" + folderTotalCount; })); } catch (Exception ex) { this.dataGridView1.Invoke(new Action(() => { this.dataGridView1.Rows.Add(wordTitle, "失败"); this.dataGridView1.Rows[dataGridView1.Rows.Count - 2].Cells["Column2"].Style.ForeColor = Color.Red; this.dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.Rows[dataGridView1.Rows.Count - 2].Index; })); myUtils.WriteLog(ex); if (!Directory.Exists(errorFolder1)) { Directory.CreateDirectory(errorFolder1); } dir.MoveTo(errorFolder1 + dir.Name); } }
private bool assertXml(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc, XPathCompiler catalogXpc, bool debug) { if (IsException()) { return(false); } else { string normalizeAtt = assertion.GetAttributeValue(new QName("normalize-space")); bool normalize = normalizeAtt != null && ("true".Equals(normalizeAtt.Trim()) || "1".Equals(normalizeAtt.Trim())); string ignoreAtt = assertion.GetAttributeValue(new QName("ignore-prefixes")); bool ignorePrefixes = ignoreAtt != null && ("true".Equals(ignoreAtt.Trim()) || "1".Equals(ignoreAtt.Trim())); string xmlVersion = assertion.GetAttributeValue(new QName("xml-version")); bool xml11 = "1.1".Equals(xmlVersion); string comparand = catalogXpc.Evaluate("if (@file) then unparsed-text(resolve-uri(@file, base-uri(.))) else string(.)", assertion).ToString(); if (comparand.StartsWith("<?xml")) { int index = comparand.IndexOf("?>"); comparand = comparand.Substring(index + 2); } comparand = comparand.Trim(); comparand = comparand.Replace("\r\n", "\n"); if (normalize) { comparand = JWhitespace.collapseWhitespace(comparand).ToString(); } if (comparand.Equals(Serialize(assertXpc.Processor, result))) { return(true); } DocumentBuilder builder = assertXpc.Processor.NewDocumentBuilder(); if (xml11) { assertXpc.Processor.SetProperty(JFeatureKeys.XML_VERSION, "1.1"); } StringReader reader = new StringReader((xml11 ? "<?xml version='1.1'?>" : "") + "<z>" + comparand + "</z>"); builder.BaseUri = assertion.BaseUri; XdmNode expected = builder.Build(reader); int flag = 0; flag |= JDeepEqual.INCLUDE_COMMENTS; flag |= JDeepEqual.INCLUDE_PROCESSING_INSTRUCTIONS; flag |= JDeepEqual.EXCLUDE_VARIETY; if (!ignorePrefixes) { flag |= JDeepEqual.INCLUDE_NAMESPACES; flag |= JDeepEqual.INCLUDE_PREFIXES; } flag |= JDeepEqual.COMPARE_STRING_VALUES; if (debug) { flag |= JDeepEqual.WARNING_IF_FALSE; } try { JSequenceIterator iter0; if (result == null) { System.Console.WriteLine("Result value is null"); return(false); } XdmValue value = result.value; if (value == null) { System.Console.WriteLine("Result value is null (perhaps serialized?)"); return(false); } if (value.Count == 1 && value.Simplify is XdmNode && ((XdmNode)value.Simplify).NodeKind == System.Xml.XmlNodeType.Document) { iter0 = ((XdmNode)value.Simplify).Implementation.iterateAxis(JAxisInfo.CHILD); } else { iter0 = value.Unwrap().iterate(); } JGroundedValue val0 = net.sf.saxon.value.SequenceExtent.makeSequenceExtent(iter0); JSequenceIterator iter1 = expected.Implementation.iterateAxis(JAxisInfo.CHILD).next().iterateAxis(JAxisInfo.CHILD); JGroundedValue val1 = net.sf.saxon.value.SequenceExtent.makeSequenceExtent(iter1); bool success = JDeepEqual.deepEqual( iter0, iter1, new JGenericAtomicComparer(JCodepointCollator.getInstance(), null), assertXpc.Processor.Implementation.getConversionContext(), flag); // if necessary try again ignoring whitespace nodes if (!success) { iter0 = val0.iterate(); iter1 = val1.iterate(); // deep-equals with the EXCLUDE_WHITESPACE flag doesn't ignore top-level whitespace, so we // need to filter that out ourselves iter0 = new JItemMappingIterator(iter0, new RemoveWhitespace()); iter1 = new JItemMappingIterator(iter1, new RemoveWhitespace()); success = JDeepEqual.deepEqual( iter0, iter1, new JGenericAtomicComparer(JCodepointCollator.getInstance(), null), assertXpc.Processor.Implementation.getConversionContext(), flag | JDeepEqual.EXCLUDE_WHITESPACE_TEXT_NODES); if (success) { comment = "OK after ignoring whitespace text"; } } if (!success) { System.Console.WriteLine("assert-xml comparison failed"); if (debug) { System.Console.WriteLine("assert-xml comparison failed"); System.Console.WriteLine("Reference results:"); System.Console.WriteLine(expected.ToString()); System.Console.WriteLine("Actual results:"); //System.Console.WriteLine(result.serialization); System.Console.WriteLine(value.ToString()); } } return(success); } catch (DynamicError e) { Console.WriteLine(e.StackTrace); return(false); } } }
override public void Execute() { this.fileStream1 = File.OpenRead(new FileInfo(Directory.GetCurrentDirectory() + "/SampleDocuments/document-with-fields.pdf").FullName); this.fileStream2 = File.OpenRead(new FileInfo(Directory.GetCurrentDirectory() + "/SampleDocuments/document-with-fields.pdf").FullName); DocumentPackage template = PackageBuilder.NewPackageNamed("Template " + PackageName) .WithEmailMessage(PACKAGE_EMAIL_MESSAGE) .WithSigner(SignerBuilder.NewSignerPlaceholder(new Placeholder(PLACEHOLDER_ID))) .WithDocument(DocumentBuilder.NewDocumentNamed(DOCUMENT_NAME) .FromStream(fileStream1, DocumentType.PDF) .WithId(DOCUMENT_ID) .WithSignature(SignatureBuilder.SignatureFor(new Placeholder(PLACEHOLDER_ID)) .OnPage(0) .AtPosition(100, 100)) .Build()) .Build(); template.Id = eslClient.CreateTemplate(template); DocumentPackage newPackage = PackageBuilder.NewPackageNamed(PackageName) .DescribedAs(PACKAGE_DESCRIPTION) .WithEmailMessage(PACKAGE_EMAIL_MESSAGE2) .WithSigner(SignerBuilder.NewSignerWithEmail(email1) .WithFirstName(PACKAGE_SIGNER2_FIRST) .WithLastName(PACKAGE_SIGNER2_LAST) .WithTitle(PACKAGE_SIGNER2_TITLE) .WithCompany(PACKAGE_SIGNER2_COMPANY) .WithCustomId(PLACEHOLDER_ID)) .WithSettings(DocumentPackageSettingsBuilder.NewDocumentPackageSettings() .WithInPerson() .Build()) .Build(); packageId = eslClient.CreatePackageFromTemplate(template.Id, newPackage); retrievedPackage = eslClient.GetPackage(packageId); // You are not able to update a document itself. // So if you want to update your document itself, you need to change the document. // For this, you should create the same document with existing one, and exchange it with existing one. // Creating the same document with existing one. Document documentToChange = DocumentBuilder.NewDocumentNamed(DOCUMENT_NAME) .FromStream(fileStream2, DocumentType.PDF) .WithId(DOCUMENT_ID) .WithSignature(SignatureBuilder.SignatureFor(new Placeholder(PLACEHOLDER_ID)) .OnPage(0) .AtPosition(100, 100)) .Build(); List <Field> injectedFields = new List <Field>(); injectedFields.Add(FieldBuilder.TextField().WithName("AGENT_SIG_1").WithValue("AGENT_SIG_1").Build()); // Adding injectedFields to new document documentToChange.AddFields(injectedFields); Document retrievedDocument = retrievedPackage.GetDocument(DOCUMENT_NAME); // Deleting the existing document. eslClient.PackageService.DeleteDocument(packageId, retrievedDocument.Id); // Uploading newly created document. eslClient.UploadDocument(documentToChange.FileName, documentToChange.Content, documentToChange, packageId); }
public void InsertInlineStoryNodes() { //ExStart //ExFor:Comment.StoryType //ExFor:Footnote.StoryType //ExFor:InlineStory.EnsureMinimum //ExFor:InlineStory.Font //ExFor:InlineStory.LastParagraph //ExFor:InlineStory.ParentParagraph //ExFor:InlineStory.StoryType //ExFor:InlineStory.Tables //ExSummary:Shows how to insert InlineStory nodes. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); Footnote footnote = builder.InsertFootnote(FootnoteType.Footnote, null); // Table nodes have an "EnsureMinimum()" method that makes sure the table has at least one cell Table table = new Table(doc); table.EnsureMinimum(); // We can place a table inside a footnote, which will make it appear at the footer of the referencing page Assert.That(footnote.Tables, Is.Empty); footnote.AppendChild(table); Assert.AreEqual(1, footnote.Tables.Count); Assert.AreEqual(NodeType.Table, footnote.LastChild.NodeType); // An InlineStory has an "EnsureMinimum()" method as well, but in this case, // it makes sure the last child of the node is a paragraph, in order for us to be able to click and write text easily in Microsoft Word footnote.EnsureMinimum(); Assert.AreEqual(NodeType.Paragraph, footnote.LastChild.NodeType); // Edit the appearance of the anchor, which is the small superscript number in the main text that points to the footnote footnote.Font.Name = "Arial"; footnote.Font.Color = Color.Green; // All inline story nodes have their own respective story types Assert.AreEqual(StoryType.Footnotes, footnote.StoryType); // A comment is another type of inline story Comment comment = (Comment)builder.CurrentParagraph.AppendChild(new Comment(doc, "John Doe", "J. D.", DateTime.Now)); // The parent paragraph of an inline story node will be the one from the main document body Assert.AreEqual(doc.FirstSection.Body.FirstParagraph, comment.ParentParagraph); // However, the last paragraph is the one from the comment text contents, which will be outside the main document body in a speech bubble // A comment won't have any child nodes by default, so we can apply the EnsureMinimum() method to place a paragraph here as well Assert.Null(comment.LastParagraph); comment.EnsureMinimum(); Assert.AreEqual(NodeType.Paragraph, comment.LastChild.NodeType); // Once we have a paragraph, we can move the builder do it and write our comment builder.MoveTo(comment.LastParagraph); builder.Write("My comment."); Assert.AreEqual(StoryType.Comments, comment.StoryType); doc.Save(ArtifactsDir + "InlineStory.InsertInlineStoryNodes.docx"); //ExEnd doc = new Document(ArtifactsDir + "InlineStory.InsertInlineStoryNodes.docx"); footnote = (Footnote)doc.GetChild(NodeType.Footnote, 0, true); TestUtil.VerifyFootnote(FootnoteType.Footnote, true, string.Empty, string.Empty, (Footnote)doc.GetChild(NodeType.Footnote, 0, true)); Assert.AreEqual("Arial", footnote.Font.Name); Assert.AreEqual(Color.Green.ToArgb(), footnote.Font.Color.ToArgb()); comment = (Comment)doc.GetChild(NodeType.Comment, 0, true); Assert.AreEqual("My comment.", comment.ToString(SaveFormat.Text).Trim()); }
public void CreateAndUseListStyle() { //ExStart //ExFor:StyleCollection.Add(StyleType,String) //ExFor:Style.List //ExFor:StyleType //ExFor:List.IsListStyleDefinition //ExFor:List.IsListStyleReference //ExFor:List.IsMultiLevel //ExFor:List.Style //ExFor:ListLevelCollection //ExFor:ListLevelCollection.Count //ExFor:ListLevelCollection.Item //ExFor:ListCollection.Add(Style) //ExSummary:Shows how to create a list style and use it in a document. Document doc = new Document(); // Create a new list style. // List formatting associated with this list style is default numbered. Style listStyle = doc.Styles.Add(StyleType.List, "MyListStyle"); // This list defines the formatting of the list style. // Note this list can not be used directly to apply formatting to paragraphs (see below). List list1 = listStyle.List; // Check some basic rules about the list that defines a list style. Console.WriteLine("IsListStyleDefinition: " + list1.IsListStyleDefinition); Console.WriteLine("IsListStyleReference: " + list1.IsListStyleReference); Console.WriteLine("IsMultiLevel: " + list1.IsMultiLevel); Console.WriteLine("List style has been set: " + (listStyle == list1.Style)); // Modify formatting of the list style to our liking. for (int i = 0; i < list1.ListLevels.Count; i++) { ListLevel level = list1.ListLevels[i]; level.Font.Name = "Verdana"; level.Font.Color = Color.Blue; level.Font.Bold = true; } // Add some text to our document and use the list style. DocumentBuilder builder = new DocumentBuilder(doc); builder.Writeln("Using list style first time:"); // This creates a list based on the list style. List list2 = doc.Lists.Add(listStyle); // Check some basic rules about the list that references a list style. Console.WriteLine("IsListStyleDefinition: " + list2.IsListStyleDefinition); Console.WriteLine("IsListStyleReference: " + list2.IsListStyleReference); Console.WriteLine("List Style has been set: " + (listStyle == list2.Style)); // Apply the list that references the list style. builder.ListFormat.List = list2; builder.Writeln("Item 1"); builder.Writeln("Item 2"); builder.ListFormat.RemoveNumbers(); builder.Writeln("Using list style second time:"); // Create and apply another list based on the list style. List list3 = doc.Lists.Add(listStyle); builder.ListFormat.List = list3; builder.Writeln("Item 1"); builder.Writeln("Item 2"); builder.ListFormat.RemoveNumbers(); builder.Document.Save(MyDir + @"\Artifacts\Lists.CreateAndUseListStyle.doc"); //ExEnd // Verify properties of list 1 Assert.IsTrue(list1.IsListStyleDefinition); Assert.IsFalse(list1.IsListStyleReference); Assert.IsTrue(list1.IsMultiLevel); Assert.AreEqual(listStyle, list1.Style); // Verify properties of list 2 Assert.IsFalse(list2.IsListStyleDefinition); Assert.IsTrue(list2.IsListStyleReference); Assert.AreEqual(listStyle, list2.Style); }
public void ApplyDefaultBulletsAndNumbers() { //ExStart //ExFor:DocumentBuilder.ListFormat //ExFor:ListFormat.ApplyNumberDefault //ExFor:ListFormat.ApplyBulletDefault //ExFor:ListFormat.ListIndent //ExFor:ListFormat.ListOutdent //ExFor:ListFormat.RemoveNumbers //ExSummary:Shows how to apply default bulleted or numbered list formatting to paragraphs when using DocumentBuilder. DocumentBuilder builder = new DocumentBuilder(); builder.Writeln("Aspose.Words allows:"); builder.Writeln(); // Start a numbered list with default formatting. builder.ListFormat.ApplyNumberDefault(); builder.Writeln("Opening documents from different formats:"); // Go to second list level, add more text. builder.ListFormat.ListIndent(); builder.Writeln("DOC"); builder.Writeln("PDF"); builder.Writeln("HTML"); // Outdent to the first list level. builder.ListFormat.ListOutdent(); builder.Writeln("Processing documents"); builder.Writeln("Saving documents in different formats:"); // Indent the list level again. builder.ListFormat.ListIndent(); builder.Writeln("DOC"); builder.Writeln("PDF"); builder.Writeln("HTML"); builder.Writeln("MHTML"); builder.Writeln("Plain text"); // Outdent the list level again. builder.ListFormat.ListOutdent(); builder.Writeln("Doing many other things!"); // End the numbered list. builder.ListFormat.RemoveNumbers(); builder.Writeln(); builder.Writeln("Aspose.Words main advantages are:"); builder.Writeln(); // Start a bulleted list with default formatting. builder.ListFormat.ApplyBulletDefault(); builder.Writeln("Great performance"); builder.Writeln("High reliability"); builder.Writeln("Quality code and working"); builder.Writeln("Wide variety of features"); builder.Writeln("Easy to understand API"); // End the bulleted list. builder.ListFormat.RemoveNumbers(); builder.Document.Save(MyDir + @"\Artifacts\Lists.ApplyDefaultBulletsAndNumbers.doc"); //ExEnd }
public void CreateCustomList() { //ExStart //ExFor:List //ExFor:List.ListLevels //ExFor:ListLevelCollection //ExFor:ListLevelCollection.Item //ExFor:ListLevel //ExFor:ListLevel.Alignment //ExFor:ListLevel.Font //ExFor:ListLevel.NumberStyle //ExFor:ListLevel.StartAt //ExFor:ListLevel.TrailingCharacter //ExFor:ListLevelAlignment //ExFor:NumberStyle //ExFor:ListTrailingCharacter //ExFor:ListLevel.NumberFormat //ExFor:ListLevel.NumberPosition //ExFor:ListLevel.TextPosition //ExFor:ListLevel.TabPosition //ExSummary:Shows how to apply custom list formatting to paragraphs when using DocumentBuilder. Document doc = new Document(); // Create a list based on one of the Microsoft Word list templates. List list = doc.Lists.Add(ListTemplate.NumberDefault); // Completely customize one list level. ListLevel level1 = list.ListLevels[0]; level1.Font.Color = Color.Red; level1.Font.Size = 24; level1.NumberStyle = NumberStyle.OrdinalText; level1.StartAt = 21; level1.NumberFormat = "\x0000"; level1.NumberPosition = -36; level1.TextPosition = 144; level1.TabPosition = 144; // Completely customize yet another list level. ListLevel level2 = list.ListLevels[1]; level2.Alignment = ListLevelAlignment.Right; level2.NumberStyle = NumberStyle.Bullet; level2.Font.Name = "Wingdings"; level2.Font.Color = Color.Blue; level2.Font.Size = 24; level2.NumberFormat = "\xf0af"; // A bullet that looks like some sort of a star. level2.TrailingCharacter = ListTrailingCharacter.Space; level2.NumberPosition = 144; // Now add some text that uses the list that we created. // It does not matter when to customize the list - before or after adding the paragraphs. DocumentBuilder builder = new DocumentBuilder(doc); builder.ListFormat.List = list; builder.Writeln("The quick brown fox..."); builder.Writeln("The quick brown fox..."); builder.ListFormat.ListIndent(); builder.Writeln("jumped over the lazy dog."); builder.Writeln("jumped over the lazy dog."); builder.ListFormat.ListOutdent(); builder.Writeln("The quick brown fox..."); builder.ListFormat.RemoveNumbers(); builder.Document.Save(MyDir + @"\Artifacts\Lists.CreateCustomList.doc"); //ExEnd }
public void DealWord() { foreach (var wordPath in wordPathList) { Document doc = new Document(wordPath); DocumentBuilder builder = new DocumentBuilder(doc); NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true); FileInfo fileInfo = new FileInfo(wordPath); string wordTitle = fileInfo.Name.Replace(fileInfo.Extension, ""); try { string oldFolder = folderPath + @"\" + wordTitle; List <string> imgList = myUtils.GetImgs(oldFolder, 2); WordToHtm(wordPath, oldFolder, wordTitle, imgList); int index = 0; foreach (Aspose.Words.Drawing.Shape item in shapes) { try { if (item.HasImage) { //Document imgDoc = item.Document as Document; //builder = new DocumentBuilder(imgDoc); //将光标移动到指定节点,移动到这个节点才可以把内容插入到这里 builder.MoveTo(item); builder.Writeln(imgList[index]); item.Remove(); index++; } } catch (Exception ee) { myUtils.WriteLog("删除word中的图片出错:" + ee); } } doc.Save(wordPath); WordToTxt(wordPath, oldFolder, wordTitle); this.dataGridView2.Invoke(new Action(() => { this.dataGridView2.Rows.Add(wordTitle, "成功"); this.dataGridView2.Rows[dataGridView2.Rows.Count - 2].Cells["Column4"].Style.ForeColor = Color.Blue; this.dataGridView2.FirstDisplayedScrollingRowIndex = dataGridView2.Rows[dataGridView2.Rows.Count - 2].Index; })); currentWordCount++; this.label10.Invoke(new Action(() => { this.label10.Text = currentWordCount + "/" + wordTotalCount; })); } catch (Exception ex) { this.dataGridView2.Invoke(new Action(() => { this.dataGridView2.Rows.Add(wordTitle, "失败"); this.dataGridView2.Rows[dataGridView2.Rows.Count - 2].Cells["Column4"].Style.ForeColor = Color.Blue; this.dataGridView2.FirstDisplayedScrollingRowIndex = dataGridView2.Rows[dataGridView2.Rows.Count - 2].Index; })); myUtils.WriteLog(ex); if (!Directory.Exists(errorFolder2)) { Directory.CreateDirectory(errorFolder2); } if (File.Exists(errorFolder2 + fileInfo.Name)) { fileInfo.MoveTo(errorFolder2 + fileInfo.Name); } } } MessageBox.Show("htm已经转换完毕!", "Article Conversion Tool"); }
public void InsertControlChars() { //ExStart //ExFor:ControlChar.Cell //ExFor:ControlChar.ColumnBreak //ExFor:ControlChar.CrLf //ExFor:ControlChar.Lf //ExFor:ControlChar.LineBreak //ExFor:ControlChar.LineFeed //ExFor:ControlChar.NonBreakingSpace //ExFor:ControlChar.PageBreak //ExFor:ControlChar.ParagraphBreak //ExFor:ControlChar.SectionBreak //ExFor:ControlChar.CellChar //ExFor:ControlChar.ColumnBreakChar //ExFor:ControlChar.DefaultTextInputChar //ExFor:ControlChar.FieldEndChar //ExFor:ControlChar.FieldStartChar //ExFor:ControlChar.FieldSeparatorChar //ExFor:ControlChar.LineBreakChar //ExFor:ControlChar.LineFeedChar //ExFor:ControlChar.NonBreakingHyphenChar //ExFor:ControlChar.NonBreakingSpaceChar //ExFor:ControlChar.OptionalHyphenChar //ExFor:ControlChar.PageBreakChar //ExFor:ControlChar.ParagraphBreakChar //ExFor:ControlChar.SectionBreakChar //ExFor:ControlChar.SpaceChar //ExSummary:Shows how to add various control characters to a document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Add a regular space. builder.Write("Before space." + ControlChar.SpaceChar + "After space."); // Add an NBSP, which is a non-breaking space. // Unlike the regular space, this space can't have an automatic line break at its position. builder.Write("Before space." + ControlChar.NonBreakingSpace + "After space."); // Add a tab character. builder.Write("Before tab." + ControlChar.Tab + "After tab."); // Add a line break. builder.Write("Before line break." + ControlChar.LineBreak + "After line break."); // Add a new line and starts a new paragraph. Assert.AreEqual(1, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count); builder.Write("Before line feed." + ControlChar.LineFeed + "After line feed."); Assert.AreEqual(2, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count); // The line feed character has two versions. Assert.AreEqual(ControlChar.LineFeed, ControlChar.Lf); // Carriage returns and line feeds can be represented together by one character. Assert.AreEqual(ControlChar.CrLf, ControlChar.Cr + ControlChar.Lf); // Add a paragraph break, which will start a new paragraph. builder.Write("Before paragraph break." + ControlChar.ParagraphBreak + "After paragraph break."); Assert.AreEqual(3, doc.FirstSection.Body.GetChildNodes(NodeType.Paragraph, true).Count); // Add a section break. This does not make a new section or paragraph. Assert.AreEqual(1, doc.Sections.Count); builder.Write("Before section break." + ControlChar.SectionBreak + "After section break."); Assert.AreEqual(1, doc.Sections.Count); // Add a page break. builder.Write("Before page break." + ControlChar.PageBreak + "After page break."); // A page break is the same value as a section break. Assert.AreEqual(ControlChar.PageBreak, ControlChar.SectionBreak); // Insert a new section, and then set its column count to two. doc.AppendChild(new Section(doc)); builder.MoveToSection(1); builder.CurrentSection.PageSetup.TextColumns.SetCount(2); // We can use a control character to mark the point where text moves to the next column. builder.Write("Text at end of column 1." + ControlChar.ColumnBreak + "Text at beginning of column 2."); doc.Save(ArtifactsDir + "ControlChar.InsertControlChars.docx"); // There are char and string counterparts for most characters. Assert.AreEqual(Convert.ToChar(ControlChar.Cell), ControlChar.CellChar); Assert.AreEqual(Convert.ToChar(ControlChar.NonBreakingSpace), ControlChar.NonBreakingSpaceChar); Assert.AreEqual(Convert.ToChar(ControlChar.Tab), ControlChar.TabChar); Assert.AreEqual(Convert.ToChar(ControlChar.LineBreak), ControlChar.LineBreakChar); Assert.AreEqual(Convert.ToChar(ControlChar.LineFeed), ControlChar.LineFeedChar); Assert.AreEqual(Convert.ToChar(ControlChar.ParagraphBreak), ControlChar.ParagraphBreakChar); Assert.AreEqual(Convert.ToChar(ControlChar.SectionBreak), ControlChar.SectionBreakChar); Assert.AreEqual(Convert.ToChar(ControlChar.PageBreak), ControlChar.SectionBreakChar); Assert.AreEqual(Convert.ToChar(ControlChar.ColumnBreak), ControlChar.ColumnBreakChar); //ExEnd }
override public void Execute() { // Create a package with one document and one signature with two fields DocumentPackage superDuperPackage = PackageBuilder.NewPackageNamed(LAYOUT_PACKAGE_NAME) .DescribedAs(LAYOUT_PACKAGE_DESCRIPTION) .WithSigner(SignerBuilder.NewSignerWithEmail(email1) .WithCustomId("Client1") .WithFirstName("John") .WithLastName("Smith") .WithTitle("Managing Director") .WithCompany("Acme Inc.")) .WithDocument(DocumentBuilder.NewDocumentNamed(LAYOUT_DOCUMENT_NAME) .WithId("documentId") .WithDescription("Layout document description") .FromStream(fileStream1, DocumentType.PDF) .WithSignature(SignatureBuilder.SignatureFor(email1) .OnPage(0) .AtPosition(100, 100) .WithField(FieldBuilder.SignerTitle() .WithName(FIELD_1_NAME) .OnPage(0) .AtPosition(100, 200)) .WithField(FieldBuilder.SignerCompany() .WithName(FIELD_2_NAME) .OnPage(0) .AtPosition(100, 300)))) .Build(); PackageId packageId1 = eslClient.CreatePackage(superDuperPackage); superDuperPackage.Id = packageId1; // Create layout from package layoutId = eslClient.LayoutService.CreateLayout(superDuperPackage); // Get a list of layouts layouts = eslClient.LayoutService.GetLayouts(Direction.ASCENDING, new PageRequest(1, 100)); // Create a new package to apply document layout to DocumentPackage packageFromLayout = PackageBuilder.NewPackageNamed("DocumentLayoutExample " + DateTime.Now) .DescribedAs("This is a package created using the e-SignLive SDK") .WithEmailMessage("This message should be delivered to all signers") .WithSigner(SignerBuilder.NewSignerWithEmail(email1) .WithCustomId("Client1") .WithFirstName("John") .WithLastName("Smith") .WithTitle("Managing Director") .WithCompany("Acme Inc.")) .WithDocument(DocumentBuilder.NewDocumentNamed(APPLY_LAYOUT_DOCUMENT_NAME) .WithId(APPLY_LAYOUT_DOCUMENT_ID) .WithDescription(APPLY_LAYOUT_DOCUMENT_DESCRIPTION) .FromStream(fileStream2, DocumentType.PDF)) .Build(); packageId = eslClient.CreatePackage(packageFromLayout); // Apply the layout to document in package eslClient.LayoutService.ApplyLayout(packageId, APPLY_LAYOUT_DOCUMENT_ID, layoutId); packageWithLayout = eslClient.GetPackage(packageId); }
private void button2_Click_1(object sender, EventArgs e) { if (textBox1.Text == "") { MessageBox.Show("请选择接收人!"); return; } if (zhonglei == "日报") { if (dataGridViewX1.Rows.Count > 11) { MessageBox.Show("常规工作内容不得超过十条,请酌情压缩!"); return; } if (dataGridViewX2.Rows.Count > 6) { MessageBox.Show("重点工作内容不得超过五条,请酌情压缩!"); return; } if (dataGridViewX3.Rows.Count > 6) { MessageBox.Show("思考不得超过五条,请酌情压缩!"); return; } if (dataGridViewX4.Rows.Count > 6) { MessageBox.Show("下阶段规划不得超过五条,请酌情压缩!"); return; } if (dataGridViewX3.Rows.Count == 1) { MessageBox.Show("必须写思考内容!"); return; } if (dataGridViewX4.Rows.Count == 1) { MessageBox.Show("必须写下阶段规划内容!"); return; } if (dataGridViewX3.Rows.Count > 1 && dataGridViewX3.Rows.Count < 7) { if (dataGridViewX3.Rows[0].Cells["开展情况3"].Value == null) { MessageBox.Show("第一条思考内容必须大于十个字符!"); return; } string a = dataGridViewX3.Rows[0].Cells["开展情况3"].Value.ToString(); int changdu = a.Length; if (changdu < 10) { MessageBox.Show("第一条思考内容必须大于十个字符!"); return; } if (a.Trim() == "") { MessageBox.Show("不准投机取巧,必须输入十个真实文字!"); return; } } if (dataGridViewX4.Rows.Count > 1 && dataGridViewX4.Rows.Count < 7) { if (dataGridViewX4.Rows[0].Cells["规划情况"].Value == null) { MessageBox.Show("第一条下阶段内容必须大于十个字符!"); return; } string a = dataGridViewX4.Rows[0].Cells["规划情况"].Value.ToString(); int changdu = a.Length; if (changdu < 10) { MessageBox.Show("第一条下阶段内容必须大于十个字符!"); return; } if (a.Trim() == "") { MessageBox.Show("不准投机取巧,必须输入十个真实文字!"); return; } } if (MessageBox.Show("确认提交吗?", "软件提示", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes) { DataTable dt1 = new DataTable(); dt1.Columns.Add("日期", typeof(string)); //工程名称 dt1.Columns.Add("汇报人", typeof(string)); dt1.Columns.Add("工作类别1", typeof(string)); dt1.Columns.Add("工作类别2", typeof(string)); dt1.Columns.Add("工作类别3", typeof(string)); dt1.Columns.Add("工作类别4", typeof(string)); dt1.Columns.Add("工作类别5", typeof(string)); dt1.Columns.Add("工作类别6", typeof(string)); dt1.Columns.Add("工作类别7", typeof(string)); dt1.Columns.Add("工作类别8", typeof(string)); dt1.Columns.Add("工作类别9", typeof(string)); dt1.Columns.Add("工作类别10", typeof(string)); dt1.Columns.Add("工作内容1", typeof(string)); dt1.Columns.Add("工作内容2", typeof(string)); dt1.Columns.Add("工作内容3", typeof(string)); dt1.Columns.Add("工作内容4", typeof(string)); dt1.Columns.Add("工作内容5", typeof(string)); dt1.Columns.Add("工作内容6", typeof(string)); dt1.Columns.Add("工作内容7", typeof(string)); dt1.Columns.Add("工作内容8", typeof(string)); dt1.Columns.Add("工作内容9", typeof(string)); dt1.Columns.Add("工作内容10", typeof(string)); dt1.Columns.Add("完成情况1", typeof(string)); dt1.Columns.Add("完成情况2", typeof(string)); dt1.Columns.Add("完成情况3", typeof(string)); dt1.Columns.Add("完成情况4", typeof(string)); dt1.Columns.Add("完成情况5", typeof(string)); dt1.Columns.Add("完成情况6", typeof(string)); dt1.Columns.Add("完成情况7", typeof(string)); dt1.Columns.Add("完成情况8", typeof(string)); dt1.Columns.Add("完成情况9", typeof(string)); dt1.Columns.Add("完成情况10", typeof(string)); dt1.Columns.Add("思考1", typeof(string)); dt1.Columns.Add("思考2", typeof(string)); dt1.Columns.Add("思考3", typeof(string)); dt1.Columns.Add("思考4", typeof(string)); dt1.Columns.Add("思考5", typeof(string)); dt1.Columns.Add("下阶段1", typeof(string)); dt1.Columns.Add("下阶段2", typeof(string)); dt1.Columns.Add("下阶段3", typeof(string)); dt1.Columns.Add("下阶段4", typeof(string)); dt1.Columns.Add("下阶段5", typeof(string)); dt1.Columns.Add("日1", typeof(string)); dt1.Columns.Add("日2", typeof(string)); dt1.Columns.Add("日3", typeof(string)); dt1.Columns.Add("日4", typeof(string)); dt1.Columns.Add("日5", typeof(string)); dt1.Columns.Add("存在问题1", typeof(string)); dt1.Columns.Add("存在问题2", typeof(string)); dt1.Columns.Add("存在问题3", typeof(string)); dt1.Columns.Add("存在问题4", typeof(string)); dt1.Columns.Add("存在问题5", typeof(string)); DataRow dr1 = dt1.NewRow(); dr1["日期"] = DateTime.Now.ToString("yyyy-MM-dd"); dr1["汇报人"] = yonghu; for (int i = 0; i < dataGridViewX1.Rows.Count - 1; i++) { if (dataGridViewX1.Rows[i].Cells["工作类别"].Value == null) { dr1["工作类别" + (i + 1)] = ""; } if (dataGridViewX1.Rows[i].Cells["工作类别"].Value != null) { dr1["工作类别" + (i + 1)] = dataGridViewX1.Rows[i].Cells["工作类别"].Value.ToString(); } if (dataGridViewX1.Rows[i].Cells["工作内容"].Value == null) { dr1["工作内容" + (i + 1)] = ""; } if (dataGridViewX1.Rows[i].Cells["工作内容"].Value != null) { dr1["工作内容" + (i + 1)] = dataGridViewX1.Rows[i].Cells["工作内容"].Value.ToString(); } if (dataGridViewX1.Rows[i].Cells["完成情况"].Value == null) { dr1["完成情况" + (i + 1)] = ""; } if (dataGridViewX1.Rows[i].Cells["完成情况"].Value != null) { dr1["完成情况" + (i + 1)] = dataGridViewX1.Rows[i].Cells["完成情况"].Value.ToString(); } } for (int i = 0; i < dataGridViewX2.Rows.Count - 1; i++) { if (dataGridViewX2.Rows[i].Cells["开展情况2"].Value == null) { dr1["日" + (i + 1)] = ""; } if (dataGridViewX2.Rows[i].Cells["开展情况2"].Value != null) { dr1["日" + (i + 1)] = dataGridViewX2.Rows[i].Cells["开展情况2"].Value.ToString(); } if (dataGridViewX2.Rows[i].Cells["存在问题"].Value == null) { dr1["存在问题" + (i + 1)] = ""; } if (dataGridViewX2.Rows[i].Cells["存在问题"].Value != null) { dr1["存在问题" + (i + 1)] = dataGridViewX2.Rows[i].Cells["存在问题"].Value.ToString(); } } for (int i = 0; i < dataGridViewX3.Rows.Count - 1; i++) { if (dataGridViewX3.Rows[i].Cells["开展情况3"].Value == null) { dr1["思考" + (i + 1)] = ""; } if (dataGridViewX3.Rows[i].Cells["开展情况3"].Value != null) { dr1["思考" + (i + 1)] = dataGridViewX3.Rows[i].Cells["开展情况3"].Value.ToString(); } } for (int i = 0; i < dataGridViewX4.Rows.Count - 1; i++) { if (dataGridViewX4.Rows[i].Cells["规划情况"].Value == null) { dr1["下阶段" + (i + 1)] = ""; } if (dataGridViewX4.Rows[i].Cells["规划情况"].Value != null) { dr1["下阶段" + (i + 1)] = dataGridViewX4.Rows[i].Cells["规划情况"].Value.ToString(); } } dt1.Rows.Add(dr1); string tempFile = Application.StartupPath + "\\日报模板.doc"; Document doc = new Document(tempFile); DocumentBuilder builder = new DocumentBuilder(doc); NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true); Dictionary <string, string> dic = new Dictionary <string, string>(); DataRow dr = dt1.Rows[0]; dic.Add("日期", dr["日期"].ToString()); dic.Add("汇报人", dr["汇报人"].ToString()); dic.Add("工作类别1", dr["工作类别1"].ToString()); dic.Add("工作类别2", dr["工作类别2"].ToString()); dic.Add("工作类别3", dr["工作类别3"].ToString()); dic.Add("工作类别4", dr["工作类别4"].ToString()); dic.Add("工作类别5", dr["工作类别5"].ToString()); dic.Add("工作类别6", dr["工作类别6"].ToString()); dic.Add("工作类别7", dr["工作类别7"].ToString()); dic.Add("工作类别8", dr["工作类别8"].ToString()); dic.Add("工作类别9", dr["工作类别9"].ToString()); dic.Add("工作类别10", dr["工作类别10"].ToString()); dic.Add("工作内容1", dr["工作内容1"].ToString()); dic.Add("工作内容2", dr["工作内容2"].ToString()); dic.Add("工作内容3", dr["工作内容3"].ToString()); dic.Add("工作内容4", dr["工作内容4"].ToString()); dic.Add("工作内容5", dr["工作内容5"].ToString()); dic.Add("工作内容6", dr["工作内容6"].ToString()); dic.Add("工作内容7", dr["工作内容7"].ToString()); dic.Add("工作内容8", dr["工作内容8"].ToString()); dic.Add("工作内容9", dr["工作内容9"].ToString()); dic.Add("工作内容10", dr["工作内容10"].ToString()); dic.Add("完成情况1", dr["完成情况1"].ToString()); dic.Add("完成情况2", dr["完成情况2"].ToString()); dic.Add("完成情况3", dr["完成情况3"].ToString()); dic.Add("完成情况4", dr["完成情况4"].ToString()); dic.Add("完成情况5", dr["完成情况5"].ToString()); dic.Add("完成情况6", dr["完成情况6"].ToString()); dic.Add("完成情况7", dr["完成情况7"].ToString()); dic.Add("完成情况8", dr["完成情况8"].ToString()); dic.Add("完成情况9", dr["完成情况9"].ToString()); dic.Add("完成情况10", dr["完成情况10"].ToString()); dic.Add("思考1", dr["思考1"].ToString()); dic.Add("思考2", dr["思考2"].ToString()); dic.Add("思考3", dr["思考3"].ToString()); dic.Add("思考4", dr["思考4"].ToString()); dic.Add("思考5", dr["思考5"].ToString()); dic.Add("下阶段1", dr["下阶段1"].ToString()); dic.Add("下阶段2", dr["下阶段2"].ToString()); dic.Add("下阶段3", dr["下阶段3"].ToString()); dic.Add("下阶段4", dr["下阶段4"].ToString()); dic.Add("下阶段5", dr["下阶段5"].ToString()); dic.Add("日1", dr["日1"].ToString()); dic.Add("日2", dr["日2"].ToString()); dic.Add("日3", dr["日3"].ToString()); dic.Add("日4", dr["日4"].ToString()); dic.Add("日5", dr["日5"].ToString()); dic.Add("存在问题1", dr["存在问题1"].ToString()); dic.Add("存在问题2", dr["存在问题2"].ToString()); dic.Add("存在问题3", dr["存在问题3"].ToString()); dic.Add("存在问题4", dr["存在问题4"].ToString()); dic.Add("存在问题5", dr["存在问题5"].ToString()); foreach (var key in dic.Keys) { builder.MoveToBookmark(key); builder.Write(dic[key]); } string mingcheng = yonghu + DateTime.Now.ToString("yyyy-MM-dd") + "日报" + ".doc"; FileInfo info1 = new FileInfo(Application.StartupPath + "\\" + mingcheng); string fileName11 = info1.Name.ToString(); string floderName = fileName11.Substring(0, fileName11.Length - 4).ToString(); doc.Save(info1.DirectoryName + "\\" + fileName11); FileInfo info = new FileInfo(info1.DirectoryName + "\\" + fileName11); //获得文件大小 long fileSize12 = info.Length; //提取文件名,三步走 int index = info.FullName.LastIndexOf("."); string fileName12 = info.FullName.Remove(index); fileName12 = fileName12.Substring(fileName12.LastIndexOf(@"\") + 1); //txtMingcheng.Text = fileName; //获得文件扩展名 string fileType12 = info.Extension.Replace(".", ""); //把文件转换成二进制流 byte[] files12 = new byte[Convert.ToInt32(fileSize12)]; FileStream file = new FileStream(info1.DirectoryName + "\\" + fileName11, FileMode.Open, FileAccess.Read); BinaryReader read = new BinaryReader(file); read.Read(files12, 0, Convert.ToInt32(fileSize12)); DateTime shijian1 = DateTime.Now; string sql1 = "INSERT INTO tb_wenjian(文件,提交时间,员工姓名) VALUES (@pic,'" + shijian1 + "','" + yonghu + "')"; SQLhelp.ExecuteNonquery(sql1, CommandType.Text, files12); string riqi = DateTime.Now.ToString("yyyy-MM-dd"); string biaoti = DateTime.Now.ToString("yyyy-MM-dd") + yonghu + "日报"; string sql = "update tb_wenjian set 报告类型='日报',提交时间='" + shijian1 + "',员工备注='" + txtBeizhu.Text + "',文件类型='doc',部门='" + bumen + "',日期='" + riqi + "' ,报告标题='" + biaoti + "',接收人='" + textBox1.Text + "',编号='" + bianhao + "' where 员工姓名='" + yonghu + "' and 提交时间='" + shijian1 + "' "; int g = SQLhelp.innn(sql, CommandType.Text); if (txtName.Text != "") { string sql2 = "update tb_wenjian set 附件=@pic where 员工姓名='" + yonghu + "' and 提交时间='" + shijian1 + "' "; SQLhelp.ExecuteNonquery(sql2, CommandType.Text, files2); string sql3 = "update tb_wenjian set 附件名称='" + fileName2 + "',附件类型='" + fileType2 + "' where 员工姓名='" + yonghu + "' and 提交时间='" + shijian1 + "' "; SQLhelp.ExecuteScalar(sql3, CommandType.Text); } MessageBox.Show("提交成功!"); this.DialogResult = DialogResult.OK; this.Close(); } } }
public void SharedElements() { //ExStart //ExFor:Border.Equals(Object) //ExFor:Border.Equals(Border) //ExFor:Border.GetHashCode //ExFor:BorderCollection.Count //ExFor:BorderCollection.Equals(BorderCollection) //ExFor:BorderCollection.Item(Int32) //ExSummary:Shows how border collections can share elements. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.Writeln("Paragraph 1."); builder.Write("Paragraph 2."); // Since we used the same border configuration while creating // these paragraphs, their border collections share the same elements. BorderCollection firstParagraphBorders = doc.FirstSection.Body.FirstParagraph.ParagraphFormat.Borders; BorderCollection secondParagraphBorders = builder.CurrentParagraph.ParagraphFormat.Borders; Assert.AreEqual(6, firstParagraphBorders.Count); //ExSkip for (int i = 0; i < firstParagraphBorders.Count; i++) { Assert.IsTrue(firstParagraphBorders[i].Equals(secondParagraphBorders[i])); Assert.AreEqual(firstParagraphBorders[i].GetHashCode(), secondParagraphBorders[i].GetHashCode()); Assert.False(firstParagraphBorders[i].IsVisible); } foreach (Border border in secondParagraphBorders) { border.LineStyle = LineStyle.DotDash; } // After changing the line style of the borders in just the second paragraph, // the border collections no longer share the same elements. for (int i = 0; i < firstParagraphBorders.Count; i++) { Assert.IsFalse(firstParagraphBorders[i].Equals(secondParagraphBorders[i])); Assert.AreNotEqual(firstParagraphBorders[i].GetHashCode(), secondParagraphBorders[i].GetHashCode()); // Changing the appearance of an empty border makes it visible. Assert.True(secondParagraphBorders[i].IsVisible); } doc.Save(ArtifactsDir + "Border.SharedElements.docx"); //ExEnd doc = new Document(ArtifactsDir + "Border.SharedElements.docx"); ParagraphCollection paragraphs = doc.FirstSection.Body.Paragraphs; foreach (Border testBorder in paragraphs[0].ParagraphFormat.Borders) { Assert.AreEqual(LineStyle.None, testBorder.LineStyle); } foreach (Border testBorder in paragraphs[1].ParagraphFormat.Borders) { Assert.AreEqual(LineStyle.DotDash, testBorder.LineStyle); } }
public override void ExecuteResult(ControllerContext context) { var response = context.HttpContext.Response; if (Meetingid.HasValue) { meeting = DbUtil.Db.Meetings.Single(mt => mt.MeetingId == Meetingid); Debug.Assert(meeting.MeetingDate != null, "meeting.MeetingDate != null"); NewMeetingInfo = new NewMeetingInfo { MeetingDate = meeting.MeetingDate.Value }; } var list1 = NewMeetingInfo.ByGroup ? ReportList2().ToList() : ReportList().ToList(); if (!list1.Any()) { response.Write("no data found"); return; } var bytes = RollsheetTemplate() ?? Resource1.DocxRollsheet; var ms = new MemoryStream(bytes); docx = DocX.Load(ms); replacements = new EmailReplacements(DbUtil.Db, docx); var sources = new List <Source>(); foreach (var o in list1) { curr = docx.Copy(); foreach (var p in curr.Headers.odd.Paragraphs) { DoHeaderFooterParagraphReplacments(p, o); } foreach (var p in curr.Footers.odd.Paragraphs) { DoHeaderFooterParagraphReplacments(p, o); } var tbl = curr.Tables[0]; var emptyrow = tbl.InsertRow(); tbl.Rows.Add(emptyrow); tbl.RemoveRow(0); if (meeting != null) { var q = from at in meeting.Attends where at.AttendanceFlag || AttendCommitmentCode.committed.Contains(at.Commitment ?? 0) orderby at.Person.LastName, at.Person.FamilyId, at.Person.Name2 select new RollsheetPersonInfo() { Person = at.Person, MemberTypeCode = at.MemberType.Code, }; foreach (var m in q) { AddRowWithReplacements(tbl, m, meeting.OrganizationId); } } else if (OrgSearchModel != null) { var q = from om in DbUtil.Db.OrganizationMembers where om.OrganizationId == o.OrgId join m in DbUtil.Db.OrgPeople(o.OrgId, o.Groups) on om.PeopleId equals m.PeopleId where om.EnrollmentDate <= Util.Now orderby om.Person.LastName, om.Person.FamilyId, om.Person.Name2 let p = om.Person let useAltName = NewMeetingInfo.UseAltNames && p.AltName != null && p.AltName.Length > 0 select new RollsheetPersonInfo() { Person = p, MemberTypeCode = om.MemberType.Code, UseAltName = useAltName, Highlight = om.OrgMemMemTags.Any(mm => mm.MemberTag.Name == NewMeetingInfo.HighlightGroup) ? NewMeetingInfo.HighlightGroup : "" }; foreach (var m in q) { AddRowWithReplacements(tbl, m, o.OrgId); } } else if (Filter?.GroupSelect == GroupSelectCode.Member) { var q = from om in DbUtil.Db.OrganizationMembers where om.OrganizationId == Filter.Id join m in DbUtil.Db.OrgFilterPeople(QueryId, null) on om.PeopleId equals m.PeopleId where om.EnrollmentDate <= Util.Now where NewMeetingInfo.ByGroup == false || m.Groups.Contains((char)10 + o.Groups + (char)10) orderby om.Person.LastName, om.Person.FamilyId, om.Person.Name2 let p = om.Person let useAltName = NewMeetingInfo.UseAltNames && p.AltName != null && p.AltName.Length > 0 select new RollsheetPersonInfo() { Person = p, MemberTypeCode = om.MemberType.Code, UseAltName = useAltName, Highlight = om.OrgMemMemTags.Any(mm => mm.MemberTag.Name == NewMeetingInfo.HighlightGroup) ? NewMeetingInfo.HighlightGroup : "" }; foreach (var m in q) { AddRowWithReplacements(tbl, m, o.OrgId); } } else { var q = from m in DbUtil.Db.OrgFilterPeople(QueryId, null) orderby m.Name2 let p = DbUtil.Db.People.Single(pp => pp.PeopleId == m.PeopleId) let om = p.OrganizationMembers.SingleOrDefault(mm => mm.OrganizationId == Filter.Id) let useAltName = NewMeetingInfo.UseAltNames && p.AltName != null && p.AltName.Length > 0 select new RollsheetPersonInfo { Person = p, MemberTypeCode = om == null ? "Guest" : om.MemberType.Code, UseAltName = useAltName, Highlight = om.OrgMemMemTags.Any(mm => mm.MemberTag.Name == NewMeetingInfo.HighlightGroup) ? NewMeetingInfo.HighlightGroup : "" }; foreach (var m in q) { AddRowWithReplacements(tbl, m, o.OrgId); } } if ((OrgSearchModel != null && NewMeetingInfo.ByGroup == false) || (Filter != null && Filter.GroupSelect == GroupSelectCode.Member && meeting == null && !Filter.SgFilter.HasValue() && !Filter.NameFilter.HasValue() && !Filter.FilterIndividuals == true && !Filter.FilterTag == true && NewMeetingInfo.ByGroup == false)) { var q = from vp in DbUtil.Db.OrgVisitorsAsOfDate(o.OrgId, NewMeetingInfo.MeetingDate, NoCurrentMembers: true) let p = DbUtil.Db.People.Single(pp => pp.PeopleId == vp.PeopleId) orderby p.LastName, p.FamilyId, p.PreferredName select new RollsheetPersonInfo { Person = p, MemberTypeCode = vp.VisitorType }; foreach (var m in q) { AddRowWithReplacements(tbl, m, o.OrgId); } } curr.Tables[0].RemoveRow(0); { var memStream = new MemoryStream(); curr.SaveAs(memStream); memStream.Position = 0; var wmlDocument = new WmlDocument(null, memStream); sources.Add(new Source(wmlDocument, keepSections: true)); } } context.HttpContext.Response.Clear(); context.HttpContext.Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; context.HttpContext.Response.AddHeader("Content-Disposition", $"attachment;filename=rollsheet.docx"); var finaldoc = DocumentBuilder.BuildDocument(sources); context.HttpContext.Response.OutputStream.Write(finaldoc.DocumentByteArray, 0, finaldoc.DocumentByteArray.Length); }
public void CreateAndRemove() { //ExStart //ExFor:DocumentBuilder.StartEditableRange //ExFor:DocumentBuilder.EndEditableRange //ExFor:EditableRange //ExFor:EditableRange.EditableRangeEnd //ExFor:EditableRange.EditableRangeStart //ExFor:EditableRange.Id //ExFor:EditableRange.Remove //ExFor:EditableRangeEnd.EditableRangeStart //ExFor:EditableRangeEnd.Id //ExFor:EditableRangeEnd.NodeType //ExFor:EditableRangeStart.EditableRange //ExFor:EditableRangeStart.Id //ExFor:EditableRangeStart.NodeType //ExSummary:Shows how to work with an editable range. Document doc = new Document(); doc.Protect(ProtectionType.ReadOnly, "MyPassword"); DocumentBuilder builder = new DocumentBuilder(doc); builder.Writeln("Hello world! Since we have set the document's protection level to read-only," + " we cannot edit this paragraph without the password."); // Editable ranges allow us to leave parts of protected documents open for editing. EditableRangeStart editableRangeStart = builder.StartEditableRange(); builder.Writeln("This paragraph is inside an editable range, and can be edited."); EditableRangeEnd editableRangeEnd = builder.EndEditableRange(); // A well-formed editable range has a start node, and end node. // These nodes have matching IDs and encompass editable nodes. EditableRange editableRange = editableRangeStart.EditableRange; Assert.AreEqual(editableRangeStart.Id, editableRange.Id); Assert.AreEqual(editableRangeEnd.Id, editableRange.Id); // Different parts of the editable range link to each other. Assert.AreEqual(editableRangeStart.Id, editableRange.EditableRangeStart.Id); Assert.AreEqual(editableRangeStart.Id, editableRangeEnd.EditableRangeStart.Id); Assert.AreEqual(editableRange.Id, editableRangeStart.EditableRange.Id); Assert.AreEqual(editableRangeEnd.Id, editableRange.EditableRangeEnd.Id); // We can access the node types of each part like this. The editable range itself is not a node, // but an entity which consists of a start, an end, and their enclosed contents. Assert.AreEqual(NodeType.EditableRangeStart, editableRangeStart.NodeType); Assert.AreEqual(NodeType.EditableRangeEnd, editableRangeEnd.NodeType); builder.Writeln("This paragraph is outside the editable range, and cannot be edited."); doc.Save(ArtifactsDir + "EditableRange.CreateAndRemove.docx"); // Remove an editable range. All the nodes that were inside the range will remain intact. editableRange.Remove(); //ExEnd Assert.AreEqual("Hello world! Since we have set the document's protection level to read-only, we cannot edit this paragraph without the password.\r" + "This paragraph is inside an editable range, and can be edited.\r" + "This paragraph is outside the editable range, and cannot be edited.", doc.GetText().Trim()); Assert.AreEqual(0, doc.GetChildNodes(NodeType.EditableRangeStart, true).Count); doc = new Document(ArtifactsDir + "EditableRange.CreateAndRemove.docx"); Assert.AreEqual(ProtectionType.ReadOnly, doc.ProtectionType); Assert.AreEqual("Hello world! Since we have set the document's protection level to read-only, we cannot edit this paragraph without the password.\r" + "This paragraph is inside an editable range, and can be edited.\r" + "This paragraph is outside the editable range, and cannot be edited.", doc.GetText().Trim()); editableRange = ((EditableRangeStart)doc.GetChild(NodeType.EditableRangeStart, 0, true)).EditableRange; TestUtil.VerifyEditableRange(0, string.Empty, EditorType.Unspecified, editableRange); }
/// <summary> /// 导出安全奖励详细 /// </summary> /// <param name="keyValue"></param> /// <returns></returns> public ActionResult ExportSafeRewardInfo(string keyValue) { HttpResponse resp = System.Web.HttpContext.Current.Response; //报告对象 string fileName = "安全奖励审批单_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".doc"; string strDocPath = Request.PhysicalApplicationPath + @"Resource\ExcelTemplate\安全奖励导出模板.docx"; Aspose.Words.Document doc = new Aspose.Words.Document(strDocPath); DocumentBuilder builder = new DocumentBuilder(doc); DataTable dt = new DataTable(); dt.Columns.Add("RewardCode"); //编号 dt.Columns.Add("ApplyUserName"); //申请人 dt.Columns.Add("ApplyTime"); //申请时间 dt.Columns.Add("BelongDept"); //被奖励部门 dt.Columns.Add("ReardNum"); //申请奖励金额 dt.Columns.Add("RewardName"); //奖励对象名称 dt.Columns.Add("RewardRemark"); //事件描述 dt.Columns.Add("approve1"); //第一步审核意见 dt.Columns.Add("approvename1"); //第一步审核人 dt.Columns.Add("approvetime1"); //第一步审核时间 dt.Columns.Add("approve2"); //第二步审核意见 dt.Columns.Add("approvename2"); //第二步审核人 dt.Columns.Add("approvetime2"); //第二步审核时间 dt.Columns.Add("approve3"); //第三步审核意见 dt.Columns.Add("approvename3"); //第三步审核人 dt.Columns.Add("approvetime3"); //第三步审核时间 dt.Columns.Add("approve4"); //第四步审核意见 dt.Columns.Add("approvename4"); //第四步审核人 dt.Columns.Add("approvetime4"); //第四步审核时间 dt.Columns.Add("approve5"); //第五步审核意见 dt.Columns.Add("approvename5"); //第五步审核人 dt.Columns.Add("approvetime5"); //第五步审核时间 DataRow row = dt.NewRow(); //安全奖励信息 SaferewardEntity saferewardentity = saferewardbll.GetEntity(keyValue); row["RewardCode"] = saferewardentity.SafeRewardCode; row["ApplyUserName"] = saferewardentity.ApplyUserName; row["ApplyTime"] = saferewardentity.ApplyTime.IsEmpty() ? "" : Convert.ToDateTime(saferewardentity.ApplyTime).ToString("yyyy-MM-dd"); row["RewardRemark"] = saferewardentity.RewardRemark; row["approve1"] = saferewardentity.SpecialtyOpinion; row["approvetime1"] = saferewardentity.CreateDate.IsEmpty() ? "" : Convert.ToDateTime(saferewardentity.CreateDate).ToString("yyyy-MM-dd"); UserEntity createuser = new UserBLL().GetEntity(saferewardentity.CreateUserId); if (createuser.SignImg.IsEmpty()) { row["approvename1"] = Server.MapPath("~/content/Images/no_1.png"); } else { var filepath = Server.MapPath("~/") + createuser.SignImg.ToString().Replace("../../", "").ToString(); if (System.IO.File.Exists(filepath)) { row["approvename1"] = filepath; } else { row["approvename1"] = Server.MapPath("~/content/Images/no_1.png"); } } builder.MoveToMergeField("approvename1"); builder.InsertImage(row["approvename1"].ToString(), 80, 35); var flist = fileinfobll.GetImageListByRecid(keyValue); builder.MoveToMergeField("RewardImage"); foreach (FileInfoEntity fmode in flist) { string path = ""; if (string.IsNullOrWhiteSpace(fmode.FilePath)) { path = Server.MapPath("~/content/Images/no_1.png"); } else { var filepath = Server.MapPath("~/") + fmode.FilePath.Replace("~/", "").ToString(); if (System.IO.File.Exists(filepath)) { path = filepath; } else { path = Server.MapPath("~/content/Images/no_1.png"); } } builder.MoveToMergeField("RewardImage"); builder.InsertImage(path, 200, 160); } //获取被考核对象 SaferewarddetailEntity SaferewarddetailEntity = saferewarddetailbll.GetListByRewardId(keyValue).OrderBy(t => t.CreateDate).FirstOrDefault(); row["BelongDept"] = departmentbll.GetEntity(SaferewarddetailEntity.BelongDept) == null ? "" : departmentbll.GetEntity(SaferewarddetailEntity.BelongDept).FullName; row["ReardNum"] = SaferewarddetailEntity.RewardNum; row["RewardName"] = SaferewarddetailEntity.RewardName; DataTable dtAptitude = saferewardbll.GetAptitudeInfo(keyValue); int count = dtAptitude.Rows.Count; for (int i = dtAptitude.Rows.Count - 1; i > 0; i--) { if (i == (dtAptitude.Rows.Count - 2)) { row["approve5"] = dtAptitude.Rows[i]["auditremark"]; row["approvetime5"] = dtAptitude.Rows[i]["auditdate"].IsEmpty() ? "" : Convert.ToDateTime(dtAptitude.Rows[i]["auditdate"]).ToString("yyyy-MM-dd"); if (dtAptitude.Rows[i]["auditsignimg"].IsEmpty()) { row["approvename5"] = Server.MapPath("~/content/Images/no_1.png"); } else { var filepath = Server.MapPath("~/") + dtAptitude.Rows[i]["auditsignimg"].ToString().Replace("../../", "").ToString(); if (System.IO.File.Exists(filepath)) { row["approvename5"] = filepath; } else { row["approvename5"] = Server.MapPath("~/content/Images/no_1.png"); } } builder.MoveToMergeField("approvename5"); builder.InsertImage(row["approvename5"].ToString(), 80, 35); } else if (i == (dtAptitude.Rows.Count - 3)) { row["approve4"] = dtAptitude.Rows[i]["auditremark"]; row["approvetime4"] = dtAptitude.Rows[i]["auditdate"].IsEmpty() ? "" : Convert.ToDateTime(dtAptitude.Rows[i]["auditdate"]).ToString("yyyy-MM-dd"); if (dtAptitude.Rows[i]["auditsignimg"].IsEmpty()) { row["approvename4"] = Server.MapPath("~/content/Images/no_1.png"); } else { var filepath = Server.MapPath("~/") + dtAptitude.Rows[i]["auditsignimg"].ToString().Replace("../../", "").ToString(); if (System.IO.File.Exists(filepath)) { row["approvename4"] = filepath; } else { row["approvename4"] = Server.MapPath("~/content/Images/no_1.png"); } } builder.MoveToMergeField("approvename4"); builder.InsertImage(row["approvename4"].ToString(), 80, 35); } else if (i == (dtAptitude.Rows.Count - 4)) { row["approve3"] = dtAptitude.Rows[i]["auditremark"]; row["approvetime3"] = dtAptitude.Rows[i]["auditdate"].IsEmpty() ? "" : Convert.ToDateTime(dtAptitude.Rows[i]["auditdate"]).ToString("yyyy-MM-dd"); if (dtAptitude.Rows[i]["auditsignimg"].IsEmpty()) { row["approvename3"] = Server.MapPath("~/content/Images/no_1.png"); } else { var filepath = Server.MapPath("~/") + dtAptitude.Rows[i]["auditsignimg"].ToString().Replace("../../", "").ToString(); if (System.IO.File.Exists(filepath)) { row["approvename3"] = filepath; } else { row["approvename3"] = Server.MapPath("~/content/Images/no_1.png"); } } builder.MoveToMergeField("approvename3"); builder.InsertImage(row["approvename3"].ToString(), 80, 35); } else if (i == (dtAptitude.Rows.Count - 5)) { row["approve2"] = dtAptitude.Rows[i]["auditremark"]; row["approvetime2"] = dtAptitude.Rows[i]["auditdate"].IsEmpty() ? "" : Convert.ToDateTime(dtAptitude.Rows[i]["auditdate"]).ToString("yyyy-MM-dd"); if (dtAptitude.Rows[i]["auditsignimg"].IsEmpty()) { row["approvename2"] = Server.MapPath("~/content/Images/no_1.png"); } else { var filepath = Server.MapPath("~/") + dtAptitude.Rows[i]["auditsignimg"].ToString().Replace("../../", "").ToString(); if (System.IO.File.Exists(filepath)) { row["approvename2"] = filepath; } else { row["approvename2"] = Server.MapPath("~/content/Images/no_1.png"); } } builder.MoveToMergeField("approvename2"); builder.InsertImage(row["approvename2"].ToString(), 80, 35); } } dt.Rows.Add(row); doc.MailMerge.Execute(dt); doc.MailMerge.DeleteFields(); doc.Save(resp, Server.UrlEncode(fileName), ContentDisposition.Attachment, Aspose.Words.Saving.SaveOptions.CreateSaveOptions(SaveFormat.Doc)); return(Success("导出成功!")); }
public StudentMoralProcessor(DocumentBuilder builder, SemesterMap map) { _builder = builder; _map = map; _types = new Dictionary <string, List <string> >(); _run = WordHelper.CreateRun(_builder); #region 取得假別設定 ConfigData cd = K12.Data.School.Configuration["學籍表"]; if (cd.Contains("假別設定")) { XmlElement config = Framework.XmlHelper.LoadXml(cd["假別設定"]); foreach (XmlElement type in config.SelectNodes("Type")) { string typeName = type.GetAttribute("Text"); if (!_types.ContainsKey(typeName)) { _types.Add(typeName, new List <string>()); } foreach (XmlElement absence in type.SelectNodes("Absence")) { string absenceName = absence.GetAttribute("Text"); if (!_types[typeName].Contains(absenceName)) { _types[typeName].Add(absenceName); } } } } #endregion #region 取得社團成績 _assnScoreCache = new Dictionary <string, List <AssnScore> >(); FISCA.UDT.AccessHelper ah = new FISCA.UDT.AccessHelper(); // string condition = string.Format("SchoolYear='{0}' and Semester='{1}'", options.SchoolYear, options.Semester); // List<AssnCode> list = ah.Select<AssnCode>(condition); if (AssociationUDTCache == null) { AssociationUDTCache = ah.Select <AssnCode>(); } List <AssnCode> list = AssociationUDTCache; foreach (AssnCode record in list) { //if (!_assnScoreCache.ContainsKey(record.StudentID)) //{ XmlElement scores = K12.Data.XmlHelper.LoadXml(record.Scores); XmlElement itemElement = (XmlElement)scores.SelectSingleNode("Item"); if (itemElement != null) { AssnScore assnScore = new AssnScore() { Score = itemElement.GetAttribute("Score"), Effort = itemElement.GetAttribute("Effort"), Text = itemElement.GetAttribute("Text"), SchoolYear = record.SchoolYear, Semester = record.Semester }; if (_assnScoreCache.ContainsKey(record.StudentID)) { _assnScoreCache[record.StudentID].Add(assnScore); } else { List <AssnScore> lis = new List <AssnScore>(); lis.Add(assnScore); _assnScoreCache.Add(record.StudentID, lis); } } //} } //<Content> //<Item AssociationName="籃球社" Score="" Effort="" Text=""></Item> //</Content> #endregion }
public void FillTableUsingRepeatingSectionItem() { //ExStart //ExFor:SdtType //ExSummary:Shows how to fill the table with data contained in the XML part. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); CustomXmlPart xmlPart = doc.CustomXmlParts.Add("Books", "<books>" + "<book><title>Everyday Italian</title>" + "<author>Giada De Laurentiis</author></book>" + "<book><title>Harry Potter</title>" + "<author>J K. Rowling</author></book>" + "<book><title>Learning XML</title>" + "<author>Erik T. Ray</author></book>" + "</books>"); // Create headers for data from xml content Table table = builder.StartTable(); builder.InsertCell(); builder.Write("Title"); builder.InsertCell(); builder.Write("Author"); builder.EndRow(); builder.EndTable(); // Create table with RepeatingSection inside StructuredDocumentTag repeatingSectionSdt = new StructuredDocumentTag(doc, SdtType.RepeatingSection, MarkupLevel.Row); repeatingSectionSdt.XmlMapping.SetMapping(xmlPart, "/books[1]/book", ""); table.AppendChild(repeatingSectionSdt); // Add RepeatingSectionItem inside RepeatingSection and mark it as a row StructuredDocumentTag repeatingSectionItemSdt = new StructuredDocumentTag(doc, SdtType.RepeatingSectionItem, MarkupLevel.Row); repeatingSectionSdt.AppendChild(repeatingSectionItemSdt); Row row = new Row(doc); repeatingSectionItemSdt.AppendChild(row); // Map xml data with created table cells for book title and author StructuredDocumentTag titleSdt = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Cell); titleSdt.XmlMapping.SetMapping(xmlPart, "/books[1]/book[1]/title[1]", ""); row.AppendChild(titleSdt); StructuredDocumentTag authorSdt = new StructuredDocumentTag(doc, SdtType.PlainText, MarkupLevel.Cell); authorSdt.XmlMapping.SetMapping(xmlPart, "/books[1]/book[1]/author[1]", ""); row.AppendChild(authorSdt); doc.Save(ArtifactsDir + "StructuredDocumentTag.RepeatingSectionItem.docx"); //ExEnd }
/// <summary> /// Pinta el contenido del hipercubo. /// </summary> /// <param name="hipercubo">Hipercubo.</param> /// <param name="instancia">Documento de instancia.</param> /// <param name="estructuraReporte">Estructura del reporte.</param> /// <param name="docBuilder">Constructor del documento.</param> /// <param name="concepto">Concepto origen.</param> /// <param name="rolAExportar">Rol que se pretende exportar.</param> /// <param name="exportadorOrigen">Exportador original</param> private void PintaTablaCubo( HipercuboReporteDTO hipercubo, DocumentoInstanciaXbrlDto instancia, ReporteXBRLDTO estructuraReporte, DocumentBuilder docBuilder, ConceptoReporteDTO concepto, IndiceReporteDTO rolAExportar, ExportadorRolDocumentoBase exportadorOrigen) { var tablaActual = docBuilder.StartTable(); var colorTitulo = exportadorOrigen.ObtenColorTitulo(); docBuilder.ParagraphFormat.SpaceAfter = 0; docBuilder.ParagraphFormat.SpaceBefore = 2; //docBuilder.InsertCell(); // docBuilder.EndRow(); docBuilder.CellFormat.Shading.BackgroundPatternColor = colorTitulo; docBuilder.Font.Color = Color.White; docBuilder.Font.Size = exportadorOrigen.TamanioLetraContenidoTabla; var listaIdsConcepto = new List <string>(); foreach (var idConcepto in hipercubo.Hechos.Keys) { if (ConceptosAplica != null && !ConceptosAplica.Contains(idConcepto)) { continue; } listaIdsConcepto.Add(idConcepto); } var etiquetaTitulo = String.Empty; if (!String.IsNullOrEmpty(IdConceptoReferencia)) { etiquetaTitulo = DesgloseDeCreditosHelper .obtenerEtiquetaDeConcepto(instancia.Taxonomia, IdConceptoReferencia, estructuraReporte.Lenguaje, ReporteXBRLUtil.ETIQUETA_DEFAULT); } else { etiquetaTitulo = concepto.Valor; } PintaFilaSubTitulo(etiquetaTitulo, docBuilder, listaIdsConcepto.Count, exportadorOrigen); docBuilder.CellFormat.Shading.BackgroundPatternColor = colorTitulo; docBuilder.Font.Color = Color.White; docBuilder.Font.Size = exportadorOrigen.TamanioLetraContenidoTabla; docBuilder.RowFormat.HeadingFormat = true; docBuilder.Bold = true; foreach (var idConcepto in listaIdsConcepto) { var nombreConcepto = DesgloseDeCreditosHelper.obtenerEtiquetaDeConcepto(instancia.Taxonomia, idConcepto, estructuraReporte.Lenguaje, ReporteXBRLUtil.ETIQUETA_DEFAULT); docBuilder.InsertCell(); docBuilder.Write(nombreConcepto ?? ""); } docBuilder.EndRow(); docBuilder.CellFormat.Shading.BackgroundPatternColor = Color.White; docBuilder.Font.Color = Color.Black; docBuilder.Bold = false; var matrisHechos = hipercubo.Utileria.ReordenaConjutosPorExplicitaImplicitaConcepto(hipercubo.Hechos); var idDimensionTitulos = String.Empty; if (matrisHechos.Count > 1) { var dimensionExplicita = hipercubo.Utileria.configuracion.PlantillaDimensiones.Values.Where(X => X.Explicita == true).FirstOrDefault(); if (dimensionExplicita != null) { idDimensionTitulos = dimensionExplicita.IdDimension; } } foreach (var idPlantillaContexto in matrisHechos.Keys) { if (IdsPlantillasContexto != null && !IdsPlantillasContexto.Contains(idPlantillaContexto)) { continue; } var listaImplicita = matrisHechos[idPlantillaContexto]; var contieneHechos = listaImplicita.Where(X => X.Count > 0).FirstOrDefault() != null; if (!contieneHechos) { continue; } if (!String.IsNullOrEmpty(idDimensionTitulos)) { Viewer.Application.Dto.Hipercubos.PlantillaContextoDto plantillaContexto; if (hipercubo.Utileria.configuracion.PlantillasContextos.TryGetValue(idPlantillaContexto, out plantillaContexto)) { var miembroDimension = plantillaContexto.ValoresDimension.Where(x => x.IdDimension.Equals(idDimensionTitulos)).FirstOrDefault(); if (miembroDimension != null) { var etiquetaMiembro = DesgloseDeCreditosHelper .obtenerEtiquetaDeConcepto(instancia.Taxonomia, miembroDimension.IdItemMiembro, estructuraReporte.Lenguaje, ReporteXBRLUtil.ETIQUETA_DEFAULT); PintaFilaSubTitulo(etiquetaMiembro, docBuilder, listaIdsConcepto.Count, exportadorOrigen); } } } for (var indexImplicita = 0; indexImplicita < listaImplicita.Count; indexImplicita++) { var diccionarioPorconcepto = listaImplicita[indexImplicita]; HechoDto hecho; foreach (var idConceptoItera in listaIdsConcepto) { docBuilder.InsertCell(); if (diccionarioPorconcepto.TryGetValue(idConceptoItera, out hecho)) { if (hecho.NoEsNumerico) { docBuilder.CellFormat.WrapText = true; docBuilder.ParagraphFormat.Alignment = ParagraphAlignment.Left; } else { docBuilder.CellFormat.WrapText = false; docBuilder.ParagraphFormat.Alignment = ParagraphAlignment.Right; } exportadorOrigen.EscribirValorHecho(docBuilder, estructuraReporte, hecho, instancia.Taxonomia.ConceptosPorId[hecho.IdConcepto]); } else { docBuilder.Write(" "); } } docBuilder.EndRow(); } } exportadorOrigen.establecerBordesGrisesTabla(tablaActual); docBuilder.EndTable(); docBuilder.Writeln(); docBuilder.Writeln(); }
public void DB006_Example_DocumentBuilder01() { FileInfo source1 = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, "DB006-Source1.docx")); FileInfo source2 = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, "DB006-Source2.docx")); FileInfo source3 = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, "DB006-Source3.docx")); List <Source> sources = null; // Create new document from 10 paragraphs starting at paragraph 5 of Source1.docx sources = new List <Source>() { new Source(new WmlDocument(source1.FullName), 5, 10, true), }; var out1 = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, "DB006-Out1.docx")); DocumentBuilder.BuildDocument(sources, out1.FullName); Validate(out1); // Create new document from paragraph 1, and paragraphs 5 through end of Source3.docx. // This effectively 'deletes' paragraphs 2-4 sources = new List <Source>() { new Source(new WmlDocument(source3.FullName), 0, 1, false), new Source(new WmlDocument(source3.FullName), 4, false), }; var out2 = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, "DB006-Out2.docx")); DocumentBuilder.BuildDocument(sources, out2.FullName); Validate(out2); // Create a new document that consists of the entirety of Source1.docx and Source2.docx. Use // the section information (headings and footers) from source1. sources = new List <Source>() { new Source(new WmlDocument(source1.FullName), true), new Source(new WmlDocument(source2.FullName), false), }; var out3 = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, "DB006-Out3.docx")); DocumentBuilder.BuildDocument(sources, out3.FullName); Validate(out3); // Create a new document that consists of the entirety of Source1.docx and Source2.docx. Use // the section information (headings and footers) from source2. sources = new List <Source>() { new Source(new WmlDocument(source1.FullName), false), new Source(new WmlDocument(source2.FullName), true), }; var out4 = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, "DB006-Out4.docx")); DocumentBuilder.BuildDocument(sources, out4.FullName); Validate(out4); // Create a new document that consists of the first 5 paragraphs of Source1.docx and the first // five paragraphs of Source2.docx. This example returns a new WmlDocument, when you then can // serialize to a SharePoint document library, or use in some other interesting scenario. sources = new List <Source>() { new Source(new WmlDocument(source1.FullName), 0, 5, false), new Source(new WmlDocument(source2.FullName), 0, 5, true), }; WmlDocument wmlOut5 = DocumentBuilder.BuildDocument(sources); var out5 = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, "DB006-Out5.docx")); wmlOut5.SaveAs(out5.FullName); // save it to the file system, but we could just as easily done something // else with it. Validate(out5); }
override public void Execute() { DocumentPackage package = PackageBuilder.NewPackageNamed(PackageName) .DescribedAs("This is a new package") .WithSigner(SignerBuilder.NewSignerWithEmail(email1) .WithFirstName("John") .WithLastName("Smith")) .WithDocument(DocumentBuilder.NewDocumentNamed(DOCUMENT_NAME) .FromStream(fileStream1, DocumentType.PDF) .WithSignature(SignatureBuilder.SignatureFor(email1) .OnPage(0) .AtPosition(500, 100) .WithField(FieldBuilder.TextField() .WithId(TEXTFIELD_ID) .WithFontSize(TEXTFIELD_FONT_SIZE) .OnPage(TEXTFIELD_PAGE) .AtPosition(500, 200)) .WithField(FieldBuilder.CheckBox() .WithId(CHECKBOX_ID) .WithValue(CHECKBOX_VALUE) .OnPage(CHECKBOX_PAGE) .AtPosition(500, 300)) .WithField(FieldBuilder.RadioButton(RADIO_GROUP_1) .WithId(RADIO_ID_1) .WithValue(false) .WithSize(RADIO_WIDTH, RADIO_HEIGHT) .OnPage(RADIO_PAGE) .AtPosition(500, 400)) .WithField(FieldBuilder.RadioButton(RADIO_GROUP_1) .WithId(RADIO_ID_2) .WithValue(true) .WithSize(RADIO_WIDTH, RADIO_HEIGHT) .OnPage(RADIO_PAGE) .AtPosition(500, 450)) .WithField(FieldBuilder.RadioButton(RADIO_GROUP_2) .WithId(RADIO_ID_3) .WithValue(true) .WithSize(RADIO_WIDTH, RADIO_HEIGHT) .OnPage(RADIO_PAGE) .AtPosition(500, 500)) .WithField(FieldBuilder.RadioButton(RADIO_GROUP_2) .WithId(RADIO_ID_4) .WithValue(false) .WithSize(RADIO_WIDTH, RADIO_HEIGHT) .OnPage(RADIO_PAGE) .AtPosition(500, 550)) .WithField(FieldBuilder.DropList() .WithId(DROP_LIST_ID) .WithValue(DROP_LIST_OPTION2) .WithFontSize(DROP_LIST_FONT_SIZE) .WithValidation(FieldValidatorBuilder.Basic() .WithOption(DROP_LIST_OPTION1) .WithOption(DROP_LIST_OPTION2) .WithOption(DROP_LIST_OPTION3)) .OnPage(DROP_LIST_PAGE) .WithSize(100, 200) .AtPosition(100, 100)) .WithField(FieldBuilder.TextArea() .WithId(TEXT_AREA_ID) .WithValue(TEXT_AREA_VALUE) .WithFontSize(TEXT_AREA_FONT_SIZE) .OnPage(TEXT_AREA_PAGE) .WithSize(400, 600) .AtPosition(200, 200) .WithValidation(FieldValidatorBuilder.Basic() .Disabled())) .WithField(FieldBuilder.Label() .WithId(LABEL_ID) .WithValue(LABEL_VALUE) .WithFontSize(LABEL_FIELD_FONT_SIZE) .OnPage(LABEL_PAGE) .WithSize(100, 60) .AtPosition(220, 220)) .WithField(FieldBuilder.Datepicker() .WithId(DATEPICKER_ID) .WithName(DATEPICKER_NAME) .WithValue(DATEPICKER_VALUE) .WithFontSize(DATEPICKER_FIELD_FONT_SIZE) .OnPage(DATEPICKER_PAGE) .WithSize(100, 60) .AtPosition(150, 150) .WithValidation(FieldValidatorBuilder.DatepickerFormat(DATEPICKER_FORMAT) .Required())))) .Build(); packageId = eslClient.CreatePackage(package); eslClient.SendPackage(PackageId); retrievedPackage = eslClient.GetPackage(packageId); }
public void CreateLinkedImage() { //ExStart //ExFor:Shape.ImageData //ExFor:ImageData //ExFor:ImageData.SourceFullName //ExFor:ImageData.SetImage(String) //ExFor:DocumentBuilder.InsertNode //ExSummary:Shows how to insert a linked image into a document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); string imageFileName = ImageDir + "Windows MetaFile.wmf"; builder.Write("Image linked, not stored in the document: "); Shape shape = new Shape(builder.Document, ShapeType.Image); shape.WrapType = WrapType.Inline; shape.ImageData.SourceFullName = imageFileName; builder.InsertNode(shape); builder.Writeln(); builder.Write("Image linked and stored in the document: "); shape = new Shape(builder.Document, ShapeType.Image); shape.WrapType = WrapType.Inline; shape.ImageData.SourceFullName = imageFileName; shape.ImageData.SetImage(imageFileName); builder.InsertNode(shape); builder.Writeln(); builder.Write("Image stored in the document, but not linked: "); shape = new Shape(builder.Document, ShapeType.Image); shape.WrapType = WrapType.Inline; shape.ImageData.SetImage(imageFileName); builder.InsertNode(shape); builder.Writeln(); doc.Save(ArtifactsDir + "Image.CreateLinkedImage.docx"); //ExEnd doc = new Document(ArtifactsDir + "Image.CreateLinkedImage.docx"); shape = (Shape)doc.GetChild(NodeType.Shape, 0, true); TestUtil.VerifyImageInShape(0, 0, ImageType.Wmf, shape); Assert.AreEqual(WrapType.Inline, shape.WrapType); Assert.AreEqual(imageFileName, shape.ImageData.SourceFullName.Replace("%20", " ")); shape = (Shape)doc.GetChild(NodeType.Shape, 1, true); TestUtil.VerifyImageInShape(1600, 1600, ImageType.Wmf, shape); Assert.AreEqual(WrapType.Inline, shape.WrapType); Assert.AreEqual(imageFileName, shape.ImageData.SourceFullName.Replace("%20", " ")); shape = (Shape)doc.GetChild(NodeType.Shape, 2, true); TestUtil.VerifyImageInShape(1600, 1600, ImageType.Wmf, shape); Assert.AreEqual(WrapType.Inline, shape.WrapType); Assert.AreEqual(string.Empty, shape.ImageData.SourceFullName.Replace("%20", " ")); }
public void DB009_ShredDocument() { FileInfo spec = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, "DB007-Spec.docx")); // Shred a document into multiple parts for each section List <DocumentInfo> documentList; using (WordprocessingDocument doc = WordprocessingDocument.Open(spec.FullName, false)) { var sectionCounts = doc .MainDocumentPart .GetXDocument() .Root .Element(W.body) .Elements() .Rollup(0, (pi, last) => (string)pi .Elements(W.pPr) .Elements(W.pStyle) .Attributes(W.val) .FirstOrDefault() == "Heading1" ? last + 1 : last); var beforeZipped = doc .MainDocumentPart .GetXDocument() .Root .Element(W.body) .Elements() .Select((p, i) => new { Paragraph = p, Index = i, }); var zipped = PtExtensions.PtZip(beforeZipped, sectionCounts, (pi, sc) => new { Paragraph = pi.Paragraph, Index = pi.Index, SectionIndex = sc, }); documentList = zipped .GroupAdjacent(p => p.SectionIndex) .Select(g => new DocumentInfo { DocumentNumber = g.Key, Start = g.First().Index, Count = g.Last().Index - g.First().Index + 1, }) .ToList(); } foreach (var doc in documentList) { string fileName = String.Format("DB009-Section{0:000}.docx", doc.DocumentNumber); var fiSection = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, fileName)); List <Source> documentSource = new List <Source> { new Source(new WmlDocument(spec.FullName), doc.Start, doc.Count, true) }; DocumentBuilder.BuildDocument(documentSource, fiSection.FullName); Validate(fiSection); } // Re-assemble the parts into a single document. List <Source> sources = TestUtil.TempDir .GetFiles("DB009-Section*.docx") .Select(d => new Source(new WmlDocument(d.FullName), true)) .ToList(); var fiReassembled = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, "DB009-Reassembled.docx")); DocumentBuilder.BuildDocument(sources, fiReassembled.FullName); using (WordprocessingDocument doc = WordprocessingDocument.Open(fiReassembled.FullName, true)) { ReferenceAdder.AddToc(doc, "/w:document/w:body/w:p[1]", @"TOC \o '1-3' \h \z \u", null, null); } Validate(fiReassembled); }
/// <summary> /// 每一名學生的報表資料列印 /// </summary> /// <returns></returns> private Document SetDocument(string classID) { List <StudentRecord> CheckList = ClassByStudentDic[classID]; List <StudentRecord> StudentList = new List <StudentRecord>(); if (np == NowPrint.empty) //未選 { foreach (StudentRecord each in CheckList) { StudentSCjoinObj scj = SCjoinObjDic[each.ID]; if (scj.CLUBRecord.Count == 0) { StudentList.Add(each); } } } else if (np == NowPrint.General) //已選 { foreach (StudentRecord each in CheckList) { StudentSCjoinObj scj = SCjoinObjDic[each.ID]; if (scj.CLUBRecord.Count == 1) { StudentList.Add(each); } } } else if (np == NowPrint.Repeat) //重覆 { foreach (StudentRecord each in CheckList) { StudentSCjoinObj scj = SCjoinObjDic[each.ID]; if (scj.CLUBRecord.Count > 1) { StudentList.Add(each); } } } else { StudentList.AddRange(CheckList); } //如果沒資料回傳null if (StudentList.Count == 0) { return(null); } //取得範本樣式 Document PageOne = (Document)_template.Clone(true); #region MailMerge List <string> name = new List <string>(); List <string> value = new List <string>(); name.Add("學校名稱"); value.Add(School.ChineseName); name.Add("名稱"); value.Add(RePortName); name.Add("班級"); value.Add(Class.SelectByID(classID).Name); name.Add("學年度"); value.Add("" + _SchoolYear); name.Add("學期"); value.Add("" + _Semester); PageOne.MailMerge.Execute(name.ToArray(), value.ToArray()); #endregion //??? _run = new Run(PageOne); //可建構的... DocumentBuilder builder = new DocumentBuilder(PageOne); builder.MoveToMergeField("資料"); Cell cell = (Cell)builder.CurrentParagraph.ParentNode; //取得目前Row Row 日3row = (Row)cell.ParentRow; int addcount = 0; foreach (StudentRecord each in StudentList) { StudentSCjoinObj scj = SCjoinObjDic[each.ID]; if (scj.CLUBRecord.Count > 0) { foreach (CLUBRecord club in scj.CLUBRecord) { addcount++; } } else { addcount++; } } //除了原來的Row-1,高於1就多建立幾行 for (int x = 1; x < addcount; x++) { cell.ParentRow.ParentTable.InsertAfter(日3row.Clone(true), cell.ParentNode); } foreach (StudentRecord each in StudentList) { StudentSCjoinObj scj = SCjoinObjDic[each.ID]; if (scj.CLUBRecord.Count > 0) { foreach (CLUBRecord club in scj.CLUBRecord) { //座號 Write(cell, scj.SeatNo); cell = GetMoveRightCell(cell, 1); Write(cell, scj.Name); cell = GetMoveRightCell(cell, 1); Write(cell, scj.StudentNumber); cell = GetMoveRightCell(cell, 1); Write(cell, scj.Gender); cell = GetMoveRightCell(cell, 1); Write(cell, club.ClubName); cell = GetMoveRightCell(cell, 1); //社團類型 Write(cell, club.ClubCategory); cell = GetMoveRightCell(cell, 1); //學生擔任幹部 List <string> list = new List <string>(); if (club.President == each.ID) { list.Add("社長"); //社長 } if (club.VicePresident == each.ID) { list.Add("副社長"); } List <CadresRecord> CadreList = tool._A.Select <CadresRecord>("ref_club_id='" + club.UID + "'"); foreach (CadresRecord cadre in CadreList) { if (cadre.RefStudentID == each.ID) { list.Add(cadre.CadreName); } } if (list.Count > 0) { Write(cell, string.Join(",", list)); } Row Nextrow = cell.ParentRow.NextSibling as Row; //取得下一行 if (Nextrow == null) { break; } cell = Nextrow.FirstCell; //第一格 } } else { //座號 Write(cell, scj.SeatNo); cell = GetMoveRightCell(cell, 1); Write(cell, scj.Name); cell = GetMoveRightCell(cell, 1); Write(cell, scj.StudentNumber); cell = GetMoveRightCell(cell, 1); Write(cell, scj.Gender); cell = GetMoveRightCell(cell, 1); Row Nextrow = cell.ParentRow.NextSibling as Row; //取得下一行 if (Nextrow == null) { break; } cell = Nextrow.FirstCell; //第一格 } } return(PageOne); }
/// <summary> /// 每一名學生的報表資料列印 /// </summary> /// <returns></returns> private Document SetDocument(string classID) { List <StudentRecord> StudentList = ClassByStudentDic[classID]; //取得範本樣式 Document PageOne = (Document)_template.Clone(true); #region MailMerge List <string> name = new List <string>(); List <string> value = new List <string>(); name.Add("班級"); value.Add(Class.SelectByID(classID).Name); name.Add("學年度"); value.Add(School.DefaultSchoolYear); name.Add("學期"); value.Add(School.DefaultSemester); PageOne.MailMerge.Execute(name.ToArray(), value.ToArray()); #endregion //??? _run = new Run(PageOne); //可建構的... DocumentBuilder builder = new DocumentBuilder(PageOne); builder.MoveToMergeField("資料"); Cell cell = (Cell)builder.CurrentParagraph.ParentNode; //取得目前Row Row 日3row = (Row)cell.ParentRow; //除了原來的Row-1,高於1就多建立幾行 for (int x = 1; x < StudentList.Count; x++) { cell.ParentRow.ParentTable.InsertAfter(日3row.Clone(true), cell.ParentNode); } foreach (StudentRecord each in StudentList) { StudentSCjoinObj scj = SCjoinObjDic[each.ID]; //座號 Write(cell, scj.SeatNo); cell = GetMoveRightCell(cell, 1); Write(cell, scj.Name); cell = GetMoveRightCell(cell, 1); Write(cell, scj.StudentNumber); cell = GetMoveRightCell(cell, 1); Write(cell, scj.Gender); cell = GetMoveRightCell(cell, 1); Write(cell, scj.GetClubName); cell = GetMoveRightCell(cell, 1); Row Nextrow = cell.ParentRow.NextSibling as Row; //取得下一行 if (Nextrow == null) { break; } cell = Nextrow.FirstCell; //第一格 } return(PageOne); }
private static Hashtable hu = new Hashtable();//用户基本信息 //生成文件 public static void CreateMortgageFile(string UID, string documentType) { Hashtable ht = DataFactory.SqlDataBase().GetHashtableById("Document_Template", "documentType", documentType); string _documentName = ""; if (ht.Contains("DOCUMENTNAME")) { _documentName = ht["DOCUMENTNAME"].ToString(); } Hashtable hm = DataFactory.SqlDataBase().GetHashtableById("Contract_Mortgage", "UID", UID); string _FilePath = _Path + _documentName + ".docx"; if (File.Exists(_FilePath)) { string _Upath = System.AppDomain.CurrentDomain.BaseDirectory + "UserInfo\\" + hm["CARD_ID"].ToString() + "\\"; string _UserFileName = string.Format("{0}_{1}.docx", _documentName, hm["CARD_NAME"].ToString()); Aspose.Words.License li = new Aspose.Words.License(); li.SetLicense("License.lic"); Document doc = new Document(_FilePath); DocumentBuilder builder = new DocumentBuilder(doc); StringBuilder sb = new StringBuilder(); sb.AppendFormat("SELECT * FROM Contract_Mortgage WHERE UID='{0}'", UID); DataTable dt = DataFactory.SqlDataBase().GetDataTableBySQL(sb); if (DataTableHelper.IsExistRows(dt)) { DataRow dr = dt.Rows[0]; //DataRow drc = dtc.Rows[0]; //DataRow drp = dtp.Rows[0]; //mark命名规则:TCard_Name003--T/P:文字/图片;Card_Name:字段名;003:序号 int markCount = doc.Range.Bookmarks.Count; for (int i = 0; i < markCount; i++) { Bookmark bookmark = doc.Range.Bookmarks[i]; string markName = bookmark.Name; string mType = markName.Substring(0, 1); string FieldName = markName.Substring(1, markName.Length - 4); switch (mType) { case "T": if (dr.Table.Columns.Contains(FieldName)) { bookmark.Text = dr[FieldName].ToString(); break; } //if (drc.Table.Columns.Contains(FieldName)) //{ // bookmark.Text = drc[FieldName].ToString(); // break; //} //if (drp.Table.Columns.Contains(FieldName)) //{ // bookmark.Text = drp[FieldName].ToString(); // break; //} break; default: break; } } try { int m = doc.MailMerge.GetFieldNames().Length; string[] MMNames = doc.MailMerge.GetFieldNames(); for (int i = 0; i < m; i++) { string MName = string.Empty; if (MMNames[i].Split(':').Length > 0) { MName = MMNames[i].Split(':')[1]; } string MType = MName.Substring(0, 1); string MFieldName = MName.Substring(1, MName.Length - 4); if (MType.Equals("P")) { if (File.Exists(_Upath + MFieldName + ".png")) { builder.MoveToMergeField(MName); Shape shape = builder.InsertImage(_Upath + MFieldName + ".png"); // shape.WrapType = WrapType.Through;//可以使图片浮于文字上方,但是位置信息丢失,不能在书签位置出现。 int _width = 0; int _height = 0; GetSize(MFieldName, out _width, out _height); shape.Width = _width; shape.Height = _height; doc.MailMerge.Execute(new string[] { MName }, new object[] { shape }); } } else { } } } catch (Exception ex) { } } doc.MailMerge.DeleteFields(); if (!Directory.Exists(_Upath)) { Directory.CreateDirectory(_Upath); } doc.Save(_Upath + _UserFileName); } }
//public FileResult PrintSubscriber() public IActionResult PrintSubscriber() { //Получаем пользователя var user = GetUser(); //Получаем все записи абонентов для пользователя var subscribers = _context.Subscribers.ToList(); //var subscribers = _context.Subscribers.Where(s => s.User.Id == user.Id).ToList(); //Получение печатной формы var streamTemplate = GetResourceStream("PrintTemplateForSubscribers.docx"); Aspose.Words.License license = new License(); Stream licFile = GetResourceStream("Aspose.Total.lic"); license.SetLicense(licFile); var document = new Aspose.Words.Document(streamTemplate); var fildNameUser = document.Range.Fields.FirstOrDefault(field => field.Result == "«NameUser»"); if (fildNameUser != null) { fildNameUser.Result = user.UserName; } DocumentBuilder builder = new DocumentBuilder(document); //Переходим на закладку TableSubscribers в документе builder.MoveToBookmark("TableSubscribers"); //Начинаем построение таблицы builder.StartTable(); //Добавление названий столбцов builder.InsertCell(); builder.Write("Идентификатор"); builder.InsertCell(); builder.Write("ИНН"); builder.InsertCell(); builder.Write("Краткое наименование абонента"); builder.InsertCell(); builder.Write("Полное наименование абонента"); builder.InsertCell(); builder.Write("Адрес абонента"); builder.InsertCell(); builder.Write("Телефоны абонента"); builder.InsertCell(); builder.Write("ФИО руководителя"); builder.InsertCell(); builder.Write("Представитель абонента"); builder.InsertCell(); builder.Write("Телефоны представителя"); builder.EndRow(); //Заполняем документ данными foreach (var subscriber in subscribers) { //Добавление ячеек с данными builder.InsertCell(); builder.Write(subscriber.Id.ToString()); builder.InsertCell(); builder.Write(subscriber.INN); builder.InsertCell(); builder.Write(subscriber.ShortName); builder.InsertCell(); builder.Write(subscriber.FullName); builder.InsertCell(); builder.Write(subscriber.Address); builder.InsertCell(); builder.Write(subscriber.Phones); builder.InsertCell(); builder.Write(subscriber.FIOHead); builder.InsertCell(); builder.Write(subscriber.SubscriberRepresentative); builder.InsertCell(); builder.Write(subscriber.RepresentativePhones); builder.EndRow(); } builder.EndTable(); MemoryStream outStream = new MemoryStream(); document.Save(outStream, SaveFormat.Pdf); return(Ok(outStream.ToArray())); }
/// <summary> /// Moving the current cursor position in the document using DocumentBuilder. /// </summary> /// <remarks> /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/documentbuilder-moving-cursor.php /// </remarks> static void MovingCursor() { DocumentCore dc = new DocumentCore(); DocumentBuilder db = new DocumentBuilder(dc); db.MoveToHeaderFooter(HeaderFooterType.HeaderDefault); db.Writeln("Moved the cursor to the header and inserted this text."); db.MoveToDocumentStart(); db.CharacterFormat.Size = 16; db.CharacterFormat.FontColor = Color.Blue; db.Writeln("Moved the cursor to the start of the document."); // Marks the current position in the document as a 1st bookmark start. db.StartBookmark("Firstbookmark"); db.CharacterFormat.Italic = true; db.CharacterFormat.Size = 14; db.CharacterFormat.FontColor = Color.Red; db.Writeln("The text inside the 'Bookmark' is inserted by the DocumentBuilder.Writeln method."); // Marks the current position in the document as a 1st bookmark end. db.EndBookmark("Firstbookmark"); db.MoveToBookmark("Firstbookmark", true, false); db.Writeln("Moved the cursor to the start of the Bookmark."); db.CharacterFormat.FontColor = Color.Black; Field f1 = db.InsertField("DATE"); db.MoveToField(f1, false); db.Write("Before the field"); // Moving to the Header and insert the table with three cells. db.MoveToHeaderFooter(HeaderFooterType.HeaderDefault); db.StartTable(); db.TableFormat.PreferredWidth = new TableWidth(LengthUnitConverter.Convert(6, LengthUnit.Inch, LengthUnit.Point), TableWidthUnit.Point); db.CellFormat.Borders.SetBorders(MultipleBorderTypes.Outside, BorderStyle.Single, Color.Green, 1); db.RowFormat.Height = new TableRowHeight(40, HeightRule.Exact); db.CharacterFormat.FontColor = Color.Green; db.CharacterFormat.Italic = false; db.InsertCell(); db.Write("This is Row 1 Cell 1"); db.InsertCell(); db.Write("This is Row 1 Cell 2"); db.InsertCell(); db.Write("This is Row 1 Cell 3"); db.EndTable(); // Insert the text in the second cell in the sixth position. db.MoveToCell(0, 0, 1, 5); db.CharacterFormat.Size = 18; db.CharacterFormat.FontColor = Color.Orange; db.Write("InsertToCell"); db.MoveToDocumentEnd(); db.CharacterFormat.Size = 16; db.CharacterFormat.FontColor = Color.Blue; db.Writeln("Moved the cursor to the end of the document."); // 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 }); }
public static void Main(string[] args) { Console.WriteLine("aaa"); Document document = new Document();//新建一个空白文档 //这里面的`builder`相当于一个画笔,提前给他规定样式, //然后他就能根据你的要求画出你想画的Word。这里的画笔使用的是就近原则, //当上面没有定义了builder的时候,会使用默认的格式,当上面定义了某个格式的时候, //使用最近的一个(即最后一个改变的样式) DocumentBuilder builder = new DocumentBuilder(document); builder.PageSetup.PaperSize = PaperSize.A4; //A4纸 builder.PageSetup.Orientation = Orientation.Portrait; //方向 builder.PageSetup.VerticalAlignment = PageVerticalAlignment.Top; //垂直对准 builder.PageSetup.LeftMargin = 42; //页面左边距 builder.PageSetup.RightMargin = 42; //页面右边距 //获取PargraphFormat对象,关于行的样式基本都在这里 var ph = builder.ParagraphFormat; //文字对齐方式 ph.Alignment = ParagraphAlignment.Center; //单行间距=12,1.5倍=18 ph.LineSpacing = 12; //获取font对象,关于文字大小,颜色,字体等等基本都在这个里面 Font font = builder.Font; //字体大小 font.Size = 22; //是否粗体 font.Bold = false; //下划线样式,None为无下划线 font.Underline = Underline.None; //字体颜色 font.Color = Color.Black; font.Color = Color.FromName("#3b3131");//自定义颜色 //设置字体 font.NameFarEast = "宋体"; //添加文字 builder.Write("添加的文字"); //添加回车 builder.Writeln(); //添加文字后回车 builder.Writeln("添加文字后回车"); //开始添加表格 Table table = builder.StartTable(); //开始添加第一行,并设置表格行高 RowFormat rowf = builder.RowFormat; rowf.Height = 40; //。。。这里rowf可以有很多的设置 //插入如一个单元格 builder.InsertCell(); //设置单元格是否水平合并,None为不合并 builder.CellFormat.HorizontalMerge = CellMerge.None; //设置单元格是否垂直合并,None为不合并 builder.CellFormat.VerticalMerge = CellMerge.None; //设置单元格宽 builder.CellFormat.Width = 40; //单元格垂直对齐方向 builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center; //单元格水平方向对齐 builder.ParagraphFormat.Alignment = ParagraphAlignment.Left; //单元格内文字设为多行(默认为单行,会影响单元格行宽) builder.CellFormat.FitText = true; //单元格内添加文字 builder.Write("这里是第一行第一个单元格"); builder.InsertCell(); //当不需要规定这个单元格的宽度的时候,设置称成-1,会是自动宽度 builder.CellFormat.Width = -1; builder.Write("这是第一行第二个单元格"); //结束第一行 builder.EndRow(); //结束表格 builder.EndTable(); //设置这个表格的上下左右,内部水平,垂直的线为白色(当背景为白色的时候就相当于隐藏边框了) table.SetBorder(BorderType.Left, LineStyle.Double, 1, Color.White, false); table.SetBorder(BorderType.Top, LineStyle.Double, 1, Color.White, false); table.SetBorder(BorderType.Right, LineStyle.Double, 1, Color.White, false); table.SetBorder(BorderType.Bottom, LineStyle.Double, 1, Color.White, false); table.SetBorder(BorderType.Vertical, LineStyle.Double, 1, Color.White, false); //横向合并单元格 builder.CellFormat.HorizontalMerge = CellMerge.None; builder.CellFormat.HorizontalMerge = CellMerge.First; builder.CellFormat.HorizontalMerge = CellMerge.Previous; //纵向合并单元格 builder.CellFormat.VerticalMerge = CellMerge.None; builder.CellFormat.VerticalMerge = CellMerge.First; builder.CellFormat.VerticalMerge = CellMerge.Previous; document.Save(@"C:\Users\DELL\Desktop\a.doc"); }
/// <summary> /// 查找报告中静载试验中应变或挠度汇总表格中的计算错误 /// </summary> /// <remarks> /// 要求:应变和挠度计算表格必须是单位报告模板格式 /// 算法:遍历应变或挠度检测结果汇总表,假定总变形、弹性变形及满载理论值计算正确,校核残余变形,校验系数及相对残余变形计算是否正确 /// 测点遍历算法:表格Rows[0].Cells[0]为"测点号",并且表格Rows[1].Cells[1]为"总应变"或"总变形" /// 表格遍历算法:从第3行到最后1行为Cells[1]=总变形,Cells[2]=弹性应变/变形,Cells[4]=满载理论值 /// 算法: /// 已知:总变形,弹性变形 /// 弹性变形=总变形-残余变形 /// 校验系数:弹性变形/理论变形 /// 相对残余变形:残余变形/总变形 /// TODO:读不出数据时的异常处理,要能定位出具体位置 /// </remarks> /// 算法主要参与人员:林迪南、陈思远 public void FindStrainOrDispError() { int row1, col1, row2, col2; string headerCharactorString, strainCharactorString, dispCharactorString; Regex regexHeader; try { //var xEle1 = xd.Element("configuration").Element("FindDescriptionError").Element("StrainCharactorString"); //MessageBox.Show(xEle1.Name.ToString()); //MessageBox.Show(xEle1.Attribute("version").Value); headerCharactorString = _config.Element("configuration").Element("FindStrainOrDispError").Attribute("charactorString").Value; row1 = Convert.ToInt32(_config.Element("configuration").Element("FindStrainOrDispError").Attribute("row1").Value); col1 = Convert.ToInt32(_config.Element("configuration").Element("FindStrainOrDispError").Attribute("col1").Value); row2 = Convert.ToInt32(_config.Element("configuration").Element("FindStrainOrDispError").Attribute("row2").Value); col2 = Convert.ToInt32(_config.Element("configuration").Element("FindStrainOrDispError").Attribute("col2").Value); strainCharactorString = _config.Element("configuration").Element("FindStrainOrDispError").Element("Strain").Attribute("charactorString").Value; dispCharactorString = _config.Element("configuration").Element("FindStrainOrDispError").Element("Disp").Attribute("charactorString").Value; } catch (Exception) { row1 = 0; col1 = 0; row2 = 1; col2 = 1; headerCharactorString = @"测点[号]?"; strainCharactorString = "总应变"; dispCharactorString = "总变形"; //TODO:增加条件编译的异常处理 } regexHeader = new Regex(headerCharactorString); int tableLastRow = 0; NodeCollection allTables = _originalDoc.GetChildNodes(NodeType.Table, true); for (int i = 0; i < allTables.Count; i++) { Table table0 = _originalDoc.GetChildNodes(NodeType.Table, true)[i] as Table; Table table1 = _doc.GetChildNodes(NodeType.Table, true)[i] as Table; //要写入批注的文档 if (regexHeader.Matches(table0.Rows[row1].Cells[col1].GetText()).Count > 0 && (table0.Rows[row2].Cells[col2].GetText().IndexOf(strainCharactorString) >= 0 || table0.Rows[row2].Cells[col2].GetText().IndexOf(dispCharactorString) >= 0)) { tableLastRow = table0.IndexOf(table0.LastRow); if (table0.Rows[table0.IndexOf(table0.LastRow)].Cells.Count <= 2) //最后1行单元格个数不超过2个 { tableLastRow = table0.IndexOf(table0.LastRow) - 1; } for (int j = 2; j < tableLastRow; j++) //TODO:增加最后行尾的判断 { try { var totalDeform = Convert.ToDecimal(table0.Rows[j].Cells[1].GetText().Trim().Replace("\a", "").Replace("\r", "")); var elasticDeform = Convert.ToDecimal(table0.Rows[j].Cells[2].GetText().Trim().Replace("\a", "").Replace("\r", "")); var remainDeform = Convert.ToDecimal(table0.Rows[j].Cells[3].GetText().Trim().Replace("\a", "").Replace("\r", "")); var theoryDeform = Convert.ToDecimal(table0.Rows[j].Cells[4].GetText().Trim().Replace("\a", "").Replace("\r", "")); var checkoutCoff = Convert.ToDecimal(table0.Rows[j].Cells[5].GetText().Trim().Replace("\a", "").Replace("\r", "")); decimal relRemainDeform; if (table0.Rows[j].Cells[6].GetText().IndexOf("%") >= 0) { relRemainDeform = Convert.ToDecimal(table0.Rows[j].Cells[6].GetText().Trim().Replace("\a", "").Replace("\r", "").Replace("%", "")) / 100; } else { relRemainDeform = Convert.ToDecimal(table0.Rows[j].Cells[6].GetText().Trim().Replace("\a", "").Replace("\r", "")) / 100; } var calcElasticDeform = totalDeform - remainDeform; var calcCheckoutCoff = Math.Round(calcElasticDeform / theoryDeform, 2); var calcRelRemainDeform = Math.Round(remainDeform / totalDeform, 4); if (calcElasticDeform != elasticDeform) { reportError.Add(new ReportError(ErrorNumber.Calc, $"第{i + 1}张表格", $"计算错误,应为{calcElasticDeform}", true)); Comment comment = new Comment(_doc, "AI", "AI校核", DateTime.Today); comment.Paragraphs.Add(new Paragraph(_doc)); comment.FirstParagraph.Runs.Add(new Run(_doc, $"计算错误,应为{calcElasticDeform}")); DocumentBuilder builder = new DocumentBuilder(_doc); builder.MoveTo(table1.Rows[j].Cells[2].FirstParagraph); builder.CurrentParagraph.AppendChild(comment); } if (calcCheckoutCoff != checkoutCoff) { reportError.Add(new ReportError(ErrorNumber.Calc, $"第{i + 1}张表格", $"计算错误,应为{calcCheckoutCoff}", true)); Comment comment = new Comment(_doc, "AI", "AI校核", DateTime.Today); comment.Paragraphs.Add(new Paragraph(_doc)); comment.FirstParagraph.Runs.Add(new Run(_doc, $"计算错误,应为{calcCheckoutCoff}")); DocumentBuilder builder = new DocumentBuilder(_doc); builder.MoveTo(table1.Rows[j].Cells[5].FirstParagraph); builder.CurrentParagraph.AppendChild(comment); } if (calcRelRemainDeform != relRemainDeform) { reportError.Add(new ReportError(ErrorNumber.Calc, $"第{i + 1}张表格", $"计算错误,应为{$"{calcRelRemainDeform:P}"}", true)); Comment comment = new Comment(_doc, "AI", "AI校核", DateTime.Today); comment.Paragraphs.Add(new Paragraph(_doc)); comment.FirstParagraph.Runs.Add(new Run(_doc, $"计算错误,应为{$"{calcRelRemainDeform:P}"}")); DocumentBuilder builder = new DocumentBuilder(_doc); builder.MoveTo(table1.Rows[j].Cells[6].FirstParagraph); builder.CurrentParagraph.AppendChild(comment); } } catch (Exception ex) { #if DEBUG throw ex; #else _log.Error(ex, $"FindDeformOrDispError函数第{i+1}张表格第{j+1}行数据读取出错,错误信息:{ ex.Message.ToString()}"); continue; //TODO:记录错误 #endif } } } } }
public static void Run() { // ExStart:CreateBookmark // The path to the documents directory. string dataDir = RunExamples.GetDataDir_WorkingWithBookmarks(); Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.StartBookmark("My Bookmark"); builder.Writeln("Text inside a bookmark."); builder.StartBookmark("Nested Bookmark"); builder.Writeln("Text inside a NestedBookmark."); builder.EndBookmark("Nested Bookmark"); builder.Writeln("Text after Nested Bookmark."); builder.EndBookmark("My Bookmark"); PdfSaveOptions options = new PdfSaveOptions(); options.OutlineOptions.BookmarksOutlineLevels.Add("My Bookmark", 1); options.OutlineOptions.BookmarksOutlineLevels.Add("Nested Bookmark", 2); dataDir = dataDir + "Create.Bookmark_out.pdf"; doc.Save(dataDir, options); // ExEnd:CreateBookmark Console.WriteLine("\nBookmark created successfully.\nFile saved at " + dataDir); }