Esempio n. 1
0
        /// <summary>
        /// Creates a link within the current document.
        /// </summary>
        /// <param name="rect">The link area in default page coordinates.</param>
        /// <param name="destinationPage">The one-based destination page number.</param>
        public static PdfLinkAnnotation CreateDocumentLink(PdfRectangle rect, int destinationPage)
        {
            if (destinationPage < 1)
                throw new ArgumentException("Invalid destination page in call to CreateDocumentLink: page number is one-based and must be 1 or higher.", "destinationPage");

            PdfLinkAnnotation link = new PdfLinkAnnotation();
            link._linkType = LinkType.Document;
            link.Rectangle = rect;
            link._destPage = destinationPage;
            return link;
        }
Esempio n. 2
0
        public override void Layout(XPdfForm inputPdf, string inputPath, string outputPath, PaperTarget paperTarget, bool rightToLeft, bool showCropMarks)
        {
            if (!showCropMarks && Math.Abs(_bleedMM) < kBleedMicroDeltaMM)
            {
                File.Copy(inputPath, outputPath, true);         // we don't have any value to add, so just deliver a copy of the original
            }
            else
            {
                //_rightToLeft = rightToLeft;
                _inputPdf      = inputPdf;
                _showCropMarks = showCropMarks;

                PdfDocument outputDocument = new PdfDocument();
                outputDocument.PageLayout = PdfPageLayout.SinglePage;

                // Despite the name, PixelWidth is the same as PointWidth, just as an integer instead of
                // double precision.  We may as well use all the precision we can get.
                _paperWidth  = _inputPdf.PointWidth;
                _paperHeight = _inputPdf.PointHeight;

                // NB: Setting outputDocument.Settings.TrimMargins.All does not do what we want: it either
                // shrinks or expands the MediaBox/CropBox/BleedBox sizes.  It does not change either
                // TrimBox or ArtBox.

                for (int idx = 1; idx <= _inputPdf.PageCount; idx++)
                {
                    using (XGraphics gfx = GetGraphicsForNewPage(outputDocument))
                    {
                        DrawPage(gfx, idx);
                    }
                }

                if (Math.Abs(_bleedMM) > kBleedMicroDeltaMM)
                {
                    var tempPath = Path.ChangeExtension(Path.Combine(Path.GetDirectoryName(outputPath),
                                                                     Path.GetRandomFileName()), "pdf");
                    outputDocument.Save(tempPath);
                    outputDocument.Close();
                    outputDocument = PdfReader.Open(tempPath, PdfDocumentOpenMode.Import);
                    var         bleedMargin = new XUnit(_bleedMM, XGraphicsUnit.Millimeter);
                    PdfDocument realOutput  = new PdfDocument();
                    realOutput.PageLayout = PdfPageLayout.SinglePage;
                    var trimLocation = new XPoint(bleedMargin.Point, bleedMargin.Point);
                    foreach (var page in outputDocument.Pages)
                    {
                        var trimBox = new PdfRectangle(trimLocation, new XSize(page.MediaBox.Width - 2 * bleedMargin.Point, page.MediaBox.Height - 2 * bleedMargin.Point));
                        // All of the boxes start out the same size: MediaBox, CropBox, BleedBox, ArtBox, and TrimBox.
                        // MediaBox is presumably the physical paper size.
                        // Set CropBox the same as MediaBox.  CropBox limits what you see in Adobe Acrobat Reader DC and even Acrobat Pro.
                        // Also set BleedBox the same as MediaBox.  See https://i0.wp.com/makingcomics.spiltink.org/wp-content/uploads/2015/05/averageamericancomicsized.jpg.
                        page.BleedBox = page.MediaBox;
                        page.CropBox  = page.MediaBox;
                        page.ArtBox   = trimBox;
                        page.TrimBox  = trimBox;
                        realOutput.AddPage(page);
                    }
                    outputDocument.Close();
                    File.Delete(tempPath);
                    realOutput.Save(outputPath);
                }
                else
                {
                    outputDocument.Save(outputPath);
                }
            }
        }
Esempio n. 3
0
        ////////////////////////////////////////////////////////////////////
        // Draw example of order form
        ////////////////////////////////////////////////////////////////////

        private void DrawBookOrderForm()
        {
            // Define constants to make the code readable
            const Double Left       = 4.35;
            const Double Top        = 4.65;
            const Double Bottom     = 1.1;
            const Double Right      = 7.4;
            const Double FontSize   = 9.0;
            const Double MarginHor  = 0.04;
            const Double MarginVer  = 0.04;
            const Double FrameWidth = 0.015;
            const Double GridWidth  = 0.01;

            // column widths
            Double ColWidthPrice = ArialNormal.TextWidth(FontSize, "9999.99") + 2.0 * MarginHor;
            Double ColWidthQty   = ArialNormal.TextWidth(FontSize, "Qty") + 2.0 * MarginHor;
            Double ColWidthDesc  = Right - Left - FrameWidth - 3 * GridWidth - 2 * ColWidthPrice - ColWidthQty;

            // define table
            PdfTable Table = new PdfTable(Page, Contents, ArialNormal, FontSize);

            Table.TableArea = new PdfRectangle(Left, Bottom, Right, Top);
            Table.SetColumnWidth(new Double[] { ColWidthDesc, ColWidthPrice, ColWidthQty, ColWidthPrice });

            // define borders
            Table.Borders.SetAllBorders(FrameWidth, GridWidth);

            // margin
            PdfRectangle Margin = new PdfRectangle(MarginHor, MarginVer);

            // default header style
            Table.DefaultHeaderStyle.Margin          = Margin;
            Table.DefaultHeaderStyle.BackgroundColor = Color.FromArgb(255, 196, 255);
            Table.DefaultHeaderStyle.Alignment       = ContentAlignment.MiddleRight;

            // private header style for description
            Table.Header[0].Style           = Table.HeaderStyle;
            Table.Header[0].Style.Alignment = ContentAlignment.MiddleLeft;

            // table heading
            Table.Header[0].Value = "Description";
            Table.Header[1].Value = "Price";
            Table.Header[2].Value = "Qty";
            Table.Header[3].Value = "Total";

            // default style
            Table.DefaultCellStyle.Margin = Margin;

            // description column style
            Table.Cell[0].Style = Table.CellStyle;
            Table.Cell[0].Style.MultiLineText = true;

            // qty column style
            Table.Cell[2].Style           = Table.CellStyle;
            Table.Cell[2].Style.Alignment = ContentAlignment.BottomRight;

            Table.DefaultCellStyle.Format    = "#,##0.00";
            Table.DefaultCellStyle.Alignment = ContentAlignment.BottomRight;

            Contents.DrawText(ArialBold, FontSize, 0.5 * (Left + Right), Top + MarginVer + Table.DefaultCellStyle.FontDescent,
                              TextJustify.Center, DrawStyle.Normal, Color.Purple, "Example of PdfTable support");

            // reset order total
            Double Total = 0;

            // loop for all items in the order
            // Order class is a atabase simulation for this example
            foreach (Order Book in Order.OrderList)
            {
                Table.Cell[0].Value = Book.Title + ". By: " + Book.Authors;
                Table.Cell[1].Value = Book.Price;
                Table.Cell[2].Value = Book.Qty;
                Table.Cell[3].Value = Book.Total;
                Table.DrawRow();

                // accumulate total
                Total += Book.Total;
            }
            Table.Close();

            // save graphics state
            Contents.SaveGraphicsState();

            // form line width 0.01"
            Contents.SetLineWidth(FrameWidth);
            Contents.SetLineCap(PdfLineCap.Square);

            // draw total before tax
            Double[] ColumnPosition = Table.ColumnPosition;
            Double   TotalDesc      = ColumnPosition[3] - MarginHor;
            Double   TotalValue     = ColumnPosition[4] - MarginHor;
            Double   PosY           = Table.RowTopPosition - 2.0 * MarginVer - Table.DefaultCellStyle.FontAscent;

            Contents.DrawText(ArialNormal, FontSize, TotalDesc, PosY, TextJustify.Right, "Total before tax");
            Contents.DrawText(ArialNormal, FontSize, TotalValue, PosY, TextJustify.Right, Total.ToString("#.00"));

            // draw tax (Ontario Canada HST)
            PosY -= Table.DefaultCellStyle.FontLineSpacing;
            Contents.DrawText(ArialNormal, FontSize, TotalDesc, PosY, TextJustify.Right, "Tax (13%)");
            Double Tax = Math.Round(0.13 * Total, 2, MidpointRounding.AwayFromZero);

            Contents.DrawText(ArialNormal, FontSize, TotalValue, PosY, TextJustify.Right, Tax.ToString("#.00"));

            // draw total line
            PosY -= Table.DefaultCellStyle.FontDescent + 0.5 * MarginVer;
            Contents.DrawLine(ColumnPosition[3], PosY, ColumnPosition[4], PosY);

            // draw final total
            PosY -= Table.DefaultCellStyle.FontAscent + 0.5 * MarginVer;
            Contents.DrawText(ArialNormal, FontSize, TotalDesc, PosY, TextJustify.Right, "Total payable");
            Total += Tax;
            Contents.DrawText(ArialNormal, FontSize, TotalValue, PosY, TextJustify.Right, Total.ToString("#.00"));

            PosY -= Table.DefaultCellStyle.FontDescent + MarginVer;
            Contents.DrawLine(ColumnPosition[0], Table.RowTopPosition, ColumnPosition[0], PosY);
            Contents.DrawLine(ColumnPosition[0], PosY, ColumnPosition[4], PosY);
            Contents.DrawLine(ColumnPosition[4], Table.RowTopPosition, ColumnPosition[4], PosY);

            // restore graphics state
            Contents.RestoreGraphicsState();
            return;
        }
        private async void GeneratePDF_Click(object sender, RoutedEventArgs e)
        {
            // Create a new document class object.
            PdfDocument doc        = new PdfDocument();
            PdfColor    blackColor = new PdfColor(System.Drawing.Color.FromArgb(255, 0, 0, 0));

            // Create few sections with one page in each.
            for (int i = 0; i < 4; ++i)
            {
                section = doc.Sections.Add();

                //Create page label
                PdfPageLabel label = new PdfPageLabel();

                label.Prefix      = "Sec" + i + "-";
                section.PageLabel = label;
                page = section.Pages.Add();
                section.Pages[0].Graphics.SetTransparency(0.35f);
                section.PageSettings.Transition.PageDuration = 1;
                section.PageSettings.Transition.Duration     = 1;
                section.PageSettings.Transition.Style        = PdfTransitionStyle.Box;
            }

            //Set page size
            doc.PageSettings.Size = PdfPageSize.A6;

            //Set viewer prefernce.
            doc.ViewerPreferences.HideToolbar = true;
            doc.ViewerPreferences.PageMode    = PdfPageMode.FullScreen;

            //Set page orientation
            doc.PageSettings.Orientation = PdfPageOrientation.Landscape;

            //Create a brush
            PdfSolidBrush brush = new PdfSolidBrush(blackColor);

            brush.Color = new PdfColor(System.Drawing.Color.FromArgb(255, 144, 238, 144));

            //Create a Rectangle
            PdfRectangle rect = new PdfRectangle(0, 0, 1000f, 1000f);

            rect.Brush = brush;
            PdfPen pen = new PdfPen(blackColor);

            pen.Width = 6f;

            //Get the first page in first section
            page = doc.Sections[0].Pages[0];

            //Draw the rectangle
            rect.Draw(page.Graphics);

            //Draw a line
            page.Graphics.DrawLine(pen, 0, 100, 300, 100);

            // Add margins.
            doc.PageSettings.SetMargins(0f);

            //Get the first page in second section
            page = doc.Sections[1].Pages[0];
            doc.Sections[1].PageSettings.Rotate = PdfPageRotateAngle.RotateAngle90;
            rect.Draw(page.Graphics);

            page.Graphics.DrawLine(pen, 0, 100, 300, 100);

            // Change the angle f the section. This should rotate the previous page.
            doc.Sections[2].PageSettings.Rotate = PdfPageRotateAngle.RotateAngle180;
            page = doc.Sections[2].Pages[0];
            rect.Draw(page.Graphics);
            page.Graphics.DrawLine(pen, 0, 100, 300, 100);

            section = doc.Sections[3];
            section.PageSettings.Orientation = PdfPageOrientation.Portrait;
            page = section.Pages[0];
            rect.Draw(page.Graphics);
            page.Graphics.DrawLine(pen, 0, 100, 300, 100);

            //Set the font
            PdfFont       font       = new PdfStandardFont(PdfFontFamily.Helvetica, 16f);
            PdfSolidBrush fieldBrush = new PdfSolidBrush(blackColor);

            //Create page number field
            PdfPageNumberField pageNumber = new PdfPageNumberField(font, fieldBrush);

            //Create page count field
            PdfPageCountField count = new PdfPageCountField(font, fieldBrush);

            //Draw page template
            PdfPageTemplateElement templateElement = new PdfPageTemplateElement(400, 400);

            templateElement.Graphics.DrawString("Page :\tof", font, PdfBrushes.Black, new PointF(260, 200));

            //Draw current page number
            pageNumber.Draw(templateElement.Graphics, new PointF(306, 200));

            //Draw number of pages
            count.Draw(templateElement.Graphics, new PointF(345, 200));
            doc.Template.Stamps.Add(templateElement);
            templateElement.Background = true;

            // Save and close the document.
            MemoryStream stream = new MemoryStream();
            await doc.SaveAsync(stream);

            doc.Close(true);
            Save(stream, "PageSettings.pdf");
        }
