Пример #1
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;
        }
Пример #2
0
        private static DocumentRenderer MakeRenderer(Document document)
        {
            DocumentRenderer renderer = new DocumentRenderer(document);

            renderer.PrepareDocument();
            return(renderer);
        }
Пример #3
0
        public PdfDocument CreateReport()
        {
            var pdfDocument = new PdfDocument();

            document = new Document();
            DefineStyles(document);

            CreateTitlePage();

            CreateTableOfContents();

            CreateIntroduction();

            CreateDataTable();


            var renderer = new DocumentRenderer(document);

            renderer.PrepareDocument();

            for (int i = 0; i < renderer.FormattedDocument.PageCount; i++)
            {
                //każda sekcja to jest strona
                var gfx = XGraphics.FromPdfPage(pdfDocument.AddPage());
                renderer.RenderPage(gfx, i + 1);
            }


            return(pdfDocument);
        }
Пример #4
0
        /// <summary>
        /// Funkcja renderująca tabelę
        /// </summary>
        /// <param name="page">Obiekt strony</param>
        /// <param name="gfx">Kontekst graficzny strony</param>
        /// <param name="coords">Koordynaty ustalone przez wyższy poziom</param>
        public void Render(PdfPage page, XGraphics gfx, XPoint?coords)
        {
            //jeśli podano koordynaty w konstruktorze
            if (X > 0 && Y > 0)
            {
                _coords = new XPoint(X, Y);
            }
            else if (X > 0 && Y <= 0)
            {
                _coords = new XPoint(X, coords.Value.Y);
                Y       = coords.Value.Y;
            }
            else
            {
                _coords = (XPoint)coords; //lub jeśli nie podano
                X       = _coords.X; Y = _coords.Y;
            }

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

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

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

            MigraDoc.Rendering.DocumentRenderer docRenderer = new DocumentRenderer(doc);
            docRenderer.PrepareDocument();
            docRenderer.RenderObject(gfx, _coords.X, _coords.Y, width, table);
        }
Пример #5
0
        private void RenderPdfDocument(PdfDocument pdfDocument, bool preRender, PageSizeInfo pageSizeInfo, bool includeBackgroundObjects, bool portrait)
        {
            if (_preRendered && preRender)
            {
                throw new InvalidOperationException("Prerender has already been performed.");
            }

            var doc = GetDocument(preRender, portrait);

            var docRenderer = new DocumentRenderer(doc);

            docRenderer.PrepareDocument();

            for (var ii = 0; ii < doc.Sections.Count; ii++)
            {
                var page = AddPage(pdfDocument, pageSizeInfo, portrait);

                var gfx = _graphicsFactory.PrepareGraphics(page, docRenderer, ii);

                DoRenderStuff(gfx, new XRect(0, 0, page.Width, page.Height), preRender, ii, _template.SectionList.Sum(x => x.GetRenderPageCount()), includeBackgroundObjects, new XRect(0, 0, 0, 0));
            }

            if (preRender)
            {
                _preRendered = true;
            }
        }
