Пример #1
0
        public PdfResourceDictionary()
        {
            this.Add(procSet, procSetObj);
            this.Add(font, fontObj);

            // Add a basic font to the page as a default
            PdfFont f = new PdfFont("F1", FontTypes.Type1, InstalledFonts.Helvetica);
            PdfDocument.RegisterForOutput(f);
            fontObj.Add(f.FontName, f.IndirectReference);
        }
Пример #2
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

            //margin
            PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
            PdfMargins margin = new PdfMargins();
            margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Bottom = margin.Top;
            margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Right = margin.Left;

            // Create one page
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin);
            
            float y = 10;

            //title
            PdfBrush brush1 = PdfBrushes.Black;
            PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Arial", 16f, FontStyle.Bold), true);
            PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);
            page.Canvas.DrawString("Categories List", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1);
            y = y + font1.MeasureString("Categories List", format1).Height;
            y = y + 5;

            RectangleF rctg = new RectangleF(new PointF(0, 0), page.Canvas.ClientSize);
            PdfLinearGradientBrush brush
                = new PdfLinearGradientBrush(rctg, Color.Navy, Color.OrangeRed, PdfLinearGradientMode.Vertical);
            PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 12f, PdfFontStyle.Bold);
            String formatted
                = "Beverages\nCondiments\nConfections\nDairy Products\nGrains/Cereals\nMeat/Poultry\nProduce\nSeafood";

            PdfList list = new PdfList(formatted);
            list.Font = font;
            list.Indent = 8;
            list.TextIndent = 5;
            list.Brush = brush;
            PdfLayoutResult result = list.Draw(page, 0, y);
            y = result.Bounds.Bottom;

            PdfSortedList sortedList = new PdfSortedList(formatted);
            sortedList.Font = font;
            sortedList.Indent = 8;
            sortedList.TextIndent = 5;
            sortedList.Brush = brush;
            sortedList.Draw(page, 0, y);

            //Save pdf file.
            doc.SaveToFile("SimpleList.pdf");
            doc.Close();

            //Launching the Pdf file.
            PDFDocumentViewer("SimpleList.pdf");
        }
 private void DefineFontResources()
 {
     String FontName1 = "Arial";
     String FontName2 = "Times New Roman";
     ArialNormal = new PdfFont(Document, FontName1, System.Drawing.FontStyle.Regular, true);
     ArialBold = new PdfFont(Document, FontName1, System.Drawing.FontStyle.Bold, true);
     ArialItalic = new PdfFont(Document, FontName1, System.Drawing.FontStyle.Italic, true);
     ArialBoldItalic = new PdfFont(Document, FontName1, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic, true);
     TimesNormal = new PdfFont(Document, FontName2, System.Drawing.FontStyle.Regular, true);
     Comic = new PdfFont(Document, "Comic Sans MS", System.Drawing.FontStyle.Bold, true);
        return;
 }
        /// <summary>
        /// PDF table style default constructor.
        /// </summary>
        /// <param name="Font">Font</param>
        public PdfTableStyle(
			PdfFont Font = null
			)
        {
            Alignment = ContentAlignment.TopLeft;
            BackgroundColor = Color.Empty;
            TextBoxLineBreakFactor = 0.5;
            TextBoxTextJustify = TextBoxJustify.Left;
            this.Font = Font;
            FontSize = 9.0;
            Margin = new PdfRectangle();
            ForegroundColor = Color.Black;
            TextDrawStyle = DrawStyle.Normal;
            return;
        }
Пример #5
0
        protected PdfLayoutResult buildPdfLines(PdfPageBase page, List<LineItem> list, string category, float y)
        {
            PdfFont helv14 = new PdfFont(PdfFontFamily.Helvetica, 14f);
            PdfFont helv12 = new PdfFont(PdfFontFamily.Helvetica, 12f);
            PdfFont helv11 = new PdfFont(PdfFontFamily.Helvetica, 11f);

            PdfTable LinesTable = new PdfTable();
            LinesTable.Style.CellPadding = 1;
            LinesTable.Style.DefaultStyle.Font = helv11;

            List<string> data = new List<string>();
            double subtotal = 0;

            if(category == "Recurring")
                data.Add("Product;Part Number;Monthly Rate;Quantity;Price");
            else
                data.Add("Product;Part Number;Unit Price;Quantity;Price");
            foreach (LineItem line in list)
            {
                data.Add(line.Product.Name + ";" + line.Product.PartNumber + ";$" + line.Product.Price + ";" + line.Quantity + ";$" + line.Total);
                subtotal += line.Total;
            } data.Add(";;; Subtotal: ;$" + subtotal.ToString());

            string[][] dataSource = new string[data.Count][];
            for (int i = 0; i < data.Count; i++)
                dataSource[i] = data[i].Split(';');

            LinesTable.DataSource = dataSource;

            LinesTable.BeginRowLayout += new BeginRowLayoutEventHandler(LinesTable_BeginRowLayout);

            LinesTable.Columns[1].StringFormat = new PdfStringFormat(PdfTextAlignment.Right);
            LinesTable.Columns[2].StringFormat = new PdfStringFormat(PdfTextAlignment.Right);
            LinesTable.Columns[3].StringFormat = new PdfStringFormat(PdfTextAlignment.Right);
            LinesTable.Columns[4].StringFormat = new PdfStringFormat(PdfTextAlignment.Right);

            float width = page.Canvas.ClientSize.Width;
            for (int i = 0; i < LinesTable.Columns.Count; i++)
            {
                if (i == 0)
                    LinesTable.Columns[i].Width = width * .1f * width;
                else
                    LinesTable.Columns[i].Width = width * .045f * width;
            }

            return LinesTable.Draw(page, new PointF(0, y));
        }
Пример #6
0
        private void AddHtmlFooter(Document document, PdfFont footerPageNumberFont)
        {
            string headerAndFooterHtmlUrl = Path.Combine(Application.StartupPath, @"..\..\HeaderFooter\HeaderAndFooterHtml.htm");

            //create a template to be added in the header and footer
            document.Footer = document.AddTemplate(document.Pages[0].ClientRectangle.Width, 60);
            // create a HTML to PDF converter element to be added to the header template
            HtmlToPdfElement footerHtmlToPdf = new HtmlToPdfElement(0, 0, document.Footer.ClientRectangle.Width,
                    document.Footer.ClientRectangle.Height, headerAndFooterHtmlUrl);
            footerHtmlToPdf.FitHeight = true;
            document.Footer.AddElement(footerHtmlToPdf);

            // add page number to the footer
            TextElement pageNumberText = new TextElement(document.Footer.ClientRectangle.Width - 100, 30,
                                "This is page &p; of &P; pages", footerPageNumberFont);
            document.Footer.AddElement(pageNumberText);
        }
Пример #7
0
        private void AlignText(PdfPageBase page)
        {
            //Draw the text - alignment
            PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 20f);
            PdfSolidBrush brush = new PdfSolidBrush(Color.Blue);

            PdfStringFormat leftAlignment = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
            page.Canvas.DrawString("Left!", font, brush, 0, 20, leftAlignment);
            page.Canvas.DrawString("Left!", font, brush, 0, 50, leftAlignment);

            PdfStringFormat rightAlignment = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
            page.Canvas.DrawString("Right!", font, brush, page.Canvas.ClientSize.Width, 30, rightAlignment);
            page.Canvas.DrawString("Right!", font, brush, page.Canvas.ClientSize.Width, 60, rightAlignment);

            PdfStringFormat centerAlignment = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush, page.Canvas.ClientSize.Width / 2, 40, centerAlignment);

        }
Пример #8
0
        private void TransformText(PdfPageBase page)
        {
            //save graphics state
            PdfGraphicsState state = page.Canvas.Save();

            //Draw the text - transform           
            PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 18f);
            PdfSolidBrush brush1 = new PdfSolidBrush(Color.Blue);
            PdfSolidBrush brush2 = new PdfSolidBrush(Color.CadetBlue);
            PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Center);

            page.Canvas.TranslateTransform(page.Canvas.ClientSize.Width / 2, 20);
            page.Canvas.DrawString("Sales Report Chart", font, brush1, 0, 0, format);

            page.Canvas.ScaleTransform(1f, -0.8f);
            page.Canvas.DrawString("Sales Report Chart", font, brush2, 0, -2 * 18 * 1.2f, format);
            //restor graphics
            page.Canvas.Restore(state);
        }
Пример #9
0
        private static void CreateGoToActions(PdfFixedDocument document, PdfFont font)
        {
            PdfPen blackPen = new PdfPen(new PdfRgbColor(0, 0, 0), 1);
            PdfBrush blackBrush = new PdfBrush();

            font.Size = 12;
            PdfStringAppearanceOptions sao = new PdfStringAppearanceOptions();
            sao.Brush = blackBrush;
            sao.Font = font;
            PdfStringLayoutOptions slo = new PdfStringLayoutOptions();
            slo.HorizontalAlign = PdfStringHorizontalAlign.Center;
            slo.VerticalAlign = PdfStringVerticalAlign.Middle;

            Random rnd = new Random();
            for (int i = 0; i < document.Pages.Count; i++)
            {
                int destinationPage = rnd.Next(document.Pages.Count);

                document.Pages[i].Graphics.DrawString("Go To actions:", font, blackBrush, 400, 240);

                document.Pages[i].Graphics.DrawRectangle(blackPen, 400, 260, 200, 20);
                slo.X = 500;
                slo.Y = 270;
                document.Pages[i].Graphics.DrawString("Go To page: " + (destinationPage + 1).ToString(), sao, slo);

                // Create a link annotation on top of the widget.
                PdfLinkAnnotation link = new PdfLinkAnnotation();
                document.Pages[i].Annotations.Add(link);
                link.VisualRectangle = new PdfVisualRectangle(400, 260, 200, 20);

                // Create a GoTo action and attach it to the link.
                PdfPageDirectDestination pageDestination = new PdfPageDirectDestination();
                pageDestination.Page = document.Pages[destinationPage];
                pageDestination.Left = 0;
                pageDestination.Top = 0;
                pageDestination.Zoom = 0; // Keep current zoom
                PdfGoToAction gotoPageAction = new PdfGoToAction();
                gotoPageAction.Destination = pageDestination;
                link.Action = gotoPageAction;
            }
        }
Пример #10
0
        private void AlignTextInRectangle(PdfPageBase page)
        {
            //Draw the text - align in rectangle
            PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 10f);
            PdfSolidBrush brush = new PdfSolidBrush(Color.Blue);
            RectangleF rctg1 = new RectangleF(0, 70, page.Canvas.ClientSize.Width / 2, 100);
            RectangleF rctg2 = new RectangleF(page.Canvas.ClientSize.Width / 2, 70, page.Canvas.ClientSize.Width / 2, 100);
            page.Canvas.DrawRectangle(new PdfSolidBrush(Color.LightBlue), rctg1);
            page.Canvas.DrawRectangle(new PdfSolidBrush(Color.LightSkyBlue), rctg2);

            PdfStringFormat leftAlignment = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Top);
            page.Canvas.DrawString("Left! Left!", font, brush, rctg1, leftAlignment);
            page.Canvas.DrawString("Left! Left!", font, brush, rctg2, leftAlignment);

            PdfStringFormat rightAlignment = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
            page.Canvas.DrawString("Right! Right!", font, brush, rctg1, rightAlignment);
            page.Canvas.DrawString("Right! Right!", font, brush, rctg2, rightAlignment);

            PdfStringFormat centerAlignment = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Bottom);
            page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush, rctg1, centerAlignment);
            page.Canvas.DrawString("Go! Turn Around! Go! Go! Go!", font, brush, rctg2, centerAlignment);
        }
Пример #11
0
 public static PdfDocument PrintCappReport(string username)
 {
     if (EntitiesHelper.GetSessionId(username) == -1) return null;
     var userData = UserHelper.GetApplicationUser(username);
     var courseData = CourseHelper.GetCappReport(username);
     var pdf = new PdfDocument();
     var cappSection = pdf.Sections.Add();
     var page = cappSection.Pages.Add();
     var font = new PdfFont(PdfFontFamily.TimesRoman, 11);
     var format = new PdfStringFormat { LineSpacing = 20f };
     var brush = PdfBrushes.Black;
     var stringData = "\n";
     stringData += userData.Username + "\t" + userData.Major + "\n";
     stringData = userData.Advisors.Aggregate(stringData,
         (current, adivsor) => current + (adivsor.Name + ": " + adivsor.Email + "\n"));
     stringData += "\n\n";
     foreach (var reqSet in courseData.RequirementSets)
     {
         stringData += reqSet.Name + "\n";
         stringData = reqSet.AppliedCourses.Aggregate(stringData,
             (current, course) => current + (course.DepartmentCode + "-" + course.CourseNumber + "\n"));
         stringData += "\n";
     }
     // put user info at the top
     // aggragate through all of them
     //      put requirementset name in the header
     //          list all of the classes applied to it
     var textWidget = new PdfTextWidget(stringData, font, brush);
     var textLayout = new PdfTextLayout
     {
         Break = PdfLayoutBreakType.FitPage,
         Layout = PdfLayoutType.Paginate
     };
     var bounds = new RectangleF(new Point(0, 0), page.Canvas.ClientSize);
     textWidget.StringFormat = format;
     textWidget.Draw(page, bounds, textLayout);
     return pdf;
 }
Пример #12
0
        private static void DrawAffineTransformations(PdfPage page, PdfFont titleFont, PdfFont sectionFont)
        {
            PdfBrush brush = new PdfBrush();
            PdfPen blackPen = new PdfPen(PdfRgbColor.Black, 1);
            PdfPen redPen = new PdfPen(PdfRgbColor.Red, 1);
            PdfPen bluePen = new PdfPen(PdfRgbColor.Blue, 1);
            PdfPen greenPen = new PdfPen(PdfRgbColor.Green, 1);

            page.Graphics.DrawString("Affine transformations", titleFont, brush, 20, 50);

            page.Graphics.DrawLine(blackPen, 0, page.Height / 2, page.Width, page.Height / 2);
            page.Graphics.DrawLine(blackPen, page.Width / 2, 0, page.Width / 2, page.Height);

            page.Graphics.SaveGraphicsState();

            // Move the coordinate system in the center of the page.
            page.Graphics.TranslateTransform(page.Width / 2, page.Height / 2);

            // Draw a rectangle with the center at (0, 0)
            page.Graphics.DrawRectangle(redPen, -page.Width / 4, -page.Height / 8, page.Width / 2, page.Height / 4);

            // Rotate the coordinate system with 30 degrees.
            page.Graphics.RotateTransform(30);

            // Draw the same rectangle with the center at (0, 0)
            page.Graphics.DrawRectangle(greenPen, -page.Width / 4, -page.Height / 8, page.Width / 2, page.Height / 4);

            // Scale the coordinate system with 1.5
            page.Graphics.ScaleTransform(1.5, 1.5);

            // Draw the same rectangle with the center at (0, 0)
            page.Graphics.DrawRectangle(bluePen, -page.Width / 4, -page.Height / 8, page.Width / 2, page.Height / 4);

            page.Graphics.RestoreGraphicsState();

            page.Graphics.CompressAndClose();
        }
        /// <summary>
        /// Creates first page in the document.
        /// </summary>
        private void CreateFirstPage()
        {
            // Add a new page.
            page = document.Pages.Add();

            page.Graphics.DrawImage(img, 0, 0, pageSize.Width, pageSize.Height);
            page.Graphics.DrawString("General Information", pdfFont, new PdfSolidBrush(new PdfColor(213, 123, 19)), x, 40);
            page.Graphics.DrawString("Education Grade", pdfFont, new PdfSolidBrush(new PdfColor(213, 123, 19)), x, 190);

            // Update font
            pdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 10f, PdfFontStyle.Regular);

            // Create fields for first page.
            page.Graphics.DrawString("First Name:", pdfFont, solidBrush, x, 65);

            //Create text box for FirstName.
            CreateTextBox(page, "FirstName", "First Name", pdfFont, bounds);

            page.Graphics.DrawString("Last Name:", pdfFont, solidBrush, x, 83);
            bounds.Y += 18;

            //Create text box for LastName.
            CreateTextBox(page, "LastName", "Last Name", pdfFont, bounds);

            page.Graphics.DrawString("Email:", pdfFont, solidBrush, x, 103);
            bounds.Y += 18;

            //Create text box for Email.
            CreateTextBox(page, "Email", "Email id", pdfFont, bounds);

            page.Graphics.DrawString("Business Phone:", pdfFont, solidBrush, x, 123);
            bounds.Y += 18;

            //Create text box for Business phone.
            CreateTextBox(page, "Business", "Business phone", pdfFont, bounds);

            page.Graphics.DrawString("Which position are\nyou applying for?", pdfFont, solidBrush, x, 143);

            bounds.Y += 24;

            #region Create ComboBox

            // Create a combo box for the first page.
            PdfComboBoxField comboBox = new PdfComboBoxField(page, "JobTitle");
            comboBox.Bounds      = bounds;
            comboBox.BorderWidth = 1;
            comboBox.BorderColor = new PdfColor(System.Drawing.Color.FromArgb(255, 128, 128, 128));

            comboBox.Font = pdfFont;

            // Set tooltip
            comboBox.ToolTip = "Job Title";

            // Add list items.
            comboBox.Items.Add(new PdfListFieldItem("Development", "accounts"));
            comboBox.Items.Add(new PdfListFieldItem("Support", "advertise"));
            comboBox.Items.Add(new PdfListFieldItem("Documentation", "agri"));

            // Add combo box to the form.
            document.Form.Fields.Add(comboBox);
            #endregion

            page.Graphics.DrawString("Highest qualification", pdfFont, solidBrush, x, 217);

            #region Create CheckBox
            //Set position to draw Checkbox
            bounds.Y     = 239;
            bounds.X     = x;
            bounds.Width = 10;

            bounds.Height = 10;

            // Create check box for Associate Degree.
            CreateCheckBox(page, "Adegree", "Degree");
            page.Graphics.DrawString("Associate degree", pdfFont, solidBrush, bounds.X, bounds.Y);
            bounds.X += 90;

            // Create check box for Bachelor Degree.
            CreateCheckBox(page, "Bdegree", "Degree");
            page.Graphics.DrawString("Bachelor degree", pdfFont, solidBrush, bounds.X, bounds.Y);
            bounds.X += 90;

            // Create check box for College.
            CreateCheckBox(page, "college", "College");
            page.Graphics.DrawString("College", pdfFont, solidBrush, bounds.X, bounds.Y);

            bounds.Y += 20;
            bounds.X  = x;

            // Create check box for PG.
            CreateCheckBox(page, "pg", "PG");
            page.Graphics.DrawString("Post Graduate", pdfFont, solidBrush, bounds.X, bounds.Y);
            bounds.X += 90;

            // Create check box for MBA.
            CreateCheckBox(page, "mba", "MBA");
            page.Graphics.DrawString("MBA", pdfFont, solidBrush, bounds.X, bounds.Y);

            #endregion

            // Add navigation button for the second page.
            NavigateToNextPage(page, "Next");
        }
