예제 #1
0
        private void MergePDF_Click(object sender, RoutedEventArgs e)
        {
            //Get template PDF file stream from assembly.
            if (firstDocumentStream == null)
            {
                firstDocumentStream = typeof(MergePDF).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.pdf_succinctly.pdf");
            }
            //Get template PDF file stream from assembly.
            if (secondDocumentStream == null)
            {
                secondDocumentStream = typeof(MergePDF).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.form_template.pdf");
            }

            //Load the PDF document from stream.
            PdfLoadedDocument loadedDocument = new PdfLoadedDocument(firstDocumentStream);

            //Load and merge the pdf documents.
            PdfDocument.Merge(loadedDocument, new PdfLoadedDocument(secondDocumentStream));

            //Creating the stream object.
            using (MemoryStream stream = new MemoryStream())
            {
                //Save and close the document.
                loadedDocument.Save(stream);
                loadedDocument.Close();

                stream.Position = 0;
                //Save the output stream as a file using file picker.
                PdfUtil.Save("MergePDF.pdf", stream);
            }
            Dispose();
        }
예제 #2
0
        private void FillAndFlatten_Click(object sender, RoutedEventArgs e)
        {
            //Get the template PDF form file stream from assembly.
            Stream documentStream = typeof(FormFilling).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.form_template.pdf");
            //Load the PDF document from stream.
            PdfLoadedDocument document = new PdfLoadedDocument(documentStream);

            //File the PDF form.
            FillDocument(document);

            //Flatten the form fields in a document.
            if (document.Form != null)
            {
                document.Form.Flatten = true;
            }

            //Creating the stream object.
            using (MemoryStream stream = new MemoryStream())
            {
                //Save and close the document.
                document.Save(stream);
                document.Close();

                stream.Position = 0;
                //Save the output stream as a file using file picker.
                PdfUtil.Save("FormFillAndFlatten.pdf", stream);
            }
        }
예제 #3
0
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Stream documentStream;
            string fileName = string.Empty;

            if ((bool)import.IsChecked)
            {
                //Get the import template PDF file stream from assembly.
                documentStream = typeof(ImportAndExport).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.form_template.pdf");
                fileName       = "ImportForm_Template.pdf";
            }
            else
            {
                //Get the export template PDF file stream from assembly.
                documentStream = typeof(ImportAndExport).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.export_template.pdf");
                fileName       = "ExportForm_Template.pdf";
            }
            //Load the PDF document from stream.
            PdfLoadedDocument loadedDocument = new PdfLoadedDocument(documentStream);

            //Creating the stream object.
            using (MemoryStream stream = new MemoryStream())
            {
                //Save and close the document.
                loadedDocument.Save(stream);
                loadedDocument.Close();

                stream.Position = 0;

                //Save the output stream as a file using file picker.
                PdfUtil.Save(fileName, stream);
            }
        }
예제 #4
0
        private void Button2_Click(object sender, RoutedEventArgs e)
        {
            string text = textbox.Text;

            // Get the template PDF file stream from assembly.
            Stream documentStream = typeof(FindText).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.pdf_succinctly.pdf");

            //Load the PDF document from stream.
            PdfLoadedDocument loadedDocument = new PdfLoadedDocument(documentStream);

            TextSearchResultCollection results;

            //Create list and add a string text to find from PDF document.
            List <string> searchItem = new List <string>();

            searchItem.Add(text);

            //Find text from PDF document and get the result collection.
            loadedDocument.FindText(searchItem, out results);

            //Iterate over the result collection.
            foreach (var result in results)
            {
                //Get the PDF page using the result.
                PdfLoadedPage page = loadedDocument.Pages[result.Key] as PdfLoadedPage;
                //Save the current graphics state.
                page.Graphics.Save();
                //Set transparency to the page graphics.
                page.Graphics.SetTransparency(0.5F);

                foreach (var matchedItem in result.Value)
                {
                    //Draw rectangle to highlight the text in PDF page.
                    page.Graphics.DrawRectangle(PdfBrushes.Yellow, matchedItem.Bounds);
                }
                //Restore the graphics state.
                page.Graphics.Restore();
            }

            //Creating the stream object.
            using (MemoryStream stream = new MemoryStream())
            {
                //Save and close the document.
                loadedDocument.Save(stream);
                loadedDocument.Close();

                stream.Position = 0;
                //Save the output stream as a file using file picker.
                PdfUtil.Save("FindText.pdf", stream);
            }
        }
예제 #5
0
        private void ImportData()
        {
            //Get the template PDF file stream from assembly.
            Stream documentStream = typeof(ImportAndExport).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.form_template.pdf");

            //Load the PDF document from stream.
            PdfLoadedDocument document = new PdfLoadedDocument(documentStream);

            //Initialize import form setting to import form data.
            ImportFormSettings settings = new ImportFormSettings();

            string fileName = string.Empty;

            if ((bool)fdf.IsChecked)
            {
                //Set data format to import form data from FDF format.
                settings.DataFormat = DataFormat.Fdf;
                fileName            = "import_data.fdf";
            }
            else if ((bool)xfdf.IsChecked)
            {
                //Set data format to import form data from XFDF format.
                settings.DataFormat = DataFormat.XFdf;
                fileName            = "import_data.xfdf";
            }
            else
            {
                //Set data format to import form data from XML format.
                settings.DataFormat = DataFormat.Xml;
                fileName            = "import_data.xml";
            }
            //Get the data file stream to import.
            Stream dataStream = typeof(ImportAndExport).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets." + fileName);

            //Import form data from stream
            document.Form.ImportData(dataStream, settings);

            //Creating the stream object.
            using (MemoryStream stream = new MemoryStream())
            {
                //Save and close the document.
                document.Save(stream);
                document.Close();

                stream.Position = 0;
                //Save the output stream as a file using file picker.
                PdfUtil.Save("ImportedDocument.pdf", stream);
            }
        }
예제 #6
0
        private void GeneratePDF_Click(object sender, RoutedEventArgs e)
        {
            //Create a new PDF document.
            PdfDocument document = new PdfDocument();
            //Add page to the PDF document.
            PdfPage page = document.Pages.Add();
            //Create font with size and style.
            PdfStandardFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 12, PdfFontStyle.Bold);
            //Create PDF graphics for the page.
            PdfGraphics graphics = page.Graphics;

            //Draw text to PDF page with font and location.
            graphics.DrawString("JPEG Image", font, PdfBrushes.Blue, new PointF(0, 40));
            //Get the image file stream from assembly.
            Stream jpgImageStream = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.Xamarin_JPEG.jpg");
            //Create new image from stream.
            PdfImage jpgImage = new PdfBitmap(jpgImageStream);

            //Draw the JPEG image
            graphics.DrawImage(jpgImage, new RectangleF(0, 70, 515, 215));
            //Draw text to PDF page with font and location.
            graphics.DrawString("PNG Image", font, PdfBrushes.Blue, new PointF(0, 355));
            //Get the image file stream from assembly.
            Stream pngImageStream = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.Xamarin_PNG.png");
            //Create new image from stream.
            PdfImage pngImage = new PdfBitmap(pngImageStream);

            //Draw the PNG image
            graphics.DrawImage(pngImage, new RectangleF(0, 375, 199, 300));

            //Creating the stream object.
            using (MemoryStream stream = new MemoryStream())
            {
                //Save the document into stream.
                document.Save(stream);
                document.Close();

                stream.Position = 0;

                //Save the output stream as a file using file picker.
                PdfUtil.Save("ImageInsertion.pdf", stream);
            }
        }
예제 #7
0
        private void ViewTemplate_Click(object sender, RoutedEventArgs e)
        {
            //Get the template PDF form file stream from assembly.
            Stream documentStream = typeof(FormFilling).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.form_template.pdf");
            //Load the PDF document from stream.
            PdfLoadedDocument loadedDocument = new PdfLoadedDocument(documentStream);

            //Creating the stream object.
            using (MemoryStream stream = new MemoryStream())
            {
                //Save and close the document.
                loadedDocument.Save(stream);
                loadedDocument.Close();

                stream.Position = 0;
                //Save the output stream as a file using file picker.
                PdfUtil.Save("FormFilling_Template.pdf", stream);
            }
        }
