コード例 #1
0
        private void tsb_Print_Click(object sender, EventArgs e)
        {
            PrintDialog pdlg = new PrintDialog();

            pdlg.Document = pd;
            DialogResult dlgRes = pdlg.ShowDialog();

            if (dlgRes == DialogResult.OK)
            {
                config.PageSize = PageSize.A4;
                config.SetMargins(20);
                XSize orgPageSize = PageSizeConverter.ToSize(config.PageSize);
                orgPageSize = new Size(Convert.ToInt32(orgPageSize.Width), Convert.ToInt32(orgPageSize.Height));
                pageSize    = new Size(Convert.ToInt32(orgPageSize.Width - config.MarginLeft - config.MarginRight), Convert.ToInt32(orgPageSize.Height - config.MarginTop - config.MarginBottom));
                hc.SetHtml(_mainControl._htmlPanel.Text);
                hc.Location = new PointF(config.MarginLeft, config.MarginTop);
                hc.MaxSize  = new Size(Convert.ToInt32(pageSize.Width), 0);
                hc.SetHtml(_mainControl._htmlPanel.Text);

                scrollOffset = 0;

                hc.UseGdiPlusTextRendering = true;

                //SizeF szf = new SizeF(pd.DefaultPageSettings.PaperSize.Width, pd.DefaultPageSettings.PaperSize.Height);
                //hc.MaxSize = szf;
                iPage = 0;
                bFirstPagePrinting = true;
                pd.Print();
            }
        }
コード例 #2
0
        public void PrintLegend(System.Drawing.Graphics g, Leyenda legend)
        {
            g.PageUnit = System.Drawing.GraphicsUnit.Point;
            XGraphics gfx = XGraphics.FromGraphics(g, XSize.FromSize(PageSizeConverter.ToSize(PageSize.A4)));

            this.CreateLegend(gfx, legend);
            gfx.Dispose();
        }
コード例 #3
0
        public void Print(System.Drawing.Graphics g)
        {
            g.PageUnit = System.Drawing.GraphicsUnit.Point;
            XGraphics gfx = XGraphics.FromGraphics(g, XSize.FromSize(PageSizeConverter.ToSize(_layout.Size)));

            this.Render(gfx);
            gfx.Dispose();
        }
コード例 #4
0
        /// <summary>
        /// Create PDF document from given HTML.<br/>
        /// </summary>
        /// <param name="html">HTML source to create PDF from</param>
        /// <param name="config">the configuration to use for the PDF generation (page size/page orientation/margins/etc.)</param>
        /// <param name="cssData">optional: the style to use for html rendering (default - use W3 default style)</param>
        /// <param name="stylesheetLoad">optional: can be used to overwrite stylesheet resolution logic</param>
        /// <param name="imageLoad">optional: can be used to overwrite image resolution logic</param>
        /// <returns>the generated image of the html</returns>
        public static PdfDocument GeneratePdf(string html, PdfGenerateConfig config, CssData cssData = null, EventHandler <HtmlStylesheetLoadEventArgs> stylesheetLoad = null, EventHandler <HtmlImageLoadEventArgs> imageLoad = null)
        {
            // create PDF document to render the HTML into
            var document = new PdfDocument();

            // get the size of each page to layout the HTML in
            var orgPageSize = PageSizeConverter.ToSize(config.PageSize);
            var pageSize    = new XSize(orgPageSize.Width - config.MarginLeft - config.MarginRight, orgPageSize.Height - config.MarginTop - config.MarginBottom);

            if (!string.IsNullOrEmpty(html))
            {
                using (var container = new HtmlContainer())
                {
                    if (stylesheetLoad != null)
                    {
                        container.StylesheetLoad += stylesheetLoad;
                    }
                    if (imageLoad != null)
                    {
                        container.ImageLoad += imageLoad;
                    }

                    container.Location = new XPoint(config.MarginLeft, config.MarginTop);
                    container.MaxSize  = new XSize(pageSize.Width, 0);
                    container.SetHtml(html, cssData);

                    // layout the HTML with the page width restriction to know how many pages are required
                    using (var measure = XGraphics.CreateMeasureContext(pageSize, XGraphicsUnit.Point, XPageDirection.Downwards))
                    {
                        container.PerformLayout(measure);
                    }

                    // while there is un-rendered HTML, create another PDF page and render with proper offset for the next page
                    double scrollOffset = 0;
                    while (scrollOffset > -container.ActualSize.Height)
                    {
                        var page = document.AddPage();
                        page.Size = config.PageSize;
                        using (var g = XGraphics.FromPdfPage(page))
                        {
                            g.IntersectClip(new XRect(config.MarginLeft, config.MarginTop, pageSize.Width, pageSize.Height));

                            container.ScrollOffset = new XPoint(0, scrollOffset);
                            container.PerformPaint(g);
                        }
                        scrollOffset -= pageSize.Height;
                    }

                    // add web links and anchors
                    HandleLinks(document, container, orgPageSize, pageSize);
                }
            }

            return(document);
        }
