Esempio n. 1
0
        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
        }
Esempio n. 2
0
        public void InsertNewColumnIntoTable()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Table.Document.doc");
            Table table = (Table)doc.GetChild(NodeType.Table, 1, true);

            //ExStart
            //ExId:InsertNewColumn
            //ExSummary:Shows how to insert a blank column into a table.
            // Get the second column in the table.
            Column column = Column.FromIndex(table, 1);

            // Create a new column to the left of this column.
            // This is the same as using the "Insert Column Before" command in Microsoft Word.
            Column newColumn = column.InsertColumnBefore();

            // Add some text to each of the column cells.
            foreach (Cell cell in newColumn.Cells)
                cell.FirstParagraph.AppendChild(new Run(doc, "Column Text " + newColumn.IndexOf(cell)));
            //ExEnd

            doc.Save(MyDir + "Table.InsertColumn Out.doc");

            Assert.AreEqual(24, table.GetChildNodes(NodeType.Cell, true).Count);
            Assert.AreEqual("Column Text 0", table.FirstRow.Cells[1].ToString(SaveFormat.Text).Trim());
            Assert.AreEqual("Column Text 3", table.LastRow.Cells[1].ToString(SaveFormat.Text).Trim());
        }
Esempio n. 3
0
        public void AddClonedRowToTable()
        {
            //ExStart
            //ExFor:Row
            //ExId:AddClonedRowToTable
            //ExSummary:Shows how to make a clone of the last row of a table and append it to the table.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Table.SimpleTable.doc");

            // Retrieve the first table in the document.
            Table table = (Table)doc.GetChild(NodeType.Table, 0, true);

            // Clone the last row in the table.
            Row clonedRow = (Row)table.LastRow.Clone(true);

            // Remove all content from the cloned row's cells. This makes the row ready for
            // new content to be inserted into.
            foreach (Cell cell in clonedRow.Cells)
                cell.RemoveAllChildren();

            // Add the row to the end of the table.
            table.AppendChild(clonedRow);

            doc.Save(ExDir + "Table.AddCloneRowToTable Out.doc");
            //ExEnd

            // Verify that the row was cloned and appended properly.
            Assert.AreEqual(5, table.Rows.Count);
            Assert.AreEqual(string.Empty, table.LastRow.ToString(SaveFormat.Text).Trim());
            Assert.AreEqual(2, table.LastRow.Cells.Count);
        }
Esempio n. 4
0
        public void InsertField()
        {
            //ExStart
            //ExFor:Paragraph.InsertField
            //ExSummary:Shows how to insert field using several methods: "field code", "field code and field value", "field code and field value after a run of text"
            Aspose.Words.Document doc = new Aspose.Words.Document();

            //Get the first paragraph of the document
            Paragraph para = doc.FirstSection.Body.FirstParagraph;

            //Inseting field using field code
            //Note: All methods support inserting field after some node. Just set "true" in the "isAfter" parameter
            para.InsertField(" AUTHOR ", null, false);

            //Using field type
            //Note:
            //1. For inserting field using field type, you can choose, update field before or after you open the document ("updateField" parameter)
            //2. For other methods it's works automatically
            para.InsertField(FieldType.FieldAuthor, false, null, true);

            //Using field code and field value
            para.InsertField(" AUTHOR ", "Test Field Value", null, false);

            //Add a run of text
            Run run = new Run(doc) { Text = " Hello World!" };
            para.AppendChild(run);

            //Using field code and field value before a run of text
            //Note: For inserting field before/after a run of text you can use all methods above, just add ref on your text ("refNode" parameter)
            para.InsertField(" AUTHOR ", "Test Field Value", run, false);
            //ExEnd
        }
Esempio n. 5
0
        public void ChangeTOCTabStops()
        {
            //ExStart
            //ExFor:TabStop
            //ExFor:ParagraphFormat.TabStops
            //ExFor:Style.StyleIdentifier
            //ExFor:TabStopCollection.RemoveByPosition
            //ExFor:TabStop.Alignment
            //ExFor:TabStop.Position
            //ExFor:TabStop.Leader
            //ExId:ChangeTOCTabStops
            //ExSummary:Shows how to modify the position of the right tab stop in TOC related paragraphs.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Document.TableOfContents.doc");

            // Iterate through all paragraphs in the document
            foreach (Paragraph para in doc.GetChildNodes(NodeType.Paragraph, true))
            {
                // Check if this paragraph is formatted using the TOC result based styles. This is any style between TOC and TOC9.
                if (para.ParagraphFormat.Style.StyleIdentifier >= StyleIdentifier.Toc1 && para.ParagraphFormat.Style.StyleIdentifier <= StyleIdentifier.Toc9)
                {
                    // Get the first tab used in this paragraph, this should be the tab used to align the page numbers.
                    TabStop tab = para.ParagraphFormat.TabStops[0];
                    // Remove the old tab from the collection.
                    para.ParagraphFormat.TabStops.RemoveByPosition(tab.Position);
                    // Insert a new tab using the same properties but at a modified position.
                    // We could also change the separators used (dots) by passing a different Leader type
                    para.ParagraphFormat.TabStops.Add(tab.Position - 50, tab.Alignment, tab.Leader);
                }
            }

            doc.Save(ExDir + "Document.TableOfContentsTabStops Out.doc");
            //ExEnd
        }
Esempio n. 6
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
        }
Esempio n. 7
0
        public void AddRemove()
        {
            //ExStart
            //ExFor:Document.Sections
            //ExFor:Section.Clone
            //ExFor:SectionCollection
            //ExFor:NodeCollection.RemoveAt(Int32)
            //ExSummary:Shows how to add/remove sections in a document.
            // Open the document.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Section.AddRemove.doc");

            // This shows what is in the document originally. The document has two sections.
            Console.WriteLine(doc.GetText());

            // Delete the first section from the document
            doc.Sections.RemoveAt(0);

            // Duplicate the last section and append the copy to the end of the document.
            int lastSectionIdx = doc.Sections.Count - 1;
            Aspose.Words.Section newSection = doc.Sections[lastSectionIdx].Clone();
            doc.Sections.Add(newSection);

            // Check what the document contains after we changed it.
            Console.WriteLine(doc.GetText());
            //ExEnd

            Assert.AreEqual("Hello2\x000cHello2\x000c", doc.GetText());
        }
        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
        }