예제 #8
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //Get the template PDF file stream from assembly.
            Stream documentStream = typeof(PdfWatermark).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.pdf_succinctly.pdf");
            //Load the PDF document from stream.
            PdfLoadedDocument loadedDocument = new PdfLoadedDocument(documentStream);
            //Create a new font instance.
            PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 36f);

            //Adding a watermark text to all the PDF pages.
            foreach (PdfPageBase loadedPage in loadedDocument.Pages)
            {
                //Get the PDF page graphics.
                PdfGraphics graphics = loadedPage.Graphics;
                //Save the current graphics state.
                PdfGraphicsState state = graphics.Save();
                //Set transparency to add a watermark text.
                graphics.SetTransparency(0.25f);
                //Rotate the graphics to add a watermark text with 40 degree.
                graphics.RotateTransform(-40);
                //Draw a watermark text to PDF page graphics.
                graphics.DrawString(stampText.Text, font, PdfPens.Red, PdfBrushes.Red, new PointF(-150, 450));
                //Restore the graphics state.
                graphics.Restore(state);
            }

            //Creating the stream object.
            using (MemoryStream stream = new MemoryStream())
            {
                //Save the document into stream.
                loadedDocument.Save(stream);
                loadedDocument.Close();

                stream.Position = 0;
                //Save the output stream as a file using file picker.
                PdfUtil.Save("PdfWatermark.pdf", stream);
            }
        }
예제 #9
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            //Get the template PDF file stream from assembly.
            Stream documentStream = typeof(Encryption).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.credit_card_statement.pdf");
            //Load the PDF document from stream.
            PdfLoadedDocument document = new PdfLoadedDocument(documentStream);

            //Get the document security.
            PdfSecurity security = document.Security;

            //Specify key size and encryption algorithm.
            if (encryptionTechnique.SelectionBoxItem.ToString() == "40-Bit RC4")
            {
                //use 40 bits key in RC4 mode.
                security.KeySize   = PdfEncryptionKeySize.Key40Bit;
                security.Algorithm = PdfEncryptionAlgorithm.RC4;
            }
            else if (encryptionTechnique.SelectionBoxItem.ToString() == "128-Bit RC4")
            {
                //use 128 bits key in RC4 mode.
                security.KeySize   = PdfEncryptionKeySize.Key128Bit;
                security.Algorithm = PdfEncryptionAlgorithm.RC4;
            }
            else if (encryptionTechnique.SelectionBoxItem.ToString() == "128-Bit AES")
            {
                //use 128 bits key in RC4 mode.
                security.KeySize   = PdfEncryptionKeySize.Key128Bit;
                security.Algorithm = PdfEncryptionAlgorithm.AES;
            }
            else if (encryptionTechnique.SelectionBoxItem.ToString() == "256-Bit AES")
            {
                //use 256 bits key in AES mode.
                security.KeySize   = PdfEncryptionKeySize.Key256Bit;
                security.Algorithm = PdfEncryptionAlgorithm.AES;
            }
            else if (encryptionTechnique.SelectionBoxItem.ToString() == "256-Bit AES Revision 6")
            {
                //use 256 bits key in AES mode with Revision 6.
                security.KeySize   = PdfEncryptionKeySize.Key256BitRevision6;
                security.Algorithm = PdfEncryptionAlgorithm.AES;
            }

            //Set the PdfEncryption option to encrypt the document.
            if (!cmbencryptOption.IsEnabled || cmbencryptOption.SelectedIndex == 0)
            {
                security.EncryptionOptions = PdfEncryptionOptions.EncryptAllContents;
            }
            else if (cmbencryptOption.SelectedIndex == 1)
            {
                security.EncryptionOptions = PdfEncryptionOptions.EncryptAllContentsExceptMetadata;
            }
            else if (cmbencryptOption.SelectedIndex == 2)
            {
                //Read a file from assembly to add an attachment.
                Stream imageStream = typeof(Encryption).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.credit_card_statement.xml");

                //Create PdfAttachment from stream.
                PdfAttachment attachment = new PdfAttachment("PDF.xml", imageStream);
                attachment.ModificationDate = DateTime.Now;
                attachment.Description      = "Product details";
                attachment.MimeType         = "application/xml";

                if (document.Attachments == null)
                {
                    document.CreateAttachment();
                }

                //Adds the attachment to the document.
                document.Attachments.Add(attachment);
                security.EncryptionOptions = PdfEncryptionOptions.EncryptOnlyAttachments;
            }

            //Set the user and owner password.
            security.OwnerPassword = txtOwnerPassword.Text;
            security.UserPassword  = txtUserPassword.Text;

            //Set the permission flags for the file.
            security.Permissions = PdfPermissionsFlags.Print | PdfPermissionsFlags.FullQualityPrint;

            //Creating the stream object.
            using (MemoryStream stream = new MemoryStream())
            {
                //Save and close the document.
                document.Save(stream);
                document.Close(true);

                stream.Position = 0;
                //Save the output stream as a file using file picker.
                PdfUtil.Save("Encryption.pdf", stream);
            }
        }
예제 #10
0
        private void GeneratePdf_Click(object sender, RoutedEventArgs e)
        {
            //Create a new PDF document.
            PdfDocument document = new PdfDocument();

            //Set PDF landscape page orientiation.
            document.PageSettings.Orientation = PdfPageOrientation.Landscape;
            //Set page margins.
            document.PageSettings.Margins.All = 0;
            //Add page to the PDF document.
            PdfPage page = document.Pages.Add();
            //Get the page size to draw the contents to PDF page.
            SizeF pageSize = page.GetClientSize();

            //Get the image file stream from assembly.
            Stream imageStream = typeof(Certificate).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.certificate.jpg");
            //Load the PDF document from stream.
            PdfBitmap bitmapImage = new PdfBitmap(imageStream);

            //Draw the PDF bitmap image to PDF page with provided size.
            page.Graphics.DrawImage(bitmapImage, new RectangleF(0, 0, pageSize.Width, pageSize.Height));

            //Create font with different size.
            PdfFont  nameFont    = new PdfStandardFont(PdfFontFamily.Helvetica, 22);
            PdfFont  controlFont = new PdfStandardFont(PdfFontFamily.Helvetica, 19);
            PdfFont  dateFont    = new PdfStandardFont(PdfFontFamily.Helvetica, 16);
            PdfBrush textBrush   = new PdfSolidBrush(new PdfColor(20, 58, 86));

            //Find the X position based on text and font size.
            float x = calculateXPosition(name.Text, nameFont, pageSize.Width);

            //Draw the string to specified location.
            page.Graphics.DrawString(name.Text, nameFont, textBrush, new RectangleF(x, 253, 0, 0));

            //Find the X position based on text and font size.
            x = calculateXPosition(courseName.Text, controlFont, pageSize.Width);
            //Draw the string to specified location.
            page.Graphics.DrawString(courseName.Text, controlFont, textBrush, new RectangleF(x, 340, 0, 0));

            //Get date value from date picker field.
            var      dateTimeOffset = date.Date;
            DateTime time           = dateTimeOffset.Value.DateTime;
            //Get the formatted Date to add in PDF page.
            string formatedDate = "on " + time.ToString("MMMM d, yyyy");

            //Find the X position based on text and font size.
            x = calculateXPosition(formatedDate, dateFont, pageSize.Width);
            //Draw the string to specified location.
            page.Graphics.DrawString(formatedDate, dateFont, textBrush, new RectangleF(x, 385, 0, 0));

            //Creating the stream object.
            using (MemoryStream stream = new MemoryStream())
            {
                //Save and close the document.
                document.Save(stream);
                document.Close();

                stream.Position = 0;
                //Save the output stream as a file using file picker.
                PdfUtil.Save("Certificate.pdf", stream);
            }
        }