コード例 #5
0
        public static void SavePDF(List <CardHolder> toprint, string filename)
        {
            const double mult          = 0.8;
            const int    PDFCardWidth  = (int)(223 * mult);
            const int    PDFCardHeight = (int)(310 * mult);
            const int    marginTop     = 60;
            const int    marginBottom  = 10;
            const int    marginLeft    = 60;
            const int    marginRight   = 10;

            var       doc = new PdfDocument();
            PdfPage   page;
            XGraphics xgr = null;

            var colnum  = -1;
            var rownum  = 0;
            var pagenum = -1;

            foreach (var ch in toprint)
            {
                for (int c = 0; c < ch.Count; c++)
                {
                    colnum++;
                    if (colnum == 3)
                    {
                        colnum = 0;
                        rownum++;
                    }

                    if (rownum == 3 || pagenum == -1)
                    {
                        rownum = 0;
                        pagenum++;
                        page = doc.AddPage();
                        var size = PageSizeConverter.ToSize(PdfSharp.PageSize.A4);
                        page.Width              = size.Width;
                        page.Height             = size.Height;
                        page.Orientation        = PageOrientation.Portrait;
                        page.TrimMargins.Top    = marginTop;
                        page.TrimMargins.Right  = marginRight;
                        page.TrimMargins.Bottom = marginBottom;
                        page.TrimMargins.Left   = marginLeft;
                        xgr = XGraphics.FromPdfPage(doc.Pages[pagenum]);
                    }

                    var r = new Rectangle(colnum * PDFCardWidth, rownum * PDFCardHeight, PDFCardWidth, PDFCardHeight);
                    xgr.DrawImage(ch.CardImage, r);
                }
            }

            doc.Save(filename);
            doc.Close();
        }
コード例 #6
0
        public Task CreatePDFWithPdfSharpAsync(Bitmap pBitmap, string pTitle, Image pLogo, Stream pStream)
        {
            return(Task.Run(() =>
            {
                XSize size = PageSizeConverter.ToSize(PdfSharp.PageSize.A4);

                var vPdf = new PdfDocument();
                var vPage = vPdf.AddPage();

                vPage.Width = XUnit.FromMillimeter(Setup.PaperSize.Width * 1000) - XUnit.FromMillimeter(Setup.Margins.Left * 0.254) - XUnit.FromMillimeter(Setup.Margins.Right * 0.254);
                vPage.Height = XUnit.FromMillimeter(Setup.PaperSize.Height * 1000) - XUnit.FromMillimeter(Setup.Margins.Top * 0.254) - XUnit.FromMillimeter(Setup.Margins.Bottom * 0.254);

                vPage.TrimMargins.Left = XUnit.FromMillimeter(Setup.Margins.Left * 0.254);
                vPage.TrimMargins.Right = XUnit.FromMillimeter(Setup.Margins.Right * 0.254);
                vPage.TrimMargins.Top = XUnit.FromMillimeter(Setup.Margins.Top * 0.254);
                vPage.TrimMargins.Bottom = XUnit.FromMillimeter(Setup.Margins.Bottom * 0.254);

                var vGraphics = XGraphics.FromPdfPage(vPage);

                var vState = vGraphics.Save();
                var vImage = XImage.FromGdiPlusImage(pBitmap);
                vGraphics.DrawImage(vImage, 0, 0, vPage.Width, vPage.Height);
                vGraphics.Restore(vState);

                if (!string.IsNullOrEmpty(pTitle))
                {
                    vState = vGraphics.Save();
                    var vFont = new XFont(this.Font.Name, this.Font.Size);
                    var vFontSize = vGraphics.MeasureString(pTitle, vFont);
                    vFontSize = new XSize(vFontSize.Width + 10, vFontSize.Height + 2);
                    var vRectangle = new RectangleF(new PointF((float)vPage.Width / 2f - (float)vFontSize.Width / 2f, 24 - (float)vFontSize.Height), vFontSize.ToSizeF());
                    var vFontRectangle = new XRect(vRectangle);

                    vGraphics.DrawRectangle(new PdfSharp.Drawing.XSolidBrush(XColors.LightGray), vRectangle);
                    vGraphics.DrawString(pTitle, vFont, XBrushes.Black, vRectangle, XStringFormats.Center);
                    vGraphics.DrawRectangle(XPens.Black, vFontRectangle);
                    vGraphics.Restore(vState);
                }

                if (pLogo != null)
                {
                    var vLogoImage = XImage.FromGdiPlusImage(pLogo);
                    var vImageSize = new XSize(vLogoImage.PointWidth / 2.0, vLogoImage.PointHeight / 2);
                    var vLogoRect = new XRect(vPage.Width - vImageSize.Width - 20, vPage.Height - vImageSize.Height - 15, vImageSize.Width, vImageSize.Height);
                    vGraphics.DrawImage(vLogoImage, vLogoRect);
                    vGraphics.DrawRectangle(XPens.Black, vLogoRect);
                }

                vPdf.Save(pStream);
            }));
        }
コード例 #7
0
ファイル: PdfPrinter.cs プロジェクト: jsuen123/openpetragit
        /// <summary>
        /// print the page, either to PDF or to the screen
        /// </summary>
        /// <param name="ASender"></param>
        /// <param name="AEv"></param>
        protected override void PrintPage(Object ASender, PrintPageEventArgs AEv)
        {
            // only use the AEv.Graphics if we display on screen
            if (FEv != AEv)
            {
                FEv = AEv;
                FEv.Graphics.PageUnit = GraphicsUnit.Inch;
                FEv.Graphics.TranslateTransform(0, 0);
                FXGraphics = XGraphics.FromGraphics(AEv.Graphics, PageSizeConverter.ToSize(PageSize.A4));
                InitFontsAndPens();
            }

            base.PrintPage(ASender, AEv);
        }