Esempio n. 9
0
        public void BodyEnsureMinimum()
        {
            //ExStart
            //ExFor:Section.Body
            //ExFor:Body.EnsureMinimum
            //ExSummary:Clears main text from all sections from the document leaving the sections themselves.

            // Open a document.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Section.BodyEnsureMinimum.doc");

            // This shows what is in the document originally. The document has two sections.
            Console.WriteLine(doc.GetText());

            // Loop through all sections in the document.
            foreach (Aspose.Words.Section section in doc.Sections)
            {
                // Each section has a Body node that contains main story (main text) of the section.
                Body body = section.Body;

                // This clears all nodes from the body.
                body.RemoveAllChildren();

                // Technically speaking, for the main story of a section to be valid, it needs to have
                // at least one empty paragraph. That's what the EnsureMinimum method does.
                body.EnsureMinimum();
            }

            // Check how the content of the document looks now.
            Console.WriteLine(doc.GetText());
            //ExEnd

            Assert.AreEqual("\x000c\x000c", doc.GetText());
        }
        public void ReplaceHyperlinks()
        {
            // Specify your document name here.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "ReplaceHyperlinks.doc");

            // Hyperlinks in a Word documents are fields, select all field start nodes so we can find the hyperlinks.
            NodeList fieldStarts = doc.SelectNodes("//FieldStart");
            foreach (FieldStart fieldStart in fieldStarts)
            {
                if (fieldStart.FieldType.Equals(FieldType.FieldHyperlink))
                {
                    // The field is a hyperlink field, use the "facade" class to help to deal with the field.
                    Hyperlink hyperlink = new Hyperlink(fieldStart);

                    // Some hyperlinks can be local (links to bookmarks inside the document), ignore these.
                    if (hyperlink.IsLocal)
                        continue;

                    // The Hyperlink class allows to set the target URL and the display name
                    // of the link easily by setting the properties.
                    hyperlink.Target = NewUrl;
                    hyperlink.Name = NewName;
                }
            }

            doc.Save(ExDir + "ReplaceHyperlinks Out.doc");
        }
Esempio n. 11
0
        public void ExecuteDataReader()
        {
            //ExStart
            //ExFor:MailMerge.Execute(IDataReader)
            //ExSummary:Executes mail merge from an ADO.NET DataReader.
            // Open the template document
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "MailingLabelsDemo.doc");

            // Open the database connection.
            string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
                DatabaseDir + "Northwind.mdb";
            OleDbConnection conn = new OleDbConnection(connString);
            conn.Open();

            // Open the data reader.
            OleDbCommand cmd = new OleDbCommand(
                "SELECT TOP 50 * FROM Customers ORDER BY Country, CompanyName", conn);
            OleDbDataReader dataReader = cmd.ExecuteReader();

            // Perform the mail merge
            doc.MailMerge.Execute(dataReader);

            // Close database.
            dataReader.Close();
            conn.Close();

            doc.Save(MyDir + "MailMerge.ExecuteDataReader Out.doc");
            //ExEnd
        }
        /// <summary>
        /// 将Word文档转换为图片的方法(该方法基于第三方DLL),你可以像这样调用该方法:
        /// ConvertPDF2Image("F:\\PdfFile.doc", "F:\\", "ImageFile", 1, 20, ImageFormat.Png, 256);
        /// </summary>
        /// <param name="pdfInputPath">Word文件路径</param>
        /// <param name="imageOutputPath">图片输出路径,如果为空,默认值为Word所在路径</param>
        /// <param name="imageName">图片的名字,不需要带扩展名,如果为空,默认值为Word的名称</param>
        /// <param name="startPageNum">从PDF文档的第几页开始转换,如果为0,默认值为1</param>
        /// <param name="endPageNum">从PDF文档的第几页开始停止转换,如果为0,默认值为Word总页数</param>
        /// <param name="imageFormat">设置所需图片格式,如果为null,默认格式为PNG</param>
        /// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param>
        public static void ConvertWordToImage(string wordInputPath, string imageOutputPath,
            string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, float resolution)
        {
            try
            {
                // open word file
                Aspose.Words.Document doc = new Aspose.Words.Document(wordInputPath);

                // validate parameter
                if (doc == null) { throw new Exception("Word文件无效或者Word文件被加密!"); }
                if (imageOutputPath.Trim().Length == 0) { imageOutputPath = Path.GetDirectoryName(wordInputPath); }
                if (!Directory.Exists(imageOutputPath)) { Directory.CreateDirectory(imageOutputPath); }
                if (imageName.Trim().Length == 0) { imageName = Path.GetFileNameWithoutExtension(wordInputPath); }
                if (startPageNum <= 0) { startPageNum = 1; }
                if (endPageNum > doc.PageCount || endPageNum <= 0) { endPageNum = doc.PageCount; }
                if (startPageNum > endPageNum) { int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum; }
                if (imageFormat == null) { imageFormat = ImageFormat.Png; }
                if (resolution <= 0) { resolution = 128; }

                ImageSaveOptions imageSaveOptions = new ImageSaveOptions(GetSaveFormat(imageFormat));
                imageSaveOptions.Resolution = resolution;

                // start to convert each page
                for (int i = startPageNum; i <= endPageNum; i++)
                {
                    imageSaveOptions.PageIndex = i - 1;
                    doc.Save(Path.Combine(imageOutputPath, imageName) + "_" + i.ToString() + "." + imageFormat.ToString(), imageSaveOptions);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 13
0
        public void BookmarkNameAndText()
        {
            //ExStart
            //ExFor:Bookmark
            //ExFor:Bookmark.Name
            //ExFor:Bookmark.Text
            //ExFor:Range.Bookmarks
            //ExId:BookmarksGetNameSetText
            //ExSummary:Shows how to get or set bookmark name and text.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Bookmark.doc");

            // Use the indexer of the Bookmarks collection to obtain the desired bookmark.
            Aspose.Words.Bookmark bookmark = doc.Range.Bookmarks["MyBookmark"];

            // Get the name and text of the bookmark.
            string name = bookmark.Name;
            string text = bookmark.Text;

            // Set the name and text of the bookmark.
            bookmark.Name = "RenamedBookmark";
            bookmark.Text = "This is a new bookmarked text.";
            //ExEnd

            Assert.AreEqual("MyBookmark", name);
            Assert.AreEqual("This is a bookmarked text.", text);
        }
        //ExStart
        //ExId:MossRtf2Docx
        //ExSummary:Converts an RTF document to OOXML.
        public static void ConvertRtfToDocx(string inFileName, string outFileName)
        {
            // Load an RTF file into Aspose.Words.
            Aspose.Words.Document doc = new Aspose.Words.Document(inFileName);

            // Save the document in the OOXML format.
            doc.Save(outFileName, SaveFormat.Docx);
        }
Esempio n. 15
0
 public void RangesDeleteText()
 {
     //ExStart
     //ExId:RangesDeleteText
     //ExSummary:Shows how to delete all characters of a range.
     Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Document.doc");
     doc.Sections[0].Range.Delete();
     //ExEnd
 }
Esempio n. 16
0
 public void ChangeStyleOfTOCLevel()
 {
     Aspose.Words.Document doc = new Aspose.Words.Document();
     //ExStart
     //ExId:ChangeTOCStyle
     //ExSummary:Changes a formatting property used in the first level TOC style.
     // Retrieve the style used for the first level of the TOC and change the formatting of the style.
     doc.Styles[StyleIdentifier.Toc1].Font.Bold = true;
     //ExEnd
 }
Esempio n. 17
0
 public void AcceptAllRevisions()
 {
     //ExStart
     //ExFor:Document.AcceptAllRevisions
     //ExId:AcceptAllRevisions
     //ExSummary:Shows how to accept all tracking changes in the document.
     Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Document.doc");
     doc.AcceptAllRevisions();
     //ExEnd
 }
Esempio n. 18
0
 public void DeleteFields()
 {
     Aspose.Words.Document doc = new Aspose.Words.Document();
     //ExStart
     //ExFor:MailMerge.DeleteFields
     //ExId:MailMergeDeleteFields
     //ExSummary:Shows how to delete all merge fields from a document without executing mail merge.
     doc.MailMerge.DeleteFields();
     //ExEnd
 }
Esempio n. 19
0
 public void ClearFormattingEx()
 {
     //ExStart
     //ExFor:ClearFormatting
     //ExId:ClearFormattingEx
     //ExSummary:Shows how to use ClearFormatting.
     Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Document.doc");
     Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(doc);
     builder.Font.Border.ClearFormatting();
     //ExEnd
 }
Esempio n. 20
0
 public void FormFieldsGetFormFieldsCollection()
 {
     //ExStart
     //ExFor:Range.FormFields
     //ExFor:FormFieldCollection
     //ExId:FormFieldsGetFormFieldsCollection
     //ExSummary:Shows how to get a collection of form fields.
     Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "FormFields.doc");
     FormFieldCollection formFields = doc.Range.FormFields;
     //ExEnd
 }
        public void ClearFormattingEx()
        {
            //ExStart
            //ExFor:BorderCollection.ClearFormatting
            //ExSummary:Shows how to remove all borders from a paragraph at once.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Document.Borders.doc");
            DocumentBuilder builder = new DocumentBuilder(doc);
            BorderCollection borders = builder.ParagraphFormat.Borders;

            borders.ClearFormatting();
            //ExEnd
        }
Esempio n. 22
0
        public void SetTextEx()
        {
            //ExStart
            //ExFor:Comment.SetText
            //ExSummary:Shows how to use SetText.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Document.doc");
            DocumentBuilder builder = new DocumentBuilder(doc);

            Aspose.Words.Comment comment = new Aspose.Words.Comment(doc, "John Doe", "J.D.", DateTime.Now);
            builder.CurrentParagraph.AppendChild(comment);
            comment.SetText("My comment.");
            //ExEnd
        }
Esempio n. 23
0
        //ExStart
        //ExId:MailMergeAlternatingRows
        //ExSummary:Demonstrates how to implement custom logic in the MergeField event to apply cell formatting.
        public void MailMergeAlternatingRows()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "MailMerge.AlternatingRows.doc");

            // Add a handler for the MergeField event.
            doc.MailMerge.FieldMergingCallback = new HandleMergeFieldAlternatingRows();

            // Execute mail merge with regions.
            DataTable dataTable = GetSuppliersDataTable();
            doc.MailMerge.ExecuteWithRegions(dataTable);

            doc.Save(ExDir + "MailMerge.AlternatingRows Out.doc");
        }