Пример #14
0
        public virtual void SmartModeSameResourcesCopyingModifyingAndFlushing_ensureObjectFresh()
        {
            String outFile = destinationFolder + "smartModeSameResourcesCopyingModifyingAndFlushing_ensureObjectFresh.pdf";
            String cmpFile = sourceFolder + "cmp_smartModeSameResourcesCopyingModifyingAndFlushing_ensureObjectFresh.pdf";

            String[]    srcFiles    = new String[] { sourceFolder + "indirectResourcesStructure.pdf", sourceFolder + "indirectResourcesStructure2.pdf" };
            PdfDocument outputDoc   = new PdfDocument(new PdfWriter(outFile, new WriterProperties().UseSmartMode()));
            int         lastPageNum = 1;
            PdfFont     font        = PdfFontFactory.CreateFont();

            foreach (String srcFile in srcFiles)
            {
                PdfDocument sourceDoc = new PdfDocument(new PdfReader(srcFile));
                for (int i = 1; i <= sourceDoc.GetNumberOfPages(); ++i)
                {
                    PdfDictionary srcRes = sourceDoc.GetPage(i).GetPdfObject().GetAsDictionary(PdfName.Resources);
                    // Ensures that objects copied to the output document are fresh,
                    // i.e. are not reused from already copied objects cache.
                    bool ensureObjectIsFresh = true;
                    // it's crucial to copy first inner objects and then the container object!
                    foreach (PdfObject v in srcRes.Values())
                    {
                        if (v.GetIndirectReference() != null)
                        {
                            // We are not interested in returned copied objects instances, they will be picked up by
                            // general copying mechanism from copied objects cache by default.
                            v.CopyTo(outputDoc, ensureObjectIsFresh);
                        }
                    }
                    if (srcRes.GetIndirectReference() != null)
                    {
                        srcRes.CopyTo(outputDoc, ensureObjectIsFresh);
                    }
                }
                sourceDoc.CopyPagesTo(1, sourceDoc.GetNumberOfPages(), outputDoc);
                sourceDoc.Close();
                int i_1;
                for (i_1 = lastPageNum; i_1 <= outputDoc.GetNumberOfPages(); ++i_1)
                {
                    PdfPage   page   = outputDoc.GetPage(i_1);
                    PdfCanvas canvas = new PdfCanvas(page);
                    canvas.BeginText().MoveText(36, 36).SetFontAndSize(font, 12).ShowText("Page " + i_1).EndText();
                }
                lastPageNum = i_1;
                outputDoc.FlushCopiedObjects(sourceDoc);
            }
            outputDoc.Close();
            PdfDocument          assertDoc       = new PdfDocument(new PdfReader(outFile));
            PdfIndirectReference page1ResFontObj = assertDoc.GetPage(1).GetPdfObject().GetAsDictionary(PdfName.Resources
                                                                                                       ).GetAsDictionary(PdfName.Font).GetIndirectReference();
            PdfIndirectReference page2ResFontObj = assertDoc.GetPage(2).GetPdfObject().GetAsDictionary(PdfName.Resources
                                                                                                       ).GetAsDictionary(PdfName.Font).GetIndirectReference();
            PdfIndirectReference page3ResFontObj = assertDoc.GetPage(3).GetPdfObject().GetAsDictionary(PdfName.Resources
                                                                                                       ).GetAsDictionary(PdfName.Font).GetIndirectReference();

            NUnit.Framework.Assert.IsFalse(page1ResFontObj.Equals(page2ResFontObj));
            NUnit.Framework.Assert.IsFalse(page1ResFontObj.Equals(page3ResFontObj));
            NUnit.Framework.Assert.IsFalse(page2ResFontObj.Equals(page3ResFontObj));
            assertDoc.Close();
            NUnit.Framework.Assert.IsNull(new CompareTool().CompareByContent(outFile, cmpFile, destinationFolder));
        }
Пример #15
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==";

            // display the attachments when the document is opened
            document.Viewer.PageMode = PdfPageMode.Attachments;

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

            // create the true type fonts that can be used in document
            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);

            // create a reference Graphics used for measuring
            System.Drawing.Bitmap   refBmp      = new System.Drawing.Bitmap(1, 1);
            System.Drawing.Graphics refGraphics = System.Drawing.Graphics.FromImage(refBmp);
            refGraphics.PageUnit = System.Drawing.GraphicsUnit.Point;

            // create an attachment with icon from file
            string        filePath1      = Server.MapPath("~") + @"\DemoFiles\Attach\TextAttach1.txt";
            PdfAttachment pdfAttachment1 = document.CreateAttachmentFromFile(page1, new System.Drawing.RectangleF(10, 30, 10, 20),
                                                                             PdfAttachIconType.PushPin, filePath1);

            pdfAttachment1.Description = "Attachment with icon from a file";

            // write a description at the right of the icon
            PdfText pdfAttachment1Descr = new PdfText(40, 35, pdfAttachment1.Description, pdfFontEmbed);

            page1.Layout(pdfAttachment1Descr);

            // create an attachment with icon from a stream
            // The stream must remain opened until the document is saved
            System.IO.FileStream fileStream2    = new System.IO.FileStream(filePath1, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            PdfAttachment        pdfAttachment2 = document.CreateAttachmentFromStream(page1, new System.Drawing.RectangleF(10, 60, 10, 20),
                                                                                      PdfAttachIconType.Paperclip, fileStream2, "AttachFromStream_WithIcon.txt");

            pdfAttachment2.Description = "Attachment with icon from a stream";

            // write a description at the right of the icon
            PdfText pdfAttachment2Descr = new PdfText(40, 65, pdfAttachment2.Description, pdfFontEmbed);

            page1.Layout(pdfAttachment2Descr);

            // create an attachment without icon in PDF from a file
            string filePath2 = Server.MapPath("~") + @"\DemoFiles\Attach\TextAttach2.txt";

            document.CreateAttachmentFromFile(filePath2);

            // create an attachment without icon in PDF from a stream
            // The stream must remain opened until the document is saved
            System.IO.FileStream fileStream1 = new System.IO.FileStream(filePath2, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            document.CreateAttachmentFromStream(fileStream1, "AttachFromStream_NoIcon.txt");

            // dispose the graphics used for measuring
            refGraphics.Dispose();
            refBmp.Dispose();

            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=PdfOutlines.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();
                fileStream1.Close();
            }
        }
Пример #16
0
        /// <summary>
        /// Add text to text box.
        /// </summary>
        /// <param name="Font">Font</param>
        /// <param name="FontSize">Font size</param>
        /// <param name="DrawStyle">Drawing style</param>
        /// <param name="FontColor">Text color</param>
        /// <param name="Text">Text</param>
        /// <param name="WebLink">Web link</param>
        public void AddText(
			PdfFont		Font,
			Double		FontSize,
			DrawStyle	DrawStyle,
			Color		FontColor,
			String		Text,
			String		WebLink = null
			)
        {
            // text is null or empty
            if(String.IsNullOrEmpty(Text)) return;

            // create new text segment
            TextBoxSeg Seg;

            // segment array is empty or new segment is different than last one
            if(SegArray.Count == 0 || !SegArray[SegArray.Count - 1].IsEqual(Font, FontSize, DrawStyle, FontColor, WebLink))
            {
            Seg = new TextBoxSeg(Font, FontSize, DrawStyle, FontColor, WebLink);
            SegArray.Add(Seg);
            }

            // add new text to most recent text segment
            else
            {
            Seg = SegArray[SegArray.Count - 1];
            }

            // save text start pointer
            Int32 TextStart = 0;

            // loop for characters
            for(Int32 TextPtr = 0; TextPtr < Text.Length; TextPtr++)
            {
            // shortcut to current character
            Char CurChar = Text[TextPtr];

            // end of paragraph
            if(CurChar == '\n' || CurChar == '\r')
                {
                // append text to current segemnt
                Seg.Text += Text.Substring(TextStart, TextPtr - TextStart);

                // test for new line after carriage return
                if(CurChar == '\r' && TextPtr + 1 < Text.Length && Text[TextPtr + 1] == '\n') TextPtr++;

                // move pointer to one after the eol
                TextStart = TextPtr + 1;

                // add line
                AddLine(true);

                // update last character
                PrevChar = ' ';

                // end of text
                if(TextPtr + 1 == Text.Length) return;

                // add new empty segment
                Seg = new TextBoxSeg(Font, FontSize, DrawStyle, FontColor, WebLink);
                SegArray.Add(Seg);
                continue;
                }

            // validate character
            Font.ValidateChar(CurChar);

            // character width
            Double CharWidth = Font.CharWidth(FontSize, Seg.DrawStyle, CurChar);

            // space
            if(CurChar == ' ')
                {
                // test for transition from non space to space
                // this is a potential line break point
                if(PrevChar != ' ')
                    {
                    // save potential line break information
                    LineBreakWidth = LineWidth;
                    BreakSegIndex = SegArray.Count - 1;
                    BreakPtr = Seg.Text.Length + TextPtr - TextStart;
                    BreakWidth = Seg.SegWidth;
                    }

                // add to line width
                LineWidth += CharWidth;
                Seg.SegWidth += CharWidth;

                // update last character
                PrevChar = CurChar;
                continue;
                }

            // add current segment width and to overall line width
            Seg.SegWidth += CharWidth;
            LineWidth += CharWidth;

            // for next loop set last character
            PrevChar = CurChar;

            Double Width = BoxWidth;
            if(FirstLineIndent != 0 && (LineArray.Count == 0 || LineArray[LineArray.Count - 1].EndOfParagraph)) Width -= FirstLineIndent;

            // current line width is less than or equal box width
            if(LineWidth <= Width) continue;

            // append text to current segemnt
            Seg.Text += Text.Substring(TextStart, TextPtr - TextStart + 1);
            TextStart = TextPtr + 1;

            // there are no breaks in this line or last segment is too long
            if(LineBreakWidth < LineBreakFactor * Width)
                {
                BreakSegIndex = SegArray.Count - 1;
                BreakPtr = Seg.Text.Length - 1;
                BreakWidth = Seg.SegWidth - CharWidth;
                }

            // break line
            BreakLine();

            // add line up to break point
            AddLine(false);
            }

            // save text
            Seg.Text += Text.Substring(TextStart);

            // exit
            return;
        }
Пример #17
0
        public ActionResult ConvertHtmlToPdf(IFormCollection collection)
        {
            // Create a HTML to PDF converter object with default settings
            HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();

            // Set license key received after purchase to use the converter in licensed mode
            // Leave it not set to use the converter in demo mode
            htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c=";

            // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed
            // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish
            htmlToPdfConverter.ConversionDelay = 2;

            Document pdfDocument = null;

            try
            {
                string htmlWithButton = collection["htmlStringTextBox"];
                string baseUrl        = collection["baseUrlTextBox"];

                // Convert a HTML string with a button to a PDF document object
                pdfDocument = htmlToPdfConverter.ConvertHtmlToPdfDocumentObject(htmlWithButton, baseUrl);

                // Get the button location in PDF
                HtmlElementMapping buttonMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("javascript_button");
                if (buttonMapping != null)
                {
                    PdfPage    buttonPdfPage   = buttonMapping.PdfRectangles[0].PdfPage;
                    RectangleF buttonRectangle = buttonMapping.PdfRectangles[0].Rectangle;

                    // The font used for buttons text in PDF document
                    PdfFont buttonTextFont = pdfDocument.AddFont(new Font("Times New Roman", 8, FontStyle.Regular, GraphicsUnit.Point));

                    // Create a PDF form button
                    PdfFormButton pdfButton = pdfDocument.Form.AddButton(buttonPdfPage, buttonRectangle, "Execute Acrobat JavaScript", buttonTextFont);

                    // Set JavaScript action to be executed when the button is clicked
                    string javaScript = null;
                    if (collection["JavaScriptAction"] == "alertMessageRadioButton")
                    {
                        // JavaScript to display an alert mesage
                        javaScript = String.Format("app.alert(\"{0}\")", collection["alertMessageTextBox"]);
                    }
                    else if (collection["JavaScriptAction"] == "printDialogRadioButton")
                    {
                        // JavaScript to open the print dialog
                        javaScript = "print()";
                    }
                    else if (collection["JavaScriptAction"] == "zoomLevelRadioButton")
                    {
                        // JavaScript to set an initial zoom level
                        javaScript = String.Format("zoom={0}", int.Parse(collection["zoomLevelTextBox"]));
                    }

                    // Set the JavaScript action
                    pdfButton.Action = new PdfActionJavaScript(javaScript);
                }

                // Save the PDF document in a memory buffer
                byte[] outPdfBuffer = pdfDocument.Save();

                // Send the PDF file to browser
                FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf");
                fileResult.FileDownloadName = "Button_JavaScript_Actions.pdf";

                return(fileResult);
            }
            finally
            {
                // Close the PDF document
                if (pdfDocument != null)
                {
                    pdfDocument.Close();
                }
            }
        }
Пример #18
0
        //pomoćna metoda za kreiranje pdf-a
        private static Table CreateTable(List <poduzeće> poduzeća)
        {
            List <poduzeće> poduzeće = poduzeća;

            PdfFont bold    = PdfFontFactory.CreateFont(StandardFonts.TIMES_BOLD, "Cp1250", true);
            PdfFont regular = PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN, "Cp1250", true);

            Table table = new Table(new float[5]).UseAllAvailableWidth();


            Cell cell1 = new Cell().Add(new Paragraph("Ime poduzeća"));

            cell1.SetBorder(new SolidBorder(2));
            cell1.SetBackgroundColor(new DeviceRgb(52, 219, 235));
            cell1.SetFont(bold);
            table.AddCell(cell1);
            Cell cell2 = new Cell().Add(new Paragraph("Županija"));

            cell2.SetBorder(new SolidBorder(2));
            cell2.SetBackgroundColor(new DeviceRgb(52, 219, 235));
            cell2.SetFont(bold);
            table.AddCell(cell2);
            Cell cell3 = new Cell().Add(new Paragraph("Grad"));

            cell3.SetBorder(new SolidBorder(2));
            cell3.SetBackgroundColor(new DeviceRgb(52, 219, 235));
            cell3.SetFont(bold);
            table.AddCell(cell3);
            Cell cell11 = new Cell().Add(new Paragraph("Ulica"));

            cell11.SetBorder(new SolidBorder(2));
            cell11.SetBackgroundColor(new DeviceRgb(52, 219, 235));
            cell11.SetFont(bold);
            table.AddCell(cell11);
            Cell cell5 = new Cell().Add(new Paragraph("Tip objekta"));

            cell5.SetBorder(new SolidBorder(2));
            cell5.SetBackgroundColor(new DeviceRgb(52, 219, 235));
            cell5.SetFont(bold);
            table.AddCell(cell5);
            foreach (poduzeće item in poduzeće)
            {
                Cell cell6 = new Cell().Add(new Paragraph(item.imePoduzeće));
                cell6.SetBorder(new SolidBorder(2));
                cell6.SetBackgroundColor(new DeviceRgb(52, 219, 235));
                cell6.SetFont(regular);
                table.AddCell(cell6);
                Cell cell7 = new Cell().Add(new Paragraph(item.županija.imeŽupanija));
                cell7.SetBorder(new SolidBorder(2));
                cell7.SetBackgroundColor(new DeviceRgb(52, 219, 235));
                cell7.SetFont(regular);
                table.AddCell(cell7);
                Cell cell8 = new Cell().Add(new Paragraph(item.grad.imeGrad));
                cell8.SetBorder(new SolidBorder(2));
                cell8.SetBackgroundColor(new DeviceRgb(52, 219, 235));
                cell8.SetFont(regular);
                table.AddCell(cell8);

                Cell cell12 = new Cell().Add(new Paragraph(item.ulica.imeUlica));
                cell12.SetBorder(new SolidBorder(2));
                cell12.SetBackgroundColor(new DeviceRgb(52, 219, 235));
                cell12.SetFont(regular);
                table.AddCell(cell12);
                Cell cell10 = new Cell().Add(new Paragraph(item.djelatnost.imeDjelatnost));
                cell10.SetBorder(new SolidBorder(2));
                cell10.SetBackgroundColor(new DeviceRgb(52, 219, 235));
                cell10.SetFont(regular);
                table.AddCell(cell10);
            }

            return(table);
        }
        protected void createPdfButton_Click(object sender, EventArgs e)
        {
            // Get the server IP and port
            String serverIP   = textBoxServerIP.Text;
            uint   serverPort = uint.Parse(textBoxServerPort.Text);

            // Create a PDF document
            Document pdfDocument = new Document(serverIP, serverPort);

            // Set optional service password
            if (textBoxServicePassword.Text.Length > 0)
            {
                pdfDocument.ServicePassword = textBoxServicePassword.Text;
            }

            // Set license key received after purchase to use the converter in licensed mode
            // Leave it not set to use the converter in demo mode
            pdfDocument.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c=";

            // Add a page to PDF document
            PdfPage pdfPage = pdfDocument.AddPage();

            // The titles font used to mark various sections of the PDF document
            PdfFont titleFont = new PdfFont("Times New Roman", 10, true);

            titleFont.Bold = true;
            PdfFont subtitleFont = new PdfFont("Times New Roman", 8, true);

            // The links text font
            PdfFont linkTextFont = new PdfFont("Times New Roman", 8, true);

            linkTextFont.Bold      = true;
            linkTextFont.Underline = true;

            // Add document title
            TextElement titleTextElement = new TextElement(5, 5, "Create URI Links in PDF Document", titleFont);

            pdfPage.AddElement(titleTextElement);

            // Make a text in PDF a link to a web page

            // Add the text element
            string      text            = "Click this text to open a web page!";
            TextElement linkTextElement = new TextElement(0, 0, 150, text, linkTextFont);

            linkTextElement.ForeColor = RgbColor.Navy;
            pdfDocument.AddElement(linkTextElement, 15);

            // Create the URI link element having the size of the text element
            RectangleFloat linkRectangle = RectangleFloat.Empty;
            string         url           = "http://www.evopdf.com";
            LinkUrlElement uriLink       = new LinkUrlElement(linkRectangle, url);

            // Add the URI link to PDF document
            pdfDocument.AddElement(uriLink, 0, true, true, 0, true, false);

            // Make an image in PDF a link to a web page

            TextElement subtitleTextElement = new TextElement(0, 0, "Click the image below to open a web page:", subtitleFont);

            pdfDocument.AddElement(subtitleTextElement, 10);

            // Add the image element
            ImageElement linkImageElement = new ImageElement(0, 0, 120, Server.MapPath("~/DemoAppFiles/Input/Images/logo.jpg"));

            pdfDocument.AddElement(linkImageElement);

            // Create the URI link element having the size of the image element
            linkRectangle = RectangleFloat.Empty;
            uriLink       = new LinkUrlElement(linkRectangle, url);

            // Add the URI link to PDF document
            pdfDocument.AddElement(uriLink, 0, true, true, 0, true, false);

            // Save the PDF document in a memory buffer
            byte[] outPdfBuffer = pdfDocument.Save();

            // Send the PDF as response to browser

            // Set response content type
            Response.AddHeader("Content-Type", "application/pdf");

            // Instruct the browser to open the PDF file as an attachment or inline
            Response.AddHeader("Content-Disposition", String.Format("attachment; filename=URI_Links.pdf; size={0}", outPdfBuffer.Length.ToString()));

            // Write the PDF document buffer to HTTP response
            Response.BinaryWrite(outPdfBuffer);

            // End the HTTP response and stop the current page processing
            Response.End();
        }
Пример #20
0
        private static void CreatePdf(Team homeTeam)
        {
            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                PdfWriter   writer   = new PdfWriter(memoryStream);
                PdfDocument pdf      = new PdfDocument(writer);
                Document    document = new Document(pdf);

                PdfFont font = PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN);

                document.SetFont(font);
                document.SetTextAlignment(TextAlignment.CENTER);


                ImageData imageData = ImageDataFactory.Create("Images/gq.png");
                Image     image     = new Image(imageData);
                image.SetMarginLeft(170);
                document.Add(image);

                PdfFont titleFont = PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN);

                var para = new Paragraph(homeTeam.TeamName)
                           .SetFont(titleFont).SetFontSize(20).SetUnderline(0.5f, -1.5f)
                           .SetHorizontalAlignment(HorizontalAlignment.CENTER)
                           .SetVerticalAlignment(VerticalAlignment.TOP);

                document.Add(para);

                para = new Paragraph(homeTeam.GameInfo)
                       .SetHorizontalAlignment(HorizontalAlignment.CENTER);

                document.Add(para);

                document.Add(new Paragraph(" "));

                Table table = new Table(new float[] { 10, 25, 9, 170 });

                table.SetHorizontalAlignment(HorizontalAlignment.CENTER);
                table.AddCell("Number");
                table.AddCell("Name");
                table.AddCell("Import?");
                table.AddCell("Signature");

                foreach (var player in homeTeam.PlayerList)
                {
                    table.AddCell(player.PlayerNumber);
                    table.AddCell(player.PlayerName);
                    table.AddCell(player.Import);
                    table.AddCell(player.SignatureBox);
                }

                CreateEmptyRow(table);
                CreateEmptyRow(table);
                CreateEmptyRow(table);
                CreateEmptyRow(table);

                document.Add(table);

                document.Add(new Paragraph(" "));
                document.Add(new Paragraph(" "));
                document.Add(new Paragraph(" "));

                document = CreateMvpTable(document);
                document.Close();
                byte[] bytes = memoryStream.ToArray();

                File.WriteAllBytes($@"../{homeTeam.TeamName}.pdf", bytes);
            }
        }