コード例 #8
0
        /// <summary>
        /// Draws the page on the printer.
        /// </summary>
        private void PrintPage(object sender, PrintPageEventArgs ev)
        {
            Graphics graphics = ev.Graphics;

            graphics.PageUnit = GraphicsUnit.Point;
            XGraphics gfx = XGraphics.FromGraphics(graphics, PageSizeConverter.ToSize(PageSize.A4));

            if (this.renderEvent != null)
            {
                this.renderEvent(gfx);
            }

            ev.HasMorePages = false;
        }
コード例 #9
0
        private void MakePdfDocumentForLabels(PdfDocument pdfDoc, LabelFormat labelFormat, Dictionary <int, EnvelopeAddress> labels)
        {
            int pageCount = FindPdfDocPagesCnt(labels.Count, labelFormat.LabelsPerPage);

            int   lastLabelIdxOnPage = 0;
            XFont xfont = GetLabelsXFont();

            for (int pageIdx = 0; pageIdx < pageCount; pageIdx++)
            {
                PdfPage pdfPage = CreateNewPage(pdfDoc, true, PageSizeConverter.ToSize(PdfSharp.PageSize.Letter));

                lastLabelIdxOnPage = FillPdfPageWithLabels(pdfPage, labelFormat, xfont, labels, lastLabelIdxOnPage);
            }
        }
コード例 #10
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            Alt.GUI.Temporary.Gwen.Control.MenuStrip menu = new Alt.GUI.Temporary.Gwen.Control.MenuStrip(this);

            Alt.GUI.Temporary.Gwen.Control.MenuItem root = menu.AddItem("Original Size");
            {
                root.Menu.AddItem("800%").SetAction(miZoom_Click);
                root.Menu.AddItem("600%").SetAction(miZoom_Click);
                root.Menu.AddItem("400%").SetAction(miZoom_Click);
                root.Menu.AddItem("200%").SetAction(miZoom_Click);
                root.Menu.AddItem("150%").SetAction(miZoom_Click);
                root.Menu.AddItem("100%").SetAction(miZoom_Click);
                root.Menu.AddItem("75%").SetAction(miZoom_Click);
                root.Menu.AddItem("50%").SetAction(miZoom_Click);
                root.Menu.AddItem("25%").SetAction(miZoom_Click);
                root.Menu.AddItem("10%").SetAction(miZoom_Click);
                root.Menu.AddDivider();
                root.Menu.AddItem("Best Fit").SetAction(miBestFit_Click);
                root.Menu.AddItem("Full Page").SetAction(miFullPage_Click);
            }

            menu.AddItem("Full Page" //, "AltData/Gwen/test16.png"
                         ).Clicked += miFullPage_Click;
            menu.AddItem("Best Fit"  //, "AltData/Gwen/test16.png"
                         ).Clicked += miBestFit_Click;
            menu.AddItem("Smaller"   //, "AltData/Gwen/test16.png"
                         ).Clicked += miSmaller_Click;
            menu.AddItem("Larger"    //, "AltData/Gwen/test16.png"
                         ).Clicked += miLarger_Click;
#if !SILVERLIGHT
            menu.AddItem("Create PDF"//, "AltData/Gwen/test16.png"
                         ).Clicked += miCreatePDF_Click;
#endif


            Alt.GUI.Temporary.Gwen.Control.StatusBar sb = new Alt.GUI.Temporary.Gwen.Control.StatusBar(this);
            m_StatisBarLabel = new Alt.GUI.Temporary.Gwen.Control.Label(sb);
            m_StatisBarLabel.AutoSizeToContents = true;
            m_StatisBarLabel.Text = "";
            sb.AddControl(m_StatisBarLabel, false);


            m_PagePreview.SetRenderEvent(new Alt.GUI.PdfSharp.Temporary.Gwen.PagePreview.RenderEvent(Render));


            m_PagePreview.PageSize = PageSizeConverter.ToSize(PageSize.A4);
            UpdateStatusBar();
        }
コード例 #11
0
ファイル: PreviewForm.cs プロジェクト: jgshumate1/Migradoc
        public PreviewForm()
        {
            InitializeComponent();

            UITools.MakeDialogSizable(this);
            this.Refresh();

            this.pagePreview.Size = PageSizeConverter.ToSize(PageSize.A3).ToSizeF().ToSize();

            UpdateStatusBar();
            Screen    screen = Screen.FromControl(this);
            Rectangle rect   = screen.Bounds;

            this.Bounds = new Rectangle(rect.Width / 2 - 2, 2, rect.Width / 2, rect.Height / 2);
            //this.FormBorderStyle = FormBorderStyle.Sizable;
        }
コード例 #12
0
        public double[] GetSizes()
        {
            var sizes = new double[2];
            var siz   = PageSizeConverter.ToSize(this.size);

            if (this.orientation == PageOrientation.Landscape)
            {
                sizes[0] = siz.Height;
                sizes[1] = siz.Width;
            }
            else
            {
                sizes[1] = siz.Height;
                sizes[0] = siz.Width;
            }

            return(sizes);
        }
コード例 #13
0
ファイル: Form1.cs プロジェクト: vanBassum/LabelTool
        private void TabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (tabControl1.SelectedIndex)
            {
            case 0:
                pagePreview1.PageSize        = PageSizeConverter.ToSize(pageSettings.PageSize);
                propertyGrid1.SelectedObject = null;
                RefreshTable();
                break;

            case 1:
                pagePreview1.PageSize = new XSize(XUnit.FromMillimeter(pageSettings.LabelSize.Width), XUnit.FromMillimeter(pageSettings.LabelSize.Height));
                break;

            case 2:
                pagePreview1.PageSize = PageSizeConverter.ToSize(pageSettings.PageSize);
                break;
            }
            pagePreview1.Refresh();
        }