예제 #11
0
        private void button3_Click(object sender, RoutedEventArgs e)
        {
            //Get the template PDF file stream from assembly.
            Stream documentStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.digital_signature_template.pdf");
            //Load the PDF document from stream.
            PdfLoadedDocument loadedDocument = new PdfLoadedDocument(documentStream);
            //Get the .pfx certificate file stream.
            Stream certificateStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.certificate.pfx");
            //Get the signature field to add digital signature.
            PdfLoadedSignatureField signatureField = loadedDocument.Form.Fields[6] as PdfLoadedSignatureField;
            //Get the signature bounds.
            RectangleF bounds = signatureField.Bounds;

            //Create PDF certificate using certificate stream and password.
            PdfCertificate pdfCertificate = new PdfCertificate(certificateStream, "password123");

            //Add certificate to first page of the document.
            PdfSignature signature = new PdfSignature(loadedDocument, loadedDocument.Pages[0], pdfCertificate, "", signatureField);

            signature.ContactInfo  = "*****@*****.**";
            signature.LocationInfo = "Honolulu, Hawaii";
            signature.Reason       = "I am author of this document.";

            //Set the cryptographic standard to signature settings.
            if ((bool)cms.IsChecked)
            {
                signature.Settings.CryptographicStandard = CryptographicStandard.CMS;
            }
            else
            {
                signature.Settings.CryptographicStandard = CryptographicStandard.CADES;
            }

            //Set the digest algorithm to signature settings.
            if ((bool)sha1.IsChecked)
            {
                signature.Settings.DigestAlgorithm = DigestAlgorithm.SHA1;
            }
            else if ((bool)sha256.IsChecked)
            {
                signature.Settings.DigestAlgorithm = DigestAlgorithm.SHA256;
            }
            else if ((bool)sha384.IsChecked)
            {
                signature.Settings.DigestAlgorithm = DigestAlgorithm.SHA384;
            }
            else if ((bool)sha512.IsChecked)
            {
                signature.Settings.DigestAlgorithm = DigestAlgorithm.SHA512;
            }

            //Get the signature field appearance graphics.
            PdfGraphics graphics = signature.Appearance.Normal.Graphics;

            if (graphics != null)
            {
                //Draw the rectangle in appearance graphics.
                graphics.DrawRectangle(PdfPens.Black, bounds);

                //Get the image file stream from assembly.
                Stream imageStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.signature.png");
                //Create the PDF bitmap image from stream.
                PdfBitmap bitmap = new PdfBitmap(imageStream, true);
                //Draw image to appearance graphics.
                graphics.DrawImage(bitmap, new RectangleF(2, 1, 30, 30));

                //Get certificate subject name.
                string subject = pdfCertificate.SubjectName;

                //Create a new font instance and draw a text to appearance graphics.
                PdfFont         font     = new PdfStandardFont(PdfFontFamily.Helvetica, 7);
                RectangleF      textRect = new RectangleF(45, 0, bounds.Width - 45, bounds.Height);
                PdfStringFormat format   = new PdfStringFormat(PdfTextAlignment.Justify);
                graphics.DrawString("Digitally signed by " + subject + " \r\nReason: Testing signature \r\nLocation: USA", font, PdfBrushes.Black, textRect, format);
            }

            //Set the digital signature to signing the field.
            signatureField.Signature = signature;

            //Creating the stream object.
            using (MemoryStream stream = new MemoryStream())
            {
                //Save and close the document.
                loadedDocument.Save(stream);
                loadedDocument.Close();

                stream.Position = 0;
                //Save the output stream as a file using file picker.
                PdfUtil.Save("DigitalSignature.pdf", stream);
            }
        }