Пример #21
0
        public ActionResult CreatePdf(IFormCollection collection)
        {
            // create a PDF document
            PdfDocument document = new PdfDocument();

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

            // display the outlines when the document is opened
            document.Viewer.PageMode = PdfPageMode.Outlines;

            // create the true type fonts that can be used in document
            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);

            System.Drawing.Font sysFontBold = new System.Drawing.Font("Times New Roman", 12, System.Drawing.FontStyle.Bold,
                                                                      System.Drawing.GraphicsUnit.Point);
            PdfFont pdfFontBold      = document.CreateFont(sysFontBold);
            PdfFont pdfFontBoldEmbed = document.CreateFont(sysFontBold, true);

            System.Drawing.Font sysFontBig = new System.Drawing.Font("Times New Roman", 16, System.Drawing.FontStyle.Bold,
                                                                     System.Drawing.GraphicsUnit.Point);
            PdfFont pdfFontBig      = document.CreateFont(sysFontBig);
            PdfFont pdfFontBigEmbed = document.CreateFont(sysFontBig, true);

            // create a reference Graphics used for measuring
            System.Drawing.Bitmap   refBmp      = new System.Drawing.Bitmap(1, 1);
            System.Drawing.Graphics refGraphics = System.Drawing.Graphics.FromImage(refBmp);
            refGraphics.PageUnit = System.Drawing.GraphicsUnit.Point;

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

            float crtXPos = 10;
            float crtYPos = 20;

            #region Create Table of contents

            // create table of contents title
            PdfText tableOfContentsTitle = new PdfText(crtXPos, crtYPos, "Table of Contents", pdfFontBigEmbed);
            page1.Layout(tableOfContentsTitle);

            // create a top outline for the table of contents
            PdfDestination tableOfContentsDest = new PdfDestination(page1, new System.Drawing.PointF(crtXPos, crtYPos));
            document.CreateTopOutline("Table of Contents", tableOfContentsDest);

            // advance current Y position in page
            crtYPos += pdfFontBigEmbed.Size + 10;

            // create Chapter 1 in table of contents
            PdfText chapter1TocTitle = new PdfText(crtXPos + 30, crtYPos, "Chapter 1", pdfFontBoldEmbed);
            // layout the chapter 1 title in TOC
            page1.Layout(chapter1TocTitle);

            // get the bounding rectangle of the chapter 1 title in TOC
            System.Drawing.SizeF      textSize = refGraphics.MeasureString("Chapter 1", sysFontBold);
            System.Drawing.RectangleF chapter1TocTitleRectangle = new System.Drawing.RectangleF(crtXPos + 30, crtYPos, textSize.Width, textSize.Height);

            // advance current Y position in page
            crtYPos += pdfFontEmbed.Size + 10;

            // create Subchapter 1 in table of contents
            PdfText subChapter11TocTitle = new PdfText(crtXPos + 60, crtYPos, "Subchapter 1", pdfFontEmbed);
            // layout the text
            page1.Layout(subChapter11TocTitle);

            // get the bounding rectangle of the subchapter 1 title in TOC
            textSize = refGraphics.MeasureString("Subchapter 1", sysFont);
            System.Drawing.RectangleF subChapter11TocTitleRectangle = new System.Drawing.RectangleF(crtXPos + 60, crtYPos, textSize.Width, textSize.Height);

            // advance current Y position in page
            crtYPos += pdfFontEmbed.Size + 10;

            // create Subchapter 2 in table of contents
            PdfText subChapter21TocTitle = new PdfText(crtXPos + 60, crtYPos, "Subchapter 2", pdfFontEmbed);
            // layout the text
            page1.Layout(subChapter21TocTitle);

            // get the bounding rectangle of the subchapter 2 title in TOC
            textSize = refGraphics.MeasureString("Subchapter 2", sysFont);
            System.Drawing.RectangleF subChapter21TocTitleRectangle = new System.Drawing.RectangleF(crtXPos + 60, crtYPos, textSize.Width, textSize.Height);

            // advance current Y position in page
            crtYPos += pdfFontEmbed.Size + 10;

            // create Chapter 2 in table of contents
            PdfText chapter2TocTitle = new PdfText(crtXPos + 30, crtYPos, "Chapter 2", pdfFontBoldEmbed);
            // layout the text
            page1.Layout(chapter2TocTitle);

            // get the bounding rectangle of the chapter 2 title in TOC
            textSize = refGraphics.MeasureString("Capter 2", sysFontBold);
            System.Drawing.RectangleF chapter2TocTitleRectangle = new System.Drawing.RectangleF(crtXPos + 30, crtYPos, textSize.Width, textSize.Height);

            // advance current Y position in page
            crtYPos += pdfFontEmbed.Size + 10;

            // create Subchapter 1 in table of contents
            PdfText subChapter12TocTitle = new PdfText(crtXPos + 60, crtYPos, "Subchapter 1", pdfFontEmbed);
            // layout the text
            page1.Layout(subChapter12TocTitle);

            // get the bounding rectangle of the subchapter 1 title in TOC
            textSize = refGraphics.MeasureString("Subchapter 1", sysFont);
            System.Drawing.RectangleF subChapter12TocTitleRectangle = new System.Drawing.RectangleF(crtXPos + 60, crtYPos, textSize.Width, textSize.Height);

            // advance current Y position in page
            crtYPos += pdfFontEmbed.Size + 10;

            // create Subchapter 2 in table of contents
            PdfText subChapter22TocTitle = new PdfText(crtXPos + 60, crtYPos, "Subchapter 2", pdfFontEmbed);
            // layout the text
            page1.Layout(subChapter22TocTitle);

            // get the bounding rectangle of the subchapter 2 title in TOC
            textSize = refGraphics.MeasureString("Subchapter 2", sysFont);
            System.Drawing.RectangleF subChapter22TocTitleRectangle = new System.Drawing.RectangleF(crtXPos + 60, crtYPos, textSize.Width, textSize.Height);

            // advance current Y position in page
            crtYPos += pdfFontEmbed.Size + 10;

            // create the website link in the table of contents
            PdfText visitWebSiteText = new PdfText(crtXPos + 30, crtYPos, "Visit HiQPdf Website", pdfFontEmbed);
            visitWebSiteText.ForeColor = System.Drawing.Color.Navy;
            // layout the text
            page1.Layout(visitWebSiteText);

            // get the bounding rectangle of the website link in TOC
            textSize = refGraphics.MeasureString("Visit HiQPdf Website", sysFont);
            System.Drawing.RectangleF visitWebsiteRectangle = new System.Drawing.RectangleF(crtXPos + 30, crtYPos, textSize.Width, textSize.Height);

            // create the link to website in table of contents
            document.CreateUriLink(page1, visitWebsiteRectangle, "http://www.hiqpdf.com");

            // advance current Y position in page
            crtYPos += pdfFontEmbed.Size + 10;

            // create a text note at the end of TOC
            PdfTextNote textNote = document.CreateTextNote(page1, new System.Drawing.PointF(crtXPos + 10, crtYPos),
                                                           "The table of contents contains internal links to chapters and subchapters");
            textNote.IconType = PdfTextNoteIconType.Note;
            textNote.IsOpen   = true;

            #endregion

            #region Create Chapter 1 content and the link from TOC

            // create page 2
            PdfPage page2 = document.AddPage();

            // create the Chapter 1 title
            PdfText chapter1Title = new PdfText(crtXPos, 10, "Chapter 1", pdfFontBoldEmbed);
            // layout the text
            page2.Layout(chapter1Title);

            // create the Chapter 1 root outline
            PdfDestination chapter1Destination = new PdfDestination(page2, new System.Drawing.PointF(crtXPos, 10));
            PdfOutline     chapter1Outline     = document.CreateTopOutline("Chapter 1", chapter1Destination);
            chapter1Outline.TitleColor = System.Drawing.Color.Navy;

            // create the PDF link from TOC to chapter 1
            document.CreatePdfLink(page1, chapter1TocTitleRectangle, chapter1Destination);

            #endregion

            #region Create Subchapter 1 content and the link from TOC

            // create the Subchapter 1
            PdfText subChapter11Title = new PdfText(crtXPos, 300, "Subchapter 1 of Chapter 1", pdfFontEmbed);
            // layout the text
            page2.Layout(subChapter11Title);

            // create subchapter 1 child outline
            PdfDestination subChapter11Destination = new PdfDestination(page2, new System.Drawing.PointF(crtXPos, 300));
            PdfOutline     subchapter11Outline     = document.CreateChildOutline("Subchapter 1", subChapter11Destination, chapter1Outline);

            // create the PDF link from TOC to subchapter 1
            document.CreatePdfLink(page1, subChapter11TocTitleRectangle, subChapter11Destination);

            #endregion

            #region Create Subchapter 2 content and the link from TOC

            // create the Subchapter 2
            PdfText subChapter21Title = new PdfText(crtXPos, 600, "Subchapter 2 of Chapter 1", pdfFontEmbed);
            // layout the text
            page2.Layout(subChapter21Title);

            // create subchapter 2 child outline
            PdfDestination subChapter21Destination = new PdfDestination(page2, new System.Drawing.PointF(crtXPos, 600));
            PdfOutline     subchapter21Outline     = document.CreateChildOutline("Subchapter 2", subChapter21Destination, chapter1Outline);

            // create the PDF link from TOC to subchapter 2
            document.CreatePdfLink(page1, subChapter21TocTitleRectangle, subChapter21Destination);

            #endregion

            #region Create Chapter 2 content and the link from TOC

            // create page 3
            PdfPage page3 = document.AddPage();

            // create the Chapter 2 title
            PdfText chapter2Title = new PdfText(crtXPos, 10, "Chapter 2", pdfFontBoldEmbed);
            // layout the text
            page3.Layout(chapter2Title);

            // create chapter 2 to outline
            PdfDestination chapter2Destination = new PdfDestination(page3, new System.Drawing.PointF(crtXPos, 10));
            PdfOutline     chapter2Outline     = document.CreateTopOutline("Chapter 2", chapter2Destination);
            chapter2Outline.TitleColor = System.Drawing.Color.Green;

            // create the PDF link from TOC to chapter 2
            document.CreatePdfLink(page1, chapter2TocTitleRectangle, chapter2Destination);

            #endregion

            #region Create Subchapter 1 content and the link from TOC

            // create the Subchapter 1
            PdfText subChapter12Title = new PdfText(crtXPos, 300, "Subchapter 1 of Chapter 2", pdfFontEmbed);
            // layout the text
            page3.Layout(subChapter12Title);

            // create subchapter 1 child outline
            PdfDestination subChapter12Destination = new PdfDestination(page3, new System.Drawing.PointF(crtXPos, 300));
            PdfOutline     subchapter12Outline     = document.CreateChildOutline("Subchapter 1", subChapter12Destination, chapter2Outline);

            // create the PDF link from TOC to subchapter 1
            document.CreatePdfLink(page1, subChapter12TocTitleRectangle, subChapter12Destination);

            #endregion

            #region Create Subchapter 2 content and the link from TOC

            // create the Subchapter 2
            PdfText subChapter22Title = new PdfText(crtXPos, 600, "Subchapter 2 of Chapter 2", pdfFontEmbed);
            // layout the text
            page3.Layout(subChapter22Title);

            // create subchapter 2 child outline
            PdfDestination subChapter22Destination = new PdfDestination(page3, new System.Drawing.PointF(crtXPos, 600));
            PdfOutline     subchapter22Outline     = document.CreateChildOutline("Subchapter 2", subChapter22Destination, chapter2Outline);

            // create the PDF link from TOC to subchapter 2
            document.CreatePdfLink(page1, subChapter22TocTitleRectangle, subChapter22Destination);

            #endregion

            // dispose the graphics used for measuring
            refGraphics.Dispose();
            refBmp.Dispose();

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

                FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf");
                fileResult.FileDownloadName = "PdfOutlines.pdf";

                return(fileResult);
            }
            finally
            {
                document.Close();
            }
        }
        public void FinalGroup(int Level)
        {
            //D:\Portada\HSKBooklets

            PdfWriter writer = new PdfWriter(@"D:\\HSKBooklet\Final_HSK_" + Level.ToString() + ".pdf");

            PdfDocument pdf       = new PdfDocument(new PdfWriter(writer));
            PdfMerger   merger    = new PdfMerger(pdf);
            PdfFont     fontKaiti = PdfFontFactory.CreateFont(FONT, PdfEncodings.IDENTITY_H, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED, true);


            pdf.AddFont(fontKaiti);

            //Interior Cover

            //Add pages from the first document
            PdfDocument InteriorCoverPdf = new PdfDocument(new PdfReader(@"D:\\Portada\HSKBooklets\Interior Cover Level " + Level.ToString() + ".pdf"));

            //From to
            merger.Merge(InteriorCoverPdf, 1, InteriorCoverPdf.GetNumberOfPages());



            //White White Page A4.pdf
            PdfDocument IWhitePdf = new PdfDocument(new PdfReader(@"D:\\Portada\HSKBooklets\White Page A4.pdf"));

            //From to
            merger.Merge(IWhitePdf, 1, IWhitePdf.GetNumberOfPages());

            //HSK Booklets D:\HSKBooklet 1_HSK
            PdfDocument bookletHSK = new PdfDocument(new PdfReader(@"D:\HSKBooklet\" + Level.ToString() + "_HSK.pdf"));

            //From to
            merger.Merge(bookletHSK, 1, bookletHSK.GetNumberOfPages());


            //Word Index Cover "Word Index Level 3.pdf"
            PdfDocument wordIndexCover = new PdfDocument(new PdfReader(@"D:\\Portada\\HSKBooklets\Word Index Level " + Level.ToString() + ".pdf"));

            //From to
            merger.Merge(wordIndexCover, 1, wordIndexCover.GetNumberOfPages());

            merger.Merge(IWhitePdf, 1, IWhitePdf.GetNumberOfPages());

            //Word Index

            PdfDocument wordIndex = new PdfDocument(new PdfReader(@"D:\\HSKBooklet\" + Level.ToString() + "WordIndex.pdf"));

            //From to
            merger.Merge(wordIndex, 1, wordIndex.GetNumberOfPages());


            //Char Cover "Character Index Level 1.pdf"
            PdfDocument CharacterIndexCover = new PdfDocument(new PdfReader(@"D:\\Portada\HSKBooklets\Character Index Level " + Level.ToString() + ".pdf"));

            //From to
            merger.Merge(CharacterIndexCover, 1, CharacterIndexCover.GetNumberOfPages());

            merger.Merge(IWhitePdf, 1, IWhitePdf.GetNumberOfPages());

            //Char Index

            PdfDocument caracterIndex = new PdfDocument(new PdfReader(@"D:\\HSKBooklet\" + Level.ToString() + "CaracterIndex.pdf"));

            //From to
            merger.Merge(caracterIndex, 1, caracterIndex.GetNumberOfPages());


            PdfDocument FinalCover = new PdfDocument(new PdfReader(@"D:\Portada\HSKBooklets\End Cover.pdf"));

            merger.Merge(FinalCover, 1, FinalCover.GetNumberOfPages());

            InteriorCoverPdf.Close();
            IWhitePdf.Close();

            bookletHSK.Close();
            wordIndexCover.Close();

            InteriorCoverPdf.Close();
            wordIndex.Close();
            CharacterIndexCover.Close();
            caracterIndex.Close();
            FinalCover.Close();
            pdf.Close();
        }
        public void WordIndexGenerator()
        {
            //Se incluyen los caracteres no las palabras
            List <Word> arrayIncluded = ToList(includedWords);

            int index = 1;

            //Hay que obtener caracter a caracter no las palabras TODO


            PdfWriter   writer   = new PdfWriter(@"D:\\HSKBooklet\" + Level.ToString() + "WordIndex.pdf");
            PdfDocument pdf      = new PdfDocument(writer);
            Document    document = new Document(pdf, PageSize.A4);

            const String FONT = @"C:\Windows\Fonts\STKAITI.TTF";
            //PdfFont fontKaiti = PdfFontFactory.CreateFont(FONT, PdfEncodings.IDENTITY_H, true, true);
            PdfFont fontKaiti = PdfFontFactory.CreateFont(FONT, PdfEncodings.IDENTITY_H, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED, true);

            document.SetFont(fontKaiti);


            var dimensionsColumns = new float[] { 25, 20, 20, 50, 10, 15 };

            Table table = new Table(UnitValue.CreatePercentArray(dimensionsColumns));

            table.UseAllAvailableWidth();

            int rowCount = 0;

            var OrderedChars = includedChars.OrderBy(x => x.Pinyin);

            var ArrayChars = OrderedChars.ToArray();

            //Palabra ordenadas alfabeticamente
            foreach (Word_HSK word in arrayIncluded)
            {
                bool first = true;

                foreach (char ch in word.Character.ToCharArray().Distinct())
                {
                    int Page = 0;
                    for (int x = 0; x < OrderedChars.Count(); x++)
                    {
                        if (ArrayChars.ElementAt(x).Character == ch.ToString())
                        {
                            Page = x;
                            break;
                        }
                    }

                    //El caracter aparece en la palabra word
                    //En la pagina index

                    // Adding cell 1 to the table

                    int SetMarginTopP = 10;
                    int SetHeightP    = 30;

                    //Shhh Esta chapuza es para que la descripcion no se repita tampoco
                    if (first)
                    {
                        Cell cell1 = new Cell(); // Creating a cell
                        cell1.Add(new Paragraph(word.Character).SetHeight(SetHeightP).SetFont(fontKaiti).SetBold().SetFontSize(20).SetTextAlignment(TextAlignment.LEFT).SetVerticalAlignment(VerticalAlignment.MIDDLE));
                        table.AddCell(cell1);    // Adding cell to the table


                        Cell cellPinyin = new Cell();
                        cellPinyin.Add(new Paragraph(word.Pinyin).SetFont(fontKaiti).SetFontSize(10).SetMarginTop(SetMarginTopP).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE));
                        table.AddCell(cellPinyin);

                        //Palabra que lo usa
                        Cell cell2 = new Cell();
                        cell2.Add(new Paragraph(ch.ToString()).SetFont(fontKaiti).SetFontSize(20).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE));
                        table.AddCell(cell2);

                        Cell cell3 = new Cell();
                        cell3.Add(new Paragraph(word.Description).SetFontSize(10).SetMarginLeft(20).SetMarginTop(SetMarginTopP).SetTextAlignment(TextAlignment.LEFT).SetVerticalAlignment(VerticalAlignment.MIDDLE));
                        table.AddCell(cell3);

                        first = false;
                    }
                    else
                    {
                        Cell cell1 = new Cell();   // Creating a cell
                        cell1.Add(new Paragraph(" ").SetHeight(SetHeightP).SetFont(fontKaiti).SetBold().SetFontSize(20).SetTextAlignment(TextAlignment.LEFT).SetVerticalAlignment(VerticalAlignment.MIDDLE));
                        table.AddCell(cell1);

                        Cell cellPinyin = new Cell();
                        cellPinyin.Add(new Paragraph(word.Pinyin).SetFont(fontKaiti).SetFontSize(10).SetMarginTop(SetMarginTopP).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE));
                        table.AddCell(cellPinyin);

                        //Palabra que lo usa
                        Cell cell2 = new Cell();
                        cell2.Add(new Paragraph(ch.ToString()).SetFont(fontKaiti).SetFontSize(20).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE));
                        table.AddCell(cell2);

                        Cell cell3 = new Cell();
                        cell3.Add(new Paragraph(" ").SetFontSize(10).SetMarginLeft(20).SetMarginTop(SetMarginTopP).SetTextAlignment(TextAlignment.LEFT).SetVerticalAlignment(VerticalAlignment.MIDDLE));
                        table.AddCell(cell3);
                    }

                    Cell cell4 = new Cell();
                    cell4.Add(new Paragraph("HSK " + word.Level.ToString()).SetFontSize(10).SetMarginTop(SetMarginTopP).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE));
                    table.AddCell(cell4);

                    Cell cell5 = new Cell();
                    cell5.Add(new Paragraph("Pag. " + (Page + 1).ToString()).SetFontSize(10).SetMarginTop(SetMarginTopP).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE));
                    table.AddCell(cell5);

                    rowCount++;

                    if (rowCount == 21)
                    {
                        PdfCanvas pdfCanvas = new PdfCanvas(pdf.AddNewPage());
                        Canvas    canvas    = new Canvas(pdfCanvas, pdf, document.GetPageEffectiveArea(pdf.GetDefaultPageSize()));
                        canvas.Add(table);

                        rowCount = 0;
                        table    = new Table(UnitValue.CreatePercentArray(dimensionsColumns));
                        table.UseAllAvailableWidth();
                    }
                }


                string sIndex = NumeroCuadrado(index, 3);
            }


            PdfCanvas pdfCanvasend = new PdfCanvas(pdf.AddNewPage());
            Canvas    canvasend    = new Canvas(pdfCanvasend, pdf, document.GetPageEffectiveArea(pdf.GetDefaultPageSize()));

            canvasend.Add(table);

            //Se añade una pagina en blanco al lomo de caracteres solo si es impar
            if (pdf.GetNumberOfPages() % 2 != 0)
            {
                PdfCanvas pdfCanvas = new PdfCanvas(pdf.AddNewPage());
            }

            document.Close();
        }
        public void CharacterIndexGenerator()
        {
            //Se incluyen los caracteres no las palabras
            List <Word> arrayIncluded = ToList(includedWords);

            int index = 0;

            //Hay que obtener caracter a caracter no las palabras TODO

            //INICIO DOCUMENTO PDF
            PdfWriter   writer   = new PdfWriter(@"D:\\HSKBooklet\" + Level.ToString() + "CaracterIndex.pdf");
            PdfDocument pdf      = new PdfDocument(writer);
            Document    document = new Document(pdf, PageSize.A4);

            const String FONT = @"C:\Windows\Fonts\STKAITI.TTF";
            //PdfFont fontKaiti = PdfFontFactory.CreateFont(FONT, PdfEncodings.IDENTITY_H, true, true);
            PdfFont fontKaiti = PdfFontFactory.CreateFont(FONT, PdfEncodings.IDENTITY_H, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED, true);

            document.SetFont(fontKaiti);

            //TABLA DE CONTENIDO

            var   DimensionesColumnas = new float[] { 5, 20, 20, 50, 10, 15 };
            Table table = new Table(UnitValue.CreatePercentArray(DimensionesColumnas));

            table.UseAllAvailableWidth();

            //TEST CON SOLO CINCO CARACTERES
            //includedChars.Clear();
            //includedChars.Add(new Word { Character = "电" });
            //includedChars.Add(new Word { Character = "出" });
            //includedChars.Add(new Word { Character = "永" });
            //includedChars.Add(new Word { Character = "一" });
            //includedChars.Add(new Word { Character = "问" });

            //Se usara para el salto de pagina
            int rowCount      = 0;
            int SetMarginTopP = 10;
            int SetHeightP    = 30;
            //Caracteres ordenados alfabeticamente
            var OrderedChars = includedChars.OrderBy(x => x.Pinyin);

            foreach (Word character in OrderedChars)

            {
                index++;
                bool first = true;
                foreach (Word_HSK word in arrayIncluded)
                {
                    //Add row to table
                    if (word.Character.Contains(character.Character))
                    {
                        //El caracter aparece en la palabra word
                        //En la pagina index

                        // Adding cell 1 to the table
                        if (first)
                        {
                            Cell cell1 = new Cell();   // Creating a cell
                            cell1.Add(new Paragraph(character.Character).SetHeight(SetHeightP).SetFont(fontKaiti).SetBold().SetFontSize(20).SetTextAlignment(TextAlignment.LEFT).SetVerticalAlignment(VerticalAlignment.MIDDLE));
                            table.AddCell(cell1);      // Adding cell to the table

                            first = false;
                        }
                        else
                        {
                            Cell cell1 = new Cell();
                            cell1.Add(new Paragraph(" ").SetHeight(SetHeightP).SetFont(fontKaiti).SetBold().SetFontSize(30).SetTextAlignment(TextAlignment.LEFT));
                            table.AddCell(cell1);
                        }
                        //Palabra que lo usa
                        Cell cell2 = new Cell();
                        cell2.Add(new Paragraph(word.Character).SetFont(fontKaiti).SetFontSize(20).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE));
                        table.AddCell(cell2);

                        Cell cellPinyin = new Cell();
                        cellPinyin.Add(new Paragraph(word.Pinyin).SetFont(fontKaiti).SetFontSize(10).SetMarginTop(SetMarginTopP).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE));
                        table.AddCell(cellPinyin);

                        Cell cell3 = new Cell();
                        cell3.Add(new Paragraph(word.Description).SetFontSize(10).SetMarginLeft(20).SetMarginTop(SetMarginTopP).SetTextAlignment(TextAlignment.LEFT).SetVerticalAlignment(VerticalAlignment.MIDDLE));
                        table.AddCell(cell3);

                        Cell cell4 = new Cell();
                        cell4.Add(new Paragraph("HSK " + word.Level.ToString()).SetFontSize(10).SetMarginTop(SetMarginTopP).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE));
                        table.AddCell(cell4);

                        Cell cell5 = new Cell();
                        cell5.Add(new Paragraph("Pag. " + index.ToString()).SetFontSize(10).SetMarginTop(SetMarginTopP).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE));
                        table.AddCell(cell5);

                        rowCount++;

                        //Salto de linea
                        if (rowCount == 21)
                        {
                            PdfCanvas pdfCanvas = new PdfCanvas(pdf.AddNewPage());
                            Canvas    canvas    = new Canvas(pdfCanvas, pdf, document.GetPageEffectiveArea(pdf.GetDefaultPageSize()));
                            canvas.Add(table);

                            rowCount = 0;

                            table = new Table(UnitValue.CreatePercentArray(DimensionesColumnas));
                            table.UseAllAvailableWidth();
                        }
                    }
                }


                string sIndex = NumeroCuadrado(index, 3);
            }


            PdfCanvas pdfCanvasend = new PdfCanvas(pdf.AddNewPage());
            Canvas    canvasend    = new Canvas(pdfCanvasend, pdf, document.GetPageEffectiveArea(pdf.GetDefaultPageSize()));

            canvasend.Add(table);



            //Se añade una pagina en blanco al lomo de caracteres solo si es impar
            if (pdf.GetNumberOfPages() % 2 == 0)
            {
                PdfCanvas pdfCanvas = new PdfCanvas(pdf.AddNewPage());
            }

            document.Close();
        }