コード例 #14
0
        private PageSize InferePageSize(XSize size)
        {
            System.Drawing.Size calcSize;
            PageSize            inferredPS = PageSize.A4;

            foreach (PageSize ps in Enum.GetValues(typeof(PageSize)))
            {
                if (ps != PageSize.Undefined)
                {
                    calcSize = PageSizeConverter.ToSize(ps);
                    if (calcSize.Width == size.Width && calcSize.Height == size.Height)
                    {
                        inferredPS = ps;
                        break;
                    }
                    if (calcSize.Width == size.Height && calcSize.Height == size.Width)
                    {
                        inferredPS = ps;
                        break;
                    }
                }
            }
            return(inferredPS);
        }
コード例 #15
0
        /// <summary>
        /// Create PDF pages from given HTML and appends them to the provided PDF document
        /// </summary>
        /// <param name="template">template to use for the page, if null just make a blank page</param>
        /// <param name="document"></param>
        /// <param name="html"></param>
        /// <param name="config"></param>
        /// <param name="cssData"></param>
        /// <param name="stylesheetLoad"></param>
        /// <param name="imageLoad"></param>
        public static void AddPdfPages(PdfDocument template, PdfDocument document, string html, PdfGenerateConfig config, CssData cssData = null, EventHandler <HtmlStylesheetLoadEventArgs> stylesheetLoad = null, EventHandler <HtmlImageLoadEventArgs> imageLoad = null)
        {
            XSize orgPageSize;

            // get the size of each page to layout the HTML in
            if (config.PageSize != PageSize.Undefined)
            {
                orgPageSize = PageSizeConverter.ToSize(config.PageSize);
            }
            else
            {
                orgPageSize = config.ManualPageSize;
            }

            if (config.PageOrientation == PageOrientation.Landscape)
            {
                // invert pagesize for landscape
                orgPageSize = new XSize(orgPageSize.Height, orgPageSize.Width);
            }

            var pageSize = new XSize(orgPageSize.Width - config.MarginLeft - config.MarginRight, orgPageSize.Height - config.MarginTop - config.MarginBottom);

            if (!string.IsNullOrEmpty(html))
            {
                using (var container = new HtmlContainer())
                {
                    if (stylesheetLoad != null)
                    {
                        container.StylesheetLoad += stylesheetLoad;
                    }
                    if (imageLoad != null)
                    {
                        container.ImageLoad += imageLoad;
                    }

                    container.Location = new XPoint(config.MarginLeft, config.MarginTop);
                    container.MaxSize  = new XSize(pageSize.Width, 0);
                    container.SetHtml(html, cssData);
                    container.PageSize     = pageSize;
                    container.MarginBottom = config.MarginBottom;
                    container.MarginLeft   = config.MarginLeft;
                    container.MarginRight  = config.MarginRight;
                    container.MarginTop    = config.MarginTop;

                    // layout the HTML with the page width restriction to know how many pages are required
                    using (var measure = XGraphics.CreateMeasureContext(pageSize, XGraphicsUnit.Point, XPageDirection.Downwards))
                    {
                        container.PerformLayout(measure);
                    }

                    // while there is un-rendered HTML, create another PDF page and render with proper offset for the next page
                    double scrollOffset = 0;
                    while (scrollOffset > -container.ActualSize.Height)
                    {
                        PdfPage page;

                        if (template != null)
                        {
                            var templatePage = template.Pages[0];
                            page = document.AddPage(templatePage);
                        }
                        else
                        {
                            page = document.AddPage();
                        }


                        page.Height = orgPageSize.Height;
                        page.Width  = orgPageSize.Width;

                        using (var g = XGraphics.FromPdfPage(page))
                        {
                            //g.IntersectClip(new XRect(config.MarginLeft, config.MarginTop, pageSize.Width, pageSize.Height));
                            g.IntersectClip(new XRect(0, 0, page.Width, page.Height));

                            container.ScrollOffset = new XPoint(0, scrollOffset);
                            container.PerformPaint(g);
                        }
                        scrollOffset -= pageSize.Height;
                    }

                    // add web links and anchors
                    HandleLinks(document, container, orgPageSize, pageSize);
                }
            }
        }
コード例 #16
0
 public PreviewForm()
 {
     InitializeComponent();
     this.pagePreview.PageSize = PageSizeConverter.ToSize(PageSize.A4);
     UpdateStatusBar();
 }