예제 #12
0
        private void GeneratePDF_Click(object sender, RoutedEventArgs e)
        {
            //Create a new PDF document.
            PdfDocument document = new PdfDocument();
            //Add a page to the document.
            PdfPage page = document.Pages.Add();
            //Create bounds to draw a image.
            RectangleF imageRect = new RectangleF(50, 50, 425, 642);
            //Get the image file stream from assembly.
            Stream imageStream = typeof(EBook).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.Pdf_Succinctly_img_1.jpg");
            //Create new image from stream.
            PdfBitmap image = new PdfBitmap(imageStream);

            //Draw image to PDF page.
            page.Graphics.DrawImage(image, imageRect);

            //Add a page to the document.
            PdfPage titlePage = document.Pages.Add();
            //Create font, string format and text bounds.
            PdfStandardFont times30Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 30);
            RectangleF      textRect    = new RectangleF(0, 60, titlePage.GetClientSize().Width, titlePage.GetClientSize().Height);
            PdfStringFormat format      = new PdfStringFormat(PdfTextAlignment.Center);

            //Draw a text to PDF page.
            titlePage.Graphics.DrawString("PDF Succinctly", times30Font, PdfBrushes.Black, textRect, format);

            //Create bounds to draw a image.
            imageRect = new RectangleF(40, 110, 435, 5);
            //Get the template PDF file stream from assembly.
            imageStream = typeof(EBook).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.Pdf_Succinctly_img_5.jpg");
            //Create new image from stream.
            image = new PdfBitmap(imageStream);
            //Draw image to PDF page.
            titlePage.Graphics.DrawImage(image, imageRect);

            //Create font, text bounds to draw a string to PDF page.
            PdfFont helvetica16 = new PdfStandardFont(PdfFontFamily.Helvetica, 16, PdfFontStyle.Bold);

            textRect = new RectangleF(0, 130, titlePage.GetClientSize().Width, titlePage.GetClientSize().Height);
            titlePage.Graphics.DrawString("By\nRyan Hodson", helvetica16, PdfBrushes.Black, textRect, format);

            //Create font, text bounds to draw a string to PDF page.
            PdfFont helvetica20 = new PdfStandardFont(PdfFontFamily.Helvetica, 20);

            textRect = new RectangleF(0, 220, titlePage.GetClientSize().Width, titlePage.GetClientSize().Height);
            titlePage.Graphics.DrawString("Foreword by Daniel Jebaraj", helvetica20, PdfBrushes.Black, textRect, format);

            //Add new section to PDF document.
            PdfSection section = document.Sections.Add();
            //Add a new page to section.
            PdfPage contentPage = section.Pages.Add();

            //Add a new text content to PDF page.
            AddParagraph(contentPage, "Table of Contents", new RectangleF(20, 60, 495, contentPage.GetClientSize().Height), true, true);

            //Create a header template and draw a text.
            PdfPageTemplateElement headerElement = new PdfPageTemplateElement(new Rectangle(0, 0, 515, 50), contentPage);

            //Set transparency to header graphics.
            headerElement.Graphics.SetTransparency(0.6F);
            //Create alignment and string format for header content.
            PdfTextAlignment     textAlingment     = PdfTextAlignment.Right;
            PdfVerticalAlignment verticalAlignment = PdfVerticalAlignment.Middle;

            format = new PdfStringFormat(textAlingment, verticalAlignment);
            //Draw text to header template.
            headerElement.Graphics.DrawString("PDF Succinctly", new PdfStandardFont(PdfFontFamily.Helvetica, 10), PdfBrushes.Black, new RectangleF(0, 0, 515, 50), format);
            //Draw line to header template.
            headerElement.Graphics.DrawLine(PdfPens.Gray, new PointF(0, 49), new PointF(515, 49));
            //Set the top page template.
            section.Template.Top = headerElement;

            //Create a footer template and draw a text.
            PdfPageTemplateElement footerElement = new PdfPageTemplateElement(new RectangleF(0, 0, 515, 50), contentPage);

            //Set transparency to header graphics.
            footerElement.Graphics.SetTransparency(0.6F);
            //Create new font to draw the content in footer template.
            PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 7);
            //Create page number field.
            PdfPageNumberField pageNumber = new PdfPageNumberField(font, PdfBrushes.Black);
            //Create page count field.
            PdfPageCountField count = new PdfPageCountField(font, PdfBrushes.Black);
            //Add the fields in composite fields.
            PdfCompositeField compositeField = new PdfCompositeField(font, PdfBrushes.Black, "Page {0} of {1}", pageNumber, count);

            compositeField.Bounds = footerElement.Bounds;
            //Draw the composite field in footer.
            compositeField.Draw(footerElement.Graphics, new PointF(450, 35));
            //Set the bottom page template.
            section.Template.Bottom = footerElement;
            //Add a new PDF page to PDF document.
            page = document.Pages.Add();
            SizeF pageSize = page.GetClientSize();

            //Add a new text content to PDF page and get layout result.
            PdfLayoutResult result = AddParagraph(page, "Introduction", new RectangleF(20, 25, 495, pageSize.Height), true, true);

            //Add to table of content and get layout result.
            PdfLayoutResult tableContent = AddTableOfContents(contentPage, "Introduction", new RectangleF(20, 110, 470, result.Page.GetClientSize().Height), true, 4, 20, result.Bounds.Top, result.Page);
            //Create color for bookmark.
            PdfColor bookmarkColor = new PdfColor(0, 0, 0);

            //Add bookmark to PDF page.
            AddBookmark(page, "Introduction", result.Bounds.Location, document, null, bookmarkColor);

            //Add a new text content to PDF page and get layout result.
            result = AddParagraph(result.Page, "Adobe Systems Incorporated\'s Portable Document Format (PDF) is the de facto standard for the accurate, reliable, and platform-independent representation of a paged document. It\'s the only universally accepted file format that allows pixel-perfect layouts. In addition, PDF supports user interaction and collaborative workflows that are not possible with printed documents.\n\nPDF documents have been in widespread use for years, and dozens of free and commercial PDF readers, editors, and libraries are readily available. However, despite this popularity, it\'s still difficult to find a succinct guide to the native PDF format. Understanding the internal workings of a PDF makes it possible to dynamically generate PDF documents. For example, a web server can extract information from a database, use it to customize an invoice, and serve it to the customer on the fly.",
                                  new RectangleF(20, result.Bounds.Bottom + 20, 495, pageSize.Height), false, false);

            //Add a new text content to PDF page and get layout result.
            result = AddParagraph(result.Page, "The PDF Standard", new RectangleF(20, result.Bounds.Bottom + 25, 495, pageSize.Height), true, false);

            //Add to table of content and get layout result.
            tableContent = AddTableOfContents(tableContent.Page, "The PDF Standard", new RectangleF(20, tableContent.Bounds.Bottom, 470, result.Page.GetClientSize().Height),
                                              false, 4, 20, result.Bounds.Top, result.Page);

            //Add bookmark to PDF page.
            AddBookmark(result.Page, "The PDF Standard", result.Bounds.Location, document, null, bookmarkColor);

            //Add a new text content to PDF page and get layout result.
            result = AddParagraph(result.Page, "The PDF format is an open standard maintained by the International Organization for Standardization. The official specification is defined in ISO 32000-1:2008, but Adobe also provides a free, comprehensive guide called PDF Reference, Sixth Edition, version 1.7.",
                                  new RectangleF(20, result.Bounds.Bottom + 20, 495, pageSize.Height), false);

            //Add a new text content to PDF page and get layout result.
            result = AddParagraph(result.Page, "Chapter 1 Conceptual Overview", new RectangleF(20, result.Bounds.Bottom + 25, 495, pageSize.Height), true, true);

            //Add to table of content and get layout result.
            tableContent = AddTableOfContents(tableContent.Page, "Chapter 1 Conceptual Overview", new RectangleF(20, tableContent.Bounds.Bottom, 470, result.Page.GetClientSize().Height),
                                              true, 4, 20, result.Bounds.Top, result.Page);

            //Add bookmark to PDF page.
            PdfBookmark standardBookmark = AddBookmark(result.Page, "Chapter 1 Conceptual Overview", result.Bounds.Location, document, null, bookmarkColor);

            //Add a new text content to PDF page and get layout result.
            result = AddParagraph(result.Page, "We\'ll begin with a conceptual overview of a simple PDF document. This chapter is designed to be a brief orientation before diving in and creating a real document from scratch.\nA PDF file can be divided into four parts: a header, body, cross-reference table, and trailer. The header marks the file as a PDF, the body defines the visible document, the cross-reference table lists the location of everything in the file, and the trailer provides instructions for how to start reading the file.",
                                  new RectangleF(20, result.Bounds.Bottom + 20, 495, pageSize.Height), false);

            //Add a new PDF page to PDF document.
            PdfPage page2 = document.Pages.Add();

            //Get the image file stream from assembly.
            Stream imageStream1 = typeof(EBook).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.Pdf_Succinctly_img_2.jpg");
            //Create PDF bitmap image from stream.
            PdfBitmap bitmap = new PdfBitmap(imageStream1);

            //Draw the image to PDF page.
            page2.Graphics.DrawImage(bitmap, new RectangleF(10, 0, 495, 600));

            //Add a new text content to PDF page and get layout result.
            result = AddParagraph(page2, "Every PDF file must have these four components.", new RectangleF(20, 620, 495, page2.GetClientSize().Height), false);

            //Add a new text content to PDF page and get layout result.
            result = AddParagraph(document.Pages.Add(), "Header", new RectangleF(20, 15, 495, pageSize.Height), true);

            //Add to table of content and get layout result.
            tableContent = AddTableOfContents(tableContent.Page, "Header", new RectangleF(20, tableContent.Bounds.Bottom, 470, result.Page.GetClientSize().Height),
                                              false, 6, 20, result.Bounds.Top, result.Page);

            //Add bookmark to PDF page.
            AddBookmark(result.Page, "Header", result.Bounds.Location, null, standardBookmark, bookmarkColor);

            //Add a new text content to PDF page and get layout result.
            result = AddParagraph(result.Page, "The header is simply a PDF version number and an arbitrary sequence of binary data. The binary data prevents na�ve applications from processing the PDF as a text file. This would result in a corrupted file, since a PDF typically consists of both plain text and binary data (e.g., a binary font file can be directly embedded in a PDF).",
                                  new RectangleF(20, result.Bounds.Bottom + 20, 495, pageSize.Height), false);

            //Add a new text content to PDF page and get layout result.
            result = AddParagraph(result.Page, "Body", new RectangleF(20, result.Bounds.Bottom + 25, 495, pageSize.Height), true);

            //Add to table of content and get layout result.
            tableContent = AddTableOfContents(tableContent.Page, "Body", new RectangleF(20, tableContent.Bounds.Bottom, 470, result.Page.GetClientSize().Height),
                                              false, 6, 20, result.Bounds.Top, result.Page);

            //Add bookmark to PDF page.
            AddBookmark(result.Page, "Body", result.Bounds.Location, null, standardBookmark, bookmarkColor);

            //Add a new text content to PDF page and get layout result.
            result = AddParagraph(result.Page, "The body of a PDF contains the entire visible document. The minimum elements required in a valid PDF body are:\n\n1. A page tree \n2. Pages \n3. Resources \n4. Content \n5. The catalog \n\nThe page tree serves as the root of the document. In the simplest case, it is just a list of the pages in the document. Each page is defined as an independent entity with metadata (e.g., page dimensions) and a reference to its resources and content, which are defined separately. Together, the page tree and page objects create the \"paper\" that composes the document.\n\nResources are objects that are required to render a page. For example, a single font is typically used across several pages, so storing the font information in an external resource is much more efficient. A content object defines the text and graphics that actually show up on the page. Together, content objects and resources define the appearance of an individual page.\nFinally, the document\'s catalog tells applications where to start reading the document. Often, this is just a pointer to the root page tree.",
                                  new RectangleF(20, result.Bounds.Bottom + 20, 495, pageSize.Height), false);

            //Add a new PDF page to PDF document.
            PdfPage page3 = document.Pages.Add();
            //Get the image file stream from assembly.
            Stream imageStream2 = typeof(EBook).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.Pdf_Succinctly_img_3.jpg");
            //Create PDF bitmap image from stream.
            PdfBitmap bitmap2 = new PdfBitmap(imageStream2);

            //Draw the image to PDF page.
            page3.Graphics.DrawImage(bitmap2, new RectangleF(20, 0, 300, 400));

            //Add a new text content to PDF page and get layout result.
            result = AddParagraph(page3, "Cross-Reference Table", new RectangleF(20, 425, 495, pageSize.Height), true);

            //Add to table of content and get layout result.
            tableContent = AddTableOfContents(tableContent.Page, "Cross-Reference Table", new RectangleF(20, tableContent.Bounds.Bottom, 470, result.Page.GetClientSize().Height),
                                              false, 7, 20, result.Bounds.Top, result.Page);

            //Add bookmark to PDF page.
            AddBookmark(result.Page, "Cross-Reference Table", result.Bounds.Location, null, standardBookmark, bookmarkColor);

            //Add a new text content to PDF page and get layout result.
            result = AddParagraph(result.Page, "After the header and the body comes the cross-reference table. It records the byte location of each object in the body of the file. This enables random-access of the document, so when rendering a page, only the objects required for that page are read from the file. This makes PDFs much faster than their PostScript predecessors, which had to read in the entire file before processing it.",
                                  new RectangleF(20, result.Bounds.Bottom + 20, 495, pageSize.Height), false);

            //Add a new text content to PDF page and get layout result.
            result = AddParagraph(result.Page, "Trailer", new RectangleF(20, result.Bounds.Bottom + 25, 495, pageSize.Height), true);

            //Add to table of content and get layout result.
            tableContent = AddTableOfContents(tableContent.Page, "Trailer", new RectangleF(20, tableContent.Bounds.Bottom, 470, result.Page.GetClientSize().Height),
                                              false, 7, 20, result.Bounds.Top, result.Page);

            //Add bookmark to PDF page.
            AddBookmark(result.Page, "Trailer", result.Bounds.Location, null, standardBookmark, bookmarkColor);

            //Add a new text content to PDF page and get layout result.
            result = AddParagraph(result.Page, "Finally, we come to the last component of a PDF document. The trailer tells applications how to start reading the file. At minimum, it contains three things:\n\n\n1. A reference to the catalog which links to the root of the document.\n2. The location of the cross-reference table.\n3. The size of the cross-reference table.\n\nSince a trailer is all you need to begin processing a document, PDFs are typically read back-to-front: first, the end of the file is found, and then you read backwards until you arrive at the beginning of the trailer. After that, you should have all the information you need to load any page in the PDF.",
                                  new RectangleF(20, result.Bounds.Bottom + 20, 495, pageSize.Height), false);

            //Add a new text content to PDF page and get layout result.
            result = AddParagraph(result.Page, "Summary", new RectangleF(20, result.Bounds.Bottom + 25, 495, pageSize.Height), true);

            //Add to table of content and get layout result.
            tableContent = AddTableOfContents(tableContent.Page, "Summary", new RectangleF(20, tableContent.Bounds.Bottom, 470, result.Page.GetClientSize().Height),
                                              false, 8, 20, result.Bounds.Top, result.Page);

            //Add bookmark to PDF page.
            AddBookmark(result.Page, "Summary", result.Bounds.Location, null, standardBookmark, bookmarkColor);

            //Add a new text content to PDF page and get layout result.
            result = AddParagraph(result.Page, "To conclude our overview, a PDF document has a header, a body, a cross-reference table, and a trailer. The trailer serves as the entryway to the entire document, giving you access to any object via the cross-reference table, and pointing you toward the root of the document. The relationship between these elements is shown in the following figure.",
                                  new RectangleF(20, result.Bounds.Bottom + 20, 495, pageSize.Height), false);

            //Get the image file stream from assembly.
            Stream imageStream3 = typeof(EBook).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.Pdf_Succinctly_img_4.jpg");
            //Create PDF bitmap image from stream.
            PdfBitmap bitmap3 = new PdfBitmap(imageStream3);

            //Draw the image to PDF page.
            result.Page.Graphics.DrawImage(bitmap3, new RectangleF(20, result.Bounds.Bottom + 20, 495, 400));

            //Creating the stream object.
            using (MemoryStream stream = new MemoryStream())
            {
                //Save the document into stream.
                document.Save(stream);
                document.Close();

                stream.Position = 0;

                //Save the output stream as a file using file picker.
                PdfUtil.Save("E-Book.pdf", stream);
            }
        }
