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());
        }
        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");
        }
Example #3
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
        }
        /// <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;
            }
        }
        //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);
        }
Example #6
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");
        }
        //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");
        }
Example #8
0
        /// <summary>
        /// 打印文档(图片)
        /// </summary>
        /// <param name="printName"></param>
        /// <param name="list"></param>
        /// <param name="documentName"></param>
        /// <returns></returns>
        public bool createdPrintDocument_img(string imgUrl, string filePathPara, string documentName, string printDocPath_save)
        {
            try
            {
                //if (!Directory.Exists(printDocPath_save)) Directory.CreateDirectory(printDocPath_save);
                ////产生要打印的文档
                ////使用特殊字符串替换
                //Aspose.Words.Document doc1 = new Aspose.Words.Document((filePathPara + documentName));
                //////var repStr = string.Format("&{0}&", "img");
                //////Regex reg = new Regex(repStr);
                //////string printValue = imgUrl;
                //////doc1.Range.Replace(reg, new ReplaceAndInsertImage(printValue), false);
                //Regex reg = new Regex("&头像&");
                //doc1.Range.Replace(reg, new ReplaceAndInsertImage(".//1.jpg"), false);

                ////doc1.Range.Replace("$a2$", UserInfo.Jgmc, false, false);
                //string filePath = string.Format("{0}{1}.doc", printDocPath_save, DateTime.Now.ToString("yyyyMMddhhmmssfff"));
                //doc1.Save(filePath);//也可以保存为1.doc 兼容03-07
                //printFilePathList.Add(filePath);



                var dic = new Dictionary <string, string>();
                dic.Add("img", ".//1.jpg");
                //使用特殊字符串替换
                Aspose.Words.Document doc = new Aspose.Words.Document((filePathPara + documentName));
                foreach (var key in dic.Keys)
                {
                    if (key != "img")
                    {
                        var repStr = string.Format("&{0}&", key);
                        doc.Range.Replace(repStr, dic[key], false, false);
                    }
                    else
                    {
                        Regex reg = new Regex("&img&");
                        doc.Range.Replace(reg, new ReplaceAndInsertImage(imgUrl), false);
                    }
                }
                string filePath = string.Format("{0}{1}.doc", printDocPath_save, DateTime.Now.ToString("yyyyMMddhhmmssfff"));
                doc.Save(filePath);//也可以保存为1.doc 兼容03-07
                printFilePathList.Add(filePath);
            }
            catch (Exception ex)
            {
                //return false;
                throw ex;
            }

            return(true);
        }
Example #9
0
        public void ImageCompression()
        {
            //ExStart
            //ExFor:PdfSaveOptions.Compliance
            //ExFor:PdfSaveOptions.ImageCompression
            //ExFor:PdfSaveOptions.JpegQuality
            //ExFor:PdfImageCompression
            //ExFor:PdfCompliance
            //ExSummary:Shows how to save images to PDF using JPEG encoding to decrease file size.
            Document doc = new Document(MyDir + "SaveOptions.PdfImageCompression.rtf");

            PdfSaveOptions options = new PdfSaveOptions
            {
                ImageCompression   = PdfImageCompression.Jpeg,
                PreserveFormFields = true
            };

            doc.Save(MyDir + @"\Artifacts\SaveOptions.PdfImageCompression.pdf", options);

            PdfSaveOptions optionsA1B = new PdfSaveOptions
            {
                Compliance       = PdfCompliance.PdfA1b,
                ImageCompression = PdfImageCompression.Jpeg,
                JpegQuality      = 50 // Use JPEG compression at 50% quality to reduce file size.
            };

            doc.Save(MyDir + @"\Artifacts\SaveOptions.PdfImageComppression PDF_A_1_B.pdf", optionsA1B);
            //ExEnd

            PdfSaveOptions optionsA1A = new PdfSaveOptions
            {
                Compliance = PdfCompliance.PdfA1a,
                ExportDocumentStructure = true,
                ImageCompression        = PdfImageCompression.Jpeg
            };

            doc.Save(MyDir + @"\Artifacts\SaveOptions.PdfImageComppression PDF_A_1_A.pdf", optionsA1A);
        }
        public void NumberFormat()
        {
            Aspose.Words.Document doc = DocumentHelper.CreateSimpleDocument("<<[s.Value1]:alphabetic>> : <<[s.Value2]:roman:lower>>, <<[s.Value3]:ordinal>>, <<[s.Value1]:ordinalText:upper>>" + ", <<[s.Value2]:cardinal>>, <<[s.Value3]:hex>>, <<[s.Value3]:arabicDash>>");

            NumericTestClass sender = new NumericTestBuilder().WithValuesAndDate(1, 2.2, 200, null, DateTime.Parse("10.09.2016 10:00:00")).Build();

            BuildReport(doc, sender, "s");

            MemoryStream dstStream = new MemoryStream();

            doc.Save(dstStream, SaveFormat.Docx);

            Assert.AreEqual("A : ii, 200th, FIRST, Two, C8, - 200 -\f", doc.GetText());
        }
Example #11
0
 /// <summary>
 /// word to pdf(此方法文件过大会有pdf内容不全的问题)
 /// ref:http://blog.51cto.com/xiaoshuaigege/1889700
 /// </summary>
 /// <param name="infile"></param>
 /// <param name="outfile"></param>
 /// <returns></returns>
 public static bool wordtopdf2(string infile, string outfile)
 {
     try
     {
         wrd.Document doc = new wrd.Document(infile);
         doc.Save(outfile, wrd.SaveFormat.Pdf);
         return(true);
     }
     catch (Exception ex)
     {
         copyto(infile);
         return(false);
     }
 }
Example #12
0
        public void ReplaceTextboxesWithImages()
        {
            //ExStart
            //ExFor:WrapSide
            //ExFor:ShapeBase.WrapSide
            //ExFor:NodeCollection
            //ExFor:CompositeNode.InsertAfter(Node, Node)
            //ExFor:NodeCollection.ToArray
            //ExSummary:Shows how to replace all textboxes with images.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Shape.ReplaceTextboxesWithImages.doc");

            // This gets a live collection of all shape nodes in the document.
            NodeCollection shapeCollection = doc.GetChildNodes(NodeType.Shape, true);

            // Since we will be adding/removing nodes, it is better to copy all collection
            // into a fixed size array, otherwise iterator will be invalidated.
            Aspose.Words.Node[] shapes = shapeCollection.ToArray();

            foreach (Shape shape in shapes)
            {
                // Filter out all shapes that we don't need.
                if (shape.ShapeType.Equals(ShapeType.TextBox))
                {
                    // Create a new shape that will replace the existing shape.
                    Shape image = new Shape(doc, ShapeType.Image);

                    // Load the image into the new shape.
                    image.ImageData.SetImage(MyDir + "Hammer.wmf");

                    // Make new shape's position to match the old shape.
                    image.Left   = shape.Left;
                    image.Top    = shape.Top;
                    image.Width  = shape.Width;
                    image.Height = shape.Height;
                    image.RelativeHorizontalPosition = shape.RelativeHorizontalPosition;
                    image.RelativeVerticalPosition   = shape.RelativeVerticalPosition;
                    image.HorizontalAlignment        = shape.HorizontalAlignment;
                    image.VerticalAlignment          = shape.VerticalAlignment;
                    image.WrapType = shape.WrapType;
                    image.WrapSide = shape.WrapSide;

                    // Insert new shape after the old shape and remove the old shape.
                    shape.ParentNode.InsertAfter(image, shape);
                    shape.Remove();
                }
            }

            doc.Save(MyDir + "Shape.ReplaceTextboxesWithImages Out.doc");
            //ExEnd
        }
Example #13
0
        public string SaveMarkDoc(string _fileName)
        {
            MemoryStream stream = new MemoryStream();

            document.RemoveEndMark();
            document.SaveAs(stream);
            stream.Position = 0;
            Aspose.Words.Document doc = new Aspose.Words.Document(stream);
            string fileName           = _fileName + "_" + DateTime.Now.ToString("yyyyMMddhhmmssfff");
            string filePath           = string.Format(@"{0}{1}.doc", this.configManager.getConfig("path.doc"), fileName);

            doc.Save(filePath, Aspose.Words.SaveFormat.Doc);
            return(filePath);
        }
