Exemplo n.º 1
0
 private static void setDateToTable(ref Word.Document doc, ref Word.Font TextFont, int pairLen, int dayWidth, int namesWidth, int namesLen)
 {
     Word.Table table = doc.Tables[1];
     Word.Range cellRange;
     //Заполнение созданной таблицы данными
     for (int j = 3; j < namesLen + 3; j++)
     {
         Form1.form.SetProc(80 + (j - 3) * 20 / namesLen);
         TextFont.Size  = 10;
         cellRange      = table.Cell(j, 1).Range;
         cellRange.Font = TextFont;
         cellRange.Text = Data.teacher[j - 3].name;
         cellRange      = table.Cell(j, 1 + 5 * pairLen + 1).Range;
         cellRange.Font = TextFont;
         cellRange.Text = Data.teacher[j - 3].name;
         TextFont.Size  = 5;
         for (int k = 2; k < 22; k++)
         {
             cellRange.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
             object A = cellRange.ParagraphFormat;
             cellRange      = table.Cell(j, k).Range;
             cellRange.Font = TextFont;
             //cellRange.Rows.SetHeight(20, Word.WdRowHeightRule.wdRowHeightExactly); Установка высоты строки
             cellRange.Text = Data.teacher[j - 3].lesson[(k - 2) / 4, (k - 2) % 4].ToString();
             cellRange.ParagraphFormat.SpaceAfter  = 0.0f;
             cellRange.ParagraphFormat.LeftIndent  = doc.Content.Application.CentimetersToPoints((float)-0.2);//Отступ отрицательный, что бы запись занимала ячейку полностью.
             cellRange.ParagraphFormat.RightIndent = doc.Content.Application.CentimetersToPoints((float)-0.2);
         }
     }
 }
Exemplo n.º 2
0
        void ReadVsto()
        {
            Stopwatch sw = Stopwatch.StartNew();

            _app.ScreenUpdating = false;

            Interop.Document document = _app.ActiveDocument;
            int i = 0;

            foreach (Interop.Range range in document.Range().Words)
            {
                string          a1   = range.Text;
                Interop.Font    font = range.Font;
                int             a2   = font.Fill.BackColor.RGB;
                Interop.WdColor a3   = font.Color;
                float           a4   = font.Size;
                int             a5   = font.Italic;
                int             a6   = font.Bold;
                i++;
            }

            _app.ScreenUpdating = true;

            sw.Stop();
            MessageBox.Show(sw.Elapsed.ToString(), $"VSTO: read {i}");
        }
Exemplo n.º 3
0
        private static void formatTable(ref Word.Table table, ref Word.Font TextFont, int pairLen, int dayWidth, int namesWidth, int namesLen, Word.Range cellRange)
        {
            string[] daysNames = { "Понедельник", "Вторник", "Среда", "Четверг", "Пятница" };
            string[] times     = { "9.30-10.30", "11.10–12.45", "13.45–15.20", "15.35–17.10", "17.25–19.00??" };
            object   nr        = 1;
            object   nc        = pairLen;

            //Прописываем дни недели.
            for (int i = 0; i < 5; i++)
            {
                table.Cell(1, i + 2).Width = dayWidth;
                cellRange      = table.Cell(1, i + 2).Range;
                cellRange.Text = daysNames[i];
            }
            table.Cell(1, 1 + 5 + 1).Width = namesWidth;

            //Делим дни на пары
            for (int i = 0; i < 5; i++)
            {
                table.Cell(2, 2 + i * 4).Split(ref nr, ref nc);
            }
            table.Cell(2, 1).Width = namesWidth;
            table.Cell(2, 1 + pairLen * 5 + 1).Width = namesWidth;

            TextFont.Size = 5;
            //Задаем размер пар, и подписываем время.

            for (int i = 0; i < 5 * pairLen; i++)
            {
                Form1.form.SetProc(10 + i * 10 / (5 * pairLen));
                table.Cell(2, i + 2).Width = dayWidth / pairLen;
                cellRange      = table.Cell(2, i + 2).Range;
                cellRange.Font = TextFont;
                cellRange.Text = times[i % pairLen];
            }

            TextFont.Size = 6;
            //Делаем разметку под пары.
            for (int i = 3; i < namesLen + 3; i++)
            {
                Form1.form.SetProc(10 + i * 30 / namesLen + 3);

                table.Cell(i, 1).Width         = namesWidth;
                table.Cell(i, 1 + 5 + 1).Width = namesWidth;
                for (int k = 0; k < 5; k++)
                {
                    table.Cell(i, 2 + k * 4).Split(ref nr, ref nc);
                }

                for (int j = 0; j < 5 * pairLen; j++)
                {
                    table.Cell(i, j + 2).Width = dayWidth / pairLen;
                }
            }
        }
Exemplo n.º 4
0
        void PutFont(FontParams fp, MSWord.Selection sel)
        {
            MSWord.Font pFont = sel.Font;

            if (fp.styleName != "")
            {
                sel.set_Style(m_pDoc.Styles[fp.styleName]);
            }

            if (fp.fontName != "")
            {
                pFont.Name = fp.fontName;
            }

            if (fp.bold != null)
            {
                if ((bool)fp.bold)
                {
                    pFont.Bold = 1;
                }
                else
                {
                    pFont.Bold = 0;
                }
            }

            if (fp.italic != null)
            {
                if ((bool)fp.italic)
                {
                    pFont.Italic = 1;
                }
                else
                {
                    pFont.Italic = 0;
                }
            }

            if (fp.underline != null)
            {
                if ((bool)fp.underline)
                {
                    pFont.Underline = MSWord.WdUnderline.wdUnderlineSingle;
                }
                else
                {
                    pFont.Underline = MSWord.WdUnderline.wdUnderlineNone;
                }
            }

            if (fp.fontHeight > 0)
            {
                pFont.Size = fp.fontHeight;
            }
        }
Exemplo n.º 5
0
 public static bool IsSame(this Word.Font font, Word.Font other)
 {
     return(other.Name == font.Name &&
            other.Size == font.Size &&
            other.Color == font.Color &&
            other.Bold == font.Bold &&
            other.Italic == font.Italic &&
            other.Underline == font.Underline &&
            other.UnderlineColor == font.UnderlineColor &&
            other.StrikeThrough == font.StrikeThrough
            );
 }
        private void CreateStyle_IndexWord()
        {
            Common.WordHelper.DeleteStyle(cINDEX_WORD_STYLE);

            Document activeDoc = Globals.ThisAddIn.Application.ActiveDocument;

            Style newStyle = activeDoc.Styles.Add(Name: cINDEX_WORD_STYLE, Type: WdStyleType.wdStyleTypeCharacter);

            newStyle.QuickStyle = true;

            //newStyle.AutomaticallyUpdate = false;
            //newStyle.NoSpaceBetweenParagraphsOfSameStyle = false;
            //newStyle.ParagraphFormat.TabStops.ClearAll();
            //newStyle.LanguageID = WdLanguageID.wdEnglishUS;
            //newStyle.NoProofing = 0;
            //newStyle.Frame.Delete();

            //activeDoc.Styles[cINDEX_HEADING_SYTLE].AutomaticallyUpdate = false;

            Microsoft.Office.Interop.Word.Font font = activeDoc.Styles[cINDEX_WORD_STYLE].Font;

            font.Name                 = "+Body";
            font.Size                 = 12;
            font.Bold                 = 1;
            font.Italic               = 0;
            font.Underline            = WdUnderline.wdUnderlineNone;
            font.UnderlineColor       = WdColor.wdColorAutomatic;
            font.StrikeThrough        = 0;
            font.Outline              = 0;
            font.Emboss               = 0;
            font.Shadow               = 0;
            font.Hidden               = 0;
            font.SmallCaps            = 0;
            font.AllCaps              = 0;
            font.Color                = WdColor.wdColorBlue;
            font.Engrave              = 0;
            font.Subscript            = 0;
            font.Scaling              = 100;
            font.Kerning              = 0;
            font.Animation            = WdAnimation.wdAnimationNone;
            font.Ligatures            = WdLigatures.wdLigaturesNone;
            font.NumberSpacing        = WdNumberSpacing.wdNumberSpacingDefault;
            font.NumberForm           = WdNumberForm.wdNumberFormDefault;
            font.StylisticSet         = WdStylisticSet.wdStylisticSetDefault;
            font.ContextualAlternates = 0;
            //font.Borders[1].LineStyle = WdLineStyle.wdLineStyleNone;
            font.Borders.Shadow  = false;
            font.Shading.Texture = WdTextureIndex.wdTextureNone;
            font.Shading.ForegroundPatternColor = WdColor.wdColorAutomatic;
            font.Shading.BackgroundPatternColor = WdColor.wdColorAutomatic;
        }
