示例#1
0
 public GanttToRTFConverter(string path)
 {
     this.path = path;
     rtfPath = path.Remove( path.Length-3, 3);
     rtfPath = rtfPath + "rtf";
     doc = new RtfDocument(rtfPath);
 }
示例#2
0
 static void Main(string[] args)
 {
     RtfDocument doc = new RtfDocument(Encoding.Unicode);
     doc.AddText("Some note yo\n123\n\n133\nψυχή", new RtfCharFormat { Font = "Calibri", Size = 11 });
     Console.Write(doc.Rtf);
     Trace.Write(doc.Rtf);
     Console.In.Read();
 }
示例#3
0
        /**
         * Constructs a RtfFont from a com.lowagie.text.Font
         * @param doc The RtfDocument this font appears in
         * @param font The Font to use as a base
         */
        public RtfFont(RtfDocument doc, Font font)
        {
            this.document = doc;
            if (font != null)
            {
                if (font is RtfFont)
                {
                    this.fontName = ((RtfFont)font).GetFontName();
                    this.charset  = ((RtfFont)font).GetCharset();
                }
                else
                {
                    SetToDefaultFamily(font.Familyname);
                }
                if (font.BaseFont != null)
                {
                    String[][] fontNames = font.BaseFont.FullFontName;
                    for (int i = 0; i < fontNames.Length; i++)
                    {
                        if (fontNames[i][2].Equals("0"))
                        {
                            this.fontName = fontNames[i][3];
                            break;
                        }
                        else if (fontNames[i][2].Equals("1033") || fontNames[i][2].Equals(""))
                        {
                            this.fontName = fontNames[i][3];
                        }
                    }
                }
                Size = font.Size;
                SetStyle(font.Style);
                Color = font.Color;
                if (document != null)
                {
                    this.fontNumber = document.GetDocumentHeader().GetFontNumber(this);
                }
            }
            if (Util.EqualsIgnoreCase(this.fontName, "unknown"))
            {
                return;
            }

            if (document != null)
            {
                SetRtfDocument(document);
            }
        }
        private void btnReport_Click(object sender, EventArgs e)
        {
            RtfDocument  doc = new RtfDocument(PaperSize.A4, PaperOrientation.Landscape, Lcid.Russian);
            RtfParagraph p   = doc.addParagraph();

            p.Text = "Статистика победителей и призёров олимпиад по регионам";

            p      = doc.addParagraph();
            p.Text = FacultyId.HasValue ? cbFaculty.Text : "";

            p      = doc.addParagraph();
            p.Text = StudyFormId.HasValue ? "" + cbStudyForm.Text : "";

            p      = doc.addParagraph();
            p.Text = StudyBasisId.HasValue ? "" + cbStudyBasis.Text : "";
        }
示例#5
0
        public void ReadingDirectionShouldBeSetBasedOnCulture()
        {
            var rtfDocument = new RtfDocument(PaperSize.A4, PaperOrientation.Landscape, Lcid.English);
            int rows        = 1;
            int columns     = 2;

            //Add Paragraph
            var rtfParagraph = rtfDocument.addParagraph();

            rtfParagraph.setText("Testing\n");

            //Add Table
            var rtfTable = rtfDocument.addTable(rows, columns, 10);

            //Add a cell in Table
            for (var i = 0; i < rtfTable.RowCount; i++)
            {
                for (var j = 0; j < rtfTable.ColCount; j++)
                {
                    rtfTable.cell(i, j).addParagraph().setText("CELL " + i + "," + j);
                }
            }

            //Add Section
            var rtfSection = rtfDocument.addSection(SectionStartEnd.Start, rtfDocument);

            //Add Image

            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("RtfWriter.UnitTests.Images.demo5.jpg"))
            {
                using (var memoryStream = new MemoryStream())
                {
                    stream.CopyTo(memoryStream);
                    var rtfImage = rtfDocument.addImage(memoryStream);
                    Assert.AreEqual(ReadingDirection.LeftToRight, rtfImage.ReadingDirection);
                }
            }

            //Get Particular cell in Table to test Direction
            var rtfTableCell = rtfTable.cell(0, 1);

            Assert.AreEqual(ReadingDirection.LeftToRight, rtfParagraph.ReadingDirection);
            Assert.AreEqual(ReadingDirection.LeftToRight, rtfTable.ReadingDirection);
            Assert.AreEqual(ReadingDirection.LeftToRight, rtfTableCell.ReadingDirection);

            Assert.AreEqual(ReadingDirection.LeftToRight, rtfSection.ReadingDirection);
        }
示例#6
0
        public void AddImageInRtfDocumentTest()
        {
            var rtfDocument = new RtfDocument(PaperSize.A4, PaperOrientation.Landscape,
                                              new CultureInfo("en-US"));

            using (
                var stream =
                    Assembly.GetExecutingAssembly().GetManifestResourceStream("RtfWriter.UnitTests.Images.demo5.jpg"))
            {
                using (var memoryStream = new MemoryStream())
                {
                    stream.CopyTo(memoryStream);
                    var rtfImage = rtfDocument.addImage(memoryStream);
                    Assert.IsNotNull(rtfImage.Width);
                }
            }
        }