Example #14
0
        static void word2Image()
        {
            string path = @"C:\Users\zhangzheng\Desktop\WMS方案设计相关.docx";

            Aspose.Words.Document document = new Aspose.Words.Document(path);

            ImageSaveOptions iso = new ImageSaveOptions(Aspose.Words.SaveFormat.Jpeg);

            iso.Resolution      = 128;
            iso.PrettyFormat    = true;
            iso.UseAntiAliasing = true;
            iso.PageIndex       = 0;
            document.Save("d:\\A\\word.jpg", iso);
        }
        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(MyDir + "InsertDocument1.doc");
            Aspose.Words.Document subDoc  = new Aspose.Words.Document(MyDir + "InsertDocument2.doc");

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

            mainDoc.Save(MyDir + "InsertDocumentAtBookmark Out.doc");
            //ExEnd
        }
        public void InsertImageDinamically()
        {
            Aspose.Words.Document template = DocumentHelper.CreateTemplateDocumentWithDrawObjects("<<image [src.Image]>>", ShapeType.TextBox);
#if NETSTANDARD2_0 || __MOBILE__
            ImageTestClass image = new ImageTestBuilder().WithImage(SKBitmap.Decode(mImage)).Build();
#else
            ImageTestClass image = new ImageTestBuilder().WithImage(Image.FromFile(this.mImage, true)).Build();
#endif

            BuildReport(template, image, "src", ReportBuildOptions.None);
            template.Save(MyDir + @"\Artifacts\ReportingEngine.InsertImageDinamically.docx");

            Assert.IsTrue(DocumentHelper.CompareDocs(MyDir + @"\Artifacts\ReportingEngine.InsertImageDinamically.docx", MyDir + @"\Golds\ReportingEngine.InsertImageDinamically(stream,doc,bytes) Gold.docx"), "Fail inserting document by bytes");
        }
Example #17
0
        private void CovertToPdf(string Destpath, string Sourcepath, Dictionary <GSS.FBU.CMAspose.DomainObject.DomainEnum.CMCustomStyleEnum, string> styles)
        {
            string fileName  = FileFrom.Text.Trim().Split('\\').Last().Split('.')[1];
            string extension = string.Empty;

            extension = fileName.Split('.').Last().ToLower();

            switch (extension)
            {
            case "xls":
            case "xlsx":
                FileStream      fsExcel   = new FileStream(Sourcepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                ExcelProcessing pdfStream = new ExcelProcessing(fsExcel);
                //底層設定客製化樣式
                pdfStream.SetCustomStyleProperty(styles);
                pdfStream.Convert2Pdf(Destpath);

                /* Workbook excelDocument = new Workbook(Sourcepath);
                 * excelDocument.Save(Destpath , Aspose.Cells.SaveFormat.Pdf);*/
                break;

            case "doc":
            case "docx":
                Aspose.Words.Document lDocDocument = new Aspose.Words.Document(Sourcepath);
                lDocDocument.Save(Destpath, Aspose.Words.SaveFormat.Pdf);
                break;

            case "tiff":
            case "tif":
            case "png":
            case "gif":
            case "jpeg":
            case "jpg":
            case "xpm":
                // Initialize new PDF document
                Aspose.Pdf.Document doc = new Aspose.Pdf.Document();
                // Add empty page in empty document
                Page             page  = doc.Pages.Add();
                Aspose.Pdf.Image image = new Aspose.Pdf.Image();
                image.File = (Sourcepath);
                // Add image on a page
                page.Paragraphs.Add(image);
                // Save output PDF file
                doc.Save(Destpath);
                break;

            default:
                break;
            }
        }
Example #18
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(MyDir + "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(MyDir + "MailMerge.AlternatingRows Out.doc");
        }
Example #19
0
        public static byte[] Get(string[] a, object[] b, string path, string content)
        {
            var doc = new Aspose.Words.Document(path);

            doc.MailMerge.Execute(a, b);
            DocumentBuilder builder = new DocumentBuilder(doc);

            builder.MoveToBookmark("content");
            builder.InsertHtml(content, true);
            var docStream = new System.IO.MemoryStream();

            doc.Save(docStream, Aspose.Words.Saving.SaveOptions.CreateSaveOptions(Aspose.Words.SaveFormat.Docx));
            return(docStream.ToArray());
        }
Example #20
0
        public void UpdateFieldsBeforeRendering()
        {
            //ExStart
            //ExFor:Document.UpdateFields
            //ExId:UpdateFieldsBeforeRendering
            //ExSummary:Shows how to update all fields before rendering a document.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Rendering.doc");

            // This updates all fields in the document.
            doc.UpdateFields();

            doc.Save(MyDir + "Rendering.UpdateFields Out.pdf");
            //ExEnd
        }
        public void StringFormat()
        {
            Aspose.Words.Document doc = DocumentHelper.CreateSimpleDocument("<<[s.Name]:lower>> says: <<[s.Message]:upper>>, <<[s.Message]:caps>>, <<[s.Message]:firstCap>>");

            MessageTestClass sender = new MessageTestClass("LINQ Reporting Engine", "hello world");

            BuildReport(doc, sender, "s");

            MemoryStream dstStream = new MemoryStream();

            doc.Save(dstStream, SaveFormat.Docx);

            Assert.AreEqual("linq reporting engine says: HELLO WORLD, Hello World, Hello world\f", doc.GetText());
        }
Example #22
0
        public void replaceWordStrToPicture(string filePath, List <string> picturesList, string imageServicePath)
        {
            Aspose.Words.Document doc = new Aspose.Words.Document(filePath);
            foreach (string pictruePath in picturesList)
            {
                string picfileName = imageServicePath + pictruePath.Replace("&", "");
                Regex  reg         = new Regex(pictruePath);
                doc.Range.Replace(reg, new ReplaceAndInsertImage(picfileName), false);
            }
            DocumentBuilder builder2 = new DocumentBuilder(doc);

            builder2.ParagraphFormat.Alignment = ParagraphAlignment.Center;
            doc.Save(filePath);
        }
Example #23
0
 public static bool CreatePDF(string soursePath, string savePath)
 {
     try
     {
         Aspose.Words.Document doc = new Aspose.Words.Document(soursePath);
         //保存PDF文件
         doc.Save(savePath);
         return(true);
     }
     catch (Exception ex)
     {
         return(false);
     }
 }
        //檢視自定範本
        private void linkViewGeDin_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ConfigData cd     = K12.Data.School.Configuration[_ReportName];
            XmlElement config = cd.GetXml("XmlData", null);

            if (config != null)
            {
                string templateBase64 = config.InnerText;
                byte[] _buffer        = Convert.FromBase64String(templateBase64);

                if (_buffer != null)
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Title    = "另存新檔";
                    sfd.FileName = "自訂學生晤談記錄表範本.docx";
                    sfd.Filter   = "Word檔案 (*.docx)|*.docx|所有檔案 (*.*)|*.*";
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        try
                        {
                            Aspose.Words.Document doc = new Aspose.Words.Document(new MemoryStream(_buffer));
                            doc.Save(sfd.FileName, Aspose.Words.SaveFormat.Docx);
                        }
                        catch (Exception ex)
                        {
                            MsgBox.Show("檔案無法儲存。" + ex.Message);
                            return;
                        }

                        try
                        {
                            System.Diagnostics.Process.Start(sfd.FileName);
                        }
                        catch (Exception ex)
                        {
                            MsgBox.Show("檔案無法開啟。" + ex.Message);
                            return;
                        }
                    }
                }
                else
                {
                    MsgBox.Show("無自訂範本");
                }
            }
            else
            {
                MsgBox.Show("無自訂範本\n請使用上傳功能上傳範本");
            }
        }
Example #25
0
        public static System.IO.MemoryStream FillStream(string templateFile, String[] fieldNames, Object[] fieldValues)
        {
            Document doc = new Aspose.Words.Document(templateFile);

            //DocumentBuilder builder = new Aspose.Words.DocumentBuilder(doc);


            //合并模版,相当于页面的渲染
            doc.MailMerge.Execute(fieldNames, fieldValues);

            System.IO.MemoryStream s = new System.IO.MemoryStream();
            doc.Save(s, Aspose.Words.SaveFormat.Doc);
            return(s);
        }