Exemplo n.º 7
0
        private void frmReportCreationcs_Load(object sender, EventArgs e)
        {
            curFont           = new Microsoft.Office.Interop.Word.FontClass();
            curFont.Bold      = 0;
            curFont.Italic    = 0;
            curFont.Underline = WdUnderline.wdUnderlineNone;
            curFont.Size      = 12;
            curFont.Name      = "Times New Roman";

            mDefaltFont = curFont;

            #region Loading Report Styles
            if (ReportDataProvider.Instance.ReportTemplets.Count > 0)
            {
                foreach (string strRep in ReportDataProvider.Instance.ReportTemplets)
                {
                    object o = System.IO.Path.GetFileNameWithoutExtension(strRep);
                    cmbxExsistingReport.Items.Add(o);
                }
                grpReportInfo.Enabled = true;

                cmbxExsistingReport.Text    = "Select A Report";
                cmbxExsistingReport.Enabled = true;
            }
            else
            {
                grpReportInfo.Enabled       = false;
                cmbxExsistingReport.Enabled = true;
                cmbxExsistingReport.Text    = mNewString;
            }
            #endregion Loading Report Styles

            ShowCurrentFontOnLabel();

            #region Upadte Reserved Images
            cmbxImageFromControl.Items.Clear();
            List <string> lsTmp = ReportDataProvider.Instance.GetAllReservedImagesNames();
            foreach (string str in lsTmp)
            {
                cmbxImageFromControl.Items.Add(str.Replace("_", " ").Trim());
            }
            #endregion

            cmbxExsistingReport.Text = mNewString;

            grpPageInfo.Enabled   = false;
            grpReportInfo.Enabled = false;
        }
Exemplo n.º 8
0
        private void SetFontToRagne(ref Range rng, Microsoft.Office.Interop.Word.Font font)
        {
            //rng.Font = new Microsoft.Office.Interop.Word.FontClass();
            rng.Font.Bold      = font.Bold;
            rng.Font.BoldBi    = font.Bold;
            rng.Font.Color     = font.Color;
            rng.Font.Underline = font.Underline;
            rng.Font.Italic    = font.Italic;
            rng.Font.Name      = font.Name;
            rng.Font.NameAscii = font.NameAscii;
            rng.Font.NameBi    = font.NameBi;
            rng.Font.NameOther = font.NameOther;
            rng.Font.Size      = font.Size;
            rng.Font.SizeBi    = font.Size;


            //rng.Font = font as FontClass;
        }
Exemplo n.º 9
0
        private void btnFontSelect_Click(object sender, EventArgs e)
        {
            FontDialog fd = new FontDialog();

            fd.ShowColor   = false;
            fd.ShowEffects = true;

            DialogResult dlgRes = fd.ShowDialog();

            if ((dlgRes == DialogResult.Cancel) || (dlgRes == DialogResult.Abort) || (dlgRes == DialogResult.No))
            {
            }
            if (dlgRes == System.Windows.Forms.DialogResult.OK)
            {
                curFont = DrawingFont2FontClass(fd.Font);
            }

            ShowCurrentFontOnLabel();
        }