Esempio n. 24
0
        public void ChangeTextToHyperlinks()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + @"Range.ChangeTextToHyperlinks.doc");

            // Create regular expression for URL search
            Regex regexUrl = new Regex(@"(?<Protocol>\w+):\/\/(?<Domain>[\w.]+\/?)\S*(?x)");

            // Run replacement, using regular expression and evaluator.
            doc.Range.Replace(regexUrl, new ChangeTextToHyperlinksEvaluator(doc), false);

            // Save updated document.
            doc.Save(MyDir + @"Range.ChangeTextToHyperlinks Out.docx");
        }
Esempio n. 25
0
        public void FormFieldsGetByName()
        {
            //ExStart
            //ExFor:FormField
            //ExId:FormFieldsGetByName
            //ExSummary:Shows how to access form fields.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "FormFields.doc");
            FormFieldCollection documentFormFields = doc.Range.FormFields;

            FormField formField1 = documentFormFields[3];
            FormField formField2 = documentFormFields["CustomerName"];
            //ExEnd
        }
Esempio n. 26
0
        public void EqualsEx()
        {
            //ExStart
            //ExFor:Equals
            //ExId:EqualsEx
            //ExSummary:Shows how to use Equals.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Document.doc");
            Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(doc);
            Aspose.Words.Border border1 = builder.Font.Border;
            Aspose.Words.Border border2 = builder.Font.Border;

            Console.WriteLine(border1.Equals(border2));
            //ExEnd
        }
Esempio n. 27
0
        public void InsertDocumentAtBookmark()
        {
            //ExStart
            //ExId:InsertDocumentAtBookmark
            //ExSummary:Invokes the InsertDocument method shown above to insert a document at a bookmark.
            Aspose.Words.Document mainDoc = new Aspose.Words.Document(ExDir + "InsertDocument1.doc");
            Aspose.Words.Document subDoc = new Aspose.Words.Document(ExDir + "InsertDocument2.doc");

            Aspose.Words.Bookmark bookmark = mainDoc.Range.Bookmarks["insertionPlace"];
            InsertDocument(bookmark.BookmarkStart.ParentNode, subDoc);

            mainDoc.Save(ExDir + "InsertDocumentAtBookmark Out.doc");
            //ExEnd
        }
Esempio n. 28
0
        public void InsertAndRetrieveFormFields()
        {
            //ExStart
            //ExFor:DocumentBuilder.InsertTextInput
            //ExId:FormFieldsInsertAndRetrieve
            //ExSummary:Shows how to insert form fields, set options and gather them back in for use
            Aspose.Words.Document doc = new Aspose.Words.Document();
            DocumentBuilder builder = new DocumentBuilder(doc);

            // Insert a text input field. The unique name of this field is "TextInput1", the other parameters define
            // what type of FormField it is, the format of the text, the field result and the maximum text length (0 = no limit)
            builder.InsertTextInput("TextInput1", TextFormFieldType.Regular, "", "", 0);
            //ExEnd
        }