Example #26
0
        public void ConvertDocxToPdfWithAspose(string OpenedDocumentPath, string OpenedDocumentName)
        {
            GetDefaultPdfName(OpenedDocumentPath, OpenedDocumentName);

            if (_saveDialog.ShowDialog() == DialogResult.OK)
            {
                using (FileStream OpenedDocumentStream = new FileStream(OpenedDocumentPath + Path.DirectorySeparatorChar + OpenedDocumentName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    Words.Document WordDocument = new Words.Document(OpenedDocumentStream);
                    _saveAsPdfPath = _saveDialog.FileName;
                    WordDocument.Save(_saveAsPdfPath, Aspose.Words.SaveFormat.Pdf);
                }
            }
        }
        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
        }
        public void CreateMissingOutlineLevels()
        {
            //ExStart
            //ExFor:OutlineOptions.CreateMissingOutlineLevels
            //ExFor:ParagraphFormat.IsHeading
            //ExFor:PdfSaveOptions.OutlineOptions
            //ExFor:PdfSaveOptions.SaveFormat
            //ExSummary:Shows how to create missing outline levels saving the document in PDF.
            Document        doc     = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);

            // Creating TOC entries
            builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;
            Assert.True(builder.ParagraphFormat.IsHeading);

            builder.Writeln("Heading 1");

            builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading4;

            builder.Writeln("Heading 1.1.1.1");
            builder.Writeln("Heading 1.1.1.2");

            builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading9;

            builder.Writeln("Heading 1.1.1.1.1.1.1.1.1");
            builder.Writeln("Heading 1.1.1.1.1.1.1.1.2");

            // Create "PdfSaveOptions" with some mandatory parameters
            // "HeadingsOutlineLevels" specifies how many levels of headings to include in the document outline
            // "CreateMissingOutlineLevels" determining whether or not to create missing heading levels
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();

            pdfSaveOptions.OutlineOptions.HeadingsOutlineLevels      = 9;
            pdfSaveOptions.OutlineOptions.CreateMissingOutlineLevels = true;
            pdfSaveOptions.SaveFormat = SaveFormat.Pdf;

            doc.Save(ArtifactsDir + "CreateMissingOutlineLevels.pdf", pdfSaveOptions);
            //ExEnd

            #if NETFRAMEWORK || NETSTANDARD2_0
            // Bind PDF with Aspose.PDF
            PdfBookmarkEditor bookmarkEditor = new PdfBookmarkEditor();
            bookmarkEditor.BindPdf(ArtifactsDir + "CreateMissingOutlineLevels.pdf");

            // Get all bookmarks from the document
            Bookmarks bookmarks = bookmarkEditor.ExtractBookmarks();

            Assert.AreEqual(11, bookmarks.Count);
            #endif
        }
        public void SimpleCase()
        {
            Aspose.Words.Document doc = DocumentHelper.CreateSimpleDocument("<<[s.Name]>> says: <<[s.Message]>>");

            MessageTestClass sender = new MessageTestClass("LINQ Reporting Engine", "Hello World");

            BuildReport(doc, sender, "s", ReportBuildOptions.None);

            MemoryStream dstStream = new MemoryStream();

            doc.Save(dstStream, SaveFormat.Docx);

            Assert.AreEqual("LINQ Reporting Engine says: Hello World\f", doc.GetText());
        }
Example #30
0
        /// <summary>
        /// 将word文档保存到指定路径中,文档会根据是否添加重复率
        /// </summary>
        /// <param name="o">字典,包含完整文件名和重复率</param>
        public void SaveDocument(object o)
        {
            //将参数o里氏转换为所有的uctask
            DataGridViewRow myrow = o as DataGridViewRow;
            //获得文件名,保存路径,重复率,以及是否添加重复率的位置
            string filename  = myrow.Cells["wendangming"].Value.ToString();
            string chongfulv = myrow.Cells["chongfulv"].Value.ToString();

            /*如果重复率是100%,保存到100文件夹下,如果add的值是true,要拼接一个新的名称
             * 如果position在前,那么重复率放在前面,否则放在后面,然后保存新的文件名到指定路径中
             */
            string oldname = Path.GetFileNameWithoutExtension(filename);
            string newname = string.Empty;

            if (Setting._qian)
            {
                oldname = chongfulv + oldname;
            }
            if (Setting._hou)
            {
                oldname = oldname + chongfulv;
            }


            string newfilename = oldname + Path.GetExtension(filename);

            Aspose.Words.Document mydoc = new Aspose.Words.Document(filename);

            if (chongfulv.Equals("100.00%"))
            {
                mydoc.Save($"{Setting._savepath100}\\{newfilename}");
            }
            else
            {
                mydoc.Save($"{Setting._savepath}\\{newfilename}");
            }
        }
Example #31
0
        public ActionResult GetContractAdditionalTemplatePdf(Guid id, string contractAdditionTypeCode)
        {
            var       db     = new ncelsEntities();
            string    name   = "Договор_на_проведение_оценки_безопасности_и_качества.pdf";
            StiReport report = new StiReport();

            try
            {
                report.Load(obkRepo.GetContractAdditionalTemplatePath(id, contractAdditionTypeCode));
                foreach (var data in report.Dictionary.Databases.Items.OfType <StiSqlDatabase>())
                {
                    data.ConnectionString = UserHelper.GetCnString();
                }

                report.Dictionary.Variables["addContractNumber"].ValueObject = id;

                report.Render(false);
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error("ex: " + ex.Message + " \r\nstack: " + ex.StackTrace);
            }
            Stream stream = new MemoryStream();

            report.ExportDocument(StiExportFormat.Word2007, stream);
            stream.Position = 0;

            Aspose.Words.Document doc = new Aspose.Words.Document(stream);

            try
            {
                var signData = db.OBK_ContractSignedDatas.Where(x => x.ContractId == id).FirstOrDefault();
                if (signData != null && signData.ApplicantSign != null && signData.CeoSign != null)
                {
                    doc.InserQrCodesToEnd("ApplicantSign", signData.ApplicantSign);
                    doc.InserQrCodesToEnd("CeoSign", signData.CeoSign);
                }
            }
            catch (Exception ex)
            {
            }

            var file = new MemoryStream();

            doc.Save(file, Aspose.Words.SaveFormat.Pdf);
            file.Position = 0;

            return(new FileStreamResult(file, "application/pdf"));
        }
Example #32
0
        private void btnGenerateDoc_Click(object sender, EventArgs e)
        {
            string fileName    = string.Format("数据库设计文档.doc");
            string saveDocFile = FileDialogHelper.SaveWord(fileName, "C:\\");

            if (!string.IsNullOrEmpty(saveDocFile))
            {
                try
                {
                    #region 准备工作
                    Aspose.Words.Document doc = new Aspose.Words.Document();
                    doc.BuiltInDocumentProperties.Title         = "数据库设计说明书";
                    doc.BuiltInDocumentProperties.Keywords      = "数据库设计说明书";
                    doc.BuiltInDocumentProperties.CreatedTime   = DateTimeHelper.GetServerDateTime2();
                    doc.BuiltInDocumentProperties.LastSavedTime = DateTimeHelper.GetServerDateTime2();

                    Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(doc);
                    builder.PageSetup.PaperSize   = PaperSize.A4;
                    builder.PageSetup.Orientation = Aspose.Words.Orientation.Portrait;
                    builder.InsertParagraph();

                    Dictionary <string, string> tableList = new Dictionary <string, string>();
                    tableList.Add("TB_DictType", "数据字典类型基础表");
                    tableList.Add("TB_DictData", "数据字典项目基础表");
                    tableList.Add("TB_LoginLog", "用户登陆日志表");

                    int i = 1;
                    foreach (string key in tableList.Keys)
                    {
                        string description = string.Format("{0}({1})", key, tableList[key]);
                        GenerateTableData(doc, builder, i++, description);
                    }

                    #endregion

                    doc.Save(saveDocFile, SaveFormat.Doc);
                    if (MessageDxUtil.ShowYesNoAndTips("保存成功,是否打开文件?") == System.Windows.Forms.DialogResult.Yes)
                    {
                        System.Diagnostics.Process.Start(saveDocFile);
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, ex, typeof(FrmAsposeWords));
                    MessageDxUtil.ShowError(ex.Message);
                    return;
                }
            }
        }
Example #33
0
 public bool WordToPDF1(string sourcePath)
 {
     try
     {
         Aspose.Words.Document doc = new Aspose.Words.Document(sourcePath);
         string targetPath         = sourcePath.ToUpper().Replace(".DOCX", ".PDF");
         doc.Save(targetPath, SaveFormat.Pdf);
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
         return(false);
     }
     return(true);
 }
Example #34
0
        public void DrawingMl()
        {
            //ExStart
            //ExFor:DmlRenderingMode
            //ExFor:SaveOptions.DmlRenderingMode
            //ExSummary:Shows how to define rendering for DML shapes
            Document doc = DocumentHelper.CreateDocumentFillWithDummyText();

            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions {
                DmlRenderingMode = DmlRenderingMode.DrawingML
            };

            doc.Save(MyDir + @"\Artifacts\DrawingMl.pdf", pdfSaveOptions);
            //ExEnd
        }