Пример #6
0
        public void Print(PrinterSettings printerSettings, bool includeBackgroundObjects = true)
        {
            _printPageCount           = 0;
            _includeBackgroundObjects = includeBackgroundObjects;

            var pageSizeInfo = GetPageSizeInfo(printerSettings);

            var portrait = true;

            if (_printerInteractionMode == PrinterInteractionMode.Active)
            {
                portrait = !printerSettings.DefaultPageSettings.Landscape;
            }

            PreRender(pageSizeInfo, includeBackgroundObjects, portrait);

            var doc = GetDocument(false, portrait);

            var docRenderer = new DocumentRenderer(doc);

            docRenderer.PrepareDocument();

            var printDocument = new MigraDocPrintDocument();

            printDocument.PrintController = new StandardPrintController();

            printDocument.PrintPage      += PrintDocument_PrintPage;
            printDocument.Renderer        = docRenderer;
            printDocument.PrinterSettings = printerSettings;
            printDocument.Print();
        }
        PdfDocument PrepareDocumentForBatch(PdfDocument document, PdfSettingsBatchDto set, string countryInSettings)
        {
            var      settings = set.Settings;
            Document doc      = new Document();
            PdfPage  page     = document.Pages[0];

            Section sec = doc.AddSection();


            sec.PageSetup.LeftMargin   = Unit.FromInch(settings.LeftMargin);
            sec.PageSetup.RightMargin  = Unit.FromInch(settings.RightMargin);
            sec.PageSetup.TopMargin    = Unit.FromInch(settings.TopMargin);
            sec.PageSetup.BottomMargin = Unit.FromInch(settings.BottomMargin);

            //date
            if (settings.ShowDate)
            {
                AddDate(sec, settings);
            }

            //address
            if (settings.ShowAddress)
            {
                AddAddress(sec, settings, set.CountryInSettings);
            }

            // body
            AddBody(sec, settings);

            //signature
            if (settings.ShowSingnature)
            {
                AddSignature(sec, settings);
            }

            //fields
            if (settings.HasReceiptStub)
            {
                FillFields(document, set.Fields, settings, countryInSettings);
            }
            DocumentRenderer docRenderer = new DocumentRenderer(doc);

            docRenderer.PrepareDocument();
            int pages = docRenderer.FormattedDocument.PageCount;

            for (int j = 1; j <= pages; ++j)
            {
                using (XGraphics gfx = XGraphics.FromPdfPage(page))
                {
                    // HACK²
                    gfx.MUH = PdfFontEncoding.Unicode;


                    docRenderer.RenderPage(gfx, j);
                }
            }
            return(document);
        }
Пример #8
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();
        }
Пример #9
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();
        }
        PdfDocument PrepareDocument(PdfDocument document, PdfSettingDto settings, string countryInSettings, LetterFieldsDto fields, int pageNum = 0, bool isBase64 = false)
        {
            PdfPage   page = document.Pages[pageNum];
            XGraphics gfx  = XGraphics.FromPdfPage(page);

            // HACK²
            gfx.MUH = PdfFontEncoding.Unicode;
            Document         doc         = new Document();
            Section          sec         = doc.AddSection();
            DocumentRenderer docRenderer = new DocumentRenderer(doc);

            sec.PageSetup.LeftMargin   = Unit.FromInch(settings.LeftMargin);
            sec.PageSetup.RightMargin  = Unit.FromInch(settings.RightMargin);
            sec.PageSetup.TopMargin    = Unit.FromInch(settings.TopMargin);
            sec.PageSetup.BottomMargin = Unit.FromInch(settings.BottomMargin);

            //date
            if (settings.ShowDate)
            {
                AddDate(sec, settings);
            }

            //address
            if (settings.ShowAddress)
            {
                AddAddress(sec, settings, countryInSettings);
            }

            // body
            AddBody(sec, settings);

            //signature
            if (settings.ShowSingnature)
            {
                AddSignature(sec, settings, isBase64);
            }

            //fields
            if (settings.HasReceiptStub)
            {
                FillFields(document, fields, settings, countryInSettings);
            }
            docRenderer.PrepareDocument();
            int pageCount = docRenderer.FormattedDocument.PageCount;

            for (int idx = 0; idx < pageCount; idx++)
            {
                docRenderer.RenderPage(gfx, idx + 1, PageRenderOptions.All);
            }

            gfx.Dispose();
            return(document);
        }
Пример #11
0
        public byte[] GetEmployeeLoggedTime(UserLoggedTimeListViewModel request, DateTime startDate, DateTime dueDate)
        {
            var pdf  = new PdfDocument();
            var page = pdf.AddPage();

            page.Orientation = PageOrientation.Landscape;
            page.Size        = PageSize.A4;

            var pages = new List <PdfPage> {
                page
            };

            //Create pdf content
            var doc = CreateDocument(nameof(this.GetProjectGeneralReport),
                                     string.Format("{1}, {0}", "Default", "Default"));

            var commonParameter = new CommonPdfParameter
            {
                Document       = doc,
                Pdf            = pdf,
                PdfPages       = pages,
                StartDate      = startDate,
                DueDate        = dueDate,
                PdfTableHelper = new PdfTableHelperA4()
            };

            PopulateForGetEmployeeLoggedTime(commonParameter, request);

            //Create renderer for content
            var renderer = new DocumentRenderer(doc);

            renderer.PrepareDocument();

            var pageSize = GetPageSizeInXRectUnits(page.Size);

            var pageNumber = 0;

            foreach (var item in pages)
            {
                var gfx       = XGraphics.FromPdfPage(item);
                var container = gfx.BeginContainer(pageSize, pageSize, XGraphicsUnit.Point);
                gfx.DrawRectangle(XPens.LightGray, pageSize);
                renderer.RenderPage(gfx, ++pageNumber);
                gfx.EndContainer(container);
            }

            using (MemoryStream ms = new MemoryStream())
            {
                pdf.Save(ms, true);
                return(ms.ToArray());
            }
        }