Пример #25
0
        private static void CreateRichMediaAnnotations(PdfFixedDocument document, PdfFont font, Stream flashStream)
        {
            PdfBrush blackBrush = new PdfBrush();

            PdfPage page = document.Pages.Add();

            page.Graphics.DrawString("Rich media annotations", font, blackBrush, 50, 50);

            byte[] flashContent = new byte[flashStream.Length];
            flashStream.Read(flashContent, 0, flashContent.Length);

            PdfRichMediaAnnotation rma = new PdfRichMediaAnnotation();
            page.Annotations.Add(rma);
            rma.VisualRectangle = new PdfVisualRectangle(100, 100, 400, 400);
            rma.FlashPayload = flashContent;
            rma.FlashFile = "clock.swf";
            rma.ActivationCondition = PdfRichMediaActivationCondition.PageVisible;
        }
Пример #26
0
 public PdfExporter(PdfDesign pdfDesign)
 {
     _pdfDesign = pdfDesign;
     _pdfFont   = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);
 }
Пример #27
0
        private static void CreateSquareCircleAnnotations(PdfFixedDocument document, PdfFont font)
        {
            PdfBrush blackBrush = new PdfBrush();

            PdfPage page = document.Pages.Add();

            page.Graphics.DrawString("Square annotations", font, blackBrush, 50, 50);

            PdfSquareAnnotation square1 = new PdfSquareAnnotation();
            page.Annotations.Add(square1);
            square1.Author = "Xfinium.pdf";
            square1.Contents = "Square annotation with red border";
            square1.BorderColor = new PdfRgbColor(255, 0, 0);
            square1.BorderWidth = 3;
            square1.VisualRectangle = new PdfVisualRectangle(50, 70, 250, 150);

            PdfSquareAnnotation square2 = new PdfSquareAnnotation();
            page.Annotations.Add(square2);
            square2.Author = "Xfinium.pdf";
            square2.Contents = "Square annotation with blue interior";
            square2.BorderColor = null;
            square2.BorderWidth = 0;
            square2.InteriorColor = new PdfRgbColor(0, 0, 192);
            square2.VisualRectangle = new PdfVisualRectangle(50, 270, 250, 150);

            PdfSquareAnnotation square3 = new PdfSquareAnnotation();
            page.Annotations.Add(square3);
            square3.Author = "Xfinium.pdf";
            square3.Contents = "Square annotation with yellow border and green interior";
            square3.BorderColor = new PdfRgbColor(255, 255, 0);
            square3.BorderWidth = 3;
            square3.InteriorColor = new PdfRgbColor(0, 192, 0);
            square3.VisualRectangle = new PdfVisualRectangle(50, 470, 250, 150);

            page.Graphics.DrawString("Circle annotations", font, blackBrush, 50, 350);

            PdfCircleAnnotation circle1 = new PdfCircleAnnotation();
            page.Annotations.Add(circle1);
            circle1.Author = "Xfinium.pdf";
            circle1.Contents = "Circle annotation with red border";
            circle1.BorderColor = new PdfRgbColor(255, 0, 0);
            circle1.BorderWidth = 3;
            circle1.VisualRectangle = new PdfVisualRectangle(350, 70, 250, 150);

            PdfCircleAnnotation circle2 = new PdfCircleAnnotation();
            page.Annotations.Add(circle2);
            circle2.Author = "Xfinium.pdf";
            circle2.Contents = "Circle annotation with blue interior";
            circle2.BorderColor = null;
            circle2.BorderWidth = 0;
            circle2.InteriorColor = new PdfRgbColor(0, 0, 192);
            circle2.VisualRectangle = new PdfVisualRectangle(350, 270, 250, 150);

            PdfCircleAnnotation circle3 = new PdfCircleAnnotation();
            page.Annotations.Add(circle3);
            circle3.Author = "Xfinium.pdf";
            circle3.Contents = "Circle annotation with yellow border and green interior";
            circle3.BorderColor = new PdfRgbColor(255, 255, 0);
            circle3.BorderWidth = 3;
            circle3.InteriorColor = new PdfRgbColor(0, 192, 0);
            circle3.VisualRectangle = new PdfVisualRectangle(350, 470, 250, 150);
        }
Пример #28
0
        private void button1_Click(object sender, EventArgs e)
        {
            LicenseKey.LoadLicenseFile("C:/Users/Toni/Desktop/Fingerprint_Test/itextkey1524180183686_0.xml");

            iText.Layout.Element.Image leftIndex  = new iText.Layout.Element.Image(ImageDataFactory.Create(LeftIndex));
            iText.Layout.Element.Image rightIndex = new iText.Layout.Element.Image(ImageDataFactory.Create(RightIndex));

            /*
             * // Modify PDF located at "source" and save to "target"
             * PdfDocument pdfDocument = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
             * // Document to add layout elements: paragraphs, images etc
             * Document document = new Document(pdfDocument);
             *
             * // Load image from disk
             * ImageData imageData = ImageDataFactory.Create(LeftIndex);
             * // Create layout image object and provide parameters. Page number = 1
             * iText.Layout.Element.Image image = new iText.Layout.Element.Image(imageData).ScaleAbsolute(100, 200).SetFixedPosition(1, 25, 25);
             * // This adds the image to the page
             * document.Add(image);
             *
             * // Don't forget to close the document.
             * // When you use Document, you should close it rather than PdfDocument instance
             * document.Close();
             */

            // Read each line of the file into a string array. Each element
            // of the array is one line of the file.
            string[] lines = System.IO.File.ReadAllLines(info_src, Encoding.UTF8);

            //string line1 = System.Text.Encoding.UTF8.GetString(lines[1]);

            // Display the file contents by using a foreach loop.
            //Console.OutputEncoding = Encoding.UTF8;
            //System.Console.OutputEncoding = System.Text.Encoding.UTF8;
            //System.Console.WriteLine("Contents of WriteLines2.txt = ");
            textBox1.Text = lines[1];
            foreach (string line in lines)
            {
                // Use a tab to indent each line of the file.
                //Console.WriteLine("\t" + line/*, Console.OutputEncoding.UTF8Encoding*/);
            }


            var writer   = new PdfWriter(dest);
            var pdf      = new PdfDocument(writer);
            var document = new Document(pdf);

            document.Add(new Paragraph("Hello World!"));

            //************************************************************************************
            //Russian Part:

            //Text Constants:
            String CZECH =
                "Podivn\u00fd p\u0159\u00edpad Dr. Jekylla a pana Hyda";
            String RUSSIAN =
                "\u0421\u0442\u0440\u0430\u043d\u043d\u0430\u044f "
                + "\u0438\u0441\u0442\u043e\u0440\u0438\u044f "
                + "\u0434\u043e\u043a\u0442\u043e\u0440\u0430 "
                + "\u0414\u0436\u0435\u043a\u0438\u043b\u0430 \u0438 "
                + "\u043c\u0438\u0441\u0442\u0435\u0440\u0430 "
                + "\u0425\u0430\u0439\u0434\u0430";
            String KOREAN =
                "\ud558\uc774\ub4dc, \uc9c0\ud0ac, \ub098";

            //Font Constants:
            String FONT      = "C:/Users/Toni/Desktop/Fingerprint_Test/FreeSans.ttf";  //"src/main/resources/fonts/FreeSans.ttf";
            String HCRBATANG = "C:/Users/Toni/Desktop/Fingerprint_Test/HANBatang.ttf"; //"src/main/resources/fonts/HANBatang.ttf";
            //String NAZANIN = "C:/Users/Toni/Desktop/Fingerprint_Test/B Nazanin.ttf"; //"src/main/resources/fonts/HANBatang.ttf";

            //Add to Document:
            PdfFont font1250 = PdfFontFactory.CreateFont(FONT, PdfEncodings.CP1250, true);

            document.Add(new Paragraph().SetFont(font1250)
                         .Add(CZECH).Add(" by Robert Louis Stevenson"));
            PdfFont font1251 = PdfFontFactory.CreateFont(FONT, "Cp1251", true);

            document.Add(new Paragraph().SetFont(font1251)
                         .Add(RUSSIAN).Add(" by Robert Louis Stevenson"));
            PdfFont fontUnicode = PdfFontFactory.CreateFont(HCRBATANG, PdfEncodings.IDENTITY_H, true);

            document.Add(new Paragraph().SetFont(fontUnicode)
                         .Add(KOREAN).Add(" by Robert Louis Stevenson"));

            //End Russian Part
            //************************************************************************************

            /*
             * //Add Arabic-Inverted
             * PdfFont fontUnicodeNazanin =
             * PdfFontFactory.CreateFont(NAZANIN, PdfEncodings.IDENTITY_H, true);
             * //document.Add(new Paragraph().SetFont(fontUnicodeNazanin)
             * //.Add("الموافق").Add(" by Ostad"));
             *
             * //Add Arabic Correct (?) @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
             * //itext 7 Equivalent
             * //Text redText = new Text("Nos formules")
             * Text redText = new Text("الموافق")
             * .SetFont(fontUnicodeNazanin)
             * .SetFontSize(20);
             * Paragraph p2 = new Paragraph().Add(redText);
             * //document.Add(p2);
             * //document.Add(new Phrase("This is a ميسو ɸ", f));
             */

            /*
             * //************************************************************************************
             * //Style Part:
             * Style arabic = new Style().SetTextAlignment(TextAlignment.RIGHT).SetBaseDirection(BaseDirection.RIGHT_TO_LEFT).
             *  SetFontSize(20).SetFont(fontUnicodeNazanin);
             *
             * //document.Add(new Paragraph("م الموافق").SetFontScript(Character.UnicodeScript.ARABIC).AddStyle(arabic));
             *
             *
             * //End Style Part
             * //************************************************************************************
             */

            /*
             * var times = PdfFontFactory.CreateFont(NAZANIN, PdfEncodings.IDENTITY_H, true);
             * Style arabic2 = new Style().SetBaseDirection(BaseDirection.RIGHT_TO_LEFT);
             * Paragraph p3 = new Paragraph();
             * p3.SetFont(NAZANIN);
             * p3.AddStyle(arabic2);
             * Text t = new Text("أسبوع");
             * p3.Add(t);
             * //document.Add(p3);
             */

            //************************************************************************************
            //Calligraph Part:

            Document arabicPdf = new Document(new PdfDocument(new PdfWriter("C:/Users/Toni/Desktop/Fingerprint_Test/arabic.pdf")));

            // Arabic text starts near the top right corner of the page
            arabicPdf.SetTextAlignment(TextAlignment.RIGHT);

            // create a font, and make it the default for the document
            //PdfFont f = PdfFontFactory.CreateFont("C:/Users/Toni/Desktop/Fingerprint_Test/DroidKufi-Regular.ttf", PdfEncodings.IDENTITY_H, true);
            //Arial -> OK
            //Tahoma -> OK
            //Koodak -> OK
            //A_Nefel_Botan -> OK
            //PdfFont f = PdfFontFactory.CreateFont("C:/Windows/Fonts/tahoma.ttf", PdfEncodings.IDENTITY_H, true);
            PdfFont f = PdfFontFactory.CreateFont("C:/Users/Toni/Desktop/Fingerprint_Test/A_Nefel_Botan.ttf", PdfEncodings.IDENTITY_H, true);

            //PdfFont f = PdfFontFactory.CreateFont("C:/Windows/Fonts/W_nazanin.ttf", PdfEncodings.IDENTITY_H, true);
            arabicPdf.SetFont(f);

            // add content: السلام عليكم (as-salaamu 'aleykum - peace be upon you)
            //arabicPdf.Add(new Paragraph("أسبوع"));
            //arabicPdf.Add(new Paragraph("هویج"));
            arabicPdf.Add(new Paragraph(lines[1]));

            arabicPdf.Close();

            //End Calligraph Part
            //************************************************************************************

            /*
             * //************************************************************************************
             * //Hebrew Part:
             *
             * //Use a table so that we can set the text direction
             * Table table = new Table(1);
             * //Ensure that wrapping is on, otherwise Right to Left text will not display
             * //table.DefaultCell.NoWrap = false;
             * table.AddStyle(arabic);
             *
             * table.AddCell(new Cell().SetHorizontalAlignment(HorizontalAlignment.CENTER).Add(p2));
             *
             *
             * //Create a regex expression to detect hebrew or arabic code points
             * const string regex_match_arabic_hebrew = @"[\u0600-\u06FF,\u0590-\u05FF]+";
             * //if (Regex.IsMatch("מה קורה", regex_match_arabic_hebrew, RegexOptions.IgnoreCase))
             * {
             *  table.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
             * }
             *
             * //Create a cell and add text to it
             * PdfPCell text = new PdfPCell(new Phrase("מה קורה", font));
             * //Ensure that wrapping is on, otherwise Right to Left text will not display
             * text.NoWrap = false;
             *
             * //Add the cell to the table
             * table.AddCell(text);
             *
             * //Add the table to the document
             * document.Add(table);
             * //End Hebrew Part
             * //************************************************************************************
             */

            document.Add(new Paragraph(lines[1]));
            Paragraph p = new Paragraph("Right Index").Add(rightIndex).Add("Left Index").Add(leftIndex);

            // Add Paragraph to document
            document.Add(p);

            //********************************************************************************************************
            //Arabic in pdf using iTextSharp in c#
            //********************************************************************************************************

            /*
             * //Declare a itextSharp document
             * //Document document = new Document(PageSize.A4);
             * //Create our file stream and bind the writer to the document and the stream
             * //PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(@"D:\Test.Pdf", FileMode.Create));
             *
             * //Open the document for writing
             * //document.Open();
             *
             * //Add a new page
             * //document.NewPage();
             *
             * //Reference a Unicode font to be sure that the symbols are present.
             * BaseFont bfArialUniCode = BaseFont.CreateFont(@"D:\ARIALUNI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
             * //Create a font from the base font
             * Font font = new Font(bfArialUniCode, 12);
             *
             * //Use a table so that we can set the text direction
             * PdfPTable table = new PdfPTable(1);
             * //Ensure that wrapping is on, otherwise Right to Left text will not display
             * table.DefaultCell.NoWrap = false;
             *
             * //Create a regex expression to detect hebrew or arabic code points
             * const string regex_match_arabic_hebrew = @"[\u0600-\u06FF,\u0590-\u05FF]+";
             * if (Regex.IsMatch("م الموافق", regex_match_arabic_hebrew, RegexOptions.IgnoreCase))
             * {
             *  table.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
             * }
             *
             * //Create a cell and add text to it
             * PdfPCell text = new PdfPCell(new Phrase(" : " + "من قبل وبين" + " 2007 " + "م الموافق" + " dsdsdsdsds " + "تم إبرام هذا العقد في هذا اليوم ", font));
             * //Ensure that wrapping is on, otherwise Right to Left text will not display
             * text.NoWrap = false;
             *
             * //Add the cell to the table
             * table.AddCell(text);
             *
             * //Add the table to the document
             * document.Add(table);
             *
             * //PdfFont f = PdfFontFactory.createFont(FONT, PdfEncodings.IDENTITY_H);
             *
             * //*********************************************************************
             *
             * //Launch the document if you have a file association set for PDF's
             * //Process AcrobatReader = new Process();
             * //AcrobatReader.StartInfo.FileName = @"D:\Test.Pdf";
             * //AcrobatReader.Start();
             */


            document.Close();
        }
Пример #29
0
        /// <summary>
        /// Add text to text box.
        /// </summary>
        /// <param name="Font">Font</param>
        /// <param name="FontSize">Font size</param>
        /// <param name="DrawStyle">Drawing style</param>
        /// <param name="Text">Text</param>
        public void AddText(
			PdfFont		Font,
			Double		FontSize,
			DrawStyle	DrawStyle,
			String		Text
			)
        {
            AddText(Font, FontSize, DrawStyle, Color.Empty, Text, null);
            return;
        }