//ExStart
//ExId:XpsPrint_PrintDocument
//ExSummary:Convert an Aspose.Words document into an XPS stream and print.
        /// <summary>
        /// Sends an Aspose.Words document to a printer using the XpsPrint API.
        /// </summary>
        /// <param name="document"></param>
        /// <param name="printerName"></param>
        /// <param name="jobName">Job name. Can be null.</param>
        /// <param name="isWait">True to wait for the job to complete. False to return immediately after submitting the job.</param>
        /// <exception cref="Exception">Thrown if any error occurs.</exception>
        public static void Print(Aspose.Words.Document document, string printerName, string jobName, bool isWait)
        {
            if (document == null)
            {
                throw new ArgumentNullException("document");
            }

            // Use Aspose.Words to convert the document to XPS and store in a memory stream.
            MemoryStream stream = new MemoryStream();

            document.Save(stream, SaveFormat.Xps);
            stream.Position = 0;

            Print(stream, printerName, jobName, isWait);
        }
Example #36
0
        public void ColorRendering()
        {
            //ExStart
            //ExFor:SaveOptions.ColorMode
            //ExSummary:Shows how change image color with save options property
            // Open document with color image
            Document doc = new Document(MyDir + "Rendering.doc");
            // Set grayscale mode for document
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions {
                ColorMode = ColorMode.Grayscale
            };

            doc.Save(MyDir + @"\Artifacts\ColorMode.PdfGrayscaleMode.pdf", pdfSaveOptions);
            //ExEnd
        }
Example #37
0
        //ExStart
        //ExFor:DocumentBuilder.MoveToMergeField(string)
        //ExFor:DocumentBuilder.InsertCheckBox
        //ExFor:FieldMergingArgsBase.FieldName
        //ExSummary:Shows how to insert checkbox form fields into a document during mail merge.
        // File 'MailMerge.InsertCheckBox.doc' is a template
        // containing the table with the following fields in it:
        // <<TableStart:StudentCourse>> <<CourseName>> <<TableEnd:StudentCourse>>.
        public void MailMergeInsertCheckBox()
        {
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "MailMerge.InsertCheckBox.doc");

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

            // Execute mail merge with regions.
            DataTable dataTable = GetStudentCourseDataTable();

            doc.MailMerge.ExecuteWithRegions(dataTable);

            // Save resulting document with a new name.
            doc.Save(MyDir + "MailMerge.InsertCheckBox Out.doc");
        }
Example #38
0
        public void MemoryOptimization()
        {
            //ExStart
            //ExFor:SaveOptions.MemoryOptimization
            //ExSummary:Shows an option to optimize memory consumption when you work with large documents.
            Document doc = new Document(MyDir + "SaveOptions.MemoryOptimization.doc");
            // When set to true it will improve document memory footprint but will add extra time to processing.
            // This optimization is only applied during save operation.
            SaveOptions saveOptions = SaveOptions.CreateSaveOptions(SaveFormat.Pdf);

            saveOptions.MemoryOptimization = true;

            doc.Save(MyDir + @"\Artifacts\SaveOptions.MemoryOptimization.pdf", saveOptions);
            //ExEnd
        }
Example #39
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
        }
 /// <summary>
 /// Convert the documents into images
 /// </summary>
 /// <param name="sourcePath"></param>
 /// <param name="targetPath">Path were the documents were generated</param>
 /// <param name="currentPage"></param>
 /// <param name="originalDocumentName"></param>
 /// <returns></returns>
 public int Process(string sourcePath, string targetPath, int currentPage, string originalDocumentName, int qualitySet)
 {
     var qSet = new QualitySet();
     var doc = new Aspose.Words.Document(sourcePath);
     var targetFileName = targetPath.PathSplit();
     var targetFileExt = targetFileName[targetFileName.Length - 1].Split('.');
     var options = new Aspose.Words.Saving.ImageSaveOptions(SaveFormat.Jpeg)
                   {
                       PageCount = 1,
                       PageIndex = currentPage - 1,
                       Resolution = qSet.Get(qualitySet).Resolution,
                       JpegQuality = qSet.Get(qualitySet).Quality
                   };
     var targetImage = targetPath.Replace("." + targetFileExt[targetFileExt.Length - 1], string.Empty) + currentPage + ConfigurationManager.AppSettings["ImageExtension"];
     doc.Save(targetImage, options);
     return doc.PageCount;
 }
        //ExStart
        //ExFor:CompositeNode.HasChildNodes
        //ExId:InsertDocumentAtMailMerge
        //ExSummary:Demonstrates how to use the InsertDocument method to insert a document into a merge field during mail merge.
        public void InsertDocumentAtMailMerge()
        {
            // Open the main document.
            Aspose.Words.Document mainDoc = new Aspose.Words.Document(ExDir + "InsertDocument1.doc");

            // Add a handler to MergeField event
            mainDoc.MailMerge.FieldMergingCallback = new InsertDocumentAtMailMergeHandler();

            // The main document has a merge field in it called "Document_1".
            // The corresponding data for this field contains fully qualified path to the document
            // that should be inserted to this field.
            mainDoc.MailMerge.Execute(
                new string[] { "Document_1" },
                new string[] { ExDir + "InsertDocument2.doc" });

            mainDoc.Save(ExDir + "InsertDocumentAtMailMerge Out.doc");
        }
Example #42
0
        public void ClearFormattingEx()
        {
            //ExStart
            //ExFor:Border.ClearFormatting
            //ExSummary:Shows how to remove borders from a paragraph one by one.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Document.Borders.doc");
            DocumentBuilder builder = new DocumentBuilder(doc);
            BorderCollection borders = builder.ParagraphFormat.Borders;

            foreach (Aspose.Words.Border border in borders)
            {
                border.ClearFormatting();
            }

            builder.CurrentParagraph.Runs[0].Text = "Paragraph with no border";
            doc.Save(MyDir + "Document.NoBorder.doc");
            //ExEnd
        }
        public void RenameMergeFields()
        {
            // Specify your document name here.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "RenameMergeFields.doc");

            // Select all field start nodes so we can find the merge fields.
            NodeCollection fieldStarts = doc.GetChildNodes(NodeType.FieldStart, true);
            foreach (FieldStart fieldStart in fieldStarts)
            {
                if (fieldStart.FieldType.Equals(FieldType.FieldMergeField))
                {
                    MergeField mergeField = new MergeField(fieldStart);
                    mergeField.Name = mergeField.Name + "_Renamed";
                }
            }

            doc.Save(MyDir + "RenameMergeFields Out.doc");
        }
Example #44
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());
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="sourcePath"></param>
 /// <param name="targetPath"></param>
 /// <param name="currentPage"></param>
 /// <param name="originalDocumentName"></param>
 /// <returns></returns>
 public int Process(string sourcePath, string targetPath, int currentPage, string originalDocumentName, int qualitySet)
 {
     var msg = MailMessage.Load(sourcePath, MailMessageLoadOptions.DefaultMsg);
     var targetFileName = targetPath.PathSplit();
     var targetFileExt = targetFileName[targetFileName.Length - 1].Split('.');
     var ms = new MemoryStream();
     msg.Save(ms, MailMessageSaveType.MHtmlFromat);
     var loadOptions = new LoadOptions { LoadFormat = (LoadFormat)Aspose.Cells.LoadFormat.MHtml };
     var document = new Aspose.Words.Document(ms, loadOptions);
     var qSet = new QualitySet();
     var options = new Aspose.Words.Saving.ImageSaveOptions(SaveFormat.Jpeg)
     {
         PageCount = 1,
         PageIndex = currentPage - 1,
         Resolution = qSet.Get(qualitySet).VerticalResolution,
         JpegQuality = qSet.Get(qualitySet).Quality
     };
     var targetImage = targetPath.Replace("." + targetFileExt[targetFileExt.Length - 1], string.Empty) + currentPage + ConfigurationManager.AppSettings["ImageExtension"];
     document.Save(targetImage, options);
     return document.PageCount;
 }
        public void GetEnumeratorEx()
        {
            //ExStart
            //ExFor:BorderCollection.GetEnumerator
            //ExSummary:Shows how to enumerate all borders in a collection.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "Document.Borders.doc");
            DocumentBuilder builder = new DocumentBuilder(doc);
            BorderCollection borders = builder.ParagraphFormat.Borders;

            var enumerator = borders.GetEnumerator();
            while (enumerator.MoveNext())
            {
                // Do something useful.
                Aspose.Words.Border b = (Aspose.Words.Border)enumerator.Current;
                b.Color = System.Drawing.Color.RoyalBlue;
                b.LineStyle = LineStyle.Double;
            }

            doc.Save(MyDir + "Document.ChangedColourBorder.doc");
            //ExEnd
        }
        public void CreateFooter()
        {
            //ExStart
            //ExFor:HeaderFooter
            //ExFor:HeaderFooter.#ctor(DocumentBase, HeaderFooterType)
            //ExFor:HeaderFooterCollection
            //ExFor:Story.AppendParagraph
            //ExSummary:Creates a footer using the document object model and inserts it into a section.
            Aspose.Words.Document doc = new Aspose.Words.Document();

            Aspose.Words.HeaderFooter footer = new Aspose.Words.HeaderFooter(doc, HeaderFooterType.FooterPrimary);
            doc.FirstSection.HeadersFooters.Add(footer);

            // Add a paragraph with text to the footer.
            footer.AppendParagraph("TEST FOOTER");

            doc.Save(ExDir + "HeaderFooter.CreateFooter Out.doc");
            //ExEnd

            doc = new Aspose.Words.Document(ExDir + "HeaderFooter.CreateFooter Out.doc");
            Assert.True(doc.FirstSection.HeadersFooters[HeaderFooterType.FooterPrimary].Range.Text.Contains("TEST FOOTER"));
        }
