Ejemplo n.º 1
0
        public static void Main()
        {
            // NOTE:
            // When used in trial mode, the library imposes some restrictions.
            // Please visit http://bitmiracle.com/pdf-library/trial-restrictions.aspx
            // for more information.

            using (PdfDocument pdf = new PdfDocument())
            {
                PdfPoint       startPoint           = new PdfPoint(10, 10);
                PdfSize        size                 = new PdfSize(100, 100);
                float          distance             = 30.0f;
                PdfTextAlign[] horizontalAlignments = { PdfTextAlign.Left, PdfTextAlign.Center, PdfTextAlign.Right };

                PdfPage page = pdf.Pages[0];
                for (int h = 0; h < horizontalAlignments.Length; ++h)
                {
                    PdfTextBox textBox = page.AddTextBox(
                        startPoint.X + h * (size.Width + distance),
                        startPoint.Y,
                        size.Width,
                        size.Height
                        );
                    textBox.Multiline = true;
                    textBox.TextAlign = horizontalAlignments[h];
                    textBox.Text      = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum eu ligula ligula, sit amet tempor odio.";
                }

                string pathToFile = "TextFieldAlignment.pdf";
                pdf.Save(pathToFile);
                Console.WriteLine($"The output is located in {Environment.CurrentDirectory}");
            }
        }
        internal override void                boxPrintBackground(PdfPoint upperLeftCorner, PrintBackground background)
        {
            upperLeftCorner += new PdfPoint(Left, Top);

            if (_border != null)
            {
                PdfPoint point = upperLeftCorner;
                PdfSize  size  = new PdfSize(Width, Height);

                if (_margin != null)
                {
                    point.y     -= _margin.Top;
                    point.x     += _margin.Left;
                    size.width  -= _margin.Left + _margin.Right;
                    size.height += _margin.Top + _margin.Bottom;
                }

                _border.boxPrint(point, size, background);
            }

            for (int i = 0; i < _children.Count; ++i)
            {
                _children[i].boxPrintBackground(upperLeftCorner, background);
            }
        }