コード例 #17
0
        private void CreatePDF(OrderlineUniter orders)
        {
            string danishAlphabet = "abcdefghijklmnopqrstuvwxyzæøåABCDEFGHIJKLMNOPQRSTUVWXYZÆØÅ"; //Used to get the height ratio.
            //PDF Sharp initializations.
            PdfDocument pdf           = new PdfDocument();
            PdfPage     pdfPage       = pdf.AddPage();
            XGraphics   graph         = XGraphics.FromPdfPage(pdfPage);
            XFont       fontHeader    = new XFont("Verdana", 13, XFontStyle.Bold);
            XFont       fontParagraph = new XFont("Verdana", 13, XFontStyle.Regular);
            XSize       size          = PageSizeConverter.ToSize(PdfSharp.PageSize.A4);

            //Margins
            int marginTop   = 20;
            int marginLeft  = 50;
            int marginRight = 50;

            //Line height
            double lineHeight = graph.MeasureString(danishAlphabet, fontParagraph).Height + 5;

            //Calculates the headline positions.
            string nameString = "Produkt";
            double nameLength = graph.MeasureString(nameString, fontHeader).Width;
            double nameX      = marginLeft;

            string unitString = "Enhed";
            double unitLength = graph.MeasureString(unitString, fontHeader).Width;
            double unitX      = size.Width - unitLength - marginRight;

            string quantityString = "Antal";
            double quantityLength = graph.MeasureString(quantityString, fontHeader).Width;
            double quantityX      = size.Width - nameLength - unitLength - marginRight;

            //Draws the product name headline.
            graph.DrawString(
                nameString,
                fontHeader,
                XBrushes.Black,
                new XRect(nameX, marginTop, pdfPage.Width.Point, pdfPage.Height.Point),
                XStringFormats.TopLeft);

            //Draws the quantity headline.
            graph.DrawString(
                quantityString,
                fontHeader,
                XBrushes.Black,
                new XRect(quantityX, marginTop, pdfPage.Width.Point, pdfPage.Height.Point),
                XStringFormats.TopLeft);

            //Draws the unit headline.
            graph.DrawString(
                unitString,
                fontHeader,
                XBrushes.Black,
                new XRect(unitX, marginTop, pdfPage.Width.Point, pdfPage.Height.Point),
                XStringFormats.TopLeft);

            //Draw entries
            for (int i = 0; i < orders.QuantityPerProduct.Count; i++)
            {
                //Calculates the position of the current line.
                double lineY = lineHeight * (i + 1);

                //Gives every second line a light gray background color.
                if (i % 2 == 1)
                {
                    XSolidBrush brush = new XSolidBrush(XColors.LightGray);

                    graph.DrawRectangle(brush, marginLeft, lineY + marginTop, size.Width - marginLeft - marginRight, lineHeight - 2);
                }

                //Draws the product name.
                graph.DrawString(
                    orders.QuantityPerProduct.ElementAt(i).ProdV.Product.Name,
                    fontParagraph,
                    XBrushes.Black,
                    new XRect(nameX, marginTop + lineY, pdfPage.Width, pdfPage.Height),
                    XStringFormats.TopLeft);

                //Draws the quantity.
                graph.DrawString(
                    orders.QuantityPerProduct.ElementAt(i).Quantity.ToString(),
                    fontParagraph,
                    XBrushes.Black,
                    new XRect(quantityX, marginTop + lineY, pdfPage.Width, pdfPage.Height),
                    XStringFormats.TopLeft);

                //Draws the unit.
                graph.DrawString(
                    orders.QuantityPerProduct.ElementAt(i).OrderedUnit.Name,
                    fontParagraph,
                    XBrushes.Black,
                    new XRect(unitX, marginTop + lineY, pdfPage.Width, pdfPage.Height),
                    XStringFormats.TopLeft);
            }

            //Code used to setup the save file dialog.
            SaveFileDialog saveFileDialog = new SaveFileDialog(); //Asks the user for the position of the code.

            saveFileDialog.Title            = "Save PDF";
            saveFileDialog.CheckPathExists  = true;
            saveFileDialog.DefaultExt       = "pdf";
            saveFileDialog.Filter           = "PDF (*.pdf)|*.pdf|All files (*.*)|*.*";
            saveFileDialog.FilterIndex      = 2;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.FileName         = orders.QuantityPerProduct.ElementAt(0).ProdV.Supplier; //File name corresponds to name of the supplier by default.

            //Shows the save file dialog.
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                pdf.Save(saveFileDialog.FileName);
            }

            //Opens the newly generated pdf.
            Process.Start(saveFileDialog.FileName);
        }