Example #48
0
        public void ExecuteArray()
        {
            HttpResponse Response = null;

            //ExStart
            //ExFor:MailMerge.Execute(String[],Object[])
            //ExFor:ContentDisposition
            //ExFor:Document.Save(HttpResponse,String,ContentDisposition,SaveOptions)
            //ExId:MailMergeArray
            //ExSummary:Performs a simple insertion of data into merge fields and sends the document to the browser inline.
            // Open an existing document.
            Aspose.Words.Document doc = new Aspose.Words.Document(MyDir + "MailMerge.ExecuteArray.doc");

            // Fill the fields in the document with user data.
            doc.MailMerge.Execute(
                new string[] {"FullName", "Company", "Address", "Address2", "City"},
                new object[] {"James Bond", "MI5 Headquarters", "Milbank", "", "London"});

            // Send the document in Word format to the client browser with an option to save to disk or open inside the current browser.
            doc.Save(Response, "MailMerge.ExecuteArray Out.doc", ContentDisposition.Inline, null);
            //ExEnd
        }
        public void UseEncoding()
        {
            //ExStart
            //ExFor:Saving.HtmlFixedSaveOptions.Encoding
            //ExSummary:Shows how to use "Encoding" parameter with "HtmlFixedSaveOptions"
            Aspose.Words.Document doc = new Aspose.Words.Document();

            DocumentBuilder builder = new DocumentBuilder(doc);
            builder.Writeln("Hello World!");

            //Create "HtmlFixedSaveOptions" with "Encoding" parameter
            //You can also set "Encoding" using System.Text.Encoding, like "Encoding.ASCII", or "Encoding.GetEncoding()"
            HtmlFixedSaveOptions htmlFixedSaveOptions = new HtmlFixedSaveOptions
            {
                Encoding = new ASCIIEncoding(),
                SaveFormat = SaveFormat.HtmlFixed,
            };

            //Uses "HtmlFixedSaveOptions"
            doc.Save(MyDir + "UseEncoding.html", htmlFixedSaveOptions);
            //ExEnd
        }
        public void CreateMissingOutlineLevels()
        {
            //ExStart
            //ExFor:Saving.PdfSaveOptions.OutlineOptions.CreateMissingOutlineLevels
            //ExSummary:Shows how to create missing outline levels saving the document in pdf
            Aspose.Words.Document doc = new Aspose.Words.Document();

            DocumentBuilder builder = new DocumentBuilder(doc);

            // Creating TOC entries
            builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;

            builder.Writeln("Heading 1");

            builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading4;

            builder.Writeln("Heading 1.1.1.1");
            builder.Writeln("Heading 1.1.1.2");

            builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading9;

            builder.Writeln("Heading 1.1.1.1.1.1.1.1.1");
            builder.Writeln("Heading 1.1.1.1.1.1.1.1.2");

            //Create "PdfSaveOptions" with some mandatory parameters
            //"HeadingsOutlineLevels" specifies how many levels of headings to include in the document outline
            //"CreateMissingOutlineLevels" determining whether or not to create missing heading levels
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();

            pdfSaveOptions.OutlineOptions.HeadingsOutlineLevels = 9;
            pdfSaveOptions.OutlineOptions.CreateMissingOutlineLevels = true;
            pdfSaveOptions.SaveFormat = SaveFormat.Pdf;

            doc.Save(ExDir + "CreateMissingOutlineLevels.pdf", pdfSaveOptions);
            //ExEnd
        }
Example #51
0
        public void ChangeLocale()
        {
            // Create a blank document.
            Aspose.Words.Document doc = new Aspose.Words.Document();
            DocumentBuilder b = new DocumentBuilder(doc);
            b.InsertField("MERGEFIELD Date");

            //ExStart
            //ExId:ChangeCurrentCulture
            //ExSummary:Shows how to change the culture used in formatting fields during update.
            // Store the current culture so it can be set back once mail merge is complete.
            CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
            // Set to German language so dates and numbers are formatted using this culture during mail merge.
            Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");

            // Execute mail merge.
            doc.MailMerge.Execute(new string[] { "Date" }, new object[] { DateTime.Now });

            // Restore the original culture.
            Thread.CurrentThread.CurrentCulture = currentCulture;
            //ExEnd

            doc.Save(ExDir + "Field.ChangeLocale Out.doc");
        }
Example #52
0
        public void ChangeStyleIdentifier()
        {
            //ExStart
            //ExFor:Font.StyleIdentifier
            //ExFor:StyleIdentifier
            //ExSummary:Shows how to use style identifier to find text formatted with a specific character style and apply different character style.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Font.StyleIdentifier.doc");

            // Select all run nodes in the document.
            NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);

            // Loop through every run node.
            foreach (Run run in runs)
            {
                // If the character style of the run is what we want, do what we need. Change the style in this case.
                // Note that using StyleIdentifier we can identify a built-in style regardless
                // of the language of Microsoft Word used to create the document.
                if (run.Font.StyleIdentifier.Equals(StyleIdentifier.Emphasis))
                    run.Font.StyleIdentifier = StyleIdentifier.Strong;
            }

            doc.Save(ExDir + "Font.StyleIdentifier Out.doc");
            //ExEnd
        }
        private void InDuLieu()
        {
            Aspose.Words.License license = new Aspose.Words.License();
            license.SetLicense("Aspose.Words.lic");

            //Open template
            string path = Context.Server.MapPath("~/DesktopModules/TrainingCoreBanking/BankProject/Report/Template/NormalLC/MT700.doc");
            //Open the template document
            Aspose.Words.Document doc = new Aspose.Words.Document(path);
            //Execute the mail merge.
            DataSet ds = new DataSet();
            ds = DataProvider.KhanhND.B_BNORMAILLC_Print(tbEssurLCCode.Text);

            // Fill the fields in the document with user data.
            doc.MailMerge.ExecuteWithRegions(ds); //moas mat thoi jan voi cuc gach nay woa

            // Send the document in Word format to the client browser with an option to save to disk or open inside the current browser.

            doc.Save("MT700_" + DateTime.Now.ToString("dd_MM_yyyy_hh_mm_ss") + ".doc", Aspose.Words.SaveFormat.Doc, Aspose.Words.SaveType.OpenInBrowser, Response);
        }
Example #54
0
        //ExStart
        //ExFor:Font.Hidden
        //ExFor:Paragraph.Accept
        //ExFor:DocumentVisitor.VisitParagraphStart(Aspose.Words.Paragraph)
        //ExFor:DocumentVisitor.VisitFormField(Aspose.Words.Fields.FormField)
        //ExFor:DocumentVisitor.VisitTableEnd(Aspose.Words.Tables.Table)
        //ExFor:DocumentVisitor.VisitCellEnd(Aspose.Words.Tables.Cell)
        //ExFor:DocumentVisitor.VisitRowEnd(Aspose.Words.Tables.Row)
        //ExFor:DocumentVisitor.VisitSpecialChar(Aspose.Words.SpecialChar)
        //ExFor:DocumentVisitor.VisitGroupShapeStart(Aspose.Words.Drawing.GroupShape)
        //ExFor:DocumentVisitor.VisitShapeStart(Aspose.Words.Drawing.Shape)
        //ExFor:DocumentVisitor.VisitCommentStart(Aspose.Words.Comment)
        //ExFor:DocumentVisitor.VisitFootnoteStart(Aspose.Words.Footnote)
        //ExFor:SpecialChar
        //ExFor:Node.Accept
        //ExFor:Paragraph.ParagraphBreakFont
        //ExFor:Table.Accept
        //ExSummary:Implements the Visitor Pattern to remove all content formatted as hidden from the document.
        public void RemoveHiddenContentFromDocument()
        {
            // Open the document we want to remove hidden content from.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Font.Hidden.doc");

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

            // 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).

            // We can run it over the entire the document like so:
            doc.Accept(hiddenContentRemover);

            // Or we can run it on only a specific node.
            Paragraph para = (Paragraph)doc.GetChild(NodeType.Paragraph, 4, true);
            para.Accept(hiddenContentRemover);

            // Or over a different type of node like below.
            Table table = (Table)doc.GetChild(NodeType.Table, 0, true);
            table.Accept(hiddenContentRemover);

            doc.Save(ExDir + "Font.Hidden Out.doc");

            Assert.AreEqual(13, doc.GetChildNodes(NodeType.Paragraph, true).Count); //ExSkip
            Assert.AreEqual(1, doc.GetChildNodes(NodeType.Table, true).Count); //ExSkip
        }