Esempio n. 5
0
 public void Write(PdfRectangle rect)
 {
     WriteSeparator(CharCat.Delimiter, '/');
     WriteRaw(PdfEncoders.Format("[{0:0.###} {1:0.###} {2:0.###} {3:0.###}]", rect.X1, rect.Y1, rect.X2, rect.Y2));
     this.lastCat = CharCat.Delimiter;
 }
        /// <summary>
        /// Builds a PdfFormXObject from the specified brush.
        /// </summary>
        PdfFormXObject BuildForm(VisualBrush brush)
        {
            //<<
            //  /BBox [0 100 100 0]
            //  /Length 65
            //  /Matrix [1 0 0 1 0 0]
            //  /Resources
            //  <<
            //    /ColorSpace
            //    <<
            //      /CS0 15 0 R
            //    >>
            //    /ExtGState
            //    <<
            //      /GS0 10 0 R
            //    >>
            //    /ProcSet [/PDF /ImageC /ImageI]
            //    /XObject
            //    <<
            //      /Im0 16 0 R
            //    >>
            //  >>
            //  /Subtype /Form
            //>>
            //stream
            //  q
            //  0 0 100 100 re
            //  W n
            //  q
            //    /GS0 gs
            //    100 0 0 -100 0 100 cm
            //    /Im0 Do
            //  Q
            //Q
            //endstream
            var pdfForm = Context.PdfDocument.Internals
                          .CreateIndirectObject <PdfFormXObject>();

            pdfForm.DpiX = 96;
            pdfForm.DpiY = 96;

            // view box
            var box = new PdfRectangle(brush.Viewbox.X,
                                       brush.Viewbox.Y + brush.Viewbox.Height - 1,
                                       brush.Viewbox.X + brush.Viewbox.Width - 1,
                                       brush.Viewbox.Y);

            pdfForm.Elements.SetRectangle(PdfFormXObject.Keys.BBox, box);

            pdfForm.Elements.SetMatrix(PdfFormXObject.Keys.Matrix, new XMatrix());

            var writer = new PdfContentWriter(Context, pdfForm);

            pdfForm.Elements.SetMatrix(PdfFormXObject.Keys.Matrix, new XMatrix());

            writer.BeginContentRaw();
            writer.WriteLiteral("-100 Tz\n");
            writer.WriteLiteral("q\n");
            writer.WriteVisual(brush.Visual);
            writer.WriteLiteral("Q\n");

#if DEBUG
            if (DevHelper.BorderPatterns)
            {
                writer.WriteLiteral("1 1 1 rg 0 0 m {0:0.###} 0 l {0:0.###} {1:0.###} l 0 {1:0.###} l h s\n",
                                    brush.Viewbox.Width, brush.Viewbox.Height);
            }
#endif

            writer.EndContent();

            return(pdfForm);
        }
        public ActionResult CustomTag(string Browser)
        {
            string image1 = ResolveApplicationImagePath("CustomTag.jpg");


            PdfFont fontnormal = new PdfTrueTypeFont(new Font("Arial", 9, FontStyle.Regular), true);
            PdfFont fontTitle  = new PdfTrueTypeFont(new Font("Arial", 22, FontStyle.Bold), true);
            PdfFont fontHead   = new PdfTrueTypeFont(new Font("Arial", 12, FontStyle.Bold), true);
            PdfFont fontHead2  = new PdfTrueTypeFont(new Font("Arial", 18, FontStyle.Bold), true);


            #region content string
            string pdfChapter = "We�ll begin with a conceptual overview of a simple PDF document. This chapter is designed to be a brief orientation before diving in and creating a real document from scratch \r\n \r\n A PDF file can be divided into four parts: a header, body, cross-reference table, and trailer. The header marks the file as a PDF, the body defines the visible document, the cross-reference table lists the location of everything in the file, and the trailer provides instructions for how to start reading the file.";
            string header     = "The header is simply a PDF version number and an arbitrary sequence of binary data.The binary data prevents na�ve applications from processing the PDF as a text file. This would result in a corrupted file, since a PDF typically consists of both plain text and binary data (e.g., a binary font file can be directly embedded in a PDF).";
            string body       = "The page tree serves as the root of the document. In the simplest case, it is just a list of the pages in the document. Each page is defined as an independent entity with metadata (e.g., page dimensions) and a reference to its resources and content, which are defined separately. Together, the page tree and page objects create the �paper� that composes the document.\r\n \r\n  Resources are objects that are required to render a page. For example, a single font is typically used across several pages, so storing the font information in an external resource is much more efficient. A content object defines the text and graphics that actually show up on the page. Together, content objects and resources define theappearance of an individual page. \r\n \r\n  Finally, the document�s catalog tells applications where to start reading the document. Often, this is just a pointer to the root page tree.";
            string resource   = "The third object is a resource defining a font configuration. \r\n \r\n The /Font key contains a whole dictionary, opposed to the name/value pairs we�ve seen previously (e.g., /Type /Page). The font we configured is called /F0, and the font face we selected is /Times-Roman. The /Subtype is the format of the font file, and /Type1 refers to the PostScript type 1 file format. The specification defines 14 �standard� fonts that all PDF applications should support.";
            string resource2  = "Any of these values can be used for the /BaseFont in a /Font dictionary. Nonstandard fonts can be embedded in a PDF document, but it is not easy to do manually. We will put off custom fonts until we can use iTextSharp�s high-level framework.";
            string crossRef   = "After the header and the body comes the cross-reference table. It records the byte location of each object in the body of the file. This enables random-access of the document, so when rendering a page, only the objects required for that page are read from the file. This makes PDFs much faster than their PostScript predecessors, which had to read in the entire file before processing it.";
            string trailer    = "Finally, we come to the last component of a PDF document. The trailer tells applications how to start reading the file. At minimum, it contains three things: \r\n 1. A reference to the catalog which links to the root of the document. \r\n 2. The location of the cross-reference table. \r\n 3. The size of the cross-reference table. \r\n \r\n Since a trailer is all you need to begin processing a document, PDFs are typically read back-to-front: first, the end of the file is found, and then you read backwards until you arrive at the beginning of the trailer. After that, you should have all the information you need to load any page in the PDF.";
            #endregion

            //Create a new PDF document.

            PdfDocument document = new PdfDocument();

            document.DocumentInformation.Title = "CustomTag";

            #region page1
            //Add a page to the document.

            PdfPage page1 = document.Pages.Add();

            //Load the image from the disk.

            PdfBitmap image = new PdfBitmap(image1);

            PdfStructureElement imageElement = new PdfStructureElement(PdfTagType.Figure);
            imageElement.AlternateText = "PDF Succintly image";
            //adding tag to the PDF image
            image.PdfTag = imageElement;
            //Draw the image
            page1.Graphics.DrawImage(image, 0, 0, page1.GetClientSize().Width, page1.GetClientSize().Height - 20);

            #endregion


            #region page2

            PdfPage page2 = document.Pages.Add();

            PdfStructureElement hTextElement1      = new PdfStructureElement(PdfTagType.HeadingLevel1);
            PdfStructureElement headingFirstLevel  = new PdfStructureElement(PdfTagType.HeadingLevel2);
            PdfStructureElement hTextElementLevel3 = new PdfStructureElement(PdfTagType.HeadingLevel3);

            headingFirstLevel.Parent  = hTextElement1;
            hTextElementLevel3.Parent = hTextElement1;

            PdfTextElement headerElement1 = new PdfTextElement("Chapter 1 Conceptual Overview", fontTitle, PdfBrushes.Black);

            headerElement1.PdfTag = headingFirstLevel;
            headerElement1.Draw(page2, new PointF(100, 0));

            //Initialize the structure element with tag type paragraph.

            PdfStructureElement textElement1 = new PdfStructureElement(PdfTagType.Paragraph);
            textElement1.Parent     = headingFirstLevel;
            textElement1.ActualText = pdfChapter;

            PdfTextElement element1 = new PdfTextElement(pdfChapter, fontnormal);
            element1.PdfTag = textElement1;
            element1.Brush  = new PdfSolidBrush(System.Drawing.Color.Black);
            element1.Draw(page2, new RectangleF(0, 40, page2.GetClientSize().Width, 70));

            PdfStructureElement hTextElement2 = new PdfStructureElement(PdfTagType.HeadingLevel2);
            hTextElement2.Parent     = hTextElement1;
            hTextElement2.ActualText = "Header";

            PdfTextElement headerElement2 = new PdfTextElement("Header", fontHead2, PdfBrushes.Black);
            headerElement2.PdfTag = hTextElement2;
            headerElement2.Draw(page2, new PointF(0, 140));

            PdfStructureElement textElement2 = new PdfStructureElement(PdfTagType.Paragraph);
            textElement2.Parent     = hTextElementLevel3;
            textElement2.ActualText = header;

            PdfTextElement element2 = new PdfTextElement(header, fontnormal);
            element2.PdfTag = textElement2;
            element2.Brush  = new PdfSolidBrush(System.Drawing.Color.Black);
            element2.Draw(page2, new RectangleF(0, 170, page2.GetClientSize().Width, 40));


            PdfStructureElement hTextElement3 = new PdfStructureElement(PdfTagType.HeadingLevel2);
            hTextElement3.Parent     = hTextElement1;
            hTextElement3.ActualText = "Body";

            PdfTextElement headerElement3 = new PdfTextElement("Body", fontHead2, PdfBrushes.Black);
            headerElement3.PdfTag = hTextElement3;
            headerElement3.Draw(page2, new PointF(0, 210));

            PdfStructureElement textElement3 = new PdfStructureElement(PdfTagType.Paragraph);
            textElement3.Parent     = hTextElementLevel3;
            textElement3.ActualText = body;

            PdfTextElement element3 = new PdfTextElement(body, fontnormal);
            element3.PdfTag = textElement3;
            element3.Brush  = new PdfSolidBrush(System.Drawing.Color.Black);
            element3.Draw(page2, new RectangleF(0, 240, page2.GetClientSize().Width, 120));

            PdfStructureElement hTextElement6 = new PdfStructureElement(PdfTagType.HeadingLevel2);
            hTextElement6.Parent     = hTextElement1;
            hTextElement6.ActualText = "Cross-Reference Table";

            PdfTextElement headerElement5 = new PdfTextElement("Cross-Reference Table", fontHead2, PdfBrushes.Black);
            headerElement5.PdfTag = hTextElement6;
            headerElement5.Draw(page2, new PointF(0, 380));

            PdfStructureElement textElement6 = new PdfStructureElement(PdfTagType.Paragraph);
            textElement6.Parent     = hTextElementLevel3;
            textElement6.ActualText = crossRef;

            PdfTextElement element6 = new PdfTextElement(crossRef, fontnormal);
            element6.PdfTag = textElement6;
            element6.Brush  = new PdfSolidBrush(System.Drawing.Color.Black);
            element6.Draw(page2, new RectangleF(0, 410, page2.GetClientSize().Width, 50));

            PdfStructureElement hTextElement7 = new PdfStructureElement(PdfTagType.HeadingLevel2);
            hTextElement7.Parent     = hTextElement1;
            hTextElement7.ActualText = "Trailer";

            PdfTextElement headerElement6 = new PdfTextElement("Trailer", fontHead2, PdfBrushes.Black);
            headerElement6.PdfTag = hTextElement7;
            headerElement6.Draw(page2, new PointF(0, 470));

            PdfStructureElement textElement7 = new PdfStructureElement(PdfTagType.Paragraph);
            textElement7.Parent     = hTextElementLevel3;
            textElement7.ActualText = trailer;

            PdfTextElement element7 = new PdfTextElement(trailer, fontnormal);
            element7.PdfTag = textElement7;
            element7.Brush  = new PdfSolidBrush(System.Drawing.Color.Black);
            element7.Draw(page2, new RectangleF(0, 500, page2.GetClientSize().Width, 110));



            #endregion

            #region page3

            PdfPage page3 = document.Pages.Add();

            PdfStructureElement hTextElement4 = new PdfStructureElement(PdfTagType.HeadingLevel2);
            hTextElement4.Parent     = hTextElement1;
            hTextElement4.ActualText = "Resource";


            PdfTextElement headerElement4 = new PdfTextElement("Resource", fontHead2, PdfBrushes.Black);
            headerElement4.PdfTag = hTextElement4;
            headerElement4.Draw(page3, new PointF(0, 0));

            PdfStructureElement textElement4 = new PdfStructureElement(PdfTagType.Paragraph);
            textElement4.Parent     = hTextElementLevel3;
            textElement4.ActualText = resource;

            PdfTextElement element4 = new PdfTextElement(resource, fontnormal);
            element4.PdfTag = textElement4;
            element4.Brush  = new PdfSolidBrush(System.Drawing.Color.Black);
            element4.Draw(page3, new RectangleF(0, 40, page2.GetClientSize().Width, 70));

            //Create a new PdfGrid.
            PdfGrid pdfGrid = new PdfGrid();

            PdfStructureElement element = new PdfStructureElement(PdfTagType.Table);

            //Adding tag to PDF grid.
            pdfGrid.PdfTag = element;

            //Add three columns.
            pdfGrid.Columns.Add(3);
            PdfGridRow[] headerRow     = pdfGrid.Headers.Add(3);
            PdfGridRow   pdfGridHeader = pdfGrid.Headers[0];
            pdfGridHeader.PdfTag = new PdfStructureElement(PdfTagType.TableRow);

            PdfGridCellStyle headerStyle = new PdfGridCellStyle();
            headerStyle.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 13);
            pdfGridHeader.ApplyStyle(headerStyle);

            pdfGridHeader.Cells[0].Value  = "Times Roman Family";
            pdfGridHeader.Cells[0].PdfTag = new PdfStructureElement(PdfTagType.TableHeader);

            pdfGridHeader.Cells[1].Value  = "Helvetica Family";
            pdfGridHeader.Cells[1].PdfTag = new PdfStructureElement(PdfTagType.TableHeader);
            pdfGridHeader.Cells[2].Value  = "Courier Family";
            pdfGridHeader.Cells[2].PdfTag = new PdfStructureElement(PdfTagType.TableHeader);

            PdfGridRow pdfGridRow1 = pdfGrid.Rows.Add();
            pdfGridRow1.PdfTag = new PdfStructureElement(PdfTagType.TableRow);

            pdfGridRow1.Cells[0].Value = "Times roman";

            pdfGridRow1.Cells[1].Value = "Helvetica";

            pdfGridRow1.Cells[2].Value = "Courier";

            pdfGridRow1.Cells[0].PdfTag = new PdfStructureElement(PdfTagType.TableDataCell);
            pdfGridRow1.Cells[1].PdfTag = new PdfStructureElement(PdfTagType.TableDataCell);
            pdfGridRow1.Cells[2].PdfTag = new PdfStructureElement(PdfTagType.TableDataCell);


            PdfGridRow pdfGridRow2 = pdfGrid.Rows.Add();
            pdfGridRow2.PdfTag = new PdfStructureElement(PdfTagType.TableRow);

            pdfGridRow2.Cells[0].Value = "Times-Bold";

            pdfGridRow2.Cells[1].Value = "Helvetica-Bold";

            pdfGridRow2.Cells[2].Value = "Courier-Bold";

            pdfGridRow2.Cells[0].PdfTag = new PdfStructureElement(PdfTagType.TableDataCell);
            pdfGridRow2.Cells[1].PdfTag = new PdfStructureElement(PdfTagType.TableDataCell);
            pdfGridRow2.Cells[2].PdfTag = new PdfStructureElement(PdfTagType.TableDataCell);

            PdfGridRow pdfGridRow3 = pdfGrid.Rows.Add();

            pdfGridRow3.PdfTag = new PdfStructureElement(PdfTagType.TableRow);

            pdfGridRow3.Cells[0].Value = "Times-Italic";

            pdfGridRow3.Cells[1].Value = "Helvetica-Oblique";

            pdfGridRow3.Cells[2].Value = "Courier-Oblique";

            pdfGridRow3.Cells[0].PdfTag = new PdfStructureElement(PdfTagType.TableDataCell);
            pdfGridRow3.Cells[1].PdfTag = new PdfStructureElement(PdfTagType.TableDataCell);
            pdfGridRow3.Cells[2].PdfTag = new PdfStructureElement(PdfTagType.TableDataCell);

            PdfGridRow pdfGridRow4 = pdfGrid.Rows.Add();

            pdfGridRow4.PdfTag = new PdfStructureElement(PdfTagType.TableRow);

            pdfGridRow4.Cells[0].Value = "Times-BoldItalic";

            pdfGridRow4.Cells[1].Value = "Helvetica-BoldOblique";

            pdfGridRow4.Cells[2].Value = "Courier-BoldOblique";

            pdfGridRow4.Cells[0].PdfTag = new PdfStructureElement(PdfTagType.TableDataCell);
            pdfGridRow4.Cells[1].PdfTag = new PdfStructureElement(PdfTagType.TableDataCell);
            pdfGridRow4.Cells[2].PdfTag = new PdfStructureElement(PdfTagType.TableDataCell);



            pdfGrid.BeginCellLayout += PdfGrid_BeginCellLayout;
            pdfGrid.Draw(page3, new PointF(20, 130));

            PdfStructureElement element8 = new PdfStructureElement(PdfTagType.Figure);
            element8.AlternateText = "Rectangle Sample";
            PdfRectangle rect = new PdfRectangle(20, 120, 490, 90);
            rect.PdfTag = element8;
            rect.Draw(page3.Graphics);



            #endregion



            //Stream the output to the browser.
            if (Browser == "Browser")
            {
                return(document.ExportAsActionResult("sample.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Open));
            }
            else
            {
                return(document.ExportAsActionResult("sample.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save));
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Algorithm for adjusting column boundary candidates
        /// </summary>
        /// <param name="B">Set of column boundary candidates B</param>
        /// <param name="P">A geometric data structure with the content of the current page P</param>
        /// <returns>Set of adjusted column boundary candidates A</returns>
        public IReadOnlyList <PdfRectangle> ColumnsHeightAdjustment(IReadOnlyList <PdfRectangle> B, PdfRectangle P, IEnumerable <Word> pageWords)
        {
            List <PdfRectangle> A = new List <PdfRectangle>();

            foreach (var b in B)
            {
                var midX         = b.Centroid.X;
                var quarterWidth = b.Width / 3; // / 4;

                // split b into three thin vertical columns, each centered
                // around the left, middle and right X-coordinates;
                PdfRectangle[] splits = new PdfRectangle[]
                {
                    //new PdfRectangle(b.Left - quarterWidth, b.Bottom, b.Left + quarterWidth, b.Top),
                    //new PdfRectangle(midX - quarterWidth, b.Bottom, midX + quarterWidth, b.Top),
                    //new PdfRectangle(b.Right - quarterWidth, b.Bottom, b.Right + quarterWidth, b.Top)
                    new PdfRectangle(b.Left, b.Bottom, b.Left + quarterWidth, b.Top),
                    new PdfRectangle(midX - quarterWidth, b.Bottom, midX + quarterWidth, b.Top),
                    new PdfRectangle(b.Right - quarterWidth, b.Bottom, b.Right, b.Top)
                };

                for (int i = 0; i < splits.Length; i++)
                {
                    var s = splits[i];

                    // Iterate through the range of Y values and determine the real length of s
                    decimal x      = s.Centroid.X;
                    decimal startY = s.Bottom;
                    decimal endY   = s.Top;

                    for (var y = s.Bottom; y > P.Bottom; y--)
                    {
                        bool blocked = pageWords.Any(word =>
                        {
                            if (word.BoundingBox.Top > y &&
                                word.BoundingBox.Bottom < y &&
                                word.BoundingBox.Left < x &&
                                word.BoundingBox.Right > x)
                            {
                                return(true);
                            }
                            return(false);
                        });
                        if (blocked)
                        {
                            break;
                        }
                        startY = y;
                    }

                    for (var y = s.Top; y < P.Top; y++)
                    {
                        bool blocked = pageWords.Any(word =>
                        {
                            if (word.BoundingBox.Top > y &&
                                word.BoundingBox.Bottom < y &&
                                word.BoundingBox.Left < x &&
                                word.BoundingBox.Right > x)
                            {
                                return(true);
                            }
                            return(false);
                        });
                        if (blocked)
                        {
                            break;
                        }
                        endY = y;
                    }

                    splits[i] = new PdfRectangle(s.Left, startY, s.Right, endY);
                }

                A.Add(splits.OrderByDescending(r => r.Height).First());
            }

            return(A);
        }
Esempio n. 9
0
        private static IReadOnlyList <PdfRectangle> GetMaximalRectangles(PdfRectangle bound,
                                                                         HashSet <PdfRectangle> obstacles, double minWidth, double minHeight, int maxRectangleCount,
                                                                         double whitespaceFuzziness, int maxBoundQueueSize)
        {
            QueueEntries queueEntries = new QueueEntries(maxBoundQueueSize);

            queueEntries.Enqueue(new QueueEntry(bound, obstacles, whitespaceFuzziness));

            HashSet <PdfRectangle> selected = new HashSet <PdfRectangle>();
            HashSet <QueueEntry>   holdList = new HashSet <QueueEntry>();

            while (queueEntries.Any())
            {
                var current = queueEntries.Dequeue();

                if (current.IsEmptyEnough(obstacles))
                {
                    if (selected.Any(c => Inside(c, current.Bound)))
                    {
                        continue;
                    }

                    // A check was added which impeded the algorithm from accepting
                    // rectangles which were not adjacent to an already accepted
                    // rectangle, or to the border of the page.
                    if (!IsAdjacentToPageBounds(bound, current.Bound) &&        // NOT in contact to border page AND
                        !selected.Any(q => IsAdjacentTo(q, current.Bound)))     // NOT in contact to any already accepted rectangle
                    {
                        // In order to maintain the correctness of the algorithm,
                        // rejected rectangles are put in a hold list.
                        holdList.Add(current);
                        continue;
                    }

                    selected.Add(current.Bound);

                    if (selected.Count >= maxRectangleCount)
                    {
                        return(selected.ToList());
                    }

                    obstacles.Add(current.Bound);

                    // Each time a new rectangle is identified and accepted, this hold list
                    // will be added back to the queue in case any of them will have become valid.
                    foreach (var hold in holdList)
                    {
                        queueEntries.Enqueue(hold);
                    }

                    // After a maximal rectangle has been found, it is added back to the list
                    // of obstacles. Whenever a QueueEntry is dequeued, its list of obstacles
                    // can be recomputed to include newly identified whitespace rectangles.
                    foreach (var overlapping in queueEntries)
                    {
                        if (OverlapsHard(current.Bound, overlapping.Bound))
                        {
                            overlapping.AddWhitespace(current.Bound);
                        }
                    }

                    continue;
                }

                var pivot = current.GetPivot();
                var b     = current.Bound;

                List <PdfRectangle> subRectangles = new List <PdfRectangle>();

                var rRight = new PdfRectangle(pivot.Right, b.Bottom, b.Right, b.Top);
                if (b.Right > pivot.Right && rRight.Height > minHeight && rRight.Width > minWidth)
                {
                    queueEntries.Enqueue(new QueueEntry(rRight,
                                                        new HashSet <PdfRectangle>(current.Obstacles.Where(o => OverlapsHard(rRight, o))),
                                                        whitespaceFuzziness));
                }

                var rLeft = new PdfRectangle(b.Left, b.Bottom, pivot.Left, b.Top);
                if (b.Left < pivot.Left && rLeft.Height > minHeight && rLeft.Width > minWidth)
                {
                    queueEntries.Enqueue(new QueueEntry(rLeft,
                                                        new HashSet <PdfRectangle>(current.Obstacles.Where(o => OverlapsHard(rLeft, o))),
                                                        whitespaceFuzziness));
                }

                var rAbove = new PdfRectangle(b.Left, b.Bottom, b.Right, pivot.Bottom);
                if (b.Bottom < pivot.Bottom && rAbove.Height > minHeight && rAbove.Width > minWidth)
                {
                    queueEntries.Enqueue(new QueueEntry(rAbove,
                                                        new HashSet <PdfRectangle>(current.Obstacles.Where(o => OverlapsHard(rAbove, o))),
                                                        whitespaceFuzziness));
                }

                var rBelow = new PdfRectangle(b.Left, pivot.Top, b.Right, b.Top);
                if (b.Top > pivot.Top && rBelow.Height > minHeight && rBelow.Width > minWidth)
                {
                    queueEntries.Enqueue(new QueueEntry(rBelow,
                                                        new HashSet <PdfRectangle>(current.Obstacles.Where(o => OverlapsHard(rBelow, o))),
                                                        whitespaceFuzziness));
                }
            }

            return(selected.ToList());
        }
Esempio n. 10
0
 private static double MinimumOverlappingArea(PdfRectangle r1, PdfRectangle r2, double whitespaceFuzziness)
 {
     return(Math.Min(r1.Area, r2.Area) * whitespaceFuzziness);
 }
Esempio n. 11
0
 public void AddWhitespace(PdfRectangle rectangle)
 {
     Obstacles.Add(rectangle);
 }
Esempio n. 12
0
 private static bool Inside(PdfRectangle rectangle1, PdfRectangle rectangle2)
 {
     return(rectangle2.Right <= rectangle1.Right && rectangle2.Left >= rectangle1.Left &&
            rectangle2.Top <= rectangle1.Top && rectangle2.Bottom >= rectangle1.Bottom);
 }
Esempio n. 13
0
 public ContentStreamProcessor(PdfRectangle cropBox, IResourceStore resourceStore, UserSpaceUnit userSpaceUnit)
 {
     this.resourceStore = resourceStore;
     this.userSpaceUnit = userSpaceUnit;
     graphicsStack.Push(new CurrentGraphicsState());
 }
Esempio n. 14
0
 private static bool Overlaps(PdfRectangle r1, PdfRectangle r2, decimal whitespaceFuzziness)
 {
     return(OverlappingArea(r1, r2) > Math.Min(r1.Area, r2.Area) * whitespaceFuzziness);
 }
Esempio n. 15
0
 /// <summary>
 /// Creates a link to a file.
 /// </summary>
 public static PdfLinkAnnotation CreateFileLink(PdfRectangle rect, string fileName)
 {
     PdfLinkAnnotation link = new PdfLinkAnnotation();
     link._linkType = LinkType.File;
     // TODO: Adjust bleed box here (if possible)
     link.Rectangle = rect;
     link._url = fileName;
     return link;
 }
Esempio n. 16
0
 /// <summary>
 /// Creates a link to the web.
 /// </summary>
 public static PdfLinkAnnotation CreateWebLink(PdfRectangle rect, string url)
 {
     PdfLinkAnnotation link = new PdfLinkAnnotation();
     link._linkType = PdfLinkAnnotation.LinkType.Web;
     link.Rectangle = rect;
     link._url = url;
     return link;
 }
Esempio n. 17
0
      private void sigPlusNET1_PenUp(object sender, EventArgs e)
      {
          sigPlusNET1.SetLCDCaptureMode(2);

         if (sigPlusNET1.KeyPadQueryHotSpot(2) > 0) //If CLEAR hotspot is tapped...
         {
            sigPlusNET1.ClearSigWindow(1);
            sigPlusNET1.LCDRefresh(1, 10, 0, 53, 17); //Refresh LCD
            sigPlusNET1.LCDRefresh(2, 0, 0, 240, 64); //Brings background image into foreground
            sigPlusNET1.ClearTablet();
         }
         else if (sigPlusNET1.KeyPadQueryHotSpot(3) > 0) //If OK hotspot is tapped...
         {
            sigPlusNET1.ClearSigWindow(1);

            sigPlusNET1.GetSigString();
            sigPlusNET1.LCDRefresh(1, 210, 3, 14, 14); //Refresh LCD

            if (sigPlusNET1.NumberOfTabletPoints() > 0)
            {
               sigPlusNET1.LCDRefresh(0, 0, 0, 240, 64);
               var f = new Font("Arial", 9.0F, FontStyle.Regular);

               sigPlusNET1.SetImageXSize(500);
               sigPlusNET1.SetImageYSize(100);
               var myImg = sigPlusNET1.GetSigImage();
               myImg.Save(Application.StartupPath + "\\test.bmp", System.Drawing.Imaging.ImageFormat.Bmp);

                    var openFileDialog1 = new OpenFileDialog()
                {
                    Filter = @"PDF File|*.pdf",
                    Title = @"Open PDF File"
                };
                openFileDialog1.ShowDialog();

                    PdfRectangle rect = new PdfRectangle(0, 0, 0, 0);
                    RectangleF rectF = new RectangleF();
                string path = Application.StartupPath + "\\test.pdf";

                    if (openFileDialog1.FileName != "")
                {
                    PdfReader reader = new PdfReader(openFileDialog1.FileName);
                    PdfStamper stamper = new PdfStamper(reader, new System.IO.FileStream(path, System.IO.FileMode.Create));
                    PdfContentByte underContent = stamper.GetUnderContent(1);

                    AcroFields form = stamper.AcroFields;
                    float[] fieldPositions = reader.AcroFields.GetFieldPositions("Digital Signature");
                    Console.WriteLine("FIELD POSITION : " + fieldPositions);
                    if (fieldPositions == null || ((ICollection) fieldPositions).Count <= 0) throw new ApplicationException("Error locating field");

                        if (fieldPositions != null)
                        {
                            //add rectangle - this is where the signature will be
                        }

                        try
                        {
                        // Add signature image to the document

                        sigPlusNET1.SetJustifyY(20);
                        sigPlusNET1.SetJustifyX(20);
                        sigPlusNET1.SetImageFileFormat(0); //0=bmp, 4=jpg, 6=tif

                        int minX, maxX, minY, maxY, aX, aY, ratio, aIndex, bIndex, fixedY;

                        minX = sigPlusNET1.GetPointXValue(0, 1);
                        maxX = sigPlusNET1.GetPointXValue(0, 1);
                        minY = sigPlusNET1.GetPointYValue(0, 1);
                        maxY = sigPlusNET1.GetPointYValue(0, 1);

                        for (aIndex = 0; aIndex < sigPlusNET1.GetNumberOfStrokes(); aIndex++)
                        {
                            for (bIndex = 0; bIndex < sigPlusNET1.GetNumPointsForStroke(aIndex); bIndex++)
                            {
                                aX = sigPlusNET1.GetPointXValue(aIndex, bIndex);
                                aY = sigPlusNET1.GetPointYValue(aIndex, bIndex);

                                if (aX < minX)
                                {
                                    minX = aX;
                                }

                                if (aX > maxX)
                                {
                                    maxX = aX;
                                }

                                if (aY < minY)
                                {
                                    minY = aY;
                                }

                                if (aY > maxY)
                                {
                                    maxY = aY;
                                }

                            }
                        }

                        ratio = ((maxX - minX) / (maxY - minY));
                        fixedY = 200;
                        sigPlusNET1.SetImagePenWidth((int) (fixedY * 0.5));
                        sigPlusNET1.SetJustifyMode(5);

                        sigPlusNET1.SetImageXSize((int) ((ratio * fixedY) * 1.5));
                        sigPlusNET1.SetImageYSize((int) (fixedY * 1.5));
                        sigPlusNET1.SetAntiAliasLineScale(0.4f);
                        sigPlusNET1.SetAntiAliasSpotSize(0.25f);

                        iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(myImg, System.Drawing.Imaging.ImageFormat.Bmp);

                        image.Transparency = new int[] {255, 255};
                        image.SetAbsolutePosition(fieldPositions[0],fieldPositions[1]);
                        image.ScalePercent(60);

                        underContent.AddImage(image);

                        stamper.Close();
                        reader.Close();
                    }
                    catch (DocumentException de)
                    {
                            Console.WriteLine(de.Message);
                        }
                    catch (IOException ioe)
                    {
                            Console.WriteLine(ioe.Message);
                        }

                    }
          #region
                    //     //Opens save file dialog
                    //     var saveFileDialog1 =
                    //     new SaveFileDialog
                    //     {
                    //         Filter = @"Bitmap Image|*.bmp|GIF Image|*.Gif|JPeg Image|*.jpg|PNG Image|*.Png",
                    //         Title = @"Save Signature Image"
                    //     };
                    // saveFileDialog1.ShowDialog();

                    //if (saveFileDialog1.FileName != "")
                    //{
                    //   var fs = (FileStream)saveFileDialog1.OpenFile();

                    //    if (saveFileDialog1.FilterIndex == 1)
                    //    {
                    //        myImg.Save(fs, System.Drawing.Imaging.ImageFormat.Bmp);
                    //        _imgFile = saveFileDialog1.FileName;
                    //    }
                    //    else if (saveFileDialog1.FilterIndex == 2)
                    //    {
                    //        myImg.Save(fs, System.Drawing.Imaging.ImageFormat.Gif);
                    //        _imgFile = saveFileDialog1.FileName;
                    //    }
                    //    else if (saveFileDialog1.FilterIndex == 3)
                    //    {
                    //        myImg.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
                    //        _imgFile = saveFileDialog1.FileName;
                    //    }
                    //    else if (saveFileDialog1.FilterIndex == 4)
                    //    {
                    //        myImg.Save(fs, System.Drawing.Imaging.ImageFormat.Png);
                    //        _imgFile = saveFileDialog1.FileName;
                    //    }
                    //    fs.Close();
                    //}
#endregion
               WindowState = FormWindowState.Minimized;
               Process.Start(Application.StartupPath + "\\test.pdf");
               sigPlusNET1.LCDWriteString(0, 2, 35, 25, f, "Signature capture complete.");
               Thread.Sleep(1000);
               Application.Exit();
            }
            else
            {
               sigPlusNET1.LCDRefresh(0, 0, 0, 240, 64);
               sigPlusNET1.LCDSendGraphic(0, 2, 4, 20, _please);
               sigPlusNET1.ClearTablet();
               sigPlusNET1.LCDRefresh(2, 0, 0, 240, 64);
               sigPlusNET1.SetLCDCaptureMode(2);   //Sets mode so ink will not disappear after a few seconds
            }
         }
         sigPlusNET1.ClearSigWindow(1);
      }
Esempio n. 18
0
        protected void buttonCreatePdf_Click(object sender, EventArgs e)
        {
            // create a PDF document
            PdfDocument document = new PdfDocument();

            // set a demo serial number
            document.SerialNumber = "YCgJMTAE-BiwJAhIB-EhlWTlBA-UEBRQFBA-U1FOUVJO-WVlZWQ==";

            // create a page in document
            PdfPage page1 = document.AddPage();

            // create the true type fonts that can be used in document text
            System.Drawing.Font sysFont      = new System.Drawing.Font("Times New Roman", 10, System.Drawing.GraphicsUnit.Point);
            PdfFont             pdfFont      = document.CreateFont(sysFont);
            PdfFont             pdfFontEmbed = document.CreateFont(sysFont, true);

            float crtYPos = 20;
            float crtXPos = 5;

            PdfLayoutInfo textLayoutInfo     = null;
            PdfLayoutInfo graphicsLayoutInfo = null;

            #region Layout lines

            PdfText titleTextLines = new PdfText(crtXPos, crtYPos, "Lines:", pdfFontEmbed);
            titleTextLines.ForeColor = System.Drawing.Color.Navy;
            textLayoutInfo           = page1.Layout(titleTextLines);

            // advance the Y position in the PDF page
            crtYPos = textLayoutInfo.LastPageRectangle.Bottom + 10;

            // layout a simple line
            PdfLine pdfLine = new PdfLine(new System.Drawing.PointF(crtXPos, crtYPos), new System.Drawing.PointF(crtXPos + 60, crtYPos));
            graphicsLayoutInfo = page1.Layout(pdfLine);

            // layout a thick line
            PdfLine pdfThickLine = new PdfLine(new System.Drawing.PointF(crtXPos + 70, crtYPos), new System.Drawing.PointF(crtXPos + 130, crtYPos));
            pdfThickLine.LineStyle.LineWidth = 3;
            graphicsLayoutInfo = page1.Layout(pdfThickLine);

            // layout a dotted colored line
            PdfLine pdfDottedLine = new PdfLine(new System.Drawing.PointF(crtXPos + 140, crtYPos), new System.Drawing.PointF(crtXPos + 200, crtYPos));
            pdfDottedLine.LineStyle.LineDashPattern = PdfLineDashPattern.Dot;
            pdfDottedLine.ForeColor = System.Drawing.Color.Green;
            graphicsLayoutInfo      = page1.Layout(pdfDottedLine);

            // layout a dashed colored line
            PdfLine pdfDashedLine = new PdfLine(new System.Drawing.PointF(crtXPos + 210, crtYPos), new System.Drawing.PointF(crtXPos + 270, crtYPos));
            pdfDashedLine.LineStyle.LineDashPattern = PdfLineDashPattern.Dash;
            pdfDashedLine.ForeColor = System.Drawing.Color.Green;
            graphicsLayoutInfo      = page1.Layout(pdfDashedLine);

            // layout a dash-dot-dot colored line
            PdfLine pdfDashDotDotLine = new PdfLine(new System.Drawing.PointF(crtXPos + 280, crtYPos), new System.Drawing.PointF(crtXPos + 340, crtYPos));
            pdfDashDotDotLine.LineStyle.LineDashPattern = PdfLineDashPattern.DashDotDot;
            pdfDashDotDotLine.ForeColor = System.Drawing.Color.Green;
            graphicsLayoutInfo          = page1.Layout(pdfDashDotDotLine);

            // layout a thick line with rounded cap style
            PdfLine pdfRoundedLine = new PdfLine(new System.Drawing.PointF(crtXPos + 350, crtYPos), new System.Drawing.PointF(crtXPos + 410, crtYPos));
            pdfRoundedLine.LineStyle.LineWidth    = 5;
            pdfRoundedLine.LineStyle.LineCapStyle = PdfLineCapStyle.RoundCap;
            pdfRoundedLine.ForeColor = System.Drawing.Color.Blue;
            graphicsLayoutInfo       = page1.Layout(pdfRoundedLine);

            // advance the Y position in the PDF page
            crtYPos += 10;

            #endregion

            #region Layout circles

            PdfText titleTextCircles = new PdfText(crtXPos, crtYPos, "Circles:", pdfFontEmbed);
            titleTextCircles.ForeColor = System.Drawing.Color.Navy;
            textLayoutInfo             = page1.Layout(titleTextCircles);

            // advance the Y position in the PDF page
            crtYPos = textLayoutInfo.LastPageRectangle.Bottom + 10;

            // draw a simple circle with solid line
            PdfCircle pdfCircle = new PdfCircle(new System.Drawing.PointF(crtXPos + 30, crtYPos + 30), 30);
            page1.Layout(pdfCircle);

            // draw a simple circle with dotted border line
            PdfCircle pdfDottedCircle = new PdfCircle(new System.Drawing.PointF(crtXPos + 100, crtYPos + 30), 30);
            pdfDottedCircle.ForeColor = System.Drawing.Color.Green;
            pdfDottedCircle.LineStyle.LineDashPattern = PdfLineDashPattern.Dot;
            graphicsLayoutInfo = page1.Layout(pdfDottedCircle);

            // draw a circle with colored border line and fill color
            PdfCircle pdfDisc = new PdfCircle(new System.Drawing.PointF(crtXPos + 170, crtYPos + 30), 30);
            pdfDisc.ForeColor  = System.Drawing.Color.Navy;
            pdfDisc.BackColor  = System.Drawing.Color.WhiteSmoke;
            graphicsLayoutInfo = page1.Layout(pdfDisc);

            // draw a circle with thick border line
            PdfCircle pdfThickBorderDisc = new PdfCircle(new System.Drawing.PointF(crtXPos + 240, crtYPos + 30), 30);
            pdfThickBorderDisc.LineStyle.LineWidth = 5;
            pdfThickBorderDisc.BackColor           = System.Drawing.Color.LightSalmon;
            pdfThickBorderDisc.ForeColor           = System.Drawing.Color.LightBlue;

            graphicsLayoutInfo = page1.Layout(pdfThickBorderDisc);

            crtYPos = graphicsLayoutInfo.LastPageRectangle.Bottom + 10;

            #endregion

            #region Layout ellipses and arcs

            PdfText titleTextEllipses = new PdfText(crtXPos, crtYPos, "Ellipses, arcs and slices:", pdfFontEmbed);
            titleTextEllipses.ForeColor = System.Drawing.Color.Navy;
            textLayoutInfo = page1.Layout(titleTextEllipses);

            // advance the Y position in the PDF page
            crtYPos = textLayoutInfo.LastPageRectangle.Bottom + 10;

            // draw a simple ellipse with solid line
            PdfEllipse pdfEllipse = new PdfEllipse(new System.Drawing.PointF(crtXPos + 50, crtYPos + 30), 50, 30);
            graphicsLayoutInfo = page1.Layout(pdfEllipse);

            // draw an ellipse with fill color and colored border line
            PdfEllipse pdfFilledEllipse = new PdfEllipse(new System.Drawing.PointF(crtXPos + 160, crtYPos + 30), 50, 30);
            pdfFilledEllipse.BackColor = System.Drawing.Color.WhiteSmoke;
            pdfFilledEllipse.ForeColor = System.Drawing.Color.Green;
            graphicsLayoutInfo         = page1.Layout(pdfFilledEllipse);

            // draw an ellipse arc with colored border line
            PdfEllipseArc pdfEllipseArc1 = new PdfEllipseArc(new System.Drawing.RectangleF(crtXPos + 220, crtYPos, 100, 60), 0, 90);
            pdfEllipseArc1.ForeColor           = System.Drawing.Color.OrangeRed;
            pdfEllipseArc1.LineStyle.LineWidth = 3;
            graphicsLayoutInfo = page1.Layout(pdfEllipseArc1);

            // draw an ellipse arc with fill color and colored border line
            PdfEllipseArc pdfEllipseArc2 = new PdfEllipseArc(new System.Drawing.RectangleF(crtXPos + 220, crtYPos, 100, 60), 90, 90);
            pdfEllipseArc2.ForeColor = System.Drawing.Color.Navy;
            graphicsLayoutInfo       = page1.Layout(pdfEllipseArc2);

            // draw an ellipse arc with fill color and colored border line
            PdfEllipseArc pdfEllipseArc3 = new PdfEllipseArc(new System.Drawing.RectangleF(crtXPos + 220, crtYPos, 100, 60), 180, 90);
            pdfEllipseArc3.ForeColor           = System.Drawing.Color.Green;
            pdfEllipseArc3.LineStyle.LineWidth = 3;
            graphicsLayoutInfo = page1.Layout(pdfEllipseArc3);

            // draw an ellipse arc with fill color and colored border line
            PdfEllipseArc pdfEllipseArc4 = new PdfEllipseArc(new System.Drawing.RectangleF(crtXPos + 220, crtYPos, 100, 60), 270, 90);
            pdfEllipseArc4.ForeColor = System.Drawing.Color.Yellow;
            graphicsLayoutInfo       = page1.Layout(pdfEllipseArc4);


            // draw an ellipse slice
            PdfEllipseSlice pdfEllipseSlice1 = new PdfEllipseSlice(new System.Drawing.RectangleF(crtXPos + 330, crtYPos, 100, 60), 0, 90);
            pdfEllipseSlice1.BackColor = System.Drawing.Color.Coral;
            graphicsLayoutInfo         = page1.Layout(pdfEllipseSlice1);

            // draw an ellipse slice
            PdfEllipseSlice pdfEllipseSlice2 = new PdfEllipseSlice(new System.Drawing.RectangleF(crtXPos + 330, crtYPos, 100, 60), 90, 90);
            pdfEllipseSlice2.BackColor = System.Drawing.Color.LightBlue;
            graphicsLayoutInfo         = page1.Layout(pdfEllipseSlice2);

            // draw an ellipse slice
            PdfEllipseSlice pdfEllipseSlice3 = new PdfEllipseSlice(new System.Drawing.RectangleF(crtXPos + 330, crtYPos, 100, 60), 180, 90);
            pdfEllipseSlice3.BackColor = System.Drawing.Color.LightGreen;
            graphicsLayoutInfo         = page1.Layout(pdfEllipseSlice3);

            // draw an ellipse slice
            PdfEllipseSlice pdfEllipseSlice4 = new PdfEllipseSlice(new System.Drawing.RectangleF(crtXPos + 330, crtYPos, 100, 60), 270, 90);
            pdfEllipseSlice4.BackColor = System.Drawing.Color.Yellow;
            graphicsLayoutInfo         = page1.Layout(pdfEllipseSlice4);

            crtYPos = graphicsLayoutInfo.LastPageRectangle.Bottom + 10;

            #endregion

            #region Layout rectangles

            PdfText titleTextRectangles = new PdfText(crtXPos, crtYPos, "Rectangles:", pdfFontEmbed);
            titleTextRectangles.ForeColor = System.Drawing.Color.Navy;
            textLayoutInfo = page1.Layout(titleTextRectangles);

            // advance the Y position in the PDF page
            crtYPos = textLayoutInfo.LastPageRectangle.Bottom + 10;

            // draw a simple rectangle with solid line
            PdfRectangle pdfRectangle = new PdfRectangle(crtXPos, crtYPos, 100, 60);
            graphicsLayoutInfo = page1.Layout(pdfRectangle);

            // draw a rectangle with fill color and colored dotted border line
            PdfRectangle pdfFilledRectangle = new PdfRectangle(crtXPos + 110, crtYPos, 100, 60);
            pdfFilledRectangle.BackColor = System.Drawing.Color.WhiteSmoke;
            pdfFilledRectangle.ForeColor = System.Drawing.Color.Green;
            pdfFilledRectangle.LineStyle.LineDashPattern = PdfLineDashPattern.Dot;
            graphicsLayoutInfo = page1.Layout(pdfFilledRectangle);

            // draw a rectangle with fill color and without border line
            PdfRectangle pdfFilledNoBorderRectangle = new PdfRectangle(crtXPos + 220, crtYPos, 100, 60);
            pdfFilledNoBorderRectangle.BackColor = System.Drawing.Color.LightGreen;
            graphicsLayoutInfo = page1.Layout(pdfFilledNoBorderRectangle);

            // draw a rectangle filled with a thick border line and reounded corners
            PdfRectangle pdfThickBorderRectangle = new PdfRectangle(crtXPos + 330, crtYPos, 100, 60);
            pdfThickBorderRectangle.BackColor               = System.Drawing.Color.LightSalmon;
            pdfThickBorderRectangle.ForeColor               = System.Drawing.Color.LightBlue;
            pdfThickBorderRectangle.LineStyle.LineWidth     = 5;
            pdfThickBorderRectangle.LineStyle.LineJoinStyle = PdfLineJoinStyle.RoundJoin;
            graphicsLayoutInfo = page1.Layout(pdfThickBorderRectangle);

            crtYPos = graphicsLayoutInfo.LastPageRectangle.Bottom + 10;

            #endregion

            #region Layout Bezier curves

            PdfText titleTextBezier = new PdfText(crtXPos, crtYPos, "Bezier curves and polygons:", pdfFontEmbed);
            titleTextBezier.ForeColor = System.Drawing.Color.Navy;
            textLayoutInfo            = page1.Layout(titleTextBezier);

            // advance the Y position in the PDF page
            crtYPos = textLayoutInfo.LastPageRectangle.Bottom + 10;

            // the points controlling the Bezier curve
            System.Drawing.PointF pt1 = new System.Drawing.PointF(crtXPos, crtYPos + 50);
            System.Drawing.PointF pt2 = new System.Drawing.PointF(crtXPos + 50, crtYPos);
            System.Drawing.PointF pt3 = new System.Drawing.PointF(crtXPos + 100, crtYPos + 100);
            System.Drawing.PointF pt4 = new System.Drawing.PointF(crtXPos + 150, crtYPos + 50);

            // draw controlling points
            PdfCircle pt1Circle = new PdfCircle(pt1, 2);
            pt1Circle.BackColor = System.Drawing.Color.LightSalmon;
            page1.Layout(pt1Circle);
            PdfCircle pt2Circle = new PdfCircle(pt2, 2);
            pt2Circle.BackColor = System.Drawing.Color.LightSalmon;
            page1.Layout(pt2Circle);
            PdfCircle pt3Circle = new PdfCircle(pt3, 2);
            pt3Circle.BackColor = System.Drawing.Color.LightSalmon;
            page1.Layout(pt3Circle);
            PdfCircle pt4Circle = new PdfCircle(pt4, 2);
            pt4Circle.BackColor = System.Drawing.Color.LightSalmon;
            page1.Layout(pt4Circle);

            // draw the Bezier curve

            PdfBezierCurve bezierCurve = new PdfBezierCurve(pt1, pt2, pt3, pt4);
            bezierCurve.ForeColor           = System.Drawing.Color.LightBlue;
            bezierCurve.LineStyle.LineWidth = 2;
            graphicsLayoutInfo = page1.Layout(bezierCurve);

            #endregion

            #region Layout a polygons

            // layout a polygon without fill color

            // the polygon points
            System.Drawing.PointF[] polyPoints = new System.Drawing.PointF[] {
                new System.Drawing.PointF(crtXPos + 200, crtYPos + 50),
                new System.Drawing.PointF(crtXPos + 250, crtYPos),
                new System.Drawing.PointF(crtXPos + 300, crtYPos + 50),
                new System.Drawing.PointF(crtXPos + 250, crtYPos + 100)
            };

            // draw polygon points
            foreach (System.Drawing.PointF polyPoint in polyPoints)
            {
                PdfCircle pointCircle = new PdfCircle(polyPoint, 2);
                pointCircle.BackColor = System.Drawing.Color.LightSalmon;
                page1.Layout(pointCircle);
            }

            // draw the polygon line
            PdfPolygon pdfPolygon = new PdfPolygon(polyPoints);
            pdfPolygon.ForeColor              = System.Drawing.Color.LightBlue;
            pdfPolygon.LineStyle.LineWidth    = 2;
            pdfPolygon.LineStyle.LineCapStyle = PdfLineCapStyle.ProjectingSquareCap;
            graphicsLayoutInfo = page1.Layout(pdfPolygon);

            // layout a polygon with fill color

            // the polygon points
            System.Drawing.PointF[] polyFillPoints = new System.Drawing.PointF[] {
                new System.Drawing.PointF(crtXPos + 330, crtYPos + 50),
                new System.Drawing.PointF(crtXPos + 380, crtYPos),
                new System.Drawing.PointF(crtXPos + 430, crtYPos + 50),
                new System.Drawing.PointF(crtXPos + 380, crtYPos + 100)
            };

            // draw a polygon with fill color and thick rounded border
            PdfPolygon pdfFillPolygon = new PdfPolygon(polyFillPoints);
            pdfFillPolygon.ForeColor               = System.Drawing.Color.LightBlue;
            pdfFillPolygon.BackColor               = System.Drawing.Color.LightSalmon;
            pdfFillPolygon.LineStyle.LineWidth     = 5;
            pdfFillPolygon.LineStyle.LineCapStyle  = PdfLineCapStyle.RoundCap;
            pdfFillPolygon.LineStyle.LineJoinStyle = PdfLineJoinStyle.RoundJoin;
            graphicsLayoutInfo = page1.Layout(pdfFillPolygon);

            #endregion

            try
            {
                // write the PDF document to a memory buffer
                byte[] pdfBuffer = document.WriteToMemory();

                // inform the browser about the binary data format
                HttpContext.Current.Response.AddHeader("Content-Type", "application/pdf");

                // let the browser know how to open the PDF document and the file name
                HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment; filename=PdfGraphics.pdf; size={0}",
                                                                                            pdfBuffer.Length.ToString()));

                // write the PDF buffer to HTTP response
                HttpContext.Current.Response.BinaryWrite(pdfBuffer);

                // call End() method of HTTP response to stop ASP.NET page processing
                HttpContext.Current.Response.End();
            }
            finally
            {
                document.Close();
            }
        }
Esempio n. 19
0
        private static Glyph ReadSimpleGlyph(TrueTypeDataBytes data, short contourCount, PdfRectangle bounds)
        {
            var endPointsOfContours = data.ReadUnsignedShortArray(contourCount);

            var instructionLength = data.ReadUnsignedShort();

            var instructions = data.ReadByteArray(instructionLength);

            var pointCount = 0;

            if (contourCount > 0)
            {
                pointCount = endPointsOfContours[contourCount - 1] + 1;
            }

            var flags = ReadFlags(data, pointCount);

            var xCoordinates = ReadCoordinates(data, pointCount, flags, SimpleGlyphFlags.XShortVector,
                                               SimpleGlyphFlags.XSignOrSame);

            var yCoordinates = ReadCoordinates(data, pointCount, flags, SimpleGlyphFlags.YShortVector,
                                               SimpleGlyphFlags.YSignOrSame);

            var points = new GlyphPoint[xCoordinates.Length];

            for (var i = xCoordinates.Length - 1; i >= 0; i--)
            {
                var isOnCurve = (flags[i] & SimpleGlyphFlags.OnCurve) == SimpleGlyphFlags.OnCurve;
                points[i] = new GlyphPoint(xCoordinates[i], yCoordinates[i], isOnCurve);
            }

            return(new Glyph(true, instructions, endPointsOfContours, points, bounds));
        }
Esempio n. 20
0
        private void button1_Click(object sender, System.EventArgs e)
        {
            // Create a new document class object.
            PdfDocument doc = new PdfDocument();

            // Create few sections with one page in each.
            for (int i = 0; i < 4; ++i)
            {
                section = doc.Sections.Add();

                //Create page label
                PdfPageLabel label = new PdfPageLabel();

                label.Prefix      = "Sec" + i + "-";
                section.PageLabel = label;
                page = section.Pages.Add();
                section.Pages[0].Graphics.SetTransparency(0.35f);
                section.PageSettings.Transition.PageDuration = 1;
                section.PageSettings.Transition.Duration     = 1;
                section.PageSettings.Transition.Style        = PdfTransitionStyle.Box;
            }

            //Set page size
            doc.PageSettings.Size = PdfPageSize.A6;

            //Set viewer prefernce.
            doc.ViewerPreferences.HideToolbar = true;
            doc.ViewerPreferences.PageMode    = PdfPageMode.FullScreen;

            //Set page orientation
            doc.PageSettings.Orientation = PdfPageOrientation.Landscape;

            //Create a brush
            PdfSolidBrush brush = new PdfSolidBrush(Color.Black);

            brush.Color = new PdfColor(System.Drawing.Color.LightGreen);

            //Create a Rectangle
            PdfRectangle rect = new PdfRectangle(0, 0, 1000f, 1000f);

            rect.Brush = brush;
            PdfPen pen = new PdfPen(System.Drawing.Color.Black);

            pen.Width = 6f;

            //Get the first page in first section
            page = doc.Sections[0].Pages[0];

            //Draw the rectangle
            rect.Draw(page.Graphics);

            //Draw a line
            page.Graphics.DrawLine(pen, 0, 100, 300, 100);

            // Add margins.
            doc.PageSettings.SetMargins(0f);

            //Get the first page in second section
            page = doc.Sections[1].Pages[0];
            doc.Sections[1].PageSettings.Rotate = PdfPageRotateAngle.RotateAngle90;
            rect.Draw(page.Graphics);

            page.Graphics.DrawLine(pen, 0, 100, 300, 100);

            // Change the angle f the section. This should rotate the previous page.
            doc.Sections[2].PageSettings.Rotate = PdfPageRotateAngle.RotateAngle180;
            page = doc.Sections[2].Pages[0];
            rect.Draw(page.Graphics);
            page.Graphics.DrawLine(pen, 0, 100, 300, 100);

            section = doc.Sections[3];
            section.PageSettings.Orientation = PdfPageOrientation.Portrait;
            page = section.Pages[0];
            rect.Draw(page.Graphics);
            page.Graphics.DrawLine(pen, 0, 100, 300, 100);

            //Set the font
            PdfFont       font       = new PdfStandardFont(PdfFontFamily.Helvetica, 16f);
            PdfSolidBrush fieldBrush = new PdfSolidBrush(Color.Black);

            //Create page number field
            PdfPageNumberField pageNumber = new PdfPageNumberField(font, fieldBrush);

            //Create page count field
            PdfPageCountField count = new PdfPageCountField(font, fieldBrush);

            //Draw page template
            PdfPageTemplateElement templateElement = new PdfPageTemplateElement(400, 400);

            templateElement.Graphics.DrawString("Page :\tof", font, PdfBrushes.Black, new PointF(260, 200));

            //Draw current page number
            pageNumber.Draw(templateElement.Graphics, new PointF(306, 200));

            //Draw number of pages
            count.Draw(templateElement.Graphics, new PointF(345, 200));
            doc.Template.Stamps.Add(templateElement);
            templateElement.Background = true;


            //Save the PDF
            doc.Save("Sample.pdf");

            //Message box confirmation to view the created PDF document.
            if (MessageBox.Show("Do you want to view the PDF file?", "PDF File Created",
                                MessageBoxButtons.YesNo, MessageBoxIcon.Information)
                == DialogResult.Yes)
            {
                //Launching the PDF file using the default Application.[Acrobat Reader]
                System.Diagnostics.Process.Start("Sample.pdf");
                this.Close();
            }
            else
            {
                // Exit
                this.Close();
            }
        }
        public PdfArray RotateAnnotations(PdfWriter writer, Rectangle pageSize)
        {
            PdfArray array       = new PdfArray();
            int      rotation    = pageSize.Rotation % 360;
            int      currentPage = writer.CurrentPageNumber;

            for (int k = 0; k < annotations.Count; ++k)
            {
                PdfAnnotation dic  = (PdfAnnotation)annotations[k];
                int           page = dic.PlaceInPage;
                if (page > currentPage)
                {
                    delayedAnnotations.Add(dic);
                    continue;
                }
                if (dic.IsForm())
                {
                    if (!dic.IsUsed())
                    {
                        Hashtable templates = dic.Templates;
                        if (templates != null)
                        {
                            acroForm.AddFieldTemplates(templates);
                        }
                    }
                    PdfFormField field = (PdfFormField)dic;
                    if (field.Parent == null)
                    {
                        acroForm.AddDocumentField(field.IndirectReference);
                    }
                }
                if (dic.IsAnnotation())
                {
                    array.Add(dic.IndirectReference);
                    if (!dic.IsUsed())
                    {
                        PdfRectangle rect = (PdfRectangle)dic.Get(PdfName.RECT);
                        if (rect != null)
                        {
                            switch (rotation)
                            {
                            case 90:
                                dic.Put(PdfName.RECT, new PdfRectangle(
                                            pageSize.Top - rect.Bottom,
                                            rect.Left,
                                            pageSize.Top - rect.Top,
                                            rect.Right));
                                break;

                            case 180:
                                dic.Put(PdfName.RECT, new PdfRectangle(
                                            pageSize.Right - rect.Left,
                                            pageSize.Top - rect.Bottom,
                                            pageSize.Right - rect.Right,
                                            pageSize.Top - rect.Top));
                                break;

                            case 270:
                                dic.Put(PdfName.RECT, new PdfRectangle(
                                            rect.Bottom,
                                            pageSize.Right - rect.Left,
                                            rect.Top,
                                            pageSize.Right - rect.Right));
                                break;
                            }
                        }
                    }
                }
                if (!dic.IsUsed())
                {
                    dic.SetUsed();
                    writer.AddToBody(dic, dic.IndirectReference);
                }
            }
            return(array);
        }
        virtual public PdfArray RotateAnnotations(PdfWriter writer, Rectangle pageSize)
        {
            PdfArray array       = new PdfArray();
            int      rotation    = pageSize.Rotation % 360;
            int      currentPage = writer.CurrentPageNumber;

            for (int k = 0; k < annotations.Count; ++k)
            {
                PdfAnnotation dic  = annotations[k];
                int           page = dic.PlaceInPage;
                if (page > currentPage)
                {
                    delayedAnnotations.Add(dic);
                    continue;
                }
                if (dic.IsForm())
                {
                    if (!dic.IsUsed())
                    {
                        Dictionary <PdfTemplate, object> templates = dic.Templates;
                        if (templates != null)
                        {
                            acroForm.AddFieldTemplates(templates);
                        }
                    }
                    PdfFormField field = (PdfFormField)dic;
                    if (field.Parent == null)
                    {
                        acroForm.AddDocumentField(field.IndirectReference);
                    }
                }
                if (dic.IsAnnotation())
                {
                    array.Add(dic.IndirectReference);
                    if (!dic.IsUsed())
                    {
                        PdfArray     tmp = dic.GetAsArray(PdfName.RECT);
                        PdfRectangle rect;
                        if (tmp.Size == 4)
                        {
                            rect = new PdfRectangle(tmp.GetAsNumber(0).FloatValue, tmp.GetAsNumber(1).FloatValue, tmp.GetAsNumber(2).FloatValue, tmp.GetAsNumber(3).FloatValue);
                        }
                        else
                        {
                            rect = new PdfRectangle(tmp.GetAsNumber(0).FloatValue, tmp.GetAsNumber(1).FloatValue);
                        }
                        switch (rotation)
                        {
                        case 90:
                            dic.Put(PdfName.RECT, new PdfRectangle(
                                        pageSize.Top - rect.Bottom,
                                        rect.Left,
                                        pageSize.Top - rect.Top,
                                        rect.Right));
                            break;

                        case 180:
                            dic.Put(PdfName.RECT, new PdfRectangle(
                                        pageSize.Right - rect.Left,
                                        pageSize.Top - rect.Bottom,
                                        pageSize.Right - rect.Right,
                                        pageSize.Top - rect.Top));
                            break;

                        case 270:
                            dic.Put(PdfName.RECT, new PdfRectangle(
                                        rect.Bottom,
                                        pageSize.Right - rect.Left,
                                        rect.Top,
                                        pageSize.Right - rect.Right));
                            break;
                        }
                    }
                }
                if (!dic.IsUsed())
                {
                    dic.SetUsed();
                    writer.AddToBody(dic, dic.IndirectReference);
                }
            }
            return(array);
        }
        public static float[] GetFeatures(Page page, PdfRectangle bbox, IEnumerable <Letter> letters, IEnumerable <PdfPath> paths, IEnumerable <IPdfImage> images)
        {
            // Letters features
            float charsCount           = 0;
            float pctNumericChars      = 0;
            float pctAlphabeticalChars = 0;
            float pctSymbolicChars     = 0;
            float pctBulletChars       = 0;
            float deltaToHeight        = -1; // might be problematic

            if (letters != null && letters.Count() > 0)
            {
                var avgHeight = page.Letters.Select(l => l.GlyphRectangle.Height).Average();

                char[] chars = letters.SelectMany(l => l.Value).ToArray();

                charsCount           = chars.Length;
                pctNumericChars      = (float)Math.Round(chars.Count(c => char.IsNumber(c)) / charsCount, 5);
                pctAlphabeticalChars = (float)Math.Round(chars.Count(c => char.IsLetter(c)) / charsCount, 5);
                pctSymbolicChars     = (float)Math.Round(chars.Count(c => !char.IsLetterOrDigit(c)) / charsCount, 5);
                pctBulletChars       = (float)Math.Round(chars.Count(c => Bullets.Any(bullet => bullet == c)) / charsCount, 5);
                deltaToHeight        = avgHeight != 0 ? (float)Math.Round(letters.Select(l => l.GlyphRectangle.Height).Average() / avgHeight, 5) : -1;
            }

            // Paths features
            float pathsCount     = 0;
            float pctBezierPaths = 0;
            float pctHorPaths    = 0;
            float pctVertPaths   = 0;
            float pctOblPaths    = 0;

            if (paths != null && paths.Count() > 0)
            {
                foreach (var path in paths)
                {
                    foreach (var command in path.Commands)
                    {
                        if (command is BezierCurve bezierCurve)
                        {
                            pathsCount++;
                            pctBezierPaths++;
                        }
                        else if (command is Line line)
                        {
                            pathsCount++;
                            if (line.From.X == line.To.X)
                            {
                                pctVertPaths++;
                            }
                            else if (line.From.Y == line.To.Y)
                            {
                                pctHorPaths++;
                            }
                            else
                            {
                                pctOblPaths++;
                            }
                        }
                    }
                }

                pctBezierPaths = (float)Math.Round(pctBezierPaths / pathsCount, 5);
                pctHorPaths    = (float)Math.Round(pctHorPaths / pathsCount, 5);
                pctVertPaths   = (float)Math.Round(pctVertPaths / pathsCount, 5);
                pctOblPaths    = (float)Math.Round(pctOblPaths / pathsCount, 5);
            }

            // Images features
            float imagesCount        = 0;
            float imageAvgProportion = 0;

            if (images != null && images.Count() > 0)
            {
                imagesCount        = images.Count();
                imageAvgProportion = (float)(images.Average(i => i.Bounds.Area) / bbox.Area);
            }

            return(new float[]
            {
                charsCount, pctNumericChars, pctAlphabeticalChars, pctSymbolicChars, pctBulletChars, deltaToHeight,
                pathsCount, pctBezierPaths, pctHorPaths, pctVertPaths, pctOblPaths,
                imagesCount, imageAvgProportion
            });
        }
Esempio n. 24
0
        private Tuple <string, PdfRectangle> GetBoundingBoxOther(IReadOnlyList <Letter> letters)
        {
            var builder = new StringBuilder();

            for (var i = 0; i < letters.Count; i++)
            {
                builder.Append(letters[i].Value);
            }

            var baseLinePoints = letters.SelectMany(r => new[]
            {
                r.StartBaseLine,
                r.EndBaseLine,
            }).ToList();

            // Fitting a line through the base lines points
            // to find the orientation (slope)
            double x0              = baseLinePoints.Average(p => p.X);
            double y0              = baseLinePoints.Average(p => p.Y);
            double sumProduct      = 0;
            double sumDiffSquaredX = 0;

            for (int i = 0; i < baseLinePoints.Count; i++)
            {
                var point  = baseLinePoints[i];
                var x_diff = point.X - x0;
                var y_diff = point.Y - y0;
                sumProduct      += x_diff * y_diff;
                sumDiffSquaredX += x_diff * x_diff;
            }

            var slope = sumProduct / sumDiffSquaredX;

            // Rotate the points to build the axis-aligned bounding box (AABB)
            var angleRad = Math.Atan(slope);
            var cos      = Math.Cos(angleRad);
            var sin      = Math.Sin(angleRad);

            var inverseRotation = new TransformationMatrix(
                cos, -sin, 0,
                sin, cos, 0,
                0, 0, 1);

            var transformedPoints = letters.SelectMany(r => new[]
            {
                r.StartBaseLine,
                r.EndBaseLine,
                r.GlyphRectangle.TopLeft,
                r.GlyphRectangle.TopRight
            }).Distinct().Select(p => inverseRotation.Transform(p));
            var aabb = new PdfRectangle(transformedPoints.Min(p => p.X),
                                        transformedPoints.Min(p => p.Y),
                                        transformedPoints.Max(p => p.X),
                                        transformedPoints.Max(p => p.Y));

            // Rotate back the AABB to obtain to oriented bounding box (OBB)
            var rotateBack = new TransformationMatrix(
                cos, sin, 0,
                -sin, cos, 0,
                0, 0, 1);

            // Candidates bounding boxes
            var obb  = rotateBack.Transform(aabb);
            var obb1 = new PdfRectangle(obb.BottomLeft, obb.TopLeft, obb.BottomRight, obb.TopRight);
            var obb2 = new PdfRectangle(obb.TopRight, obb.BottomRight, obb.TopLeft, obb.BottomLeft);
            var obb3 = new PdfRectangle(obb.BottomRight, obb.BottomLeft, obb.TopRight, obb.TopLeft);

            // Find the orientation of the OBB, using the baseline angle
            var firstLetter = letters[0];
            var lastLetter  = letters[letters.Count - 1];

            var baseLineAngle = Math.Atan2(
                lastLetter.EndBaseLine.Y - firstLetter.StartBaseLine.Y,
                lastLetter.EndBaseLine.X - firstLetter.StartBaseLine.X) * 180 / Math.PI;

            double deltaAngle  = Math.Abs(baseLineAngle - obb.Rotation);
            double deltaAngle1 = Math.Abs(baseLineAngle - obb1.Rotation);

            if (deltaAngle1 < deltaAngle)
            {
                deltaAngle = deltaAngle1;
                obb        = obb1;
            }

            double deltaAngle2 = Math.Abs(baseLineAngle - obb2.Rotation);

            if (deltaAngle2 < deltaAngle)
            {
                deltaAngle = deltaAngle2;
                obb        = obb2;
            }

            double deltaAngle3 = Math.Abs(baseLineAngle - obb3.Rotation);

            if (deltaAngle3 < deltaAngle)
            {
                obb = obb3;
            }

            return(new Tuple <string, PdfRectangle>(builder.ToString(), obb));
        }
Esempio n. 25
0
        private void ShowGlyph(IFont font, PdfRectangle glyphRectangle, PdfPoint position, decimal width, string unicode, decimal fontSize, decimal pointSize)
        {
            var letter = new Letter(unicode, glyphRectangle, position, width, fontSize, font.Name.Data, pointSize);

            Letters.Add(letter);
        }
Esempio n. 26
0
        /// <summary>
        /// Creates the normal appearance form X object for the annotation that represents
        /// this acro form text field.
        /// </summary>
        void RenderAppearance()
        {
#if true_
            PdfFormXObject xobj = new PdfFormXObject(Owner);
            Owner.Internals.AddObject(xobj);
            xobj.Elements["/BBox"]     = new PdfLiteral("[0 0 122.653 12.707]");
            xobj.Elements["/FormType"] = new PdfLiteral("1");
            xobj.Elements["/Matrix"]   = new PdfLiteral("[1 0 0 1 0 0]");
            PdfDictionary res = new PdfDictionary(Owner);
            xobj.Elements["/Resources"] = res;
            res.Elements["/Font"]       = new PdfLiteral("<< /Helv 28 0 R >> /ProcSet [/PDF /Text]");
            xobj.Elements["/Subtype"]   = new PdfLiteral("/Form");
            xobj.Elements["/Type"]      = new PdfLiteral("/XObject");

            string s =
                "/Tx BMC " + '\n' +
                "q" + '\n' +
                "1 1 120.653 10.707 re" + '\n' +
                "W" + '\n' +
                "n" + '\n' +
                "BT" + '\n' +
                "/Helv 7.93 Tf" + '\n' +
                "0 g" + '\n' +
                "2 3.412 Td" + '\n' +
                "(Hello ) Tj" + '\n' +
                "20.256 0 Td" + '\n' +
                "(XXX) Tj" + '\n' +
                "ET" + '\n' +
                "Q" + '\n' +
                "";//"EMC";
            int    length = s.Length;
            byte[] stream = new byte[length];
            for (int idx = 0; idx < length; idx++)
            {
                stream[idx] = (byte)s[idx];
            }
            xobj.CreateStream(stream);

            // Get existing or create new appearance dictionary
            PdfDictionary ap = Elements[PdfAnnotation.Keys.AP] as PdfDictionary;
            if (ap == null)
            {
                ap = new PdfDictionary(_document);
                Elements[PdfAnnotation.Keys.AP] = ap;
            }

            // Set XRef to normal state
            ap.Elements["/N"] = xobj.Reference;



            //// HACK
            //string m =
            //"<?xpacket begin=\"\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>" + '\n' +
            //"<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\"Adobe XMP Core 4.0-c321 44.398116, Tue Aug 04 2009 14:24:39\"> " + '\n' +
            //"   <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"> " + '\n' +
            //"      <rdf:Description rdf:about=\"\" " + '\n' +
            //"            xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\"> " + '\n' +
            //"         <pdf:Producer>PDFsharp 1.40.2150-g (www.pdfsharp.com) (Original: Powered By Crystal)</pdf:Producer> " + '\n' +
            //"      </rdf:Description> " + '\n' +
            //"      <rdf:Description rdf:about=\"\" " + '\n' +
            //"            xmlns:xap=\"http://ns.adobe.com/xap/1.0/\"> " + '\n' +
            //"         <xap:ModifyDate>2011-07-11T23:15:09+02:00</xap:ModifyDate> " + '\n' +
            //"         <xap:CreateDate>2011-05-19T16:26:51+03:00</xap:CreateDate> " + '\n' +
            //"         <xap:MetadataDate>2011-07-11T23:15:09+02:00</xap:MetadataDate> " + '\n' +
            //"         <xap:CreatorTool>Crystal Reports</xap:CreatorTool> " + '\n' +
            //"      </rdf:Description> " + '\n' +
            //"      <rdf:Description rdf:about=\"\" " + '\n' +
            //"            xmlns:dc=\"http://purl.org/dc/elements/1.1/\"> " + '\n' +
            //"         <dc:format>application/pdf</dc:format> " + '\n' +
            //"      </rdf:Description> " + '\n' +
            //"      <rdf:Description rdf:about=\"\" " + '\n' +
            //"            xmlns:xapMM=\"http://ns.adobe.com/xap/1.0/mm/\"> " + '\n' +
            //"         <xapMM:DocumentID>uuid:68249d89-baed-4384-9a2d-fbf8ace75c45</xapMM:DocumentID> " + '\n' +
            //"         <xapMM:InstanceID>uuid:3d5f2f46-c140-416f-baf2-7f9c970cef1d</xapMM:InstanceID> " + '\n' +
            //"      </rdf:Description> " + '\n' +
            //"   </rdf:RDF> " + '\n' +
            //"</x:xmpmeta> " + '\n' +
            //"                                                                          " + '\n' +
            //"                                                                          " + '\n' +
            //"                                                                          " + '\n' +
            //"                                                                          " + '\n' +
            //"                                                                          " + '\n' +
            //"                                                                          " + '\n' +
            //"                                                                          " + '\n' +
            //"                                                                          " + '\n' +
            //"                                                                          " + '\n' +
            //"                                                                          " + '\n' +
            //"<?xpacket end=\"w\"?>";

            //PdfDictionary mdict = (PdfDictionary)_document.Internals.GetObject(new PdfObjectID(32));

            //length = m.Length;
            //stream = new byte[length];
            //for (int idx = 0; idx < length; idx++)
            //  stream[idx] = (byte)m[idx];

            //mdict.Stream.Value = stream;
#else
            PdfRectangle rect = Elements.GetRectangle(PdfAnnotation.Keys.Rect);
            XForm        form = new XForm(_document, rect.Size);
            XGraphics    gfx  = XGraphics.FromForm(form);

            if (BackColor != XColor.Empty)
            {
                gfx.DrawRectangle(new XSolidBrush(BackColor), rect.ToXRect() - rect.Location);
            }
            // Draw Border
            if (!BorderColor.IsEmpty)
            {
                gfx.DrawRectangle(new XPen(BorderColor), rect.ToXRect() - rect.Location);
            }

            string text = Text;
            if (text.Length > 0)
            {
                var xRect = rect.ToXRect();
                if ((Flags & PdfAcroFieldFlags.Comb) != 0 && MaxLength > 0)
                {
                    var combWidth = xRect.Width / MaxLength;
                    var format    = XStringFormats.TopLeft;
                    format.Comb      = true;
                    format.CombWidth = combWidth;
                    gfx.Save();
                    gfx.IntersectClip(xRect);
                    gfx.DrawString(text, Font, new XSolidBrush(ForeColor), xRect + new XPoint(0, 1.5), format);
                    gfx.Restore();
                }
                else
                {
                    gfx.DrawString(Text, Font, new XSolidBrush(ForeColor),
                                   rect.ToXRect() - rect.Location + new XPoint(2, 0), XStringFormats.TopLeft);
                }
            }

            form.DrawingFinished();
            form.PdfForm.Elements.Add("/FormType", new PdfLiteral("1"));

            // Get existing or create new appearance dictionary.
            PdfDictionary ap = Elements[PdfAnnotation.Keys.AP] as PdfDictionary;
            if (ap == null)
            {
                ap = new PdfDictionary(_document);
                Elements[PdfAnnotation.Keys.AP] = ap;
            }

            // Set XRef to normal state
            ap.Elements["/N"] = form.PdfForm.Reference;

            PdfFormXObject xobj = form.PdfForm;
            if (xobj.Stream == null)
            {
                xobj.CreateStream(new byte[] { });
            }

            string s = xobj.Stream.ToString();
            // Thank you Adobe: Without putting the content in 'EMC brackets'
            // the text is not rendered by PDF Reader 9 or higher.
            s = "/Tx BMC\n" + s + "\nEMC";
            xobj.Stream.Value = new RawEncoding().GetBytes(s);
#endif
        }
Esempio n. 27
0
 private string ToPoints(PdfRectangle pdfRectangle, double height)
 {
     return(ToPoints(new[] { pdfRectangle.BottomLeft, pdfRectangle.TopLeft, pdfRectangle.TopRight, pdfRectangle.BottomRight }, height));
 }
Esempio n. 28
0
        /// <summary>
        /// Creates a simple void rectangle delimited by this Area.
        /// </summary>
        /// <param name="BorderColor"></param>
        /// <param name="FillingColor"></param>
        /// <returns></returns>
        public PdfRectangle ToRectangle(Color BorderColor, Color FillingColor)
        {
            PdfRectangle pr = new PdfRectangle(this.PdfDocument, this, BorderColor, FillingColor);

            return(pr);
        }
        /// <summary>
        /// Generate a csv file of features. You will need the pdf documents and the ground truths in PAGE xml format.
        /// </summary>
        /// <param name="dataFolder">The path to the data folder. It should contain both the pdf files
        /// and their corresponding ground truth xml files.</param>
        /// <param name="numberOfPdfDocs">Number of documents to concider.</param>
        public static void GetCsv(string dataFolder, int numberOfPdfDocs, string outputFileName)
        {
            string outputFullPath      = GetDataPath(outputFileName);
            string outputErrorFullPath = Path.Combine(OutputFolderPath, "invalide_pdfs_" + Path.ChangeExtension(outputFileName, "txt"));

            ConcurrentBag <string> invalidPdfs = new ConcurrentBag <string>();
            ConcurrentBag <string> data        = new ConcurrentBag <string>();

            int done = 0;

            DirectoryInfo d             = new DirectoryInfo(dataFolder);
            var           pdfFileLinks  = d.GetFiles("*.pdf", SearchOption.TopDirectoryOnly);
            var           maxPageNumber = d.GetFiles("*.xml", SearchOption.TopDirectoryOnly).Select(f => ParseXmlFileName(f.Name)).Max() + 1;

            numberOfPdfDocs = Math.Min(pdfFileLinks.Count(), numberOfPdfDocs);
            numberOfPdfDocs = numberOfPdfDocs == 0 ? pdfFileLinks.Count() : numberOfPdfDocs;

            var indexesSelected = GenerateRandom(numberOfPdfDocs, 0, pdfFileLinks.Length);

            Parallel.ForEach(indexesSelected, index =>
            {
                var pdfFile                = pdfFileLinks[index];
                string fileName            = pdfFile.Name;
                string xmlFileNameTemplate = fileName.Replace(".pdf", "_");

                var pageXmlLinksCandidates = Enumerable.Range(0, maxPageNumber).Select(i =>
                                                                                       Path.Combine(dataFolder, fileName.Replace(".pdf", "_" + string.Format("{0:00000}", i) + ".xml"))).ToArray();
                var pageXmlLinks = pageXmlLinksCandidates.Where(l => File.Exists(l)).Select(l => new FileInfo(l)).ToArray();

                if (pageXmlLinks.Length == 0)
                {
                    Console.BackgroundColor = ConsoleColor.DarkRed;
                    Console.WriteLine("Error for document '" + fileName + "': No PageXml files found");
                    Console.ResetColor();
                    return;
                }

                try
                {
                    var pagesNumbers             = pageXmlLinks.Select(l => ParseXmlFileName(l.Name)).ToList();
                    List <float[]> localFeatures = new List <float[]>();
                    List <int> localCategories   = new List <int>();
                    bool isValidDocument         = true;

                    using (var doc = PdfDocument.Open(pdfFile.FullName))
                    {
                        // Checks if this pdf document looks to be valid
                        if ((pagesNumbers.Max() + 1) > doc.NumberOfPages)
                        {
                            // ignore this document as page number is not correct
                            Console.BackgroundColor = ConsoleColor.Red;
                            Console.WriteLine("Error for document '" + fileName + "': Ignoring this document as page number is not correct");
                            Console.ResetColor();
                            isValidDocument = false;
                        }

                        foreach (var pageXmlLink in pageXmlLinks)
                        {
                            if (!isValidDocument)
                            {
                                break;
                            }

                            int pageNo = ParseXmlFileName(pageXmlLink.Name);
                            var page   = doc.GetPage(pageNo + 1);

                            if (page.Rotation.Value != 0)
                            {
                                Console.BackgroundColor = ConsoleColor.Yellow;
                                Console.ForegroundColor = ConsoleColor.Black;
                                Console.WriteLine("Error for document '" + fileName + "': Ignoring page " + (pageNo + 1) + " because it is rotated");
                                Console.ResetColor();
                                continue;
                            }

                            var pageXml = Deserialize(pageXmlLink.FullName);

                            var blocks = pageXml.Page.Items;

                            foreach (var block in blocks)
                            {
                                int category      = -1;
                                PdfRectangle bbox = new PdfRectangle();

                                if (block is PageXmlTextRegion textBlock)
                                {
                                    bbox = ParsePageXmlCoord(textBlock.Coords.Points, page.Height);
                                    switch (textBlock.Type)
                                    {
                                    case PageXmlTextSimpleType.Paragraph:
                                        category = 0;
                                        break;

                                    case PageXmlTextSimpleType.Heading:
                                        category = 1;
                                        break;

                                    case PageXmlTextSimpleType.LisLabel:
                                        category = 2;
                                        break;

                                    default:
                                        throw new ArgumentException("Unknown category");
                                    }

                                    if (FeatureHelper.GetLettersInside(bbox, page.Letters).Count() == 0)
                                    {
                                        Console.BackgroundColor = ConsoleColor.Red;
                                        Console.ForegroundColor = ConsoleColor.Black;
                                        Console.WriteLine("Error for document '" + fileName + "': Ignoring this document as an empty paragraph was found");
                                        Console.ResetColor();
                                        isValidDocument = false;
                                        break;
                                    }
                                }
                                else if (block is PageXmlTableRegion tableBlock)
                                {
                                    bbox     = ParsePageXmlCoord(tableBlock.Coords.Points, page.Height);
                                    category = 3;
                                }
                                else if (block is PageXmlImageRegion imageBlock)
                                {
                                    bbox     = ParsePageXmlCoord(imageBlock.Coords.Points, page.Height);
                                    category = 4;
                                }
                                else
                                {
                                    throw new ArgumentException("Unknown region type");
                                }

                                var letters = FeatureHelper.GetLettersInside(bbox, page.Letters).ToList();
                                var paths   = FeatureHelper.GetPathsInside(bbox, page.ExperimentalAccess.Paths).ToList();
                                var images  = FeatureHelper.GetImagesInside(bbox, page.GetImages());
                                var f       = FeatureHelper.GetFeatures(page, bbox, letters, paths, images);

                                if (category == -1)
                                {
                                    throw new ArgumentException("Unknown category number.");
                                }

                                if (f != null)
                                {
                                    localFeatures.Add(f);
                                    localCategories.Add(category);
                                }
                            }
                        }
                    }

                    if (isValidDocument)
                    {
                        if (localFeatures.Count != localCategories.Count)
                        {
                            throw new ArgumentException("features and categories don't have the same size");
                        }

                        foreach (var line in localFeatures.Zip(localCategories, (f, c) => string.Join(",", f) + "," + c))
                        {
                            data.Add(line);
                        }
                    }
                    else
                    {
                        invalidPdfs.Add(pdfFile.Name);
                    }
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Error for document '" + fileName + "': " + ex.Message);
                    Console.ResetColor();
                }
                Console.WriteLine(done++);
            });

            List <string> csv = new List <string>()
            {
                header
            };

            csv.AddRange(data);
            File.WriteAllLines(outputFullPath, csv);
            File.WriteAllLines(outputErrorFullPath, invalidPdfs);

            Console.WriteLine("Done. Csv file saved in " + outputFullPath);
        }
        internal PdfFormXObject(PdfDocument thisDocument, PdfImportedObjectTable importedObjectTable, XPdfForm form)
            : base(thisDocument)
        {
            Debug.Assert(Object.ReferenceEquals(thisDocument, importedObjectTable.Owner));
            Elements.SetName(Keys.Type, "/XObject");
            Elements.SetName(Keys.Subtype, "/Form");

            if (form.IsTemplate)
            {
                Debug.Assert(importedObjectTable == null);
                // TODO more initialization here???
                return;
            }
            Debug.Assert(importedObjectTable != null);

            XPdfForm pdfForm = (XPdfForm)form;
            // Get import page
            PdfPages importPages = importedObjectTable.ExternalDocument.Pages;

            if (pdfForm.PageNumber < 1 || pdfForm.PageNumber > importPages.Count)
            {
                PSSR.ImportPageNumberOutOfRange(pdfForm.PageNumber, importPages.Count, form.path);
            }
            PdfPage importPage = importPages[pdfForm.PageNumber - 1];

            // Import resources
            PdfItem res = importPage.Elements["/Resources"];

            if (res != null) // unlikely but possible
            {
#if true
                // Get root object
                PdfObject root;
                if (res is PdfReference)
                {
                    root = ((PdfReference)res).Value;
                }
                else
                {
                    root = (PdfDictionary)res;
                }

                root = ImportClosure(importedObjectTable, thisDocument, root);
                // If the root was a direct object, make it indirect.
                if (root.Reference == null)
                {
                    thisDocument.irefTable.Add(root);
                }

                Debug.Assert(root.Reference != null);
                Elements["/Resources"] = root.Reference;
#else
                // Get transitive closure
                PdfObject[] resources = importPage.Owner.Internals.GetClosure(resourcesRoot);
                int         count     = resources.Length;
#if DEBUG_
                for (int idx = 0; idx < count; idx++)
                {
                    Debug.Assert(resources[idx].XRef != null);
                    Debug.Assert(resources[idx].XRef.Document != null);
                    Debug.Assert(resources[idx].Document != null);
                    if (resources[idx].ObjectID.ObjectNumber == 12)
                    {
                        GetType();
                    }
                }
#endif
                // 1st step. Already imported objects are reused and new ones are cloned.
                for (int idx = 0; idx < count; idx++)
                {
                    PdfObject obj = resources[idx];
                    if (importedObjectTable.Contains(obj.ObjectID))
                    {
                        // external object was already imported
                        PdfReference iref = importedObjectTable[obj.ObjectID];
                        Debug.Assert(iref != null);
                        Debug.Assert(iref.Value != null);
                        Debug.Assert(iref.Document == this.Owner);
                        // replace external object by the already clone counterpart
                        resources[idx] = iref.Value;
                    }
                    else
                    {
                        // External object was not imported ealier and must be cloned
                        PdfObject clone = obj.Clone();
                        Debug.Assert(clone.Reference == null);
                        clone.Document = this.Owner;
                        if (obj.Reference != null)
                        {
                            // add it to this (the importer) document
                            this.Owner.irefTable.Add(clone);
                            Debug.Assert(clone.Reference != null);
                            // save old object identifier
                            importedObjectTable.Add(obj.ObjectID, clone.Reference);
                            //Debug.WriteLine("Cloned: " + obj.ObjectID.ToString());
                        }
                        else
                        {
                            // The root object (the /Resources value) is not an indirect object
                            Debug.Assert(idx == 0);
                            // add it to this (the importer) document
                            this.Owner.irefTable.Add(clone);
                            Debug.Assert(clone.Reference != null);
                        }
                        // replace external object by its clone
                        resources[idx] = clone;
                    }
                }
#if DEBUG_
                for (int idx = 0; idx < count; idx++)
                {
                    Debug.Assert(resources[idx].XRef != null);
                    Debug.Assert(resources[idx].XRef.Document != null);
                    Debug.Assert(resources[idx].Document != null);
                    if (resources[idx].ObjectID.ObjectNumber == 12)
                    {
                        GetType();
                    }
                }
#endif

                // 2nd step. Fix up indirect references that still refers to the import document.
                for (int idx = 0; idx < count; idx++)
                {
                    PdfObject obj = resources[idx];
                    Debug.Assert(obj.Owner != null);
                    FixUpObject(importedObjectTable, importedObjectTable.Owner, obj);
                }

                // Set resources key to the root of the clones
                Elements["/Resources"] = resources[0].Reference;
#endif
            }

            // Take /Rotate into account
            PdfRectangle rect   = importPage.Elements.GetRectangle(PdfPage.Keys.MediaBox);
            int          rotate = importPage.Elements.GetInteger(PdfPage.Keys.Rotate);
            //rotate = 0;
            if (rotate == 0)
            {
                // Set bounding box to media box
                this.Elements["/BBox"] = rect;
            }
            else
            {
                // TODO: Have to adjust bounding box? (I think not, but I'm not sure -> wait for problem)
                this.Elements["/BBox"] = rect;

                // Rotate the image such that it is upright
                XMatrix matrix = new XMatrix();  //XMatrix.Identity;
                double  width  = rect.Width;
                double  height = rect.Height;
                matrix.RotateAtPrepend(-rotate, new XPoint(width / 2, height / 2));

                // Translate the image such that its center lies on the center of the rotated bounding box
                double offset = (height - width) / 2;
                if (height > width)
                {
                    matrix.TranslatePrepend(offset, offset);
                }
                else
                {
                    matrix.TranslatePrepend(-offset, -offset);
                }

                //string item = "[" + PdfEncoders.ToString(matrix) + "]";
                //Elements[Keys.Matrix] = new PdfLiteral(item);
                Elements.SetMatrix(Keys.Matrix, matrix);
            }

            // Preserve filter because the content keeps unmodified
            PdfContent content = importPage.Contents.CreateSingleContent();
#if !DEBUG
            content.Compressed = true;
#endif
            PdfItem filter = content.Elements["/Filter"];
            if (filter != null)
            {
                this.Elements["/Filter"] = filter.Clone();
            }

            // (no cloning needed because the bytes keep untouched)
            this.Stream = content.Stream; // new PdfStream(bytes, this);
            Elements.SetInteger("/Length", content.Stream.Value.Length);
        }
Esempio n. 31
0
 public bool TryGetBoundingBox(int characterIdentifier, out PdfRectangle boundingBox) => TryGetBoundingBox(characterIdentifier, null, out boundingBox);
Esempio n. 32
0
 public bool TryGetBoundingBox(int characterIdentifier, Func <int, int?> characterCodeToGlyphId, out PdfRectangle boundingBox)
 => font.TryGetBoundingBox(characterIdentifier, characterCodeToGlyphId, out boundingBox);
Esempio n. 33
0
        private void AddQuestions(int qcount, int cellsinq, List <string> cellslabels, int rowscnt, PdfRectangle rect)
        {
            int rowhight  = 7;
            int rowscount = rowscnt;//Convert.ToInt32((_page.Height.Millimeter - 80d) / 7d);
            int colscount = qcount / rowscount;

            int mincolwidth = cellsinq * (4 + 3);

            // int colsinterval = Convert.ToInt32(((_page.Width.Millimeter - 40d) - (mincolwidth * colscount)) / colscount);

            int colsinterval = Convert.ToInt32(((XUnit.FromPoint(rect.X2 - rect.X1).Millimeter - 40d) - (mincolwidth * colscount)) / colscount);

            colsinterval = colsinterval < 8 ? 8 : colsinterval;
            int colwidgth = cellsinq * (4 + 3) + colsinterval;

            int maxy  = 0;
            int initx = 15 + (int)XUnit.FromPoint(rect.X1).Millimeter;
            int inity = 55;

            int x = initx;

            int number = 1;

            int rr = 0;
            int y  = inity;

            for (int question = 0; question < qcount; question++)
            {
                if (rr != 0)
                {
                    DrawQuestion(number, cellsinq, x, y);
                }
                else
                {
                    DrawQuestion(number, cellsinq, x, y, cellslabels);
                }
                number++;
                rr++;
                y = y + rowhight;
                if (y > maxy)
                {
                    maxy = y;
                }
                if (rr == rowscount)
                {
                    rr = 0;
                    x += colwidgth;
                    y  = inity;
                }
            }

            this.DrawLine(0, (float)_page.Width.Millimeter, maxy);
            this.DrawLeftString("Добровольность тестирования и достоверность результатов подтверждаю:_______________", initx - 10, maxy + 1, 60, 10);
        }
Esempio n. 34
0
 public void Write(PdfRectangle rect)
 {
   WriteSeparator(CharCat.Delimiter, '/');
   WriteRaw(PdfEncoders.Format("[{0:0.###} {1:0.###} {2:0.###} {3:0.###}]", rect.X1, rect.Y1, rect.X2, rect.Y2));
   this.lastCat = CharCat.Delimiter;
 }
Esempio n. 35
0
 public void Write(PdfRectangle rect)
 {
     const string format = Config.SignificantFigures3;
     WriteSeparator(CharCat.Delimiter, '/');
     WriteRaw(PdfEncoders.Format("[{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "}]", rect.X1, rect.Y1, rect.X2, rect.Y2));
     _lastCat = CharCat.Delimiter;
 }