Esempio n. 29
0
        public void AcceptAllRevisions()
        {
            //ExStart
            //ExFor:Document.AcceptAllRevisions
            //ExSummary:Shows how to accept all tracking changes in the document.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Document.doc");

            // Start tracking and make some revisions.
            doc.StartTrackRevisions("Author");
            doc.FirstSection.Body.AppendParagraph("Hello world!");

            // Revisions will now show up as normal text in the output document.
            doc.AcceptAllRevisions();
            doc.Save(MyDir + "Document.AcceptedRevisions.doc");
            //ExEnd
        }
        public void InsertImageFromByteArrayRelativePositionEx()
        {
            //ExStart
            //ExFor:DocumentBuilder.InsertImage(Byte[], RelativeHorizontalPosition, Double, RelativeVerticalPosition, Double, Double, Double, WrapType)
            //ExSummary:Shows how to import an image from a byte array into a document using relative positions.
            Aspose.Words.Document doc = new Aspose.Words.Document();
            DocumentBuilder builder = new DocumentBuilder();

            // Prepare a byte array of an image.
            System.Drawing.Image image = System.Drawing.Image.FromFile(ExDir + "Aspose.Words.gif");
            System.Drawing.ImageConverter imageConverter = new System.Drawing.ImageConverter();
            byte[] imageBytes = (byte[])imageConverter.ConvertTo(image, typeof(byte[]));

            builder.InsertImage(imageBytes, Aspose.Words.ConvertUtil.PixelToPoint(450), Aspose.Words.ConvertUtil.PixelToPoint(144));
            builder.Document.Save(ExDir + "Image.CreateFromByteArrayRelativePosition Out.doc");
            //ExEnd
        }
Esempio n. 31
0
        public void SetTableBordersOutline()
        {
            //ExStart
            //ExFor:Table.Alignment
            //ExFor:TableAlignment
            //ExFor:Table.ClearBorders
            //ExFor:Table.SetBorder
            //ExFor:TextureIndex
            //ExFor:Table.SetShading
            //ExId:TableBordersOutline
            //ExSummary:Shows how to apply a outline border to a table.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Table.EmptyTable.doc");
            Table table = (Table)doc.GetChild(NodeType.Table, 0, true);

            // Align the table to the center of the page.
            table.Alignment = TableAlignment.Center;

            // Clear any existing borders from the table.
            table.ClearBorders();

            // Set a green border around the table but not inside.
            table.SetBorder(BorderType.Left, LineStyle.Single, 1.5, Color.Green, true);
            table.SetBorder(BorderType.Right, LineStyle.Single, 1.5, Color.Green, true);
            table.SetBorder(BorderType.Top, LineStyle.Single, 1.5, Color.Green, true);
            table.SetBorder(BorderType.Bottom, LineStyle.Single, 1.5, Color.Green, true);

            // Fill the cells with a light green solid color.
            table.SetShading(TextureIndex.TextureSolid, Color.LightGreen, Color.Empty);

            doc.Save(MyDir + "Table.SetOutlineBorders Out.doc");
            //ExEnd

            // Verify the borders were set correctly.
            doc = new Aspose.Words.Document(MyDir + "Table.SetOutlineBorders Out.doc");
            Assert.AreEqual(TableAlignment.Center, table.Alignment);
            Assert.AreEqual(Color.Green.ToArgb(), table.FirstRow.RowFormat.Borders.Top.Color.ToArgb());
            Assert.AreEqual(Color.Green.ToArgb(), table.FirstRow.RowFormat.Borders.Left.Color.ToArgb());
            Assert.AreEqual(Color.Green.ToArgb(), table.FirstRow.RowFormat.Borders.Right.Color.ToArgb());
            Assert.AreEqual(Color.Green.ToArgb(), table.FirstRow.RowFormat.Borders.Bottom.Color.ToArgb());
            Assert.AreNotEqual(Color.Green.ToArgb(), table.FirstRow.RowFormat.Borders.Horizontal.Color.ToArgb());
            Assert.AreNotEqual(Color.Green.ToArgb(), table.FirstRow.RowFormat.Borders.Vertical.Color.ToArgb());
            Assert.AreEqual(Color.LightGreen.ToArgb(), table.FirstRow.FirstCell.CellFormat.Shading.ForegroundPatternColor.ToArgb());
        }
Esempio n. 32
0
        public void FixDefaultTableFormattingExceptionIn105()
        {
            //ExStart
            //ExId:FixTableFormattingException
            //ExSummary:Shows how to avoid encountering an exception when applying table formatting.
            Aspose.Words.Document doc     = new Aspose.Words.Document();
            DocumentBuilder       builder = new DocumentBuilder(doc);

            // Keep a reference to the table being built.
            Table table = builder.StartTable();

            // We must first insert a new cell which in turn inserts a row into the table.
            builder.InsertCell();
            // Once a row exists in our table we can apply table wide formatting.
            table.AllowAutoFit = true;

            // Continue with building your table as usual...
            //ExEnd
        }
Esempio n. 33
0
        public void SubsetFontsInPdf()
        {
            //ExStart
            //ExFor:PdfSaveOptions.EmbedFullFonts
            //ExId:Subset
            //ExSummary:Demonstrates how to set Aspose.Words to subset fonts in the output PDF.
            // Load the document to render.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Rendering.doc");

            // To subset fonts in the output PDF document, simply create new PdfSaveOptions and set EmbedFullFonts to false.
            PdfSaveOptions options = new PdfSaveOptions();

            options.EmbedFullFonts = false;

            // The output PDF will contain subsets of the fonts in the document. Only the glyphs used
            // in the document are included in the PDF fonts.
            doc.Save(MyDir + "Rendering.SubsetFonts Out.pdf");
            //ExEnd
        }
Esempio n. 34
0
        public void SaveToImageJpegQuality()
        {
            //ExStart
            //ExFor:ImageSaveOptions
            //ExFor:ImageSaveOptions.JpegQuality
            //ExSummary:Converts a page of a Word document into JPEG images of different qualities.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Rendering.doc");

            ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Jpeg);

            // Try worst quality.
            options.JpegQuality = 0;
            doc.Save(MyDir + "Rendering.SaveToImageJpegQuality0 Out.jpeg", options);

            // Try best quality.
            options.JpegQuality = 100;
            doc.Save(MyDir + "Rendering.SaveToImageJpegQuality100 Out.jpeg", options);
            //ExEnd
        }