コード例 #18
0
        /// <summary>
        /// Create PDF pages from given HTML and appends them to the provided PDF document.<br/>
        /// </summary>
        /// <param name="document">PDF document to append pages to</param>
        /// <param name="html">HTML source to create PDF from</param>
        /// <param name="config">the configuration to use for the PDF generation (page size/page orientation/margins/etc.)</param>
        /// <param name="cssData">optional: the style to use for html rendering (default - use W3 default style)</param>
        /// <param name="stylesheetLoad">optional: can be used to overwrite stylesheet resolution logic</param>
        /// <param name="imageLoad">optional: can be used to overwrite image resolution logic</param>
        /// <returns>the generated image of the html</returns>
        public static void AddPdfPages(PdfDocument document, string html, PdfGenerateConfig config, CssData cssData = null, EventHandler <HtmlStylesheetLoadEventArgs> stylesheetLoad = null, EventHandler <HtmlImageLoadEventArgs> imageLoad = null)
        {
            XSize orgPageSize;

            // get the size of each page to layout the HTML in
            if (config.PageSize != PageSize.Undefined)
            {
                orgPageSize = PageSizeConverter.ToSize(config.PageSize);
            }
            else
            {
                orgPageSize = config.ManualPageSize;
            }

            if (config.PageOrientation == PageOrientation.Landscape)
            {
                // invert pagesize for landscape
                orgPageSize = new XSize(orgPageSize.Height, orgPageSize.Width);
            }

            var pageSize = new XSize(orgPageSize.Width - config.MarginLeft - config.MarginRight, orgPageSize.Height - config.MarginTop - config.MarginBottom);

            if (!string.IsNullOrEmpty(html))
            {
                using (var container = new HtmlContainer())
                {
                    if (stylesheetLoad != null)
                    {
                        container.StylesheetLoad += stylesheetLoad;
                    }
                    if (imageLoad != null)
                    {
                        container.ImageLoad += imageLoad;
                    }

                    container.Location = new XPoint(config.MarginLeft, config.MarginTop);
                    container.MaxSize  = new XSize(pageSize.Width, 0);
                    container.SetHtml(html, cssData);
                    container.PageSize     = pageSize;
                    container.MarginBottom = config.MarginBottom;
                    container.MarginLeft   = config.MarginLeft;
                    container.MarginRight  = config.MarginRight;
                    container.MarginTop    = config.MarginTop;

                    // layout the HTML with the page width restriction to know how many pages are required
                    using (var measure = XGraphics.CreateMeasureContext(pageSize, XGraphicsUnit.Point, XPageDirection.Downwards))
                    {
                        container.PerformLayout(measure);
                    }

                    // while there is un-rendered HTML, create another PDF page and render with proper offset for the next page
                    double scrollOffset = 0;

                    int totalPages = (int)(container.ActualSize.Height / pageSize.Height) + 1;

                    while (scrollOffset > -container.ActualSize.Height)
                    {
                        var page = document.AddPage();
                        page.Height = orgPageSize.Height;
                        page.Width  = orgPageSize.Width;

                        using (var g = XGraphics.FromPdfPage(page))
                        {
                            //g.IntersectClip(new XRect(config.MarginLeft, config.MarginTop, pageSize.Width, pageSize.Height));
                            g.IntersectClip(new XRect(0, 0, page.Width, page.Height));

                            container.ScrollOffset = new XPoint(0, scrollOffset);
                            container.PerformPaint(g);

                            if (config.EnablePageNumbering)
                            {
                                string pageNumbersStr     = string.Format(config.PageNumbersPattern, (-scrollOffset / pageSize.Height) + 1, totalPages);
                                var    pageNumbersStrSize = g.MeasureString(pageNumbersStr, config.PageNumbersFont);

                                double xCord = 0;
                                switch (config.PageNumberLocation)
                                {
                                case PageNumberLocation.Left:
                                    xCord = config.MarginLeft + pageNumbersStrSize.Width / 2;
                                    break;

                                case PageNumberLocation.Middle:
                                    xCord = config.MarginLeft + pageSize.Width / 2 - pageNumbersStrSize.Width / 2;
                                    break;

                                case PageNumberLocation.Right:
                                    xCord = pageSize.Width - pageNumbersStrSize.Width / 2;
                                    break;
                                }

                                //draw page numbers
                                g.DrawString(
                                    pageNumbersStr,
                                    config.PageNumbersFont,
                                    new XSolidBrush(),
                                    new XPoint(xCord, page.Height - config.PageNumbersMarginBottom));

                                //g.DrawString(
                                //	"middle",
                                //	config.PageNumbersFont,
                                //	new XSolidBrush(),
                                //	new XPoint(0, page.Height - config.PageNumbersMarginBottom));

                                //g.DrawString(
                                //	"right",
                                //	config.PageNumbersFont,
                                //	new XSolidBrush(),
                                //	new XPoint(pageSize.Width/2 + config.MarginLeft - g.MeasureString("x", config.PageNumbersFont).Width, page.Height - config.PageNumbersMarginBottom));

                                //g.DrawString(
                                //	"left",
                                //	config.PageNumbersFont,
                                //	new XSolidBrush(),
                                //	new XPoint(config.MarginLeft + g.MeasureString("left", config.PageNumbersFont).Width / 2, page.Height - config.PageNumbersMarginBottom));
                            }
                        }

                        scrollOffset -= pageSize.Height;
                    }

                    // add web links and anchors
                    HandleLinks(document, container, orgPageSize, pageSize);
                }
            }
        }