Exemplo n.º 10
0
        public static void ApplyFont(Microsoft.Office.Interop.Word.Font wFont, System.Drawing.Font font)
        {
            try
            {
                wFont.Bold          = Convert.ToInt32(font.Bold);
                wFont.Italic        = Convert.ToInt32(font.Italic);
                wFont.StrikeThrough = Convert.ToInt32(font.Strikeout);
                wFont.Size          = font.Size;
                wFont.Underline     = font.Underline ? WdUnderline.wdUnderlineSingle : WdUnderline.wdUnderlineNone;
                wFont.Name          = font.Name;
            }
            catch (Exception)
            {
                MessageBox.Show(@"Не удалось загрузить шрифт.
Для решения проблемы будет применен шрифт по умолчанию.",
                                "Информация", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                wFont.Name = "Times New Roman";
            }
        }
Exemplo n.º 11
0
        /*
         * public void TypeText(FontClass thisFont, string text, string alignment)
         * {
         *  Range textRange;
         *  object curStart = 0;
         *  object curEnd = 0;
         *  textRange = mCurDoc.Range(ref mCurLocation, ref mMissing);
         *  SetFontToRagne(ref textRange, thisFont);
         *
         *  textRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; // Right
         *  switch (alignment.ToLower())
         *  {
         *      case "center":
         *          textRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; // CENTERED
         *          break;
         *      case "left":
         *          textRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; // Right
         *          break;
         *      case "right":
         *          textRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; // Right
         *          break;
         *  }
         *
         *  textRange.ParagraphFormat.LeftIndent = 0;
         *
         *  string sHeader = text;
         *
         *  textRange.InsertAfter(sHeader + " ");
         *  //textRange.InsertAfter(System.Environment.NewLine);
         *
         *  mCurLocation = mCurRange.StoryLength - 1;
         *  mCurRange = mCurDoc.Range(ref mCurLocation, ref mMissing);
         *  InsertBreak();
         * }
         */
        public void TypeText(Microsoft.Office.Interop.Word.Font thisFont, string text, string alignment)
        {
            Microsoft.Office.Interop.Word.Range textRange;
            object curStart = 0;
            object curEnd   = 0;

            textRange = mCurDoc.Range(ref mCurLocation, ref mMissing);

            textRange.InsertBefore(text.ToString());
            textRange.Select();


            Microsoft.Office.Interop.Word.Font curFont = thisFont;
            SetFontToRagne(ref textRange, curFont);

            textRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; // Right
            switch (alignment.ToLower())
            {
            case "center":
                textRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;     // CENTERED
                break;

            case "left":
                textRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;     // Right
                break;

            case "right":
                textRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;     // Right
                break;
            }

            textRange.ParagraphFormat.LeftIndent = 0;


            textRange.InsertParagraphAfter();
            textRange.Select();
            //textRange.InsertAfter(System.Environment.NewLine);
            //InsertBreak();

            mCurLocation = mCurRange.StoryLength - 1;
            mCurRange    = mCurDoc.Range(ref mCurLocation, ref mMissing);
        }
Exemplo n.º 12
0
        // 在书签位置 插入指定文本(带style和font)
        #region InsertTextToBookMarkWithStyle
        /// <summary>
        /// 在书签位置 插入指定文本(带style)
        /// </summary>
        /// <param name="style"> 指定样式 </param>
        /// <param name="font"> 指定字体 </param>
        /// <param name="selection"></param>
        /// <param name="markName"> BookMark Name </param>
        /// <param name="text"> 插入的字符串内容 </param>
        /// <param name="logInfo"> 日志内容 </param>
        /// <returns></returns>
        public static bool InsertTextToBookMarkWithStyle(object style, Word.Font font, ref Word.Selection selection,
                                                         string markName, string text, out string logInfo)
        {
            bool res = true;

            try
            {
                GoToBookMark(ref selection, markName);
                selection.set_Style(style);
                selection.Font = font;
                selection.TypeText(text);
                logInfo = "写入 【" + markName + "】 成功!";
            }
            catch (Exception ex)
            {
                JCMsg.ShowErrorOK(ex.GetType().ToString() + "\n" + ex.Message);
                res     = false;
                logInfo = "写入 【" + markName + "】 失败!";
            }
            return(res);
        }
Exemplo n.º 13
0
        void WriteVsto(int size)
        {
            Stopwatch sw = Stopwatch.StartNew();

            _app.ScreenUpdating = false;

            Interop.WdColor[] colors =
            {
                Interop.WdColor.wdColorRed,
                Interop.WdColor.wdColorGreen,
                Interop.WdColor.wdColorBlue,
                Interop.WdColor.wdColorGold,
                Interop.WdColor.wdColorAqua,
                Interop.WdColor.wdColorPink,
                Interop.WdColor.wdColorDarkBlue
            };
            Interop.Document document = _app.ActiveDocument;
            for (int i = 1; i <= size; i++)
            {
                Interop.Paragraph paragraph = document.Range().Paragraphs.Add();
                for (int j = 1; j <= size; j++)
                {
                    Interop.Range range = paragraph.Range;
                    range.Collapse(Interop.WdCollapseDirection.wdCollapseEnd);
                    range.Text = " " + (1000 * i + j);
                    Interop.Font font = range.Font;
                    font.Fill.BackColor.RGB = GenerateRandomColor();
                    font.Color  = colors[_rand.Next(6)];
                    font.Size   = _rand.Next(9, 14);
                    font.Italic = -_rand.Next(2);
                    font.Bold   = -_rand.Next(2);
                }
            }

            _app.ScreenUpdating = true;

            sw.Stop();
            MessageBox.Show(sw.Elapsed.ToString(), $"VSTO: write {size * size}");
        }
Exemplo n.º 14
0
        public static System.Drawing.Font ToFont(Microsoft.Office.Interop.Word.Font fontW)
        {
            try
            {
                bool isBold      = Convert.ToBoolean(fontW.Bold);
                bool isItalic    = Convert.ToBoolean(fontW.Italic);
                bool isStrikeout = Convert.ToBoolean(fontW.StrikeThrough);
                bool isUnderline = Convert.ToBoolean(fontW.Underline);

                FontStyle style = FontStyle.Regular;

                if (isBold)
                {
                    style = style | FontStyle.Bold;
                }
                if (isItalic)
                {
                    style = style | FontStyle.Italic;
                }
                if (isStrikeout)
                {
                    style = style | FontStyle.Strikeout;
                }
                if (isUnderline)
                {
                    style = style | FontStyle.Underline;
                }

                return(new System.Drawing.Font(fontW.Name, fontW.Size, style, GraphicsUnit.Point, 204));
            }
            catch (Exception)
            {
                MessageBox.Show(@"Не удалось загрузить шрифт.
Для решения проблемы будет применен шрифт по умолчанию.",
                                "Информация", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return(new System.Drawing.Font("Times New Roman", 14, FontStyle.Regular));
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Gets a list of all marked ranges in the specified range. The current selection is updated to the end of the range to scan.
        /// </summary>
        /// <param name="rangeToScan">The Range to scan.</param>
        /// <param name="ShadingColor">The color for redaction marks in the document.</param>
        /// <param name="mergeAdjacent">True to merge adjacent ranges with identical formatting, False otherwise.</param>
        /// <returns>A List of RangeDataEx objects containing each marked subrange.</returns>
        internal static List <RangeDataEx> GetAllMarkedRanges(Word.Range rangeToScan, Word.WdColor ShadingColor, bool mergeAdjacent)
        {
            object Missing             = Type.Missing;
            object CollapseStart       = Word.WdCollapseDirection.wdCollapseStart;
            object CharacterFormatting = Word.WdUnits.wdCharacterFormatting;

            int LastPosition;
            int OriginalPosition;
            List <RangeDataEx> Ranges             = new List <RangeDataEx>();
            List <RangeDataEx> RangesToDelete     = new List <RangeDataEx>();
            List <RangeDataEx> ConcatenatedRanges = new List <RangeDataEx>();

            //we don't redact comments - if that's where we are, return
            if (rangeToScan.StoryType == Word.WdStoryType.wdCommentsStory)
            {
                return(ConcatenatedRanges);
            }

            //move the selection to the beginning of the requested range
            rangeToScan.Select();

            Word.Selection CurrentSelection = rangeToScan.Application.Selection;
            CurrentSelection.Collapse(ref CollapseStart);
            OriginalPosition = CurrentSelection.Start;

            //scan for distinct ranges of formatting
            do
            {
                //update LastPosition
                LastPosition = CurrentSelection.Start;

                //move to the next position
                CurrentSelection.Move(ref CharacterFormatting, ref Missing);

                //BUG 3913: if we detect that .Move has moved us out of the scan range (which appears to happen because of a Word bug)
                // break out and don't save the current range
                if (CurrentSelection.Start < OriginalPosition)
                {
                    CurrentSelection.End = rangeToScan.End;
                    break;
                }

                //store that range
                if (CurrentSelection.Start != LastPosition && rangeToScan.End != LastPosition)
                {
                    if (mergeAdjacent)
                    {
                        Ranges.Add(new RangeDataEx(LastPosition, CurrentSelection.Start < rangeToScan.End ? CurrentSelection.Start : rangeToScan.End, new RangeDataEx())); //since we're going to merge, don't fetch the extra properties
                    }
                    else
                    {
                        Word.Font CurrentFont = CurrentSelection.Font;
                        Ranges.Add(new RangeDataEx(LastPosition, CurrentSelection.Start < rangeToScan.End ? CurrentSelection.Start : rangeToScan.End, CurrentFont.Name, CurrentFont.Size, CurrentFont.Bold, CurrentFont.Italic, CurrentSelection.OMaths.Count > 0));
                    }
                }
            }while (CurrentSelection.End <= rangeToScan.End && CurrentSelection.End > LastPosition);

            if (CurrentSelection.End != rangeToScan.End)
            {
                if (mergeAdjacent)
                {
                    Ranges.Add(new RangeDataEx(CurrentSelection.End, rangeToScan.End, new RangeDataEx())); //since we're going to merge, don't fetch the extra properties
                }
                else
                {
                    Word.Font CurrentFont = CurrentSelection.Font;
                    Ranges.Add(new RangeDataEx(CurrentSelection.End, rangeToScan.End, CurrentFont.Name, CurrentFont.Size, CurrentFont.Bold, CurrentFont.Italic, CurrentSelection.OMaths.Count > 0));
                }
            }

            //go through those ranges and check if they are marked
            foreach (RangeDataEx UniqueRange in Ranges)
            {
                rangeToScan.Start = UniqueRange.Start;
                rangeToScan.End   = UniqueRange.End;

                //remove the range from the list
                if (!IsMarkedRange(rangeToScan, ShadingColor))
                {
                    RangesToDelete.Add(UniqueRange);
                }
            }

            //clean out the list
            foreach (RangeDataEx RangeToDelete in RangesToDelete)
            {
                Ranges.Remove(RangeToDelete);
            }
            RangesToDelete.Clear();

            //concatenate ranges that are next to each other
            int?Start = null;
            int?End   = null;

            for (int i = 0; i < Ranges.Count; i++)
            {
                //set start and end points
                if (Start == null)
                {
                    Start = Ranges[i].Start;
                }
                if (End == null)
                {
                    End = Ranges[i].End;
                }

                if ((i + 1) < Ranges.Count && (mergeAdjacent || (Ranges[i].InMath && Ranges[i + 1].InMath) || Ranges[i].IdenticalTo(Ranges[i + 1])) && End == Ranges[i + 1].Start)
                {
                    End = null;
                }
                else
                {
                    ConcatenatedRanges.Add(new RangeDataEx((int)Start, (int)End, Ranges[i]));
                    Start = End = null;
                }
            }

            //return the marked ranges
            return(ConcatenatedRanges);
        }
Exemplo n.º 16
0
        private void btn_dosyasec_Click(object sender, EventArgs e)
        {
            // kullanıcının sistem için bilgisayarında seçeceği tez dosyasının bulunması ve sisteme iletilmesi

            OpenFileDialog file = new OpenFileDialog();

            file.Filter           = "Word Dosyası |*.docx";
            file.RestoreDirectory = true;
            file.CheckFileExists  = false;
            file.Title            = "Word Dosyası Seçiniz...";

            if (file.ShowDialog() == DialogResult.OK)
            {
                // Sistem içerisinde kontrol edilen dosya bilgisini ekranda yazdırmak için atama ifadesi

                string dosyayolu = file.FileName;
                string dosya_adi = file.SafeFileName;

                {
                    // sistemin dosya kontrolü sırasındaki mesajı

                    label1.Text = dosya_adi + " Dosyası Kontrol Ediliyor. Lütfen Bekleyiniz...";

                    richTextBox1.Clear();

                    // kontrol edilecek olan word dosyasının taranması için Microsoft Office Word nesnesinin oluşturulması

                    Microsoft.Office.Interop.Word.Application wordObject = new Microsoft.Office.Interop.Word.Application();

                    object nullobject = System.Reflection.Missing.Value;

                    // seçilen word dosyasının açılması

                    Microsoft.Office.Interop.Word.Document docs = wordObject.Documents.Open(dosyayolu);

                    docs.ActiveWindow.Selection.WholeStory();
                    docs.ActiveWindow.Selection.Copy();
                    IDataObject data = Clipboard.GetDataObject();

                    //string tumu = data.GetData(DataFormats.Text).ToString(); tüm word sayfalarını getirir.

                    //tez dosyasındaki hataların konumunu belirtmek için değişken belirleme.

                    string satir = "";
                    int    i     = 1;

                    Document ddd = new Document();
                    ddd = docs;

                    // oluşturulan Document nesnesinin tüm satırların taranması

                    foreach (Microsoft.Office.Interop.Word.Paragraph objParagraph in docs.Paragraphs)
                    {
                        // font özelliklerinin kontrolü için oluşturulan satır konumun Font özelliğine atanması.



                        Microsoft.Office.Interop.Word.Font s = docs.Paragraphs[i].Range.Font;



                        if (docs.Paragraphs[i].Range.Text == "ÖNSÖZ")
                        {
                            richTextBox1.Text += "\n ÖNSÖZ MEVCUTTUR " + i;
                        }
                        else if (docs.Paragraphs[i].Range.ToString() == "İÇİNDEKİLER")
                        {
                            richTextBox1.Text += "\n İÇİNDEKİLER LİSTESİ MEVCUTTUR" + i;
                        }
                        else if (docs.Paragraphs[i].Range.ToString() == "ÖZET")
                        {
                            richTextBox1.Text += "\n ÖZET METNİ MEVCUTTUR. " + i;
                        }
                        else if (docs.Paragraphs[i].Range.ToString() == "ABSTRACT")
                        {
                            richTextBox1.Text += "\n İNGİLİZCE ÖZET METNİ MEVCUTTUR. " + i;
                        }
                        else if (docs.Paragraphs[i].Range.ToString() == "ŞEKİLLER LİSTESİ")
                        {
                            richTextBox1.Text += "\n ŞEKİLLER LİSTESİ MEVCUTTUR. " + i;
                        }
                        else if (docs.Paragraphs[i].Range.ToString() == "TABLOLAR LİSTESİ")
                        {
                            richTextBox1.Text += "\n TABLOLAR LİSTESİ MEVCUTTUR. " + i;
                        }
                        else if (docs.Paragraphs[i].Range.ToString() == "EKLER LİSTESİ")
                        {
                            richTextBox1.Text += "\n EKLER LİSTESİ MEVCUTTUR. " + i;
                        }
                        else if (docs.Paragraphs[i].Range.ToString() == "SİMGELER VE KISALTMALAR")
                        {
                            richTextBox1.Text += "\n SİMGELER VE KISALTMLAR MEVCUTTUR." + i;
                        }

                        if (s.Size == 12F)
                        {
                            // yazı fontunun 12 olması durumunda kontrol edilecek ifadeler.

                            if (s.Position.ToString() != "wdVerticalAlignmentLeft")
                            {
                                //pozisyon kontrolü
                                richTextBox1.Text += "\n ara başlık sola yaslı değil satır :" + i;
                            }
                            if (s.ColorIndex.ToString() != "wdBlack")
                            {
                                //yazı rengi kontrolü
                                richTextBox1.Text += "\n yazı rengi yanlış satır:" + i;
                            }
                            if (s.Name.ToString() != "Times New Roman")
                            {
                                // yazı stili kontrolü
                                richTextBox1.Text += "\n yazı stili yanlış satır:" + i;
                            }
                        }
                        else
                        if (s.Size == 16F)
                        {
                            // yazı fontunun 16 olması durumunda kontrol edilecek ifadeler.

                            if (s.Position.ToString() != "WdVerticalAlignmentCenter")
                            {
                                // pozisyon kontrolü
                                richTextBox1.Text += "\n ana başlık iki yana yaslı değil satır:  " + i;
                            }
                            if (s.ColorIndex.ToString() != "wdBlack")
                            {
                                //yazı rengi kontrolü
                                richTextBox1.Text += "\n yazı rengi yanlış satır:" + i;
                            }
                            if (s.Name.ToString() != "Times New Roman")
                            {
                                // yazı stili kontrolü
                                richTextBox1.Text += "\n yazı stili yanlış satır:" + i;
                            }
                        }
                        else
                        if (s.Size == 11F)
                        {
                            // yazı fontunun 11 olması durumunda kontrol edilecek ifadeler.

                            if (s.Position.ToString() != "WdVerticalAlignmentCenter")
                            {
                                // pozisyon kontrolü
                                richTextBox1.Text += "\n ana başlık iki yana yaslı değil satır:  " + i;
                            }
                            if (s.ColorIndex.ToString() != "wdBlack")
                            {
                                // yazı rengi kontrolü
                                richTextBox1.Text += "\n yazı rengi yanlış satır:" + i;
                            }
                            if (s.Name.ToString() != "Times New Roman")
                            {
                                // yazı stili kontrolü
                                richTextBox1.Text += "\n yazı stili yanlış satır:" + i;
                            }
                        }
                        // kılavuzda belirtilen tüm yazı fontlarının kontrolü yapıldı

                        else
                        {
                            // eğer kılavuzda belirtilen yazı fontu dışında bir font varsa kontolü bu blokta yapılacaktır.

                            richTextBox1.Text += "\n yazı boyutu 11 punto değil satır:" + i;

                            if (s.Name.ToString() != "Times New Roman")
                            {
                                richTextBox1.Text += "\n yazı stili yanlış satır:" + i;
                            }
                            if (s.ColorIndex.ToString() != "wdBlack")
                            {
                                richTextBox1.Text += "\n yazı rengi yanlış satır:" + i;
                            }
                        }



                        // satır konumunun arttırılıp sonraki satır konumun kontrolünün yapılması

                        i++;
                    }

                    i = 1;


                    // üst boşluk kontrolü
                    if (ddd.PageSetup.TopMargin.ToString() != "85,05")
                    {
                        richTextBox1.Text += "\n üst boşluk yanlış:";
                    }

                    //sol boşluk kontrolü
                    if (ddd.PageSetup.LeftMargin.ToString() != "92,15")
                    {
                        richTextBox1.Text += "\n sol boşluk yanlış:";
                    }

                    //sağ boşluk kontrolü
                    if (ddd.PageSetup.RightMargin.ToString() != "70,9")
                    {
                        richTextBox1.Text += "\n sağ boşluk yanlış:";
                    }

                    // alt boşluk kontrolü
                    if (ddd.PageSetup.BottomMargin.ToString() != "70,9")
                    {
                        richTextBox1.Text += "\n alt boşluk yanlış:";
                    }

                    // paragrafın düzen kontrolü
                    if (ddd.Paragraphs.Alignment != WdParagraphAlignment.wdAlignParagraphCenter)
                    {
                        richTextBox1.Text += "\n iki yana yaslı değil";

                        // kontrol işleminden sonra kullanıcın sisteme ilettiği dosyanın kontrolünün tamamlandığını göstermek için metin ataması.
                        label1.Text = dosya_adi + " Dosyası Kontrol Edildi. Ayrıntılar Aşağıdaki Kısımdadır.";
                    }

                    // tarama işleminin bittiğini kullanıcıya ileten kısım
                    MessageBox.Show("Tarama İşlemi Başarılı Bir Şekilde Tamamlandı", "BİLGİ", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    docs.Close(ref nullobject, ref nullobject, ref nullobject);


git:
                    return;
                }
            }
        }
Exemplo n.º 17
0
 public void AddContent(ContentType type, string text, Word.Font font)
 {
     AddContent(new ContentItem(type, text, font));
 }
Exemplo n.º 18
0
        public static void CreateWordDoc(string name)
        {
            #region inicialization

            Form1.form.SetProc(0);
            int       namesLen   = Data.teacher.Count;
            const int pairLen    = 4;//Сколько пар в день отображать
            string[]  daysNames  = { "Понедельник", "Вторник", "Среда", "Четверг", "Пятница" };
            string[]  times      = { "9.30-10.30", "11.10–12.45", "13.45–15.20", "15.35–17.10", "17.25–19.00??" };
            object    nr         = 1;
            object    nc         = pairLen;
            object    start      = 0;
            object    end        = 0;
            const int dayWidth   = 120; //ширина одного дня
            const int namesWidth = 95;  //ширина имен.

            Word.Application app          = new Word.ApplicationClass();
            Word.Document    doc          = new Word.DocumentClass();
            Object           template     = Type.Missing;
            Object           newTemplate  = Type.Missing;
            Object           documentType = Type.Missing;
            Object           visible      = Type.Missing;
            app.Documents.Add(ref template, ref newTemplate, ref documentType, ref visible);
            Object DefaultTableBehavior = Type.Missing;
            Object AutoFitBehavior      = Type.Missing;
            //Формирование страницы
            doc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;
            //Создание таблицы
            Word.Range cellRange;
            Word.Range tableLocation = doc.Range(ref start, ref end);
            doc.Tables.Add(tableLocation, namesLen + 2, 7, ref DefaultTableBehavior, ref AutoFitBehavior);
            Word.Table table = doc.Tables[1];
            table.Borders.Enable = 1;
            table.Rows.SetHeight(14f, Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightExactly);

            //Формирование Шрифтов
            Word.Font TextFont = new Word.Font();
            TextFont.Size          = 8;
            TextFont.Bold          = 0;
            table.Cell(1, 1).Width = namesWidth;
            cellRange      = table.Cell(1, 1).Range;
            cellRange.Font = TextFont;
            #endregion

            formatTable(ref table, ref TextFont, pairLen, dayWidth, namesWidth, namesLen, cellRange);
            setBorders(ref table, pairLen);
            setDateToTable(ref doc, ref TextFont, pairLen, dayWidth, namesWidth, namesLen);

            #region save
            Object fileName                = name;//@"C:\Test\Форматированная_Таблица.doc";
            Object fileFormat              = Type.Missing;
            Object lockComments            = Type.Missing;
            Object password                = Type.Missing;
            Object addToRecentFiles        = Type.Missing;
            Object writePassword           = Type.Missing;
            Object readOnlyRecommended     = Type.Missing;
            Object embedTrueTypeFonts      = Type.Missing;
            Object saveNativePictureFormat = Type.Missing;
            Object saveFormsData           = Type.Missing;
            Object saveAsAOCELetter        = Type.Missing;
            Object encoding                = Type.Missing;
            Object insertLineBreaks        = Type.Missing;
            Object allowSubstitutions      = Type.Missing;
            Object lineEnding              = Type.Missing;
            Object addBiDiMarks            = Type.Missing;

            doc.SaveAs(ref fileName, ref fileFormat, ref lockComments,
                       ref password, ref addToRecentFiles, ref writePassword,
                       ref readOnlyRecommended, ref embedTrueTypeFonts,
                       ref saveNativePictureFormat, ref saveFormsData,
                       ref saveAsAOCELetter, ref encoding, ref insertLineBreaks,
                       ref allowSubstitutions, ref lineEnding, ref addBiDiMarks);


            Object saveChanges    = Word.WdSaveOptions.wdSaveChanges;
            Object originalFormat = Type.Missing;
            Object routeDocument  = Type.Missing;
            app.Quit(ref saveChanges, ref originalFormat, ref routeDocument);
            #endregion
        }
Exemplo n.º 19
0
        public static void AutomateWord()
        {
            object missing = Type.Missing;
            object notTrue = false;

            Word.Application oWord    = null;
            Word.Documents   oDocs    = null;
            Word.Document    oDoc     = null;
            Word.Paragraphs  oParas   = null;
            Word.Paragraph   oPara    = null;
            Word.Range       oParaRng = null;
            Word.Font        oFont    = null;

            try
            {
                // Create an instance of Microsoft Word and make it invisible.

                oWord         = new Word.Application();
                oWord.Visible = false;
                Console.WriteLine("Word.Application is started");

                // Create a new Document and add it to document collection.
                oDoc = oWord.Documents.Add(ref missing, ref missing, ref missing, ref missing);
                Console.WriteLine("A new document is created");

                // Insert a paragraph.

                Console.WriteLine("Insert a paragraph");

                oParas        = oDoc.Paragraphs;
                oPara         = oParas.Add(ref missing);
                oParaRng      = oPara.Range;
                oParaRng.Text = "Heading 1";
                oFont         = oParaRng.Font;
                oFont.Bold    = 1;
                oParaRng.InsertParagraphAfter();

                // Save the document as a docx file and close it.

                Console.WriteLine("Save and close the document");

                object fileName = Path.GetDirectoryName(
                    Assembly.GetExecutingAssembly().Location) + "\\Sample1.docx";
                object fileFormat = Word.WdSaveFormat.wdFormatXMLDocument;

                // Saves the document with a new name or format.
                // Some of the arguments for this method correspond to
                // the options in the Save As dialog box.
                // For details,please refer to
                // :http://msdn.microsoft.com/en-us/library/microsoft.office.tools.word.document.saveas(VS.80).aspx
                oDoc.SaveAs(ref fileName, ref fileFormat, ref missing,
                            ref missing, ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing, ref missing,
                            ref missing);
                ((Word._Document)oDoc).Close(ref missing, ref missing,
                                             ref missing);

                // Quit the Word application.

                Console.WriteLine("Quit the Word application");
                ((Word._Application)oWord).Quit(ref notTrue, ref missing,
                                                ref missing);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Solution1.AutomateWord throws the error: {0}",
                                  ex.Message);
            }
            finally
            {
                // Clean up the unmanaged Word COM resources by explicitly
                // calling Marshal.FinalReleaseComObject on all accessor objects.
                // See http://support.microsoft.com/kb/317109.

                if (oFont != null)
                {
                    Marshal.FinalReleaseComObject(oFont);
                    oFont = null;
                }
                if (oParaRng != null)
                {
                    Marshal.FinalReleaseComObject(oParaRng);
                    oParaRng = null;
                }
                if (oPara != null)
                {
                    Marshal.FinalReleaseComObject(oPara);
                    oPara = null;
                }
                if (oParas != null)
                {
                    Marshal.FinalReleaseComObject(oParas);
                    oParas = null;
                }
                if (oDoc != null)
                {
                    Marshal.FinalReleaseComObject(oDoc);
                    oDoc = null;
                }
                if (oDocs != null)
                {
                    Marshal.FinalReleaseComObject(oDocs);
                    oDocs = null;
                }
                if (oWord != null)
                {
                    Marshal.FinalReleaseComObject(oWord);
                    oWord = null;
                }
            }
        }
        private void CreateStyle_IndexHeading()
        {
            Common.WordHelper.DeleteStyle(cINDEX_HEADING_STYLE);

            Document activeDoc = Globals.ThisAddIn.Application.ActiveDocument;

            Style newStyle = activeDoc.Styles.Add(Name: cINDEX_HEADING_STYLE, Type: WdStyleType.wdStyleTypeParagraph);

            newStyle.AutomaticallyUpdate = false;
            newStyle.NoSpaceBetweenParagraphsOfSameStyle = false;
            newStyle.ParagraphFormat.TabStops.ClearAll();
            newStyle.LanguageID = WdLanguageID.wdEnglishUS;
            newStyle.NoProofing = 0;
            newStyle.Frame.Delete();

            //activeDoc.Styles[cINDEX_HEADING_SYTLE].AutomaticallyUpdate = false;

            Microsoft.Office.Interop.Word.Font font = activeDoc.Styles[cINDEX_HEADING_STYLE].Font;

            font.Name                 = "+Body";
            font.Size                 = 12;
            font.Italic               = 0;
            font.Underline            = WdUnderline.wdUnderlineNone;
            font.UnderlineColor       = WdColor.wdColorAutomatic;
            font.StrikeThrough        = 0;
            font.Outline              = 0;
            font.Emboss               = 0;
            font.Shadow               = 0;
            font.Hidden               = 0;
            font.SmallCaps            = 0;
            font.AllCaps              = 0;
            font.Color                = WdColor.wdColorBlue;
            font.Engrave              = 0;
            font.Subscript            = 0;
            font.Scaling              = 100;
            font.Kerning              = 0;
            font.Animation            = WdAnimation.wdAnimationNone;
            font.Ligatures            = WdLigatures.wdLigaturesNone;
            font.NumberSpacing        = WdNumberSpacing.wdNumberSpacingDefault;
            font.NumberForm           = WdNumberForm.wdNumberFormDefault;
            font.StylisticSet         = WdStylisticSet.wdStylisticSetDefault;
            font.ContextualAlternates = 0;

            Microsoft.Office.Interop.Word.ParagraphFormat paragraphFormat = activeDoc.Styles[cINDEX_HEADING_STYLE].ParagraphFormat;

            paragraphFormat.LeftIndent      = Globals.ThisAddIn.Application.InchesToPoints(0);
            paragraphFormat.RightIndent     = Globals.ThisAddIn.Application.InchesToPoints(0);
            paragraphFormat.SpaceBefore     = 0;
            paragraphFormat.SpaceBeforeAuto = 0;
            paragraphFormat.SpaceAfter      = 6;
            paragraphFormat.SpaceAfterAuto  = 0;
            paragraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceMultiple;
            paragraphFormat.LineSpacing     = Globals.ThisAddIn.Application.LinesToPoints((float)1.15);
            paragraphFormat.Alignment       = WdParagraphAlignment.wdAlignParagraphCenter;
            // This throws exception.
            //paragraphFormat.WidowControl = 1;
            paragraphFormat.KeepTogether                 = 0;
            paragraphFormat.KeepWithNext                 = 0;
            paragraphFormat.PageBreakBefore              = 0;
            paragraphFormat.NoLineNumber                 = 0;
            paragraphFormat.Hyphenation                  = 0;
            paragraphFormat.FirstLineIndent              = Globals.ThisAddIn.Application.InchesToPoints(0);
            paragraphFormat.OutlineLevel                 = WdOutlineLevel.wdOutlineLevelBodyText;
            paragraphFormat.CharacterUnitLeftIndent      = 0;
            paragraphFormat.CharacterUnitRightIndent     = 0;
            paragraphFormat.CharacterUnitFirstLineIndent = 0;
            paragraphFormat.LineUnitBefore               = 0;
            paragraphFormat.LineUnitAfter                = 0;
            paragraphFormat.MirrorIndents                = 0;
            paragraphFormat.TextboxTightWrap             = WdTextboxTightWrap.wdTightNone;

            paragraphFormat.Shading.Texture = WdTextureIndex.wdTextureNone;
            paragraphFormat.Shading.ForegroundPatternColor = WdColor.wdColorAutomatic;
            paragraphFormat.Shading.BackgroundPatternColor = WdColor.wdColorAutomatic;

            paragraphFormat.Borders[WdBorderType.wdBorderLeft].LineStyle   = WdLineStyle.wdLineStyleNone;
            paragraphFormat.Borders[WdBorderType.wdBorderRight].LineStyle  = WdLineStyle.wdLineStyleNone;
            paragraphFormat.Borders[WdBorderType.wdBorderTop].LineStyle    = WdLineStyle.wdLineStyleNone;
            paragraphFormat.Borders[WdBorderType.wdBorderBottom].LineStyle = WdLineStyle.wdLineStyleNone;

            paragraphFormat.Borders.DistanceFromTop    = 1;
            paragraphFormat.Borders.DistanceFromLeft   = 4;
            paragraphFormat.Borders.DistanceFromBottom = 1;
            paragraphFormat.Borders.DistanceFromRight  = 4;
        }
Exemplo n.º 21
0
        public static void AutomateWord()
        {
            object missing = Type.Missing;
            object notTrue = false;

            Word.Application oWord    = null;
            Word.Documents   oDocs    = null;
            Word.Document    oDoc     = null;
            Word.Paragraphs  oParas   = null;
            Word.Paragraph   oPara    = null;
            Word.Range       oParaRng = null;
            Word.Font        oFont    = null;

            try
            {
                // 创建一个Microsoft Word实例并令其不可见

                oWord         = new Word.Application();
                oWord.Visible = false;
                Console.WriteLine("Word.Application is started");

                // 创建一个新的文档

                oDocs = oWord.Documents;
                oDoc  = oDocs.Add(ref missing, ref missing, ref missing, ref missing);
                Console.WriteLine("A new document is created");

                // 插入段落

                Console.WriteLine("Insert a paragraph");

                oParas        = oDoc.Paragraphs;
                oPara         = oParas.Add(ref missing);
                oParaRng      = oPara.Range;
                oParaRng.Text = "Heading 1";
                oFont         = oParaRng.Font;
                oFont.Bold    = 1;
                oParaRng.InsertParagraphAfter();

                // 将文档保存为.docx文件并关闭

                Console.WriteLine("Save and close the document");

                object fileName = Path.GetDirectoryName(
                    Assembly.GetExecutingAssembly().Location) + "\\Sample1.docx";
                object fileFormat = Word.WdSaveFormat.wdFormatXMLDocument;
                oDoc.SaveAs(ref fileName, ref fileFormat, ref missing,
                            ref missing, ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing, ref missing,
                            ref missing, ref missing, ref missing, ref missing,
                            ref missing);
                ((Word._Document)oDoc).Close(ref missing, ref missing,
                                             ref missing);

                // 退出Word应用程序

                Console.WriteLine("Quit the Word application");
                ((Word._Application)oWord).Quit(ref notTrue, ref missing,
                                                ref missing);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Solution1.AutomateWord throws the error: {0}",
                                  ex.Message);
            }
            finally
            {
                // 通过在所有访问对象上显示调用Marshal.FinalReleaseComObject方法
                // 释放非托管Word COM资源
                // 见 http://support.microsoft.com/kb/317109.

                if (oFont != null)
                {
                    Marshal.FinalReleaseComObject(oFont);
                    oFont = null;
                }
                if (oParaRng != null)
                {
                    Marshal.FinalReleaseComObject(oParaRng);
                    oParaRng = null;
                }
                if (oPara != null)
                {
                    Marshal.FinalReleaseComObject(oPara);
                    oPara = null;
                }
                if (oParas != null)
                {
                    Marshal.FinalReleaseComObject(oParas);
                    oParas = null;
                }
                if (oDoc != null)
                {
                    Marshal.FinalReleaseComObject(oDoc);
                    oDoc = null;
                }
                if (oDocs != null)
                {
                    Marshal.FinalReleaseComObject(oDocs);
                    oDocs = null;
                }
                if (oWord != null)
                {
                    Marshal.FinalReleaseComObject(oWord);
                    oWord = null;
                }
            }
        }
        public static bool justificationMax(string fileName, int numBits, out List <int> lines)
        {
            lines = new List <int>();
            Application oWord;
            object      oMissing = Type.Missing;

            oWord         = new Application();
            oWord.Visible = false;
            Document doc = oWord.Documents.Open(fileName);

            string strLine;
            bool   bolEOF = false;
            int    noBits = 0;

            doc.Characters[1].Select();
            do
            {
                object unit  = WdUnits.wdLine;
                object count = 1;
                oWord.Selection.MoveEnd(ref unit, ref count);

                strLine = oWord.Selection.Text;
                Range rgn       = oWord.Selection.Range;
                float d         = (rgn.ComputeStatistics(WdStatistic.wdStatisticWords) - 1) / 2;
                int   maxSpaces = (int)Math.Floor(d);

                Microsoft.Office.Interop.Word.Font font = rgn.Font;
                string fontName = font.Name;
                float  fontSize = font.Size;


                PageSetup p = oWord.Selection.PageSetup;

                float margR            = p.RightMargin; //72
                float margL            = p.LeftMargin;  //72
                float pageWidth        = p.PageWidth;   //595.3 - 72*2 ukupno za tekst 451.3
                int   u                = doc.Application.Width;
                System.Drawing.Font f1 = new System.Drawing.Font(fontName, fontSize, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                Image    fakeImage     = new Bitmap(1, 1);
                Graphics graphics      = Graphics.FromImage(fakeImage);
                graphics.PageUnit = GraphicsUnit.Point;
                SizeF size      = graphics.MeasureString(strLine, f1, 0, StringFormat.GenericTypographic);
                SizeF sizeSpace = graphics.MeasureString(" ", f1);



                float maxSpacesPom = (pageWidth - margL - margR - size.Width)
                                     / sizeSpace.Width;
                int maxSpaces1 = (int)Math.Floor(maxSpacesPom);

                maxSpaces = (maxSpaces < maxSpaces1) ? maxSpaces : maxSpaces1;  //konacan broj spaceova
                if (maxSpaces > 0)
                {
                    noBits += maxSpaces;
                }
                lines.Add(maxSpaces);

                object direction = WdCollapseDirection.wdCollapseEnd;
                oWord.Selection.Collapse(ref direction);

                if (oWord.Selection.Bookmarks.Exists(@"\EndOfDoc"))
                {
                    bolEOF = true;
                }
            } while (!bolEOF);


            doc.Close();
            doc = null;
            oWord.Quit();
            if (noBits >= numBits)
            {
                return(true);
            }
            return(false);
        }
Exemplo n.º 23
0
 public ContentItem()
 {
     Font = new Word.Font();
 }
        private static void AddMarkingHeaderToDocument(ProtectiveMarking marking, Word.Document document)
        {
            Debug.WriteLine("PspfMarkingsAddIn: AddMarkingHeaderToDocument");
            Debug.WriteLine("==============================================================================");

            Word.Range           range  = null;
            Word.Font            font   = null;
            Word.ParagraphFormat format = null;

            try
            {
                object start = 0;
                object end   = 0;

                // Move to start
                range = document.Range(ref start, ref end);

                // Insert Paragraph break
                range.InsertParagraphAfter();

                Marshal.ReleaseComObject(range);

                // Move to start
                range = document.Range(ref start, ref end);

                range.Text = marking.MailBodyHeaderText;

                font = range.Font;

                if (!string.IsNullOrWhiteSpace(marking.MailBodyHeaderColour))
                {
                    var colorConverter = new ColorConverter();

                    var color = (Color)colorConverter.ConvertFromString(marking.MailBodyHeaderColour);

                    font.Color = (Word.WdColor)(color.R + 0x100 * color.G + 0x10000 * color.B);
                }

                if (!string.IsNullOrWhiteSpace(marking.MailBodyHeaderSizePoints))
                {
                    font.Size = float.Parse(marking.MailBodyHeaderSizePoints);
                }

                if (!string.IsNullOrWhiteSpace(marking.MailBodyHeaderFont))
                {
                    font.Name = marking.MailBodyHeaderFont;
                }

                if (!string.IsNullOrWhiteSpace(marking.MailBodyHeaderAlign))
                {
                    format = range.ParagraphFormat;

                    switch (marking.MailBodyHeaderAlign.ToLowerInvariant())
                    {
                    case "center":
                    case "centre":
                    case "middle":
                        format.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                        break;

                    case "left":
                    case "normal":
                        format.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
                        break;

                    case "right":
                        format.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
                        break;

                    default:
                        Debug.WriteLine("Unexpected text alignment: " + marking.MailBodyHeaderAlign);
                        break;
                    }
                }

                // Force the edit to persist:
                document.Activate();
            }
            finally
            {
                if (format != null)
                {
                    Marshal.ReleaseComObject(format);
                }

                if (font != null)
                {
                    Marshal.ReleaseComObject(font);
                }

                if (range != null)
                {
                    Marshal.ReleaseComObject(range);
                }
            }
        }
Exemplo n.º 25
0
 public ContentItem(ContentType type, string text, Word.Font font)
 {
     Type = type;
     Text = text;
     Font = font;
 }
Exemplo n.º 26
0
        // 复制到WORD内置定义FONT的参数
        public void copy2(Word.Font fnt)
        {
            fnt.AllCaps   = this.AllCaps;                       // 复制到WORD内置定义FONT的参数
            fnt.Animation = (Word.WdAnimation) this.Animations; // wdAnimationNone// 复制到WORD内置定义FONT的参数
            fnt.Bold      = this.Bold;                          // 复制到WORD内置定义FONT的参数
            fnt.BoldBi    = this.BoldBi;                        // 复制到WORD内置定义FONT的参数

            int nTmp = 0;

            fnt.Color = WdColor.wdColorAutomatic;// 复制到WORD内置定义FONT的参数
            if (int.TryParse(this.ColorRGB, out nTmp))
            {
                fnt.Color = (WdColor)nTmp;// 复制到WORD内置定义FONT的参数
            }

            fnt.DoubleStrikeThrough = this.DoubleStrikeThrough; // 复制到WORD内置定义FONT的参数
            fnt.Emboss      = this.Emboss;                      // 复制到WORD内置定义FONT的参数
            fnt.Engrave     = this.Engrave;                     // 复制到WORD内置定义FONT的参数
            fnt.NameAscii   = this.FontHighAnsi;                //"Arial Unicode MS"// 复制到WORD内置定义FONT的参数
            fnt.NameOther   = this.FontLowAnsi;                 //"Arial Unicode MS"// 复制到WORD内置定义FONT的参数
            fnt.NameFarEast = this.FontMajor;                   //"微软雅黑"// 复制到WORD内置定义FONT的参数
            fnt.Name        = this.FontMajor;                   // 复制到WORD内置定义FONT的参数

            fnt.Hidden   = this.Hidden;                         // 复制到WORD内置定义FONT的参数
            fnt.Italic   = this.Italic;                         // 复制到WORD内置定义FONT的参数
            fnt.ItalicBi = this.ItalicBi;                       // 复制到WORD内置定义FONT的参数

            float fTmp = 0.0f;

            if (this.Kerning > 0)
            {
                if (m_hashPointsDialog2Size.Contains(this.KerningMin))             // 复制到WORD内置定义FONT的参数
                {
                    fnt.Kerning = (float)m_hashPointsDialog2Size[this.KerningMin]; // this.point// 复制到WORD内置定义FONT的参数
                }
                else
                {
                    if (float.TryParse(this.KerningMin, out fTmp)) // 复制到WORD内置定义FONT的参数
                    {
                        fnt.Kerning = fTmp;                        // 复制到WORD内置定义FONT的参数
                    }
                    else
                    {
                        fnt.Kerning = 0.0f;// 复制到WORD内置定义FONT的参数
                    }
                }
            }
            else
            {
                fnt.Kerning = this.Kerning; // 0.0f// 复制到WORD内置定义FONT的参数
            }

            fnt.Outline = this.Outline;                // 复制到WORD内置定义FONT的参数

            if (int.TryParse(this.Position, out nTmp)) // 复制到WORD内置定义FONT的参数
            {
                fnt.Position = nTmp;                   // 复制到WORD内置定义FONT的参数
            }
            else
            {
                fnt.Position = 0;// 复制到WORD内置定义FONT的参数
            }

            if (int.TryParse(this.Scale.Replace("%", ""), out nTmp)) // 复制到WORD内置定义FONT的参数
            {
                fnt.Scaling = nTmp;                                  // 复制到WORD内置定义FONT的参数
            }
            else
            {
                fnt.Scaling = 100;// 复制到WORD内置定义FONT的参数
            }

            fnt.Shadow    = this.Shadow;    // 复制到WORD内置定义FONT的参数
            fnt.SmallCaps = this.SmallCaps; // 复制到WORD内置定义FONT的参数


            if (float.TryParse(this.Spacing, out fTmp)) // 复制到WORD内置定义FONT的参数
            {
                fnt.Spacing = fTmp;                     // 复制到WORD内置定义FONT的参数
            }
            else
            {
                fnt.Spacing = 0.0f;// 复制到WORD内置定义FONT的参数
            }


            fnt.StrikeThrough = this.StrikeThrough;          // 复制到WORD内置定义FONT的参数
            fnt.Subscript     = this.Subscript;              // 复制到WORD内置定义FONT的参数
            fnt.Superscript   = this.Superscript;            // 复制到WORD内置定义FONT的参数

            fnt.UnderlineColor = WdColor.wdColorAutomatic;   // 复制到WORD内置定义FONT的参数
            if (int.TryParse(this.UnderlineColor, out nTmp)) // 复制到WORD内置定义FONT的参数
            {
                fnt.UnderlineColor = (WdColor)nTmp;          // 复制到WORD内置定义FONT的参数
            }

            fnt.Underline = WdUnderline.wdUnderlineNone;                                     // 复制到WORD内置定义FONT的参数
            if (m_hashUnderlineDialog2WordFont.Contains(this.Underline))                     // 复制到WORD内置定义FONT的参数
            {
                fnt.Underline = (WdUnderline)m_hashUnderlineDialog2WordFont[this.Underline]; // wdUnderlineNone// 复制到WORD内置定义FONT的参数
            }

            if (m_hashPointsDialog2Size.Contains(this.Points))          // 复制到WORD内置定义FONT的参数
            {
                fnt.Size = (float)m_hashPointsDialog2Size[this.Points]; // this.point// 复制到WORD内置定义FONT的参数
            }
            else
            {
                if (float.TryParse(this.Points, out fTmp)) // 复制到WORD内置定义FONT的参数
                {
                    fnt.Size = fTmp;                       // 复制到WORD内置定义FONT的参数
                }
                else
                {
                    fnt.Size = 14.0f;// 复制到WORD内置定义FONT的参数
                }
            }

            if (m_hashPointsDialog2Size.Contains(this.PointsBi))            // 复制到WORD内置定义FONT的参数
            {
                fnt.SizeBi = (float)m_hashPointsDialog2Size[this.PointsBi]; // this.PointsBi// 复制到WORD内置定义FONT的参数
            }
            else
            {
                if (float.TryParse(this.PointsBi, out fTmp)) // 复制到WORD内置定义FONT的参数
                {
                    fnt.SizeBi = fTmp;                       // 复制到WORD内置定义FONT的参数
                }
                else
                {
                    fnt.SizeBi = 14.0f;// 复制到WORD内置定义FONT的参数
                }
            }

            fnt.DisableCharacterSpaceGrid = (this.CharacterWidthGrid != 0);// 复制到WORD内置定义FONT的参数

            return;
        }