示例#7
0
        /**
         * Constructs a RtfParagraph belonging to a RtfDocument based on a Paragraph.
         *
         * @param doc The RtfDocument this RtfParagraph belongs to
         * @param paragraph The Paragraph that this RtfParagraph is based on
         */
        public RtfParagraph(RtfDocument doc, Paragraph paragraph) : base(doc)
        {
            ST.RtfFont baseFont = null;
            if (paragraph.Font is ST.RtfParagraphStyle)
            {
                this.paragraphStyle = this.document.GetDocumentHeader().GetRtfParagraphStyle(((ST.RtfParagraphStyle)paragraph.Font).GetStyleName());
                baseFont            = this.paragraphStyle;
            }
            else
            {
                baseFont            = new ST.RtfFont(this.document, paragraph.Font);
                this.paragraphStyle = new ST.RtfParagraphStyle(this.document, this.document.GetDocumentHeader().GetRtfParagraphStyle("Normal"));
                this.paragraphStyle.SetAlignment(paragraph.Alignment);
                this.paragraphStyle.SetFirstLineIndent((int)(paragraph.FirstLineIndent * RtfElement.TWIPS_FACTOR));
                this.paragraphStyle.SetIndentLeft((int)(paragraph.IndentationLeft * RtfElement.TWIPS_FACTOR));
                this.paragraphStyle.SetIndentRight((int)(paragraph.IndentationRight * RtfElement.TWIPS_FACTOR));
                this.paragraphStyle.SetSpacingBefore((int)(paragraph.SpacingBefore * RtfElement.TWIPS_FACTOR));
                this.paragraphStyle.SetSpacingAfter((int)(paragraph.SpacingAfter * RtfElement.TWIPS_FACTOR));
                if (paragraph.HasLeading())
                {
                    this.paragraphStyle.SetLineLeading((int)(paragraph.Leading * RtfElement.TWIPS_FACTOR));
                }
                this.paragraphStyle.SetKeepTogether(paragraph.KeepTogether);
            }

            for (int i = 0; i < paragraph.Count; i++)
            {
                IElement chunk = (IElement)paragraph[i];
                if (chunk is Chunk)
                {
                    ((Chunk)chunk).Font = baseFont.Difference(((Chunk)chunk).Font);
                }
                else if (chunk is RtfImage)
                {
                    ((RtfImage)chunks[i]).SetAlignment(this.paragraphStyle.GetAlignment());
                }
                try {
                    IRtfBasicElement[] rtfElements = doc.GetMapper().MapElement(chunk);
                    for (int j = 0; j < rtfElements.Length; j++)
                    {
                        chunks.Add(rtfElements[j]);
                    }
                } catch (DocumentException) {
                }
            }
        }
示例#8
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Process PDF");
            Console.WriteLine("------------------");
            DocumentReader reader = new PdfDocument();

            reader.OpenDocument();


            Console.WriteLine("\nProcess RTF");
            Console.WriteLine("------------------");
            reader = new RtfDocument();
            reader.OpenDocument();


            Console.ReadKey();
        }
        /// <summary>
        /// Gets the name of the exported file.
        /// </summary>
        /// <param name="appealLetter">The appeal letter container.</param>
        /// <param name="reportVirtualPath">The report virtual path.</param>
        /// <param name="fileBaseName">Name of the file base.</param>
        /// <returns></returns>
        public static string[] GetExportedFileName(AppealLetter appealLetter, string reportVirtualPath, string fileBaseName)
        {
            string fileName;

            if (appealLetter.ReportThreshold == Constants.ReportThreshold) // Exceeded threshold limit
            {
                fileName = Convert.ToString(Constants.ReportThreshold);
            }
            else if (appealLetter.AppealLetterClaims.Count == 0) //No Records Found
            {
                fileName = Constants.EmptyReportResult;
            }
            else
            {
                _appealLetter = appealLetter;
                string dateTimeStamp = DateTime.Now.ToString(Constants.DateTimeExtendedFormat);
                fileName  = string.Format("{0}{1}.{2}", fileBaseName, dateTimeStamp, Constants.AppealLetterFileExtension);
                _filePath = Path.Combine(reportVirtualPath, fileName);
                //Build rtf document object
                RtfDocument rtfDocument = GetRtfDocument();

                //Get rtf content String
                RtfWriter rtfWriter          = new RtfWriter();
                string    templateRtfContent = rtfWriter.GetRtfContent(rtfDocument);
                //loop through each claim data and replace claim text and merge rtf content
                string finalRtfContent = _appealLetter.AppealLetterClaims.Select(
                    appealLetterClaim => ReplaceClaimData(templateRtfContent, appealLetterClaim))
                                         .Aggregate(string.Empty,
                                                    (current, rtfClaimText) =>
                                                    !string.IsNullOrEmpty(current)
                                ? MergeRtfContent(current, rtfClaimText)
                                : rtfClaimText);

                //Write rtf content into file
                using (TextWriter writer = new StreamWriter(_filePath))
                {
                    rtfWriter.Write(writer, finalRtfContent);
                }
                if (appealLetter.IsPreview)
                {
                    return(new[] { appealLetter.LetterTemplaterText, fileName });
                }
            }
            return(new[] { fileName });
        }