Пример #12
0
        private void BT_Imprimir_Click(object sender, EventArgs e)
        {
            MigraDoc.Rendering.Printing.MigraDocPrintDocument pd = new MigraDoc.Rendering.Printing.MigraDocPrintDocument();
            var rendered = new DocumentRenderer(reporte());

            rendered.PrepareDocument();
            pd.Renderer = rendered;
            if (printDialog1.ShowDialog() == DialogResult.OK)
            {
                pd.PrinterSettings = printDialog1.PrinterSettings;
                pd.Print();
            }
        }
Пример #13
0
        static void CreatePngFromPdf(Document document, PdfDocumentRenderer renderer)
        {
            int page = 1;

            // Reuse the renderer from the preview
            DocumentRenderer renderer2 = new DocumentRenderer(document);

            renderer2.PrepareDocument();

            PageInfo info = renderer.DocumentRenderer.FormattedDocument.GetPageInfo(page);

            // Create an image
            int dpi = 150;
            int dx, dy;

            if (info.Orientation == PdfSharp.PageOrientation.Portrait)
            {
                dx = (int)(info.Width.Inch * dpi);
                dy = (int)(info.Height.Inch * dpi);
            }
            else
            {
                dx = (int)(info.Height.Inch * dpi);
                dy = (int)(info.Width.Inch * dpi);
            }

            //Create image object from the PDF
            //UGLY HACK: divide width by 3 to create only 1 label
            Image image = new Bitmap(dx / 3, dy, PixelFormat.Format32bppRgb);

            // Create a Graphics object for the image and scale it for drawing with 72 dpi
            Graphics graphics = Graphics.FromImage(image);

            graphics.Clear(System.Drawing.Color.White);
            float scale = dpi / 72f;

            graphics.ScaleTransform(scale, scale);

            // Create an XGraphics object and render the page
            XGraphics gfx = XGraphics.FromGraphics(graphics, new XSize(info.Width.Point, info.Height.Point));

            renderer2.RenderPage(gfx, page);
            gfx.Dispose();
            image.Save("test.png", ImageFormat.Png);
        }