Example #55
0
        public void ChangeStyleName()
        {
            //ExStart
            //ExFor:Font.StyleName
            //ExSummary:Shows how to use style name to find text formatted with a specific character style and apply different character style.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Font.StyleName.doc");

            // Select all run nodes in the document.
            NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);

            // Loop through every run node.
            foreach (Run run in runs)
            {
                // If the character style of the run is what we want, do what we need. Change the style in this case.
                // Note that names of built in styles could be different in documents
                // created by Microsoft Word versions for different languages.
                if (run.Font.StyleName.Equals("Emphasis"))
                    run.Font.StyleName = "Strong";
            }

            doc.Save(ExDir + "Font.StyleName Out.doc");
            //ExEnd
        }
Example #56
0
        /// <summary>
        /// 把多个PDF文件、word文件、JPG/PNG/jpge图合并成一个PDF文档
        /// </summary>
        /// <param name="fileList">需要合并文件的完整路径列表</param>
        /// <param name="outMergeFile">输出文件完整路径</param>
        public void MergePDFFile(List<string> fileList, string outMergeFile)
        {
            PdfReader reader;
            PdfImportedPage newPage;
            PdfWriter pw;
            iTextSharp.text.Document document = new iTextSharp.text.Document();
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create));
            document.Open();
            PdfContentByte cb = writer.DirectContent;

            foreach (var itemFile in fileList)
            {
                string fileName = Path.GetFileName(itemFile);
                var ext = Path.GetExtension(itemFile).ToLower();
                if (!File.Exists(itemFile))
                {

                    LogManage.WriteLog(LogManage.LogFile.Error, string.Format("文件打印合并__{0} 文件不存在", fileName));
                    continue;
                }
                FileInfo fInfo = new FileInfo(itemFile);
                if (fInfo.Length < 1)
                {

                    LogManage.WriteLog(LogManage.LogFile.Error, string.Format("文件打印合并__文件内容为空,无法打印,{0}", fileName));
                    return;
                }

                if (".pdf".Equals(ext))
                {
                    reader = new PdfReader(itemFile);
                    int iPageNum = reader.NumberOfPages;
                    for (int j = 1; j <= iPageNum; j++)
                    {
                        document.NewPage();
                        newPage = writer.GetImportedPage(reader, j);
                        cb.AddTemplate(newPage, 0, 0);
                    }
                }
                else if (".doc".Equals(ext) || ".docx".Equals(ext))
                {
                    Aspose.Words.Document doc = new Aspose.Words.Document(itemFile);
                    string newPdf = Path.GetDirectoryName(itemFile) + "\\" + Path.GetFileNameWithoutExtension(itemFile) + ".pdf";
                    doc.Save(newPdf, SaveFormat.Pdf);
                    reader = new PdfReader(newPdf);
                    int iPageNum = reader.NumberOfPages;
                    for (int j = 1; j <= iPageNum; j++)
                    {
                        document.NewPage();
                        newPage = writer.GetImportedPage(reader, j);
                        cb.AddTemplate(newPage, 0, 0);
                    }
                }
                else if (".jpg".Equals(ext) || ".jpge".Equals(ext) || ".png".Equals(ext))
                {
                    FileStream rf = new FileStream(itemFile, FileMode.Open, FileAccess.Read);
                    int size = (int)rf.Length;
                    byte[] imext = new byte[size];
                    rf.Read(imext, 0, size);
                    rf.Close();

                    iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imext);

                    //调整图片大小,使之适合A4
                    var imgHeight = img.Height;
                    var imgWidth = img.Width;
                    if (img.Height > iTextSharp.text.PageSize.A4.Height)
                    {
                        imgHeight = iTextSharp.text.PageSize.A4.Height;
                    }

                    if (img.Width > iTextSharp.text.PageSize.A4.Width)
                    {
                        imgWidth = iTextSharp.text.PageSize.A4.Width;
                    }
                    img.ScaleToFit(imgWidth, imgHeight);

                    //调整图片位置,使之居中
                    img.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE;

                    document.NewPage();
                    document.Add(img);
                }
                string message = DateTime.Now.ToString("MM-dd HH:mm:ss") + "正在合拼" + itemFile + "……";
                listBoxLog.Items.Add(message);
                LogManage.WriteLog(LogManage.LogFile.Trace, message);
                listBoxLog.SelectedIndex = listBoxLog.Items.Count - 1;
            }
            document.Close();
        }