示例#10
0
        /**
         * Constructs a RtfChunk based on the content of a Chunk
         *
         * @param doc The RtfDocument that this Chunk belongs to
         * @param chunk The Chunk that this RtfChunk is based on
         */
        public RtfChunk(RtfDocument doc, Chunk chunk) : base(doc)
        {
            if (chunk == null)
            {
                return;
            }

            if (chunk.Attributes != null && chunk.Attributes[Chunk.SUBSUPSCRIPT] != null)
            {
                this.superSubScript = (float)chunk.Attributes[Chunk.SUBSUPSCRIPT];
            }
            if (chunk.Attributes != null && chunk.Attributes[Chunk.BACKGROUND] != null)
            {
                this.background = new RtfColor(this.document, (Color)((Object[])chunk.Attributes[Chunk.BACKGROUND])[0]);
            }
            font    = new ST.RtfFont(doc, chunk.Font);
            content = chunk.Content;
        }
示例#11
0
        public RtfPageBuilder(string filepath)
        {
            m_strFilepath   = filepath;
            m_doc           = new RtfDocument();
            m_currParagraph = null;

            // resize font table
            m_doc.FontTable.Add(new RtfFont(AppSettings.Settings.Rtf.TextFont.Name));
            m_doc.FontTable.Add(new RtfFont(AppSettings.Settings.Rtf.AttributeFont.Name));
            m_doc.FontTable.Add(new RtfFont(AppSettings.Settings.Rtf.HyperlinkFont.Name));

            // resize color table
            m_doc.ColorTable.Add(new RtfColor(ColorTranslator.FromHtml(AppSettings.Settings.Rtf.TextFont.Color)));
            m_doc.ColorTable.Add(new RtfColor(ColorTranslator.FromHtml(AppSettings.Settings.Rtf.AttributeFont.Color)));
            m_doc.ColorTable.Add(new RtfColor(ColorTranslator.FromHtml(AppSettings.Settings.Rtf.HyperlinkFont.Color)));

            StartNewParagraph();
        }
示例#12
0
        public static void Append()
        {
            RtfDocument doc = new RtfDocument(@"D:\rtfdoc.rtf", System.Text.Encoding.UTF8);


            RtfCharFormat format = new RtfCharFormat();

            format.Size      = 12;
            format.Bold      = false;
            format.Underline = false;
            format.Color     = System.Drawing.Color.Blue;

            doc.AddText("This is a test.", format);
            doc.AddText("This is a {bad} text.");


            doc.Save(@"D:\rtfdoc1.rtf");
        }
示例#13
0
 /**
  * Constructs a RtfBorder
  *
  * @param doc The RtfDocument this RtfBorder belongs to
  * @param borderType The type of border this RtfBorder is
  * @param borderPosition The position of this RtfBorder
  * @param borderStyle The style of this RtfBorder
  * @param borderWidth The width of this RtfBorder
  * @param borderColor The colour of this RtfBorder
  */
 protected internal RtfBorder(RtfDocument doc, int borderType, int borderPosition, int borderStyle, float borderWidth, Color borderColor) : base(doc)
 {
     this.borderType     = borderType;
     this.borderPosition = borderPosition;
     this.borderStyle    = borderStyle;
     this.borderWidth    = (int)Math.Min((borderWidth * TWIPS_FACTOR), 75);
     if (this.borderWidth == 0)
     {
         this.borderStyle = BORDER_NONE;
     }
     if (borderColor == null)
     {
         this.borderColor = new RtfColor(this.document, new Color(0, 0, 0));
     }
     else
     {
         this.borderColor = new RtfColor(this.document, borderColor);
     }
 }
 /// <summary>
 /// Constructs a RtfSection for a given Section. If the autogenerateTOCEntries
 /// property of the RtfDocument is set and the title is not empty then a TOC entry
 /// is generated for the title.
 /// </summary>
 /// <param name="doc">The RtfDocument this RtfSection belongs to</param>
 /// <param name="section">The Section this RtfSection is based on</param>
 public RtfSection(RtfDocument doc, Section section) : base(doc)
 {
     Items = new ArrayList();
     try
     {
         if (section.Title != null)
         {
             Title = (RtfParagraph)doc.GetMapper().MapElement(section.Title)[0];
         }
         if (Document.GetAutogenerateTocEntries())
         {
             StringBuilder titleText = new StringBuilder();
             foreach (IElement element in section.Title)
             {
                 if (element.Type == Element.CHUNK)
                 {
                     titleText.Append(((Chunk)element).Content);
                 }
             }
             if (titleText.ToString().Trim().Length > 0)
             {
                 FD.RtfTocEntry tocEntry = new FD.RtfTocEntry(titleText.ToString());
                 tocEntry.SetRtfDocument(Document);
                 Items.Add(tocEntry);
             }
         }
         foreach (IElement element in section)
         {
             IRtfBasicElement[] rtfElements = doc.GetMapper().MapElement(element);
             for (int i = 0; i < rtfElements.Length; i++)
             {
                 if (rtfElements[i] != null)
                 {
                     Items.Add(rtfElements[i]);
                 }
             }
         }
         updateIndentation(section.IndentationLeft, section.IndentationRight, section.Indentation);
     }
     catch (DocumentException)
     {
     }
 }
        private void createGlobalRtfReport()
        {
            int         maxPagesInReport  = AppSettings.Settings.Rtf.RtfNumberOfPagesInReport;
            RtfDocument globalDoc         = null;
            string      globalDocFilename = "";

            for (int idx = 0; idx < m_allDocuments.Count; idx++)
            {
                if ((idx % maxPagesInReport) == 0)
                {
                    // close the current document
                    if (globalDoc != null)
                    {
                        globalDocFilename = m_reportFolder + String.Format("{0}{1}-{2}.rtf", AppSettings.Settings.Rtf.RtfReportBaseFilename, idx - maxPagesInReport, idx - 1);
                        RtfWriter  rtfWriter = new RtfWriter();
                        TextWriter writer    = new StreamWriter(globalDocFilename);
                        rtfWriter.Write(writer, globalDoc);
                        writer.Close();
                    }

                    // start new document
                    globalDoc = new RtfDocument();
                }

                RtfDocument currDoc = m_allDocuments[idx];
                foreach (RtfDocumentContentBase item in currDoc.Contents)
                {
                    globalDoc.Contents.Add(item);
                }
            }

            // close the last file
            if (globalDoc != null)
            {
                int lastCount = (m_allDocuments.Count / maxPagesInReport) * maxPagesInReport;
                globalDocFilename = m_reportFolder + String.Format("{0}{1}-{2}.rtf", AppSettings.Settings.Rtf.RtfReportBaseFilename, lastCount, m_allDocuments.Count);
                RtfWriter  rtfWriter = new RtfWriter();
                TextWriter writer    = new StreamWriter(globalDocFilename);
                rtfWriter.Write(writer, globalDoc);
                writer.Close();
            }
        }
 /// <summary>
 /// Sets the RtfDocument this RtfElement belongs to
 /// </summary>
 /// <param name="doc">The RtfDocument to use</param>
 public void SetRtfDocument(RtfDocument doc)
 {
     _document = doc;
     if (_headerAll != null)
     {
         _headerAll.SetRtfDocument(_document);
     }
     if (_headerFirst != null)
     {
         _headerFirst.SetRtfDocument(_document);
     }
     if (_headerLeft != null)
     {
         _headerLeft.SetRtfDocument(_document);
     }
     if (_headerRight != null)
     {
         _headerRight.SetRtfDocument(_document);
     }
 }
 /**
  * Sets the RtfDocument this RtfElement belongs to
  *
  * @param doc The RtfDocument to use
  */
 public void SetRtfDocument(RtfDocument doc)
 {
     this.document = doc;
     if (headerAll != null)
     {
         headerAll.SetRtfDocument(this.document);
     }
     if (headerFirst != null)
     {
         headerFirst.SetRtfDocument(this.document);
     }
     if (headerLeft != null)
     {
         headerLeft.SetRtfDocument(this.document);
     }
     if (headerRight != null)
     {
         headerRight.SetRtfDocument(this.document);
     }
 }