コード例 #19
0
        /// <summary>
        /// Create PDF pages from given HTML and appends them to the provided PDF document.<br/>
        /// </summary>
        /// <param name="document">PDF document to append pages to</param>
        /// <param name="html">HTML source to create PDF from</param>
        /// <param name="config">the configuration to use for the PDF generation (page size/page orientation/margins/etc.)</param>
        /// <param name="cssData">optional: the style to use for html rendering (default - use W3 default style)</param>
        /// <param name="stylesheetLoad">optional: can be used to overwrite stylesheet resolution logic</param>
        /// <param name="imageLoad">optional: can be used to overwrite image resolution logic</param>
        /// <returns>the generated image of the html</returns>
        public static void AddPdfPages(PdfDocument document, string html, PdfGenerateConfig config, CssData cssData = null, EventHandler <HtmlStylesheetLoadEventArgs> stylesheetLoad = null, EventHandler <HtmlImageLoadEventArgs> imageLoad = null)
        {
            XSize orgPageSize;

            // get the size of each page to layout the HTML in
            if (config.PageSize != PageSize.Undefined)
            {
                orgPageSize = PageSizeConverter.ToSize(config.PageSize);
            }
            else
            {
                orgPageSize = config.ManualPageSize;
            }

            if (config.PageOrientation == PageOrientation.Landscape)
            {
                // invert pagesize for landscape
                orgPageSize = new XSize(orgPageSize.Height, orgPageSize.Width);
            }

            var pageSize = new XSize(orgPageSize.Width - config.MarginLeft - config.MarginRight, orgPageSize.Height - config.MarginTop - config.MarginBottom);

            if (!string.IsNullOrEmpty(html))
            {
                using (var container = new HtmlContainer())
                {
                    if (stylesheetLoad != null)
                    {
                        container.StylesheetLoad += stylesheetLoad;
                    }
                    if (imageLoad != null)
                    {
                        container.ImageLoad += imageLoad;
                    }

                    container.Location = new XPoint(config.MarginLeft, config.MarginTop);
                    container.MaxSize  = new XSize(pageSize.Width, 0);
                    container.SetHtml(html, cssData);
                    container.PageSize     = pageSize;
                    container.MarginBottom = config.MarginBottom;
                    container.MarginLeft   = config.MarginLeft;
                    container.MarginRight  = config.MarginRight;
                    container.MarginTop    = config.MarginTop;

                    // layout the HTML with the page width restriction to know how many pages are required
                    var measure = XGraphics.CreateMeasureContext(pageSize, XGraphicsUnit.Point, XPageDirection.Downwards);
                    container.PerformLayout(measure);

                    // while there is un-rendered HTML, create another PDF page and render with proper offset for the next page
                    double scrollOffset = 0;
                    //SL: if there is more than one page, increase the bottom margin to allow space for the page number
                    container.MarginBottom += scrollOffset > -container.ActualSize.Height ?  20 : 0;
                    container.PerformLayout(measure); //SL: This still does not increase the margin for the first page of a multi page.. welp
                    while (scrollOffset > -container.ActualSize.Height)
                    {
                        var page = document.AddPage();
                        page.Height = orgPageSize.Height;
                        page.Width  = orgPageSize.Width;

                        using (var g = XGraphics.FromPdfPage(page))
                        {
                            //g.IntersectClip(new XRect(config.MarginLeft, config.MarginTop, pageSize.Width, pageSize.Height));
                            g.IntersectClip(new XRect(0, 0, page.Width, page.Height));

                            container.ScrollOffset = new XPoint(0, scrollOffset);
                            container.PerformPaint(g);
                        }
                        scrollOffset -= pageSize.Height;
                    }

                    if (config.AddPageCountFoooter && document.PageCount > 1)  //Only add page numbers if more than one page
                    {
                        AddPageCountFoooter(document, pageSize);
                    }

                    // SL: Set config option to handle links or not as it crashes for
                    // some valid html links.
                    // TODO: Investigate reason for crashing.
                    if (config.HandleLinks)
                    {
                        HandleLinks(document, container, orgPageSize, pageSize);
                    }
                }
            }
        }
コード例 #20
0
        /// <summary>
        /// Create PDF pages from given HTML and appends them to the provided PDF document.<br/>
        /// </summary>
        /// <param name="document">PDF document to append pages to</param>
        /// <param name="html">HTML source to create PDF from</param>
        /// <param name="config">the configuration to use for the PDF generation (page size/page orientation/margins/etc.)</param>
        /// <param name="cssData">optional: the style to use for html rendering (default - use W3 default style)</param>
        /// <param name="stylesheetLoad">optional: can be used to overwrite stylesheet resolution logic</param>
        /// <param name="imageLoad">optional: can be used to overwrite image resolution logic</param>
        /// <returns>the generated image of the html</returns>
        public static async Task AddPdfPages(PdfDocument document,
                                             IResourceServer resourceServer,
                                             PdfGenerateConfig config
                                             )
        {
            XSize orgPageSize;

            // get the size of each page to layout the HTML in
            if (config.PageSize != PageSize.Undefined)
            {
                orgPageSize = PageSizeConverter.ToSize(config.PageSize);
            }
            else
            {
                orgPageSize = config.ManualPageSize;
            }

            if (config.PageOrientation == PageOrientation.Landscape)
            {
                // invert pagesize for landscape
                orgPageSize = new XSize(orgPageSize.Height, orgPageSize.Width);
            }

            var pageSize = new XSize(orgPageSize.Width - config.MarginLeft - config.MarginRight, orgPageSize.Height - config.MarginTop - config.MarginBottom);

            var html = await resourceServer.GetHtmlAsync();

            if (!string.IsNullOrEmpty(html))
            {
                using (var container = new HtmlContainer())
                {
                    container.Location = new XPoint(config.MarginLeft, config.MarginTop);
                    container.MaxSize  = new XSize(pageSize.Width, 0);
                    await container.SetResourceServerAsync(resourceServer);

                    container.PageSize     = pageSize;
                    container.MarginBottom = config.MarginBottom;
                    container.MarginLeft   = config.MarginLeft;
                    container.MarginRight  = config.MarginRight;
                    container.MarginTop    = config.MarginTop;

                    // layout the HTML with the page width restriction to know how many pages are required
                    using (var measure = XGraphics.CreateMeasureContext(pageSize, XGraphicsUnit.Point, XPageDirection.Downwards))
                    {
                        container.PerformLayout(measure);
                    }

                    // while there is un-rendered HTML, create another PDF page and render with proper offset for the next page
                    double scrollOffset = 0;
                    while (scrollOffset > -container.ActualSize.Height)
                    {
                        var page = document.AddPage();
                        page.Height = orgPageSize.Height;
                        page.Width  = orgPageSize.Width;

                        using (var g = XGraphics.FromPdfPage(page))
                        {
                            //g.IntersectClip(new XRect(config.MarginLeft, config.MarginTop, pageSize.Width, pageSize.Height));
                            g.IntersectClip(new XRect(0, 0, page.Width, page.Height));

                            container.ScrollOffset = new XPoint(0, scrollOffset);
                            container.PerformPaint(g);
                        }
                        scrollOffset -= pageSize.Height;
                    }

                    // add web links and anchors
                    HandleLinks(document, container, orgPageSize, pageSize);
                }
            }
        }