Esempio n. 35
0
        public void SaveToPdfWithJpegImageCompression()
        {
            //ExStart
            //ExFor:PdfSaveOptions.ImageCompression
            //ExFor:PdfSaveOptions.JpegQuality
            //ExFor:PdfImageCompression
            //ExId:SaveToPdfJpegImageCompression
            //ExSummary:Demonstrates how to save images to PDF using JPEG encoding to decrease file size.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Rendering.doc");

            PdfSaveOptions options = new PdfSaveOptions();

            // Use JPEG compression at 50% quality to reduce file size.
            options.ImageCompression = PdfImageCompression.Jpeg;
            options.JpegQuality      = 50;

            doc.Save(MyDir + "Rendering.JpegImageCompression Out.pdf", options);
            //ExEnd
        }
Esempio n. 36
0
        public void FormFieldsWorkWithProperties()
        {
            //ExStart
            //ExFor:FormField
            //ExFor:FormField.Result
            //ExFor:FormField.Type
            //ExFor:FormField.Name
            //ExId:FormFieldsWorkWithProperties
            //ExSummary:Shows how to work with form field name, type, and result.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "FormFields.doc");

            FormField formField = doc.Range.FormFields[3];

            if (formField.Type.Equals(FieldType.FieldFormTextInput))
            {
                formField.Result = "My name is " + formField.Name;
            }
            //ExEnd
        }
Esempio n. 37
0
        public void CompositeNode_SelectNodes()
        {
            //ExStart
            //ExFor:CompositeNode.SelectSingleNode
            //ExFor:CompositeNode.SelectNodes
            //ExSummary:Shows how to select certain nodes by using an XPath expression.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Table.Document.doc");

            // This expression will extract all paragraph nodes which are descendants of any table node in the document.
            // This will return any paragraphs which are in a table.
            NodeList nodeList = doc.SelectNodes("//Table//Paragraph");

            // This expression will select any paragraphs that are direct children of any body node in the document.
            nodeList = doc.SelectNodes("//Body/Paragraph");

            // Use SelectSingleNode to select the first result of the same expression as above.
            Aspose.Words.Node node = doc.SelectSingleNode("//Body/Paragraph");
            //ExEnd
        }
Esempio n. 38
0
        public void MailMergeImageFromUrl()
        {
            //ExStart
            //ExFor:MailMerge.Execute(String[], Object[])
            //ExSummary:Demonstrates how to merge an image from a web address using an Image field.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "MailMerge.MergeImageSimple.doc");

            // Pass a URL which points to the image to merge into the document.
            doc.MailMerge.Execute(new string[] { "Logo" }, new object[] { "http://www.aspose.com/images/aspose-logo.gif" });

            doc.Save(MyDir + "MailMerge.MergeImageFromUrl Out.doc");
            //ExEnd

            // Verify the image was merged into the document.
            Shape logoImage = (Shape)doc.GetChild(NodeType.Shape, 0, true);

            Assert.IsNotNull(logoImage);
            Assert.IsTrue(logoImage.HasImage);
        }
Esempio n. 39
0
        //ExStart
        //ExFor:DocumentBuilder.InsertHtml(string)
        //ExFor:MailMerge.FieldMergingCallback
        //ExFor:IFieldMergingCallback
        //ExFor:FieldMergingArgs
        //ExFor:FieldMergingArgsBase.DocumentFieldName
        //ExFor:FieldMergingArgsBase.Document
        //ExFor:FieldMergingArgsBase.FieldValue
        //ExFor:IFieldMergingCallback.FieldMerging
        //ExFor:FieldMergingArgs.Text
        //ExSummary:Shows how to mail merge HTML data into a document.
        // File 'MailMerge.InsertHtml.doc' has merge field named 'htmlField1' in it.
        // File 'MailMerge.HtmlData.html' contains some valid Html data.
        // The same approach can be used when merging HTML data from database.
        public void MailMergeInsertHtml()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "MailMerge.InsertHtml.doc");

            // Add a handler for the MergeField event.
            doc.MailMerge.FieldMergingCallback = new HandleMergeFieldInsertHtml();

            // Load some Html from file.
            StreamReader sr       = File.OpenText(MyDir + "MailMerge.HtmlData.html");
            string       htmltext = sr.ReadToEnd();

            sr.Close();

            // Execute mail merge.
            doc.MailMerge.Execute(new string[] { "htmlField1" }, new string[] { htmltext });

            // Save resulting document with a new name.
            doc.Save(MyDir + "MailMerge.InsertHtml Out.doc");
        }
        public void SetPageColor()
        {
            //ExStart
            //ExFor:DocumentBase.PageColor
            //ExSummary:Shows how to set the background color for all pages of a document.
            Document        doc     = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);

            builder.Writeln("Hello world!");

            doc.PageColor = System.Drawing.Color.LightGray;

            doc.Save(ArtifactsDir + "DocumentBase.SetPageColor.docx");
            //ExEnd

            doc = new Document(ArtifactsDir + "DocumentBase.SetPageColor.docx");

            Assert.AreEqual(System.Drawing.Color.LightGray.ToArgb(), doc.PageColor.ToArgb());
        }
Esempio n. 41
0
        public void SplitTable()
        {
            //ExStart
            //ExId:SplitTableAtRow
            //ExSummary:Shows how to split a table into two tables a specific row.
            // Load the document.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Table.SimpleTable.doc");

            // Get the first table in the document.
            Table firstTable = (Table)doc.GetChild(NodeType.Table, 0, true);

            // We will split the table at the third row (inclusive).
            Row row = firstTable.Rows[2];

            // Create a new container for the split table.
            Table table = (Table)firstTable.Clone(false);

            // Insert the container after the original.
            firstTable.ParentNode.InsertAfter(table, firstTable);

            // Add a buffer paragraph to ensure the tables stay apart.
            firstTable.ParentNode.InsertAfter(new Paragraph(doc), firstTable);

            Row currentRow;

            do
            {
                currentRow = firstTable.LastRow;
                table.PrependChild(currentRow);
            }while (currentRow != row);

            doc.Save(MyDir + "Table.SplitTable Out.doc");
            //ExEnd

            doc = new Aspose.Words.Document(MyDir + "Table.SplitTable Out.doc");
            // Test we are adding the rows in the correct order and the
            // selected row was also moved.
            Assert.AreEqual(row, table.FirstRow);

            Assert.AreEqual(2, firstTable.Rows.Count);
            Assert.AreEqual(2, table.Rows.Count);
            Assert.AreEqual(2, doc.GetChildNodes(NodeType.Table, true).Count);
        }
