Exemplo n.º 1
0
//   [UnitTestFunction]
    public static void TestParagraph()
    {
      Document doc = new Document();
      doc.Styles["Heading3"].Font.Color = Color.CadetBlue;
      Section sec = doc.Sections.AddSection();
      Paragraph par = sec.AddParagraph();
      par.Style = "Heading4";
      par.AddText("A bit ");
      FormattedText ft = par.AddFormattedText("differently formatted");
      ft.Style = "InvalidStyleName";
      ft.Font.Size = 40;
      ft.Font.Name = "Courier New";
      //ft.Font.Color = Color.Azure;
      ft.Font.Bold = true;
      ft.Font.Italic = true;
      //ft.Font.Underline = Underline.Dotted;

      par.AddText(" text.");

      DocumentRenderer docRndrr = new DocumentRenderer();
      docRndrr.Render(doc, "RtfParagraph.txt", null);

      File.Copy("RtfParagraph.txt", "RtfParagraph.rtf", true);
      System.Diagnostics.Process.Start("RtfParagraph.rtf");
    }
Exemplo n.º 2
0
        void PrepareDocumentRenderer()
        {
            if (_document == null)
                throw new InvalidOperationException(Messages2.PropertyNotSetBefore("DocumentRenderer", MethodInfo.GetCurrentMethod().Name));

            _documentRenderer = new DocumentRenderer(_document);
            _documentRenderer.WorkingDirectory = this.workingDirectory;
            _documentRenderer.PrepareDocument();
        }
Exemplo n.º 3
0
        protected string Render(string parrot, object model, IHost host)
        {
            Parser.Parser parser = new Parser.Parser(host);
            Document document;

            parser.Parse(parrot, out document);

            DocumentRenderer renderer = new DocumentRenderer(new MemoryHost());

            StringBuilder sb = new StringBuilder();
            return renderer.Render(document, model);
        }
Exemplo n.º 4
0
        internal ConsoleString CreateTable()
        {
            if (commandLine.Length == 0)
            {
                commandLine = new string[] { "item" };
                elements = elements.Select(e => (object)new { item = e }).ToList();
            }

            DocumentRenderer renderer = new DocumentRenderer();
            var template = "{{ table elements " + string.Join(" ", commandLine) + " !}}";
            var result = renderer.Render(template, new { elements = elements });
            return result;
        }
Exemplo n.º 5
0
//    [UnitTestFunction]
    public static void TestDocumentProps()
    {
      Document doc = new Document();
      doc.Info.Author = "ich";
      doc.Info.Keywords = "toller typ, kann alles";
      doc.Info.Subject = "Womanizer";
      doc.Info.Title = "K. P.";

      doc.DefaultTabStop = "4cm";
      doc.FootnoteLocation = FootnoteLocation.BeneathText;
      doc.FootnoteNumberingRule = FootnoteNumberingRule.RestartSection;
      doc.FootnoteNumberStyle = FootnoteNumberStyle.UppercaseRoman;
      doc.FootnoteStartingNumber = 12;

      DocumentRenderer docRndrr = new DocumentRenderer();
      docRndrr.Render(doc, "RtfDocumentArea.txt", null);

      File.Copy("RtfDocumentArea.txt", "RtfDocumentArea.rtf", true);
      System.Diagnostics.Process.Start("RtfDocumentArea.txt");
    }
Exemplo n.º 6
0
    public static void Test()
    {
      Document doc = new Document();
      Section sec = doc.AddSection();

      Chart chart = sec.AddChart(ChartType.Line);
      chart.Width = "13cm";
      chart.Height = "8cm";
      chart.FillFormat.Color = Color.Linen;
      chart.LineFormat.Width = 2;

      chart.PlotArea.FillFormat.Color = Color.Blue;

//      chart.XAxis.Title.Caption = "X-Axis";
//      chart.YAxis.Title.Caption = "Y-Axis";

      DocumentRenderer docRenderer = new DocumentRenderer();
      docRenderer.Render(doc, "RtfChart.txt");
      DdlWriter.SerializeToFile(doc, "RtfChart.mdddl");
      System.IO.File.Copy("RtfChart.txt", "RtfChart.rtf", true);
      System.Diagnostics.Process.Start("RtfChart.txt");
    }
        private void Draw(IRenderer renderer, PageMarginBoxContextNode node, PdfDocument pdfDocument, PdfPage page
                          , DocumentRenderer documentRenderer, int pageNumber)
        {
            LayoutResult result = renderer.Layout(new LayoutContext(new LayoutArea(pageNumber, node.GetPageMarginBoxRectangle
                                                                                       ())));
            IRenderer rendererToDraw = result.GetStatus() == LayoutResult.FULL ? renderer : result.GetSplitRenderer();

            if (rendererToDraw != null)
            {
                TagTreePointer tagPointer    = null;
                TagTreePointer backupPointer = null;
                PdfPage        backupPage    = null;
                if (pdfDocument.IsTagged())
                {
                    tagPointer    = pdfDocument.GetTagStructureContext().GetAutoTaggingPointer();
                    backupPage    = tagPointer.GetCurrentPage();
                    backupPointer = new TagTreePointer(tagPointer);
                    tagPointer.MoveToRoot();
                    tagPointer.SetPageForTagging(page);
                }
                rendererToDraw.SetParent(documentRenderer).Draw(new DrawContext(page.GetDocument(), new PdfCanvas(page), pdfDocument
                                                                                .IsTagged()));
                if (pdfDocument.IsTagged())
                {
                    tagPointer.SetPageForTagging(backupPage);
                    tagPointer.MoveToPointer(backupPointer);
                }
            }
            else
            {
                // marginBoxElements have overflow property set to HIDDEN, therefore it is not expected to neither get
                // LayoutResult other than FULL nor get no split renderer (result NOTHING) even if result is not FULL
                LOGGER.Error(MessageFormatUtil.Format(iText.Html2pdf.LogMessageConstant.PAGE_MARGIN_BOX_CONTENT_CANNOT_BE_DRAWN
                                                      , node.GetMarginBoxName()));
            }
        }
Exemplo n.º 8
0
//    [UnitTestFunction]
    public static void Test()
    {
      Document doc = new Document();
      Styles styles = doc.Styles;
      Style style = styles.AddStyle("MyTestA", "Heading7"); 
      style.ParagraphFormat.Shading.Color = Color.Aqua;
      style.ParagraphFormat.SpaceAfter = 5;
      style.ParagraphFormat.SpaceBefore = 12;
      style.ParagraphFormat.WidowControl = false;
      style.ParagraphFormat.Borders.Width = 2;
      style.Font.Bold = true;
      style.Font.Italic = true;
      style.Font.Color = Color.DarkGray;
      style.Font.Name = "Courier New";
      Style styleB = styles.AddStyle("MyTestB", "MyTestA"); 
      styleB.ParagraphFormat.OutlineLevel = OutlineLevel.BodyText;
      styleB.ParagraphFormat.Borders.Left.Color = Color.Goldenrod;
      style.ParagraphFormat.TabStops.AddTabStop(100, TabAlignment.Right, TabLeader.MiddleDot);
      DocumentRenderer docRenderer = new DocumentRenderer();
      styleB.ParagraphFormat.TabStops.RemoveTabStop(100);
      docRenderer.Render(doc, "RtfHeader.txt", null);
      System.IO.File.Copy("RtfHeader.txt", "RtfHeader.rtf", true);
      System.Diagnostics.Process.Start("RtfHeader.txt");
    }
Exemplo n.º 9
0
        //   [UnitTestFunction]
        public static void TestTable()
        {
            Document doc   = new Document();
            Section  sec   = doc.Sections.AddSection();
            Table    table = sec.AddTable();

            table.Borders.Visible = true;
            for (int clmIdx = 0; clmIdx <= 8; ++clmIdx)
            {
                Column clm = table.Columns.AddColumn();
                clm.Format.Font.Color = clmIdx > 2 ? Color.Red : Color.Green;
            }
            for (int rowIdx = 0; rowIdx <= 1000; ++rowIdx)
            {
                Row row = table.AddRow();
                row.Format.Font.Size = (float)(rowIdx / 10 + 10);
            }
            for (int clmIdx = 0; clmIdx <= 8; ++clmIdx)
            {
                for (int rowIdx = 0; rowIdx <= 1000; ++rowIdx)
                {
                    table[rowIdx, clmIdx].AddParagraph(rowIdx + "," + clmIdx);
                }
            }

//      cell.AddParagraph("Tabelle");
//      cell.Shading.Color = Color.Blue;
//      cell.Borders.Right.Visible = false;
//      sec.AddParagraph("Paragraph After.");
            DocumentRenderer docRndrr = new DocumentRenderer();

            docRndrr.Render(doc, "RtfTable.txt", null);

            File.Copy("RtfTable.txt", "RtfTable.rtf", true);
            System.Diagnostics.Process.Start("RtfTable.rtf");
        }
Exemplo n.º 10
0
//    [UnitTestFunction]
    public static void TestInvalidStyle()
    {
      Document doc = new Document();
      Section sec = doc.Sections.AddSection();
      Paragraph par = sec.AddParagraph();
      par.AddFormattedText("text", "_invalid_");

      DocumentRenderer docRndrr = new DocumentRenderer();
      docRndrr.Render(doc, "RtfInvalidStyle.txt", null);
      File.Copy("RtfInvalidStyle.txt", "RtfInvalidStyle.rtf", true);
      System.Diagnostics.Process.Start("RtfInvalidStyle.txt", null);
      DdlWriter.WriteToFile(doc, "RtfInvalidStyle.mdddl");
    }
Exemplo n.º 11
0
 //   [UnitTestFunction]
    public static void TestCharacterStyleAsParagraphStyle()
    {
      Document doc = new Document();
      doc.Styles.AddStyle("charstyle", Style.DefaultParagraphFontName).Font.Italic = true;
      Section sec = doc.Sections.AddSection();

      sec.AddParagraph("CharStyle").Style = "charstyle";

      DocumentRenderer docRndrr = new DocumentRenderer();
      docRndrr.Render(doc, "RtfCharacterStyleAsParagraphStyle.txt", null);
      File.Copy("RtfCharacterStyleAsParagraphStyle.txt", "RtfCharacterStyleAsParagraphStyle.rtf", true);
      System.Diagnostics.Process.Start("RtfCharacterStyleAsParagraphStyle.txt");
      DdlWriter.WriteToFile(doc, "RtfCharacterStyleAsParagraphStyle.mdddl");
    }
Exemplo n.º 12
0
        public byte[] Generate(OrderReportParameters parameters, string reportContentPath)
        {
            reportData = parameters;
            renderer   = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);
            document   = new Document();
            document.DefaultPageSetup.TopMargin    = "9.75cm";
            document.DefaultPageSetup.BottomMargin = "3.15cm";
            document.DefaultPageSetup.LeftMargin   = "3cm";
            document.DefaultPageSetup.RightMargin  = "1cm";
            document.DefaultPageSetup.PageFormat   = PageFormat.A4;

            docRenderer = new DocumentRenderer(document);
            labels      = new SubmitOrderPdfReportContent(reportContentPath);

            document.Info.Title = "Bestellen-" + DateTime.Now.ToString("dd.MM.yyyy");

            var style = document.Styles["Normal"];

            style.Font.Name = "Calibri";
            style.Font.Size = 9;

            section = document.AddSection();

            SetupHeader();
            SetupFooter();

            var drugsGrouped             = reportData.Orders.OrderedDrugs.GroupBy(t => t.Name).ToDictionary(t => t.Key, t => t.ToList());
            var summaryTableColumnConfig = new List <TableColumnConfig>()
            {
                new TableColumnConfig()
                {
                    ColumnName = labels.Medication, ColumnWidth = "15cm"
                },
                new TableColumnConfig()
                {
                    ColumnName = labels.Amount, ColumnWidth = "2cm", Alignment = ParagraphAlignment.Right
                }
            };

            SetupContent(labels.OrderOverview, summaryTableColumnConfig, drugsGrouped.Select(t => new List <TableContent>()
            {
                new TableContent()
                {
                    Alignment = ParagraphAlignment.Left, Value = t.Key
                },
                new TableContent()
                {
                    Alignment = ParagraphAlignment.Right, Value = t.Value.Count.ToString()
                },
            }).ToList());
            document.LastSection.AddPageBreak();
            summaryTableColumnConfig = new List <TableColumnConfig>()
            {
                new TableColumnConfig()
                {
                    ColumnName = labels.Patient, ColumnWidth = "4cm"
                },
                new TableColumnConfig()
                {
                    ColumnName = labels.BirthDate, ColumnWidth = "3cm"
                },
                new TableColumnConfig()
                {
                    ColumnName = labels.HealthInsurance, ColumnWidth = "4cm"
                },
                new TableColumnConfig()
                {
                    ColumnName = labels.InsuranceStatus, ColumnWidth = "3cm"
                },
                new TableColumnConfig()
                {
                    ColumnName = labels.FeeWaived, ColumnWidth = "3cm"
                },
            };

            var i = 0;

            foreach (var drug in drugsGrouped)
            {
                SetupContent(drug.Key, summaryTableColumnConfig, drug.Value.Select(t => new List <TableContent>()
                {
                    new TableContent()
                    {
                        Alignment = ParagraphAlignment.Left, Value = String.Format("{0} {1}", t.Patient.FirstName, t.Patient.LastName)
                    },
                    new TableContent()
                    {
                        Alignment = ParagraphAlignment.Left, Value = t.Patient.BirthDate.ToString("dd.MM.yyyy")
                    },
                    new TableContent()
                    {
                        Alignment = ParagraphAlignment.Left, Value = t.Patient.Hip
                    },
                    new TableContent()
                    {
                        Alignment = ParagraphAlignment.Left, Value = t.Patient.InsuranceStatus
                    },
                    new TableContent()
                    {
                        Alignment = ParagraphAlignment.Center, Value = t.Patient.FeeWaived
                    },
                    new TableContent()
                    {
                        Alignment = ParagraphAlignment.Left, Value = t.PositionComment, NewRow = true
                    }
                }).ToList(), true);

                if (i++ < drugsGrouped.Count - 1)
                {
                    document.LastSection.AddPageBreak();
                }
            }

            var stream = new MemoryStream();

            renderer.Document = document;
            renderer.RenderDocument();
            renderer.Save(stream, false);

            return(stream.ToArray());
        }