예제 #13
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            //Create a new PDF document.
            PdfDocument document = new PdfDocument();
            //Creates a new page
            PdfPage page = document.Pages.Add();

            //Sets the margins to the page.
            document.PageSettings.SetMargins(0);
            //Create new PDF font instance.
            PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 10f);
            //Create new PDF solid brush.
            PdfBrush brush = new PdfSolidBrush(Color.FromArgb(255, 0, 0, 0));

            //Draw the text to PDF page graphics.
            string text = "Adventure Works Cycles, the fictitious company on which the AdventureWorks sample databases are based, is a large, multinational manufacturing company. The company manufactures and sells metal and composite bicycles to North American, European and Asian commercial markets. While its base operation is located in Washington with 290 employees, several regional sales teams are located throughout their market base.";

            page.Graphics.DrawString("Annotation with Comments and Reviews", font, brush, new PointF(30, 10));
            page.Graphics.DrawString(text, font, brush, new RectangleF(30, 40, page.GetClientSize().Width - 60, 60));

            //Creates PDF text markup annotation.
            string markupText = "North American, European and Asian commercial markets";
            PdfTextMarkupAnnotation textMarkupAnnotation = new PdfTextMarkupAnnotation("sample", "Highlight", markupText, new PointF(147, 63.5f), font);

            textMarkupAnnotation.Author                   = "Annotation";
            textMarkupAnnotation.Opacity                  = 1.0f;
            textMarkupAnnotation.Subject                  = "Comments and Reviews";
            textMarkupAnnotation.ModifiedDate             = new DateTime(2015, 1, 18);
            textMarkupAnnotation.TextMarkupAnnotationType = PdfTextMarkupAnnotationType.Highlight;
            textMarkupAnnotation.TextMarkupColor          = new PdfColor(Color.Yellow);
            textMarkupAnnotation.InnerColor               = new PdfColor(Color.Red);
            textMarkupAnnotation.Color = new PdfColor(Color.Yellow);

            //Create a new comment.
            PdfPopupAnnotation userQuery = new PdfPopupAnnotation();

            userQuery.Author       = "John";
            userQuery.Text         = "Can you please change South Asian to Asian?";
            userQuery.ModifiedDate = new DateTime(2015, 1, 18);
            //Add comment to the annotation
            textMarkupAnnotation.Comments.Add(userQuery);

            //Creates a new comment.
            PdfPopupAnnotation userAnswer = new PdfPopupAnnotation();

            userAnswer.Author       = "Smith";
            userAnswer.Text         = "South Asian has changed as Asian";
            userAnswer.ModifiedDate = new DateTime(2015, 1, 18);
            //Add comment to the annotation.
            textMarkupAnnotation.Comments.Add(userAnswer);

            //Creates a new review.
            PdfPopupAnnotation userAnswerReview = new PdfPopupAnnotation();

            userAnswerReview.Author       = "Smith";
            userAnswerReview.State        = PdfAnnotationState.Completed;
            userAnswerReview.StateModel   = PdfAnnotationStateModel.Review;
            userAnswerReview.ModifiedDate = new DateTime(2015, 1, 18);
            //Add review to the comment.
            userAnswer.ReviewHistory.Add(userAnswerReview);

            //Creates a new review.
            PdfPopupAnnotation userAnswerReviewJohn = new PdfPopupAnnotation();

            userAnswerReviewJohn.Author       = "John";
            userAnswerReviewJohn.State        = PdfAnnotationState.Accepted;
            userAnswerReviewJohn.StateModel   = PdfAnnotationStateModel.Review;
            userAnswerReviewJohn.ModifiedDate = new DateTime(2015, 1, 18);
            //Add review to the comment.
            userAnswer.ReviewHistory.Add(userAnswerReviewJohn);

            //Add annotation to the page.
            page.Annotations.Add(textMarkupAnnotation);

            //Creates a new Circle annotation.
            PdfCircleAnnotation circleAnnotation = new PdfCircleAnnotation(new RectangleF(350, 170, 80, 80));

            circleAnnotation.InnerColor      = new PdfColor(Color.Yellow);
            circleAnnotation.Color           = new PdfColor(Color.Red);
            circleAnnotation.AnnotationFlags = PdfAnnotationFlags.Default;
            circleAnnotation.Author          = "Syncfusion";
            circleAnnotation.Subject         = "CircleAnnotation";
            circleAnnotation.ModifiedDate    = new DateTime(2015, 1, 18);
            page.Annotations.Add(circleAnnotation);
            page.Graphics.DrawString("Circle Annotation", font, brush, new PointF(350, 130));

            //Creates a new Ellipse annotation.
            PdfEllipseAnnotation ellipseAnnotation = new PdfEllipseAnnotation(new RectangleF(30, 150, 50, 100), "Ellipse Annotation");

            ellipseAnnotation.Color      = new PdfColor(Color.Red);
            ellipseAnnotation.InnerColor = new PdfColor(Color.Yellow);
            page.Graphics.DrawString("Ellipse Annotation", font, brush, new PointF(30, 130));
            page.Annotations.Add(ellipseAnnotation);

            //Creates a new Square annotation.
            PdfSquareAnnotation squareAnnotation = new PdfSquareAnnotation(new RectangleF(30, 300, 80, 80));

            squareAnnotation.Text       = "SquareAnnotation";
            squareAnnotation.InnerColor = new PdfColor(Color.Red);
            squareAnnotation.Color      = new PdfColor(Color.Yellow);
            page.Graphics.DrawString("Square Annotation", font, brush, new PointF(30, 280));
            page.Annotations.Add(squareAnnotation);

            //Creates a new Rectangle annotation.
            PdfRectangleAnnotation rectangleAnnotation = new PdfRectangleAnnotation(new RectangleF(350, 320, 100, 50), "RectangleAnnotation");

            rectangleAnnotation.InnerColor = new PdfColor(Color.Red);
            rectangleAnnotation.Color      = new PdfColor(Color.Yellow);
            page.Graphics.DrawString("Rectangle Annotation", font, brush, new PointF(350, 280));
            page.Annotations.Add(rectangleAnnotation);

            //Creates a new Line annotation.
            int[]             linePoints     = new int[] { 400, 350, 550, 350 };
            PdfLineAnnotation lineAnnotation = new PdfLineAnnotation(linePoints, "Line Annoation is the one of the annotation type...");

            lineAnnotation.Author       = "Syncfusion";
            lineAnnotation.Subject      = "LineAnnotation";
            lineAnnotation.ModifiedDate = new DateTime(2015, 1, 18);
            lineAnnotation.Text         = "PdfLineAnnotation";
            lineAnnotation.BackColor    = new PdfColor(Color.Red);
            page.Graphics.DrawString("Line Annotation", font, brush, new PointF(400, 420));
            page.Annotations.Add(lineAnnotation);

            //Creates a new Polygon annotation.
            int[] polyLinePoints = new int[] { 50, 298, 100, 325, 200, 355, 300, 230, 180, 230 };
            PdfPolygonAnnotation polygonAnnotation = new PdfPolygonAnnotation(polyLinePoints, "PolygonAnnotation");

            polygonAnnotation.Bounds     = new RectangleF(30, 210, 300, 200);
            polygonAnnotation.Text       = "polygon";
            polygonAnnotation.Color      = new PdfColor(Color.Red);
            polygonAnnotation.InnerColor = new PdfColor(Color.LightPink);
            page.Graphics.DrawString("Polygon Annotation", font, brush, new PointF(50, 420));
            page.Annotations.Add(polygonAnnotation);

            //Creates a new Freetext annotation.
            PdfFreeTextAnnotation freeTextAnnotation = new PdfFreeTextAnnotation(new RectangleF(405, 645, 80, 30));

            freeTextAnnotation.MarkupText      = "Free Text with Callouts";
            freeTextAnnotation.TextMarkupColor = new PdfColor(Color.Green);
            freeTextAnnotation.Font            = new PdfStandardFont(PdfFontFamily.Helvetica, 7f);
            freeTextAnnotation.BorderColor     = new PdfColor(Color.Blue);
            freeTextAnnotation.Border          = new PdfAnnotationBorder(.5f);
            freeTextAnnotation.AnnotationFlags = PdfAnnotationFlags.Default;
            freeTextAnnotation.Text            = "Free Text";
            freeTextAnnotation.Color           = new PdfColor(Color.Yellow);
            PointF[] freeTextPoints = { new PointF(365, 700), new PointF(379, 654), new PointF(405, 654) };
            freeTextAnnotation.CalloutLines = freeTextPoints;
            page.Graphics.DrawString("FreeText Annotation", font, brush, new PointF(400, 610));
            page.Annotations.Add(freeTextAnnotation);

            //Creates a new Ink annotation.
            List <float> inkLinePoints = new List <float> {
                72.919f, 136.376f, 72.264f, 136.376f, 62.446f, 142.922f, 61.137f, 142.922f, 55.901f, 139.649f, 55.246f, 138.34f, 54.592f, 132.449f, 54.592f, 127.867f, 55.901f, 125.904f, 59.828f, 121.976f, 63.101f, 121.322f, 65.719f, 122.631f, 68.992f, 125.249f, 70.301f, 130.485f, 71.61f, 133.104f, 72.264f, 136.376f, 72.919f, 140.304f, 74.883f, 144.885f, 76.192f, 150.776f, 76.192f, 151.431f, 76.192f, 152.085f, 76.192f, 158.631f, 76.192f, 159.94f, 75.537f, 155.358f, 74.228f, 150.122f, 74.228f, 146.195f, 73.574f, 141.613f, 73.574f, 137.685f, 74.228f, 132.449f, 74.883f, 128.522f, 75.537f, 124.594f, 76.192f, 123.285f, 76.846f, 122.631f, 80.774f, 122.631f, 82.737f, 123.285f, 85.355f, 125.249f, 88.628f, 129.831f, 89.283f, 133.104f, 89.937f, 137.031f, 90.592f, 140.958f, 89.937f, 142.267f, 86.665f, 141.613f, 85.355f, 140.304f, 84.701f, 138.34f, 84.701f, 137.685f, 85.355f, 137.031f, 87.974f, 135.722f, 90.592f, 136.376f, 92.555f, 137.031f, 96.483f, 139.649f, 98.446f, 140.958f, 101.719f, 142.922f, 103.028f, 142.922f, 100.41f, 138.34f, 99.756f, 134.413f, 99.101f, 131.14f, 99.101f, 128.522f, 99.756f, 127.213f, 101.065f, 125.904f, 102.374f, 123.94f, 103.683f, 123.94f, 107.61f, 125.904f, 110.228f, 129.831f, 114.156f, 135.067f, 117.428f, 140.304f, 119.392f, 143.576f, 121.356f, 144.231f, 122.665f, 144.231f, 123.974f, 142.267f, 126.592f, 139.649f, 127.247f, 140.304f, 126.592f, 142.922f, 124.628f, 143.576f, 122.01f, 142.922f, 118.083f, 141.613f, 114.81f, 136.376f, 114.81f, 131.14f, 113.501f, 127.213f, 114.156f, 125.904f, 118.083f, 125.904f, 120.701f, 126.558f, 123.319f, 130.485f, 125.283f, 136.376f, 125.937f, 140.304f, 125.937f, 142.922f, 126.592f, 143.576f, 125.937f, 135.722f, 125.937f, 131.794f, 125.937f, 131.14f, 127.247f, 129.176f, 129.21f, 127.213f, 131.828f, 127.213f, 134.447f, 128.522f, 136.41f, 136.376f, 139.028f, 150.122f, 141.647f, 162.558f, 140.992f, 163.213f, 138.374f, 160.595f, 135.756f, 153.395f, 135.101f, 148.158f, 134.447f, 140.304f, 134.447f, 130.485f, 133.792f, 124.594f, 133.792f, 115.431f, 133.792f, 110.194f, 133.792f, 105.612f, 134.447f, 105.612f, 137.065f, 110.194f, 137.719f, 116.74f, 139.028f, 120.013f, 139.028f, 123.94f, 137.719f, 127.213f, 135.756f, 130.485f, 134.447f, 130.485f, 133.792f, 130.485f, 137.719f, 131.794f, 141.647f, 135.722f, 146.883f, 142.922f, 152.774f, 153.395f, 153.428f, 159.286f, 150.156f, 159.94f, 147.537f, 156.667f, 146.883f, 148.813f, 146.883f, 140.958f, 146.883f, 134.413f, 146.883f, 125.904f, 145.574f, 118.703f, 145.574f, 114.776f, 145.574f, 112.158f, 146.228f, 111.503f, 147.537f, 111.503f, 148.192f, 112.158f, 150.156f, 112.812f, 150.81f, 113.467f, 152.119f, 114.776f, 154.083f, 117.394f, 155.392f, 119.358f, 156.701f, 120.667f, 157.356f, 121.976f, 156.701f, 121.322f, 156.047f, 120.013f, 155.392f, 119.358f, 154.083f, 117.394f, 154.083f, 116.74f, 152.774f, 114.776f, 152.119f, 114.121f, 150.81f, 113.467f, 149.501f, 113.467f, 147.537f, 112.158f, 146.883f, 112.158f, 145.574f, 111.503f, 144.919f, 112.158f, 144.265f, 114.121f, 144.265f, 115.431f, 144.265f, 116.74f, 144.265f, 117.394f, 144.265f, 118.049f, 144.919f, 118.703f, 145.574f, 120.667f, 146.228f, 122.631f, 147.537f, 123.285f, 147.537f, 124.594f, 148.192f, 125.904f, 147.537f, 128.522f, 147.537f, 129.176f, 147.537f, 130.485f, 147.537f, 132.449f, 147.537f, 134.413f, 147.537f, 136.376f, 147.537f, 138.34f, 147.537f, 138.994f, 145.574f, 138.994f, 142.956f, 138.252f
            };
            RectangleF       rectangle     = new RectangleF(30, 580, 300, 400);
            PdfInkAnnotation inkAnnotation = new PdfInkAnnotation(rectangle, inkLinePoints);

            inkAnnotation.Bounds = rectangle;
            inkAnnotation.Color  = new PdfColor(Color.Red);
            page.Graphics.DrawString("Ink Annotation", font, brush, new PointF(30, 610));
            page.Annotations.Add(inkAnnotation);

            //Creates a new page.
            PdfPage secondPage = document.Pages.Add();

            //Creates a new TextMarkup annotation.
            text = "This is TextMarkup annotation!!!";
            secondPage.Graphics.DrawString(text, font, brush, new PointF(30, 70));
            PdfTextMarkupAnnotation textAnnotation = new PdfTextMarkupAnnotation("sample", "Strikeout", text, new PointF(30, 70), font);

            textAnnotation.Author                   = "Annotation";
            textAnnotation.Opacity                  = 1.0f;
            textAnnotation.Subject                  = "pdftextmarkupannotation";
            textAnnotation.ModifiedDate             = new DateTime(2015, 1, 18);
            textAnnotation.TextMarkupAnnotationType = PdfTextMarkupAnnotationType.StrikeOut;
            textAnnotation.TextMarkupColor          = new PdfColor(Color.Yellow);
            textAnnotation.InnerColor               = new PdfColor(Color.Red);
            textAnnotation.Color = new PdfColor(Color.Yellow);

            secondPage.Graphics.DrawString("TextMarkup Annotation", font, brush, new PointF(30, 40));
            secondPage.Annotations.Add(textAnnotation);

            //Creates a new popup annotation.
            RectangleF         popupRectangle  = new RectangleF(430, 70, 30, 30);
            PdfPopupAnnotation popupAnnotation = new PdfPopupAnnotation();

            popupAnnotation.Border.Width            = 4;
            popupAnnotation.Border.HorizontalRadius = 20;
            popupAnnotation.Border.VerticalRadius   = 30;
            popupAnnotation.Opacity    = 1;
            popupAnnotation.Open       = true;
            popupAnnotation.Text       = "Popup Annotation";
            popupAnnotation.Color      = Color.Green;
            popupAnnotation.InnerColor = Color.Blue;
            popupAnnotation.Bounds     = popupRectangle;
            secondPage.Graphics.DrawString("Popup Annotation", font, brush, new PointF(400, 40));

            if (flatten.IsChecked == true)
            {
                //Flatten the annotation and popup window.
                popupAnnotation.FlattenPopUps = true;
                popupAnnotation.Flatten       = true;
            }
            secondPage.Annotations.Add(popupAnnotation);

            //Creates a new Line measurement annotation.
            linePoints = new int[] { 400, 540, 550, 540 };
            PdfLineMeasurementAnnotation lineMeasureAnnotation = new PdfLineMeasurementAnnotation(linePoints);

            lineMeasureAnnotation.Author                 = "Syncfusion";
            lineMeasureAnnotation.Subject                = "LineAnnotation";
            lineMeasureAnnotation.ModifiedDate           = new DateTime(2015, 1, 18);
            lineMeasureAnnotation.Unit                   = PdfMeasurementUnit.Inch;
            lineMeasureAnnotation.lineBorder.BorderWidth = 2;
            lineMeasureAnnotation.Font                   = new PdfStandardFont(PdfFontFamily.Helvetica, 10f, PdfFontStyle.Regular);
            lineMeasureAnnotation.Color                  = new PdfColor(Color.Red);
            if (flatten.IsChecked == true)
            {
                //Flatten the line measurement annotation.
                lineMeasureAnnotation.Flatten = true;
            }
            secondPage.Graphics.DrawString("Line Measurement Annotation", font, brush, new PointF(370, 240));
            secondPage.Annotations.Add(lineMeasureAnnotation);

            //Creates a new Freetext annotation.
            PdfFreeTextAnnotation freeTextAnnotationRotation = new PdfFreeTextAnnotation(new RectangleF(80, 160, 100, 50));

            freeTextAnnotationRotation.MarkupText      = "Free Text with Callouts";
            freeTextAnnotationRotation.TextMarkupColor = new PdfColor(Color.Green);
            freeTextAnnotationRotation.Font            = new PdfStandardFont(PdfFontFamily.Helvetica, 7f);
            freeTextAnnotationRotation.BorderColor     = new PdfColor(Color.Blue);
            freeTextAnnotationRotation.Border          = new PdfAnnotationBorder(.5f);
            freeTextAnnotationRotation.AnnotationFlags = PdfAnnotationFlags.Default;
            freeTextAnnotationRotation.Text            = "Free Text";
            freeTextAnnotationRotation.Rotate          = PdfAnnotationRotateAngle.RotateAngle90;
            freeTextAnnotationRotation.Color           = new PdfColor(Color.Yellow);
            PointF[] callOutLines = { new PointF(45, 220), new PointF(60, 175), new PointF(80, 175) };
            freeTextAnnotationRotation.CalloutLines = callOutLines;
            secondPage.Graphics.DrawString("Rotated FreeText Annotation", font, brush, new PointF(40, 130));
            secondPage.Annotations.Add(freeTextAnnotationRotation);

            //Creates a new rectangle annotation with cloud border style.
            PdfRectangleAnnotation cloudAnnotation = new PdfRectangleAnnotation(new RectangleF(30, 300, 100, 50), "Rectangle Cloud Annoatation");

            cloudAnnotation.Border.BorderWidth = 1;
            cloudAnnotation.Color      = Color.Red;
            cloudAnnotation.InnerColor = Color.Blue;
            PdfBorderEffect borderEffect = new PdfBorderEffect();

            borderEffect.Intensity       = 2;
            borderEffect.Style           = PdfBorderEffectStyle.Cloudy;
            cloudAnnotation.BorderEffect = borderEffect;
            secondPage.Graphics.DrawString("Cloud Annotation", font, brush, new PointF(40, 260));
            secondPage.Annotations.Add(cloudAnnotation);

            if (flatten.IsChecked == false)
            {
                //Create a new redaction annotation.
                PdfRedactionAnnotation redactionannotation = new PdfRedactionAnnotation();
                redactionannotation.Bounds        = new RectangleF(350, 340, 100, 50);
                redactionannotation.Text          = "Redaction Annotation";
                redactionannotation.InnerColor    = Color.Orange;
                redactionannotation.BorderColor   = Color.Red;
                redactionannotation.Font          = new PdfStandardFont(PdfFontFamily.Helvetica, 13);
                redactionannotation.TextColor     = Color.Green;
                redactionannotation.OverlayText   = "REDACTED";
                redactionannotation.RepeatText    = true;
                redactionannotation.TextAlignment = PdfTextAlignment.Left;
                redactionannotation.SetAppearance(true);
                secondPage.Graphics.DrawString("Redaction Annotation", font, brush, new PointF(350, 320));
                secondPage.Annotations.Add(redactionannotation);
            }

            //Creating the stream object.
            using (MemoryStream stream = new MemoryStream())
            {
                string fileName = "Annotation.pdf";

                //Save and close the document.
                document.Save(stream);
                document.Close(true);

                if ((bool)flatten.IsChecked)
                {
                    fileName = "AnnotationFlatten.pdf";

                    //Loading and flatten the annotation in a PDF document.
                    PdfLoadedDocument loadedDocument = new PdfLoadedDocument(stream);
                    PdfLoadedPage     page1          = loadedDocument.Pages[0] as PdfLoadedPage;
                    PdfLoadedPage     page2          = loadedDocument.Pages[1] as PdfLoadedPage;
                    if (flatten.IsChecked == true)
                    {
                        page1.Annotations.Flatten = true;
                        page2.Annotations.Flatten = true;
                    }

                    //Save the document into stream.
                    loadedDocument.Save(stream);
                    loadedDocument.Close();
                }
                stream.Position = 0;
                //Save the output stream as a file using file picker.
                PdfUtil.Save(fileName, stream);
            }
        }