示例#18
0
 /**
  * Constructs a RtfHeaderFooter as a copy of an existing RtfHeaderFooter.
  * For internal use only.
  *
  * @param doc The RtfDocument this RtfHeaderFooter belongs to
  * @param headerFooter The RtfHeaderFooter to copy
  * @param displayAt The display location of this RtfHeaderFooter
  */
 protected internal RtfHeaderFooter(RtfDocument doc, RtfHeaderFooter headerFooter, int displayAt) : base(new Phrase(""), false)
 {
     this.document  = doc;
     this.content   = headerFooter.GetContent();
     this.displayAt = displayAt;
     for (int i = 0; i < this.content.Length; i++)
     {
         if (this.content[i] is IElement)
         {
             try {
                 this.content[i] = this.document.GetMapper().MapElement((IElement)this.content[i]);
             } catch (DocumentException) {
             }
         }
         if (this.content[i] is IRtfBasicElement)
         {
             ((IRtfBasicElement)this.content[i]).SetInHeader(true);
         }
     }
 }
示例#19
0
        private void Print()
        {
            doc = new RtfDocument(PaperSize.A4, PaperOrientation.Portrait, Lcid.English);
            doc.Margins[Direction.Top]    = 30;
            doc.Margins[Direction.Bottom] = 30;
            doc.Margins[Direction.Left]   = 50;
            doc.Margins[Direction.Right]  = 30;
            this.TypeParagraph(14, Align.Center, "Характеристика на основе стенов или баллов");
            this.TypeParagraph(14, Align.Center, _tp.description);
            this.TypeParagraph(12, Align.Left, "");
            this.TypeParagraph(12, Align.Left, "");
            this.TypeParagraph(12, Align.Left, "Дата составления: " + DateTime.Now.ToString());
            this.TypeParagraph(12, Align.Left, "ФИО: " + _human.secondname.ToString() + " " + _human.firstname.ToString() + " " + _human.lastname.ToString());
            this.TypeParagraph(12, Align.Left, "Дата рождения: " + _human.birthday.Value.Date.ToLongDateString() + " (" + ((DateTime.Now.Date - _human.birthday.Value.Date).Days / 365) + ")");
            this.TypeParagraph(12, Align.Left, "Пол: " + _fe.gensers.First(g => g.idg == _human.genderid).description);
            this.TypeParagraph(12, Align.Left, "Образование: " + _fe.educations.First(e => e.ide == _human.educationid).description);
            this.TypeParagraph(12, Align.Left, "Подразделение: " + _fe.departments.First(d => d.idd == _human.departmentid).description);
            this.TypeParagraph(12, Align.Left, "");


            foreach (Control c in flp_parent.Controls)
            {
                Recog.Controls.ScaleControl sc = (Recog.Controls.ScaleControl)c;
                if (sc.IsActive == true)
                {
                    this.TypeParagraph(10, Align.Center, sc.ControlScale.Name);
                    this.TypeParagraph(10, Align.Center, "(" + sc.ControlScale.Description + "):");
                    this.TypeParagraph(10, Align.Left, "Баллы: " + sc.ControlScale.Mark + " [Стены: " + sc.ControlScale.Stens + "]" + " {Уровень: " + sc.ControlScale.Level + "}");
                    this.TypeParagraph(10, Align.FullyJustify, "Оценка: " + sc.ControlScale.ResultDescription);
                }
            }

            string filename = _human.secondname.ToString() + "_" + _human.firstname.ToString() + "_" + DateTime.Now.ToShortDateString() + "_" + DateTime.Now.Hour.ToString() + "_" + DateTime.Now.Minute.ToString() + "_КеттеллС.rtf";

            doc.save(filename);
            var p = new Process {
                StartInfo = { FileName = filename }
            };

            p.Start();
        }