Exemplo n.º 13
0
        private void Page1(PdfDocument document, int pageNum)
        {
            PdfPage   page = document.AddPage();
            XGraphics gfx  = XGraphics.FromPdfPage(page);

            // Unicode hack
            gfx.MUH = PdfFontEncoding.Unicode;

            // Get the A4 page size
            Unit width, height;

            PageSetup.GetPageSize(PageFormat.A4, out width, out height);

            XFont font = new XFont("Verdana", 13, XFontStyle.Bold);

            // You always need a MigraDoc document for rendering.
            Document doc = new Document();

            // Add a section to the document and configure it such
            // that it will be in the center of the page
            Section section = doc.AddSection();

            section.PageSetup.PageHeight  = height;
            section.PageSetup.PageWidth   = width;
            section.PageSetup.LeftMargin  = 0;
            section.PageSetup.RightMargin = 0;
            section.PageSetup.TopMargin   = 20;

            // Add a top paragraph with date
            Paragraph para = section.AddParagraph();

            para.Format.Alignment  = ParagraphAlignment.Right;
            para.Format.Font.Name  = "Times New Roman";
            para.Format.Font.Size  = 12;
            para.Format.Font.Color = MigraDoc.DocumentObjectModel.Colors.DarkGray;
            para.AddFormattedText(dateTimePicker1.Value.Date.ToString("dddd, d MMMM yyyy"), TextFormat.Bold);

            // Add a bottom paragraph with page number
            Paragraph pg = section.AddParagraph();

            pg.Format.Alignment  = ParagraphAlignment.Right;
            pg.Format.Font.Name  = "Times New Roman";
            pg.Format.Font.Size  = 12;
            pg.Format.Font.Color = MigraDoc.DocumentObjectModel.Colors.DarkGray;
            pg.AddFormattedText("Page " + pageNum, TextFormat.Bold);

            // Create a table
            Table table = new Table();

            table.Borders.Visible = true;
            table.Borders.Width   = 1; // Default to show borders 1 pixel wide Column
            table.TopPadding      = 5;
            table.BottomPadding   = 5;

            Column column = table.AddColumn(40);

            column.Format.Alignment = ParagraphAlignment.Left;

            column = table.AddColumn(150);
            column.Format.Alignment = ParagraphAlignment.Left;

            column = table.AddColumn(120);
            column.Format.Alignment = ParagraphAlignment.Center;

            column = table.AddColumn(120);
            column.Format.Alignment = ParagraphAlignment.Center;

            column = table.AddColumn(80);
            column.Format.Alignment = ParagraphAlignment.Center;

            table.Rows.Height = 20;

            Row row = table.AddRow();

            row.Shading.Color     = Colors.PaleGoldenrod;
            row.VerticalAlignment = VerticalAlignment.Top;

            // Table header
            row.Cells[0].AddParagraph("#");
            row.Cells[1].AddParagraph("Name");
            row.Cells[2].AddParagraph("Start");
            row.Cells[3].AddParagraph("End");
            row.Cells[4].AddParagraph("Duration");

            // Define the last row number on the current page
            int lastNum;

            if (rowNum >= pageNum * rowsPerPage)
            {
                lastNum = pageNum * rowsPerPage;
            }
            else
            {
                lastNum = rowNum;
            }

            // Put the rows into the table
            for (int i = 1 + (pageNum - 1) * rowsPerPage; i <= lastNum; i++)
            {
                DataRow dr = dt.Rows[i - 1];
                row = table.AddRow();
                row.Cells[0].AddParagraph(i.ToString());
                row.Cells[1].AddParagraph(dr["name"].ToString());
                row.Cells[2].AddParagraph(dr["start"].ToString());
                row.Cells[3].AddParagraph(dr["end"].ToString());
                row.Cells[4].AddParagraph(dr["duration"].ToString());
            }

            table.SetEdge(0, 0, 5, 1, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 1.5, Colors.Black);

            doc.LastSection.Add(table);

            // Create a renderer and prepare (=layout) the document
            MigraDoc.Rendering.DocumentRenderer docRenderer = new DocumentRenderer(doc);
            docRenderer.PrepareDocument();

            // Render the paragraph. You can render tables or shapes the same way.
            docRenderer.RenderObject(gfx, XUnit.FromCentimeter(10), XUnit.FromCentimeter(1), "10cm", para);
            docRenderer.RenderObject(gfx, XUnit.FromCentimeter(2), XUnit.FromCentimeter(2), "12cm", table);
            docRenderer.RenderObject(gfx, XUnit.FromCentimeter(10), XUnit.FromCentimeter(28), "10cm", pg);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="T:MigraDoc.Rendering.Printing.MigraDocPrintDocument"/> class
 /// with the specified <see cref="T:MigraDoc.Rendering.DocumentRenderer"/> object.
 /// </summary>
 public MigraDocPrintDocument(DocumentRenderer renderer)
 {
     _renderer = renderer;
     DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
     OriginAtMargins             = false;
 }
Exemplo n.º 15
0
//    [UnitTestFunction]
    public static void TestHyperlink()
    {
      Document doc = new Document();
      doc.Info.Author = "K.P.";
      Section sec = doc.Sections.AddSection();
      Paragraph par = sec.AddParagraph();

      par.AddBookmark("myBookmark1");
      Hyperlink hp = par.AddHyperlink("myBookmark1");
      hp.AddText ("Hyperlink lokal");

      hp = par.AddHyperlink("http://www.empira.de", HyperlinkType.Web);
      hp.AddText("Hyperlink Web");

      hp = par.AddHyperlink("RtfHyperlinks.txt", HyperlinkType.File);
      hp.AddText("Hyperlink Datei Relativ");
      
      hp = par.AddHyperlink(@"\\Klpo01\D$\Kram\Tabs.pdf", HyperlinkType.File);
      hp.AddText("Hyperlink Datei Netzwerk");

      DocumentRenderer docRndrr = new DocumentRenderer();
      docRndrr.Render(doc, "RtfHyperlinks.txt", null);

      File.Copy("RtfHyperlinks.txt", "RtfHyperlinks.rtf", true);
      System.Diagnostics.Process.Start("RtfHyperlinks.txt");
    }
Exemplo n.º 16
0
        public override SubmissionStatus ServiceSubmit(string jobName, string fclInfo, Dictionary <string, string> driverSettings, Logger externalHandler, Stream xpsStream, int pageIndexStart, int pageIndexEnd, List <PageDimensions> pageDimensions)
        {
            AttachDebugger();

            var status = new SubmissionStatus();

            status.Result = false;

            try
            {
                string username    = GetPropertyResult("username", "", false);
                string password    = GetPropertyResult("password", "", false);
                string destination = GetPropertyResult("destination", "", false);
                if (string.IsNullOrWhiteSpace(username))
                {
                    throw new Exception("Missing property: username");
                }
                if (string.IsNullOrWhiteSpace(password))
                {
                    throw new Exception("Missing property: password");
                }
                if (string.IsNullOrWhiteSpace(destination))
                {
                    throw new Exception("Missing property: destination");
                }

                var outputImageType = GetProperty <OutputImageTypeProperty>("outputImageType", false);
                if (outputImageType == null)
                {
                    throw new Exception("Missing property: outputImageType");
                }

                DocumentRenderer renderingConverter = GetRenderer(outputImageType);
                if (renderingConverter != null)
                {
                    TempFileStream outputStream = null;
                    try
                    {
                        try
                        {
                            string tempFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Temp\");
                            Directory.CreateDirectory(tempFolder);
                            outputStream = new TempFileStream(tempFolder);
                        }
                        catch (Exception)
                        {
                            // Ignore - attempt another temp location (UAC may block UI from accessing Temp folder.
                        }

                        if (outputStream == null)
                        {
                            string tempFolder = Path.Combine(Path.GetTempPath(), @"FS_UPD_v4\NewUpdPlugin\");
                            Directory.CreateDirectory(tempFolder);
                            outputStream = new TempFileStream(tempFolder);
                        }

                        renderingConverter.RenderXpsToOutput(xpsStream, outputStream, pageIndexStart, pageIndexEnd, externalHandler);
                        outputStream.Seek(0, SeekOrigin.Begin);

                        string jobId;
                        if (SubmitDocumentWithCustomLogic(outputStream, username, password, destination, out jobId))
                        {
                            status.Result     = true;
                            status.Message    = "Successfully Submitted";
                            status.StatusCode = 0;
                            status.LogDetails = "Submitted Document with ID: " + jobId + "\r\n";
                        }
                    }
                    finally
                    {
                        if (outputStream != null)
                        {
                            outputStream.Dispose();
                            outputStream = null;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                status.Result     = false;
                status.Message    = "An error has occurred.";
                status.LogDetails = ex.Message;
                status.NotifyUser = true;
                status.StatusCode = 12;
            }

            return(status);
        }
Exemplo n.º 17
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:MigraDoc.Rendering.Printing.MigraDocPrintDocument"/> class
 /// with the specified <see cref="T:MigraDoc.Rendering.DocumentRenderer"/> object.
 /// </summary>
 public MigraDocPrintDocument(DocumentRenderer renderer)
 {
   this.renderer = renderer;
   DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
   OriginAtMargins = false;
 }
        public static (PdfDocument document, (string crisisType, int startIndex)[]) CreateDocument(IEnumerable <CardData> cards, DateTime fileChanged, int currentInstance)
        {
            var pageWdith  = XUnit.FromInch(2.5);
            var pageHeight = XUnit.FromInch(3.5);


            PdfDocument document = new PdfDocument();

            document.Info.Title    = "Forschungs Karten";
            document.Info.Subject  = "Die Forschungskarten des spiels";
            document.Info.Author   = "Arbeitstitel Karthago";
            document.Info.Keywords = "Karten, Forschung, Karthago";


            //var maxOccurenceOfCard = cards.Max(x => x.Metadata.Times);
            int    counter         = 0;
            var    total           = cards.Sum(x => x.Metadata.Times);
            string currentCardType = null;
            var    resultList      = new List <(string crisisType, int startIndex)>();

            foreach (var card in cards)
            {
                if (card.Metadata.Type != null && currentCardType != null)
                {
                    // Create new Back
                    CrateBack(pageWdith, pageHeight, document, currentCardType);
                }

                if (card.Metadata.Type != null)
                {
                    resultList.Add((card.Metadata.Type, document.PageCount));
                }

                currentCardType = card.Metadata.Type ?? currentCardType;
                if (currentCardType is null)
                {
                    Console.WriteLine($"{currentInstance}: Did not found card metadata. SKIP");
                    continue;
                }
                var header = card.Content.FirstOrDefault(x => x is HeaderBlock);
                Console.WriteLine($"{currentInstance}: Working on <{header?.ToString() ?? "UNKNOWN TITLE"}> with {card.Metadata.Times} instances.");
                for (int i = 0; i < card.Metadata.Times; i++)
                {
                    Console.Write($"{i + 1}...");
                    counter++;

                    PdfPage page = document.AddPage();

                    page.Width  = new XUnit(pageWdith.Millimeter, XGraphicsUnit.Millimeter);
                    page.Height = new XUnit(pageHeight.Millimeter, XGraphicsUnit.Millimeter);


                    XGraphics gfx = XGraphics.FromPdfPage(page);
                    // HACK²
                    gfx.MUH = PdfFontEncoding.Unicode;
                    //gfx.MFEH = PdfFontEmbedding.Default;

                    XFont font = new XFont("Verdana", 13, XFontStyle.Regular);



                    var costSize = new XSize(new XUnit(23, XGraphicsUnit.Millimeter), font.Height);

                    var costMarginRight = new XUnit(5, XGraphicsUnit.Millimeter);



                    var actionRect     = new XRect(costMarginRight, new XUnit(5, XGraphicsUnit.Millimeter), pageHeight * 2, costSize.Height * 2);
                    var actionTextRect = actionRect;
                    actionTextRect.Height = costSize.Height;
                    actionTextRect.Offset(new XUnit(3, XGraphicsUnit.Millimeter), 0);

                    gfx.TranslateTransform(new XUnit(3, XGraphicsUnit.Millimeter), 0);
                    gfx.RotateAtTransform(90, actionRect.TopLeft);



                    gfx.DrawRoundedRectangle(XPens.MidnightBlue, XBrushes.DarkSlateBlue, actionRect, new XSize(10, 10));
                    gfx.DrawString(currentCardType, font, XBrushes.White,
                                   actionTextRect, XStringFormats.CenterLeft);

                    gfx.RotateAtTransform(-90, actionRect.TopLeft);
                    gfx.TranslateTransform(new XUnit(-3, XGraphicsUnit.Millimeter), 0);

                    var circle = new XRect(new XUnit(-3, XGraphicsUnit.Millimeter), pageHeight - new XUnit(10, XGraphicsUnit.Millimeter), new XUnit(13, XGraphicsUnit.Millimeter), new XUnit(13, XGraphicsUnit.Millimeter));

                    gfx.DrawEllipse(XPens.MidnightBlue, XBrushes.White, circle);

                    gfx.DrawString($"{card.Metadata.Duration:n0}", font, XBrushes.Black,
                                   circle, XStringFormats.Center);


                    var dateRec  = new XRect(new XUnit(13, XGraphicsUnit.Millimeter), pageHeight - new XUnit(2.5, XGraphicsUnit.Millimeter), new XUnit(13, XGraphicsUnit.Millimeter), new XUnit(3, XGraphicsUnit.Millimeter));
                    var dateFont = new XFont("Verdana", 7, XFontStyle.Regular);
                    gfx.DrawString(fileChanged.ToString(), dateFont, XBrushes.Gray, dateRec.TopLeft);
                    gfx.DrawString($"{counter}/{total}", dateFont, XBrushes.Gray, new XRect(0, 0, pageWdith - new XUnit(3, XGraphicsUnit.Millimeter), pageHeight - new XUnit(2.5, XGraphicsUnit.Millimeter)), XStringFormats.BottomRight);

                    // Create a new MigraDoc document
                    var doc = new Document();
                    doc.Info.Title   = "Krisen Karten";
                    doc.Info.Subject = "Die Krisenkarten des spiels";
                    doc.Info.Author  = "Arbeitstitel Karthago";


                    doc.DefaultPageSetup.PageWidth  = new Unit(pageWdith.Inch, UnitType.Inch);
                    doc.DefaultPageSetup.PageHeight = new Unit(pageHeight.Inch, UnitType.Inch);

                    doc.DefaultPageSetup.LeftMargin   = new Unit(13, UnitType.Millimeter);
                    doc.DefaultPageSetup.RightMargin  = new Unit(5, UnitType.Millimeter);
                    doc.DefaultPageSetup.BottomMargin = new Unit(10, UnitType.Millimeter);
                    doc.DefaultPageSetup.TopMargin    = new Unit(6, UnitType.Millimeter);

                    doc.DefineStyles();

                    //Cover.DefineCover(document);
                    //DefineTableOfContents(document);

                    DefineContentSection(doc);
                    card.Content.HandleBlocks(doc);


                    // Create a renderer and prepare (=layout) the document
                    MigraDoc.Rendering.DocumentRenderer docRenderer = new DocumentRenderer(doc);
                    docRenderer.PrepareDocument();

                    //XRect rect = new XRect(new XPoint(Unit.FromCentimeter(1).Value, Unit.FromCentimeter(3).Value), new XSize((pageWdith.Value - Unit.FromCentimeter(2).Value), (pageHeight.Value - Unit.FromCentimeter(4).Value)));

                    // Use BeginContainer / EndContainer for simplicity only. You can naturaly use you own transformations.
                    //XGraphicsContainer container = gfx.BeginContainer(rect, A4Rect, XGraphicsUnit.Point);

                    // Draw page border for better visual representation
                    //gfx.DrawRectangle(XPens.LightGray, A4Rect);

                    // Render the page. Note that page numbers start with 1.
                    docRenderer.RenderPage(gfx, 1);

                    // Note: The outline and the hyperlinks (table of content) does not work in the produced PDF document.

                    // Pop the previous graphical state
                    //gfx.EndContainer(container);
                }
                Console.WriteLine(" Finished card.");
            }
            CrateBack(pageWdith, pageHeight, document, currentCardType);


            //DefineParagraphs(document);
            //DefineTables(document);
            //DefineCharts(document);

            return(document, resultList.ToArray());
        }
Exemplo n.º 19
0
        /// <summary>
        /// Writes the table and optionally passes the objects through
        /// </summary>
        protected override void BeforeSetDrainedToTrue()
        {
            bool wrapped = false;
            if (commandLine.Length == 0)
            {
                wrapped = true;
                commandLine = new string[] { "item" };
                elements = elements.Select(e => (object)new { item = e }).ToList();
            }

            DocumentRenderer renderer = new DocumentRenderer();
            var template = "{{ table elements " + string.Join(" ", commandLine) + " !}}";
            var result = renderer.Render(template, new { elements = elements });
            result.WriteLine();
            if (TableWritten != null)
            {
                TableWritten(template, elements, result);
            }

            if (passThrough == false) return;

            if(wrapped)
            {
                foreach(var item in elements)
                {
                    ArgPipeline.Push(item.GetType().GetProperty("item").GetValue(item, null), this);
                }
            }
            else
            {
                foreach (var item in elements)
                {
                    ArgPipeline.Push(item, this);
                }
            }
        }
        public static void PDFFormat(string acronimo, string servicio, DateTime lstService, string emp,
                                     int idFact, DateTime emision, string precio, int unidades, int dctofact, string importe,
                                     string formapago, Corp corp)
        {
            PdfDocument document = new PdfDocument();

            document.Info.Title = $"Factura{emision.ToString("yyyyMMdd")}";

            PdfPage   page = document.AddPage();
            XGraphics gfx  = XGraphics.FromPdfPage(page);

            // HACK²
            gfx.MUH = PdfFontEncoding.Unicode;
            //gfx.MFEH = PdfFontEmbedding.Default;

            XFont font = new XFont("Verdana", 13, XFontStyle.Bold);

            gfx.DrawString($"Factura {idFact}:", font, XBrushes.Black,
                           new XRect(100, 100, page.Width - 200, 300), XStringFormats.Center);

            // You always need a MigraDoc document for rendering.
            Document doc = new Document();
            Section  sec = doc.AddSection();
            // Add a single paragraph with some text and format information.
            Paragraph para = sec.AddParagraph();

            para.Format.Alignment  = ParagraphAlignment.Left;
            para.Format.Font.Name  = "Times New Roman";
            para.Format.Font.Size  = 12;
            para.Format.Font.Color = MigraDoc.DocumentObjectModel.Colors.Black;
            //para.Format.Font.Color = MigraDoc.DocumentObjectModel.Colors.DarkGray;
            para.AddText("Id factura: ");
            para.AddFormattedText($"{idFact} \n", TextFormat.Bold);
            para.AddText("Precio del servicio: ");
            para.AddFormattedText($"{precio} €\n", TextFormat.Bold);
            para.AddText("Unidades: ");
            para.AddFormattedText($"{unidades} \n", TextFormat.Bold);
            para.AddText("Descuento: ");
            para.AddFormattedText($"{dctofact} %\n", TextFormat.Bold);
            para.AddText("Importe servicio: ");
            para.AddFormattedText($"{importe} €\n", TextFormat.Bold);
            para.AddText("Forma de pago: ");
            para.AddFormattedText($"{formapago} \n", TextFormat.Bold);
            para.AddText("Fecha del último servicio: ");
            para.AddFormattedText($"{lstService.ToShortDateString()} \n", TextFormat.Bold);
            para.AddText("Acrónimo del servicio: ");
            para.AddFormattedText($"{acronimo} \n", TextFormat.Bold);
            para.AddText("Nombre del servicio: ");
            para.AddFormattedText($"{servicio} \n", TextFormat.Bold);
            para.AddText("Nombre del empleado: ");
            para.AddFormattedText($"{emp} \n", TextFormat.Bold);

            para.AddText("Nombre corporativo: ");
            para.AddFormattedText($"{corp.Nombre} \n", TextFormat.Bold);
            para.AddText("CIF: ");
            para.AddFormattedText($"{corp.CIF} \n", TextFormat.Bold);
            para.AddText("Dirección: ");
            para.AddFormattedText($"{corp.Dir} \n", TextFormat.Bold);
            para.AddText("Código Postal: ");
            para.AddFormattedText($"{corp.CP} \n", TextFormat.Bold);
            para.AddText("Ciudad: ");
            para.AddFormattedText($"{corp.Ciudad} \n", TextFormat.Bold);
            para.AddText("Teléfono: ");
            para.AddFormattedText($"{corp.Tlf} \n", TextFormat.Bold);
            para.AddText("Email: ");
            para.AddFormattedText($"{corp.Correo} \n", TextFormat.Bold);
            para.AddText("Gracias por su visita.");

            //para.AddText(txt);
            para.Format.Borders.Distance = "5pt";
            para.Format.Borders.Color    = Colors.Gold;

            // Create a renderer and prepare (=layout) the document
            MigraDoc.Rendering.DocumentRenderer docRenderer = new DocumentRenderer(doc);
            docRenderer.PrepareDocument();

            // Render the paragraph. You can render tables or shapes the same way.
            docRenderer.RenderObject(gfx, XUnit.FromCentimeter(5), XUnit.FromCentimeter(10), "12cm", para);

            string filename = $"Factura{idFact}{emision.ToString("yyyyMMdd")}.pdf";
            string path     = "wwwroot/Pdf/" + filename;

            document.Save(path);
            // ...and start a viewer
            Process.Start(filename);
        }
        public static PdfDocument CreateDocument(IEnumerable <CardData> cards, DateTime fileChanged)
        {
            var pageWdith  = XUnit.FromInch(2.5);
            var pageHeight = XUnit.FromInch(3.5);


            PdfDocument document = new PdfDocument();

            document.Info.Title    = "Forschungs Karten";
            document.Info.Subject  = "Die Forschungskarten des spiels";
            document.Info.Author   = "Arbeitstitel Karthago";
            document.Info.Keywords = "Karten, Forschung, Karthago";


            //var maxOccurenceOfCard = cards.Max(x => x.Metadata.Times);
            int counter = 0;
            var total   = cards.Count();

            foreach (var card in cards)
            {
                counter++;

                PdfPage page = document.AddPage();

                page.Width  = new XUnit(pageWdith.Millimeter, XGraphicsUnit.Millimeter);
                page.Height = new XUnit(pageHeight.Millimeter, XGraphicsUnit.Millimeter);


                XGraphics gfx = XGraphics.FromPdfPage(page);
                // HACK²
                gfx.MUH = PdfFontEncoding.Unicode;
                //gfx.MFEH = PdfFontEmbedding.Default;

                XFont font = new XFont("Verdana", 13, XFontStyle.Regular);



                var costSize = new XSize(new XUnit(23, XGraphicsUnit.Millimeter), font.Height);

                var costMarginRight = new XUnit(5, XGraphicsUnit.Millimeter);



                var costRect     = new XRect(pageWdith - costSize.Width - costMarginRight, new XUnit(5, XGraphicsUnit.Millimeter), costSize.Width, costSize.Height);
                var actionRect   = new XRect(costMarginRight, new XUnit(5, XGraphicsUnit.Millimeter), pageWdith - costMarginRight - costMarginRight, costSize.Height);
                var durationRect = costRect;
                durationRect.Height *= 2.1;

                gfx.DrawRoundedRectangle(XPens.RoyalBlue, XBrushes.LightBlue, actionRect, new XSize(10, 10));
                gfx.DrawRoundedRectangle(XPens.Orange, XBrushes.LightYellow, durationRect, new XSize(10, 10));
                gfx.DrawRoundedRectangle(XPens.Purple, XBrushes.MediumPurple, costRect, new XSize(10, 10));


                var costTextRect = costRect;
                costTextRect.Width -= new XUnit(1, XGraphicsUnit.Millimeter);
                gfx.DrawString($"{card.Metadata.Cost:n0} ¤", font, XBrushes.Black,
                               costTextRect, XStringFormats.CenterRight);

                var subfont = Markdown.GetSubstituteFont("⌛");
                subfont = new XFont(subfont.Name, font.Size);

                var durationTextRect = durationRect;
                durationTextRect.Width -= new XUnit(1, XGraphicsUnit.Millimeter);

                gfx.DrawString($"{card.Metadata.Duration:n0} ⌛", subfont, XBrushes.Black,
                               durationTextRect, XStringFormats.BottomRight);


                var actionTextRect = actionRect;
                actionTextRect.Offset(new XUnit(3, XGraphicsUnit.Millimeter), 0);

                gfx.DrawString($"Forschung", font, XBrushes.Black,
                               actionTextRect, XStringFormats.CenterLeft);



                var dateRec  = new XRect(new XUnit(3, XGraphicsUnit.Millimeter), pageHeight - new XUnit(2.5, XGraphicsUnit.Millimeter), new XUnit(3, XGraphicsUnit.Millimeter), new XUnit(3, XGraphicsUnit.Millimeter));
                var dateFont = new XFont("Verdana", 7, XFontStyle.Regular);
                gfx.DrawString(fileChanged.ToString(), dateFont, XBrushes.Gray, dateRec.TopLeft);
                gfx.DrawString($"{counter}/{total}", dateFont, XBrushes.Gray, new XRect(0, 0, pageWdith - new XUnit(3, XGraphicsUnit.Millimeter), pageHeight - new XUnit(2.5, XGraphicsUnit.Millimeter)), XStringFormats.BottomRight);

                // Create a new MigraDoc document
                var doc = new Document();
                doc.Info.Title   = "Forschungs Karten";
                doc.Info.Subject = "Die Forschungskarten des spiels";
                doc.Info.Author  = "Arbeitstitel Karthago";


                doc.DefaultPageSetup.PageWidth  = new Unit(pageWdith.Inch, UnitType.Inch);
                doc.DefaultPageSetup.PageHeight = new Unit(pageHeight.Inch, UnitType.Inch);

                doc.DefaultPageSetup.LeftMargin   = new Unit(5, UnitType.Millimeter);
                doc.DefaultPageSetup.RightMargin  = new Unit(5, UnitType.Millimeter);
                doc.DefaultPageSetup.BottomMargin = new Unit(10, UnitType.Millimeter);
                doc.DefaultPageSetup.TopMargin    = new Unit(16, UnitType.Millimeter);

                doc.DefineStyles();

                //Cover.DefineCover(document);
                //DefineTableOfContents(document);

                DefineContentSection(doc);
                card.Content.HandleBlocks(doc);


                // Create a renderer and prepare (=layout) the document
                MigraDoc.Rendering.DocumentRenderer docRenderer = new DocumentRenderer(doc);
                docRenderer.PrepareDocument();

                //XRect rect = new XRect(new XPoint(Unit.FromCentimeter(1).Value, Unit.FromCentimeter(3).Value), new XSize((pageWdith.Value - Unit.FromCentimeter(2).Value), (pageHeight.Value - Unit.FromCentimeter(4).Value)));

                // Use BeginContainer / EndContainer for simplicity only. You can naturaly use you own transformations.
                //XGraphicsContainer container = gfx.BeginContainer(rect, A4Rect, XGraphicsUnit.Point);

                // Draw page border for better visual representation
                //gfx.DrawRectangle(XPens.LightGray, A4Rect);

                // Render the page. Note that page numbers start with 1.
                docRenderer.RenderPage(gfx, 1);

                // Note: The outline and the hyperlinks (table of content) does not work in the produced PDF document.

                // Pop the previous graphical state
                //gfx.EndContainer(container);
            }

            // Back
            {
                PdfPage page = document.AddPage();

                page.Width  = new XUnit(pageWdith.Millimeter, XGraphicsUnit.Millimeter);
                page.Height = new XUnit(pageHeight.Millimeter, XGraphicsUnit.Millimeter);


                XGraphics gfx = XGraphics.FromPdfPage(page);
                // HACK²
                gfx.MUH = PdfFontEncoding.Unicode;
                //gfx.MFEH = PdfFontEmbedding.Default;

                XFont font = new XFont("Verdana", 30, XFontStyle.Regular);



                var costRect = new XRect(0, 0, page.Width, page.Height);


                gfx.DrawString($"Forschung", font, XBrushes.SkyBlue,
                               costRect, XStringFormats.Center);
            }

            //DefineParagraphs(document);
            //DefineTables(document);
            //DefineCharts(document);

            return(document);
        }
Exemplo n.º 22
0
        public PdfDocument CreateFirstPage(Candidate model, PdfDocument pdfDocument)
        {
            PdfPage pdfPage = new PdfPage();
            XSize   size    = PageSizeConverter.ToSize(PageSize.A4);

            pdfPage.Orientation = PageOrientation.Portrait;

            pdfPage.Width              = size.Width;
            pdfPage.Height             = size.Height;
            pdfPage.TrimMargins.Top    = 10;
            pdfPage.TrimMargins.Right  = 10;
            pdfPage.TrimMargins.Bottom = 10;
            pdfPage.TrimMargins.Left   = 10;

            pdfDocument.Pages.Add(pdfPage);


            XGraphics gfx = XGraphics.FromPdfPage(pdfPage);

            gfx.MUH  = PdfFontEncoding.Unicode;
            gfx.MFEH = PdfFontEmbedding.Default;


            var document = new Document();
            var section  = document.AddSection();

            section.PageSetup.PageFormat   = PageFormat.A4;
            section.PageSetup.TopMargin    = "5cm";
            section.PageSetup.BottomMargin = "5cm";
            section.PageSetup.RightMargin  = "5cm";
            section.PageSetup.LeftMargin   = "5cm";

            var paragraph = section.AddParagraph();

            paragraph.Format.Alignment    = ParagraphAlignment.Left;
            paragraph.Format.KeepTogether = true;
            paragraph.AddText(model.CandidateProfile.Profile);


            Image image = section.AddImage(@"D:\source\play\pdfgen\pdfgen\portrait-profile-007.jpg");

            image.Height             = "1.5cm";
            image.Width              = "4cm";
            image.LockAspectRatio    = true;
            image.RelativeVertical   = RelativeVertical.Line;
            image.RelativeHorizontal = RelativeHorizontal.Margin;
            image.Top              = ShapePosition.Top;
            image.Left             = ShapePosition.Right;
            image.WrapFormat.Style = WrapStyle.Through;



            PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(true, PdfFontEmbedding.Always);

            pdfRenderer.Document = document;
            pdfRenderer.RenderDocument();


            MigraDoc.Rendering.DocumentRenderer docRenderer = new DocumentRenderer(document);
            docRenderer.PrepareDocument();
            docRenderer.RenderObject(gfx, XUnit.FromCentimeter(0), XUnit.FromCentimeter(0), "18cm", paragraph);

            return(pdfDocument);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Renders a single paragraph.
        /// </summary>
        static void SamplePage1(PdfDocument document)
        {
            var page = document.AddPage();
            var gfx  = XGraphics.FromPdfPage(page);

            // HACK²
            gfx.MUH = PdfFontEncoding.Unicode;

            var font = new XFont("Segoe UI", 13, XFontStyle.Bold);

            gfx.DrawString("The following paragraph was rendered using MigraDoc:", font, XBrushes.Black,
                           new XRect(100, 100, page.Width - 200, 300), XStringFormats.Center);

            // You always need a MigraDoc document for rendering.
            var doc = new Document();
            var sec = doc.AddSection();
            // Add a single paragraph with some text and format information.
            var para = sec.AddParagraph();

            para.Format.Alignment  = ParagraphAlignment.Justify;
            para.Format.Font.Name  = "Times New Roman";
            para.Format.Font.Size  = 12;
            para.Format.Font.Color = Colors.DarkGray;
            para.Format.Font.Color = Colors.DarkGray;
            para.AddText("Duisism odigna acipsum delesenisl ");
            para.AddFormattedText("ullum in velenit", TextFormat.Bold);
            para.AddText(" ipit iurero dolum zzriliquisis nit wis dolore vel et nonsequipit, velendigna " +
                         "auguercilit lor se dipisl duismod tatem zzrit at laore magna feummod oloborting ea con vel " +
                         "essit augiati onsequat luptat nos diatum vel ullum illummy nonsent nit ipis et nonsequis " +
                         "niation utpat. Odolobor augait et non etueril landre min ut ulla feugiam commodo lortie ex " +
                         "essent augait el ing eumsan hendre feugait prat augiatem amconul laoreet. ≤≥≈≠");
            para.Format.Borders.Distance = "5pt";
            para.Format.Borders.Color    = Colors.Gold;

#if DEBUG
            MigraDoc.DocumentObjectModel.IO.Xml.DdlWriter.WriteToFile(doc, "MigraDoc.xml");

            Document doc3 = null;
            using (StreamReader sr = File.OpenText("MigraDoc.xml"))
            {
                var errors = new MigraDoc.DocumentObjectModel.IO.DdlReaderErrors();
                var reader = new MigraDoc.DocumentObjectModel.IO.Xml.DdlReader(sr, errors);

                doc3 = reader.ReadDocument();

                using (StreamWriter sw = new StreamWriter("MigraDoc.xml.errors"))
                {
                    foreach (MigraDoc.DocumentObjectModel.IO.DdlReaderError error in errors)
                    {
                        sw.WriteLine("{0}:{1} {2} {3}", error.SourceLine, error.SourceColumn, error.ErrorLevel, error.ErrorMessage);
                    }
                }
            }
#endif

            // Create a renderer and prepare (=layout) the document.
            var docRenderer = new DocumentRenderer(doc3);
            docRenderer.PrepareDocument();

            // Render the paragraph. You can render tables or shapes the same way.
            docRenderer.RenderObject(gfx, XUnit.FromCentimeter(5), XUnit.FromCentimeter(10), "12cm", doc3.Sections[0].LastParagraph /*para*/);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Renders a single paragraph.
        /// </summary>
        void GenerateReport(PdfDocument document)
        {
            //PdfPage page = document.AddPage();
            PdfPage page = document.Pages[0];

            XGraphics gfx = XGraphics.FromPdfPage(page);

            // HACK²
            gfx.MUH  = PdfFontEncoding.Unicode;
            gfx.MFEH = PdfFontEmbedding.Default;

            XFont font = new XFont("Verdana", 4, XFontStyle.Regular);



            // map image origin
            //gfx.DrawString("O", font, XBrushes.Red, new XRect(5, 5, 108, 161), XStringFormats.Center);


            // ovmap image origin
            //gfx.DrawString("X", font, XBrushes.Red, new XRect(5, 5, 798, 1144), XStringFormats.Center);



            //gfx.DrawString("+", font, XBrushes.Red, new XRect(5, 5, 100, 1299), XStringFormats.Center);



            //XImage ximg = XImage.FromFile(mapImagePth);
            XImage ximg = XImage.FromGdiPlusImage(mimg);

            //ximg.Interpolate = true;
            Point ipt = new Point(58, 86);

            //gfx.SmoothingMode = XSmoothingMode.HighQuality;
            gfx.DrawImage(ximg, ipt);



            //gfx.DrawImage(ximg, ipt.X, ipt.Y, ApplyTransform(ximg.PointWidth), ApplyTransform(ximg.PointHeight));


            /*
             * XImage ximg_ov = XImage.FromFile(ovmapImagePth);
             * Point ov_ipt = new Point(398, 580);
             * gfx.DrawImage(ximg_ov, ov_ipt);
             */

            //String ovmapImageTPth = @"C:\inetpub\wwwroot\ms6\output\ov\ov13_mxd_a.png";

            /*
             * XImage ximg_ov = XImage.FromFile(ovmapImagePth);
             *
             * Point ov_ipt = new Point(408, 570);
             * //gfx.DrawImage(ximg_ov, ov_ipt);
             * gfx.DrawImage(ximg_ov, ov_ipt.X, ov_ipt.Y,97,130);
             */
            /*
             * double rminx = 1218342.661;
             * double rminy = 500202.9879;
             * double rmaxx = 1397365.953;
             * double rmaxy = 738900.7105;
             * double rxw = 179023.292;
             * double rxh = 238697.7226;
             * double img_width = 97.0;
             * double img_height = 130.0;
             */
            double rminx      = 1232659.28962;
            double rminy      = 498047.976697;
            double rmaxx      = 1390211.37295;
            double rmaxy      = 739801.448919;
            double rxw        = 157552.0833;
            double rxh        = 241753.4722;
            double img_width  = 87;
            double img_height = 133;
            double qx         = minx + ((maxx - minx) / 2.0);
            double qy         = miny + ((maxy - miny) / 2.0);

            double pct_x = (qx - rminx) / rxw;
            double pct_y = (qy - rminy) / rxh;

            double px_x = pct_x * img_width;
            double px_y = (1.0 - pct_y) * img_height;

            double ul_px = ((minx - rminx) / rxw) * img_width;
            double ul_py = (1.0 - ((maxy - rminy) / rxh)) * img_height;

            double qwidth_pct = (maxx - minx) / (rmaxx - rminx);
            double qhght_pct  = (maxy - miny) / (rmaxy - rminy);

            double px_width = qwidth_pct * img_width;
            double px_hgt   = qhght_pct * img_height;


            //Debug.Print(String.Format("qx/qy: {0}  {1}    pct_x/pct_y: {2}  {3}   px_x/px_y:  {4}  {5} ", qx, qy, pct_x, pct_y, px_x, px_y));



            // option #1 - using graphics object directly on image
            Image ovImg = Image.FromFile(ovmapImageTPth);

            using (Graphics g = Graphics.FromImage(ovImg))
            {
                Pen myPen = new Pen(System.Drawing.Color.Red, 5);
                System.Drawing.Font myFont = new System.Drawing.Font("Helvetica", 15, FontStyle.Bold);
                Brush myBrush = new SolidBrush(System.Drawing.Color.Red);
                g.DrawString("x", myFont, myBrush, new PointF((float)px_x, (float)px_y));
                g.DrawRectangle(myPen, (float)ul_px, (float)ul_py, (float)px_width, (float)px_hgt);
            }

            ovImg.Save(ovmapImagePth);
            XImage ximg_ov = XImage.FromFile(ovmapImagePth);



            XImage ximgn = XImage.FromFile(northimgpth);

            //ximg.Interpolate = true;
            Point iptn = new Point(520, 570);

            //gfx.SmoothingMode = XSmoothingMode.HighQuality;
            gfx.DrawImage(ximgn, iptn);



            Point ov_ipt = new Point(400, 570);
            //gfx.DrawImage(ximg_ov, ov_ipt);

            //gfx.DrawImage(ximg_ov, ov_ipt.X, ov_ipt.Y, 97, 130);

            RectangleF srcR  = new RectangleF(0, 0, (int)img_width, (int)img_height);
            RectangleF destR = new RectangleF(ov_ipt.X, ov_ipt.Y, (int)img_width, (int)img_height);

            gfx.DrawImage(ximg_ov, destR, srcR, XGraphicsUnit.Point);

            // option #2 - using pdf object directly on report



            // XPen peno = new XPen(XColors.Aqua, 0.5);

            //gfx.DrawRectangle(peno, 408, 570,  95,  128);

            //peno = new XPen(XColors.DodgerBlue, 0.5);

            //gfx.DrawRectangle(peno, 354, 570, 200, 128);



            XPen pen = new XPen(XColors.Black, 0.5);

            gfx.DrawRectangle(pen, 29, 59, 555, 643);


            XPen pen2 = new XPen(XColors.Black, 0.8);

            gfx.DrawRectangle(pen, 29, 566, 555, 136);


            XPen   pen3  = new XPen(XColors.HotPink, 0.5);
            XBrush brush = XBrushes.LightPink;

            gfx.DrawRectangle(pen, brush, 29, 705, 555, 43);



            Document doc = new Document();



            // You always need a MigraDoc document for rendering.

            Section sec = doc.AddSection();
            // Add a single paragraph with some text and format information.
            Paragraph para = sec.AddParagraph();

            para.Format.Alignment  = ParagraphAlignment.Justify;
            para.Format.Font.Name  = "Verdana";
            para.Format.Font.Size  = Unit.FromPoint(6);
            para.Format.Font.Color = MigraDoc.DocumentObjectModel.Colors.DarkGray;
            para.Format.Font.Color = MigraDoc.DocumentObjectModel.Colors.DarkGray;
            //para.AddText("Duisism odigna acipsum delesenisl ");
            //para.AddFormattedText("ullum in velenit", TextFormat.Bold);

            para.AddText("Okaloosa County makes every effort to produce the most accurate information possible. No warranties, expressed or implied, are provided for the data herein, its use or interpretation. The assessment information is from the last certified taxroll. All data is subject to change before the next certified taxroll. PLEASE NOTE THAT THE GIS MAPS ARE FOR ASSESSMENT PURPOSES ONLY NEITHER OKALOOSA COUNTY NOR ITS EMPLOYEES ASSUME RESPONSIBILITY FOR ERRORS OR OMISSIONS ---THIS IS NOT A SURVEY---");


            //para.Format.Borders.Distance = "1pt";
            //para.Format.Borders.Color = Colors.Orange;

            // Create a renderer and prepare (=layout) the document
            MigraDoc.Rendering.DocumentRenderer docRenderer = new DocumentRenderer(doc);
            docRenderer.PrepareDocument();

            // Render the paragraph. You can render tables or shapes the same way.  29, 705, 555, 43
            docRenderer.RenderObject(gfx, XUnit.FromPoint(38), XUnit.FromPoint(710), XUnit.FromPoint(535), para);



            Section section = doc.AddSection();



            MigraDoc.DocumentObjectModel.Tables.Table table = section.AddTable();
            table.Style         = "Table";
            table.Borders.Color = MigraDoc.DocumentObjectModel.Colors.Black;
            table.Borders.Width = 0.25;

            table.Borders.Left.Width  = 0.5;
            table.Borders.Right.Width = 0.5;
            table.Rows.LeftIndent     = 0;
            table.Format.Font.Name    = "Verdana";
            table.Format.Font.Size    = Unit.FromPoint(6);
            table.Rows.Height         = Unit.FromInch(0.203);

            /*
             * // Before you can add a row, you must define the columns
             * Column column = table.AddColumn("1cm");
             * column.Format.Alignment = ParagraphAlignment.Center;
             *
             * column = table.AddColumn("2.5cm");
             * column.Format.Alignment = ParagraphAlignment.Right;
             *
             * column = table.AddColumn("3cm");
             * column.Format.Alignment = ParagraphAlignment.Right;
             *
             * column = table.AddColumn("3.5cm");
             * column.Format.Alignment = ParagraphAlignment.Right;
             *
             * column = table.AddColumn("2cm");
             * column.Format.Alignment = ParagraphAlignment.Center;
             *
             * column = table.AddColumn("4cm");
             * column.Format.Alignment = ParagraphAlignment.Right;
             *
             * // Create the header of the table
             * Row row = table.AddRow();
             * row.HeadingFormat = true;
             * row.Format.Alignment = ParagraphAlignment.Center;
             * row.Format.Font.Bold = true;
             * row.Shading.Color = MigraDoc.DocumentObjectModel.Colors.Blue;
             * row.Cells[0].AddParagraph("Item");
             * row.Cells[0].Format.Font.Bold = false;
             * row.Cells[0].Format.Alignment = ParagraphAlignment.Left;
             * row.Cells[0].VerticalAlignment = VerticalAlignment.Bottom;
             * row.Cells[0].MergeDown = 1;
             * row.Cells[1].AddParagraph("Title and Author");
             * row.Cells[1].Format.Alignment = ParagraphAlignment.Left;
             * row.Cells[1].MergeRight = 3;
             * row.Cells[5].AddParagraph("Extended Price");
             * row.Cells[5].Format.Alignment = ParagraphAlignment.Left;
             * row.Cells[5].VerticalAlignment = VerticalAlignment.Bottom;
             * row.Cells[5].MergeDown = 1;
             *
             *
             * row = table.AddRow();
             * row.HeadingFormat = true;
             * row.Format.Alignment = ParagraphAlignment.Center;
             * row.Format.Font.Bold = true;
             * row.Shading.Color = MigraDoc.DocumentObjectModel.Colors.BlueViolet;
             * row.Cells[1].AddParagraph("Quantity");
             * row.Cells[1].Format.Alignment = ParagraphAlignment.Left;
             * row.Cells[2].AddParagraph("Unit Price");
             * row.Cells[2].Format.Alignment = ParagraphAlignment.Left;
             * row.Cells[3].AddParagraph("Discount (%)");
             * row.Cells[3].Format.Alignment = ParagraphAlignment.Left;
             * row.Cells[4].AddParagraph("Taxable");
             * row.Cells[4].Format.Alignment = ParagraphAlignment.Left;
             */


            Column column = table.AddColumn(Unit.FromInch(0.31));

            column.Format.Alignment = ParagraphAlignment.Center;

            column = table.AddColumn(Unit.FromInch(2.0));
            column.Format.Alignment = ParagraphAlignment.Right;

            column = table.AddColumn(Unit.FromInch(0.8));
            column.Format.Alignment = ParagraphAlignment.Right;

            column = table.AddColumn(Unit.FromInch(1.0));
            column.Format.Alignment = ParagraphAlignment.Right;

            Row row = table.AddRow();

            row.HeadingFormat    = true;
            row.Format.Alignment = ParagraphAlignment.Center;
            row.Format.Font.Bold = true;
            row.Shading.Color    = MigraDoc.DocumentObjectModel.Color.FromRgbColor((byte)255, new MigraDoc.DocumentObjectModel.Color((byte)100, (byte)125, (byte)254));
            row.Cells[0].AddParagraph("Okaloosa County Property Appraiser  -  2013 Certified Values");
            row.Cells[0].Format.Font.Bold  = false;
            row.Cells[0].Format.Alignment  = ParagraphAlignment.Center;
            row.Cells[0].VerticalAlignment = VerticalAlignment.Center;
            row.Cells[0].MergeRight        = 3;

            row = table.AddRow();
            row.Shading.Color = MigraDoc.DocumentObjectModel.Color.FromRgbColor((byte)255, new MigraDoc.DocumentObjectModel.Color((byte)255, (byte)236, (byte)255));
            row.Cells[0].AddParagraph("Parcel: " + obCama.pinstr);
            row.Cells[0].Format.Font.Bold  = false;
            row.Cells[0].Format.Alignment  = ParagraphAlignment.Left;
            row.Cells[0].VerticalAlignment = VerticalAlignment.Center;
            row.Cells[0].MergeRight        = 3;


            row = table.AddRow();
            row.Cells[0].Shading.Color = MigraDoc.DocumentObjectModel.Color.FromRgbColor((byte)255, new MigraDoc.DocumentObjectModel.Color((byte)100, (byte)125, (byte)254));
            row.Cells[0].AddParagraph("Name");
            row.Cells[0].Format.Alignment = ParagraphAlignment.Left;

            row.Cells[1].AddParagraph(obCama.owner);
            row.Cells[1].Shading.Color    = MigraDoc.DocumentObjectModel.Color.FromRgbColor((byte)255, new MigraDoc.DocumentObjectModel.Color((byte)255, (byte)236, (byte)255));
            row.Cells[1].Format.Alignment = ParagraphAlignment.Left;

            row.Cells[2].AddParagraph("Land Value:");
            row.Cells[2].Shading.Color    = MigraDoc.DocumentObjectModel.Color.FromRgbColor((byte)255, new MigraDoc.DocumentObjectModel.Color((byte)100, (byte)125, (byte)254));
            row.Cells[2].Format.Alignment = ParagraphAlignment.Left;

            row.Cells[3].AddParagraph("$" + String.Format("{0:#,#######0}", obCama.landval));
            row.Cells[3].Shading.Color    = MigraDoc.DocumentObjectModel.Color.FromRgbColor((byte)255, new MigraDoc.DocumentObjectModel.Color((byte)255, (byte)236, (byte)255));
            row.Cells[3].Format.Alignment = ParagraphAlignment.Left;



            row = table.AddRow();
            row.Cells[0].Shading.Color = MigraDoc.DocumentObjectModel.Color.FromRgbColor((byte)255, new MigraDoc.DocumentObjectModel.Color((byte)100, (byte)125, (byte)254));
            row.Cells[0].AddParagraph("Site");
            row.Cells[0].Format.Alignment = ParagraphAlignment.Left;

            row.Cells[1].AddParagraph(obCama.site_addr);
            row.Cells[1].Shading.Color    = MigraDoc.DocumentObjectModel.Color.FromRgbColor((byte)255, new MigraDoc.DocumentObjectModel.Color((byte)255, (byte)236, (byte)255));
            row.Cells[1].Format.Alignment = ParagraphAlignment.Left;

            row.Cells[2].AddParagraph("Building Value");
            row.Cells[2].Shading.Color    = MigraDoc.DocumentObjectModel.Color.FromRgbColor((byte)255, new MigraDoc.DocumentObjectModel.Color((byte)100, (byte)125, (byte)254));
            row.Cells[2].Format.Alignment = ParagraphAlignment.Left;

            row.Cells[3].AddParagraph("$" + String.Format("{0:#,#######0}", obCama.bldval));
            row.Cells[3].Shading.Color    = MigraDoc.DocumentObjectModel.Color.FromRgbColor((byte)255, new MigraDoc.DocumentObjectModel.Color((byte)255, (byte)236, (byte)255));
            row.Cells[3].Format.Alignment = ParagraphAlignment.Left;



            row = table.AddRow();
            row.Cells[0].Shading.Color = MigraDoc.DocumentObjectModel.Color.FromRgbColor((byte)255, new MigraDoc.DocumentObjectModel.Color((byte)100, (byte)125, (byte)254));
            row.Cells[0].AddParagraph("Sale");
            row.Cells[0].Format.Alignment = ParagraphAlignment.Left;

            row.Cells[1].AddParagraph(obCama.sale_info);
            row.Cells[1].Shading.Color    = MigraDoc.DocumentObjectModel.Color.FromRgbColor((byte)255, new MigraDoc.DocumentObjectModel.Color((byte)255, (byte)236, (byte)255));
            row.Cells[1].Format.Alignment = ParagraphAlignment.Left;

            row.Cells[2].AddParagraph("Misc Value");
            row.Cells[2].Shading.Color    = MigraDoc.DocumentObjectModel.Color.FromRgbColor((byte)255, new MigraDoc.DocumentObjectModel.Color((byte)100, (byte)125, (byte)254));
            row.Cells[2].Format.Alignment = ParagraphAlignment.Left;

            row.Cells[3].AddParagraph("$" + String.Format("{0:#,#######0}", obCama.miscval));
            row.Cells[3].Shading.Color    = MigraDoc.DocumentObjectModel.Color.FromRgbColor((byte)255, new MigraDoc.DocumentObjectModel.Color((byte)255, (byte)236, (byte)255));
            row.Cells[3].Format.Alignment = ParagraphAlignment.Left;


            row = table.AddRow();
            row.Cells[0].Shading.Color = MigraDoc.DocumentObjectModel.Color.FromRgbColor((byte)255, new MigraDoc.DocumentObjectModel.Color((byte)100, (byte)125, (byte)254));
            row.Cells[0].AddParagraph("\nMail\n");
            row.Cells[0].Format.Alignment = ParagraphAlignment.Left;

            row.Cells[0].MergeDown = 3;

            //row.Cells[1].AddParagraph(obCama.mail_addr);
            row.Cells[1].AddParagraph(obCama.mail_addr_1);
            row.Cells[1].AddParagraph(obCama.mail_addr_2);

            row.Cells[1].Shading.Color    = MigraDoc.DocumentObjectModel.Color.FromRgbColor((byte)255, new MigraDoc.DocumentObjectModel.Color((byte)255, (byte)236, (byte)255));
            row.Cells[1].Format.Alignment = ParagraphAlignment.Left;
            row.Cells[1].MergeDown        = 3;

            row.Cells[2].AddParagraph("Just Value");
            row.Cells[2].Shading.Color    = MigraDoc.DocumentObjectModel.Color.FromRgbColor((byte)255, new MigraDoc.DocumentObjectModel.Color((byte)100, (byte)125, (byte)254));
            row.Cells[2].Format.Alignment = ParagraphAlignment.Left;

            row.Cells[3].AddParagraph("$" + String.Format("{0:#,#######0}", obCama.justval));
            row.Cells[3].Shading.Color    = MigraDoc.DocumentObjectModel.Color.FromRgbColor((byte)255, new MigraDoc.DocumentObjectModel.Color((byte)255, (byte)236, (byte)255));
            row.Cells[3].Format.Alignment = ParagraphAlignment.Left;


            row = table.AddRow();

            row.Cells[2].AddParagraph("Assessed Value");
            row.Cells[2].Shading.Color    = MigraDoc.DocumentObjectModel.Color.FromRgbColor((byte)255, new MigraDoc.DocumentObjectModel.Color((byte)100, (byte)125, (byte)254));
            row.Cells[2].Format.Alignment = ParagraphAlignment.Left;

            row.Cells[3].AddParagraph("$" + String.Format("{0:#,#######0}", obCama.assdval));
            row.Cells[3].Shading.Color    = MigraDoc.DocumentObjectModel.Color.FromRgbColor((byte)255, new MigraDoc.DocumentObjectModel.Color((byte)255, (byte)236, (byte)255));
            row.Cells[3].Format.Alignment = ParagraphAlignment.Left;



            row = table.AddRow();

            row.Cells[2].AddParagraph("Exempt Value");
            row.Cells[2].Shading.Color    = MigraDoc.DocumentObjectModel.Color.FromRgbColor((byte)255, new MigraDoc.DocumentObjectModel.Color((byte)100, (byte)125, (byte)254));
            row.Cells[2].Format.Alignment = ParagraphAlignment.Left;

            row.Cells[3].AddParagraph("$" + String.Format("{0:#,#######0}", obCama.exempt_val));
            row.Cells[3].Shading.Color    = MigraDoc.DocumentObjectModel.Color.FromRgbColor((byte)255, new MigraDoc.DocumentObjectModel.Color((byte)255, (byte)236, (byte)255));
            row.Cells[3].Format.Alignment = ParagraphAlignment.Left;



            row = table.AddRow();

            row.Cells[2].AddParagraph("Taxable Value");
            row.Cells[2].Shading.Color    = MigraDoc.DocumentObjectModel.Color.FromRgbColor((byte)255, new MigraDoc.DocumentObjectModel.Color((byte)100, (byte)125, (byte)254));
            row.Cells[2].Format.Alignment = ParagraphAlignment.Left;

            row.Cells[3].AddParagraph("$" + String.Format("{0:#,#######0}", obCama.taxblval));
            row.Cells[3].Shading.Color    = MigraDoc.DocumentObjectModel.Color.FromRgbColor((byte)255, new MigraDoc.DocumentObjectModel.Color((byte)255, (byte)236, (byte)255));
            row.Cells[3].Format.Alignment = ParagraphAlignment.Left;


            // Create a renderer and prepare (=layout) the document
            //MigraDoc.Rendering.DocumentRenderer docRenderer = new DocumentRenderer(doc);
            docRenderer.PrepareDocument();

            // Render the paragraph. You can render tables or shapes the same way.
            docRenderer.RenderObject(gfx, XUnit.FromInch(0.4025), XUnit.FromInch(7.88), XUnit.FromInch(3.85), table);

            //table.SetEdge(0, 0, 2, 2, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 0.75, MigraDoc.DocumentObjectModel.Colors.Yellow);

            // table.SetEdge(0, 0, 6, 2, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 0.75, MigraDoc.DocumentObjectModel.Colors.Yellow);


            XFont    font2       = new XFont("Verdana", 5, XFontStyle.Regular);
            DateTime tdate       = DateTime.Now;
            String   datestr     = tdate.ToString("MMM dd,yyy");
            String   metadataMSG = String.Format("map created {0}", datestr);

            gfx.DrawString(metadataMSG, font2, XBrushes.Black, new XRect(480, 769, 100, 20), XStringFormats.Center);

            /*
             * double xp = 0;
             * double yp = 0;
             * int numticks = 10;
             *
             * double w_inc = page.Width.Value / (double)numticks;
             * double h_inc = page.Height.Value / (double)numticks;
             *
             * for (int x = 0; x < numticks; x++)
             * {
             * for (int y = 0; y < numticks; y++)
             * {
             *
             *     xp = (double)x * w_inc;
             *     yp = (double)y * h_inc;
             *
             *     XUnit xu_x = new XUnit(xp, XGraphicsUnit.Point);
             *     XUnit xu_y = new XUnit(yp, XGraphicsUnit.Point);
             *
             *     xu_x.ConvertType(XGraphicsUnit.Inch);
             *     xu_y.ConvertType(XGraphicsUnit.Inch);
             *
             *     gfx.DrawString("+", font, XBrushes.Red, new XRect( xp,  yp, 5, 5), XStringFormats.Center);
             *     String lbl = String.Format("{0},{1}-{2},{3}", (int)xp, (int)yp, xu_x.Value, xu_y.Value);
             *     gfx.DrawString(lbl, font, XBrushes.Red, new XRect( xp + 5,  yp + 5, 5, 5), XStringFormats.Center);
             *
             *
             * }
             *
             * }
             */
        }
        public void TestDocumentRenderingVarExpressionColors()
        {
            var rendered = new DocumentRenderer().Render("{{var ConsoleForegroundColor Red!}}Hi {{FirstName!}}{{clearvar ConsoleForegroundColor !}}.  How are you?", new { FirstName = "Adam" });

            Assert.AreEqual(new ConsoleString("Hi Adam", foregroundColor: ConsoleColor.Red) + new ConsoleString(".  How are you?"), rendered);
        }
Exemplo n.º 26
0
            public override void Draw(DrawContext drawContext)
            {
                base.Draw(drawContext);

                Rectangle area = GetOccupiedAreaBBox();

                img.ScaleToFit(area.GetWidth(), area.GetHeight());

                drawContext.GetCanvas().AddXObjectFittedIntoRectangle(img.GetXObject(), new Rectangle(
                                                                          area.GetX() + (area.GetWidth() - img.GetImageWidth() *
                                                                                         img.GetProperty <float>(Property.HORIZONTAL_SCALING)) / 2,
                                                                          area.GetY() + (area.GetHeight() - img.GetImageHeight() *
                                                                                         img.GetProperty <float>(Property.VERTICAL_SCALING)) / 2,
                                                                          img.GetImageWidth() * img.GetProperty <float>(Property.HORIZONTAL_SCALING),
                                                                          img.GetImageHeight() * img.GetProperty <float>(Property.VERTICAL_SCALING)));

                drawContext.GetCanvas().Stroke();

                Paragraph p       = new Paragraph(content);
                Leading   leading = p.GetDefaultProperty <Leading>(Property.LEADING);

                UnitValue defaultFontSizeUv = new DocumentRenderer(new Document(drawContext.GetDocument()))
                                              .GetPropertyAsUnitValue(Property.FONT_SIZE);

                float         defaultFontSize = defaultFontSizeUv.IsPointValue() ? defaultFontSizeUv.GetValue() : 12f;
                float         x;
                float         y;
                TextAlignment?alignment;

                switch (position)
                {
                case POSITION.TOP_LEFT:
                {
                    x         = area.GetLeft() + 3;
                    y         = area.GetTop() - defaultFontSize * leading.GetValue();
                    alignment = TextAlignment.LEFT;
                    break;
                }

                case POSITION.TOP_RIGHT:
                {
                    x         = area.GetRight() - 3;
                    y         = area.GetTop() - defaultFontSize * leading.GetValue();
                    alignment = TextAlignment.RIGHT;
                    break;
                }

                case POSITION.BOTTOM_LEFT:
                {
                    x         = area.GetLeft() + 3;
                    y         = area.GetBottom() + 3;
                    alignment = TextAlignment.LEFT;
                    break;
                }

                case POSITION.BOTTOM_RIGHT:
                {
                    x         = area.GetRight() - 3;
                    y         = area.GetBottom() + 3;
                    alignment = TextAlignment.RIGHT;
                    break;
                }

                default:
                {
                    x         = 0;
                    y         = 0;
                    alignment = TextAlignment.CENTER;
                    break;
                }
                }

                new Canvas(drawContext.GetCanvas(), area).ShowTextAligned(p, x, y, alignment);
            }
Exemplo n.º 27
0
        /// <summary>
        /// Called when the Ddl property has changed.
        /// </summary>
        void DdlUpdated()
        {
            if (_ddl != null)
            {
                _document = DdlReader.DocumentFromString(_ddl);
                _renderer = new DocumentRenderer(_document);

                //this.renderer.PrivateFonts = this.privateFonts;
                _renderer.PrepareDocument();

                //IDocumentPaginatorSource source = this.documentViewer.Document;

                //IDocumentPaginatorSource source = this.documentViewer.Document;

                int pageCount = _renderer.FormattedDocument.PageCount;
                if (pageCount == 0)
                    return;

                // HACK: hardcoded A4 size
                //double pageWidth = XUnit.FromMillimeter(210).Presentation;
                //double pageHeight = XUnit.FromMillimeter(297).Presentation;
                //Size a4 = new Size(pageWidth, pageHeight);

                XUnit pageWidth, pageHeight;
                Size size96 = GetSizeOfPage(1, out pageWidth, out pageHeight);

                FixedDocument fixedDocument = new FixedDocument();
                fixedDocument.DocumentPaginator.PageSize = size96;

                for (int pageNumber = 1; pageNumber <= pageCount; pageNumber++)
                {
                    try
                    {
                        size96 = GetSizeOfPage(1, out pageWidth, out pageHeight);

                        DrawingVisual dv = new DrawingVisual();
                        DrawingContext dc = dv.RenderOpen();
                        //XGraphics gfx = XGraphics.FromDrawingContext(dc, new XSize(XUnit.FromMillimeter(210).Point, XUnit.FromMillimeter(297).Point), XGraphicsUnit.Point);
                        XGraphics gfx = XGraphics.FromDrawingContext(dc, new XSize(pageWidth.Point, pageHeight.Presentation), XGraphicsUnit.Point);
                        _renderer.RenderPage(gfx, pageNumber, PageRenderOptions.All);
                        dc.Close();

                        // Create page content
                        PageContent pageContent = new PageContent();
                        pageContent.Width = size96.Width;
                        pageContent.Height = size96.Height;
                        FixedPage fixedPage = new FixedPage();
                        fixedPage.Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0xFE, 0xFE, 0xFE));

                        UIElement visual = new DrawingVisualPresenter(dv);
                        FixedPage.SetLeft(visual, 0);
                        FixedPage.SetTop(visual, 0);

                        fixedPage.Width = size96.Width;
                        fixedPage.Height = size96.Height;

                        fixedPage.Children.Add(visual);

                        fixedPage.Measure(size96);
                        fixedPage.Arrange(new Rect(new Point(), size96));
                        fixedPage.UpdateLayout();

                        ((IAddChild)pageContent).AddChild(fixedPage);

                        fixedDocument.Pages.Add(pageContent);
                    }
                    catch (Exception)
                    {
                        // eat exception
                    }

                    viewer.Document = fixedDocument;
                }
            }
            else
                viewer.Document = null;
        }
        public override SubmissionStatus ServiceSubmit(string jobName, List <KeyValuePair <string, string> > fclInfo, Dictionary <string, string> driverSettings, Logger externalHandler, Stream xpsStream, int pageIndexStart, int pageIndexEnd, List <PageDimensions> pageDimensions)
        {
            AttachDebugger();

            SubmissionStatus status = new SubmissionStatus();

            status.Result = false;
            try
            {
                string      recipientEmail = GetPropertyResult("Recipient_EmailAddress", "", false);
                string      recipientName  = GetPropertyResult("Recipient_Name", "", false);
                MailAddress emailRecipient = new MailAddress(recipientEmail, recipientName);
                status.Destination = emailRecipient.ToString();
                using (SmtpClient smtpConn = new SmtpClient())
                {
                    using (MailMessage newMessage = new MailMessage())
                    {
                        smtpConn.Host      = GetPropertyResult("SMTP_Server", "", false);
                        smtpConn.EnableSsl = (GetPropertyResult("SMTP_SSL", "", false) == "NO" ? false : true);

                        string username = GetPropertyResult("SMTP_Username", "", false);
                        if (!string.IsNullOrWhiteSpace(username))
                        {
                            string smtpPassword = GetPropertyResult("SMTP_Password", "", false);
                            smtpConn.Credentials = new System.Net.NetworkCredential(username, smtpPassword);
                        }

                        smtpConn.Port = GetPropertyResult("SMTP_Port", 587, false);

                        string senderAddress = GetPropertyResult("Sender_EmailAddress", "", false);
                        string senderName    = GetPropertyResult("Sender_Name", "", false);
                        newMessage.From = new MailAddress(senderAddress, senderName);

                        newMessage.To.Add(emailRecipient);

                        string ccAddress = GetPropertyResult("Recipient_CCEmailAddress", "", false);
                        if (!string.IsNullOrWhiteSpace(ccAddress))
                        {
                            newMessage.CC.Add(new MailAddress(ccAddress));
                        }

                        string bccAddress = GetPropertyResult("Recipient_BCCEmailAddress", "", false);
                        if (!string.IsNullOrWhiteSpace(bccAddress))
                        {
                            newMessage.Bcc.Add(new MailAddress(bccAddress));
                        }

                        newMessage.Subject = GetPropertyResult("Message_Subject", "", false);
                        newMessage.Body    = GetPropertyResult("Message_Body", "", false);

                        string attachmentName = GetPropertyResult("Message_Attachment_Name", "", false);
                        if (string.IsNullOrWhiteSpace(attachmentName))
                        {
                            attachmentName = "Document";
                        }

                        var outputImageType = GetProperty <OutputImageTypeProperty>("OutputImageType", false);
                        if (outputImageType != null)
                        {
                            DocumentRenderer renderingConverter = GetRenderer(outputImageType);

                            if (renderingConverter != null)
                            {
                                TempFileStream outputStream = null;
                                try
                                {
                                    try
                                    {
                                        string tempFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Temp\");
                                        Directory.CreateDirectory(tempFolder);
                                        outputStream = new TempFileStream(tempFolder);
                                    }
                                    catch (Exception)
                                    {
                                        //Ignore - attempt another temp location (UAC may block UI from accessing Temp folder.
                                    }

                                    if (outputStream == null)
                                    {
                                        string tempFolder = Path.Combine(Path.GetTempPath(), @"FS_UPD_v4\Email_SMTP\");
                                        Directory.CreateDirectory(tempFolder);
                                        outputStream = new TempFileStream(tempFolder);
                                    }

                                    renderingConverter.RenderXpsToOutput(xpsStream, outputStream, pageIndexStart, pageIndexEnd, externalHandler);

                                    outputStream.Seek(0, SeekOrigin.Begin);
                                    attachmentName += renderingConverter.FileExtension;
                                    Attachment mailAttachment = new Attachment(outputStream, attachmentName);

                                    newMessage.Attachments.Add(mailAttachment);


                                    smtpConn.Send(newMessage);
                                }
                                finally
                                {
                                    if (outputStream != null)
                                    {
                                        outputStream.Dispose();
                                        outputStream = null;
                                    }
                                }
                            }
                        }
                    }
                }

                status.Result     = true;
                status.Message    = "Successfully sent the email to " + emailRecipient.ToString();
                status.StatusCode = 0;
            }
            catch (Exception ex)
            {
                externalHandler.LogMessage("SMTP Email Error: " + ex.ToString());
                status.Message           = "Email Error: " + ex.Message.ToString();
                status.LogDetails        = "Email Error: " + ex.ToString();
                status.SeverityLevel     = StatusResults.SeverityLevels.High;
                status.StatusCode        = 1;
                status.IsUserCorrectable = false;
                status.NotifyUser        = true;
            }

            externalHandler.LogMessage("SMTP Email Result: " + status.Result.ToString());

            return(status);
        }
Exemplo n.º 29
0
        ///// <summary>
        ///// Gets or sets the working directory.
        ///// </summary>
        //public string WorkingDirectory
        //{
        //  get
        //  {
        //    return this.workingDirectory;
        //  }
        //  set
        //  {
        //    this.workingDirectory = value;
        //  }
        //}
        //string workingDirectory = "";

        /// <summary>
        /// Called when the Ddl property has changed.
        /// </summary>
        void DdlUpdated()
        {
            if (_ddl != null)
            {
                _document = DocumentObjectModel.IO.DdlReader.DocumentFromString(_ddl);
                _renderer = new DocumentRenderer(_document);
                //_renderer.PrivateFonts = _privateFonts;
                _renderer.PrepareDocument();
                Page = 1;
                _preview.Invalidate();
            }
            //      if (this.job != null)
            //        this.job.Dispose();
            //
            //      if (this.ddl == null || this.ddl == "")
            //        return;
            //
            //      this.job = new PrintJob();
            //      this.job.Type = JobType.Standard;
            //      this.job.Ddl = this.ddl;
            //      this.job.WorkingDirectory = this.workingDirectory;
            //      this.job.InitDocument();
            //      this.preview = this.job.GetPreview(this.Handle);
            //      this.previewHandle = this.preview.Hwnd;
            //
            //      if (this.preview != null)
            //        this.preview.Page = 1;
        }
Exemplo n.º 30
0
//    [UnitTestFunction]
    public static void TestPageFormat()
    {
      Document doc = new Document();
      Section sec1 = doc.Sections.AddSection();
      sec1.PageSetup.PageFormat = PageFormat.A4;
      sec1.AddParagraph("PageFormat a4");
      Section sec2 = doc.Sections.AddSection();
      sec2.PageSetup.PageFormat = PageFormat.A6;
      sec2.PageSetup.Orientation = Orientation.Landscape;

      DocumentRenderer docRndrr = new DocumentRenderer();
      docRndrr.Render(doc, "RtfPageFormat.txt", null);
      File.Copy("RtfPageFormat.txt", "RtfPageFormat.rtf", true);
      System.Diagnostics.Process.Start("RtfPageFormat.txt");
      DdlWriter.WriteToFile(doc, "RtfPageFormat.mdddl");
    }
Exemplo n.º 31
0
 //   [UnitTestFunction]
    public static void TestTable()
    {
      Document doc = new Document();
      Section sec = doc.Sections.AddSection();
      Table table = sec.AddTable();

      table.Borders.Visible = true;
      for(int clmIdx = 0; clmIdx <= 8; ++clmIdx)
      {
        Column clm = table.Columns.AddColumn();
        clm.Format.Font.Color = clmIdx >2 ? Color.Red : Color.Green;
      }
      for(int rowIdx = 0; rowIdx <= 1000; ++rowIdx)
      {
        Row row = table.AddRow();
        row.Format.Font.Size = (float)(rowIdx / 10 + 10);
      }
      for(int clmIdx = 0; clmIdx <= 8; ++clmIdx)
      {
        for(int rowIdx = 0; rowIdx <= 1000; ++rowIdx)
        {
          table[rowIdx, clmIdx].AddParagraph(rowIdx + "," + clmIdx);
        }
      }

//      cell.AddParagraph("Tabelle");
//      cell.Shading.Color = Color.Blue;
//      cell.Borders.Right.Visible = false;
//      sec.AddParagraph("Paragraph After.");
      DocumentRenderer docRndrr = new DocumentRenderer();
      docRndrr.Render(doc, "RtfTable.txt", null);

      File.Copy("RtfTable.txt", "RtfTable.rtf", true);
      System.Diagnostics.Process.Start("RtfTable.rtf");
    }
Exemplo n.º 32
0
//    [UnitTestFunction]
    public static void TestVerticalAlign()
    {
      Document doc = new Document();
      Section sec = doc.Sections.AddSection();
      Table tbl = sec.AddTable();
      tbl.AddColumn();
      tbl.Rows.Height = 40;
      tbl.Rows.AddRow().VerticalAlignment = VerticalAlignment.Bottom;
      tbl[0, 0].AddParagraph("Text");
      tbl.Borders.Visible = true;

      DocumentRenderer docRndrr = new DocumentRenderer();
      docRndrr.Render(doc, "RtfVerticalAlign.txt", null);
      File.Copy("RtfVerticalAlign.txt", "RtfVerticalAlign.rtf", true);
      System.Diagnostics.Process.Start("RtfVerticalAlign.txt");
      DdlWriter.WriteToFile(doc, "RtfVerticalAlign.mdddl");
    }
Exemplo n.º 33
0
//    [UnitTestFunction]
    public static void TestSection()
    {
      Document doc = new Document();
      Section sec = doc.AddSection();
      Table tbl = sec.AddTable();
      tbl.AddColumn();
      Row rw = tbl.AddRow();
      rw.Cells[0].AddParagraph("Table 1");

      sec = doc.AddSection();
      tbl = sec.AddTable();
      tbl.AddColumn();
      rw = tbl.AddRow();
      rw.Cells[0].AddParagraph("Table 2");


      DocumentRenderer docRndrr = new DocumentRenderer();
      docRndrr.Render(doc, "RtfSection.txt", null);
      File.Copy("RtfSection.txt", "RtfSection.rtf", true);
      System.Diagnostics.Process.Start("RtfSection.txt");
      DdlWriter.WriteToFile(doc, "RtfSection.mdddl");
    }
Exemplo n.º 34
0
        public static void GeneratePage(PageData data, string filePath)
        {
            DateTime now      = DateTime.Now;
            string   filename = filePath;
            //filename = Guid.NewGuid().ToString("D").ToUpper() + ".pdf";
            PdfDocument document = new PdfDocument();
            //document.Info.Title = "";
            //document.Info.Author = "";
            //document.Info.Subject = "";
            //document.Info.Keywords = "";

            PdfPage   page = document.AddPage();
            XGraphics gfx  = XGraphics.FromPdfPage(page);

            gfx.MUH = PdfFontEncoding.Unicode;

            // You always need a MigraDoc document for rendering.
            Document doc = new Document();

            MigraDoc.Rendering.DocumentRenderer docRenderer = new DocumentRenderer(doc);

            gfx.DrawImage(XImage.FromFile("form.png"),
                          S(0.5f),
                          S(0.4f),
                          S(20.05f),
                          S(14.2f));

            XPdfFontOptions fontOptions    = new XPdfFontOptions(PdfFontEncoding.Unicode, PdfFontEmbedding.Always);
            XFont           smallFont      = new XFont("Times New Roman", 7, XFontStyle.Regular, fontOptions);
            XFont           notSoSmallFont = new XFont("Times New Roman", 8, XFontStyle.Regular, fontOptions);
            XFont           font           = new XFont("Times New Roman", 9.3, XFontStyle.Regular, fontOptions);
            XFont           bigFont        = new XFont("Times New Roman", 10, XFontStyle.Bold, fontOptions);

            XBrush brush = XBrushes.Black;
            Color  color = MigraDoc.DocumentObjectModel.Colors.Black;

            Action <String, double, double> DrawSmallText      = (text, x, y) => gfx.DrawString(text, smallFont, brush, S(x), S(y), XStringFormats.TopLeft);
            Action <String, double, double> DrawNotSoSmallText = (text, x, y) => gfx.DrawString(text, notSoSmallFont, brush, S(x), S(y), XStringFormats.TopLeft);
            Action <String, double, double> DrawText           = (text, x, y) => gfx.DrawString(text, font, brush, S(x), S(y), XStringFormats.TopLeft);
            Action <String, double, double> DrawBigText        = (text, x, y) => gfx.DrawString(text, bigFont, brush, S(x), S(y), XStringFormats.TopLeft);

            Action <float, double, double>          DRV   = (value, x, y) => DrawRightValue(doc, docRenderer, gfx, color, "Times New Roman", 7.2, value, x, y);
            Action <String, double, double>         DLTf8 = (text, x, y) => DrawLeftText(doc, docRenderer, gfx, color, "Times New Roman", 8.1, text, x, y);
            Action <float, double, double>          DRVf8 = (value, x, y) => DrawRightValue(doc, docRenderer, gfx, color, "Times New Roman", 8.1, value, x, y);
            Action <String, double, double, double> DCTf8 = (text, x, y, width) => DrawCenterText(doc, docRenderer, gfx, color, "Times New Roman", 8.8, text, x, y, width);
            Action <String, double, double>         DLTf6 = (text, x, y) => DrawLeftText(doc, docRenderer, gfx, color, "Times New Roman", 6.7, text, x, y);
            Action <float, double, double>          DRVf6 = (value, x, y) => DrawRightValue(doc, docRenderer, gfx, color, "Times New Roman", 6.8, value, x, y);
            Action <String, double, double>         DRTf6 = (text, x, y) => DrawRightText(doc, docRenderer, gfx, color, "Times New Roman", 6.8, text, x, y);

            DCTf8(data.poluchatel, 5.45, 0.9, 14.4);

            DrawText(data.FIO, 6.52, 1.98);
            DrawText(data.address, 6.53, 2.43);
            DrawText(data.FLS, 15.91, 2.65);

            DrawBigText(data.month.ToString(), 15.82, 2.1f);
            DrawBigText(data.year.ToString(), 18.37, 2.1f);

            DrawRightValue(doc, docRenderer, gfx, color, "Arial", 10, data.itogo, 8.63f, 3.82f);
            DrawRightValue(doc, docRenderer, gfx, color, "Times New Roman", 10, data.itogo, 4.64f, 5.51f);

            //--------------------------------------------
            DCTf8(data.poluchatel, 5.45, 7.23, 14.4);

            double sx0          = 5.44;
            double sy0          = 8.92;
            double systep       = 0.295;
            int    serviceIndex = 0;

            for (int i = 0; i < data.services.Length; i++)
            {
                Service service = data.services[i];
                if (service == null)
                {
                    continue;                     //no db response
                }
                double y = sy0 + systep * serviceIndex;
                DLTf6(service.vid, sx0, y);
                DRVf6(service.tarif, sx0 - 1.56, y);
                DRTf6(service.obem, sx0 - 0.08, y);
                DRVf6(service.nachisleno, sx0 + 1.14, y);
                DRVf6(service.lgoty, sx0 + 2.24, y);
                DRVf6(service.vsego, sx0 + 3.44, y);

                serviceIndex++;
            }

            DrawSmallText(data.FIO, 14.97, 8.2);
            DrawSmallText(data.address, 14.97, 8.6);
            DrawSmallText(Months(data.month) + " " + data.year, 15.88, 9.01);
            DrawSmallText(data.FLS, 18.84, 9.01);

            {
                double x0 = 14.091;
                double y0 = 9.45;
                double xv = 15.28;
                DLTf8("ИТОГО К ОПЛАТЕ", x0, y0);

                DRVf8(data.itogo, xv, y0);
            }

            DRV(data.nachisleno, 6.55, 13.02);
            DRV(data.summaLgot, 7.65, 13.02);
            DRV(data.itogo, 8.85, 13.02);

            DrawNotSoSmallText(data.date, 3.58, 13.83);

            docRenderer.PrepareDocument();


            Debug.WriteLine("seconds=" + (DateTime.Now - now).TotalSeconds.ToString());

            // Save the document...
            document.Save(filename);
        }
Exemplo n.º 35
0
//    [UnitTestFunction]
    public static void TestRowHeight()
    {
      Document doc = new Document();
      Section sec = doc.Sections.AddSection();
      Table tbl = sec.AddTable();
      tbl.AddColumn();
      tbl.Rows.Height = 40;
      tbl.Rows.AddRow();
      tbl.Borders.Visible = true;

      DocumentRenderer docRndrr = new DocumentRenderer();
      docRndrr.Render(doc, "RtfRowHeight.txt", null);
      File.Copy("RtfRowHeight.txt", "RtfRowHeight.rtf", true);
      System.Diagnostics.Process.Start("RtfRowHeight.txt");
      DdlWriter.WriteToFile(doc, "RtfRowHeight.mdddl");
    }
Exemplo n.º 36
0
 public static void TestVermögensverwaltung()
 {
   Document doc = DocumentObjectModel.IO.DdlReader.DocumentFromFile("Vermögensverwaltung.mdddl"); //, null);
   DocumentRenderer docRndrr = new DocumentRenderer();
   docRndrr.Render(doc, "RtfVermögensverwaltung.txt", null);
   File.Copy("RtfVermögensverwaltung.txt", "RtfVermögensverwaltung.rtf", true);
   System.Diagnostics.Process.Start("RtfVermögensverwaltung.txt");
   DdlWriter.WriteToFile(doc, "RtfVermögensverwaltung.mdddl");
 }
Exemplo n.º 37
0
    //[UnitTestFunction]
    public static void TestBorderDistances()
    {
      Document doc = new Document();
      Section sec = doc.Sections.AddSection();
      Paragraph par = sec.AddParagraph("left dist = 10");
      par.Format.Borders.DistanceFromLeft = 10;


      DocumentRenderer docRndrr = new DocumentRenderer();
      docRndrr.Render(doc, "RtfBorderDistances.txt", null);
      File.Copy("RtfBorderDistances.txt", "RtfBorderDistances.rtf", true);
      System.Diagnostics.Process.Start("RtfBorderDistances.txt");
      DdlWriter.WriteToFile(doc, "RtfBorderDistances.mdddl");
    }
Exemplo n.º 38
0
//    [UnitTestFunction]
    public static void TestHeaderParagraphStyle()
    {
      Document doc = new Document();
      Style myHdrStl = doc.Styles.AddStyle("MyHeaderStyle","Normal");
      myHdrStl.ParagraphFormat.TabStops.AddTabStop("10cm");
      Paragraph par = doc.AddSection().Headers.Primary.AddParagraph();
      par.Style = "MyHeaderStyle";
      par.Elements.AddTab();
      par.Elements.AddText("Hallo");

      DocumentRenderer docRndrr = new DocumentRenderer();
      docRndrr.Render(doc, "RtfHeaderParagraphStyle.txt", null);
      File.Copy("RtfHeaderParagraphStyle.txt", "RtfHeaderParagraphStyle.rtf", true);
      System.Diagnostics.Process.Start("RtfHeaderParagraphStyle.txt");
      DdlWriter.WriteToFile(doc, "RtfHeaderParagraphStyle.mdddl");
    }
Exemplo n.º 39
0
//    [UnitTestFunction]
    public static void TestTextFramePos()
    {
      Document doc = new Document();
      Section sec = doc.Sections.AddSection();
      sec.AddParagraph("paragraphBefore");
      TextFrame txtFrm = sec.AddTextFrame();
      txtFrm.RelativeHorizontal = RelativeHorizontal.Page;
      txtFrm.WrapFormat.Style = WrapStyle.Through;
      txtFrm.WrapFormat.DistanceRight = "5cm";
      txtFrm.Left = ShapePosition.Right;
      sec.AddParagraph("paragraphAfter");

      DocumentRenderer docRndrr = new DocumentRenderer();
      docRndrr.Render(doc, "RtfTextFramePos.txt", null);
      File.Copy("RtfTextFramePos.txt", "RtfTextFramePos.rtf", true);
      System.Diagnostics.Process.Start("RtfTextFramePos.txt");
      DdlWriter.WriteToFile(doc, "RtfTextFramePos.mdddl");
    }
Exemplo n.º 40
0
//    [UnitTestFunction]
    public static void TestSpecialCharacters()
    {
      Document doc = new Document();
      Section sec = doc.Sections.AddSection();
      Paragraph par = sec.AddParagraph();
      par.AddCharacter('\x93');
      par.AddCharacter(SymbolName.Blank);
      par.AddCharacter(SymbolName.Bullet);
      par.AddCharacter(SymbolName.Copyright);
      par.AddCharacter(SymbolName.Em);
      par.AddCharacter(SymbolName.Em4);
      par.AddCharacter(SymbolName.EmDash);
      par.AddCharacter(SymbolName.En);
      par.AddCharacter(SymbolName.EnDash);
      par.AddCharacter(SymbolName.Euro);
      par.AddCharacter(SymbolName.HardBlank);
      par.AddCharacter(SymbolName.LineBreak);
      par.AddCharacter(SymbolName.Not);
      par.AddCharacter(SymbolName.ParaBreak);
      par.AddCharacter(SymbolName.RegisteredTrademark);
      par.AddCharacter(SymbolName.Tab);
      par.AddCharacter(SymbolName.Trademark);

      DocumentRenderer docRndrr = new DocumentRenderer();
      docRndrr.Render(doc, "RtfSpecialChars.txt", null);

      File.Copy("RtfSpecialChars.txt", "RtfSpecialChars.rtf", true);
      System.Diagnostics.Process.Start("RtfSpecialChars.txt");
    }
        public void TestDocumentRenderingWithNoReplacements()
        {
            var rendered = new DocumentRenderer().Render("Hi", 1);

            Assert.AreEqual("Hi", rendered.ToString());
        }
        public override SubmissionStatus ServiceSubmit(string jobName, string fclInfo, Dictionary <string, string> driverSettings, Logger externalHandler, Stream xpsStream, int pageIndexStart, int pageIndexEnd, List <PageDimensions> pageDimensions)
        {
            AttachDebugger();

            var status = new SubmissionStatus();

            status.Result = false;

            try
            {
                string account  = GetPropertyResult("account", "");
                string username = GetPropertyResult("username", "");
                string password = GetPropertyResult("password", "");
                //string faxHeader = GetPropertyResult("faxHeader", "");
                string faxTag            = GetPropertyResult("faxTag", "");
                string callerId          = GetPropertyResult("callerId", "");
                string faxNumber         = GetPropertyResult("faxNumber", "");
                bool?  requireEncryption = GetPropertyResult <bool?>("requireEncryption", null);

                if (String.IsNullOrWhiteSpace(account))
                {
                    throw new Exception("Missing property: account");
                }
                if (String.IsNullOrWhiteSpace(username))
                {
                    throw new Exception("Missing property: username");
                }
                if (String.IsNullOrWhiteSpace(password))
                {
                    throw new Exception("Missing property: password");
                }
                //if (String.IsNullOrWhiteSpace(faxHeader))
                //{
                //    throw new Exception("Missing property: faxHeader");
                //}
                if (String.IsNullOrWhiteSpace(faxNumber))
                {
                    throw new Exception("Missing property: faxNumber");
                }
                if (requireEncryption == null)
                {
                    throw new Exception("Missing property: requireEncryption");
                }

                // Force OuptutImageType values. The user cannot change them for EtherFax.
                OutputImageTypeProperty outputImageType = new OutputImageTypeProperty("OutputImageType", "Output File Type")
                {
                    UserGenerated      = false,
                    DocxOutputAllowed  = false,
                    XpsOutputAllowed   = false,
                    PdfOutputAllowed   = false,
                    TiffOutputAllowed  = true,
                    RenderMode         = RenderModes.Raster_1,
                    RenderModesAllowed = new List <RenderModes>()
                    {
                        RenderModes.Raster_1
                    },

                    TiffCompression         = TiffCompressOption.Ccitt4,
                    TiffCompressionsAllowed = new List <TiffCompressOption>()
                    {
                        TiffCompressOption.Ccitt4
                    },

                    RenderPixelFormat         = PixelFormats.BlackWhite,
                    RenderPixelFormatsAllowed = new List <PixelFormats>()
                    {
                        PixelFormats.BlackWhite
                    }
                };

                /*
                 * https://tools.ietf.org/html/rfc2306
                 *
                 *  XResolution x Yresolution                  | ImageWidth
                 * --------------------------------------------|------------------
                 *  204x98, 204x196, 204x391, 200x100, 200x200 | 1728, 2048, 2432
                 *  300x300                                    | 2592, 3072, 3648
                 *  408x391, 400x400                           | 3456, 4096, 4864
                 * --------------------------------------------|------------------
                 *
                 * These are the fixed page widths in pixels.  The permissible values are dependent upon X and Y resolutions.
                 *
                 */

                int faxHorizontalResolution = 204;
                int faxVerticalResolution   = 196;

                outputImageType.HorizontalDpi = faxHorizontalResolution;
                outputImageType.VerticalDpi   = faxVerticalResolution;

                int faxPageWidth = 1728;  // 8.5" x 11" @ 204 x 196 dpi = 1734px x 2156px @ 99.6% => 1728px x 2148px (Desired fax width of 1728px @ 204 horizontal dpi)

                PointF pagePixels = pageDimensions[pageIndexStart].GetPixels(faxHorizontalResolution, faxVerticalResolution);

                float pageScaleRatio = faxPageWidth / pagePixels.X;
                int   faxPageHeight  = (int)(pageScaleRatio * pagePixels.Y);

                outputImageType.ImageDimensions = new System.Drawing.Point(faxPageWidth, faxPageHeight);

                DocumentRenderer renderingConverter = GetRenderer(outputImageType);
                if (renderingConverter != null)
                {
                    // Read the image to memory
                    byte[] fileBytes;


                    TempFileStream outputStream = null;
                    try
                    {
                        try
                        {
                            string tempFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Temp\");
                            Directory.CreateDirectory(tempFolder);
                            outputStream = new TempFileStream(tempFolder);
                        }
                        catch (Exception)
                        {
                            // Ignore - attempt another temp location (UAC may block UI test button from accessing the default Temp folder.)
                        }

                        if (outputStream == null)
                        {
                            string tempFolder = Path.Combine(Path.GetTempPath(), @"FS_UPD_v4\EtherFax\");
                            Directory.CreateDirectory(tempFolder);
                            outputStream = new TempFileStream(tempFolder);
                        }

                        renderingConverter.RenderXpsToOutput(xpsStream, outputStream, pageIndexStart, pageIndexEnd, externalHandler);
                        outputStream.Seek(0, SeekOrigin.Begin);

                        fileBytes = new byte[outputStream.Length];
                        outputStream.Read(fileBytes, 0, fileBytes.Length);
                    }
                    finally
                    {
                        if (outputStream != null)
                        {
                            outputStream.Dispose();
                            outputStream = null;
                        }
                    }


                    var offset = TimeZoneInfo.Local.GetUtcOffset(DateTime.UtcNow);

                    status.Destination = "Fax: " + faxNumber;

                    var       client    = new SampleEtherFaxApi(account, username, password);
                    FaxStatus faxStatus = client.SendFax(faxNumber, faxTag, callerId, offset, fileBytes, ((pageIndexEnd - pageIndexStart) + 1), requireEncryption.Value);

                    if (faxStatus.FaxResult == FaxResult.InProgress)
                    {
                        status.Result            = true;
                        status.Message           = "Fax in progress.";
                        status.NextStatusRefresh = DateTime.Now.AddSeconds(30);
                        status.StatusCode        = 0;

                        var stateData = new UpdStatusState();
                        stateData.account          = account;
                        stateData.username         = username;
                        stateData.password         = Convert.ToBase64String(ProtectedData.Protect(Encoding.UTF8.GetBytes(password), _encryptionEntropy, DataProtectionScope.LocalMachine));
                        stateData.jobId            = faxStatus.JobId;
                        stateData.tagValue         = faxTag;
                        stateData.statusRetryCount = 0;

                        status.State = JsonConvert.SerializeObject(stateData);

                        status.LogDetails += "Submitted Fax with etherFAX ID: " + faxStatus.JobId + "\r\n";
                        status.LogDetails += "etherFAX Tag: " + faxTag + "\r\n";
                    }
                    else if (faxStatus.FaxResult == FaxResult.Success)
                    {
                        status.Result     = true;
                        status.Message    = "Your fax was delivered successfully.";
                        status.StatusCode = 100;
                        status.NotifyUser = true;

                        status.LogDetails  = "Your fax was delivered successfully!\r\n";
                        status.LogDetails += "Submitted Fax with etherFAX ID: " + faxStatus.JobId + "\r\n";
                        status.LogDetails += "etherFAX Tag: " + faxTag + "\r\n";
                    }
                    else if (faxStatus.FaxResult == FaxResult.Cancelled)
                    {
                        status.Result        = false;
                        status.Message       = "Your fax was cancelled.";
                        status.StatusCode    = 300;
                        status.SeverityLevel = StatusResults.SeverityLevels.Low;
                        status.NotifyUser    = true;

                        status.LogDetails  = "Fax cancelled:  " + faxStatus.ToString().Replace("_", " ") + "\r\n";
                        status.LogDetails += "Submitted Fax with etherFAX ID: " + faxStatus.JobId + "\r\n";
                        status.LogDetails += "etherFAX Tag: " + faxTag + "\r\n";
                    }
                    else // All errors
                    {
                        status.Result        = false;
                        status.Message       = "Your fax was not delivered. Reason: " + faxStatus.ToString().Replace("_", " ");
                        status.StatusCode    = 400 + (int)faxStatus.FaxResult;
                        status.SeverityLevel = StatusResults.SeverityLevels.High;
                        status.NotifyUser    = true;

                        status.LogDetails  = "Fax failed:  " + faxStatus.ToString().Replace("_", " ") + "\r\n";
                        status.LogDetails += "Submitted Fax with etherFAX ID: " + faxStatus.JobId + "\r\n";
                        status.LogDetails += "etherFAX Tag: " + faxTag + "\r\n";
                    }
                }
            }
            catch (WebException httpEx)
            {
                string webExDetails = "";

                using (var httpResponse = httpEx.Response as HttpWebResponse)
                {
                    if (httpResponse != null)
                    {
                        HttpStatusCode statusCode        = httpResponse.StatusCode;
                        string         statusDescription = httpResponse.StatusDescription;

                        string responseHeaders = httpResponse.Headers != null?httpResponse.Headers.ToString() : null;

                        using (Stream stream = httpResponse.GetResponseStream())
                        {
                            using (var sr = new StreamReader(stream))
                            {
                                string content = sr.ReadToEnd();
                                webExDetails = "Status: " + statusCode.ToString() + @"/" + statusDescription + "\r\n\r\n" + "Response: " + content;
                            }
                        }
                    }
                }

                status.Result     = false;
                status.Message    = "An error has occurred.";
                status.LogDetails = httpEx.Message + "\r\n\r\n" + webExDetails;
                status.NotifyUser = true;
                status.StatusCode = 11;
            }
            catch (Exception ex)
            {
                status.Result     = false;
                status.Message    = "An error has occurred.";
                status.LogDetails = ex.Message;
                status.NotifyUser = true;
                status.StatusCode = 12;
            }

            return(status);
        }
Exemplo n.º 43
0
//    [UnitTestFunction]
    public static void TestImage()
    {
      Document doc = new Document();
      doc.AddSection().AddImage("logo.jpg").ScaleHeight = 0.5f;
      DocumentRenderer docRndrr = new DocumentRenderer();
      docRndrr.Render(doc, "RtfImage.txt", null);
      File.Copy("RtfImage.txt", "RtfImage.rtf", true);
      System.Diagnostics.Process.Start("RtfImage.txt");
      DdlWriter.WriteToFile(doc, "RtfImage.mdddl");
    }
Exemplo n.º 44
0
        public void ExportToPdf(string path)
        {
            var document = new Document();

            document.Info.Title   = string.Format("Invoice from {0}", Seller.Name);
            document.Info.Author  = Seller.Name;
            document.Info.Subject = "Invoice";

            //metody poniższe zwracają obiekty dodawane
            var section = document.AddSection();
            var image   = section.Headers.Primary.AddImage(Seller.LogoImagePath);

            image.Height = Unit.FromCentimeter(2.5); // ustawienie wysokości obrazka na 2,5 cm

            image.LockAspectRatio = true;

            //ustawianie wycentrowania
            image.RelativeHorizontal = RelativeHorizontal.Margin;
            image.RelativeVertical   = RelativeVertical.Line;
            image.Top  = ShapePosition.Top;
            image.Left = ShapePosition.Right;

            image.WrapFormat.Style = WrapStyle.Through; //otaczanie elementami np ramka

            // Create the text frame for the address
            var addressFrame = section.AddTextFrame();

            addressFrame.Height             = "3.0cm";
            addressFrame.Width              = "7.0cm";
            addressFrame.Left               = ShapePosition.Left;
            addressFrame.RelativeHorizontal = RelativeHorizontal.Margin;
            addressFrame.Top = "5.0cm";
            addressFrame.RelativeVertical = RelativeVertical.Page;

            // Put sender in address frame
            var paragraph = addressFrame.AddParagraph(Seller.Name + " " + Seller.Address);

            paragraph.Format.Font.Name  = "Times New Roman";
            paragraph.Format.Font.Size  = 7;
            paragraph.Format.SpaceAfter = 3;

            var customerParagraph = addressFrame.AddParagraph(Customer.Name);

            customerParagraph.AddLineBreak();
            customerParagraph.AddText(Customer.TaxId);
            customerParagraph.AddLineBreak();
            customerParagraph.AddText(Customer.Address);

            // Add the print date field
            var dateParagraph = section.AddParagraph();

            dateParagraph.Format.SpaceBefore = "8cm";
            dateParagraph.Style             = "Reference";
            dateParagraph.Format.Font.Color = getColor(System.Drawing.Color.Black);
            dateParagraph.AddFormattedText("FAKTURA", TextFormat.Bold);
            dateParagraph.AddTab();
            dateParagraph.AddText("Łódź, ");
            dateParagraph.AddDateField("dd-MM-yyyy");



            // Create the item table
            var table = section.AddTable();

            table.Style               = "Table";
            table.Borders.Color       = getColor(System.Drawing.Color.Black);
            table.Borders.Width       = 0.25;
            table.Borders.Left.Width  = 0.5;
            table.Borders.Right.Width = 0.5;
            table.Rows.LeftIndent     = 0;

            // Before you can add a row, you must define the columns
            var column = table.AddColumn("1cm");

            column.Format.Alignment = ParagraphAlignment.Center;

            column = table.AddColumn("2.5cm");
            column.Format.Alignment = ParagraphAlignment.Right;

            column = table.AddColumn("3cm");
            column.Format.Alignment = ParagraphAlignment.Right;

            //column = table.AddColumn("3.5cm");
            //column.Format.Alignment = ParagraphAlignment.Right;

            column = table.AddColumn("2cm");
            column.Format.Alignment = ParagraphAlignment.Center;

            column = table.AddColumn("4cm");
            column.Format.Alignment = ParagraphAlignment.Right;

            // Create the header of the table
            var row = table.AddRow();

            row.HeadingFormat    = true;
            row.Format.Alignment = ParagraphAlignment.Center;
            row.Format.Font.Bold = true;
            row.Shading.Color    = getColor(System.Drawing.Color.LightBlue);
            row.Cells[0].AddParagraph("Kod towaru");
            row.Cells[0].Format.Font.Bold  = false;
            row.Cells[0].Format.Alignment  = ParagraphAlignment.Left;
            row.Cells[0].VerticalAlignment = VerticalAlignment.Bottom;
            row.Cells[0].MergeDown         = 1;
            row.Cells[1].AddParagraph("Nazwa");
            row.Cells[1].Format.Alignment = ParagraphAlignment.Left;
            row.Cells[1].MergeRight       = 2;
            //5 >> 4
            row.Cells[4].AddParagraph("Wartość");
            row.Cells[4].Format.Alignment  = ParagraphAlignment.Left;
            row.Cells[4].VerticalAlignment = VerticalAlignment.Bottom;
            row.Cells[4].MergeDown         = 1;

            row = table.AddRow();
            row.HeadingFormat    = true;
            row.Format.Alignment = ParagraphAlignment.Center;
            row.Format.Font.Bold = true;
            row.Shading.Color    = getColor(System.Drawing.Color.LightBlue);
            row.Cells[1].AddParagraph("Ilość");
            row.Cells[1].Format.Alignment = ParagraphAlignment.Left;
            row.Cells[2].AddParagraph("Cena jedn. ");
            row.Cells[2].Format.Alignment = ParagraphAlignment.Left;
            row.Cells[3].AddParagraph("VAT");
            row.Cells[3].Format.Alignment = ParagraphAlignment.Left;
            //row.Cells[4].AddParagraph("Taxable");
            //row.Cells[4].Format.Alignment = ParagraphAlignment.Left;

            table.SetEdge(0, 0, 5, 2, Edge.Box, BorderStyle.Single, 0.75, getColor(System.Drawing.Color.Black));//ustawienie tabeli 5 - ilość kolumn

            float totalValue = 0.0f;
            float totalTax   = 0.0f;


            foreach (var item in Items)
            {
                var row1 = table.AddRow();
                var row2 = table.AddRow();

                row1.Cells[0].MergeDown  = 1; //łączenie komórek z innymi
                row1.Cells[1].MergeRight = 2;
                row1.Cells[4].MergeDown  = 1;

                row1.Cells[0].AddParagraph(item.Good.ItemCode);

                var rowPara = row1.Cells[1].AddParagraph(item.Good.ItemName);
                rowPara.Format.Alignment = ParagraphAlignment.Left;

                row2.Cells[1].AddParagraph(item.Quantity.ToString());
                row2.Cells[2].AddParagraph(item.Good.ItemPrice.ToString());
                row2.Cells[3].AddParagraph(item.Good.ItemVat + "%");

                var taxValue = item.Quantity * item.Good.ItemVat / 100 * item.Good.ItemPrice;
                var value    = item.Quantity * item.Good.ItemPrice + taxValue;
                totalValue += value;
                totalTax   += taxValue;

                row1.Cells[4].AddParagraph(value.ToString("0.00") + "zł");
            }

            row = table.AddRow();
            row.Borders.Visible = false;

            row = table.AddRow();
            var totalParagraph = row.Cells[3].AddParagraph("TOTAL: ");

            totalParagraph.Format.Font.Bold = true;
            row.Cells[0].MergeRight         = 2;
            row.Cells[0].Borders.Visible    = false;

            row.Cells[4].AddParagraph(totalValue.ToString("0.00") + "zł");

            //row = table.AddRow();
            //row.Cells[3].AddParagraph("TOTAL: ");
            //row.Cells[4].AddParagraph(totalValue.ToString("0.00") + "zł");

            row = table.AddRow();
            var vatParagraph = row.Cells[3].AddParagraph("VAT: ");

            vatParagraph.Format.Font.Bold = true;
            row.Cells[0].MergeRight       = 2;
            row.Cells[0].Borders.Visible  = false;

            row.Cells[4].AddParagraph(totalTax.ToString("0.00") + "zł");

            //row = table.AddRow();
            //row.Cells[3].AddParagraph("VAT:");
            //row.Cells[4].AddParagraph(totalTax.ToString("0.00") + "zł");

            var pdfDoc = new PdfDocument();
            var page   = pdfDoc.AddPage();

            var xdr = XGraphics.FromPdfPage(page);  //generuje obiekt do rysowania kanwas graficzny


            var docRender = new DocumentRenderer(document); //klasa która przetwara instrukcje i przygotowuje metaopis do wygenerowania pdf

            docRender.PrepareDocument();                    //przygotowujemy (pre-rendering) dokument MigraDoc
            docRender.RenderPage(xdr, 1);                   // dodajemy do canvasu tj. do strony w dokumencie PDF

            pdfDoc.Save(path);                              // zapis do pliku PDF
        }
Exemplo n.º 45
0
 //[UnitTestFunction]
 public static void TestImagePath()
 {
   Document doc = new Document();
   doc.ImagePath = "Images";
   doc.Sections.AddSection().AddImage("logo.gif");
   DocumentRenderer docRndrr = new DocumentRenderer();
   docRndrr.Render(doc, "RtfImagePath.txt", null);
   File.Copy("RtfImagePath.txt", "RtfImagePath.rtf", true);
   System.Diagnostics.Process.Start("RtfImagePath.txt");
   DdlWriter.WriteToFile(doc, "RtfImagePath.mdddl");
 }
Exemplo n.º 46
0
        /// <summary>
        /// Writes the work items.
        /// </summary>
        private void WriteWorkItems()
        {
            // Create document
            var migraDoc = new Document();

            var areas = workItems.Select(c => c.Area).Distinct();

            foreach (var area in areas)
            {
                Section sec = migraDoc.AddSection();

                // Add a single paragraph with some text and format information.
                Paragraph para = sec.AddParagraph();
                para.Format.Alignment  = ParagraphAlignment.Justify;
                para.Format.Font.Name  = "Tahoma";
                para.Format.Font.Size  = 14;
                para.Format.Font.Color = Colors.Black;

                // Are we looking at a sub area?
                var startChar = area.LastIndexOf(@"\", System.StringComparison.Ordinal) == -1
                    ? 0
                    : area.LastIndexOf(@"\", System.StringComparison.Ordinal) + 1;

                // Add the area name
                para.AddText(area.Substring(startChar));
                para.AddLineBreak();
                para.AddLineBreak();

                WriteWorkItemTable(migraDoc, area);
            }

            // Create a renderer and prepare (=layout) the document
            var docRenderer = new DocumentRenderer(migraDoc);

            docRenderer.PrepareDocument();

            int pageCount = docRenderer.FormattedDocument.PageCount;

            for (int idx = 0; idx < pageCount; idx++)
            {
                // Template Page
                var pageTemplateDoc = PdfReader.Open(this.request.PageTemplate, PdfDocumentOpenMode.Import);
                var page            = pageTemplateDoc.Pages[0];

                page = this.doc.AddPage(page);
                XGraphics gfx = XGraphics.FromPdfPage(page);

                var font = new XFont("Tahoma", 9, XFontStyle.Regular);

                gfx.DrawString(
                    string.Format(
                        "Project: {0} - Build: {1} - Iteration: {2}",
                        this.request.TfsProject,
                        this.request.BuildNumber,
                        this.request.IterationNumber),
                    font,
                    XBrushes.Gray,
                    new XRect(50, 800, page.Width - 200, 50),
                    XStringFormats.TopLeft);

                gfx.DrawString(
                    string.Format(
                        "Page {0}",
                        idx + 2),
                    font,
                    XBrushes.Gray,
                    new XRect(page.Width - 100, 800, page.Width - 50, 50),
                    XStringFormats.TopLeft);

                // HACK²
                gfx.MUH  = PdfFontEncoding.Unicode;
                gfx.MFEH = PdfFontEmbedding.Default;

                // Render the page. Note that page numbers start with 1.
                docRenderer.RenderPage(gfx, idx + 1);
            }
        }
Exemplo n.º 47
0
        private static void CreatePage(BillInvoiceDto bill)
        {
            // You always need a MigraDoc document for rendering.
            Document doc  = new Document();
            Section  sec  = doc.AddSection();
            PdfPage  page = _document.AddPage();
            //setup size to letter type
            //612 pixels
            XUnit pdfWidth = new XUnit(216, XGraphicsUnit.Millimeter);
            //790 pixels
            XUnit pdfHeight = new XUnit(279, XGraphicsUnit.Millimeter);

            page.Height      = pdfHeight;
            page.Width       = pdfWidth;
            page.Orientation = PageOrientation.Portrait;
            XGraphics gfx = XGraphics.FromPdfPage(page);

            // HACK²
            gfx.MUH = PdfFontEncoding.Unicode;

            gfx.MFEH = PdfFontEmbedding.Default;
            XFont regulerFontBold = new XFont("Verdana", 9, XFontStyle.Bold);
            XFont CompanyFont     = new XFont("Verdana", 20, XFontStyle.Bold);
            XFont regularFont     = new XFont("Verdana", 9, XFontStyle.Regular);
            XFont smallFont       = new XFont("Verdana", 7, XFontStyle.Regular);

            //Header
            //Company name
            gfx.DrawString("CompanyName", CompanyFont, XBrushes.Black,
                           new XRect(30, 30, 50, 300), XStringFormats.TopLeft);
            //address
            gfx.DrawString("some address", regulerFontBold, XBrushes.Black,
                           new XRect(30, 55, 30, 300), XStringFormats.TopLeft);
            //contact
            gfx.DrawString("some contacts", regulerFontBold, XBrushes.Black,
                           new XRect(30, 65, 30, 300), XStringFormats.TopLeft);

            //Line
            //thin line
            DrawLine(gfx, 30, 77, 480, 77, 1);
            DrawLine(gfx, 547, 77, 582, 77, 1);
            //fat line
            DrawLine(gfx, 30, 81, 480, 81, 3);
            DrawLine(gfx, 547, 81, 582, 81, 3);
            //thin line
            DrawLine(gfx, 30, 85, 480, 85, 1);
            DrawLine(gfx, 547, 85, 582, 85, 1);
            gfx.DrawString("INVOICE", new XFont("Verdana", 13, XFontStyle.BoldItalic), XBrushes.Black,
                           new XRect(481, 73, 481, 70), XStringFormats.TopLeft);


            //invoice number and dates
            //invoice number
            gfx.DrawString("Invoice No:", regularFont, XBrushes.Black,
                           new XRect(30, 120, 100, 120), XStringFormats.TopLeft);
            gfx.DrawString(bill.InvoiceNo?.ToString() ?? "", regularFont, XBrushes.Black,
                           new XRect(90, 120, 170, 120), XStringFormats.TopLeft);
            // invoice dates
            gfx.DrawString("Invoice Date:", regularFont, XBrushes.Black,
                           new XRect(400, 120, 440, 120), XStringFormats.TopLeft);
            gfx.DrawString(bill.Date.ToShortDateString(), regularFont, XBrushes.Black,
                           new XRect(470, 120, 530, 120), XStringFormats.TopLeft);
            gfx.DrawString("Hebrew:", regularFont, XBrushes.Black,
                           new XRect(400, 135, 440, 135), XStringFormats.TopLeft);
            gfx.DrawString("13 Tishrei 5778", regularFont, XBrushes.Black,
                           new XRect(470, 135, 530, 135), XStringFormats.TopLeft);

            Styles(ref doc);
            //bill to
            DocumentRenderer docRenderer = new DocumentRenderer(doc);

            docRenderer.PrepareDocument();
            var billToPar = sec.AddParagraph();

            billToPar.AddText("Bill To:");
            billToPar.Format.Shading.Color = Colors.Black;
            billToPar.Format.Font.Color    = Colors.White;
            billToPar.Format.Font.Size     = 9;
            docRenderer.RenderObject(gfx, 40, 180, 30, billToPar);
            DrawLine(gfx, 70, 180, 350, 180, 1);

            // bill address
            var addresPar = sec.AddParagraph();

            addresPar.AddText($"{bill.Family} \n" +
                              $"{bill.CompanyName}\n" +
                              $"{bill.Address} \n" +
                              $"{bill.City}, {bill.State} {bill.Zip}\n" +
                              $"{bill.Country}");
            addresPar.Format.Font.Color = Colors.Black;
            addresPar.Format.Font.Size  = 9;
            docRenderer.RenderObject(gfx, 70, 190, 240, addresPar);

            _table       = sec.AddTable();
            _table.Style = "Table";

            _table.Borders.Color       = TableBorder;
            _table.Borders.Width       = 0.25;
            _table.Borders.Left.Width  = 0.5;
            _table.Borders.Right.Width = 0.5;
            _table.Borders.Top.Width   = 0;
            _table.Rows.LeftIndent     = 0;
            _table.Rows.HeightRule     = RowHeightRule.AtLeast;
            _table.Rows.Height         = 12;

            CreateColumns();
            FillRows(bill);
            docRenderer.PrepareDocument();
            docRenderer.RenderObject(gfx, 30, 282, 582, _table);

            //footer
            //text and line
            XTextFormatter tf = new XTextFormatter(gfx);

            tf.Alignment = XParagraphAlignment.Right;
            gfx.DrawString("Please include bottom portion of invoice with your payment", regularFont, XBrushes.Black,
                           new XRect(30, 600, 200, 20), XStringFormats.TopLeft);
            DrawLine(gfx, 30, 615, 582, 615, 1, true);

            gfx.DrawString("Total Debits:", regularFont, XBrushes.Black,
                           new XRect(400, 630, 50, 50), XStringFormats.TopLeft);
            tf.DrawString(bill.Amount.ToMoneyString(), regularFont, XBrushes.Black,
                          new XRect(460, 630, 50, 50), XStringFormats.TopLeft);

            gfx.DrawString("Total Paid:", regularFont, XBrushes.Black,
                           new XRect(410, 645, 50, 50), XStringFormats.TopLeft);
            tf.DrawString(GetPayd(bill).ToMoneyString(), regularFont, XBrushes.Black,
                          new XRect(460, 645, 50, 50), XStringFormats.TopLeft);

            gfx.DrawString("Amount Due:", regulerFontBold, XBrushes.Black,
                           new XRect(393, 665, 50, 50), XStringFormats.TopLeft);

            tf.Alignment = XParagraphAlignment.Right;
            tf.DrawString(bill.AmountDue != null ? ((decimal)bill.AmountDue).ToMoneyString() : 0M.ToMoneyString(), regulerFontBold, XBrushes.Black,
                          new XRect(460, 665, 50, 50), XStringFormats.TopLeft);
            //additional invoice number
            gfx.DrawString("Invoice No:", smallFont, XBrushes.Black,
                           new XRect(350, 710, 50, 50), XStringFormats.TopLeft);

            tf.Alignment = XParagraphAlignment.Left;
            tf.DrawString(bill.InvoiceNo?.ToString() ?? "", smallFont, XBrushes.Black,
                          new XRect(400, 710, 50, 50), XStringFormats.TopLeft);
            //additional recipient name
            gfx.DrawString(bill.Family, smallFont, XBrushes.Black,
                           new XRect(350, 720, 100, 50), XStringFormats.TopLeft);
        }
Exemplo n.º 48
0
   // [UnitTestFunction]
    public static void Test()
    {
      Document doc = new Document();
      Style styl = doc.AddStyle("TestStyle1", Style.DefaultParagraphFontName);
      styl.Font.Bold = true;
      Section sec = doc.AddSection();

      sec.PageSetup.PageHeight = "30cm";

      sec.Headers.FirstPage.Format.Font.Bold = true;
      sec.Headers.Primary.AddParagraph("This is the Primary Header.");
      sec.Headers.FirstPage.AddParagraph("This is the First Page Header.");
      sec.Headers.EvenPage.AddParagraph("This is the Even Page Header.");

      Paragraph par = sec.AddParagraph("Paragraph 1");
//      par.Style = "TestStyle1";
      par.Format.ListInfo.NumberPosition = 2;


      par = sec.AddParagraph("Paragraph 2");
      par.Format.ListInfo.ListType = ListType.BulletList3;
      Image img1 = par.AddImage("logo.gif");
//      Image img1 = par.AddImage("tick_green.png");
      img1.ScaleHeight = 5;
      img1.ScaleWidth = 2;
      img1.Height = "0.3cm";
      img1.Width = "5cm";
      img1.PictureFormat.CropLeft = "-2cm";
      img1.FillFormat.Color = Color.PowderBlue;
      img1.LineFormat.Width = 2;


      par = sec.AddParagraph("Paragraph 3");
      par.AddLineBreak();
      par.Format.ListInfo.NumberPosition = 2;

      TextFrame tf = sec.AddTextFrame();
      tf.WrapFormat.Style = WrapStyle.None;
      tf.RelativeHorizontal = RelativeHorizontal.Page;
      tf.RelativeVertical = RelativeVertical.Page;

      tf.Top = Unit.FromCm(2);
      tf.Left = ShapePosition.Center;
      tf.Height = "20cm";
      tf.Width = "10cm";
      tf.FillFormat.Color = Color.LemonChiffon;
      tf.LineFormat.Color = Color.BlueViolet;
      tf.LineFormat.DashStyle = DashStyle.DashDotDot;
      tf.LineFormat.Width = 2;
      tf.AddParagraph("in a text frame");
      tf.MarginTop = "3cm";
      tf.Orientation = TextOrientation.Downward;

      Image img = sec.AddImage("test1.jpg");
      img.ScaleHeight = 500;
      img.ScaleWidth = 200;
      img.Height = "10cm";
      img.Width = "10cm";
      img.PictureFormat.CropLeft = "-2cm";
      img.FillFormat.Color = Color.LawnGreen;
      img.LineFormat.Width = 3;
      img.WrapFormat.Style = WrapStyle.None;

      sec = doc.AddSection();//.AddParagraph("test");
      sec.PageSetup.PageWidth = "30cm";
      sec.AddParagraph("Section 2");

      DocumentRenderer docRenderer = new DocumentRenderer();
      docRenderer.Render(doc, "RtfListInfo.txt", null);
      DdlWriter.WriteToFile(doc, "RtfListInfo.mdddl");
      System.IO.File.Copy("RtfListInfo.txt", "RtfListInfo.rtf", true);
      System.Diagnostics.Process.Start("RtfListInfo.txt");
    }
        public void TestDocumentRenderingWithEachReplacement()
        {
            var rendered = new DocumentRenderer().Render("{{each number in Numbers}}{{number!}}!{{each}}", new { Numbers = new int[] { 1, 2, 3, 4 } });

            Assert.AreEqual("1234", rendered.ToString());
        }
Exemplo n.º 50
0
        public byte[] Write()
        {
            var stream = new MemoryStream();


            using (var document = new PdfDocument())
            {
                XFont font = new XFont("Times", 11, XFontStyle.Bold);
                XPen  pen  = new XPen(XColor.FromKnownColor(XKnownColor.Black));

                PdfPage page = document.AddPage();
                page.Size        = PageSize.A4;
                page.Orientation = PageOrientation.Portrait;

                XGraphics      gfx = XGraphics.FromPdfPage(page);
                XTextFormatter tf  = new XTextFormatter(gfx);

                var template = new TemplateA(60);

                gfx.DrawRectangle(pen, XBrushes.White, template.Adress.Area);
                gfx.DrawRectangle(pen, XBrushes.White, template.Sender);
                gfx.DrawRectangle(pen, XBrushes.White, template.Text);
                gfx.DrawRectangle(pen, XBrushes.White, template.LetterHead);

                gfx.DrawRectangle(pen, XBrushes.White, template.FoldMarkTop);
                gfx.DrawRectangle(pen, XBrushes.White, template.HoleMark);
                gfx.DrawRectangle(pen, XBrushes.White, template.FoldMarkButtom);

                gfx.DrawRectangle(pen, XBrushes.White, template.Adress.ReturnInformation);
                gfx.DrawRectangle(pen, XBrushes.White, template.Adress.InfoZone);
                gfx.DrawRectangle(pen, XBrushes.White, template.Adress.AdressZone);

                tf.DrawString("Rücksende Angabe", font, XBrushes.Black, template.Adress.ReturnInformation);
                tf.DrawString("Vermerkzone", font, XBrushes.Black, template.Adress.InfoZone);
                tf.DrawString("Adresszone", font, XBrushes.Black, template.Adress.AdressZone);

                tf.DrawString("Text Inhalt", font, XBrushes.Black, template.Text);
                tf.DrawString("Briefkopf", font, XBrushes.Black, template.LetterHead);
                tf.DrawString("Absender", font, XBrushes.Black, template.Sender);

                //mix with migradoc
                Document doc = new Document();
                doc.DefaultPageSetup.LeftMargin = 0;
                doc.DefaultPageSetup.TopMargin  = 0;

                Section sec = doc.AddSection();

                var adress = sec.AddTextFrame( );
                adress.Top    = template.Adress.Area.Top;
                adress.Left   = template.Adress.Area.Left;
                adress.Width  = template.Adress.Area.Width;
                adress.Height = template.Adress.Area.Height;
                var p = adress.AddParagraph("Hallo Adresse \r\n some test Value");

                var table = sec.AddTable();
                table.Rows.LeftIndent = "3 cm";
                var c1 = table.AddColumn("10 cm");
                var c2 = table.AddColumn("10 cm");

                var header = table.AddRow();
                header.Cells[0].AddParagraph("Header 1");
                header.Cells[1].AddParagraph("Header 2");

                var row1 = table.AddRow();
                row1.Cells[0].AddParagraph("row 1");
                row1.Cells[1].AddParagraph("row 2");

                var row2 = table.AddRow();
                row2.Cells[0].AddParagraph("row 3");
                row2.Cells[1].AddParagraph("row 4");

                MigraDoc.Rendering.DocumentRenderer docRenderer = new DocumentRenderer(doc);
                docRenderer.PrepareDocument();
                //docRenderer.RenderObject(gfx, XUnit.FromCentimeter(5), XUnit.FromCentimeter(10), "12cm", doc);
                docRenderer.RenderPage(gfx, 1);

                document.Save(stream);
            }

            return(stream.ToArray());
        }
        public void TestDocumentRenderingVarExpression()
        {
            var rendered = new DocumentRenderer().Render("{{var first FirstName!}}Hi {{first!}}{{clearvar first!}}", new { FirstName = "Adam" });

            Assert.AreEqual("Hi Adam", rendered.ToString());
        }
Exemplo n.º 52
0
        /// <summary>
        /// Called when the Ddl property has changed.
        /// </summary>
        void DdlUpdated()
        {
            if (_ddl != null)
            {
                _document = DdlReader.DocumentFromString(_ddl);
                _renderer = new DocumentRenderer(_document);

                //this.renderer.PrivateFonts = this.privateFonts;
                _renderer.PrepareDocument();

                //IDocumentPaginatorSource source = this.documentViewer.Document;

                //IDocumentPaginatorSource source = this.documentViewer.Document;

                int pageCount = _renderer.FormattedDocument.PageCount;
                if (pageCount == 0)
                {
                    return;
                }

                // HACK: hardcoded A4 size
                //double pageWidth = XUnit.FromMillimeter(210).Presentation;
                //double pageHeight = XUnit.FromMillimeter(297).Presentation;
                //Size a4 = new Size(pageWidth, pageHeight);

                XUnit pageWidth, pageHeight;
                Size  size96 = GetSizeOfPage(1, out pageWidth, out pageHeight);

                FixedDocument fixedDocument = new FixedDocument();
                fixedDocument.DocumentPaginator.PageSize = size96;

                for (int pageNumber = 1; pageNumber <= pageCount; pageNumber++)
                {
                    try
                    {
                        size96 = GetSizeOfPage(1, out pageWidth, out pageHeight);

                        DrawingVisual  dv = new DrawingVisual();
                        DrawingContext dc = dv.RenderOpen();
                        //XGraphics gfx = XGraphics.FromDrawingContext(dc, new XSize(XUnit.FromMillimeter(210).Point, XUnit.FromMillimeter(297).Point), XGraphicsUnit.Point);
                        XGraphics gfx = XGraphics.FromDrawingContext(dc, new XSize(pageWidth.Point, pageHeight.Presentation), XGraphicsUnit.Point);
                        _renderer.RenderPage(gfx, pageNumber, PageRenderOptions.All);
                        dc.Close();

                        // Create page content
                        PageContent pageContent = new PageContent();
                        pageContent.Width  = size96.Width;
                        pageContent.Height = size96.Height;
                        FixedPage fixedPage = new FixedPage();
                        fixedPage.Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0xFE, 0xFE, 0xFE));

                        UIElement visual = new DrawingVisualPresenter(dv);
                        FixedPage.SetLeft(visual, 0);
                        FixedPage.SetTop(visual, 0);

                        fixedPage.Width  = size96.Width;
                        fixedPage.Height = size96.Height;

                        fixedPage.Children.Add(visual);

                        fixedPage.Measure(size96);
                        fixedPage.Arrange(new Rect(new Point(), size96));
                        fixedPage.UpdateLayout();

                        ((IAddChild)pageContent).AddChild(fixedPage);

                        fixedDocument.Pages.Add(pageContent);
                    }
                    catch (Exception)
                    {
                        // eat exception
                    }

                    viewer.Document = fixedDocument;
                }
            }
            else
            {
                viewer.Document = null;
            }
        }
Exemplo n.º 53
0
 /// <summary>Finalizes page processing by drawing margins if necessary.</summary>
 /// <param name="pageNum">the page to process</param>
 /// <param name="pdfDocument">
 /// the
 /// <see cref="iText.Kernel.Pdf.PdfDocument"/>
 /// to which content is written
 /// </param>
 /// <param name="documentRenderer">the document renderer</param>
 internal virtual void ProcessPageEnd(int pageNum, PdfDocument pdfDocument, DocumentRenderer documentRenderer
                                      )
 {
     DrawMarginBoxes(pageNum, pdfDocument, documentRenderer);
 }
Exemplo n.º 54
0
 public virtual void BuildForSinglePage(int pageNumber, PdfDocument pdfDocument, DocumentRenderer documentRenderer
                                        , ProcessorContext context)
 {
     if (resolvedPageMarginBoxes.IsEmpty())
     {
         return;
     }
     nodes = new PageMarginBoxContextNode[16];
     foreach (PageMarginBoxContextNode marginBoxContentNode in resolvedPageMarginBoxes)
     {
         nodes[MapMarginBoxNameToIndex(marginBoxContentNode.GetMarginBoxName())] = marginBoxContentNode;
     }
     IElement[] elements = new IElement[16];
     for (int i = 0; i < 16; i++)
     {
         if (nodes[i] != null)
         {
             elements[i] = ProcessMarginBoxContent(nodes[i], pageNumber, context);
         }
     }
     GetPMBRenderers(elements, documentRenderer, pdfDocument);
 }
Exemplo n.º 55
0
 /// <summary>
 /// Changes the
 /// <see cref="iText.Layout.Renderer.DocumentRenderer"/>
 /// at runtime.
 /// </summary>
 /// <remarks>
 /// Changes the
 /// <see cref="iText.Layout.Renderer.DocumentRenderer"/>
 /// at runtime. Use this to customize
 /// the Document's
 /// <see cref="iText.Layout.Renderer.IRenderer"/>
 /// behavior.
 /// </remarks>
 /// <param name="documentRenderer">the DocumentRenderer to set</param>
 public virtual void SetRenderer(DocumentRenderer documentRenderer)
 {
     this.rootRenderer = documentRenderer;
 }
Exemplo n.º 56
0
        void GenerateReport(PdfDocument document)
        {
            //PdfPage page = document.AddPage();
            PdfPage page = document.Pages[0];

            XGraphics gfx = XGraphics.FromPdfPage(page);

            // HACK²
            gfx.MUH  = PdfFontEncoding.Unicode;
            gfx.MFEH = PdfFontEmbedding.Default;

            XFont font = new XFont("Verdana", 4, XFontStyle.Regular);

            // map image origin
            //gfx.DrawString("O", font, XBrushes.Red, new XRect(20, 42, 12, 12), XStringFormats.Center);

            //gfx.DrawString("O", font, XBrushes.Blue, new XRect(220,  42, 12, 12), XStringFormats.Center);

            //gfx.DrawString("O", font, XBrushes.Green, new XRect(20, 120, 12, 12), XStringFormats.Center);
            //XPen penn = new XPen(XColors.DarkSeaGreen, 1.5);
            //gfx.DrawRectangle(penn, 420, 42, 153, 63);


            // ovmap image origin
            //gfx.DrawString("X", font, XBrushes.Red, new XRect(5, 5, 798, 1144), XStringFormats.Center);



            //gfx.DrawString("+", font, XBrushes.Red, new XRect(5, 5, 100, 1299), XStringFormats.Center);


            XPen pen = new XPen(XColors.DarkTurquoise, 0.5);

            //gfx.DrawRectangle(pen, 20, 42, 150, 40);

            Document doc = new Document();

            // Create a renderer and prepare (=layout) the document
            MigraDoc.Rendering.DocumentRenderer docRenderer = new DocumentRenderer(doc);
            docRenderer.PrepareDocument();



            int numlabels = label_al.Count;
            int pagenum   = 1;

            double xp = 0;
            double yp = 0;

            double x_marg = 20.0;
            double y_marg = 42.0;

            double w_inc = 200;
            double h_inc = 78;

            double label_width = 150.0;

            double rows = 3;
            double cols = 10;

            //Debug.Print(String.Format("{0} labels", numlabels));

            for (int l = 0; l < numlabels; l++)
            {
                // get label
                MailingLabel ml = (MailingLabel)label_al[l];

                // get col and row

                int irow = 1;
                int icol = 1;

                if ((l + 1) <= ((int)rows * (int)cols))
                {
                    try
                    {
                        irow = (((int)l / 3));
                        icol = (l % 3);
                    }
                    catch (Exception ex)
                    {
                    }

                    //Debug.Print(String.Format("{0}  ->  {1}   {2}", l, irow, icol));
                }
                else if ((l + 1) > (((int)rows * (int)cols)))
                {
                    //if ((l + 1) == (((int)rows * (int)cols) + 1))

                    int recpp = ((int)rows * (int)cols);
                    int modpp = (l - 1) % (recpp);
                    //Debug.Print(String.Format("{0}   mod {1}", l, modpp));
                    if (modpp == 0)
                    {
                        // print second page
                        page = document.Pages.Add();
                        //page = document.Pages[1];
                        gfx = XGraphics.FromPdfPage(page);
                        // HACK²
                        gfx.MUH  = PdfFontEncoding.Unicode;
                        gfx.MFEH = PdfFontEmbedding.Default;
                        pagenum++;
                        Debug.Print(String.Format("   pagenum {0}", pagenum));
                    }

                    try
                    {
                        irow = (((l - ((pagenum - 1) * 30)) / 3)) - 1;
                        icol = ((l - ((pagenum - 1) * 30)) % 3);
                    }
                    catch (Exception ex)
                    {
                    }
                }

                double xloc = x_marg + (icol * w_inc);
                double yloc = y_marg + (irow * h_inc);

                //Debug.Print(String.Format("          {0}   {1}", xloc, yloc));

                //gfx.DrawRectangle(pen, xloc, yloc, 150, 60);


                Section sec = doc.AddSection();
                // Add a single paragraph with some text and format information.
                Paragraph para = sec.AddParagraph();
                para.Format.Alignment    = ParagraphAlignment.Justify;
                para.Format.KeepTogether = true;

                para.Format.Font.Name  = "Verdana";
                para.Format.Font.Size  = Unit.FromPoint(6);
                para.Format.Font.Color = MigraDoc.DocumentObjectModel.Colors.Black;
                para.Format.Font.Bold  = true;
                //para.AddText("Duisism odigna acipsum delesenisl ");
                //para.AddFormattedText("ullum in velenit", TextFormat.Bold);

                //para.AddText(ml.lname + "\r\n" + ml.laddr);

                String lbltext = "";
                lbltext += ml.lname;
                para.AddText(ml.lname);



                Paragraph para2 = sec.AddParagraph();
                if (ml.laddr_1 != "")
                {
                    lbltext += "\r\n" + ml.laddr_1;
                    //para.AddText(ml.laddr_1);
                    //para.AddLineBreak();


                    para2.Format.Alignment    = ParagraphAlignment.Justify;
                    para2.Format.KeepTogether = true;

                    para2.Format.Font.Name  = "Verdana";
                    para2.Format.Font.Size  = Unit.FromPoint(6);
                    para2.Format.Font.Color = MigraDoc.DocumentObjectModel.Colors.Black;
                    para2.Format.Font.Bold  = true;
                    para2.AddText(ml.laddr_1);
                }
                if (ml.laddr_2 != "")
                {
                    lbltext += "\r\n" + ml.laddr_2;
                }
                if (ml.laddr_3 != "")
                {
                    lbltext += "\r\n" + ml.laddr_3;
                }
                if (ml.lcity != "")
                {
                    lbltext += "\r\n" + ml.lcity + ", " + ml.lstate;
                }
                if (ml.lcntry != "")
                {
                    lbltext += "\r\n" + ml.lcntry;
                }
                if (ml.zip != "")
                {
                    lbltext += "\r\n" + ml.zip;
                }

                //para.AddText(ml.lcity + ", " + ml.lstate + " " + ml.zip);
                //para.AddLineBreak();

                //para.AddText(lbltext);

                Paragraph para3 = sec.AddParagraph();
                para3.Format.Alignment    = ParagraphAlignment.Justify;
                para3.Format.KeepTogether = true;

                para3.Format.Font.Name  = "Verdana";
                para3.Format.Font.Size  = Unit.FromPoint(6);
                para3.Format.Font.Color = MigraDoc.DocumentObjectModel.Colors.Black;
                para3.Format.Font.Bold  = true;
                para3.AddText(ml.lcity + ", " + ml.lstate + " " + ml.zip);


                //para.Format.Borders.Distance = "1pt";
                //para.Format.Borders.Color = Colors.Orange;

                // Create a renderer and prepare (=layout) the document
                //MigraDoc.Rendering.DocumentRenderer docRenderer = new DocumentRenderer(doc);
                docRenderer.PrepareDocument();

                // Render the paragraph. You can render tables or shapes the same way.  29, 705, 555, 43
                docRenderer.RenderObject(gfx, XUnit.FromPoint(xloc), XUnit.FromPoint(yloc + 15.0), XUnit.FromPoint((int)label_width), para);
                docRenderer.RenderObject(gfx, XUnit.FromPoint(xloc), XUnit.FromPoint(yloc + 23.0), XUnit.FromPoint((int)label_width), para2);
                docRenderer.RenderObject(gfx, XUnit.FromPoint(xloc), XUnit.FromPoint(yloc + 31.0), XUnit.FromPoint((int)label_width), para3);
            }



            // You always need a MigraDoc document for rendering.

            /*
             * Section sec = doc.AddSection();
             * // Add a single paragraph with some text and format information.
             * Paragraph para = sec.AddParagraph();
             * para.Format.Alignment = ParagraphAlignment.Justify;
             * para.Format.Font.Name = "Verdana";
             * para.Format.Font.Size = Unit.FromPoint(6);
             * para.Format.Font.Color = MigraDoc.DocumentObjectModel.Colors.DarkGray;
             * para.Format.Font.Color = MigraDoc.DocumentObjectModel.Colors.DarkGray;
             * //para.AddText("Duisism odigna acipsum delesenisl ");
             * //para.AddFormattedText("ullum in velenit", TextFormat.Bold);
             *
             * para.AddText("BillyBob\r\n123 Deep Elem Lane");
             *
             *
             * //para.Format.Borders.Distance = "1pt";
             * //para.Format.Borders.Color = Colors.Orange;
             *
             * // Create a renderer and prepare (=layout) the document
             * MigraDoc.Rendering.DocumentRenderer docRenderer = new DocumentRenderer(doc);
             * docRenderer.PrepareDocument();
             *
             * // Render the paragraph. You can render tables or shapes the same way.  29, 705, 555, 43
             * docRenderer.RenderObject(gfx, XUnit.FromPoint(38), XUnit.FromPoint(710), XUnit.FromPoint(535), para);
             *
             */


            /*
             * double xp = 0;
             * double yp = 0;
             * int numticks = 8;
             *
             * double w_inc = page.Width.Value / (double)numticks;
             * double h_inc = page.Height.Value / (double)numticks;
             *
             * for (int x = 0; x < numticks; x++)
             * {
             * for (int y = 0; y < numticks; y++)
             * {
             *
             *     xp = (double)x * w_inc;
             *     yp = (double)y * h_inc;
             *
             *     XUnit xu_x = new XUnit(xp, XGraphicsUnit.Point);
             *     XUnit xu_y = new XUnit(yp, XGraphicsUnit.Point);
             *
             *     xu_x.ConvertType(XGraphicsUnit.Inch);
             *     xu_y.ConvertType(XGraphicsUnit.Inch);
             *
             *     gfx.DrawString("+", font, XBrushes.Red, new XRect( xp,  yp, 5, 5), XStringFormats.Center);
             *     //String lbl = String.Format("{0}    \r\n{1}   {2}\r\n    {3}", (int)xp, (int)yp, xu_x.Value, xu_y.Value);
             *     String lbl = String.Format("{0}  {1}",xu_x.Value, xu_y.Value);
             *     gfx.DrawString(lbl, font, XBrushes.Red, new XRect( xp + 5,  yp + 5, 5, 5), XStringFormats.Center);
             *
             *
             * }
             *
             * }
             */
        }
Exemplo n.º 57
0
        // [UnitTestFunction]
        public static void Test()
        {
            Document doc  = new Document();
            Style    styl = doc.AddStyle("TestStyle1", Style.DefaultParagraphFontName);

            styl.Font.Bold = true;
            Section sec = doc.AddSection();

            sec.PageSetup.PageHeight = "30cm";

            sec.Headers.FirstPage.Format.Font.Bold = true;
            sec.Headers.Primary.AddParagraph("This is the Primary Header.");
            sec.Headers.FirstPage.AddParagraph("This is the First Page Header.");
            sec.Headers.EvenPage.AddParagraph("This is the Even Page Header.");

            Paragraph par = sec.AddParagraph("Paragraph 1");

//      par.Style = "TestStyle1";
            par.Format.ListInfo.NumberPosition = 2;


            par = sec.AddParagraph("Paragraph 2");
            par.Format.ListInfo.ListType = ListType.BulletList3;
            Image img1 = par.AddImage("logo.gif");

//      Image img1 = par.AddImage("tick_green.png");
            img1.ScaleHeight            = 5;
            img1.ScaleWidth             = 2;
            img1.Height                 = "0.3cm";
            img1.Width                  = "5cm";
            img1.PictureFormat.CropLeft = "-2cm";
            img1.FillFormat.Color       = Color.PowderBlue;
            img1.LineFormat.Width       = 2;


            par = sec.AddParagraph("Paragraph 3");
            par.AddLineBreak();
            par.Format.ListInfo.NumberPosition = 2;

            TextFrame tf = sec.AddTextFrame();

            tf.WrapFormat.Style   = WrapStyle.None;
            tf.RelativeHorizontal = RelativeHorizontal.Page;
            tf.RelativeVertical   = RelativeVertical.Page;

            tf.Top                  = Unit.FromCm(2);
            tf.Left                 = ShapePosition.Center;
            tf.Height               = "20cm";
            tf.Width                = "10cm";
            tf.FillFormat.Color     = Color.LemonChiffon;
            tf.LineFormat.Color     = Color.BlueViolet;
            tf.LineFormat.DashStyle = DashStyle.DashDotDot;
            tf.LineFormat.Width     = 2;
            tf.AddParagraph("in a text frame");
            tf.MarginTop   = "3cm";
            tf.Orientation = TextOrientation.Downward;

            Image img = sec.AddImage("test1.jpg");

            img.ScaleHeight            = 500;
            img.ScaleWidth             = 200;
            img.Height                 = "10cm";
            img.Width                  = "10cm";
            img.PictureFormat.CropLeft = "-2cm";
            img.FillFormat.Color       = Color.LawnGreen;
            img.LineFormat.Width       = 3;
            img.WrapFormat.Style       = WrapStyle.None;

            sec = doc.AddSection();//.AddParagraph("test");
            sec.PageSetup.PageWidth = "30cm";
            sec.AddParagraph("Section 2");

            DocumentRenderer docRenderer = new DocumentRenderer();

            docRenderer.Render(doc, "RtfListInfo.txt", null);
            DdlWriter.WriteToFile(doc, "RtfListInfo.mdddl");
            System.IO.File.Copy("RtfListInfo.txt", "RtfListInfo.rtf", true);
            System.Diagnostics.Process.Start("RtfListInfo.txt");
        }
Exemplo n.º 58
0
  //  [UnitTestFunction]
    public static void TestFields()
    {
      Document doc = new Document();
      doc.Info.Author = "K.P.";
      Section sec = doc.Sections.AddSection();
      Paragraph par = sec.AddParagraph();

      par.AddBookmark("myBookmark1");

      PageRefField prf = par.AddPageRefField("myBookmark1");
      prf.Format = "ALPHABETIC";
      
      PageField pf = par.AddPageField();
      pf.Format = "ROMAN";

      SectionField sf = par.AddSectionField();
      sf.Format = "roman";
      
      SectionPagesField spf = par.AddSectionPagesField();
      spf.Format = "roman";

      NumPagesField npf = par.AddNumPagesField();
      npf.Format = "alphabetic";

      InfoField inf = par.AddInfoField(InfoFieldType.Author);
      DateField df = par.AddDateField("D");

      df = par.AddDateField("d");
      df = par.AddDateField("s");
      df = par.AddDateField("r");
      df = par.AddDateField("G");
      df = par.AddDateField("dddd dd.MM.yyyy");

      DocumentRenderer docRndrr = new DocumentRenderer();
      docRndrr.Render(doc, "RtfFields.txt", null);

      File.Copy("RtfFields.txt", "RtfFields.rtf", true);
      System.Diagnostics.Process.Start("RtfFields.txt");
    }