Esempio n. 42
0
        /// <summary>
        ///导入简历
        /// </summary>
        /// <returns></returns>
        public ActionResult PutInWord()
        {
            try
            {
                Aspose.Words.Document doc = new Aspose.Words.Document();
                string   str = doc.ToTxt();
                string   s   = str.Replace("时    间:", "|").Replace("地    点:", "|").Replace("人员:", "|").Replace("主 持 人:", "|").Replace("议    程:", "|").Replace("领导:", "|");
                string[] st  = s.Split('|');
                //  赋值,保存方法
            }
            catch (Exception ex)
            {
                //ShowMessage("模板文件格式有误,请修改后重新导入");
                return(null);
            }


            return(View());
        }
Esempio n. 43
0
        [Test] //ExSkip
        public void ResourceLoadingCallback()
        {
            Document doc = new Document();

            doc.ResourceLoadingCallback = new ImageNameHandler();

            DocumentBuilder builder = new DocumentBuilder(doc);

            // Images usually are inserted using a URI, or a byte array.
            // Every instance of a resource load will call our callback's ResourceLoading method.
            builder.InsertImage("Google logo");
            builder.InsertImage("Aspose logo");
            builder.InsertImage("Watermark");

            Assert.AreEqual(3, doc.GetChildNodes(NodeType.Shape, true).Count);

            doc.Save(ArtifactsDir + "DocumentBase.ResourceLoadingCallback.docx");
            TestResourceLoadingCallback(new Document(ArtifactsDir + "DocumentBase.ResourceLoadingCallback.docx")); //ExSkip
        }
Esempio n. 44
0
 //将word文档转换成pdf
 public static string GetPdfFromWord(string soursefilepath, string scode)
 {
     //读取word文档
     try
     {
         using (System.IO.Stream stream = new System.IO.FileStream(soursefilepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
         {
             Aspose.Words.Document doc = new Aspose.Words.Document(soursefilepath);
             string htmlName           = scode + ".pdf";//Path.GetFileNameWithoutExtension(physicalPath)
             string outpdfpath         = AppDomain.CurrentDomain.BaseDirectory + "pdfjs\\pdf\\" + htmlName;
             doc.Save(outpdfpath, Aspose.Words.SaveFormat.Pdf);
             return(outpdfpath);
         }
     }
     catch (Exception ex)
     {
         return("error!" + ex.Message);
     }
 }
        public static Aspose.Words.Document GenerateDocument(Aspose.Words.Document srcDoc, ArrayList nodes)
        {
            // Create a blank document.
            Aspose.Words.Document dstDoc = new Aspose.Words.Document();
            // Remove the first paragraph from the empty document.
            dstDoc.FirstSection.Body.RemoveAllChildren();

            // Import each node from the list into the new document. Keep the original formatting of the node.
            NodeImporter importer = new NodeImporter(srcDoc, dstDoc, ImportFormatMode.KeepSourceFormatting);

            foreach (Node node in nodes)
            {
                Node importNode = importer.ImportNode(node, true);
                dstDoc.FirstSection.Body.AppendChild(importNode);
            }

            // Return the generated document.
            return(dstDoc);
        }
        public void SetPointColorsDynamically()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "ReportingEngine.SetPointColorDinamically.docx");

            List <ColorItemTestClass> colors = new List <ColorItemTestClass>
            {
                new ColorItemTestBuilder().WithColorCodeAndValues("Black", Color.Black.ToArgb(), 1.0, 2.5, 3.5).Build(),
                new ColorItemTestBuilder().WithColorCodeAndValues("Red", Color.Red.ToArgb(), 2.0, 4.0, 2.5).Build(),
                new ColorItemTestBuilder().WithColorCodeAndValues("Green", Color.Green.ToArgb(), 0.5, 1.5, 2.5).Build(),
                new ColorItemTestBuilder().WithColorCodeAndValues("Blue", Color.Blue.ToArgb(), 4.5, 3.5, 1.5).Build(),
                new ColorItemTestBuilder().WithColorCodeAndValues("Yellow", Color.Yellow.ToArgb(), 5.0, 2.5, 1.5).Build()
            };

            BuildReport(doc, colors, "colorItems", new [] { typeof(ColorItemTestClass) });

            doc.Save(MyDir + @"\Artifacts\ReportingEngine.SetPointColorDinamically.docx");

            Assert.IsTrue(DocumentHelper.CompareDocs(MyDir + @"\Artifacts\ReportingEngine.SetPointColorDinamically.docx", MyDir + @"\Golds\ReportingEngine.SetPointColorDinamically Gold.docx"));
        }
Esempio n. 47
0
        //aspose.word
        private void button7_Click(object sender, EventArgs e)
        {
            #region html插入word
            ////Document doc = new Document("temp.doc"); //使用模板 只有一个书签
            //Aspose.Words.Document doc = new Aspose.Words.Document();
            //DocumentBuilder builder = new DocumentBuilder(doc);
            ////builder.Font.Name = "宋体";
            //using (StreamReader reader = new StreamReader("苏州抵押合同模板.html")) //苏州抵押合同模板.html 苏州借款合同模板-3月.html
            //{
            //    string content = reader.ReadToEnd();
            //    //builder.MoveToBookmark("content");//如果设置了书签可以直接定位到书签处
            //    builder.InsertHtml(content, true);
            //    //doc.Range.Bookmarks.Clear();//清除书签

            //    doc.Save("苏州抵押合同模板.docx", Aspose.Words.SaveFormat.Docx);
            //    //doc.Save("苏州借款合同模板.doc");
            //}
            #endregion

            #region word模板变量填充

            string tempPath   = "contracttemp.doc";
            string outputPath = "templateout.doc";
            //载入模板
            var    doc  = new Aspose.Words.Document(tempPath);
            string name = doc.OriginalFileName;

            //提供数据源
            String[] fieldNames  = new String[] { "合同编号", "客户姓名", "借款人", "手机号码" };
            Object[] fieldValues = new Object[] { "HT001", "张三", "李四", "12345678900" };
            //合并模版,相当于页面的渲染
            doc.MailMerge.Execute(fieldNames, fieldValues);

            String[] fieldNames2  = new String[] { "车辆品牌", "车牌号码" };
            Object[] fieldValues2 = new Object[] { "蹦床", "苏E123456" };
            doc.MailMerge.Execute(fieldNames2, fieldValues2);

            //保存合并后的文档
            doc.Save(outputPath, Aspose.Words.SaveFormat.Doc);

            #endregion
        }