コード例 #21
0
        private void RunDownloadPdf(ItemDownload itemDownload)
        {
            //Tạo folder chapter
            string folderChapterPath = DataForm.FolderDownload + @"\" + itemDownload.ComicName;

            if (!Directory.Exists(folderChapterPath))
            {
                Directory.CreateDirectory(folderChapterPath);
            }

            //Tải image
            UpdateStatus(itemDownload.ComicName, itemDownload.ChapterName, "Đang tải");
            HtmlAgilityPack.HtmlDocument html = new HtmlAgilityPack.HtmlDocument();
            HtmlWeb docHFile = new HtmlWeb();

            //html = docHFile.Load(itemDownload.ComicLink);
            html = docHFile.LoadFromWebAsync(itemDownload.ComicLink).Result;
            WebComic           webComic = DataForm.WebComics.Where(x => itemDownload.ComicLink.Contains(x.web)).FirstOrDefault();
            HtmlNodeCollection nodes    = html.DocumentNode.SelectNodes(webComic.pageChapterXpath);

            if (nodes != null)
            {
                string      imageLink;
                PdfDocument doc = new PdfDocument();
                if (DataForm.DownloadType == DownloadTypeEnum.MutilChapterOneFilePdf)
                {
                    doc.Info.Title = itemDownload.ChapterName;
                }
                else if (DataForm.DownloadType == DownloadTypeEnum.OneChapterOneFilePdf)
                {
                    doc.Info.Title = itemDownload.ComicName + "-" + itemDownload.ChapterName;
                }

                doc.PageLayout = PdfPageLayout.SinglePage;

                for (int i = 0, n = nodes.Count; i < n; i++)
                {
                    imageLink = nodes[i].Attributes["src"].Value;
                    Image imagePageChapter = Common.DownloadImage(imageLink, webComic.headersDownloadImage);
                    if (imagePageChapter != null)
                    {
                        PdfPage pdfPage = new PdfPage();
                        XSize   size    = PageSizeConverter.ToSize(PageSize.A4);
                        XImage  img     = null;
                        if (imagePageChapter.Width > imagePageChapter.Height)
                        {
                            pdfPage.Orientation = PageOrientation.Landscape;
                            Image _imagePageChapter = ResizeImage(imagePageChapter, (int)size.Height, (int)size.Width - 5, false);
                            img = XImage.FromStream(GetStream(_imagePageChapter, ImageFormat.Jpeg));
                        }
                        else
                        {
                            pdfPage.Orientation = PageOrientation.Portrait;
                            Image _imagePageChapter = ResizeImage(imagePageChapter, (int)size.Width, (int)size.Height - 5, false);
                            img = XImage.FromStream(GetStream(_imagePageChapter, ImageFormat.Jpeg));
                        }

                        pdfPage.Width  = size.Width * 72 / 96;
                        pdfPage.Height = size.Height * 72 / 96;

                        doc.Pages.Add(pdfPage);

                        XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[doc.Pages.Count - 1]);

                        double dx = xgr.PageSize.Width;
                        double dy = xgr.PageSize.Height;
                        xgr.DrawImage(img, (dx - (img.PixelWidth * 72) / 96) / 2, 0);
                    }
                }
                if (doc.Pages.Count == 0)
                {
                    UpdateStatus(itemDownload.ComicName, itemDownload.ChapterName, "Lỗi tải ảnh");
                    currentProcessDownloading.Remove(itemDownload);
                    ShowNotification("Lỗi tải ảnh: " + itemDownload.ComicName + "-" + itemDownload.ChapterName, "", AlertTypeEnum.Error);
                    return;
                }
                doc.Save(folderChapterPath + @"\" + itemDownload.ChapterName + ".pdf");
                doc.Close();
            }

            //Save file
            UpdateStatus(itemDownload.ComicName, itemDownload.ChapterName, "Đã xong");
            currentProcessDownloading.Remove(itemDownload);

            //Merge chapter pdf
            if (!DataDownload.ListDownload.Where(x => x.ComicName.Equals(itemDownload.ComicName) && !x.Status.Equals("Đã xong") && !x.Status.Equals("Lỗi tải ảnh")).Any())
            {
                if (DataForm.DownloadType == DownloadTypeEnum.MutilChapterOneFilePdf)
                {
                    string[] pdfChapters = Directory.GetFiles(folderChapterPath).Where(s => Path.GetExtension(s).ToLowerInvariant() == ".pdf").ToArray();
                    if (pdfChapters == null || pdfChapters.Count() == 0)
                    {
                        ShowNotification("Không tải thành công chapter nào!", folderChapterPath, AlertTypeEnum.Error);
                        return;
                    }
                    MergeMultiplePDFIntoSinglePDF(folderChapterPath + "\\" + itemDownload.ComicName + ".pdf", pdfChapters, itemDownload.ComicName);
                }

                //Show notification
                if (!DataForm.OffAlert)
                {
                    ShowNotification("Đã tải xong: " + itemDownload.ComicName, folderChapterPath);
                }
            }
        }
コード例 #22
0
        public PdfDocument CreateFirstPage(Candidate model, PdfDocument pdfDocument)
        {
            PdfPage pdfPage = new PdfPage();
            XSize   size    = PageSizeConverter.ToSize(PageSize.A4);

            pdfPage.Orientation = PageOrientation.Portrait;

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

            pdfDocument.Pages.Add(pdfPage);


            XGraphics gfx = XGraphics.FromPdfPage(pdfPage);

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


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

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

            var paragraph = section.AddParagraph();

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


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

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



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

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


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

            return(pdfDocument);
        }