Ejemplo n.º 3
0
 internal PdfPage(PdfPageTree parent, PdfSize size)
 {
     m_Size     = size;
     m_Unit     = m_Size.Unit;
     m_Parent   = parent;
     m_Fonts    = new List <PdfFont>();
     m_Elements = new List <PdfElement>();
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Creates new page and adds it to the page tree
        /// </summary>
        /// <returns></returns>
        public PdfPage CreatePage(PdfSize size)
        {
            var page = new PdfPage(this, size);

            m_Pages.Add(page);

            return(page);
        }
        private void centerContentInPrintableArea(Graphics gr, PdfSize contentSizeInPoints, float scaleFactor)
        {
            float xDiff = (float)(m_printableAreaInPoints.Width - contentSizeInPoints.Width * scaleFactor);
            float yDiff = (float)(m_printableAreaInPoints.Height - contentSizeInPoints.Height * scaleFactor);

            if (Math.Abs(xDiff) > 0 || Math.Abs(yDiff) > 0)
            {
                gr.TranslateTransform(xDiff / 2, yDiff / 2);
            }
        }
        private void printDocument_QueryPageSettings(object sender, QueryPageSettingsEventArgs e)
        {
            PdfPage page = m_pdf.Pages[m_pageIndex];

            // Auto-detect portrait/landscape orientation.
            // Printer settings for orientation are ignored in this sample.
            PdfSize pageSize = getPageSizeInPoints(page);

            e.PageSettings.Landscape = pageSize.Width > pageSize.Height;

            m_printableAreaInPoints = getPrintableAreaInPoints(e.PageSettings);
        }
        private static void drawImage(Graphics gr, PdfPaintedImage image, float userUnit)
        {
            // Do not render images with zero width or height. GDI+ throws OutOfMemoryException
            // in x86 processes for regular image size (e.g. 1x51) and very small transformation
            // matrix (e.g. { 0.000005, 0, 0, 0.003, x, y }).
            PdfSize paintedImageSize = image.Bounds.Size;

            if (Math.Abs(paintedImageSize.Width) < 0.001 || Math.Abs(paintedImageSize.Height) < 0.001)
            {
                return;
            }

            // ignore mask images in this sample
            if (image.Image.IsMask)
            {
                return;
            }

            using (var stream = new MemoryStream())
            {
                image.Image.Save(stream);
                using (Bitmap bitmap = (Bitmap)Image.FromStream(stream))
                {
                    saveStateAndDraw(gr, image.ClipRegion, userUnit, () =>
                    {
                        gr.TranslateTransform((float)image.Position.X, (float)image.Position.Y);
                        concatMatrix(gr, image.TransformationMatrix);

                        // Important for rendering of neighbour image tiles
                        gr.PixelOffsetMode = PixelOffsetMode.Half;

                        PdfSize imageSize = new PdfSize(image.Image.Width, image.Image.Height);
                        if (imageSize.Width < bitmap.Width && imageSize.Height < bitmap.Height)
                        {
                            // the bitmap produced from the image is larger than the image.
                            // usually this happens when image has a mask image which is larger than the image itself.
                            InterpolationMode current = gr.InterpolationMode;
                            gr.InterpolationMode      = InterpolationMode.HighQualityBicubic;
                            gr.DrawImage(bitmap, 0, 0, (float)imageSize.Width, (float)imageSize.Height);
                            gr.InterpolationMode = current;
                        }
                        else
                        {
                            // bitmap has the same size
                            // or one of it's dimensions is longer than the corresponding image dimension
                            gr.DrawImage(bitmap, 0, 0, bitmap.Width, bitmap.Height);
                        }
                    });
                }
            }
        }
Ejemplo n.º 8
0
        private static void drawFooter(int pageIndex, PdfPage page, PdfFont font)
        {
            var canvas = page.Canvas;

            canvas.Font     = font;
            canvas.FontSize = 14;

            PdfSize rotatedPageSize     = getRotatedPageSize(page);
            var     paddingFromCorner   = new PdfSize(30, 30);
            var     positionRightBottom = new PdfPoint(
                rotatedPageSize.Width - paddingFromCorner.Width,
                rotatedPageSize.Height - paddingFromCorner.Height
                );

            showTextAtRotatedPage((pageIndex + 1).ToString(), positionRightBottom, page);
        }
Ejemplo n.º 9
0
        public static void Main()
        {
            // NOTE:
            // When used in trial mode, the library imposes some restrictions.
            // Please visit http://bitmiracle.com/pdf-library/trial-restrictions.aspx
            // for more information.

            string pathToFile = "BlendModes.pdf";

            using (PdfDocument pdf = new PdfDocument())
            {
                PdfCanvas canvas = pdf.Pages[0].Canvas;

                PdfPoint location = new PdfPoint(50, 80);
                PdfSize  size     = new PdfSize(50, 50);

                PdfBlendMode[] modes = new PdfBlendMode[] { PdfBlendMode.Hue, PdfBlendMode.Lighten, PdfBlendMode.Darken };
                for (int i = 0; i < modes.Length; ++i)
                {
                    if (i != 0)
                    {
                        location.X += size.Width * 2;
                    }

                    canvas.BlendMode = PdfBlendMode.Normal;

                    canvas.Brush.Color = new PdfRgbColor(0, 0, 0);
                    canvas.DrawString(location.X, location.Y - 20, "BlendMode: " + modes[i].ToString());

                    canvas.Brush.Color = new PdfRgbColor(200, 140, 7);
                    canvas.DrawRectangle(new PdfRectangle(location, size), 0, PdfDrawMode.Fill);

                    canvas.BlendMode   = modes[i];
                    canvas.Brush.Color = new PdfRgbColor(125, 125, 255);
                    PdfRectangle secondRect = new PdfRectangle(location.X + 15, location.Y + 15, size.Width, size.Height);
                    canvas.DrawRectangle(secondRect, 0, PdfDrawMode.Fill);
                }

                pdf.Save(pathToFile);
            }

            Process.Start(pathToFile);
        }
Ejemplo n.º 10
0
        private void printDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            Graphics gr = e.Graphics;

            // Work in points to have consistent units for all contexts:
            // 1. Printer
            // 2. Print preview
            // 3. PDF
            gr.PageUnit = GraphicsUnit.Point;

            if (m_printAction == PrintAction.PrintToPreview)
            {
                gr.SmoothingMode = SmoothingMode.HighQuality;

                gr.Clear(Color.LightGray);
                gr.FillRectangle(Brushes.White, m_printableAreaInPoints);
                gr.IntersectClip(m_printableAreaInPoints);

                gr.TranslateTransform(m_printableAreaInPoints.X, m_printableAreaInPoints.Y);
            }

            PdfPage page             = m_pdf.Pages[m_pageIndex];
            PdfSize pageSizeInPoints = getPageSizeInPoints(page);

            if (m_printSize == PrintSize.FitPage)
            {
                float sx          = (float)(m_printableAreaInPoints.Width / pageSizeInPoints.Width);
                float sy          = (float)(m_printableAreaInPoints.Height / pageSizeInPoints.Height);
                float scaleFactor = Math.Min(sx, sy);

                centerContentInPrintableArea(gr, pageSizeInPoints, scaleFactor);
                gr.ScaleTransform(scaleFactor, scaleFactor);
            }
            else if (m_printSize == PrintSize.ActualSize)
            {
                centerContentInPrintableArea(gr, pageSizeInPoints, 1);
            }

            page.Draw(gr);

            ++m_pageIndex;
            e.HasMorePages = (m_pageIndex <= m_lastPageIndex);
        }
        public static void Main()
        {
            // NOTE:
            // When used in trial mode, the library imposes some restrictions.
            // Please visit http://bitmiracle.com/pdf-library/trial-restrictions.aspx
            // for more information.

            string pathToFile = "TextMarkupAnnotations.pdf";

            using (PdfDocument pdf = new PdfDocument())
            {
                PdfPage   page   = pdf.Pages[0];
                PdfCanvas canvas = page.Canvas;

                // Draw text on the page
                const string Text         = "Highlighted text";
                PdfPoint     textPosition = new PdfPoint(10, 50);
                canvas.FontSize = 30;
                canvas.DrawString(textPosition, Text);

                // Get size of the drawn text
                PdfSize size   = canvas.MeasureText(Text);
                var     bounds = new PdfRectangle(textPosition, size);

                // Highlight and annotate the text
                var          color = new PdfRgbColor(0, 0, 255);
                const string AnnotationContents = "Lorem ipsum";
                page.AddHighlightAnnotation(AnnotationContents, bounds, color);

                // Or call these method to strike out or underline the text:
                // page.AddStrikeoutAnnotation(AnnotationContents, bounds, color);
                // page.AddJaggedUnderlineAnnotation(AnnotationContents, bounds, color);
                // page.AddUnderlineAnnotation(AnnotationContents, bounds, color);

                pdf.Save(pathToFile);
            }

            Process.Start(pathToFile);
        }