Пример #30
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==";

            // add a page to document
            PdfPage page = document.AddPage();

            // create true type fonts that can be used in document
            System.Drawing.Font ttfFont      = new System.Drawing.Font("Times New Roman", 10, System.Drawing.GraphicsUnit.Point);
            PdfFont             newTimesFont = document.CreateFont(ttfFont, false);

            // create a standard font that can be used in document
            PdfFont helveticaStd = document.CreateStandardFont(PdfStandardFont.Helvetica);

            helveticaStd.Size = 10;

            float crtXPos = 10;
            float crtYPos = 10;

            #region Add Check Box Field

            if (checkBoxAddCheckBox.Checked)
            {
                // add a check box field to PDF form
                PdfFormCheckBox checkBoxField = document.Form.AddCheckBox(page, new System.Drawing.RectangleF(crtXPos, crtYPos, 10, 10));

                checkBoxField.Checked = checkBoxCheckedState.Checked;

                // common field properties
                checkBoxField.Name     = "cb";
                checkBoxField.ToolTip  = "Click to change the checked state";
                checkBoxField.Required = false;
                checkBoxField.ReadOnly = false;
                checkBoxField.Flatten  = false;

                // advance the current drawing position in PDF page
                crtYPos = checkBoxField.BoundingRectangle.Bottom + 5;
            }

            #endregion

            #region Add Text Box Field

            if (checkBoxAddTextBox.Checked)
            {
                string         initialText  = textBoxInitialText.Text;
                PdfFormTextBox textBoxField = document.Form.AddTextBox(page, new System.Drawing.RectangleF(crtXPos, crtYPos, 300, 50), initialText, newTimesFont);

                textBoxField.IsMultiLine = checkBoxMultiline.Checked;
                textBoxField.IsPassword  = checkBoxIsPassword.Checked;

                textBoxField.Style.ForeColor   = System.Drawing.Color.Navy;
                textBoxField.Style.BackColor   = System.Drawing.Color.WhiteSmoke;
                textBoxField.Style.BorderStyle = PdfBorderStyle.FixedSingle;
                textBoxField.Style.BorderColor = System.Drawing.Color.Green;

                // common field properties
                textBoxField.Name         = "tb";
                textBoxField.ToolTip      = "Please enter some text";
                textBoxField.Required     = false;
                textBoxField.ReadOnly     = false;
                textBoxField.DefaultValue = "Default text";
                textBoxField.Flatten      = false;

                // advance the current drawing position in PDF page
                crtYPos = textBoxField.BoundingRectangle.Bottom + 5;
            }

            #endregion

            #region Add  List Box Field

            if (checkBoxAddListBox.Checked)
            {
                string[] listValues = textBoxListBoxValues.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                PdfFormListBox listBoxField = document.Form.AddListBox(page, new System.Drawing.RectangleF(crtXPos, crtYPos, 300, 50), listValues, helveticaStd);

                // common field properties
                listBoxField.Name     = "lb";
                listBoxField.ToolTip  = "Select an element from the list";
                listBoxField.Required = false;
                listBoxField.ReadOnly = false;
                if (listValues.Length > 0)
                {
                    listBoxField.DefaultValue = listValues[0];
                }
                listBoxField.Flatten = false;

                // advance the current drawing position in PDF page
                crtYPos = listBoxField.BoundingRectangle.Bottom + 5;
            }

            #endregion

            #region Add Combo Box Field

            if (checkBoxAddComboBox.Checked)
            {
                string[] listValues = textBoxComboBoxValues.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                PdfFormComboBox comboBoxField = document.Form.AddComboBox(page, new System.Drawing.RectangleF(crtXPos, crtYPos, 300, 15), listValues, helveticaStd);

                comboBoxField.Editable = checkBoxEditableCombo.Checked;

                // common field properties
                comboBoxField.Name     = "combo";
                comboBoxField.ToolTip  = "Select an element from the combo drop down";
                comboBoxField.Required = false;
                comboBoxField.ReadOnly = false;
                if (listValues.Length > 0)
                {
                    comboBoxField.DefaultValue = listValues[0];
                }
                comboBoxField.Flatten = false;

                // advance the current drawing position in PDF page
                crtYPos = comboBoxField.BoundingRectangle.Bottom + 5;
            }

            #endregion

            #region Add Radio Buttons Group Field

            if (checkBoxAddRadioButtons.Checked)
            {
                PdfFormRadioButtonsGroup radioGroup = document.Form.AddRadioButtonsGroup(page);

                PdfFormRadioButton rb1 = radioGroup.AddRadioButton(new System.Drawing.RectangleF(crtXPos, crtYPos, 10, 10), "rb1");
                PdfFormRadioButton rb2 = radioGroup.AddRadioButton(new System.Drawing.RectangleF(crtXPos + 20, crtYPos, 10, 10), "rb2");

                radioGroup.SetCheckedRadioButton(rb2);

                radioGroup.Name = "rg";

                // advance the current drawing position in PDF page
                crtYPos = rb1.BoundingRectangle.Bottom + 20;
            }

            #endregion

            #region Create the Submit Button

            // create the Submit button
            PdfFormButton submitButton = document.Form.AddButton(page, new System.Drawing.RectangleF(crtXPos, crtYPos, 100, 20), "Submit Form", newTimesFont);
            submitButton.Name = "submitButton";

            // create the submit action with the submit URL
            PdfSubmitFormAction submitAction = new PdfSubmitFormAction(textBoxSubmitUrl.Text);
            // set the action flags such that the form values are submitted in HTML form format
            submitAction.Flags |= PdfFormSubmitFlags.ExportFormat;
            if (radioButtonGet.Checked)
            {
                submitAction.Flags |= PdfFormSubmitFlags.GetMethod;
            }

            // set the submit button action
            submitButton.Action = submitAction;

            #endregion

            #region Create the Reset Button

            if (checkBoxAddResetButton.Checked)
            {
                // create the reset button
                PdfFormButton resetButton = document.Form.AddButton(page, new System.Drawing.RectangleF(crtXPos + 120, crtYPos, 100, 20),
                                                                    "Reset Form", newTimesFont);
                resetButton.Name = "resetButton";

                // create the reset action
                PdfResetFormAction resetAction = new PdfResetFormAction();

                // set the reset button action
                resetButton.Action = resetAction;
            }

            #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=CreateForms.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();
            }
        }
Пример #31
0
        /// <summary>
        /// Compare two TextBox segments.
        /// </summary>
        /// <param name="Font">Segment font.</param>
        /// <param name="FontSize">Segment font size.</param>
        /// <param name="DrawStyle">Segment drawing style.</param>
        /// <param name="FontColor">Segment color.</param>
        /// <param name="WebLink">Segment web link.</param>
        /// <returns>Result</returns>
        public Boolean IsEqual(
			PdfFont		Font,
			Double		FontSize,
			DrawStyle	DrawStyle,
			Color		FontColor,
			String		WebLink
			)
        {
            // test all but weblink
            if(this.Font != Font || this.FontSize != FontSize || this.DrawStyle != DrawStyle || this.FontColor != FontColor) return(false);

            // weblink argument is null. return true if local weblink is null. return false otherwise
            if(String.IsNullOrWhiteSpace(WebLink)) return(this.WebLink == null);

            // weblink argument is not null. return true if local weblink is not null and both are equal. return false otherwise
            return(this.WebLink != null && this.WebLink.Equals(WebLink));
        }
Пример #32
0
 internal virtual iText.Forms.Fields.AppearanceResources AddFontFromDefaultResources(PdfName name, PdfFont
                                                                                     font)
 {
     if (name != null && font != null && font.GetPdfObject().GetIndirectReference() != null)
     {
         //So, most likely it's a document PdfFont
         drFonts.Put(font.GetPdfObject().GetIndirectReference(), name);
     }
     return(this);
 }
Пример #33
0
 public virtual float GetTextContentLength(float parentFontSize, PdfFont font)
 {
     return(0.0f);
 }
Пример #34
0
        protected void createPdfButton_Click(object sender, EventArgs e)
        {
            // Get the server IP and port
            String serverIP   = textBoxServerIP.Text;
            uint   serverPort = uint.Parse(textBoxServerPort.Text);

            // Create a PDF document
            Document pdfDocument = new Document(serverIP, serverPort);

            // Set optional service password
            if (textBoxServicePassword.Text.Length > 0)
            {
                pdfDocument.ServicePassword = textBoxServicePassword.Text;
            }

            // Set license key received after purchase to use the converter in licensed mode
            // Leave it not set to use the converter in demo mode
            pdfDocument.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c=";

            // Add a page to PDF document
            PdfPage pdfPage = pdfDocument.AddPage();

            // The titles font used to mark various sections of the PDF document
            PdfFont titleFont = new PdfFont("Times New Roman", 10, true);

            titleFont.Bold = true;
            PdfFont subtitleFont = new PdfFont("Times New Roman", 8, true);

            // Add document title
            TextElement titleTextElement = new TextElement(5, 5, "Add Text Notes to a PDF Document", titleFont);

            pdfPage.AddElement(titleTextElement);

            // Add the text element
            string      text        = "Click the next icon to open the the text note:";
            TextElement textElement = new TextElement(0, 0, 200, text, subtitleFont);

            pdfDocument.AddElement(textElement, 10);

            RectangleFloat textNoteRectangle = new RectangleFloat(0, 0, 10, 10);

            // Create the text note
            TextNoteElement textNoteElement = new TextNoteElement(textNoteRectangle, "This is an initially closed text note");

            textNoteElement.NoteIcon = TextNoteIcon.Note;
            textNoteElement.Open     = false;
            pdfDocument.AddElement(textNoteElement, 10, true, false, 0, true, false);

            // Add the text element
            text        = "This is an already opened text note:";
            textElement = new TextElement(0, 0, 200, text, subtitleFont);
            pdfDocument.AddElement(textElement, 5, false, 10, true);

            textNoteRectangle = new RectangleFloat(0, 0, 10, 10);

            // Create the text note
            TextNoteElement textNoteOpenedElement = new TextNoteElement(textNoteRectangle, "This is an initially opened text note");

            textNoteOpenedElement.NoteIcon = TextNoteIcon.Note;
            textNoteOpenedElement.Open     = true;
            pdfDocument.AddElement(textNoteOpenedElement, 10, true, false, 0, true, false);


            // Add the text element
            text        = "Click the next icon to open the the help note:";
            textElement = new TextElement(0, 0, 200, text, subtitleFont);
            pdfDocument.AddElement(textElement, 5, false, 10, true);

            textNoteRectangle = new RectangleFloat(0, 0, 10, 10);

            // Create the text note
            TextNoteElement helpNoteElement = new TextNoteElement(textNoteRectangle, "This is an initially closed help note");

            helpNoteElement.NoteIcon = TextNoteIcon.Help;
            helpNoteElement.Open     = false;
            pdfDocument.AddElement(helpNoteElement, 10, true, false, 0, true, false);

            // Add the text element
            text        = "This is an already opened help note:";
            textElement = new TextElement(0, 0, 200, text, subtitleFont);
            pdfDocument.AddElement(textElement, 5, false, 10, true);

            textNoteRectangle = new RectangleFloat(0, 0, 10, 10);

            // Create the text note
            TextNoteElement helpNoteOpenedElement = new TextNoteElement(textNoteRectangle, "This is an initially opened help note");

            helpNoteOpenedElement.NoteIcon = TextNoteIcon.Help;
            helpNoteOpenedElement.Open     = true;
            pdfDocument.AddElement(helpNoteOpenedElement, 10, true, false, 0, true, false);

            // Add the text element
            text        = "Click the next icon to open the comment:";
            textElement = new TextElement(0, 0, 200, text, subtitleFont);
            pdfDocument.AddElement(textElement, 5, false, 10, true);

            textNoteRectangle = new RectangleFloat(0, 0, 10, 10);

            // Create the text note
            TextNoteElement commentNoteElement = new TextNoteElement(textNoteRectangle, "This is an initially closed comment note");

            commentNoteElement.NoteIcon = TextNoteIcon.Comment;
            commentNoteElement.Open     = false;
            pdfDocument.AddElement(commentNoteElement, 10, true, false, 0, true, false);


            // Add the text element
            text        = "This is an already opened comment:";
            textElement = new TextElement(0, 0, 200, text, subtitleFont);
            pdfDocument.AddElement(textElement, 5, false, 10, true);

            textNoteRectangle = new RectangleFloat(0, 0, 10, 10);

            // Create the text note
            TextNoteElement commentNoteOpenedElement = new TextNoteElement(textNoteRectangle, "This is an initially opened comment note");

            commentNoteOpenedElement.NoteIcon = TextNoteIcon.Comment;
            commentNoteOpenedElement.Open     = true;
            pdfDocument.AddElement(commentNoteOpenedElement, 10, true, false, 0, true, false);

            // Add the text element
            text        = "Click the next icon to open the paragraph note: ";
            textElement = new TextElement(0, 0, 200, text, subtitleFont);
            pdfDocument.AddElement(textElement, 5, false, 10, true);

            textNoteRectangle = new RectangleFloat(0, 0, 10, 10);

            // Create the text note
            TextNoteElement paragraphNoteElement = new TextNoteElement(textNoteRectangle, "This is an initially closed paragraph note");

            paragraphNoteElement.NoteIcon = TextNoteIcon.Paragraph;
            paragraphNoteElement.Open     = false;
            pdfDocument.AddElement(paragraphNoteElement, 10, true, false, 0, true, false);

            // Add the text element
            text        = "Click the next icon to open the new paragraph note:";
            textElement = new TextElement(0, 0, 200, text, subtitleFont);
            pdfDocument.AddElement(textElement, 5, false, 10, true);

            textNoteRectangle = new RectangleFloat(0, 0, 10, 10);

            // Create the text note
            TextNoteElement newParagraphNoteElement = new TextNoteElement(textNoteRectangle, "This is an initially closed new paragraph note");

            newParagraphNoteElement.NoteIcon = TextNoteIcon.NewParagraph;
            newParagraphNoteElement.Open     = false;
            pdfDocument.AddElement(newParagraphNoteElement, 10, true, false, 0, true, false);

            // Add the text element
            text        = "Click the next icon to open the key note:";
            textElement = new TextElement(0, 0, 200, text, subtitleFont);
            pdfDocument.AddElement(textElement, 5, false, 10, true);

            textNoteRectangle = new RectangleFloat(0, 0, 10, 10);

            // Create the text note
            TextNoteElement keyNoteElement = new TextNoteElement(textNoteRectangle, "This is an initially closed key note");

            keyNoteElement.NoteIcon = TextNoteIcon.Key;
            keyNoteElement.Open     = false;
            pdfDocument.AddElement(keyNoteElement, 10, true, false, 0, true, false);

            // Save the PDF document in a memory buffer
            byte[] outPdfBuffer = pdfDocument.Save();

            // Send the PDF as response to browser

            // Set response content type
            Response.AddHeader("Content-Type", "application/pdf");

            // Instruct the browser to open the PDF file as an attachment or inline
            Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Text_Notes.pdf; size={0}", outPdfBuffer.Length.ToString()));

            // Write the PDF document buffer to HTTP response
            Response.BinaryWrite(outPdfBuffer);

            // End the HTTP response and stop the current page processing
            Response.End();
        }
        public ActionResult CreatePdf(FormCollection collection)
        {
            // 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);

            System.Drawing.Font sysFontBold = new System.Drawing.Font("Times New Roman", 10, System.Drawing.FontStyle.Bold,
                                                                      System.Drawing.GraphicsUnit.Point);
            PdfFont pdfFontBold      = document.CreateFont(sysFontBold);
            PdfFont pdfFontBoldEmbed = document.CreateFont(sysFontBold, true);

            // create a standard Helvetica Type 1 font that can be used in document text
            PdfFont helveticaStdFont = document.CreateStandardFont(PdfStandardFont.Helvetica);

            helveticaStdFont.Size = 10;

            float crtYPos = 20;
            float crtXPos = 5;

            PdfLayoutInfo textLayoutInfo = null;

            string dummyText = @"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

            #region Layout a text that expands to the right edge of the PDF page

            PdfText titleTextAtLocation = new PdfText(crtXPos, crtYPos,
                                                      "The text below extends from the layout position to the right edge of the PDF page:", pdfFontBoldEmbed);
            titleTextAtLocation.ForeColor = System.Drawing.Color.Navy;
            textLayoutInfo = page1.Layout(titleTextAtLocation);

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

            PdfText textExpandsToRightEdge = new PdfText(crtXPos + 50, crtYPos, dummyText, pdfFont);
            textExpandsToRightEdge.BackColor = System.Drawing.Color.WhiteSmoke;
            textLayoutInfo = page1.Layout(textExpandsToRightEdge);

            // draw a rectangle around the text
            PdfRectangle borderPdfRectangle = new PdfRectangle(textLayoutInfo.LastPageRectangle);
            borderPdfRectangle.LineStyle.LineWidth = 0.5f;
            page1.Layout(borderPdfRectangle);

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

            #endregion

            #region Layout a text with width limit

            PdfText titleTextWithWidth = new PdfText(crtXPos, crtYPos,
                                                     "The text below is limited by a given width and has a free height:", pdfFontBoldEmbed);
            titleTextWithWidth.ForeColor = System.Drawing.Color.Navy;
            textLayoutInfo = page1.Layout(titleTextWithWidth);

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

            PdfText textWithWidthLimit = new PdfText(crtXPos + 50, crtYPos, 300, dummyText, pdfFont);
            textWithWidthLimit.BackColor = System.Drawing.Color.WhiteSmoke;
            textLayoutInfo = page1.Layout(textWithWidthLimit);

            // draw a rectangle around the text
            borderPdfRectangle = new PdfRectangle(textLayoutInfo.LastPageRectangle);
            borderPdfRectangle.LineStyle.LineWidth = 0.5f;
            page1.Layout(borderPdfRectangle);

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

            #endregion

            #region Layout a text with width and height limits

            PdfText titleTextWithWidthAndHeight = new PdfText(crtXPos, crtYPos,
                                                              "The text below is limited by a given width and height and is trimmed:", pdfFontBoldEmbed);
            titleTextWithWidthAndHeight.ForeColor = System.Drawing.Color.Navy;
            textLayoutInfo = page1.Layout(titleTextWithWidthAndHeight);

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

            PdfText textWithWidthAndHeightLimit = new PdfText(crtXPos + 50, crtYPos, 300, 50, dummyText, pdfFont);
            textWithWidthAndHeightLimit.BackColor = System.Drawing.Color.WhiteSmoke;
            textLayoutInfo = page1.Layout(textWithWidthAndHeightLimit);

            // draw a rectangle around the text
            borderPdfRectangle = new PdfRectangle(textLayoutInfo.LastPageRectangle);
            borderPdfRectangle.LineStyle.LineWidth = 0.5f;
            page1.Layout(borderPdfRectangle);

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

            #endregion

            #region Layout a text with standard font

            PdfText textWithStandardFont = new PdfText(crtXPos, crtYPos, "This green text is written with a Helvetica Standard Type 1 font", helveticaStdFont);
            textWithStandardFont.BackColor = System.Drawing.Color.WhiteSmoke;
            textWithStandardFont.ForeColor = System.Drawing.Color.Green;
            textLayoutInfo = page1.Layout(textWithStandardFont);

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

            #endregion

            #region Layout a rotated text

            PdfText titleRotatedText = new PdfText(crtXPos, crtYPos, "The text below is rotated:", pdfFontBoldEmbed);
            titleRotatedText.ForeColor = System.Drawing.Color.Navy;
            textLayoutInfo             = page1.Layout(titleRotatedText);

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

            // create a reference Graphics used for measuring
            System.Drawing.Bitmap   refBmp      = new System.Drawing.Bitmap(1, 1);
            System.Drawing.Graphics refGraphics = System.Drawing.Graphics.FromImage(refBmp);
            refGraphics.PageUnit = System.Drawing.GraphicsUnit.Point;

            string counterRotatedText = "This text is rotated 45 degrees counter clockwise";

            // measure the rotated text size
            System.Drawing.SizeF counterRotatedTextSize = refGraphics.MeasureString(counterRotatedText, sysFont);

            // advance the Y position in the PDF page
            crtYPos += counterRotatedTextSize.Width / (float)Math.Sqrt(2) + 10;

            string clockwiseRotatedText = "This text is rotated 45 degrees clockwise";

            PdfText rotatedCounterClockwiseText = new PdfText(crtXPos + 100, crtYPos, counterRotatedText, pdfFontEmbed);
            rotatedCounterClockwiseText.RotationAngle = 45;
            textLayoutInfo = page1.Layout(rotatedCounterClockwiseText);

            PdfText rotatedClockwiseText = new PdfText(crtXPos + 100, crtYPos, clockwiseRotatedText, pdfFontEmbed);
            rotatedClockwiseText.RotationAngle = -45;
            textLayoutInfo = page1.Layout(rotatedClockwiseText);

            // measure the rotated text size
            System.Drawing.SizeF clockwiseRotatedTextSize = refGraphics.MeasureString(clockwiseRotatedText, sysFont);

            // advance the Y position in the PDF page
            crtYPos += clockwiseRotatedTextSize.Width / (float)Math.Sqrt(2) + 10;

            // dispose the graphics used for measuring
            refGraphics.Dispose();
            refBmp.Dispose();

            #endregion

            #region Layout an automatically paginated text

            string dummyBigText = System.IO.File.ReadAllText(Server.MapPath("~") + @"\DemoFiles\Text\DummyBigText.txt");

            PdfText titleTextPaginated = new PdfText(crtXPos, crtYPos,
                                                     "The text below is automatically paginated when it gets to the bottom of this page:", pdfFontBoldEmbed);
            titleTextPaginated.ForeColor = System.Drawing.Color.Navy;
            textLayoutInfo = page1.Layout(titleTextPaginated);

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

            PdfText paginatedText = new PdfText(crtXPos + 50, crtYPos, 300, dummyBigText, pdfFont);
            paginatedText.BackColor = System.Drawing.Color.WhiteSmoke;
            paginatedText.Cropping  = false;
            textLayoutInfo          = page1.Layout(paginatedText);

            // get the last page where the text was rendered
            PdfPage crtPage = document.Pages[textLayoutInfo.LastPageIndex];

            // draw a line at the bottom of the text on the second page
            System.Drawing.PointF leftPoint  = new System.Drawing.PointF(textLayoutInfo.LastPageRectangle.Left, textLayoutInfo.LastPageRectangle.Bottom);
            System.Drawing.PointF rightPoint = new System.Drawing.PointF(textLayoutInfo.LastPageRectangle.Right, textLayoutInfo.LastPageRectangle.Bottom);
            PdfLine borderLine = new PdfLine(leftPoint, rightPoint);
            borderLine.LineStyle.LineWidth = 0.5f;
            crtPage.Layout(borderLine);

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

            #endregion

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

                FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf");
                fileResult.FileDownloadName = "PdfText.pdf";

                return(fileResult);
            }
            finally
            {
                document.Close();
            }
        }