Esempio n. 48
0
        public void PreviewAndPrint()
        {
            //ExStart
            //ExFor:AsposeWordsPrintDocument
            //ExSummary:Shows the Print dialog that allows selecting the printer and page range to print with. Then brings up the print preview from which you can preview the document and choose to print or close.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Rendering.doc");

            PrintPreviewDialog previewDlg = new PrintPreviewDialog();

            // Show non-modal first is a hack for the print preview form to show on top.
            previewDlg.Show();

            // Initialize the Print Dialog with the number of pages in the document.
            PrintDialog printDlg = new PrintDialog();

            printDlg.AllowSomePages = true;
            printDlg.PrinterSettings.MinimumPage = 1;
            printDlg.PrinterSettings.MaximumPage = doc.PageCount;
            printDlg.PrinterSettings.FromPage    = 1;
            printDlg.PrinterSettings.ToPage      = doc.PageCount;

            if (!printDlg.ShowDialog().Equals(DialogResult.OK))
            {
                return;
            }

            // Create the Aspose.Words' implementation of the .NET print document
            // and pass the printer settings from the dialog to the print document.
            AsposeWordsPrintDocument awPrintDoc = new AsposeWordsPrintDocument(doc);

            awPrintDoc.PrinterSettings = printDlg.PrinterSettings;

            // Hide and invalidate preview is a hack for print preview to show on top.
            previewDlg.Hide();
            previewDlg.PrintPreviewControl.InvalidatePreview();

            // Pass the Aspose.Words' print document to the .NET Print Preview dialog.
            previewDlg.Document = awPrintDoc;

            previewDlg.ShowDialog();
            //ExEnd
        }
        public void ImportNodeCustom()
        {
            //ExStart
            //ExFor:DocumentBase.ImportNode(Node, System.Boolean, ImportFormatMode)
            //ExSummary:Shows how to import node from source document to destination document with specific options.
            // Create two documents and add a character style to each document.
            // Configure the styles to have the same name, but different text formatting.
            Document srcDoc   = new Document();
            Style    srcStyle = srcDoc.Styles.Add(StyleType.Character, "My style");

            srcStyle.Font.Name = "Courier New";
            DocumentBuilder srcBuilder = new DocumentBuilder(srcDoc);

            srcBuilder.Font.Style = srcStyle;
            srcBuilder.Writeln("Source document text.");

            Document dstDoc   = new Document();
            Style    dstStyle = dstDoc.Styles.Add(StyleType.Character, "My style");

            dstStyle.Font.Name = "Calibri";
            DocumentBuilder dstBuilder = new DocumentBuilder(dstDoc);

            dstBuilder.Font.Style = dstStyle;
            dstBuilder.Writeln("Destination document text.");

            // Import the Section from the destination document into the source document, causing a style name collision.
            // If we use destination styles, then the imported source text with the same style name
            // as destination text will adopt the destination style.
            Section importedSection = (Section)dstDoc.ImportNode(srcDoc.FirstSection, true, ImportFormatMode.UseDestinationStyles);

            Assert.AreEqual("Source document text.", importedSection.Body.Paragraphs[0].Runs[0].GetText().Trim()); //ExSkip
            Assert.IsNull(dstDoc.Styles["My style_0"]);                                                            //ExSkip
            Assert.AreEqual(dstStyle.Font.Name, importedSection.Body.FirstParagraph.Runs[0].Font.Name);
            Assert.AreEqual(dstStyle.Name, importedSection.Body.FirstParagraph.Runs[0].Font.StyleName);

            // If we use ImportFormatMode.KeepDifferentStyles, the source style is preserved,
            // and the naming clash resolves by adding a suffix.
            dstDoc.ImportNode(srcDoc.FirstSection, true, ImportFormatMode.KeepDifferentStyles);
            Assert.AreEqual(dstStyle.Font.Name, dstDoc.Styles["My style"].Font.Name);
            Assert.AreEqual(srcStyle.Font.Name, dstDoc.Styles["My style_0"].Font.Name);
            //ExEnd
        }
Esempio n. 50
0
        private void AddBodyAndSetData()
        {
            var jklcDocument = new Aspose.Words.Document(GetSroce("Tunnel.Word.ErchenFiles.二衬正文.doc"));
            //var jklcDocument = new Aspose.Words.Document(GetSroce("Tunnel.Word.TunnelMonthFiles.监控量测.docx"));
            var builder = new DocumentBuilder(jklcDocument);

            if (this._bodyModel != null)
            {
                WordManage.SetModel(this._bodyModel, jklcDocument, builder);
            }

            jklcDocument.UpdateFields();
            _coverCount = jklcDocument.PageCount - 2;
            _word.Document.AppendDocument(jklcDocument, ImportFormatMode.KeepSourceFormatting);

            SetEnclosure();
            builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
            WordManage.BookMarkReplace(_word.Document, builder, "totalPage", _coverCount.ToString());
            WordManage.BookMarkReplace(_word.Document, builder, "totalPage1", _coverCount.ToString());
        }
Esempio n. 51
0
        public void SaveToTiffCompression()
        {
            //ExStart
            //ExFor:TiffCompression
            //ExFor:ImageSaveOptions.TiffCompression
            //ExFor:ImageSaveOptions.PageIndex
            //ExFor:ImageSaveOptions.PageCount
            //ExFor:Document.Save(String, SaveOptions)
            //ExSummary:Converts a page of a Word document into a TIFF image and uses the CCITT compression.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Rendering.doc");

            ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Tiff);

            options.TiffCompression = TiffCompression.Ccitt3;
            options.PageIndex       = 0;
            options.PageCount       = 1;

            doc.Save(MyDir + "Rendering.SaveToTiffCompression Out.tiff", options);
            //ExEnd
        }
Esempio n. 52
0
        public void WithUpdateFields()
        {
            Document doc = DocumentHelper.CreateDocumentFillWithDummyText();

            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions {
                UpdateFields = true
            };

            doc.Save(MyDir + @"\Artifacts\UpdateFields_False.pdf", pdfSaveOptions);

            Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(MyDir + @"\Artifacts\UpdateFields_False.pdf");

            // Get text fragment by search String from PDF document
            TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("Page 1 of 2");

            pdfDocument.Pages.Accept(textFragmentAbsorber);

            // Assert that fields are updated
            Assert.AreEqual("Page 1 of 2", textFragmentAbsorber.TextFragments[1].Text);
        }