示例#20
0
        public void AddSectionInRtfDocumentTest_RTL()
        {
            var rtfDocument = new RtfDocument(PaperSize.A4, PaperOrientation.Landscape, new CultureInfo("ar-AE"));
            var rtfSection  = rtfDocument.addSection(SectionStartEnd.Start, rtfDocument);
            var sb          = new StringBuilder();

            sb.AppendLine(
                string.Format(@"{{\sectd\{0}sect\footery{1}\{2}\sftnbj\qd ", RtlContent, "720", "sectdefaultcl"))
            .AppendLine(@"\pgwsxn0\pghsxn0 \marglsxn0\margrsxn0\margtsxn0\margbsxn0 {\footerr \rtlpar \pard\plain")
            .AppendLine(@"\par ")
            .AppendLine()
            .AppendLine(@"\par")
            .AppendLine("}")
            .AppendLine();


            var actualText = rtfSection.render();

            Assert.AreEqual(SectionStartEnd.Start, rtfSection.StartEnd);
            Assert.AreEqual(actualText.Trim(), sb.ToString().Trim());
        }
示例#21
0
        /**
         * Constructs a RtfParagraphStyle from another RtfParagraphStyle.
         *
         * INTERNAL USE ONLY
         *
         * @param doc The RtfDocument this RtfParagraphStyle belongs to.
         * @param style The RtfParagraphStyle to copy settings from.
         */
        public RtfParagraphStyle(RtfDocument doc, RtfParagraphStyle style) : base(doc, style)
        {
            this.document             = doc;
            this.styleName            = style.GetStyleName();
            this.alignment            = style.GetAlignment();
            this.indentLeft           = (int)(style.GetIndentLeft() * RtfElement.TWIPS_FACTOR);
            this.indentRight          = (int)(style.GetIndentRight() * RtfElement.TWIPS_FACTOR);
            this.spacingBefore        = (int)(style.GetSpacingBefore() * RtfElement.TWIPS_FACTOR);
            this.spacingAfter         = (int)(style.GetSpacingAfter() * RtfElement.TWIPS_FACTOR);
            this.lineLeading          = (int)(style.GetLineLeading() * RtfElement.TWIPS_FACTOR);
            this.keepTogether         = style.GetKeepTogether();
            this.keepTogetherWithNext = style.GetKeepTogetherWithNext();
            this.basedOnName          = style.basedOnName;
            this.modified             = style.modified;
            this.styleNumber          = style.GetStyleNumber();

            if (this.document != null)
            {
                SetRtfDocument(this.document);
            }
        }