Example #57
0
        public void Style()
        {
            //ExStart
            //ExFor:Font.Style
            //ExFor:Style.BuiltIn
            //ExSummary:Applies double underline to all runs in a document that are formatted with custom character styles.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Font.Style.doc");

            // Select all run nodes in the document.
            NodeCollection runs = doc.GetChildNodes(NodeType.Run, true);

            // Loop through every run node.
            foreach (Run run in runs)
            {
                Aspose.Words.Style charStyle = run.Font.Style;

                // If the style of the run is not a built-in character style, apply double underline.
                if (!charStyle.BuiltIn)
                    run.Font.Underline = Underline.Double;
            }

            doc.Save(ExDir + "Font.Style Out.doc");
            //ExEnd
        }
        public ActionResult TestingPage()
        {

            int customerID = 1;
            int bookingID = 4;

            /*AUTOMAILER CODE*/
            //       MaintainanceMailer letsMail = new MaintainanceMailer();
            //letsMail.SendEmail();

            //Merge with Regions
            DataTable MyTable = new DataTable();
            MyTable.TableName = "MyTable";
            ConnectionStringSettings connection = ConfigurationManager.ConnectionStrings["PortugalVillasContext"];
            using (SqlConnection conn = new SqlConnection(connection.ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand("GetDataForBookingExtraParticipantMailMerge", conn))
                {
                    using (SqlDataAdapter da = new SqlDataAdapter("GetDataForBookingExtraParticipantMailMerge", conn))
                    {

                        // cmd.Parameters.AddWithValue("@BookingExtraSelectionID", 3);                
                        //da.SelectCommand = cmd;
                        da.SelectCommand.CommandText = cmd.CommandText;
                        da.SelectCommand.CommandType = CommandType.StoredProcedure;

                        da.SelectCommand.Parameters.AddWithValue("@BookingExtraSelectionID", 3);


                        conn.Open();
                        da.Fill(MyTable);
                    }
                }
            }

            ////Main Merge
            //DataTable MainMergeTable = new DataTable();
            //MainMergeTable.TableName = "MainMergeTable";
            //ConnectionStringSettings connection = ConfigurationManager.ConnectionStrings["PortugalVillasContext"];
            //using (SqlConnection conn = new SqlConnection(connection.ConnectionString))
            //{
            //    using (SqlCommand cmd = new SqlCommand("GetDataForBookingMailMerge", conn))
            //{
            //    using (SqlDataAdapter da = new SqlDataAdapter("GetDataForBookingMailMerge", conn))
            //    {

            //       // cmd.Parameters.AddWithValue("@BookingExtraSelectionID", 3);                
            //        //da.SelectCommand = cmd;
            //        da.SelectCommand.CommandText = cmd.CommandText;
            //        da.SelectCommand.CommandType = CommandType.StoredProcedure;

            //        da.SelectCommand.Parameters.AddWithValue("@CustomerID", 1);                
            //        da.SelectCommand.Parameters.AddWithValue("@BookingID", 4);                

            //    conn.Open();
            //    da.Fill(MyTable);                
            //}
            //}
            //}

            /*MAIL MERGE CODE*/
            PRCDocumentData theDocumentDataInstance = new PRCDocumentData();
            //call the methods to bring back the necessary rows

            DataTable PRCInformation = theDocumentDataInstance.GetPRCDocumentData(PRCDocumentData.PRCReturnDataTableWrapperTypes.StandardPRCInformation, 1); //NOT WORKING
            DataTable Customers = theDocumentDataInstance.GetPRCDocumentData(PRCDocumentData.PRCReturnDataTableWrapperTypes.CustomerByCustomerID, 1); //works
            DataTable Booking = theDocumentDataInstance.GetPRCDocumentData(PRCDocumentData.PRCReturnDataTableWrapperTypes.BookingByBookingID, 4); //works

            DataTable BookingParticipant = theDocumentDataInstance.GetPRCDocumentData(PRCDocumentData.PRCReturnDataTableWrapperTypes.BookingParticipantByBookingID, 4);

            DataTable BookingExtraSelectionByCustomerID = theDocumentDataInstance.GetPRCDocumentData(PRCDocumentData.PRCReturnDataTableWrapperTypes.BookingExtraSelectionByCustomerID, 1);

            DataTable StandardBookingExtraSelection = theDocumentDataInstance.GetPRCDocumentData(PRCDocumentData.PRCReturnDataTableWrapperTypes.BookingExtraSelectionByBookingExtraSelectionID, 3);

            DataTable StandardPropertyQuery = theDocumentDataInstance.GetPRCDocumentData(PRCDocumentData.PRCReturnDataTableWrapperTypes.PropertyByPropertyID, 221);

            DataTable StandardPropertyRegionQuery = theDocumentDataInstance.GetPRCDocumentData(PRCDocumentData.PRCReturnDataTableWrapperTypes.PropertyRegionByPropertyRegionID, 1);

            DataTable StandardBookingExtraQuery = theDocumentDataInstance.GetPRCDocumentData(PRCDocumentData.PRCReturnDataTableWrapperTypes.BookingExtraByBookingExtraID, 1);

            DataTable BookingExtraParticipantByBookingExtraSelectionID = theDocumentDataInstance.GetPRCDocumentData(PRCDocumentData.PRCReturnDataTableWrapperTypes.BookingExtraParticipantByBookingExtraSelectionID, 3);

            DataTable CustomAttributes = new DataTable();
            CustomAttributes.Columns.Add("CurrentDate").DefaultValue = DateTime.Now.ToShortDateString();

            DataRow newDateRow = CustomAttributes.NewRow();
            newDateRow["CurrentDate"] = DateTime.Now.ToShortDateString();
            CustomAttributes.Rows.Add(newDateRow);


            //pass property ID
            DataTable StandardPropertyOwnerQuery = theDocumentDataInstance.GetPRCDocumentData(PRCDocumentData.PRCReturnDataTableWrapperTypes.StandardPropertyOwner, 221);
            //attempt a merge

            string ApplicationPath = HttpContext.Server.MapPath("~/DocumentTemplates/BookingConfirmationVoucherTemplate.docx");

            string SecndApplicationPath = HttpContext.Server.MapPath("~/DocumentTemplates/BCTTemplate.rtf");


            string BookingRequestFormEU = HttpContext.Server.MapPath("~/DocumentTemplates/BOOKING_EU_EFTABookingRequestFormTemplate.doc");
            string BookingRequestFormUK = HttpContext.Server.MapPath("~/DocumentTemplates/UKROWBookingRequestFormTemplate.doc");
            string SecurityDepositTemplate = HttpContext.Server.MapPath("~/DocumentTemplates/SecurityDepositTemplate.docx");
            string RentalRemittanceAdviceTemplate = HttpContext.Server.MapPath("~/DocumentTemplates/RemTemplate.doc");
            string TestTemplate = HttpContext.Server.MapPath("~/DocumentTemplates/TESTMERGEREGIONS.doc");


            string SavePath = HttpContext.Server.MapPath("~/DocumentGenerated/");
            // string FullDocumentPath = ApplicationPath + "~/DocumentTemplates/BookingConfirmationVoucherTemplate.docx";
            Aspose.Words.Document theDoc = new Aspose.Words.Document(TestTemplate);


            //do all the table merges



            // theDoc.MailMerge.Execute(MyMergeTable);


            theDoc.MailMerge.ExecuteWithRegions(MyTable);
            theDoc.Save(@"c:\test\testdoc1.doc");

            /*
            PRCImageCollection ImageCollection = new PRCImageCollection(Server, "PRCV29");

            BookingCalendar TestBookingCalendar = new BookingCalendar(1);
            TestBookingCalendar.GetAllBookingDatesAndAddToThisCalendar();
            ViewBag.BookingCalDates = TestBookingCalendar;


            Session.Add("test", Property.GetPropertyByID(76));
            */

            return View();
        }