예제 #14
0
        private void GeneratePDF_Click(object sender, RoutedEventArgs e)
        {
            //Create a new PDF document.
            PdfDocument document = new PdfDocument();
            //Add a page to the document.
            PdfPage page = document.Pages.Add();
            //Create PDF graphics for the page.
            PdfGraphics graphics = page.Graphics;

            //Get the page width and height
            float pageWidth  = page.GetClientSize().Width;
            float pageHeight = page.GetClientSize().Height;

            //Set the header height
            float headerHeight = 90;
            //Create brush with light blue color.
            PdfColor lightBlue      = Color.FromArgb(255, 91, 126, 215);
            PdfBrush lightBlueBrush = new PdfSolidBrush(lightBlue);
            //Create brush with dark blue color.
            PdfColor darkBlue      = Color.FromArgb(255, 65, 104, 209);
            PdfBrush darkBlueBrush = new PdfSolidBrush(darkBlue);
            //Create brush with white color.
            PdfBrush whiteBrush = new PdfSolidBrush(Color.FromArgb(255, 255, 255, 255));

            //Get the font file stream from assembly.
            Stream fontStream = typeof(Invoice).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.arial.ttf");

            //Create PdfTrueTypeFont from stream with different size.
            PdfTrueTypeFont headerFont       = new PdfTrueTypeFont(fontStream, 30, PdfFontStyle.Regular);
            PdfTrueTypeFont arialRegularFont = new PdfTrueTypeFont(fontStream, 18, PdfFontStyle.Regular);
            PdfTrueTypeFont arialBoldFont    = new PdfTrueTypeFont(fontStream, 9, PdfFontStyle.Bold);

            //Create string format.
            PdfStringFormat format = new PdfStringFormat();

            format.Alignment     = PdfTextAlignment.Center;
            format.LineAlignment = PdfVerticalAlignment.Middle;

            float y = 0;
            float x = 0;

            //Set the margins of address.
            float margin = 30;

            //Set the line space.
            float lineSpace = 10;

            //Create border pen and draw the border to PDF page.
            PdfColor borderColor = Color.FromArgb(255, 142, 170, 219);
            PdfPen   borderPen   = new PdfPen(borderColor, 1f);

            graphics.DrawRectangle(borderPen, new RectangleF(0, 0, pageWidth, pageHeight));

            //Create a new PdfGrid
            PdfGrid grid = new PdfGrid();

            //Add five columns to the grid.
            grid.Columns.Add(5);

            //Create the header row of the grid.
            PdfGridRow[] headerRow = grid.Headers.Add(1);

            //Set style to the header row and set value to the header cells.
            headerRow[0].Style.BackgroundBrush           = new PdfSolidBrush(new PdfColor(68, 114, 196));
            headerRow[0].Style.TextBrush                 = PdfBrushes.White;
            headerRow[0].Cells[0].Value                  = "Product ID";
            headerRow[0].Cells[0].StringFormat.Alignment = PdfTextAlignment.Center;
            headerRow[0].Cells[1].Value                  = "Product Name";
            headerRow[0].Cells[2].Value                  = "Price ($)";
            headerRow[0].Cells[3].Value                  = "Quantity";
            headerRow[0].Cells[4].Value                  = "Total ($)";

            //Add products to the grid table.
            AddProducts("CA-1098", "AWC Logo Cap", 8.99, 2, 17.98, grid);
            AddProducts("LJ-0192", "Long-Sleeve Logo Jersey,M", 49.99, 3, 149.97, grid);
            AddProducts("So-B909-M", "Mountain Bike Socks,M", 9.50, 2, 19, grid);
            AddProducts("LJ-0192", "Long-Sleeve Logo Jersey,M", 49.99, 4, 199.96, grid);
            AddProducts("FK-5136", "ML Fork", 175.49, 6, 1052.94, grid);
            AddProducts("HL-U509", "Sports-100 Helmet,Black", 34.99, 1, 34.99, grid);

            #region Header

            //Fill the header with light blue brush
            graphics.DrawRectangle(lightBlueBrush, new RectangleF(0, 0, pageWidth, headerHeight));

            string title = "INVOICE";

            //Specificy the bounds for total value.
            RectangleF headerTotalBounds = new RectangleF(400, 0, pageWidth - 400, headerHeight);

            //Measure the string size using font.
            SizeF textSize = headerFont.MeasureString(title);
            graphics.DrawString(title, headerFont, whiteBrush, new RectangleF(0, 0, textSize.Width + 50, headerHeight), format);
            //Draw rectangle in PDF page.
            graphics.DrawRectangle(darkBlueBrush, headerTotalBounds);
            //Draw the toal value to PDF page.
            graphics.DrawString("$" + GetTotalAmount(grid).ToString(), arialRegularFont, whiteBrush, new RectangleF(400, 0, pageWidth - 400, headerHeight + 10), format);
            //Create font from font stream.
            arialRegularFont = new PdfTrueTypeFont(fontStream, 9, PdfFontStyle.Regular);
            //Set bottom line alignment and draw the text to PDF page.
            format.LineAlignment = PdfVerticalAlignment.Bottom;
            graphics.DrawString("Amount", arialRegularFont, whiteBrush, new RectangleF(400, 0, pageWidth - 400, headerHeight / 2 - arialRegularFont.Height), format);
            #endregion
            //Measure the string size using font.
            SizeF size = arialRegularFont.MeasureString("Invoice Number: 2058557939");
            y = headerHeight + margin;
            x = (pageWidth - margin) - size.Width;
            //Draw text to PDF page with provided font and location.
            graphics.DrawString("Invoice Number: 2058557939", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
            //Measure the string size using font.
            size = arialRegularFont.MeasureString("Date :" + DateTime.Now.ToString("dddd dd, MMMM yyyy"));
            x    = (pageWidth - margin) - size.Width;
            y   += arialRegularFont.Height + lineSpace;
            //Draw text to PDF page with provided font and location.
            graphics.DrawString("Date: " + DateTime.Now.ToString("dddd dd, MMMM yyyy"), arialRegularFont, PdfBrushes.Black, new PointF(x, y));

            y = headerHeight + margin;
            x = margin;
            //Draw text to PDF page with provided font and location.
            graphics.DrawString("Bill To:", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
            y += arialRegularFont.Height + lineSpace;
            graphics.DrawString("Abraham Swearegin,", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
            y += arialRegularFont.Height + lineSpace;
            graphics.DrawString("United States, California, San Mateo,", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
            y += arialRegularFont.Height + lineSpace;
            graphics.DrawString("9920 BridgePointe Parkway,", arialRegularFont, PdfBrushes.Black, new PointF(x, y));
            y += arialRegularFont.Height + lineSpace;
            graphics.DrawString("9365550136", arialRegularFont, PdfBrushes.Black, new PointF(x, y));

            #region Grid
            //Set width to grid columns.
            grid.Columns[0].Width = 110;
            grid.Columns[1].Width = 150;
            grid.Columns[2].Width = 110;
            grid.Columns[3].Width = 70;
            grid.Columns[4].Width = 100;

            for (int i = 0; i < grid.Headers.Count; i++)
            {
                //Set height to the grid header row.
                grid.Headers[i].Height = 20;
                for (int j = 0; j < grid.Columns.Count; j++)
                {
                    //Create string format for header cell.
                    PdfStringFormat pdfStringFormat = new PdfStringFormat();
                    pdfStringFormat.LineAlignment = PdfVerticalAlignment.Middle;
                    pdfStringFormat.Alignment     = PdfTextAlignment.Left;

                    //Set cell padding for header cell.
                    if (j == 0 || j == 2)
                    {
                        grid.Headers[i].Cells[j].Style.CellPadding = new PdfPaddings(30, 1, 1, 1);
                    }
                    //Set string format to grid header cell.
                    grid.Headers[i].Cells[j].StringFormat = pdfStringFormat;
                    //Set font to the grid header cell.
                    grid.Headers[i].Cells[j].Style.Font = arialBoldFont;
                }
                //Set value to the grid header cell.
                grid.Headers[0].Cells[0].Value = "Product ID";
            }
            for (int i = 0; i < grid.Rows.Count; i++)
            {
                //Set height to the grid row.
                grid.Rows[i].Height = 23;
                for (int j = 0; j < grid.Columns.Count; j++)
                {
                    //Create string format for grid row.
                    PdfStringFormat pdfStringFormat = new PdfStringFormat();
                    pdfStringFormat.LineAlignment = PdfVerticalAlignment.Middle;
                    pdfStringFormat.Alignment     = PdfTextAlignment.Left;

                    //Set cell padding for grid row cell.
                    if (j == 0 || j == 2)
                    {
                        grid.Rows[i].Cells[j].Style.CellPadding = new PdfPaddings(30, 1, 1, 1);
                    }

                    //Set string format to grid row cell.
                    grid.Rows[i].Cells[j].StringFormat = pdfStringFormat;
                    //Set font to the grid row cell.
                    grid.Rows[i].Cells[j].Style.Font = arialRegularFont;
                }
            }
            //Apply built-in table style to the grid.
            grid.ApplyBuiltinStyle(PdfGridBuiltinStyle.ListTable4Accent5);
            //Subscribing to begin cell layout event.
            grid.BeginCellLayout += Grid_BeginCellLayout;
            //Draw the PDF grid to PDF page and get the layout result.
            PdfGridLayoutResult result = grid.Draw(page, new PointF(0, y + 40));

            //Using the layout result, continue to draw the text.
            y                = result.Bounds.Bottom + lineSpace;
            format           = new PdfStringFormat();
            format.Alignment = PdfTextAlignment.Center;
            RectangleF bounds = new RectangleF(QuantityCellBounds.X, y, QuantityCellBounds.Width, QuantityCellBounds.Height);
            //Draw text to PDF page based on the layout result.
            page.Graphics.DrawString("Grand Total:", arialBoldFont, PdfBrushes.Black, bounds, format);
            //Draw the total amount value to PDF page based on the layout result.
            bounds = new RectangleF(TotalPriceCellBounds.X, y, TotalPriceCellBounds.Width, TotalPriceCellBounds.Height);
            page.Graphics.DrawString("$" + GetTotalAmount(grid).ToString(), arialBoldFont, PdfBrushes.Black, bounds);
            #endregion
            //Create border pen with custom dash style and draw the border to page.
            borderPen.DashStyle   = PdfDashStyle.Custom;
            borderPen.DashPattern = new float[] { 3, 3 };
            graphics.DrawLine(borderPen, new PointF(0, pageHeight - 100), new PointF(pageWidth, pageHeight - 100));

            //Get the image file stream from assembly.
            Stream imageStream = typeof(Invoice).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.AdventureWork.png");
            //Create PDF bitmap image from stream.
            PdfBitmap bitmap = new PdfBitmap(imageStream);
            //Draw the image to PDF page.
            graphics.DrawImage(bitmap, new RectangleF(10, pageHeight - 90, 80, 80));

            //Calculate the text position and draw the text to PDF page.
            y    = pageHeight - 100 + margin;
            size = arialRegularFont.MeasureString("800 Interchange Blvd.");
            x    = pageWidth - size.Width - margin;
            graphics.DrawString("800 Interchange Blvd.", arialRegularFont, PdfBrushes.Black, new PointF(x, y));

            //Calculate the text position and draw the text to PDF page.
            y   += arialRegularFont.Height + lineSpace;
            size = arialRegularFont.MeasureString("Suite 2501,  Austin, TX 78721");
            x    = pageWidth - size.Width - margin;
            graphics.DrawString("Suite 2501,  Austin, TX 78721", arialRegularFont, PdfBrushes.Black, new PointF(x, y));

            //Calculate the text position and draw the text to PDF page.
            y   += arialRegularFont.Height + lineSpace;
            size = arialRegularFont.MeasureString("Any Questions? [email protected]");
            x    = pageWidth - size.Width - margin;
            graphics.DrawString("Any Questions? [email protected]", arialRegularFont, PdfBrushes.Black, new PointF(x, y));

            //Creating the stream object
            using (MemoryStream stream = new MemoryStream())
            {
                //Save the document into stream
                document.Save(stream);
                document.Close();

                stream.Position = 0;
                //Save the output stream as a file using file picker.
                PdfUtil.Save("Invoice.pdf", stream);
            }
        }