示例#22
0
        public void CopySelection(object sender, ExecutedRoutedEventArgs e)
        {
            if (Content.HasSelection)
            {
                if (Math.Abs(Content.SelectionEnd.Chunk.ActualOffset - Content.SelectionStart.Chunk.ActualOffset) > 1024 * 1024)
                {
                    MessageBox.Show("Selection is too large. Use Drag & Drop instead.", "Clipboard", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    return;
                }

                try
                {
                    using (var stream = new MemoryStream())
                    {
                        var rtf    = new RtfDocument();
                        var target = new CompositeChunkWriter(new StreamChunkWriter(stream), new RtfChunkWriter(rtf, Metrics.Encoding));

                        var transfer = new DataTransfer(CurrentSession.Storage, target);
                        transfer.CopySelection(Content.SelectionStart, Content.SelectionEnd);

                        var bytes = stream.ToArray();

                        DataObject data = new DataObject();
                        data.SetData(DataFormats.Text, Metrics.Encoding.GetString(bytes));
                        data.SetData(DataFormats.Rtf, rtf.render());

                        if (bytes.IsBinary())
                        {
                            data.SetData(bytes.GetType().ToString(), bytes);
                        }

                        Clipboard.SetDataObject(data);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
        /// <summary>
        /// Constructs a RtfHeaderFooter based on a HeaderFooter with a certain type and displayAt
        /// location. For internal use only.
        /// </summary>
        /// <param name="doc">The RtfDocument this RtfHeaderFooter belongs to</param>
        /// <param name="headerFooter">The HeaderFooter to base this RtfHeaderFooter on</param>
        /// <param name="type">The type of RtfHeaderFooter</param>
        /// <param name="displayAt">The display location of this RtfHeaderFooter</param>
        protected internal RtfHeaderFooter(RtfDocument doc, HeaderFooter headerFooter, int type, int displayAt) : base(new Phrase(""), false)
        {
            _document  = doc;
            _type      = type;
            _displayAt = displayAt;
            var par = new Paragraph
            {
                Alignment = headerFooter.Alignment
            };

            if (headerFooter.Before != null)
            {
                par.Add(headerFooter.Before);
            }
            if (headerFooter.IsNumbered())
            {
                par.Add(new FD.RtfPageNumber(_document));
            }
            if (headerFooter.After != null)
            {
                par.Add(headerFooter.After);
            }
            try
            {
                _content = new object[1];
                if (_document != null)
                {
                    _content[0] = _document.GetMapper().MapElement(par)[0];
                    ((IRtfBasicElement)_content[0]).SetInHeader(true);
                }
                else
                {
                    _content[0] = par;
                }
            }
            catch (DocumentException)
            {
            }
        }
        /// <summary>
        /// Constructs a RtfParagraphStyle from another RtfParagraphStyle.
        /// INTERNAL USE ONLY
        /// </summary>
        /// <param name="doc">The RtfDocument this RtfParagraphStyle belongs to.</param>
        /// <param name="style">The RtfParagraphStyle to copy settings from.</param>
        public RtfParagraphStyle(RtfDocument doc, RtfParagraphStyle style) : base(doc, style)
        {
            Document              = doc;
            _styleName            = style.GetStyleName();
            _alignment            = style.GetAlignment();
            _firstLineIndent      = (int)(style.GetFirstLineIndent() * RtfElement.TWIPS_FACTOR);
            _indentLeft           = (int)(style.GetIndentLeft() * RtfElement.TWIPS_FACTOR);
            _indentRight          = (int)(style.GetIndentRight() * RtfElement.TWIPS_FACTOR);
            _spacingBefore        = (int)(style.GetSpacingBefore() * RtfElement.TWIPS_FACTOR);
            _spacingAfter         = (int)(style.GetSpacingAfter() * RtfElement.TWIPS_FACTOR);
            _lineLeading          = (int)(style.GetLineLeading() * RtfElement.TWIPS_FACTOR);
            _keepTogether         = style.GetKeepTogether();
            _keepTogetherWithNext = style.GetKeepTogetherWithNext();
            _basedOnName          = style._basedOnName;
            _modified             = style._modified;
            _styleNumber          = style.getStyleNumber();

            if (Document != null)
            {
                SetRtfDocument(Document);
            }
        }
示例#25
0
        /// <summary>
        /// Constructs a new RtfPhrase for the RtfDocument with the given Phrase
        /// </summary>
        /// <param name="doc">The RtfDocument this RtfPhrase belongs to</param>
        /// <param name="phrase">The Phrase this RtfPhrase is based on</param>
        public RtfPhrase(RtfDocument doc, Phrase phrase) : base(doc)
        {
            if (phrase == null)
            {
                return;
            }

            if (phrase.HasLeading())
            {
                _lineLeading = (int)(phrase.Leading * TWIPS_FACTOR);
            }
            else
            {
                _lineLeading = 0;
            }

            var phraseFont = new ST.RtfFont(null, phrase.Font);

            for (var i = 0; i < phrase.Count; i++)
            {
                var chunk = (IElement)phrase[i];
                if (chunk is Chunk)
                {
                    ((Chunk)chunk).Font = phraseFont.Difference(((Chunk)chunk).Font);
                }
                try
                {
                    var rtfElements = doc.GetMapper().MapElement(chunk);
                    for (var j = 0; j < rtfElements.Length; j++)
                    {
                        Chunks.Add(rtfElements[j]);
                    }
                }
                catch (DocumentException)
                {
                }
            }
        }
        /// <summary>
        /// Gets the RTF document.
        /// </summary>
        /// <returns></returns>
        private static RtfDocument GetRtfDocument()
        {
            string templateText = HttpUtility.HtmlDecode(_appealLetter.LetterTemplaterText);

            //Add Content into Paragraph (if letter template is save without pressing enter than no paragraph is coming and for generating rtf we need each content into paragraph)
            if (!templateText.Contains(Constants.HtmlStartTag + Constants.HtmlParagraphTagName))
            {
                templateText = string.Format("{0}{1}{2}", Constants.HtmlParagraphStartTag, templateText, Constants.HtmlParagraphEndTag);
            }

            //Replace Image Path
            templateText = ReplaceImagePath(templateText);

            _htmlDocument = new HtmlDocument();

            //Replace some style attributes for rtf conversion
            templateText = ReplaceStyle(templateText);

            //HTML Div element's attributes will be copied to child paragraph nodes.
            templateText = CloneParentDivHtmlAttributesToChildNodes(templateText);
            templateText = PropagateImageStyleToParagraph(templateText);

            //Get HtmlDocument from templateText
            _htmlDocument.LoadHtml(templateText);

            //Get List of RtfHtmlNode from Document node
            List <RtfHtmlNode> rtfHtmlNodes = GetRtfHtmlNodes(_htmlDocument.DocumentNode);

            //Create rtfDocument object and add default properties
            RtfDocument rtfDocument = new RtfDocument();

            rtfDocument.FontTable.Add(new RtfFont(RtfFontType));

            //Get RtfDocumentContentBase array from list of RtfHtmlNode
            RtfDocumentContentBase[] rtfDocumentContents = GetRtfDocumentContents(rtfHtmlNodes);
            rtfDocument.Contents.AddRange(rtfDocumentContents);
            return(rtfDocument);
        }
 /// <summary>
 /// Constructs a RtfHeaderFooter as a copy of an existing RtfHeaderFooter.
 /// For internal use only.
 /// </summary>
 /// <param name="doc">The RtfDocument this RtfHeaderFooter belongs to</param>
 /// <param name="headerFooter">The RtfHeaderFooter to copy</param>
 /// <param name="displayAt">The display location of this RtfHeaderFooter</param>
 protected internal RtfHeaderFooter(RtfDocument doc, RtfHeaderFooter headerFooter, int displayAt) : base(new Phrase(""), false)
 {
     _document  = doc;
     _content   = headerFooter.getContent();
     _displayAt = displayAt;
     for (var i = 0; i < _content.Length; i++)
     {
         if (_content[i] is IElement)
         {
             try
             {
                 _content[i] = _document.GetMapper().MapElement((IElement)_content[i])[0];
             }
             catch (DocumentException)
             {
             }
         }
         if (_content[i] is IRtfBasicElement)
         {
             ((IRtfBasicElement)_content[i]).SetInHeader(true);
         }
     }
 }
 /**
  * Constructs a RtfHeaderFooterGroup by copying the content of the original
  * RtfHeaderFooterGroup
  *
  * @param doc The RtfDocument this RtfHeaderFooter belongs to
  * @param headerFooter The RtfHeaderFooterGroup to copy
  * @param type The type of RtfHeaderFooterGroup to create
  */
 public RtfHeaderFooterGroup(RtfDocument doc, RtfHeaderFooterGroup headerFooter, int type) : base(new Phrase(""), false)
 {
     this.document = doc;
     this.mode     = headerFooter.GetMode();
     this.type     = type;
     if (headerFooter.GetHeaderAll() != null)
     {
         this.headerAll = new RtfHeaderFooter(this.document, headerFooter.GetHeaderAll(), RtfHeaderFooter.DISPLAY_ALL_PAGES);
     }
     if (headerFooter.GetHeaderFirst() != null)
     {
         this.headerFirst = new RtfHeaderFooter(this.document, headerFooter.GetHeaderFirst(), RtfHeaderFooter.DISPLAY_FIRST_PAGE);
     }
     if (headerFooter.GetHeaderLeft() != null)
     {
         this.headerLeft = new RtfHeaderFooter(this.document, headerFooter.GetHeaderLeft(), RtfHeaderFooter.DISPLAY_LEFT_PAGES);
     }
     if (headerFooter.GetHeaderRight() != null)
     {
         this.headerRight = new RtfHeaderFooter(this.document, headerFooter.GetHeaderRight(), RtfHeaderFooter.DISPLAY_RIGHT_PAGES);
     }
     SetType(this.type);
 }
示例#29
0
 /**
  * Sets the RtfDocument this RtfElement belongs to
  *
  * @param doc The RtfDocument to use
  */
 public void SetRtfDocument(RtfDocument doc)
 {
     this.document = doc;
     if (this.document != null)
     {
         for (int i = 0; i < this.content.Length; i++)
         {
             try {
                 if (this.content[i] is Element)
                 {
                     this.content[i] = this.document.GetMapper().MapElement((IElement)this.content[i]);
                     ((IRtfBasicElement)this.content[i]).SetInHeader(true);
                 }
                 else if (this.content[i] is IRtfBasicElement)
                 {
                     ((IRtfBasicElement)this.content[i]).SetRtfDocument(this.document);
                     ((IRtfBasicElement)this.content[i]).SetInHeader(true);
                 }
             } catch (DocumentException) {
             }
         }
     }
 }
示例#30
0
 /**
  * Constructs a new RtfColorList for the RtfDocument. Will add the default
  * black and white colours.
  *
  * @param doc The RtfDocument this RtfColorList belongs to
  */
 public RtfColorList(RtfDocument doc) : base(doc)
 {
     colorList.Add(new RtfColor(doc, 0, 0, 0, 0));
     colorList.Add(new RtfColor(doc, 255, 255, 255, 1));
 }
 /// <summary>
 /// Creates a RtfFontList
 /// </summary>
 /// <param name="doc">The RtfDocument this RtfFontList belongs to</param>
 public RtfFontList(RtfDocument doc) : base(doc)
 {
     _fontList.Add(new RtfFont(Document, 0));
 }
示例#32
0
 /**
  * Sets the RtfDocument this RtfChunk belongs to.
  *
  * @param doc The RtfDocument to use
  */
 public override void SetRtfDocument(RtfDocument doc)
 {
     base.SetRtfDocument(doc);
     this.font.SetRtfDocument(this.document);
 }
示例#33
0
        public void CreateSimpleDocument()
        {
            RtfDocument doc = new RtfDocument();

            RtfCharFormat charFormat = new RtfCharFormat();
            charFormat.Color = Color.DarkBlue;
            charFormat.Underline = true;
            charFormat.Bold = true;
            doc.UpdateCharFormat(charFormat);

            RtfParFormat parFormat = new RtfParFormat();
            parFormat.Alignment = TextAlignment.Justified;
            doc.UpdateParFormat(parFormat);

            doc.AddText("First Paragraph");
            doc.AddNewParagraph(2);

            doc.SetFormatBold(false);
            doc.SetFormatUnderline(false);
            doc.SetFormatColor(Color.Red);

            doc.AddText("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer quis eros at tortor pharetra laoreet. Donec tortor diam, imperdiet ut porta quis, congue eu justo.");
            doc.AddText("Quisque viverra tellus id mauris tincidunt luctus. Fusce in interdum ipsum. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.");
            doc.AddText("Donec ac leo justo, vitae rutrum elit. Nulla tellus elit, imperdiet luctus porta vel, consectetur quis turpis. Nam purus odio, dictum vitae sollicitudin nec, tempor eget mi.");
            doc.AddText("Etiam vitae porttitor enim. Aenean molestie facilisis magna, quis tincidunt leo placerat in. Maecenas malesuada eleifend nunc vitae cursus.");
            doc.AddNewParagraph(2);

            doc.Save("..\\..\\testdocs\\rtfdocument1.rtf");

            string text1 = doc.Text;
            string rtfcode1 = doc.Rtf;

            doc.AddText("Second Paragraph", charFormat);
            doc.AddNewParagraph(2);

            charFormat.Font = "Courier New";
            charFormat.Color = Color.Green;
            charFormat.Bold = false;
            charFormat.Underline = false;
            doc.UpdateCharFormat(charFormat);

            doc.SetAlignment(TextAlignment.Left);
            doc.SetLeftIndentation(2);
            doc.SetRightIndentation(2);

            doc.AddText("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer quis eros at tortor pharetra laoreet. Donec tortor diam, imperdiet ut porta quis, congue eu justo.");
            doc.AddText("Quisque viverra tellus id mauris tincidunt luctus. Fusce in interdum ipsum. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.");
            doc.AddText("Donec ac leo justo, vitae rutrum elit. Nulla tellus elit, imperdiet luctus porta vel, consectetur quis turpis. Nam purus odio, dictum vitae sollicitudin nec, tempor eget mi.");
            doc.AddText("Etiam vitae porttitor enim. Aenean molestie facilisis magna, quis tincidunt leo placerat in. Maecenas malesuada eleifend nunc vitae cursus.");
            doc.AddNewParagraph(2);

            doc.UpdateCharFormat(charFormat);
            doc.SetFormatUnderline(false);
            doc.SetFormatItalic(true);
            doc.SetFormatColor(Color.DarkBlue);

            doc.SetLeftIndentation(0);

            doc.AddText("Test Doc. Петяв ñáéíó\n");
            doc.AddNewLine(1);
            doc.AddText("\tStop.");

            string text2 = doc.Text;
            string rtfcode2 = doc.Rtf;

            doc.Save("..\\..\\testdocs\\rtfdocument2.rtf");

            StreamReader sr = null;
            sr = new StreamReader("..\\..\\testdocs\\rtfdocument1.rtf");
            string rtf1 = sr.ReadToEnd();
            sr.Close();

            sr = null;
            sr = new StreamReader("..\\..\\testdocs\\rtfdocument2.rtf");
            string rtf2 = sr.ReadToEnd();
            sr.Close();

            sr = new StreamReader("..\\..\\testdocs\\rtf4.txt");
            string rtf4 = sr.ReadToEnd();
            sr.Close();

            sr = new StreamReader("..\\..\\testdocs\\rtf6.txt");
            string rtf6 = sr.ReadToEnd();
            sr.Close();

            sr = new StreamReader("..\\..\\testdocs\\doctext1.txt");
            string doctext1 = sr.ReadToEnd();
            sr.Close();

            sr = new StreamReader("..\\..\\testdocs\\doctext2.txt");
            string doctext2 = sr.ReadToEnd() + " Петяв ñáéíó\r\n\r\n\tStop.\r\n";
            sr.Close();

            //Se adapta el lenguaje al del PC donde se ejecutan los tests
            int deflangInd = rtf4.IndexOf("\\deflang3082");
            rtf4 = rtf4.Substring(0, deflangInd) + "\\deflang" + CultureInfo.CurrentCulture.LCID + rtf4.Substring(deflangInd + 8 + CultureInfo.CurrentCulture.LCID.ToString().Length);

            //Se adapta el lenguaje al del PC donde se ejecutan los tests
            int deflangInd2 = rtf6.IndexOf("\\deflang3082");
            rtf6 = rtf6.Substring(0, deflangInd2) + "\\deflang" + CultureInfo.CurrentCulture.LCID + rtf6.Substring(deflangInd2 + 8 + CultureInfo.CurrentCulture.LCID.ToString().Length);

            Assert.That(rtf1, Is.EqualTo(rtf6));
            Assert.That(rtf2, Is.EqualTo(rtf4));

            Assert.That(text1, Is.EqualTo(doctext1));
            Assert.That(text2, Is.EqualTo(doctext2));
        }