Esempio n. 53
0
        //ExStart
        //ExFor:Document.Accept
        //ExFor:Body.Accept
        //ExFor:DocumentVisitor
        //ExFor:DocumentVisitor.VisitRun
        //ExFor:DocumentVisitor.VisitFieldStart
        //ExFor:DocumentVisitor.VisitFieldEnd
        //ExFor:DocumentVisitor.VisitFieldSeparator
        //ExFor:DocumentVisitor.VisitBodyStart
        //ExFor:DocumentVisitor.VisitBodyEnd
        //ExFor:DocumentVisitor.VisitParagraphEnd
        //ExFor:DocumentVisitor.VisitHeaderFooterStart
        //ExFor:VisitorAction
        //ExId:ExtractContentDocToTxtConverter
        //ExSummary:Shows how to use the Visitor pattern to add new operations to the Aspose.Words object model. In this case we create a simple document converter into a text format.
        public void ToText()
        {
            // Open the document we want to convert.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Visitor.ToText.doc");

            // Create an object that inherits from the DocumentVisitor class.
            MyDocToTxtWriter myConverter = new MyDocToTxtWriter();

            // This is the well known Visitor pattern. Get the model to accept a visitor.
            // The model will iterate through itself by calling the corresponding methods
            // on the visitor object (this is called visiting).
            //
            // Note that every node in the object model has the Accept method so the visiting
            // can be executed not only for the whole document, but for any node in the document.
            doc.Accept(myConverter);

            // Once the visiting is complete, we can retrieve the result of the operation,
            // that in this example, has accumulated in the visitor.
            Console.WriteLine(myConverter.GetText());
        }
Esempio n. 54
0
        public static Stream ToPdfStream(Stream stream)
        {
            byte[] byteContent;

            using (MemoryStream ms = new MemoryStream())
            {
                stream.CopyTo(ms);
                byteContent = ms.ToArray();
            }

            Document     loadedFromBytes = new Document(new MemoryStream(byteContent));
            MemoryStream pdfStream       = new MemoryStream();

            loadedFromBytes.Save(pdfStream, new PdfSaveOptions {
                SaveFormat = SaveFormat.Pdf, Compliance = PdfCompliance.PdfA1b
            });
            byte[] pdfBytes = pdfStream.ToArray();

            return(new MemoryStream(pdfBytes));
        }
Esempio n. 55
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (this.FileUpload1.HasFile)
            {
                using (Stream stream = this.FileUpload1.PostedFile.InputStream)
                {
                    var doc = new Aspose.Words.Document(stream, this.FileUpload1.PostedFile.FileName);

                    var filePath = Page.MapPath("temp");
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }

                    var fileName = Path.Combine(filePath, Guid.NewGuid().ToString() + ".pdf");

                    doc.SaveToPdf(fileName);
                }
            }
        }
Esempio n. 56
0
        public void RemoveColumnFromTable()
        {
            //ExStart
            //ExId:RemoveTableColumn
            //ExSummary:Shows how to remove a column from a table in a document.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Table.Document.doc");
            Table table = (Table)doc.GetChild(NodeType.Table, 1, true);

            // Get the third column from the table and remove it.
            Column column = Column.FromIndex(table, 2);

            column.Remove();
            //ExEnd

            doc.Save(MyDir + "Table.RemoveColumn Out.doc");

            Assert.AreEqual(16, table.GetChildNodes(NodeType.Cell, true).Count);
            Assert.AreEqual("Cell 3 contents", table.Rows[2].Cells[2].ToString(SaveFormat.Text).Trim());
            Assert.AreEqual("Cell 3 contents", table.LastRow.Cells[2].ToString(SaveFormat.Text).Trim());
        }
Esempio n. 57
0
        public void ApplyNewListToParagraphs()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document();

            //ExStart
            //ExFor:Paragraph.ListFormat
            //ExFor:ListFormat.ListLevelNumber
            //ExFor:ListCollection.Add(ListTemplate)
            //ExSummary:Creates new list formatting and applies it to a collection of paragraphs.
            Aspose.Words.Lists.List list = doc.Lists.Add(ListTemplate.NumberUppercaseLetterDot);

            Body body = doc.FirstSection.Body;

            foreach (Paragraph paragraph in body.Paragraphs)
            {
                paragraph.ListFormat.List            = list;
                paragraph.ListFormat.ListLevelNumber = 1;
            }
            //ExEnd
        }
Esempio n. 58
0
        private void InsertWatermarkText(Aspose.Words.Document doc)
        {
            SetParagraphsBackgroundNoColor(doc);
            var watermark = SetWatermarkFormat(doc, m_waterMarkText);

            watermark.Width  = 500;
            watermark.Height = 100;
            //角度
            watermark.Rotation = m_rotation;

            Aspose.Words.Paragraph watermarkPara = new Aspose.Words.Paragraph(doc);
            watermarkPara.AppendChild(watermark);

            foreach (Aspose.Words.Section sect in doc.Sections)
            {
                InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderPrimary);
                InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderFirst);
                InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderEven);
            }
        }
Esempio n. 59
0
 /// <summary>
 /// 将Word转换为Pdf
 /// </summary>
 /// <param name="strFilePath">文件地址</param>
 /// <param name="savepath">保存地址</param>
 /// <returns></returns>
 public bool Word2Pdf(string strFilePath, string savepath, HttpResponse Response)
 {
     try
     {
         Aspose.Words.Document doc = new Aspose.Words.Document(strFilePath);
         //将Word保存到指定路径下 savepath:保存路径
         doc.Save(savepath, Aspose.Words.SaveFormat.Pdf);
         //将Word保存至数据流中 再通过Response显示在页面中
         MemoryStream memStream = new MemoryStream();
         doc.Save(memStream, Aspose.Words.SaveFormat.Pdf);
         byte[] bt = memStream.ToArray();
         Response.ContentType = "application/pdf";
         Response.OutputStream.Write(bt, 0, bt.Length);
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Esempio n. 60
0
        public static byte[] ReplaceParametersAndConvertToPdf(Aspose.Words.Document doc, Dictionary <string, string> variables)
        {
            foreach (var variable in variables)
            {
                string parameter = string.Format("@{0}@", variable.Key);
                string value     = string.IsNullOrEmpty(variable.Value) ? " " : variable.Value;
                int    result    = doc.Range.Replace(parameter, value, false, false);
                Log.InfoFormat("Replace {0} to {1} result: {2}", parameter, variable.Value, result);
            }

            foreach (Aspose.Words.Section section in doc.Sections)
            {
                section.PageSetup.PaperSize = PaperSize.A4;
            }

            MemoryStream ms     = new MemoryStream();
            var          output = doc.Save(ms, SaveFormat.Pdf);

            return(ms.ToArray());
        }