Ejemplo n.º 12
0
        internal void                boxPrint(PdfPoint upperLeftCorner, PdfSize size, PrintBackground background)
        {
            if (_top != null)
            {
                background.DrawLineHorizontal(_top, upperLeftCorner + new PdfSize(0, -_top.LineWidth.pnts / 2), size.width);
            }

            if (_left != null)
            {
                background.DrawLineVertical(_left, upperLeftCorner + new PdfSize(_left.LineWidth.pnts / 2, 0), size.height);
            }

            if (_right != null)
            {
                background.DrawLineVertical(_right, upperLeftCorner + new PdfSize(size.width.pnts - _right.LineWidth.pnts / 2, 0), size.height);
            }

            if (_bottom != null)
            {
                background.DrawLineHorizontal(_bottom, upperLeftCorner + new PdfSize(0, size.height.pnts + _bottom.LineWidth.pnts / 2), size.width);
            }
        }
Ejemplo n.º 13
0
        public async Task Can_Create_Complex_Pdf(PdfOrientation orientation, PdfSize size, int lowerExpectedSize, int higherExpectedSize)
        {
            string html;

            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Adliance.AspNetCore.Buddy.Pdf.Test.complex_html.html"))
            {
                Assert.NotNull(stream);
                using (var reader = new StreamReader(stream ?? throw new Exception("Stream should not be null at this point.")))
                {
                    html = reader.ReadToEnd();
                }
            }

            string footer;

            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Adliance.AspNetCore.Buddy.Pdf.Test.complex_footer.html"))
            {
                Assert.NotNull(stream);
                using (var reader = new StreamReader(stream ?? throw new Exception("Stream should not be null at this point.")))
                {
                    footer = await reader.ReadToEndAsync();
                }
            }

            var bytes = await _pdfer.HtmlToPdf(html, new PdfOptions
            {
                MarginTop    = 15,
                MarginBottom = 33,
                MarginLeft   = 0,
                MarginRight  = 0,
                FooterHtml   = footer,
                Orientation  = orientation,
                Size         = size
            });

            //File.WriteAllBytes($@"C:\Users\Hannes\Downloads\complex_{size}_{orientation}.pdf", bytes);
            Assert.True(bytes.Length > lowerExpectedSize && bytes.Length < higherExpectedSize, $"Bytes were not in expected range ({bytes.Length})"); // seems like the resulting PDF is about 4MB for this
        }
        public void                            DrawLineDiagonal(PdfStyleLine lineStyle, PdfPoint begin, PdfSize size)
        {
            if (lineStyle is null)
            {
                throw new ArgumentNullException(nameof(lineStyle));
            }

            if (_diagonalLines == null)
            {
                _diagonalLines = new Lines();
            }

            _diagonalLines.Add(new Line(lineStyle, begin, begin + size));
        }
Ejemplo n.º 15
0
 /// <summary>
 /// Adds new page to document
 /// </summary>
 /// <returns>Page</returns>
 public PdfPage AddPage(PdfSize size = null)
 {
     size = size ?? PageSize ?? PdfPageSize.Default();
     return(m_PageTree.CreatePage(size));
 }