Example #59
0
        public ActionResult UserImport(int userId)
        {
            string table = "CrmUser";
            string strwhere = "UserId=" + userId.ToString();
            string htable = "CrmHealth";
            string hstrwhere = "HealthUserId=" + userId.ToString();
            UserDto userDto = UserBll.GetOneUserDto(table, strwhere);
            HealthDto healthDto = HealthBll.GetOneHealthDto(htable, hstrwhere);
            string userClassInfo = "";
            string[] userClassId = userDto.UserClass.Split(',');

            foreach (string userClass in userClassId)
            {
                userClassInfo = userClassInfo + UserClassBll.GetOneUserClassDto("CrmUserClass", "UserClassId=" + userClass).UserClassName+" ";
            }

            string jiwangshiJibing = "";
            List<JiwangshiDto> jiwangshiJibingList = JiwangshiBll.GetJiwangshiDtoList("CrmJiwangshi", "JiwangshiUserId="+userId.ToString()+" and JiwangshiClass='疾病'");
            if (jiwangshiJibingList.Count == 0)
            {
                jiwangshiJibing = "无";
            }
            else
            {
                foreach (JiwangshiDto jiwangshiDto in jiwangshiJibingList)
                {
                    jiwangshiJibing=jiwangshiJibing+ jiwangshiDto.JiwangshiName+ jiwangshiDto.JiwangshiTime.ToString("yyyy年MM月dd日") + "||";
                }

            }

            string jiwangshiShoushu = "";
            List<JiwangshiDto> jiwangshiShoushuList = JiwangshiBll.GetJiwangshiDtoList("CrmJiwangshi", "JiwangshiUserId=" + userId.ToString() + " and JiwangshiClass='手术'");
            if (jiwangshiShoushuList.Count == 0)
            {
                jiwangshiShoushu = "无";
            }
            else
            {
                foreach (JiwangshiDto jiwangshiDto in jiwangshiShoushuList)
                {
                    jiwangshiShoushu = jiwangshiShoushu + jiwangshiDto.JiwangshiName + jiwangshiDto.JiwangshiTime.ToString("yyyy年MM月dd日") + "||";
                }

            }

            string jiwangshiWaishang = "";
            List<JiwangshiDto> jiwangshiWaishangList = JiwangshiBll.GetJiwangshiDtoList("CrmJiwangshi", "JiwangshiUserId=" + userId.ToString() + " and JiwangshiClass='外伤'");
            if (jiwangshiWaishangList.Count == 0)
            {
                jiwangshiWaishang = "无";
            }
            else
            {
                foreach (JiwangshiDto jiwangshiDto in jiwangshiWaishangList)
                {
                    jiwangshiWaishang = jiwangshiWaishang + jiwangshiDto.JiwangshiName + jiwangshiDto.JiwangshiTime.ToString("yyyy年MM月dd日") + "||";
                }

            }

            string jiwangshiShuxue = "";
            List<JiwangshiDto> jiwangshiShuxueList = JiwangshiBll.GetJiwangshiDtoList("CrmJiwangshi", "JiwangshiUserId=" + userId.ToString() + " and JiwangshiClass='输血'");
            if (jiwangshiShuxueList.Count == 0)
            {
                jiwangshiShuxue = "无";
            }
            else
            {
                foreach (JiwangshiDto jiwangshiDto in jiwangshiWaishangList)
                {
                    jiwangshiShuxue = jiwangshiShuxue + jiwangshiDto.JiwangshiName + jiwangshiDto.JiwangshiTime.ToString("yyyy年MM月dd日") + "||";
                }

            }

            try
            {
                string templateFile = Server.MapPath("~/jkda.docx");
                string saveDocFile = Server.MapPath("~/" + userDto.UserName + DateTime.Now.ToString("yyyyMMddhhmmss") + ".doc");

                Aspose.Words.Document doc = new Aspose.Words.Document(templateFile);

                #region 给普通标签赋值
                Bookmark markDesigner;

                if (doc.Range.Bookmarks["bianhao"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["bianhao"];
                    markDesigner.Text = userDto.UserRegTime.ToString("yyyyMMddhhmmss");
                }
                if (doc.Range.Bookmarks["UserClass"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["UserClass"];
                    markDesigner.Text = userClassInfo;
                }
                if (doc.Range.Bookmarks["UserName"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["UserName"];
                    markDesigner.Text = userDto.UserName;
                }

                if (doc.Range.Bookmarks["UserNowAddress"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["UserNowAddress"];
                    markDesigner.Text = userDto.UserNowAddress;
                }
                if (doc.Range.Bookmarks["UserOldAddress"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["UserOldAddress"];
                    markDesigner.Text = userDto.UserOldAddress;
                }

                if (doc.Range.Bookmarks["TheUserTel"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["TheUserTel"];
                    markDesigner.Text = userDto.UserTel;
                }
                if (doc.Range.Bookmarks["UserGroup"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["UserGroup"];
                    markDesigner.Text = GroupBll.GetOneGroupDto("CrmGroup","GroupId="+userDto.UserGroup).GroupName;
                }
                if (doc.Range.Bookmarks["UserDoctor"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["UserDoctor"];
                    markDesigner.Text = DoctorBll.GetOneDoctorDto("CrmDoctor","DoctorId="+userDto.UserDoctor).DoctorRealName;
                }
                if (doc.Range.Bookmarks["UserRegTime"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["UserRegTime"];
                    markDesigner.Text = userDto.UserRegTime.ToString("yyyy年MM月dd日");
                }

                if (doc.Range.Bookmarks["TheUserName"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["TheUserName"];
                    markDesigner.Text = userDto.UserName;
                }

                if (doc.Range.Bookmarks["Thebianhao"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["Thebianhao"];
                    markDesigner.Text = userDto.UserRegTime.ToString("yyyyMMddhhmmss");
                }

                if (doc.Range.Bookmarks["UserTel"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["UserTel"];
                    markDesigner.Text = userDto.UserTel;
                }
                if (doc.Range.Bookmarks["UserSex"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["UserSex"];
                    markDesigner.Text = userDto.UserSex;
                }
                if (doc.Range.Bookmarks["UserBirthday"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["UserBirthday"];
                    markDesigner.Text = userDto.UserBirthday.ToString("yyyy年MM月dd日");
                }
                if (doc.Range.Bookmarks["UserNumber"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["UserNumber"];
                    markDesigner.Text = userDto.UserNumber;
                }
                if (doc.Range.Bookmarks["UserJobGroup"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["UserJobGroup"];
                    markDesigner.Text = userDto.UserJobGroup;
                }
                if (doc.Range.Bookmarks["UserFirstTel"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["UserFirstTel"];
                    markDesigner.Text = userDto.UserFirstPersonTel;
                }
                if (doc.Range.Bookmarks["UserFirstPerson"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["UserFirstPerson"];
                    markDesigner.Text = userDto.UserFirstPerson;
                }
                if (doc.Range.Bookmarks["UserHuji"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["UserHuji"];
                    markDesigner.Text = userDto.UserHuji;
                }
                if (doc.Range.Bookmarks["UserMinzu"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["UserMinzu"];
                    markDesigner.Text = userDto.UserMinzu;
                }
                if (doc.Range.Bookmarks["UserWenhua"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["UserWenhua"];
                    markDesigner.Text = userDto.UserWenhua;
                }
                if (doc.Range.Bookmarks["UserZhiye"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["UserZhiye"];
                    markDesigner.Text = userDto.UserZhiye;
                }
                if (doc.Range.Bookmarks["UserHunyin"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["UserHunyin"];
                    markDesigner.Text = userDto.UserHunyin;
                }
                #endregion

                if (doc.Range.Bookmarks["HealthXuexing"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["HealthXuexing"];
                    markDesigner.Text = healthDto.HealthXuexing;
                }
                if (doc.Range.Bookmarks["HealthRH"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["HealthRH"];
                    markDesigner.Text = healthDto.HealthRH;
                }
                if (doc.Range.Bookmarks["HealthFeiyong"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["HealthFeiyong"];
                    markDesigner.Text = healthDto.HealthFeiyong;
                }
                if (doc.Range.Bookmarks["HealthGuomin"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["HealthGuomin"];
                    markDesigner.Text = healthDto.HealthGuomin;
                }
                if (doc.Range.Bookmarks["HealthBaolou"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["HealthBaolou"];
                    markDesigner.Text = healthDto.HealthBaolou;
                }
                if (doc.Range.Bookmarks["HealthJibing"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["HealthJibing"];
                    markDesigner.Text = jiwangshiJibing;
                }
                if (doc.Range.Bookmarks["HealthShoushu"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["HealthShoushu"];
                    markDesigner.Text = jiwangshiShoushu;
                }
                if (doc.Range.Bookmarks["HealthWaishang"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["HealthWaishang"];
                    markDesigner.Text = jiwangshiWaishang;
                }
                if (doc.Range.Bookmarks["HealthShuxue"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["HealthShuxue"];
                    markDesigner.Text = jiwangshiShuxue;
                }
                if (doc.Range.Bookmarks["HealthJiazuDady"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["HealthJiazuDady"];
                    markDesigner.Text = healthDto.HealthJiazuDady;
                }
                if (doc.Range.Bookmarks["HealthJiazuMama"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["HealthJiazuMama"];
                    markDesigner.Text = healthDto.HealthJiazuMama;
                }
                if (doc.Range.Bookmarks["HealthJiazuXiongdi"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["HealthJiazuXiongdi"];
                    markDesigner.Text = healthDto.HealthJiazuXiongdi;
                }
                if (doc.Range.Bookmarks["HealthJiazuZinv"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["HealthJiazuZinv"];
                    markDesigner.Text = healthDto.HealthJiazuZinv;
                }
                if (doc.Range.Bookmarks["HealthYichuan"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["HealthYichuan"];
                    markDesigner.Text = healthDto.HealthYichuan;
                }
                if (doc.Range.Bookmarks["HealthCanji"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["HealthCanji"];
                    markDesigner.Text = healthDto.HealthCanji;
                }
                if (doc.Range.Bookmarks["HealthChufang"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["HealthChufang"];
                    markDesigner.Text = healthDto.HealthChufang;
                }
                if (doc.Range.Bookmarks["HealthRanliao"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["HealthRanliao"];
                    markDesigner.Text = healthDto.HealthRanliao;
                }
                if (doc.Range.Bookmarks["HealthYinshui"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["HealthYinshui"];
                    markDesigner.Text = healthDto.HealthYinshui;
                }
                if (doc.Range.Bookmarks["HealthCesuo"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["HealthCesuo"];
                    markDesigner.Text = healthDto.HealthCesuo;
                }
                if (doc.Range.Bookmarks["HealthQichulan"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["HealthQichulan"];
                    markDesigner.Text = healthDto.HealthQichulan;
                }
                if (doc.Range.Bookmarks["UserDiy1"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["UserDiy1"];
                    markDesigner.Text = userDto.UserDiy1;
                }
                if (doc.Range.Bookmarks["UserDiy2"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["UserDiy2"];
                    markDesigner.Text = userDto.UserDiy2;
                }
                if (doc.Range.Bookmarks["HealthDiy3"] != null)
                {
                    markDesigner = doc.Range.Bookmarks["HealthDiy3"];
                    markDesigner.Text = userDto.UserDiy3;
                }

                doc.Save(saveDocFile);//保存
                ViewBag.msg = "生成成功,保存路径:<br />" + saveDocFile;
                //System.Diagnostics.Process.Start(saveDocFile);//打开文档
                return File(saveDocFile, "application/msword",userDto.UserName+DateTime.Now.ToString("yyyyMMddhhmmss") + ".doc");//输出到浏览器
            }
            catch (Exception ex)
            {
                ViewBag.msg = ex.Message;
            }

               // UserBll.UpdateUserDto(userDto);

              //  return File(saveDocFile, "application/msword", DateTime.Now.ToString("yyyyMMddhhmmss") + ".doc");//输出到浏览器

            //  return Redirect("/Health/HealthAdd?userId=" + model.UserId + "&userName="******"UserIndex", "User", new { groupId = 0, userClass = 0, doctorId = System.Web.HttpContext.Current.Request.Cookies["DoctorId"].Value });
            return Content(ViewBag.msg);
        }
Example #60
0
        public void RemoveTOCFromDocument()
        {
            //ExStart
            //ExFor:CompositeNode.GetChildNodes(NodeType, Boolean)
            //ExId:RemoveTableOfContents
            //ExSummary:Demonstrates how to remove a specified TOC from a document.
            // Open a document which contains a TOC.
            Aspose.Words.Document doc = new Aspose.Words.Document(ExDir + "Document.TableOfContents.doc");

            // Remove the first TOC from the document.
            Field tocField = doc.Range.Fields[0];
            tocField.Remove();

            // Save the output.
            doc.Save(ExDir + "Document.TableOfContentsRemoveTOC Out.doc");
            //ExEnd
        }