Пример #36
0
 /// <summary>Performs a number of checks on the font.</summary>
 /// <remarks>
 /// Performs a number of checks on the font. See ISO 19005-1 section 6.3,
 /// ISO 19005-2 and ISO 19005-3 section 6.2.11.
 /// Be aware that not all constraints defined in the ISO are checked in this method,
 /// for most of them we consider that iText always creates valid fonts.
 /// </remarks>
 /// <param name="pdfFont">font to be checked</param>
 public abstract void CheckFont(PdfFont pdfFont);
Пример #37
0
        //#endregion

        #region Ctor

        //public PdfService(ILocalizationService localizationService, IWorkContext workContext)
        //{
        //    _localizationService = localizationService;
        //    _workContext = workContext;
        //}

        #endregion

        public void PrintResume(Stream stream, Resume resume)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            if (resume == null)
            {
                throw new ArgumentNullException("Resume");
            }

            var pageSize = iText.Kernel.Geom.PageSize.A4;

            var     line   = new LineSeparator(new SolidLine());
            var     writer = new PdfWriter(stream);
            var     pdf    = new PdfDocument(writer);
            PdfFont font   = PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN);

            var doc = new Document(pdf);

            doc.SetFont(font).SetFontSize(8);


            doc.Add(new Paragraph()
                    .Add(new Text(resume.Name).SetItalic().SetBold().SetFontSize(12)).Add(Newline)
                    .Add(new Text(resume.Address)).Add(Newline)
                    .Add(new Text(string.Format("{0} {1}", resume.PostalCode, resume.Town))));

            //doc.Add(new Paragraph(10, "\u00a0"));
            var table = new Table(UnitValue.CreatePercentArray(new float[] { 10, 80 }));

            table.SetWidth(UnitValue.CreatePercentValue(100f));

            if (!String.IsNullOrWhiteSpace(resume.Phone))
            {
                table.AddCell(InsertColumn(new Text(string.Format("{0}", _localizationWebApi.GetResource("Resume.Fields.TelePhone")))));
                table.AddCell(InsertColumn(new Text(resume.Phone)));
            }

            if (!String.IsNullOrWhiteSpace(resume.Mobile))
            {
                table.AddCell(InsertColumn(new Text(string.Format("{0}", _localizationWebApi.GetResource("Resume.Fields.Mobile")))));
                table.AddCell(InsertColumn(new Text(resume.Mobile)));
            }

            if (!String.IsNullOrWhiteSpace(resume.Email))
            {
                table.AddCell(InsertColumn(new Text("Email:")));
                table.AddCell(InsertColumn(new Text(resume.Email)));
            }

            if (!String.IsNullOrWhiteSpace(resume.Website))
            {
                table.AddCell(InsertColumn(new Text("Website:")));
                table.AddCell(InsertColumn(new Text(resume.Website)));
            }

            if (!String.IsNullOrWhiteSpace(resume.LinkedIn))
            {
                table.AddCell(InsertColumn(new Text("LinkedIn:")));
                table.AddCell(InsertColumn(new Text(resume.LinkedIn)));
            }

            doc.Add(table);

            doc.Add(new Paragraph().Add(new Text(_localizationWebApi.GetResource("Resume.Fields.Summary").GetAwaiter().GetResult()).SetItalic().SetBold().SetFontSize(12)));
            doc.Add(new Paragraph().Add(new Text(resume.GetLocalized(x => x.Summary))).SetMarginLeft(20f));


            InsertEducations(resume, doc);
            InsertSkills(resume, doc);
            InsertExperiences(resume, doc);

            doc.Close();
        }
Пример #38
0
        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
            Document    doc    = new Document(pdfDoc);

            // The 3rd argument indicates whether the font is to be embedded into the target document
            PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.IDENTITY_H, false);

            doc.SetFont(font);

            // The text line is "Vous êtes d'où?"
            doc.Add(new Paragraph("Vous \u00EAtes d\'o\u00F9?"));

            // The text line is "À tout à l'heure. À bientôt."
            doc.Add(new Paragraph("\u00C0 tout \u00E0 l\'heure. \u00C0 bient\u00F4t."));

            // The text line is "Je me présente."
            doc.Add(new Paragraph("Je me pr\u00E9sente."));

            // The text line is "C'est un étudiant."
            doc.Add(new Paragraph("C\'est un \u00E9tudiant."));

            // The text line is "Ça va?"
            doc.Add(new Paragraph("\u00C7a va?"));

            // The text line is "Il est ingénieur. Elle est médecin."
            doc.Add(new Paragraph("Il est ing\u00E9nieur. Elle est m\u00E9decin."));

            // The text line is "C'est une fenêtre."
            doc.Add(new Paragraph("C\'est une fen\u00EAtre."));

            // The text line is "Répétez, s'il vous plaît."
            doc.Add(new Paragraph("R\u00E9p\u00E9tez, s\'il vous pla\u00EEt."));
            doc.Add(new Paragraph("Odkud jste?"));

            // The text line is "Uvidíme se za chvilku. Měj se."
            doc.Add(new Paragraph("Uvid\u00EDme se za chvilku. M\u011Bj se."));

            // The text line is "Dovolte, abych se představil."
            doc.Add(new Paragraph("Dovolte, abych se p\u0159edstavil."));
            doc.Add(new Paragraph("To je studentka."));

            // The text line is "Všechno v pořádku?"
            doc.Add(new Paragraph("V\u0161echno v po\u0159\u00E1dku?"));

            // The text line is "On je inženýr. Ona je lékař."
            doc.Add(new Paragraph("On je in\u017Een\u00FDr. Ona je l\u00E9ka\u0159."));
            doc.Add(new Paragraph("Toto je okno."));

            // The text line is "Zopakujte to prosím"
            doc.Add(new Paragraph("Zopakujte to pros\u00EDm."));

            // The text line is "Откуда ты?"
            doc.Add(new Paragraph("\u041e\u0442\u043a\u0443\u0434\u0430 \u0442\u044b?"));

            // The text line is "Увидимся позже. Увидимся."
            doc.Add(new Paragraph("\u0423\u0432\u0438\u0434\u0438\u043c\u0441\u044f "
                                  + "\u043f\u043E\u0437\u0436\u0435. \u0423\u0432\u0438\u0434\u0438\u043c\u0441\u044f."));

            // The text line is "Позвольте мне представиться."
            doc.Add(new Paragraph("\u041f\u043e\u0437\u0432\u043e\u043b\u044c\u0442\u0435 \u043c\u043d\u0435 "
                                  + "\u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u0438\u0442\u044c\u0441\u044f."));

            // The text line is "Это студент."
            doc.Add(new Paragraph("\u042d\u0442\u043e \u0441\u0442\u0443\u0434\u0435\u043d\u0442."));

            // The text line is "Хорошо?"
            doc.Add(new Paragraph("\u0425\u043e\u0440\u043e\u0448\u043e?"));

            // The text line is "Он инженер. Она доктор."
            doc.Add(new Paragraph("\u041e\u043d \u0438\u043d\u0436\u0435\u043d\u0435\u0440. "
                                  + "\u041e\u043d\u0430 \u0434\u043e\u043a\u0442\u043e\u0440."));

            // The text line is "Это окно."
            doc.Add(new Paragraph("\u042d\u0442\u043e \u043e\u043a\u043d\u043e."));

            // The text line is "Повторите, пожалуйста."
            doc.Add(new Paragraph("\u041f\u043e\u0432\u0442\u043e\u0440\u0438\u0442\u0435, "
                                  + "\u043f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430."));

            doc.Close();
        }
Пример #39
0
 public TextElement(string content, float fontSize, PdfFont font)
     : this(content, fontSize, font, PdfColor.Black)
 {
 }
Пример #40
0
 public virtual void Process(Table table, String line, PdfFont font, bool isHeader)
 {
     Process(table, line, font, isHeader, new SolidBorder(ColorConstants.BLACK, 0.5f));
 }
Пример #41
0
        private static void CreateRedactionAnnotations(PdfFixedDocument document, PdfFont font, Stream flashStream)
        {
            PdfBrush blackBrush = new PdfBrush();

            PdfPage page = document.Pages.Add();

            page.Graphics.DrawString("Redaction annotations", font, blackBrush, 50, 50);

            PdfStandardFont helvetica = new PdfStandardFont(PdfStandardFontFace.Helvetica, 10);
            page.Graphics.DrawString(
                "Open the file with Adobe Acrobat, right click on the annotation and select \"Apply redactions\". The text under the annotation will be redacted.",
                helvetica, blackBrush, 50, 110);

            PdfFormXObject redactionAppearance = new PdfFormXObject(250, 150);
            redactionAppearance.Graphics.DrawRectangle(new PdfBrush(PdfRgbColor.LightGreen),
                0, 0, redactionAppearance.Width, redactionAppearance.Height);
            PdfStringAppearanceOptions sao = new PdfStringAppearanceOptions();
            sao.Brush = new PdfBrush(PdfRgbColor.DarkRed);
            sao.Font = new PdfStandardFont(PdfStandardFontFace.HelveticaBold, 32);
            PdfStringLayoutOptions slo = new PdfStringLayoutOptions();
            slo.Width = redactionAppearance.Width;
            slo.Height = redactionAppearance.Height;
            slo.X = 0;
            slo.Y = 0;
            slo.HorizontalAlign = PdfStringHorizontalAlign.Center;
            slo.VerticalAlign = PdfStringVerticalAlign.Middle;
            redactionAppearance.Graphics.DrawString("This content has been redacted", sao, slo);

            PdfRedactionAnnotation redactionAnnotation = new PdfRedactionAnnotation();
            page.Annotations.Add(redactionAnnotation);
            redactionAnnotation.Author = "XFINIUM.PDF";
            redactionAnnotation.BorderColor = new PdfRgbColor(192, 0, 0);
            redactionAnnotation.BorderWidth = 1;
            redactionAnnotation.OverlayAppearance = redactionAppearance;
            redactionAnnotation.VisualRectangle = new PdfVisualRectangle(50, 100, 250, 150);
        }
Пример #42
0
        private static void Create3DAnnotations(PdfFixedDocument document, PdfFont font, Stream u3dStream)
        {
            PdfBrush blackBrush = new PdfBrush();

            PdfPage page = document.Pages.Add();
            page.Rotation = 90;

            page.Graphics.DrawString("3D annotations", font, blackBrush, 50, 50);

            byte[] u3dContent = new byte[u3dStream.Length];
            u3dStream.Read(u3dContent, 0, u3dContent.Length);

            Pdf3DView view0 = new Pdf3DView();
            view0.CameraToWorldMatrix = new double[] { 1, 0, 0, 0, 0, -1, 0, 1, 0, -0.417542, -0.881257, -0.125705 };
            view0.CenterOfOrbit = 0.123106;
            view0.ExternalName = "Default";
            view0.InternalName = "Default";
            view0.Projection = new Pdf3DProjection();
            view0.Projection.FieldOfView = 30;

            Pdf3DView view1 = new Pdf3DView();
            view1.CameraToWorldMatrix = new double[] { -0.999888, 0.014949, 0, 0.014949, 0.999887, 0.00157084, 0.0000234825, 0.00157066, -0.999999, -0.416654, -0.761122, -0.00184508 };
            view1.CenterOfOrbit = 0.123106;
            view1.ExternalName = "Top";
            view1.InternalName = "Top";
            view1.Projection = new Pdf3DProjection();
            view1.Projection.FieldOfView = 14.8096;

            Pdf3DView view2 = new Pdf3DView();
            view2.CameraToWorldMatrix = new double[] { -1.0, -0.0000411671, 0.0000000000509201, -0.00000101387, 0.0246288, 0.999697, -0.0000411546, 0.999697, -0.0246288, -0.417072, -0.881787, -0.121915 };
            view2.CenterOfOrbit = 0.123106;
            view2.ExternalName = "Side";
            view2.InternalName = "Side";
            view2.Projection = new Pdf3DProjection();
            view2.Projection.FieldOfView = 12.3794;

            Pdf3DView view3 = new Pdf3DView();
            view3.CameraToWorldMatrix = new double[] { -0.797002, -0.603977, -0.0000000438577, -0.294384, 0.388467, 0.873173, -0.527376, 0.695921, -0.48741, -0.3518, -0.844506, -0.0675629 };
            view3.CenterOfOrbit = 0.123106;
            view3.ExternalName = "Isometric";
            view3.InternalName = "Isometric";
            view3.Projection = new Pdf3DProjection();
            view3.Projection.FieldOfView = 15.1226;

            Pdf3DView view4 = new Pdf3DView();
            view4.CameraToWorldMatrix = new double[] { 0.00737633, -0.999973, -0.0000000000147744, -0.0656414, -0.000484206, 0.997843, -0.997816, -0.00736042, -0.0656432, -0.293887, -0.757928, -0.119485 };
            view4.CenterOfOrbit = 0.123106;
            view4.ExternalName = "Front";
            view4.InternalName = "Front";
            view4.Projection = new Pdf3DProjection();
            view4.Projection.FieldOfView = 15.1226;

            Pdf3DView view5 = new Pdf3DView();
            view5.CameraToWorldMatrix = new double[] { 0.0151008, 0.999886, 0.0000000000261366, 0.0492408, -0.000743662, 0.998787, 0.998673, -0.0150825, -0.0492464, -0.540019, -0.756862, -0.118884 };
            view5.CenterOfOrbit = 0.123106;
            view5.ExternalName = "Back";
            view5.InternalName = "Back";
            view5.Projection = new Pdf3DProjection();
            view5.Projection.FieldOfView = 12.3794;

            Pdf3DStream _3dStream = new Pdf3DStream();
            _3dStream.Views.Add(view0);
            _3dStream.Views.Add(view1);
            _3dStream.Views.Add(view2);
            _3dStream.Views.Add(view3);
            _3dStream.Views.Add(view4);
            _3dStream.Views.Add(view5);
            _3dStream.Content = u3dContent;
            _3dStream.DefaultViewIndex = 0;
            Pdf3DAnnotation _3da = new Pdf3DAnnotation();
            _3da.Stream = _3dStream;

            PdfAnnotationAppearance appearance = new PdfAnnotationAppearance(200, 200);
            appearance.Graphics.DrawString("Click to activate", font, blackBrush, 50, 50);
            _3da.NormalAppearance = appearance;

            page.Annotations.Add(_3da);
            _3da.VisualRectangle = new PdfVisualRectangle(36, 36, 720, 540);

            PdfStringAppearanceOptions sao = new PdfStringAppearanceOptions();
            sao.Font = font;
            sao.Brush = blackBrush;
            PdfStringLayoutOptions slo = new PdfStringLayoutOptions();
            slo.Y = 585 + 18 / 2;
            slo.HorizontalAlign = PdfStringHorizontalAlign.Center;
            slo.VerticalAlign = PdfStringVerticalAlign.Middle;

            PdfPen blackPen = new PdfPen(new PdfRgbColor(0, 0, 0), 1);

            page.Graphics.DrawRectangle(blackPen, 50, 585, 120, 18);
            slo.X = 50 + 120 / 2;
            page.Graphics.DrawString("Top", sao, slo);

            PdfGoTo3DViewAction gotoTopView = new PdfGoTo3DViewAction();
            gotoTopView.ViewIndex = 1;
            gotoTopView.TargetAnnotation = _3da;
            PdfLinkAnnotation linkGotoTopView = new PdfLinkAnnotation();
            page.Annotations.Add(linkGotoTopView);
            linkGotoTopView.VisualRectangle = new PdfVisualRectangle(50, 585, 120, 18);
            linkGotoTopView.Action = gotoTopView;

            page.Graphics.DrawRectangle(blackPen, 190, 585, 120, 18);
            slo.X = 190 + 120 / 2;
            page.Graphics.DrawString("Side", sao, slo);

            PdfGoTo3DViewAction gotoSideView = new PdfGoTo3DViewAction();
            gotoSideView.ViewIndex = 2;
            gotoSideView.TargetAnnotation = _3da;
            PdfLinkAnnotation linkGotoSideView = new PdfLinkAnnotation();
            page.Annotations.Add(linkGotoSideView);
            linkGotoSideView.VisualRectangle = new PdfVisualRectangle(190, 585, 120, 18);
            linkGotoSideView.Action = gotoSideView;

            page.Graphics.DrawRectangle(blackPen, 330, 585, 120, 18);
            slo.X = 330 + 120 / 2;
            page.Graphics.DrawString("Isometric", sao, slo);

            PdfGoTo3DViewAction gotoIsometricView = new PdfGoTo3DViewAction();
            gotoIsometricView.ViewIndex = 3;
            gotoIsometricView.TargetAnnotation = _3da;
            PdfLinkAnnotation linkGotoIsometricView = new PdfLinkAnnotation();
            page.Annotations.Add(linkGotoIsometricView);
            linkGotoIsometricView.VisualRectangle = new PdfVisualRectangle(330, 585, 120, 18);
            linkGotoIsometricView.Action = gotoIsometricView;

            page.Graphics.DrawRectangle(blackPen, 470, 585, 120, 18);
            slo.X = 470 + 120 / 2;
            page.Graphics.DrawString("Front", sao, slo);

            PdfGoTo3DViewAction gotoFrontView = new PdfGoTo3DViewAction();
            gotoFrontView.ViewIndex = 4;
            gotoFrontView.TargetAnnotation = _3da;
            PdfLinkAnnotation linkGotoFrontView = new PdfLinkAnnotation();
            page.Annotations.Add(linkGotoFrontView);
            linkGotoFrontView.VisualRectangle = new PdfVisualRectangle(470, 585, 120, 18);
            linkGotoFrontView.Action = gotoFrontView;

            page.Graphics.DrawRectangle(blackPen, 610, 585, 120, 18);
            slo.X = 610 + 120 / 2;
            page.Graphics.DrawString("Back", sao, slo);

            PdfGoTo3DViewAction gotoBackView = new PdfGoTo3DViewAction();
            gotoBackView.ViewIndex = 5;
            gotoBackView.TargetAnnotation = _3da;
            PdfLinkAnnotation linkGotoBackView = new PdfLinkAnnotation();
            page.Annotations.Add(linkGotoBackView);
            linkGotoBackView.VisualRectangle = new PdfVisualRectangle(610, 585, 120, 18);
            linkGotoBackView.Action = gotoBackView;
        }