Пример #14
0
        static void SamplePage1(PdfDocument document)
        {
            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("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.
            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.Justify;
            para.Format.Font.Name  = "Times New Roman";
            para.Format.Font.Size  = 12;
            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(" 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;

            // 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);
        }
Пример #15
0
        static void TableOfContents(PdfDocument document)
        {
            // Puts the Table of contents on the second page
            PdfPage   page = document.Pages[1];
            XGraphics gfx  = XGraphics.FromPdfPage(page);

            gfx.MUH = PdfFontEncoding.Unicode;

            // Create MigraDoc document + Setup styles
            Document doc = new Document();

            Styles.DefineStyles(doc);

            // Add header
            Section   section   = doc.AddSection();
            Paragraph paragraph = section.AddParagraph("Table of Contents");

            paragraph.Format.Font.Size    = 14;
            paragraph.Format.Font.Bold    = true;
            paragraph.Format.SpaceAfter   = 24;
            paragraph.Format.OutlineLevel = OutlineLevel.Level1;


            // Add links - these are the PdfSharp outlines/bookmarks added previously when concatinating the pages
            foreach (var bookmark in document.Outlines)
            {
                paragraph       = section.AddParagraph();
                paragraph.Style = "TOC";
                //paragraph.AddBookmark(bookmark.Title);
                Hyperlink hyperlink = paragraph.AddHyperlink(bookmark.Title);
                hyperlink.AddText($"{bookmark.Title}\t");
                //hyperlink.AddPageRefField(bookmark.Title);
            }

            // Render document
            DocumentRenderer docRenderer = new DocumentRenderer(doc);

            docRenderer.PrepareDocument();
            docRenderer.RenderPage(gfx, 1);

            gfx.Dispose();
        }
Пример #16
0
        /// <summary>
        /// Renders a whole MigraDoc document scaled to a single PDF page.
        /// </summary>
        static void SamplePage2(PdfDocument document)
        {
            PdfPage   page = document.AddPage();
            XGraphics gfx  = XGraphics.FromPdfPage(page);

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

            // Create document from HalloMigraDoc sample
            Document doc = HelloMigraDoc.Documents.CreateDocument();

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

            // For clarity we use point as unit of measure in this sample.
            // A4 is the standard letter size in Germany (21cm x 29.7cm).
            XRect A4Rect = new XRect(0, 0, A4Width, A4Height);

            int pageCount = docRenderer.FormattedDocument.PageCount;

            for (int idx = 0; idx < pageCount; idx++)
            {
                XRect rect = GetRect(idx);

                // 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, idx + 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);
            }
        }
        private void ConvertMigraDocToPdfSharp(ref PdfDocument document, Document migraDocument)
        {
            var pdfRenderer = new DocumentRenderer(migraDocument);

            pdfRenderer.PrepareDocument();

            int pages     = pdfRenderer.FormattedDocument.PageCount;
            var firstPage = (PdfPage)document.Pages[0].Clone();

            for (int i = 1; i <= pages; ++i)
            {
                PdfPage page = i == 1 ? document.Pages[0] : document.AddPage((PdfPage)firstPage.Clone());

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

                    pdfRenderer.RenderPage(gfx, i, PageRenderOptions.All);
                }
            }
        }
Пример #18
0
        /// <summary>
        /// Add pages of MigraDoc document to PdfSharp document.
        /// </summary>
        /// <param name="document">MigraDoc document.</param>
        /// <param name="pdfSharpDocument">PdfSharp document.</param>
        public static void MergeInto(
            this Document document,
            PdfDocument pdfSharpDocument)
        {
            DocumentRenderer docRenderer = new DocumentRenderer(document);

            docRenderer.PrepareDocument();

            for (int i = 0; i < docRenderer.FormattedDocument.PageCount; i++)
            {
                // Add new page to pdf sharp document.
                PdfPage page = pdfSharpDocument.AddPage();
                page.Size = PdfSharp.PageSize.A4;

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

                // Render MigraDoc page to PdfSharp page.
                // Remember that page number start with 1.
                docRenderer.RenderPage(gfx, i + 1);
            }
        }
Пример #19
0
        public static PdfDocument CreateDocument(Ventana ventana)
        {
            PdfDocument document = new PdfDocument();

            document.Info.Title = ventana.PO + "_" + ventana.Proveedor.NombreCorto + "_" + ventana.NombreCarrier + "_" + ventana.Evento.FechaInicio.ToString("yyyy-MM-dd");

            Document doc     = new Document();
            Section  section = doc.AddSection();

            CreateHeader(doc);
            CreatePage(doc, ventana);

            var pdfRenderer = new DocumentRenderer(doc);

            pdfRenderer.PrepareDocument();

            int pages = pdfRenderer.FormattedDocument.PageCount;

            for (int i = 1; i <= pages; ++i)
            {
                var page = document.AddPage();

                PageInfo pageInfo = pdfRenderer.FormattedDocument.GetPageInfo(i);
                page.Width       = pageInfo.Width;
                page.Height      = pageInfo.Height;
                page.Orientation = pageInfo.Orientation;

                using (XGraphics gfx = XGraphics.FromPdfPage(page))
                {
                    gfx.MUH  = PdfFontEncoding.Unicode;
                    gfx.MFEH = PdfFontEmbedding.Default;
                    pdfRenderer.RenderPage(gfx, i);
                }
            }

            return(document);
        }
Пример #20
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
        }
Пример #21
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;
        }
Пример #22
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*/);
        }
Пример #23
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);
        }
Пример #24
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);
        }
Пример #25
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);
        }
Пример #26
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);
        }
        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);
        }
Пример #28
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);
             *
             *
             * }
             *
             * }
             */
        }
        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);
        }
Пример #30
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;
        }
Пример #31
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;
            }
        }
Пример #32
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());
        }
Пример #33
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);
            }
        }