Пример #43
0
        private static void CreateRubberStampAnnotations(PdfFixedDocument document, PdfFont font)
        {
            PdfBrush blackBrush = new PdfBrush();

            PdfPage page = document.Pages.Add();

            string[] rubberStampAnnotationNames = new string[]
                {
                    "Approved", "AsIs", "Confidential", "Departmental", "Draft", "Experimental", "Expired", "Final",
                    "ForComment", "ForPublicRelease", "NotApproved", "NotForPublicRelease", "Sold", "TopSecret"
                };

            page.Graphics.DrawString("Rubber stamp annotations", font, blackBrush, 50, 50);
            for (int i = 0; i < rubberStampAnnotationNames.Length; i++)
            {
                PdfRubberStampAnnotation rsa = new PdfRubberStampAnnotation();
                rsa.Author = "Xfinium.Pdf";
                rsa.Contents = "I am a " + rubberStampAnnotationNames[i] + " rubber stamp annotation.";
                rsa.StampName = rubberStampAnnotationNames[i];
                page.Annotations.Add(rsa);
                rsa.VisualRectangle = new PdfVisualRectangle(50, 70 + 50 * i, 200, 40);
                page.Graphics.DrawString(rubberStampAnnotationNames[i], font, blackBrush, 270, 85 + 50 * i);
            }

            page.Graphics.DrawString("Stamp annotations with custom appearance", font, blackBrush, 350, 50);
            PdfRubberStampAnnotation customRubberStampAnnotation = new PdfRubberStampAnnotation();
            customRubberStampAnnotation.Contents = "Rubber stamp annotation with custom appearance.";
            customRubberStampAnnotation.StampName = "Custom";
            page.Annotations.Add(customRubberStampAnnotation);
            customRubberStampAnnotation.VisualRectangle = new PdfVisualRectangle(350, 70, 200, 40);

            PdfAnnotationAppearance customAppearance = new PdfAnnotationAppearance(50, 50);
            PdfPen redPen = new PdfPen(new PdfRgbColor(255, 0, 0), 10);
            PdfPen bluePen = new PdfPen(new PdfRgbColor(0, 0, 192), 10);
            customAppearance.Graphics.DrawRectangle(redPen, 5, 5, 40, 40);
            customAppearance.Graphics.DrawLine(bluePen, 0, 0, customAppearance.Width, customAppearance.Height);
            customAppearance.Graphics.DrawLine(bluePen, 0, customAppearance.Height, customAppearance.Width, 0);
            customAppearance.Graphics.CompressAndClose();
            customRubberStampAnnotation.NormalAppearance = customAppearance;
        }
Пример #44
0
        private void DefineFontResources()
        {
            // Define font resources
            // Arguments: PdfDocument class, font family name, font style, embed flag
            // Font style (must be: Regular, Bold, Italic or Bold | Italic) All other styles are invalid.
            // Embed font. If true, the font file will be embedded in the PDF file.
            // If false, the font will not be embedded
            String FontName1 = "Arial";
            String FontName2 = "Times New Roman";

            ArialNormal = new PdfFont(Document, FontName1, System.Drawing.FontStyle.Regular, true);
            ArialBold = new PdfFont(Document, FontName1, System.Drawing.FontStyle.Bold, true);
            ArialItalic = new PdfFont(Document, FontName1, System.Drawing.FontStyle.Italic, true);
            ArialBoldItalic = new PdfFont(Document, FontName1, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic, true);
            TimesNormal = new PdfFont(Document, FontName2, System.Drawing.FontStyle.Regular, true);
            Comic = new PdfFont(Document, "Comic Sans MS", System.Drawing.FontStyle.Bold, true);

            ArialNormalToPDF = new PdfFont(DocumentToPDF, FontName1, System.Drawing.FontStyle.Regular, true);
            ArialBoldToPDF = new PdfFont(DocumentToPDF, FontName1, System.Drawing.FontStyle.Bold, true);
            ArialItalicToPDF = new PdfFont(DocumentToPDF, FontName1, System.Drawing.FontStyle.Italic, true);
            ArialBoldItalicToPDF = new PdfFont(DocumentToPDF, FontName1, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic, true);
            TimesNormalToPDF = new PdfFont(DocumentToPDF, FontName2, System.Drawing.FontStyle.Regular, true);
            ComicToPDF = new PdfFont(DocumentToPDF, "Comic Sans MS", System.Drawing.FontStyle.Bold, true);

            // substitute one character for another
            // this program supports characters 32 to 126 and 160 to 255
            // if a font has a character outside these ranges that is required by the application,
            // you can replace an unused character with this character
            // Note: space (32) and non breaking space (160) cannot be replaced
            /*ArialNormal.CharSubstitution(9679, 9679, 161);		// euro
            ArialNormal.CharSubstitution(1488, 1514, 162);		// hebrew
            ArialNormal.CharSubstitution(1040, 1045, 189);		// russian
            ArialNormal.CharSubstitution(945, 950, 195);		// greek

            ArialNormalToPDF.CharSubstitution(9679, 9679, 161);		// euro
            ArialNormalToPDF.CharSubstitution(1488, 1514, 162);		// hebrew
            ArialNormalToPDF.CharSubstitution(1040, 1045, 189);		// russian
            ArialNormalToPDF.CharSubstitution(945, 950, 195);		// greek
             * */
            return;
        }
Пример #45
0
        private static void CreateTextAnnotations(PdfFixedDocument document, PdfFont font)
        {
            PdfBrush blackBrush = new PdfBrush();

            PdfPage page = document.Pages.Add();

            string[] textAnnotationNames = new string[]
                {
                    "Comment", "Check", "Circle", "Cross", "Help", "Insert", "Key", "NewParagraph",
                    "Note", "Paragraph", "RightArrow", "RightPointer", "Star", "UpArrow", "UpLeftArrow"
                };

            page.Graphics.DrawString("B/W text annotations", font, blackBrush, 50, 50);
            for (int i = 0; i < textAnnotationNames.Length; i++)
            {
                PdfTextAnnotation ta = new PdfTextAnnotation();
                ta.Author = "Xfinium.Pdf";
                ta.Contents = "I am a " + textAnnotationNames[i] + " annotation.";
                ta.IconName = textAnnotationNames[i];
                page.Annotations.Add(ta);
                ta.Location = new PdfPoint(50, 100 + 40 * i);
                page.Graphics.DrawString(textAnnotationNames[i], font, blackBrush, 90, 100 + 40 * i);
            }

            Random rnd = new Random();
            byte[] rgb = new byte[3];
            page.Graphics.DrawString("Color text annotations", font, blackBrush, 300, 50);
            for (int i = 0; i < textAnnotationNames.Length; i++)
            {
                PdfTextAnnotation ta = new PdfTextAnnotation();
                ta.Author = "Xfinium.Pdf";
                ta.Contents = "I am a " + textAnnotationNames[i] + " annotation.";
                ta.IconName = textAnnotationNames[i];
                rnd.NextBytes(rgb);
                ta.OutlineColor = new PdfRgbColor(rgb[0], rgb[1], rgb[2]);
                rnd.NextBytes(rgb);
                ta.InteriorColor = new PdfRgbColor(rgb[0], rgb[1], rgb[2]);
                page.Annotations.Add(ta);
                ta.Location = new PdfPoint(300, 100 + 40 * i);
                page.Graphics.DrawString(textAnnotationNames[i], font, blackBrush, 340, 100 + 40 * i);
            }

            page.Graphics.DrawString("Text annotations with custom icons", font, blackBrush, 50, 700);
            PdfTextAnnotation customTextAnnotation = new PdfTextAnnotation();
            customTextAnnotation.Author = "Xfinium.Pdf";
            customTextAnnotation.Contents = "Text annotation with custom icon.";
            page.Annotations.Add(customTextAnnotation);
            customTextAnnotation.IconName = "Custom icon appearance";
            customTextAnnotation.Location = new PdfPoint(50, 720);

            PdfAnnotationAppearance customAppearance = new PdfAnnotationAppearance(50, 50);
            PdfPen redPen = new PdfPen(new PdfRgbColor(255, 0, 0), 10);
            PdfPen bluePen = new PdfPen(new PdfRgbColor(0, 0, 192), 10);
            customAppearance.Graphics.DrawRectangle(redPen, 5, 5, 40, 40);
            customAppearance.Graphics.DrawLine(bluePen, 0, 0, customAppearance.Width, customAppearance.Height);
            customAppearance.Graphics.DrawLine(bluePen, 0, customAppearance.Height, customAppearance.Width, 0);
            customAppearance.Graphics.CompressAndClose();
            customTextAnnotation.NormalAppearance = customAppearance;
        }
Пример #46
0
 public Font(string pathToFont, string encoding, float fontSize)
 {
     _font     = PdfFontFactory.CreateFont(String.IsNullOrEmpty(pathToFont) ? StandardFonts.TIMES_ROMAN : pathToFont, encoding, true);
     _fontSize = fontSize;
 }
Пример #47
0
        private static void CreateTextMarkupAnnotations(PdfFixedDocument document, PdfFont font)
        {
            PdfBrush blackBrush = new PdfBrush();

            PdfPage page = document.Pages.Add();

            page.Graphics.DrawString("Text markup annotations", font, blackBrush, 50, 50);

            PdfTextMarkupAnnotationType[] tmat = new PdfTextMarkupAnnotationType[]
                {
                    PdfTextMarkupAnnotationType.Highlight, PdfTextMarkupAnnotationType.Squiggly, PdfTextMarkupAnnotationType.StrikeOut, PdfTextMarkupAnnotationType.Underline
                };

            PdfStringAppearanceOptions sao = new PdfStringAppearanceOptions();
            sao.Brush = blackBrush;
            sao.Font = font;

            PdfStringLayoutOptions slo = new PdfStringLayoutOptions();
            slo.HorizontalAlign = PdfStringHorizontalAlign.Center;
            slo.VerticalAlign = PdfStringVerticalAlign.Bottom;
            for (int i = 0; i < tmat.Length; i++)
            {
                PdfTextMarkupAnnotation tma = new PdfTextMarkupAnnotation();
                page.Annotations.Add(tma);
                tma.VisualRectangle = new PdfVisualRectangle(50, 100 + 50 * i, 200, font.Size + 2);
                tma.TextMarkupType = tmat[i];

                slo.X = 150;
                slo.Y = 100 + 50 * i + font.Size;

                page.Graphics.DrawString(tmat[i].ToString() + " annotation.", sao, slo);
            }
        }
Пример #48
0
 /// <summary>Sets the font of this Element.</summary>
 /// <remarks>
 /// Sets the font of this Element.
 /// <para />
 /// This property overrides the value set by
 /// <see cref="ElementPropertyContainer{T}.SetFontFamily(System.String[])"/>
 /// . Font is set either via exact
 /// <see cref="iText.Kernel.Font.PdfFont"/>
 /// instance or via font-family name that should correspond to the font in
 /// <see cref="iText.Layout.Font.FontProvider"/>
 /// , but not both.
 /// </remarks>
 /// <param name="font">
 /// a
 /// <see cref="iText.Kernel.Font.PdfFont">font</see>
 /// </param>
 /// <returns>this Element.</returns>
 public virtual T SetFont(PdfFont font)
 {
     SetProperty(Property.FONT, font);
     return((T)(Object)this);
 }
Пример #49
0
        /// <summary>
        /// Add text to text box.
        /// </summary>
        /// <param name="Font">Font</param>
        /// <param name="FontSize">Font size</param>
        /// <param name="Text">Text</param>
        /// <param name="WebLink">Web link</param>
        public void AddText(
			PdfFont		Font,
			Double		FontSize,
			String		Text,
			String		WebLink
			)
        {
            AddText(Font, FontSize, DrawStyle.Underline, Color.Blue, Text, WebLink);
            return;
        }
Пример #50
0
        static void LinesTable_BeginRowLayout(object sender, BeginRowLayoutEventArgs args)
        {
            PdfFont helv11 = new PdfFont(PdfFontFamily.Helvetica, 11f);
            PdfFont helv12Bold = new PdfFont(PdfFontFamily.Helvetica, 12f, PdfFontStyle.Bold);
            PdfStringFormat centered = new PdfStringFormat(PdfTextAlignment.Center);
            PdfBrush gray = new PdfSolidBrush(Color.LightGray);
            PdfBrush clear = new PdfSolidBrush(Color.Transparent);

            args.CellStyle.BorderPen = new PdfPen(Color.Transparent);
            args.CellStyle.BackgroundBrush = clear;

            if(args.RowIndex == 0)
            {
                //header
                args.CellStyle.Font = helv12Bold;

            }
            else
                args.CellStyle.Font = helv11;

            if(args.RowIndex % 2 != 0)
            {
                args.CellStyle.BackgroundBrush = gray;
            }
        }
Пример #51
0
        /// <summary>
        /// Add text to text box.
        /// </summary>
        /// <param name="Font">Font</param>
        /// <param name="FontSize">Font size</param>
        /// <param name="FontColor">Text color</param>
        /// <param name="Text">Text</param>
        public void AddText(
			PdfFont		Font,
			Double		FontSize,
			Color		FontColor,
			String		Text
			)
        {
            AddText(Font, FontSize, DrawStyle.Normal, FontColor, Text, null);
            return;
        }
Пример #52
0
 string IContentStream.GetFontName(string idName, byte[] fontData, out PdfFont pdfFont)
 {
     return(GetFontName(idName, fontData, out pdfFont));
 }
Пример #53
0
        /// <summary>
        /// TextBox segment constructor.
        /// </summary>
        /// <param name="Font">Segment font.</param>
        /// <param name="FontSize">Segment font size.</param>
        /// <param name="DrawStyle">Segment drawing style.</param>
        /// <param name="FontColor">Segment color.</param>
        /// <param name="WebLink">Segment web link.</param>
        public TextBoxSeg(
			PdfFont		Font,
			Double		FontSize,
			DrawStyle	DrawStyle,
			Color		FontColor,
			String		WebLink
			)
        {
            this.Font = Font;
            this.FontSize = FontSize;
            this.DrawStyle = DrawStyle;
            this.FontColor = FontColor;
            Text = String.Empty;
            this.WebLink = String.IsNullOrWhiteSpace(WebLink) ? null : WebLink;
            return;
        }
Пример #54
0
 public virtual bool Add(String text, PdfFont font)
 {
     // adding an empty string doesn't modify the TextArray at all
     return(Add(font.ConvertToBytes(text)));
 }
Пример #55
0
        protected void PDFQuote(Object source, EventArgs e)
        {
            //demos: http://www.e-iceblue.com/Tutorials/Spire.PDF/Demos.html //had to add permissions to IIS Express Folder for Network Users. Wont export more than 10 pages on free version.

            SaveQuote();

            var filename = PdfFileName.Value;
            if (filename == "CANCELDONOTMAKE") return;

            PdfDocument pdf = new PdfDocument();
            PdfPageBase page = pdf.Pages.Add();
                float pageWidth = page.Canvas.ClientSize.Width;
                float y = 0;

            //formatting helpers
            PdfStringFormat centered = new PdfStringFormat(PdfTextAlignment.Center);
            PdfStringFormat rightAlign = new PdfStringFormat(PdfTextAlignment.Right);
            PdfFont helv24 = new PdfFont(PdfFontFamily.Helvetica, 24f, PdfFontStyle.Bold);
            PdfFont helv20 = new PdfFont(PdfFontFamily.Helvetica, 20f, PdfFontStyle.Bold);
            PdfFont helv16 = new PdfFont(PdfFontFamily.Helvetica, 16f, PdfFontStyle.Bold);
            PdfFont helv14 = new PdfFont(PdfFontFamily.Helvetica, 14f);
            PdfFont helv12 = new PdfFont(PdfFontFamily.Helvetica, 12f);
            PdfFont helv12Bold = new PdfFont(PdfFontFamily.Helvetica, 12f, PdfFontStyle.Bold);
            PdfFont helv11 = new PdfFont(PdfFontFamily.Helvetica, 11f);
            PdfFont helv9Ital = new PdfFont(PdfFontFamily.Helvetica, 9f, PdfFontStyle.Italic);
            PdfFont helv8  = new PdfFont(PdfFontFamily.Helvetica, 8f);
            PdfBrush black = new PdfSolidBrush(Color.Black);
            SizeF size;

            string brand = "Texas Digital Systems, Inc.";
            string address = "400 Technology Parkway  College Station, TX 77845";
            string contact = "(979) 693-9378 Voice  (979) 764-8650 Fax";
            string title = "Proposal Summary";

            //HEADER
            page.Canvas.DrawString(brand, helv24, new PdfSolidBrush(Color.Black), pageWidth/2, y, centered);
                size = helv24.MeasureString(brand);
                y += size.Height + 1;
            page.Canvas.DrawString(address, helv12, black, pageWidth/2, y, centered);
                size = helv12.MeasureString(address);
                y += size.Height + 1;
            page.Canvas.DrawString(contact, helv12, black, pageWidth / 2, y, centered);
                size = helv12.MeasureString(contact);
                y += size.Height + 1;
            page.Canvas.DrawString("By: " + quote.Owner, helv12, black, 0, y);
            page.Canvas.DrawString(quote.Email, helv12, black, pageWidth, y, rightAlign);
            size = helv12.MeasureString(contact);
            y += size.Height + 1;
            page.Canvas.DrawString("Date: " + quote.Date, helv12, black, 0, y);
            page.Canvas.DrawString("PN: " + quote.PhoneNumber, helv12, black, pageWidth, y, rightAlign);
                size = helv12.MeasureString(quote.Owner);
                y += size.Height + 5;
            page.Canvas.DrawString(title, helv20, black, pageWidth / 2, y, centered);
                size = helv20.MeasureString(title);
                y += size.Height + 5;

            //ADDRESS TABLE
            PdfTable addressTable = new PdfTable();
            addressTable.Style.CellPadding = 1;
            addressTable.Style.BorderPen = new PdfPen(PdfBrushes.Black, .5f);

            string[] addressData
                = {
                      ";Customer Address;Billing Address;Shipping Address",
                      "Contact;"+quote.Customer.Contact+";"+quote.Billing.Contact+";"+quote.Shipping.Contact,
                      "Company;"+quote.Customer.Company+";"+quote.Billing.Company+";"+quote.Shipping.Company,
                      "Address1;"+quote.Customer.Address1+";"+quote.Billing.Address1+";"+quote.Shipping.Address1,
                      "Address2;"+quote.Customer.Address2+";"+quote.Billing.Address2+";"+quote.Shipping.Address2,
                      "City/State/Zip;"+quote.Customer.CityState+";"+quote.Billing.CityState+";"+quote.Shipping.CityState,
                      "Phone;"+quote.Customer.Phone+";"+quote.Billing.Phone+";"+quote.Shipping.Phone,
                      "Fax;"+quote.Customer.Fax+";"+quote.Billing.Fax+";"+quote.Shipping.Fax,
                      "Email;"+quote.Customer.Email+";"+quote.Billing.Email+";"+quote.Shipping.Email
                  };

            string[][] addressDataSource = new string[addressData.Length][];
            for (int i = 0; i < addressData.Length; i++)
                addressDataSource[i] = addressData[i].Split(';');

            addressTable.DataSource = addressDataSource;
            float width = page.Canvas.ClientSize.Width - (addressTable.Columns.Count + 1) * addressTable.Style.BorderPen.Width;
            for (int i = 0; i < addressTable.Columns.Count; i++)
            {
                if(i==0)
                    addressTable.Columns[i].Width = width * .12f * width;
                else
                    addressTable.Columns[i].Width = width * .2f * width;
            }
            addressTable.BeginRowLayout += new BeginRowLayoutEventHandler(addressTable_BeginRowLayout);

            PdfLayoutResult addressResult = addressTable.Draw(page, new PointF(0, y));
            y += addressResult.Bounds.Height + 5;

            //QUOTE DETAILS
            PdfTable detailsTable = new PdfTable();
            detailsTable.Style.CellPadding = 1;
            detailsTable.Style.BorderPen = new PdfPen(PdfBrushes.Black, .5f);
            detailsTable.Style.DefaultStyle.Font = helv11;
            detailsTable.Style.DefaultStyle.StringFormat = centered;
            width = page.Canvas.ClientSize.Width - (detailsTable.Columns.Count + 1) * detailsTable.Style.BorderPen.Width;

            //converting t/f to y/n
            string NewLocation, Dealer, TaxExempt;
            if (quote.NewLocation) NewLocation = "Yes";
                else NewLocation = "No";
            if (quote.Dealer) Dealer = "Yes";
                else Dealer = "No";
            if (quote.TaxExempt == "exempt") TaxExempt = "Yes";
                else TaxExempt = "No";

            string[] detailsData
                = {
                      "Source: ;"+quote.Source+";Source Specific: ;"+quote.SpecificSource+";No. Of Locations: ;"+quote.LocationCount,
                      "POS Provider: ;"+quote.POSProvidor+";Install Date: ;"+quote.InstallDate+";Business Unit: ;"+quote.BusinessUnit,
                      "New Location: ;"+NewLocation+";Dealer: ;"+Dealer+";Tax Exempt: ;"+TaxExempt
                  };

            string[][] detailsDataSource = new string[detailsData.Length][];
            for (int i = 0; i < detailsData.Length; i++)
                detailsDataSource[i] = detailsData[i].Split(';');

            detailsTable.DataSource = detailsDataSource;
            for (int i = 0; i < detailsTable.Columns.Count; i++)
            {
                if (i %2 != 0)
                    detailsTable.Columns[i].Width = width * .05f * width;
                else
                    detailsTable.Columns[i].Width = width * .08f * width;
            }

            PdfLayoutResult detailsResult = detailsTable.Draw(page, new PointF(0, y));
            y += detailsResult.Bounds.Height + 5;

            //QUOTE LINES
            if(quote.linesHW.Count > 0)
            {
                page.Canvas.DrawString("Hardware", helv16, black, pageWidth / 2, y, centered);
                    size = helv14.MeasureString("Hardware");
                    y += size.Height + 2;
                y += (buildPdfLines(page, quote.linesHW,"Hardware", y)).Bounds.Height + 2;
            }

            if(quote.linesSW.Count > 0)
            {
                page.Canvas.DrawString("Software", helv16, black, pageWidth / 2, y, centered);
                    size = helv16.MeasureString("Software & Maintenance");
                    y += size.Height + 2;
                y += (buildPdfLines(page, quote.linesSW,"Software", y)).Bounds.Height + 2;
            }

            if(quote.linesCC.Count > 0)
            {
                page.Canvas.DrawString("Content", helv16, black, pageWidth / 2, y, centered);
                    size = helv16.MeasureString("Content");
                    y += size.Height + 2;
                y += (buildPdfLines(page, quote.linesCC,"Content", y)).Bounds.Height + 2;
            }

            if(quote.linesInst.Count > 0)
            {
                page.Canvas.DrawString("Installation", helv16, black, pageWidth / 2, y, centered);
                    size = helv16.MeasureString("Installation");
                    y += size.Height + 2;
                y += (buildPdfLines(page, quote.linesInst, "Installation", y)).Bounds.Height + 2;
            }

            if (quote.linesRec.Count > 0)
            {
                page.Canvas.DrawString("Recurring", helv16, black, pageWidth / 2, y, centered);
                size = helv16.MeasureString("Recurring");
                y += size.Height + 2;
                y += (buildPdfLines(page, quote.linesRec, "Recurring", y)).Bounds.Height + 2;
            }

            bool FreightExists = false; if (quote.Freight > 0) FreightExists = true;
            bool SalesTaxExists = false; if (quote.SalesTax > 0) SalesTaxExists = true;
            double GrandTotal = quote.GetGrandTotal();

            //NOTES
            if (quote.ExternalNotes.Length > 0)
            {
                string notes = quote.ExternalNotes;
                PdfStringLayouter layouter = new PdfStringLayouter();
                PdfStringFormat format = new PdfStringFormat();
                format.LineSpacing = helv11.Size * 1.5f;

                PdfStringLayoutResult result = layouter.Layout(notes, helv11, format, new SizeF(pageWidth, y));

                page.Canvas.DrawString("Notes", helv14, black, pageWidth / 2, y, centered);
                size = helv14.MeasureString("LULZ");
                y += size.Height + 2;

                foreach (LineInfo line in result.Lines)
                {
                    page.Canvas.DrawString(line.Text, helv11, black, 0, y, format);
                    y = y + result.LineHeight;
                }

            }

            y += 5;
            page.Canvas.DrawLine(new PdfPen(PdfBrushes.Black, .5f), new PointF(0, y), new PointF(pageWidth, y));
            y += 5;

            //TOTALS
            if(FreightExists || SalesTaxExists)
            {
                page.Canvas.DrawString("Subtotal: $" + GrandTotal.ToString(), helv12, black, 0, y);
            }
            if(FreightExists)
            {
                page.Canvas.DrawString("Freight: $" + quote.Freight.ToString(), helv12, black, pageWidth/4, y);
                GrandTotal += quote.Freight;
            }
            if (SalesTaxExists)
            {
                page.Canvas.DrawString("Sales Tax: $" + quote.SalesTax.ToString(), helv12, black, pageWidth / 2, y);
                GrandTotal += quote.SalesTax;
            }

            page.Canvas.DrawString("Total: $" + GrandTotal.ToString(), helv12Bold, black, pageWidth, y, rightAlign);
                size = helv12Bold.MeasureString("999999");

            y += size.Height + 5;
            page.Canvas.DrawLine(new PdfPen(PdfBrushes.Black, .5f), new PointF(0, y), new PointF(pageWidth, y));
            y += 5;

            //FINE PRINT
            page.Canvas.DrawString("Quote is good for: " + quote.QuoteLength + " days", helv8, black, 0, y);
            page.Canvas.DrawString("F.O.B. College Station, TX", helv8, black, pageWidth / 2, y, centered);
            page.Canvas.DrawString("Payment Terms: " + quote.PaymentTerms, helv8, black, pageWidth, y, rightAlign);
                size = helv8.MeasureString("THESE WORDS DON'T MATTER");
                y += size.Height + 1;

            page.Canvas.DrawString("This is not an invoice and may not include freight and/or sales tax. An invoice will be sent upon receipt of the signed quote.", helv9Ital, black, pageWidth/2, y, centered);
                size = helv9Ital.MeasureString("ONLY DEVS WILL SEE THIS");
                y += size.Height + 10;

            page.Canvas.DrawString("Please sign to accept this quotation: ", helv8, black, 0, y);
                size = helv8.MeasureString("I CAN SAY WHATEVER I WANT");
                page.Canvas.DrawLine(new PdfPen(PdfBrushes.Black, .5f), new PointF(150, y+size.Height), new PointF(350, y+size.Height));
                y += size.Height + 1;

            page.Canvas.DrawString("By signing I agree that I have read, understand and agree to be bound by the Texas Digital Standard Terms and Conditions Applicable to", helv8, black, 0, y);
                size = helv8.MeasureString("PAY UP GUY");
                y += size.Height + 1;

            page.Canvas.DrawString("Quotes and Purchase Orders accessible at: ", helv8, black, 0, y);
                size = helv8.MeasureString("Quotes and Purchase Orders accessible at: ");
                page.Canvas.DrawString("http://www.ncr.com/wp-content/uploads/TXDigital_Terms_and_Conditions.pdf", helv8, PdfBrushes.DarkGreen, size.Width, y);
                y += size.Height + 1;

            page.Canvas.DrawString("After signing please fax to (979) 764-8650", helv8, black, 0, y);
            page.Canvas.DrawString("Delivery ARO: 45-60 days", helv8, black, pageWidth, y, rightAlign);
                size = helv8.MeasureString("THIS ISNT THE END LOL");
                y += size.Height + 1;

            //pdf.SaveToFile(filename);
            pdf.SaveToHttpResponse(filename, Response, HttpReadType.Save);
            pdf.Close();
            System.Diagnostics.Process.Start(filename);
        }
Пример #56
0
        /// <summary>
        /// Converts simple XHTML to a formatted content object.
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        private PdfFormattedContent ConvertHtmlToFormattedContent(Stream html)
        {
            PdfFormattedContent   fc = new PdfFormattedContent();
            PdfFormattedParagraph currentParagraph  = null;
            PdfUriAction          currentLinkAction = null;
            PdfFormattedTextBlock bullet            = null;
            float currentIndent = 0;

            // Create a default font.
            fonts.Push(new PdfStandardFont(PdfStandardFontFace.Helvetica, 10));



            // Create a default text color.
            textColors.Push(new PdfBrush(PdfRgbColor.Black));

            System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(html);
            xmlReader.MoveToContent();

            while (xmlReader.Read())
            {
                switch (xmlReader.NodeType)
                {
                case System.Xml.XmlNodeType.Element:
                    switch (xmlReader.Name)
                    {
                    case "p":
                        currentParagraph = new PdfFormattedParagraph();
                        //currentParagraph.SpacingBefore = 3;
                        //currentParagraph.SpacingAfter = 3;
                        fc.Paragraphs.Add(currentParagraph);
                        break;

                    case "br":
                        if (currentParagraph.Blocks.Count > 0)
                        {
                            PdfFormattedTextBlock textBlock =
                                currentParagraph.Blocks[currentParagraph.Blocks.Count - 1] as PdfFormattedTextBlock;
                            textBlock.Text = textBlock.Text + "\r\n";
                        }
                        else
                        {
                            PdfFormattedTextBlock textBlock = new PdfFormattedTextBlock("\r\n", ActiveFont);
                            currentParagraph.Blocks.Add(textBlock);
                        }
                        break;

                    case "a":
                        while (xmlReader.MoveToNextAttribute())
                        {
                            if (xmlReader.Name == "href")
                            {
                                currentLinkAction     = new PdfUriAction();
                                currentLinkAction.URI = xmlReader.Value;
                            }
                        }
                        break;

                    case "font":
                        while (xmlReader.MoveToNextAttribute())
                        {
                            if (xmlReader.Name == "color")
                            {
                                PdfBrush color     = ActiveTextColor;
                                string   colorCode = xmlReader.Value;
                                // #RRGGBB
                                if (colorCode.StartsWith("#") && (colorCode.Length == 7))
                                {
                                    byte r = byte.Parse(colorCode.Substring(1, 2), System.Globalization.NumberStyles.HexNumber);
                                    byte g = byte.Parse(colorCode.Substring(3, 2), System.Globalization.NumberStyles.HexNumber);
                                    byte b = byte.Parse(colorCode.Substring(5, 2), System.Globalization.NumberStyles.HexNumber);
                                    color = new PdfBrush(new PdfRgbColor(r, g, b));
                                }

                                textColors.Push(color);
                            }
                        }
                        break;

                    case "ul":
                        //bullet = new PdfFormattedTextBlock("\x95 ", ActiveFont);
                        currentIndent += 18;
                        break;

                    case "li":
                        currentParagraph = new PdfFormattedParagraph();
                        currentParagraph.SpacingBefore   = 3;
                        currentParagraph.SpacingAfter    = 3;
                        currentParagraph.Bullet          = bullet;
                        currentParagraph.LeftIndentation = currentIndent;
                        fc.Paragraphs.Add(currentParagraph);
                        break;

                    case "b":
                    case "strong":
                        PdfFont boldFont = CopyFont(ActiveFont);
                        boldFont.Bold = true;
                        fonts.Push(boldFont);
                        break;

                    case "i":
                    case "em":
                        PdfFont italicFont = CopyFont(ActiveFont);
                        italicFont.Italic = true;
                        fonts.Push(italicFont);
                        break;

                    case "u":
                        PdfFont underlineFont = CopyFont(ActiveFont);
                        underlineFont.Underline = true;
                        fonts.Push(underlineFont);
                        break;

                    case "span":
                        if (currentParagraph == null)
                        {
                            currentParagraph = new PdfFormattedParagraph();
                            fc.Paragraphs.Add(currentParagraph);
                        }
                        break;

                    case "h1":
                    case "h2":
                        currentParagraph = new PdfFormattedParagraph();
                        currentParagraph.SpacingBefore = 6;
                        currentParagraph.SpacingAfter  = 6;
                        fc.Paragraphs.Add(currentParagraph);
                        fonts.Push(CopyFont(new PdfStandardFont(PdfStandardFontFace.Helvetica, 17)));
                        break;

                    case "h3":
                    case "h4":
                        currentParagraph = new PdfFormattedParagraph();
                        currentParagraph.SpacingBefore = 6;
                        //currentParagraph.SpacingAfter = 6;
                        fc.Paragraphs.Add(currentParagraph);
                        fonts.Push(CopyFont(new PdfStandardFont(PdfStandardFontFace.Helvetica, 14)));
                        break;

                    case "h5":
                    case "h6":
                        currentParagraph = new PdfFormattedParagraph();
                        currentParagraph.SpacingBefore = 3;
                        currentParagraph.SpacingAfter  = 3;
                        fc.Paragraphs.Add(currentParagraph);
                        fonts.Push(CopyFont(new PdfStandardFont(PdfStandardFontFace.Helvetica, 11)));
                        break;
                    }
                    break;

                case System.Xml.XmlNodeType.EndElement:
                    switch (xmlReader.Name)
                    {
                    case "a":
                        currentLinkAction = null;
                        break;

                    case "ul":
                        //bullet = null;
                        currentIndent -= 18;
                        break;

                    case "b":
                    case "strong":
                    case "i":
                    case "em":
                    case "u":
                    case "h1":
                    case "h2":
                    case "h3":
                    case "h4":
                    case "h5":
                    case "h6":
                        currentParagraph = new PdfFormattedParagraph();
                        currentParagraph.SpacingBefore = 0;
                        currentParagraph.SpacingAfter  = 0;
                        fc.Paragraphs.Add(currentParagraph);
                        fonts.Pop();
                        break;

                    case "font":
                        if (textColors.Count > 1)
                        {
                            textColors.Pop();
                        }
                        break;
                    }
                    break;

                case System.Xml.XmlNodeType.Text:
                    string text = xmlReader.Value;
                    if (currentParagraph != null && text != null && text.Length > 0)
                    {
                        // Remove spaces from text that do not have meaning in HTML.
                        text = text.Replace("\r", "");
                        text = text.Replace("\n", "");
                        text = text.Replace("\t", " ");
                        PdfFormattedTextBlock block = new PdfFormattedTextBlock(text, ActiveFont);
                        block.TextColor = ActiveTextColor;
                        if (currentLinkAction != null)
                        {
                            block.Action = currentLinkAction;
                            // Make the links blue.
                            block.TextColor = new PdfBrush(PdfRgbColor.Blue);
                        }

                        currentParagraph.Blocks.Add(block);
                    }
                    break;
                }
            }

            return(fc);
        }
Пример #57
0
        static void addressTable_BeginRowLayout(object sender, BeginRowLayoutEventArgs args)
        {
            PdfFont helv12 = new PdfFont(PdfFontFamily.Helvetica, 12f, PdfFontStyle.Bold);
            PdfFont helv11 = new PdfFont(PdfFontFamily.Helvetica, 11f);
            PdfStringFormat centered = new PdfStringFormat(PdfTextAlignment.Center);

            if (args.RowIndex == 0)
            {
                //header
                args.CellStyle.Font = helv12;
                args.CellStyle.StringFormat = centered;
                args.CellStyle.BackgroundBrush = PdfBrushes.LightGray;
            }
            else
            {
                args.CellStyle.Font = helv11;
                args.CellStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Left);
                args.CellStyle.BackgroundBrush = PdfBrushes.White;
            }
        }
Пример #58
0
        public void generatePDF(String dest, Chart carrito, List <Items> items)
        {
            Double  totalSaldo   = 0.0D;
            Decimal totalVencer  = 0.0M;
            Decimal total030     = 0.0M;
            Decimal total3060    = 0.0M;
            Decimal total6090    = 0.0M;
            Decimal total90      = 0.0M;
            Decimal totalVencido = 0.0M;

            PdfWriter pdfWriter = null;

            pdfWriter = new PdfWriter(dest);
            PdfDocument pdfDoc = new PdfDocument(pdfWriter);
            Document    doc    = new Document(pdfDoc, new PageSize(595, 842));

            PdfFont BOLD    = PdfFontFactory.CreateFont(StandardFonts.COURIER_BOLD);
            PdfFont COURIER = PdfFontFactory.CreateFont(StandardFonts.COURIER);

            doc.SetFont(COURIER);
            doc.SetFontSize(8f);
            doc.SetMargins(15, 20, 15, 20);
            float fntSize;

            fntSize = 28f;

            String nombreCliente = carrito.nombre_cliente;
            String codigoCliente = carrito.codigo_cliente;

            doc.Add(new Paragraph("Pedido Cliente: " + carrito.nombre_cliente).SetFont(BOLD).SetFontSize(fntSize));
            doc.Add(new Paragraph(""));
            doc.Add(new Paragraph("CORSENESA"));
            doc.Add(new Paragraph("Fecha: " + DateTime.Now.ToString("M/d/yyyy").ToString()).SetFixedLeading(2));
            doc.Add(new Paragraph("Nombre Cliente: " + nombreCliente).SetFixedLeading(2));
            doc.Add(new Paragraph("Codigo Cliente: " + codigoCliente).SetFixedLeading(2));
            doc.Add(new Paragraph("Codigo Vendedor: " + carrito.cod_vendedor).SetFixedLeading(2));
            doc.Add(new Paragraph(""));
            Table table = new Table(new float[6]).UseAllAvailableWidth();

            table.SetMarginTop(0);
            table.SetMarginBottom(0);

            Cell cell = new Cell(1, 6).Add(new Paragraph("Pedido Cliente " + nombreCliente));

            cell.SetTextAlignment(TextAlignment.CENTER);
            cell.SetPadding(5);
            cell.SetBackgroundColor(new DeviceRgb(112, 128, 144));
            table.AddCell(cell);

            table.AddCell("#").SetTextAlignment(TextAlignment.CENTER);
            table.AddCell("Empresa").SetTextAlignment(TextAlignment.CENTER);

            table.AddCell("Cantidad").SetTextAlignment(TextAlignment.CENTER);
            table.AddCell("Codigo").SetTextAlignment(TextAlignment.CENTER);
            table.AddCell("Nombre producto").SetTextAlignment(TextAlignment.CENTER);
            table.AddCell("Precio venta").SetTextAlignment(TextAlignment.CENTER);


            int i = 0;

            foreach (Items item in items)
            {
                i++;
                table.AddCell((new Paragraph(i.ToString()).SetTextAlignment(TextAlignment.CENTER)));
                table.AddCell((new Paragraph(item.producto.Empresa)).SetTextAlignment(TextAlignment.CENTER));
                table.AddCell((new Paragraph(item.cantidad.ToString())).SetTextAlignment(TextAlignment.RIGHT));
                table.AddCell((new Paragraph(item.producto.Codigo)).SetTextAlignment(TextAlignment.CENTER));
                table.AddCell((new Paragraph(item.producto.nombre)).SetTextAlignment(TextAlignment.CENTER));
                table.AddCell((new Paragraph("Q." + item.producto.prec_vta1.ToString("0.00"))).SetTextAlignment(TextAlignment.RIGHT));
            }

            doc.Add(table);
            doc.Flush();
            doc.Close();
            pdfDoc.Close();
            pdfWriter.Close();
            pdfWriter.Dispose();
        }
Пример #59
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(ofdSingleFile.SafeFileName))
            {
                MessageBox.Show("Please select a pdf file");
                return;
            }
            btnRun.Enabled = false;

            Task.Factory.StartNew(() =>
            {
                var filePath = ofdSingleFile.FileName;
                var helper = new PdfHelper();
                var pdf = new PdfDocument(filePath);
                var pdfTemp = new PdfDocument();
                var docWillSave = new PdfDocument();
                var totalPage = pdf.Pages.Count;
                pbSplitProgress.Maximum = totalPage;
                var curPage = 0;
                foreach (PdfPageBase itemPage in pdf.Pages)
                {
                    curPage++;
                    #region Lable one
                    var pageOrigin = itemPage;
                    var template = pageOrigin.CreateTemplate();
                    var pageTemp = pdfTemp.Pages.Add(PdfHelper.SizeF4x6, new PdfMargins(0));
                    pageTemp.Canvas.DrawTemplate(template, new PointF(38, 9));
                    var templateNew = pageTemp.CreateTemplate();
                    var page = docWillSave.Pages.Add(PdfHelper.SizeF4x6, new PdfMargins(0));
                    page.Canvas.DrawTemplate(templateNew, new PointF(-40, -9));

                    PdfGraphicsState state = page.Canvas.Save();
                    PdfStringFormat leftAlignment = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
                    PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 20f);
                    PdfSolidBrush brush = new PdfSolidBrush(Color.Blue);
                    page.Canvas.RotateTransform(-90);
                    page.Canvas.DrawString(txtText.Text, font, brush, new PointF(-250, 25), leftAlignment);
                    //  page.Canvas.Restore(state);

                    pdfTemp.Pages.RemoveAt(0);
                    #endregion

                    #region Lable two
                    var ListImage = itemPage.ExtractImages();
                    #region Second Page
                    PdfPageBase page2 = docWillSave.Pages.Add(new SizeF(288, 432), new PdfMargins(0));
                    ListImage[1].RotateFlip(RotateFlipType.Rotate90FlipNone);

                    #region cut image
                    System.Drawing.Rectangle cropArea = new System.Drawing.Rectangle(0, 0, 800, 1204);
                    var img = ListImage[1];
                    System.Drawing.Bitmap bmpImage = new System.Drawing.Bitmap(img);
                    System.Drawing.Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
                    #endregion
                    PdfImage image = PdfImage.FromImage(bmpCrop);
                    page2.Canvas.DrawImage(image, 0, 0, page2.Canvas.ClientSize.Width, page2.Canvas.ClientSize.Height);
                    #endregion
                    #endregion
                    pbSplitProgress.Value = curPage ;
                }

                var newFile = filePath.Remove(filePath.LastIndexOf('.'), 4) + "_cut" + DateTime.Now.ToFileTime() + ".pdf";
                docWillSave.SaveToFile(newFile);
                docWillSave.Close();
                lblMsg.Text = "File has been save as " + newFile;
                System.Diagnostics.Process.Start(newFile);
            });
        }
Пример #60
0
 string IContentStream.GetFontName(XFont font, out PdfFont pdfFont)
 {
     return(GetFontName(font, out pdfFont));
 }