Ejemplo n.º 1
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            //Create ZugFerd invoice PDF
            PdfDocument document = new PdfDocument(PdfConformanceLevel.Pdf_A3B);

            document.ZugferdVersion          = ZugferdVersion.ZugferdVersion2_0;
            document.ZugferdConformanceLevel = ZugferdConformanceLevel.Extended;

            CreateZugFerdInvoicePDF(document);

            //Create ZugFerd Xml attachment file
            Stream zugferdXmlStream = CreateZugFerdXML();

            //Creates an attachment.
            PdfAttachment attachment = new PdfAttachment("ZUGFeRD-invoice.xml", zugferdXmlStream);

            attachment.Relationship     = PdfAttachmentRelationship.Alternative;
            attachment.ModificationDate = DateTime.Now;

            attachment.Description = "Adventure Invoice";

            attachment.MimeType = "application/xml";

            document.Attachments.Add(attachment);
            MemoryStream ms = new MemoryStream();

            document.Save(ms);

            SaveFile(ms, "output.pdf");
        }
Ejemplo n.º 2
0
        public ActionResult ZugFerd(string Browser)
        {
            //Create ZugFerd invoice PDF
            PdfDocument document = new PdfDocument(PdfConformanceLevel.Pdf_A3B);

            document.ZugferdConformanceLevel = ZugferdConformanceLevel.Basic;

            CreateZugferdInvoicePDF(document);

            //Create ZugFerd Xml attachment file
            Stream zugferdXmlStream = CreateZugferdXML();

            //Creates an attachment.
            PdfAttachment attachment = new PdfAttachment("ZUGFeRD-invoice.xml", zugferdXmlStream);

            attachment.Relationship     = PdfAttachmentRelationship.Alternative;
            attachment.ModificationDate = DateTime.Now;

            attachment.Description = "Adventure Invoice";

            attachment.MimeType = "application/xml";

            document.Attachments.Add(attachment);


            //Stream the output to the browser.
            if (Browser == "Browser")
            {
                return(document.ExportAsActionResult("sample.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Open));
            }
            else
            {
                return(document.ExportAsActionResult("sample.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save));
            }
        }
Ejemplo n.º 3
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a new PDF document
            PdfDocument pdf = new PdfDocument();

            //Load the file from disk.
            pdf.LoadFromFile(@"..\..\..\..\..\..\Data\Template_Pdf_2.pdf");

            //Get a collection of attachments on the PDF document
            PdfAttachmentCollection collection = pdf.Attachments;

            //Get the first attachment.
            PdfAttachment attachment = collection[0];

            //Get the information of the first attachment.
            StringBuilder content = new StringBuilder();

            content.AppendLine("Filename: " + attachment.FileName);
            content.AppendLine("Description: " + attachment.Description);
            content.AppendLine("Creation Date: " + attachment.CreationDate);
            content.AppendLine("Modification Date: " + attachment.ModificationDate);


            String result = "GetPdfAttachmentInfo_out.txt";

            //Save to file.
            File.WriteAllText(result, content.ToString());

            //Launch the file.
            DocumentViewer(result);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// GoToE action
        /// </summary>
        /// <param name="pdf"></param>
        private static void EmbeddedGoToAction(PdfDocument pdf, PdfPageBase page)
        {
            //add a attachment
            PdfAttachment attachment = new PdfAttachment(@"..\..\..\..\..\..\Data\GoToAction.pdf");

            pdf.Attachments.Add(attachment);

            string          text   = "Test embedded go-to action! Click this will open the attached PDF in a new window.";
            PdfTrueTypeFont font   = new PdfTrueTypeFont(new Font("Arial", 13f));
            float           width  = 490f;
            float           height = font.Height * 2.2f;
            RectangleF      rect   = new RectangleF(0, 100, width, height);

            page.Canvas.DrawString(text, font, PdfBrushes.Black, rect);

            //create a PdfDestination with specific page, location and 200% zoom factor
            PdfDestination dest = new PdfDestination(1, new PointF(0, 842), 2f);

            //create GoToE action with dest
            PdfEmbeddedGoToAction action     = new PdfEmbeddedGoToAction(attachment.FileName, dest, true);
            PdfActionAnnotation   annotation = new PdfActionAnnotation(rect, action);

            //add the annotation
            (page as PdfNewPage).Annotations.Add(annotation);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Create a simple PDF document
        /// </summary>
        /// <returns>Return the created PDF document as stream</returns>
        public MemoryStream CreatePdfDocument()
        {
            PdfDocument document = new PdfDocument();

            //Creating new portfolio
            document.PortfolioInformation = new PdfPortfolioInformation();

            //setting the view mode of the portfolio
            document.PortfolioInformation.ViewMode = PdfPortfolioViewMode.Tile;



            //Read the file
            FileStream file = new FileStream(ResolveApplicationPath("CorporateBrochure.pdf"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            //Creating the attachment
            PdfAttachment pdfFile = new PdfAttachment("CorporateBrochure.pdf", file);

            pdfFile.FileName = "CorporateBrochure.pdf";

            file = new FileStream(ResolveApplicationPath("Stock.docx"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            //Creating the attachement
            PdfAttachment wordfile = new PdfAttachment("Stock.docx", file);

            wordfile.FileName = "Stock.docx";

            file = new FileStream(ResolveApplicationPath("Chart.xlsx"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            //Creating the attachement
            PdfAttachment excelfile = new PdfAttachment("Chart.xlsx", file);

            excelfile.FileName = "Chart.xlsx";

            //Setting the startup document to view
            document.PortfolioInformation.StartupDocument = pdfFile;

            //Adding the attachment into document
            document.Attachments.Add(pdfFile);
            document.Attachments.Add(wordfile);
            document.Attachments.Add(excelfile);

            //Adding new page into the document
            document.Pages.Add();

            //Save the PDF to the MemoryStream
            MemoryStream ms = new MemoryStream();

            document.Save(ms);

            //If the position is not set to '0' then the PDF will be empty.
            ms.Position = 0;

            //Close the PDF document.
            document.Close(true);

            return(ms);
        }
Ejemplo n.º 6
0
        public ActionResult Portfolio(string InsideBrowser)
        {
            //Stream readFile = new FileStream(ResolveApplicationDataPath(@"..\DocIO\DocToPDF.doc"), FileMode.Open, FileAccess.Read, FileShare.Read);
            // Create a new instance of PdfDocument class.
            PdfDocument document = new PdfDocument();

            //Creating new portfolio
            document.PortfolioInformation = new PdfPortfolioInformation();

            //setting the view mode of the portfolio
            document.PortfolioInformation.ViewMode = PdfPortfolioViewMode.Tile;

            //Creating the attachment
            PdfAttachment pdfFile = new PdfAttachment(ResolveApplicationDataPath("CorporateBrochure.pdf"));

            pdfFile.FileName = "CorporateBrochure.pdf";

            //Creating the attachement
            PdfAttachment wordfile = new PdfAttachment(ResolveApplicationDataPath("Stock.docx"));

            wordfile.FileName = "Stock.docx";

            //Creating the attachement
            PdfAttachment excelfile = new PdfAttachment(ResolveApplicationDataPath("Chart.xlsx"));

            excelfile.FileName = "Chart.xlsx";

            //Setting the startup document to view
            document.PortfolioInformation.StartupDocument = pdfFile;

            //Adding the attachment into document
            document.Attachments.Add(pdfFile);
            document.Attachments.Add(wordfile);
            document.Attachments.Add(excelfile);

            //Adding new page into the document
            document.Pages.Add();

            //Save the pdf file
            if (InsideBrowser == "Browser")
            {
                return(document.ExportAsActionResult("sample.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Open));
            }
            else
            {
                return(document.ExportAsActionResult("sample.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save));
            }
        }
Ejemplo n.º 7
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a new PDF document.
            PdfDocument pdf = new PdfDocument();

            //Load the file from disk.
            pdf.LoadFromFile(@"..\..\..\..\..\..\Data\Template_Pdf_2.pdf");

            //Get a collection of attachments on the PDF document.
            PdfAttachmentCollection collection = pdf.Attachments;

            //Get the second attachment in PDF file.
            PdfAttachment attachment = collection[1];

            //Save the second attachment to the file.
            File.WriteAllBytes(attachment.FileName, attachment.Data);
        }
Ejemplo n.º 8
0
        void OnButtonClicked(object sender, EventArgs e)
        {
            //Create ZugFerd invoice PDF
            PdfDocument document = new PdfDocument(PdfConformanceLevel.Pdf_A3B);

            document.ZugferdVersion          = ZugferdVersion.ZugferdVersion2_0;
            document.ZugferdConformanceLevel = ZugferdConformanceLevel.Extended;

            CreateZugFerdInvoicePDF(document);

            //Create ZugFerd Xml attachment file
            Stream zugferdXmlStream = CreateZugFerdXML();

            //Creates an attachment.
            PdfAttachment attachment = new PdfAttachment("ZUGFeRD-invoice.xml", zugferdXmlStream);

            attachment.Relationship     = PdfAttachmentRelationship.Alternative;
            attachment.ModificationDate = DateTime.Now;

            attachment.Description = "Adventure Invoice";

            attachment.MimeType = "application/xml";

            document.Attachments.Add(attachment);

            MemoryStream stream = new MemoryStream();

            //Save the PDF document.
            document.Save(stream);

            //Close the PDF document.
            document.Close();

            stream.Position = 0;

            if (Device.RuntimePlatform == Device.UWP)
            {
                Xamarin.Forms.DependencyService.Get <ISaveWindowsPhone>().Save("ZugFerd.pdf", "application/pdf", stream);
            }
            else
            {
                Xamarin.Forms.DependencyService.Get <ISave>().Save("ZugFerd.pdf", "application/pdf", stream);
            }
        }
Ejemplo n.º 9
0
        void OnButtonClicked(object sender, EventArgs e)
        {
            //Create ZugFerd invoice PDF
            PdfDocument document = new PdfDocument(PdfConformanceLevel.Pdf_A3B);

            document.ZugferdVersion          = ZugferdVersion.ZugferdVersion2_0;
            document.ZugferdConformanceLevel = ZugferdConformanceLevel.Extended;

            CreateZugFerdInvoicePDF(document);

            //Create ZugFerd Xml attachment file
            Stream zugferdXmlStream = CreateZugFerdXML();

            //Creates an attachment.
            PdfAttachment attachment = new PdfAttachment("ZUGFeRD-invoice.xml", zugferdXmlStream);

            attachment.Relationship     = PdfAttachmentRelationship.Alternative;
            attachment.ModificationDate = DateTime.Now;

            attachment.Description = "Adventure Invoice";

            attachment.MimeType = "application/xml";

            document.Attachments.Add(attachment);

            MemoryStream stream = new MemoryStream();

            //Save the PDF document.
            document.Save(stream);

            //Close the PDF document.
            document.Close();

            stream.Position = 0;

            if (stream != null)
            {
                SaveiOS iosSave = new SaveiOS();
                iosSave.Save("ZugFerd.pdf", "application/pdf", stream);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        //protected override void OnNavigatedTo(NavigationEventArgs e)
        //{
        //}

        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Stream pdf = typeof(Portfolio).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.Invoice.pdf");
            Stream doc = typeof(Portfolio).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.Stock.docx");
            Stream xls = typeof(Portfolio).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.Chart.xlsx");

            // Create a new instance of PdfDocument class.
            PdfDocument document = new PdfDocument();

            //Creating new portfolio
            document.PortfolioInformation = new PdfPortfolioInformation();

            //setting the view mode of the portfolio
            document.PortfolioInformation.ViewMode = PdfPortfolioViewMode.Tile;

            //Creating the attachment
            PdfAttachment pdfFile = new PdfAttachment("Invoice.pdf", pdf);

            //Creating the attachement
            PdfAttachment wordfile = new PdfAttachment("Stock.docx", doc);

            //Creating the attachement
            PdfAttachment excelFile = new PdfAttachment("Chart.xlsx", xls);

            //Setting the startup document to view
            document.PortfolioInformation.StartupDocument = wordfile;

            //Adding the attachment into document
            document.Attachments.Add(pdfFile);
            document.Attachments.Add(wordfile);
            document.Attachments.Add(excelFile);
            //Adding new page into the document
            document.Pages.Add();

            MemoryStream stream = new MemoryStream();
            await document.SaveAsync(stream);

            document.Close(true);
            Save(stream, "Portfolio.pdf");
        }
        public ActionResult Zugferd(string Browser)
        {
            //Create ZugFerd invoice PDF
            PdfDocument document = new PdfDocument(PdfConformanceLevel.Pdf_A3B);

            document.ZugferdVersion          = ZugferdVersion.ZugferdVersion2_0;
            document.ZugferdConformanceLevel = ZugferdConformanceLevel.Extended;

            CreateZugFerdInvoicePDF(document);

            //Create ZugFerd Xml attachment file
            Stream zugferdXmlStream = CreateZugFerdXML();

            //Creates an attachment.
            PdfAttachment attachment = new PdfAttachment("ZUGFeRD-invoice.xml", zugferdXmlStream);

            attachment.Relationship     = PdfAttachmentRelationship.Alternative;
            attachment.ModificationDate = DateTime.Now;

            attachment.Description = "Adventure Invoice";

            attachment.MimeType = "application/xml";

            document.Attachments.Add(attachment);

            MemoryStream stream = new MemoryStream();

            //Save the PDF document.
            document.Save(stream);

            //Close the PDF document.
            document.Close();

            stream.Position = 0;
            //Download the PDF document in the browser.
            FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf");

            fileStreamResult.FileDownloadName = "Zugferd.pdf";
            return(fileStreamResult);
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            // Create a new instance of PdfDocument class.
            PdfDocument document = new PdfDocument();

            //Creating new portfolio
            document.PortfolioInformation = new PdfPortfolioInformation();

            //setting the view mode of the portfolio
            document.PortfolioInformation.ViewMode = PdfPortfolioViewMode.Tile;

            //Creating the attachment
            PdfAttachment pdfFile = new PdfAttachment(ResolveApplicationDataPath("CorporateBrochure.pdf"));

            pdfFile.FileName = "CorporateBrochure.pdf";

            //Creating the attachement
            PdfAttachment wordfile = new PdfAttachment(ResolveApplicationDataPath("Stock.docx"));

            wordfile.FileName = "Stock.docx";

            //Creating the attachement
            PdfAttachment excelfile = new PdfAttachment(ResolveApplicationDataPath("Chart.xlsx"));

            excelfile.FileName = "Chart.xlsx";

            //Setting the startup document to view
            document.PortfolioInformation.StartupDocument = pdfFile;

            //Adding the attachment into document
            document.Attachments.Add(pdfFile);
            document.Attachments.Add(wordfile);
            document.Attachments.Add(excelfile);

            //Adding new page into the document
            document.Pages.Add();
            //save the document
            document.Save("Portfolio.pdf", HttpContext.Current.ApplicationInstance.Context.Response, HttpReadType.Save);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //Pdf file
            String input = @"..\..\..\..\..\..\Data\SampleB_2.pdf";

            //Open pdf document
            PdfDocument doc = new PdfDocument();

            doc.LoadFromFile(input);
            PdfNewDocument newDoc = new PdfNewDocument();

            //Set Pdf_A1B
            newDoc.Conformance = PdfConformanceLevel.Pdf_A1B;
            foreach (PdfPageBase page in doc.Pages)
            {
                SizeF       size = page.Size;
                PdfPageBase p    = newDoc.Pages.Add(size, new Spire.Pdf.Graphics.PdfMargins(0));
                page.CreateTemplate().Draw(p, 0, 0);
            }

            //Load files and add in attachments
            byte[]        data    = File.ReadAllBytes(@"..\..\..\..\..\..\Data\SampleB_1.png");
            PdfAttachment attach1 = new PdfAttachment("attachment1.png", data);

            byte[]        data2   = File.ReadAllBytes(@"..\..\..\..\..\..\Data\SampleB_1.pdf");
            PdfAttachment attach2 = new PdfAttachment("attachment2.pdf", data2);

            newDoc.Attachments.Add(attach1);
            newDoc.Attachments.Add(attach2);

            string output = "ToPDFAWithAttachments-result.pdf";

            newDoc.Save(output);
            newDoc.Close();

            //Launch the reuslt file
            PDFDocumentViewer(output);
        }
Ejemplo n.º 14
0
        void OnButtonClicked(object sender, EventArgs e)
        {
            //Create new PDF document.
            PdfDocument document = new PdfDocument();

            //Add page to the PDF document.
            PdfPage page = document.Pages.Add();

            PdfGraphics graphics = page.Graphics;

            //Create font object.
            PdfStandardFont font  = new PdfStandardFont(PdfFontFamily.TimesRoman, 14f, PdfFontStyle.Bold);
            PdfBrush        brush = PdfBrushes.Black;

            //Document security
            PdfSecurity security = document.Security;

            int algorithmindex = algorithmlist.IndexOf(algorithmfilterType);
            int keyindex;

            if (algorithmindex == 0)
            {
                keyindex           = AESkeylist.IndexOf(keysizefilterType);
                security.Algorithm = PdfEncryptionAlgorithm.AES;
                if (keyindex == 0)
                {
                    security.KeySize = PdfEncryptionKeySize.Key128Bit;
                }
                else if (keyindex == 1)
                {
                    security.KeySize = PdfEncryptionKeySize.Key256Bit;
                }
                else if (keyindex == 2)
                {
                    security.KeySize = PdfEncryptionKeySize.Key256BitRevision6;
                }
            }
            else
            {
                keyindex = RC4keylist.IndexOf(keysizefilterType);

                if (keyindex == 0)
                {
                    security.KeySize = PdfEncryptionKeySize.Key40Bit;
                }
                else if (keyindex == 1)
                {
                    security.KeySize = PdfEncryptionKeySize.Key128Bit;
                }
            }

            int optionIndex = options.IndexOf(optionType);

            if (optionIndex == 0)
            {
                security.EncryptionOptions = PdfEncryptionOptions.EncryptAllContents;
            }
            else if (optionIndex == 1)
            {
                security.EncryptionOptions = PdfEncryptionOptions.EncryptAllContentsExceptMetadata;
            }
            else if (optionIndex == 2)
            {
                //Read the file
                Stream file = typeof(DigitalSignatureValidation).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.Products.xml");

                //Creates an attachment
                PdfAttachment attachment = new PdfAttachment("Products.xml", file);

                attachment.ModificationDate = DateTime.Now;

                attachment.Description = "About Syncfusion";

                attachment.MimeType = "application/txt";

                //Adds the attachment to the document
                document.Attachments.Add(attachment);

                security.EncryptionOptions = PdfEncryptionOptions.EncryptOnlyAttachments;
            }


            security.Permissions   = PdfPermissionsFlags.Print | PdfPermissionsFlags.FullQualityPrint;
            security.UserPassword  = "******";
            security.OwnerPassword = "******";

            string text = "Security options:\n\n" + String.Format("KeySize: {0}\n\nEncryption Algorithm: {4}\n\nOwner Password: {1}\n\nPermissions: {2}\n\n" +
                                                                  "UserPassword: {3}", security.KeySize, security.OwnerPassword, security.Permissions, security.UserPassword, security.Algorithm);

            if (algorithmindex == 1)
            {
                if (keyindex == 2)
                {
                    text += String.Format("\n\nRevision: {0}", "Revision 6");
                }
                else if (keyindex == 1)
                {
                    text += String.Format("\n\nRevision: {0}", "Revision 5");
                }
            }
            // Draw String.
            graphics.DrawString("Document is Encrypted with following settings", font, brush, Syncfusion.Drawing.PointF.Empty);

            font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11f, PdfFontStyle.Bold);
            graphics.DrawString(text, font, brush, new Syncfusion.Drawing.PointF(0, 40));

            MemoryStream stream = new MemoryStream();

            //Save the PDF document.
            document.Save(stream);

            document.Close();

            if (stream != null)
            {
                stream.Position = 0;
                SaveiOS iosSave = new SaveiOS();
                iosSave.Save("Secure.pdf", "application/pdf", stream);
            }
        }
Ejemplo n.º 15
0
        private void button1_Click(object sender, System.EventArgs e)
        {
            PdfDocument document = new PdfDocument();
            PdfPage     page     = document.Pages.Add();
            PdfGraphics graphics = page.Graphics;

            PdfStandardFont font  = new PdfStandardFont(PdfFontFamily.TimesRoman, 20f, PdfFontStyle.Bold);
            PdfBrush        brush = PdfBrushes.Black;
            PdfForm         form  = document.Form;

            //Document security
            PdfSecurity security = document.Security;

            //Specify key size and encryption algorithm
            if (rdButton40Bit.Checked)
            {
                //use 40 bits key in RC4 mode
                security.KeySize = PdfEncryptionKeySize.Key40Bit;
            }
            else if (rdButton128Bit.Checked && rdButtonRC4.Checked)
            {
                //use 128 bits key in RC4 mode
                security.KeySize   = PdfEncryptionKeySize.Key128Bit;
                security.Algorithm = PdfEncryptionAlgorithm.RC4;
            }
            else if (rdButton128Bit.Checked && rdButtonAES.Checked)
            {
                //use 128 bits key in AES mode
                security.KeySize   = PdfEncryptionKeySize.Key128Bit;
                security.Algorithm = PdfEncryptionAlgorithm.AES;
            }
            else if (rdButton256Bit.Checked)
            {
                //use 256 bits key in AES mode
                security.KeySize   = PdfEncryptionKeySize.Key256Bit;
                security.Algorithm = PdfEncryptionAlgorithm.AES;
            }
            else if (rdButton256BitRevision6.Checked)
            {
                security.KeySize   = PdfEncryptionKeySize.Key256BitRevision6;
                security.Algorithm = PdfEncryptionAlgorithm.AES;
            }
            if (cmbEncrypt.SelectedIndex == 0 || !cmbEncrypt.Enabled)
            {
                security.EncryptionOptions = PdfEncryptionOptions.EncryptAllContents;
            }
            else if (cmbEncrypt.SelectedIndex == 1)
            {
                security.EncryptionOptions = PdfEncryptionOptions.EncryptAllContentsExceptMetadata;
            }
            else if (cmbEncrypt.SelectedIndex == 2)
            {
                security.EncryptionOptions = PdfEncryptionOptions.EncryptOnlyAttachments;
                //Read the file
                FileStream file = new FileStream(GetFullTemplatePath("Products.xml", false), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                //Creates an attachment
                PdfAttachment attachment = new PdfAttachment("Products.xml", file);

                attachment.ModificationDate = DateTime.Now;

                attachment.Description = "About Syncfusion";

                attachment.MimeType = "application/txt";

                //Adds the attachment to the document
                document.Attachments.Add(attachment);
            }

            security.OwnerPassword = "******";
            security.Permissions   = PdfPermissionsFlags.Print | PdfPermissionsFlags.FullQualityPrint;
            security.UserPassword  = "******";

            string text = "Security options:\n\n" + String.Format("KeySize: {0}\n\nEncryption Algorithm: {4}\n\nOwner Password: {1}\n\nPermissions: {2}\n\n" +
                                                                  "UserPassword: {3}", security.KeySize, security.OwnerPassword, security.Permissions, security.UserPassword, security.Algorithm);

            if (rdButton256BitRevision6.Checked)
            {
                text += String.Format("\n\nRevision: {0}", "Revision6");
            }
            else if (rdButton256Bit.Checked)
            {
                text += String.Format("\n\nRevision: {0}", "Revision5");
            }

            graphics.DrawString("Document is Encrypted with following settings", font, brush, PointF.Empty);
            font = new PdfStandardFont(PdfFontFamily.TimesRoman, 16f, PdfFontStyle.Bold);
            graphics.DrawString(text, font, brush, new PointF(0, 40));

            document.Save("Sample.pdf");

            //Message box confirmation to view the created PDF document.
            if (MessageBox.Show("Do you want to view the PDF file?", "PDF File Created",
                                MessageBoxButtons.YesNo, MessageBoxIcon.Information)
                == DialogResult.Yes)
            {
                //Launching the PDF file using the default Application.[Acrobat Reader]
#if NETCORE
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo = new System.Diagnostics.ProcessStartInfo("Sample.pdf")
                {
                    UseShellExecute = true
                };
                process.Start();
#else
                System.Diagnostics.Process.Start("Sample.pdf");
#endif
                this.Close();
            }
            else
            {
                // Exit
                this.Close();
            }
        }
        public ActionResult Portfolio(string InsideBrowser)
        {
            //Stream readFile = new FileStream(ResolveApplicationDataPath(@"..\DocIO\DocToPDF.doc"), FileMode.Open, FileAccess.Read, FileShare.Read);
            // Create a new instance of PdfDocument class.
            PdfDocument document = new PdfDocument();

            //Creating new portfolio
            document.PortfolioInformation = new PdfPortfolioInformation();

            //setting the view mode of the portfolio
            document.PortfolioInformation.ViewMode = PdfPortfolioViewMode.Tile;

            string basePath = _hostingEnvironment.WebRootPath;
            string dataPath = string.Empty;

            dataPath = basePath + @"/PDF/";

            //Read the file
            FileStream file = new FileStream(dataPath + "CorporateBrochure.pdf", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            //Creating the attachment
            PdfAttachment pdfFile = new PdfAttachment("CorporateBrochure.pdf", file);

            pdfFile.FileName = "CorporateBrochure.pdf";

            file = new FileStream(dataPath + "Stock.docx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            //Creating the attachement
            PdfAttachment wordfile = new PdfAttachment("Stock.docx", file);

            wordfile.FileName = "Stock.docx";

            file = new FileStream(dataPath + "Chart.xlsx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            //Creating the attachement
            PdfAttachment excelfile = new PdfAttachment("Chart.xlsx", file);

            excelfile.FileName = "Chart.xlsx";

            //Setting the startup document to view
            document.PortfolioInformation.StartupDocument = pdfFile;

            //Adding the attachment into document
            document.Attachments.Add(pdfFile);
            document.Attachments.Add(wordfile);
            document.Attachments.Add(excelfile);

            //Adding new page into the document
            document.Pages.Add();

            //Save the PDF to the MemoryStream
            MemoryStream ms = new MemoryStream();

            document.Save(ms);

            //If the position is not set to '0' then the PDF will be empty.
            ms.Position = 0;

            //Close the PDF document.
            document.Close(true);

            //Download the PDF document in the browser.
            FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf");

            fileStreamResult.FileDownloadName = "Portfolio.pdf";
            return(fileStreamResult);
        }
Ejemplo n.º 17
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 section
            PdfSection section = doc.Sections.Add();
            section.PageSettings.Size = PdfPageSize.A4;
            section.PageSettings.Margins = margin;

            // Create one page
            PdfPageBase page = section.Pages.Add();

            float y = 10;

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

            //attachment
            PdfAttachment attachment = new PdfAttachment("Header.png");
            attachment.Data = File.ReadAllBytes(@"..\..\..\..\..\..\Data\Header.png");
            attachment.Description = "Page header picture of demo.";
            attachment.MimeType = "image/png";
            doc.Attachments.Add(attachment);

            attachment = new PdfAttachment("Footer.png");
            attachment.Data = File.ReadAllBytes(@"..\..\..\..\..\..\Data\Footer.png");
            attachment.Description = "Page footer picture of demo.";
            attachment.MimeType = "image/png";
            doc.Attachments.Add(attachment);

            PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 12f, FontStyle.Bold));
            PointF location = new PointF(0, y);
            String label = "Sales Report Chart";
            byte[] data = File.ReadAllBytes(@"..\..\..\..\..\..\Data\SalesReportChart.png");
            SizeF size = font2.MeasureString(label);
            RectangleF bounds = new RectangleF(location, size);
            page.Canvas.DrawString(label, font2, PdfBrushes.DarkOrange, bounds);
            bounds = new RectangleF(bounds.Right + 3, bounds.Top, font2.Height / 2, font2.Height);
            PdfAttachmentAnnotation annotation1
                = new PdfAttachmentAnnotation(bounds, "SalesReportChart.png", data);
            annotation1.Color = Color.Teal;
            annotation1.Flags = PdfAnnotationFlags.ReadOnly;
            annotation1.Icon = PdfAttachmentIcon.Graph;
            annotation1.Text = "Sales Report Chart";
            (page as PdfNewPage).Annotations.Add(annotation1);
            y = y + size.Height + 2;

            location = new PointF(0, y);
            label = "Science Personification Boston";
            data = File.ReadAllBytes(@"..\..\..\..\..\..\Data\SciencePersonificationBoston.jpg");
            size = font2.MeasureString(label);
            bounds = new RectangleF(location, size);
            page.Canvas.DrawString(label, font2, PdfBrushes.DarkOrange, bounds);
            bounds = new RectangleF(bounds.Right + 3, bounds.Top, font2.Height / 2, font2.Height);
            PdfAttachmentAnnotation annotation2
                = new PdfAttachmentAnnotation(bounds, "SciencePersonificationBoston.jpg", data);
            annotation2.Color = Color.Orange;
            annotation2.Flags = PdfAnnotationFlags.NoZoom;
            annotation2.Icon = PdfAttachmentIcon.PushPin;
            annotation2.Text = "SciencePersonificationBoston.jpg, from Wikipedia, the free encyclopedia";
            (page as PdfNewPage).Annotations.Add(annotation2);
            y = y + size.Height + 2;

            location = new PointF(0, y);
            label = "Picture of Science";
            data = File.ReadAllBytes(@"..\..\..\..\..\..\Data\Wikipedia_Science.png");
            size = font2.MeasureString(label);
            bounds = new RectangleF(location, size);
            page.Canvas.DrawString(label, font2, PdfBrushes.DarkOrange, bounds);
            bounds = new RectangleF(bounds.Right + 3, bounds.Top, font2.Height / 2, font2.Height);
            PdfAttachmentAnnotation annotation3
                = new PdfAttachmentAnnotation(bounds, "Wikipedia_Science.png", data);
            annotation3.Color = Color.SaddleBrown;
            annotation3.Flags = PdfAnnotationFlags.Locked;
            annotation3.Icon = PdfAttachmentIcon.Tag;
            annotation3.Text = "Wikipedia_Science.png, from Wikipedia, the free encyclopedia";
            (page as PdfNewPage).Annotations.Add(annotation3);
            y = y + size.Height + 2;

            location = new PointF(0, y);
            label = "Hawaii Killer Font";
            data = File.ReadAllBytes(@"..\..\..\..\..\..\Data\Hawaii_Killer.ttf");
            size = font2.MeasureString(label);
            bounds = new RectangleF(location, size);
            page.Canvas.DrawString(label, font2, PdfBrushes.DarkOrange, bounds);
            bounds = new RectangleF(bounds.Right + 3, bounds.Top, font2.Height / 2, font2.Height);
            PdfAttachmentAnnotation annotation4
                = new PdfAttachmentAnnotation(bounds, "Hawaii_Killer.ttf", data);
            annotation4.Color = Color.CadetBlue;
            annotation4.Flags = PdfAnnotationFlags.NoRotate;
            annotation4.Icon = PdfAttachmentIcon.Paperclip;
            annotation4.Text = "Hawaii Killer Font, from http://www.1001freefonts.com";
            (page as PdfNewPage).Annotations.Add(annotation4);
            y = y + size.Height + 2;

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

            //Launching the Pdf file.
            PDFDocumentViewer("Attachment.pdf");
        }
Ejemplo n.º 18
0
        public void OnButtonClicked(object sender, EventArgs e)
        {
            //Create new PDF document.
            PdfDocument document = new PdfDocument();

            //Add page to the PDF document.
            PdfPage page = document.Pages.Add();

            PdfGraphics graphics = page.Graphics;

            //Create font object.
            PdfStandardFont font  = new PdfStandardFont(PdfFontFamily.TimesRoman, 14f, PdfFontStyle.Bold);
            PdfBrush        brush = PdfBrushes.Black;
            PdfForm         form  = document.Form;

            //Document security
            PdfSecurity security = document.Security;

            if (this.Algorithms.Items[this.Algorithms.SelectedIndex] == "AES")
            {
                security.Algorithm = PdfEncryptionAlgorithm.AES;
                if (this.keysize.SelectedIndex == 0)
                {
                    security.KeySize = PdfEncryptionKeySize.Key128Bit;
                }
                else if (this.keysize.SelectedIndex == 1)
                {
                    security.KeySize = PdfEncryptionKeySize.Key256Bit;
                }
                else if (this.keysize.SelectedIndex == 2)
                {
                    security.KeySize = PdfEncryptionKeySize.Key256BitRevision6;
                }
            }
            else if (this.Algorithms.Items[this.Algorithms.SelectedIndex] == "RC4")
            {
                security.Algorithm = PdfEncryptionAlgorithm.RC4;
                if (this.keysize.SelectedIndex == 0)
                {
                    security.KeySize = PdfEncryptionKeySize.Key40Bit;
                }
                else if (this.keysize.SelectedIndex == 1)
                {
                    security.KeySize = PdfEncryptionKeySize.Key128Bit;
                }
            }

            if (this.Options.Items[this.Options.SelectedIndex] == "Encrypt all contents")
            {
                security.EncryptionOptions = PdfEncryptionOptions.EncryptAllContents;
            }
            else if (this.Options.Items[this.Options.SelectedIndex] == "Encrypt all contents except metadata")
            {
                security.EncryptionOptions = PdfEncryptionOptions.EncryptAllContentsExceptMetadata;
            }
            else if (this.Options.Items[this.Options.SelectedIndex] == "Encrypt only attachments")
            {
                //Read the file
#if COMMONSB
                Stream file = typeof(Encryption).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.Products.xml");
#else
                Stream file = typeof(Encryption).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.Products.xml");
#endif

                //Creates an attachment
                PdfAttachment attachment = new PdfAttachment("Products.xml", file);

                attachment.ModificationDate = DateTime.Now;

                attachment.Description = "About Syncfusion";

                attachment.MimeType = "application/txt";

                //Adds the attachment to the document
                document.Attachments.Add(attachment);

                security.EncryptionOptions = PdfEncryptionOptions.EncryptOnlyAttachments;
            }

            security.OwnerPassword = "******";
            security.Permissions   = PdfPermissionsFlags.Print | PdfPermissionsFlags.FullQualityPrint;
            security.UserPassword  = "******";

            string text = "Security options:\n\n" + String.Format("KeySize: {0}\n\nEncryption Algorithm: {4}\n\nOwner Password: {1}\n\nPermissions: {2}\n\n" +
                                                                  "UserPassword: {3}", security.KeySize, security.OwnerPassword, security.Permissions, security.UserPassword, security.Algorithm);
            if (this.Algorithms.SelectedIndex == 1)
            {
                if (this.keysize.SelectedIndex == 2)
                {
                    text += String.Format("\n\nRevision: {0}", "Revision 6");
                }
                else if (this.keysize.SelectedIndex == 1)
                {
                    text += String.Format("\n\nRevision: {0}", "Revision 5");
                }
            }

            graphics.DrawString("Document is Encrypted with following settings", font, brush, PointF.Empty);
            font = new PdfStandardFont(PdfFontFamily.TimesRoman, 11f, PdfFontStyle.Bold);
            graphics.DrawString(text, font, brush, new PointF(0, 40));

            MemoryStream stream = new MemoryStream();
            //Save the PDF document.
            document.Save(stream);

            if (Device.RuntimePlatform == Device.UWP)
            {
                Xamarin.Forms.DependencyService.Get <ISaveWindowsPhone>().Save("Secured.pdf", "application/pdf", stream);
            }
            else
            {
                Xamarin.Forms.DependencyService.Get <ISave>().Save("Secured.pdf", "application/pdf", stream);
            }
        }
Ejemplo n.º 19
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);
            }
        }
Ejemplo n.º 20
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();
            }
        }
Ejemplo n.º 21
0
        public ActionResult Attachments(string Browser)
        {
            //Creates a new PDF document.
            PdfDocument doc = new PdfDocument();

            //Add a page
            PdfPage page = doc.Pages.Add();

            //Set the font
            PdfStandardFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 18f, PdfFontStyle.Bold);

            //Create new PDF color
            PdfColor orangeColor = new PdfColor(255, 255, 167, 73);

            //Draw the text
            page.Graphics.DrawString("Attachments", font, PdfBrushes.Black, new RectangleF(0, 0, page.GetClientSize().Width, page.GetClientSize().Height), new PdfStringFormat(PdfTextAlignment.Center));

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

            page.Graphics.DrawString("This PDF document contains image and text file as attachment.", font, PdfBrushes.Black, new PointF(0, 30));

            font = new PdfStandardFont(PdfFontFamily.Helvetica, 8f, PdfFontStyle.Regular);

            page.Graphics.DrawString("Click to open the attachment:", font, PdfBrushes.Black, new PointF(0, 50));

            page.Graphics.DrawString("Click to open the attachment:", font, PdfBrushes.Black, new PointF(0, 70));

            string basePath = _hostingEnvironment.WebRootPath;
            string dataPath = string.Empty;

            dataPath = basePath + @"/PDF/";

            //Read the file
            FileStream file = new FileStream(dataPath + "Text1.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            //Creates an attachment
            PdfAttachment attachment = new PdfAttachment("Text1.txt", file);

            attachment.ModificationDate = DateTime.Now;

            attachment.Description = "About Syncfusion";

            attachment.MimeType = "application/txt";

            //Adds the attachment to the document
            doc.Attachments.Add(attachment);

            file = new FileStream(dataPath + "Autumn Leaves.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            //Creates an attachment
            attachment = new PdfAttachment("Autumn Leaves.jpg", file);

            attachment.ModificationDate = DateTime.Now;

            attachment.Description = "Autumn Leaves Image";

            attachment.MimeType = "application/jpg";

            doc.Attachments.Add(attachment);

            file = new FileStream(dataPath + "Text2.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            //Creates an attachment
            attachment = new PdfAttachment("Text2.txt", file);

            attachment.ModificationDate = DateTime.Now;

            attachment.Description = "List of Syncfusion Control";

            attachment.MimeType = "application/txt";

            doc.Attachments.Add(attachment);

            //Set document viewerpreference.
            doc.ViewerPreferences.HideWindowUI = false;
            doc.ViewerPreferences.HideMenubar  = false;
            doc.ViewerPreferences.HideToolbar  = false;
            doc.ViewerPreferences.FitWindow    = false;
            doc.ViewerPreferences.DisplayTitle = false;
            doc.ViewerPreferences.PageMode     = PdfPageMode.UseAttachments;

            //Disable the default appearance.
            doc.Form.SetDefaultAppearance(false);

            //Create pdfbuttonfield.
            PdfButtonField openSpecificationButton = new PdfButtonField(page, "openSpecification");

            openSpecificationButton.Bounds          = new RectangleF(105, 50, 62, 10);
            openSpecificationButton.TextAlignment   = PdfTextAlignment.Left;
            openSpecificationButton.Font            = new PdfStandardFont(PdfFontFamily.Helvetica, 7);
            openSpecificationButton.BorderStyle     = PdfBorderStyle.Underline;
            openSpecificationButton.BorderColor     = orangeColor;
            openSpecificationButton.BackColor       = new PdfColor(255, 255, 255);
            openSpecificationButton.ForeColor       = orangeColor;
            openSpecificationButton.Text            = "Autumn Leaves.jpg";
            openSpecificationButton.Actions.MouseUp = new PdfJavaScriptAction("this.exportDataObject({ cName: 'Autumn Leaves.jpg', nLaunch: 2 });");
            doc.Form.Fields.Add(openSpecificationButton);

            openSpecificationButton                 = new PdfButtonField(page, "openSpecification");
            openSpecificationButton.Bounds          = new RectangleF(105, 70, 30, 10);
            openSpecificationButton.TextAlignment   = PdfTextAlignment.Left;
            openSpecificationButton.Font            = new PdfStandardFont(PdfFontFamily.Helvetica, 7);
            openSpecificationButton.BorderStyle     = PdfBorderStyle.Underline;
            openSpecificationButton.BorderColor     = orangeColor;
            openSpecificationButton.BackColor       = new PdfColor(255, 255, 255);
            openSpecificationButton.ForeColor       = orangeColor;
            openSpecificationButton.Text            = "Text1.txt";
            openSpecificationButton.Actions.MouseUp = new PdfJavaScriptAction("this.exportDataObject({ cName: 'Text1.txt', nLaunch: 2 });");
            doc.Form.Fields.Add(openSpecificationButton);

            //Save the PDF to the MemoryStream
            MemoryStream ms = new MemoryStream();

            doc.Save(ms);

            //If the position is not set to '0' then the PDF will be empty.
            ms.Position = 0;

            //Close the PDF document.
            doc.Close(true);

            //Download the PDF document in the browser.
            FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf");

            fileStreamResult.FileDownloadName = "Attachments.pdf";
            return(fileStreamResult);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        //protected override void OnNavigatedTo(NavigationEventArgs e)
        //{
        //}

        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            PdfDocument document = new PdfDocument();

            PdfPageBase page     = document.Pages.Add();
            PdfGraphics graphics = page.Graphics;

            PdfStandardFont font  = new PdfStandardFont(PdfFontFamily.TimesRoman, 20f, PdfFontStyle.Bold);
            PdfBrush        brush = PdfBrushes.Black;
            PdfForm         form  = document.Form;

            //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;
            }
            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 the file
                Stream imgStream = typeof(Encryption).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.Products.xml");

                PdfAttachment attachment = new PdfAttachment("Products.xml", imgStream);

                attachment.ModificationDate = DateTime.Now;

                attachment.Description = "About Syncfusion";

                attachment.MimeType = "application/txt";

                //Adds the attachment to the document
                document.Attachments.Add(attachment);

                security.EncryptionOptions = PdfEncryptionOptions.EncryptOnlyAttachments;
            }
            security.OwnerPassword = txtOwnerPassword.Password;
            security.Permissions   = PdfPermissionsFlags.Print | PdfPermissionsFlags.FullQualityPrint;
            security.UserPassword  = txtUserPassword.Password;

            string text = "Security options:\n\n" + String.Format("KeySize: {0}\n\nEncryption Algorithm: {4}\n\nOwner Password: {1}\n\nPermissions: {2}\n\n" +
                                                                  "UserPassword: {3}", security.KeySize, security.OwnerPassword, security.Permissions, security.UserPassword, security.Algorithm);

            if (encryptionTechnique.SelectionBoxItem.ToString() == "256-Bit AES Revision 6")
            {
                text += String.Format("\n\nRevision: {0}", "Revision6");
            }
            else if (encryptionTechnique.SelectionBoxItem.ToString() == "256-Bit AES")
            {
                text += String.Format("\n\nRevision: {0}", "Revision5");
            }

            graphics.DrawString("Document is Encrypted with following settings", font, brush, PointF.Empty);
            font = new PdfStandardFont(PdfFontFamily.TimesRoman, 16f, PdfFontStyle.Bold);
            graphics.DrawString(text, font, brush, new PointF(0, 40));

            MemoryStream stream = new MemoryStream();
            await document.SaveAsync(stream);

            document.Close(true);
            Save(stream, "FormFilling.pdf");
        }
        public ActionResult PdfConformance(string Browser, string conformance)
        {
            PdfDocument doc = null;

            if (conformance == "PDF/A-1a")
            {
                //Create a new document with PDF/A standard.
                doc = new PdfDocument(PdfConformanceLevel.Pdf_A1A);
            }
            else if (conformance == "PDF/A-1b")
            {
                doc = new PdfDocument(PdfConformanceLevel.Pdf_A1B);
            }
            else if (conformance == "PDF/A-2a")
            {
                doc = new PdfDocument(PdfConformanceLevel.Pdf_A2A);
            }
            else if (conformance == "PDF/A-2b")
            {
                doc = new PdfDocument(PdfConformanceLevel.Pdf_A2B);
            }
            else if (conformance == "PDF/A-2u")
            {
                doc = new PdfDocument(PdfConformanceLevel.Pdf_A2U);
            }
            else if (conformance == "PDF/X-1a 2001")
            {
                doc = new PdfDocument(PdfConformanceLevel.Pdf_X1A2001);
            }
            else
            {
                if (conformance == "PDF/A-3a")
                {
                    doc = new PdfDocument(PdfConformanceLevel.Pdf_A3A);
                }
                else if (conformance == "PDF/A-3b")
                {
                    doc = new PdfDocument(PdfConformanceLevel.Pdf_A3B);
                }
                else if (conformance == "PDF/A-3u")
                {
                    doc = new PdfDocument(PdfConformanceLevel.Pdf_A3U);
                }
                PdfAttachment attachment = new PdfAttachment(ResolveApplicationDataPath("PDF_A.rtf"));
                attachment.Relationship     = PdfAttachmentRelationship.Alternative;
                attachment.ModificationDate = DateTime.Now;

                attachment.Description = "PDF_A";

                attachment.MimeType = "application/xml";

                doc.Attachments.Add(attachment);
            }

            //Add a page
            PdfPage page = doc.Pages.Add();

            //Create Pdf graphics for the page
            PdfGraphics graphics = page.Graphics;
            //Load the image from the disk.
            PdfImage img = PdfImage.FromFile(ResolveApplicationImagePath("AdventureCycle.jpg"));

            //Draw the image in the specified location and size.
            graphics.DrawImage(img, new RectangleF(150, 30, 200, 100));

            //Create font.
            PdfFont font = new PdfTrueTypeFont(new Font("Arial", 14), true);

            PdfTextElement textElement = new PdfTextElement("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 Bothell, Washington with 290 employees, several regional" +
                                                            " sales teams are located throughout their market base.")
            {
                Font = font
            };
            PdfLayoutResult layoutResult = textElement.Draw(page, new RectangleF(0, 150, page.GetClientSize().Width, page.GetClientSize().Height));


            //Stream the output to the browser.
            if (Browser == "Browser")
            {
                return(doc.ExportAsActionResult("sample.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Open));
            }
            else
            {
                return(doc.ExportAsActionResult("sample.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save));
            }
        }
Ejemplo n.º 24
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document
            PdfDocument doc = new PdfDocument();

            doc.LoadFromFile(@"..\..\..\..\..\..\Data\Attachment.pdf");

            PdfPageBase page = doc.Pages[0];

            float y = 320;

            //Title
            PdfBrush        brush1  = PdfBrushes.CornflowerBlue;
            PdfTrueTypeFont font1   = new PdfTrueTypeFont(new Font("Arial", 18f, FontStyle.Bold));
            PdfStringFormat format1 = new PdfStringFormat(PdfTextAlignment.Center);

            page.Canvas.DrawString("Attachment", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1);
            y = y + font1.MeasureString("Attachment", format1).Height;
            y = y + 10;

            //Add an attachment
            PdfAttachment attachment = new PdfAttachment("Header.png");

            attachment.Data        = File.ReadAllBytes(@"..\..\..\..\..\..\Data\Header.png");
            attachment.Description = "Page header picture of demo.";
            attachment.MimeType    = "image/png";
            doc.Attachments.Add(attachment);

            //Add an attachment
            attachment             = new PdfAttachment("Footer.png");
            attachment.Data        = File.ReadAllBytes(@"..\..\..\..\..\..\Data\Footer.png");
            attachment.Description = "Page footer picture of demo.";
            attachment.MimeType    = "image/png";
            doc.Attachments.Add(attachment);
            float           x        = 50;
            PdfTrueTypeFont font2    = new PdfTrueTypeFont(new Font("Arial", 14f, FontStyle.Bold));
            PointF          location = new PointF(x, y);
            String          label    = "Sales Report Chart";

            byte[]     data   = File.ReadAllBytes(@"..\..\..\..\..\..\Data\SalesReportChart.png");
            SizeF      size   = font2.MeasureString(label);
            RectangleF bounds = new RectangleF(location, size);

            page.Canvas.DrawString(label, font2, PdfBrushes.DarkOrange, bounds);
            bounds = new RectangleF(bounds.Right + 3, bounds.Top, font2.Height / 2, font2.Height);

            //Create a PdfAttachmentAnnotation
            PdfAttachmentAnnotation annotation1
                = new PdfAttachmentAnnotation(bounds, "SalesReportChart.png", data);

            annotation1.Color = Color.Teal;
            annotation1.Flags = PdfAnnotationFlags.ReadOnly;
            annotation1.Icon  = PdfAttachmentIcon.Graph;
            annotation1.Text  = "Sales Report Chart";
            //Add the annotation1
            page.AnnotationsWidget.Add(annotation1);
            y = y + size.Height + 3;

            location = new PointF(x, y);
            label    = "Science Personification Boston";
            data     = File.ReadAllBytes(@"..\..\..\..\..\..\Data\SciencePersonificationBoston.jpg");
            size     = font2.MeasureString(label);
            bounds   = new RectangleF(location, size);
            page.Canvas.DrawString(label, font2, PdfBrushes.DarkOrange, bounds);

            bounds = new RectangleF(bounds.Right + 3, bounds.Top, font2.Height / 2, font2.Height);


            PdfAttachmentAnnotation annotation2
                = new PdfAttachmentAnnotation(bounds, "SciencePersonificationBoston.jpg", data);

            annotation2.Color = Color.Orange;
            annotation2.Flags = PdfAnnotationFlags.NoZoom;
            annotation2.Icon  = PdfAttachmentIcon.PushPin;
            annotation2.Text  = "SciencePersonificationBoston.jpg, from Wikipedia, the free encyclopedia";
            page.AnnotationsWidget.Add(annotation2);
            y = y + size.Height + 2;

            location = new PointF(x, y);
            label    = "Picture of Science";
            data     = File.ReadAllBytes(@"..\..\..\..\..\..\Data\Wikipedia_Science.png");
            size     = font2.MeasureString(label);
            bounds   = new RectangleF(location, size);
            page.Canvas.DrawString(label, font2, PdfBrushes.DarkOrange, bounds);
            bounds = new RectangleF(bounds.Right + 3, bounds.Top, font2.Height / 2, font2.Height);
            PdfAttachmentAnnotation annotation3
                = new PdfAttachmentAnnotation(bounds, "Wikipedia_Science.png", data);

            annotation3.Color = Color.SaddleBrown;
            annotation3.Flags = PdfAnnotationFlags.Locked;
            annotation3.Icon  = PdfAttachmentIcon.Tag;
            annotation3.Text  = "Wikipedia_Science.png, from Wikipedia, the free encyclopedia";
            page.AnnotationsWidget.Add(annotation3);
            y = y + size.Height + 2;

            location = new PointF(x, y);
            label    = "Hawaii Killer Font";
            data     = File.ReadAllBytes(@"..\..\..\..\..\..\Data\Hawaii_Killer.ttf");
            size     = font2.MeasureString(label);
            bounds   = new RectangleF(location, size);
            page.Canvas.DrawString(label, font2, PdfBrushes.DarkOrange, bounds);
            bounds = new RectangleF(bounds.Right + 3, bounds.Top, font2.Height / 2, font2.Height);
            PdfAttachmentAnnotation annotation4
                = new PdfAttachmentAnnotation(bounds, "Hawaii_Killer.ttf", data);

            annotation4.Color = Color.CadetBlue;
            annotation4.Flags = PdfAnnotationFlags.NoRotate;
            annotation4.Icon  = PdfAttachmentIcon.Paperclip;
            annotation4.Text  = "Hawaii Killer Font, from http://www.1001freefonts.com";
            page.AnnotationsWidget.Add(annotation4);
            y = y + size.Height + 2;

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

            //Launch the Pdf file
            PDFDocumentViewer("Attachment.pdf");
        }
Ejemplo n.º 25
0
        private async void listpreview_ItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            var Orderproduct = listpreview.SelectedItem as OrderItem;

            //  await Navigation.PushAsync(new NavigationPage(new RecieptPage(products,saleproducts,  paymentname)) );
            #region Fields
            //Create border color
            PdfColor borderColor     = new PdfColor(Syncfusion.Drawing.Color.FromArgb(255, 51, 181, 75));
            PdfBrush lightGreenBrush = new PdfSolidBrush(new PdfColor(Syncfusion.Drawing.Color.FromArgb(255, 218, 218, 221)));

            PdfBrush darkGreenBrush = new PdfSolidBrush(new PdfColor(Syncfusion.Drawing.Color.FromArgb(255, 51, 181, 75)));

            PdfBrush whiteBrush = new PdfSolidBrush(new PdfColor(Syncfusion.Drawing.Color.FromArgb(255, 255, 255, 255)));
            PdfPen   borderPen  = new PdfPen(borderColor, 1f);
            Stream   fontStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("IttezanPos.Assets.arial.ttf");
            //Create TrueType font
            PdfTrueTypeFont headerFont       = new PdfTrueTypeFont(fontStream, 9, PdfFontStyle.Bold);
            PdfTrueTypeFont arialRegularFont = new PdfTrueTypeFont(fontStream, 9, PdfFontStyle.Regular);
            PdfTrueTypeFont arialBoldFont    = new PdfTrueTypeFont(fontStream, 11, PdfFontStyle.Bold);


            const float margin       = 30;
            const float lineSpace    = 7;
            const float headerHeight = 90;
            #endregion

            #region header and buyer infomation
            //Create PDF with PDF/A-3b conformance
            PdfDocument document = new PdfDocument(PdfConformanceLevel.Pdf_A3B);
            //Set ZUGFeRD profile
            document.ZugferdConformanceLevel = ZugferdConformanceLevel.Basic;

            //Add page to the PDF
            PdfPage page = document.Pages.Add();

            PdfGraphics graphics = page.Graphics;

            //Get the page width and height
            float pageWidth  = page.GetClientSize().Width;
            float pageHeight = page.GetClientSize().Height;
            //Draw page border
            graphics.DrawRectangle(borderPen, new RectangleF(0, 0, pageWidth, pageHeight));

            //Fill the header with light Brush
            graphics.DrawRectangle(lightGreenBrush, new RectangleF(0, 0, pageWidth, headerHeight));

            RectangleF headerAmountBounds = new RectangleF(400, 0, pageWidth - 400, headerHeight);

            graphics.DrawString("INVOICE", headerFont, whiteBrush, new PointF(margin, headerAmountBounds.Height / 3));
            Stream imageStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("IttezanPos.Assets.ic_launcher.png");

            //Create a new PdfBitmap instance
            PdfBitmap image = new PdfBitmap(imageStream);

            //Draw the image
            graphics.DrawImage(image, new PointF(margin + 90, headerAmountBounds.Height / 2));
            graphics.DrawRectangle(darkGreenBrush, headerAmountBounds);

            graphics.DrawString("Amount", arialRegularFont, whiteBrush, headerAmountBounds,
                                new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));
            graphics.DrawString("$" + Orderproduct.amount_paid.ToString(), arialBoldFont, whiteBrush,
                                new RectangleF(400, lineSpace, pageWidth - 400, headerHeight + 15), new
                                PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));



            PdfTextElement textElement = new PdfTextElement("Invoice Number: " + Orderproduct.id.ToString(), arialRegularFont);

            PdfLayoutResult layoutResult = textElement.Draw(page, new PointF(headerAmountBounds.X - margin, 120));

            textElement.Text = "Date : " + DateTime.Now.ToString("dddd dd, MMMM yyyy");
            textElement.Draw(page, new PointF(layoutResult.Bounds.X, layoutResult.Bounds.Bottom + lineSpace));
            var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDb.db");
            var db     = new SQLiteConnection(dbpath);
            if (Orderproduct.client_id != null)
            {
                var client = (db.Table <Client>().ToList().Where(clien => clien.id == int.Parse(Orderproduct.client_id)).FirstOrDefault());
                textElement.Text = "Bill To:";
                layoutResult     = textElement.Draw(page, new PointF(margin, 120));

                textElement.Text = client.enname;
                layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
                textElement.Text = client.address;
                layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
                textElement.Text = client.email;
                layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
                textElement.Text = client.phone;
                layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
            }

            #endregion

            #region Invoice data
            PdfGrid        grid            = new PdfGrid();
            DataTable      dataTable       = new DataTable("EmpDetails");
            List <Product> customerDetails = new List <Product>();
            //Add columns to the DataTable
            dataTable.Columns.Add("ID");
            dataTable.Columns.Add("Name");
            dataTable.Columns.Add("Price");
            dataTable.Columns.Add("Qty");
            dataTable.Columns.Add("Disc");
            dataTable.Columns.Add("Total");

            //Add rows to the DataTable.
            foreach (var item in Orderproduct.products)
            {
                Product customer = new Product();
                customer.id          = Orderproduct.products.IndexOf(item) + 1;
                customer.Enname      = item.Enname;
                customer.sale_price  = item.sale_price;
                customer.quantity    = item.quantity;
                customer.discount    = item.discount;
                customer.total_price = item.total_price;
                customerDetails.Add(customer);
                dataTable.Rows.Add(new string[] { customer.id.ToString(), customer.Enname, customer.sale_price.ToString(),
                                                  customer.quantity.ToString(), customer.discount.ToString(), customer.total_price.ToString() });
            }

            //Assign data source.
            grid.DataSource = dataTable;


            grid.Columns[1].Width      = 150;
            grid.Style.Font            = arialRegularFont;
            grid.Style.CellPadding.All = 5;

            grid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable1Light);

            layoutResult = grid.Draw(page, new PointF(0, layoutResult.Bounds.Bottom + 40));

            textElement.Text = "Grand Total: ";
            textElement.Font = arialBoldFont;
            layoutResult     = textElement.Draw(page, new PointF(headerAmountBounds.X - 40, layoutResult.Bounds.Bottom +
                                                                 lineSpace));

            float totalAmount = float.Parse(Orderproduct.total_price);
            textElement.Text = "$" + totalAmount.ToString();
            layoutResult     = textElement.Draw(page, new PointF(layoutResult.Bounds.Right + 4, layoutResult.Bounds.Y));

            //graphics.DrawString("$" + totalAmount.ToString(), arialBoldFont, whiteBrush,
            //    new RectangleF(400, lineSpace, pageWidth - 400, headerHeight + 15), new
            //    PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));
            textElement.Text = "Total Discount: ";
            textElement.Font = arialBoldFont;
            layoutResult     = textElement.Draw(page, new PointF(headerAmountBounds.X - 40, layoutResult.Bounds.Bottom +
                                                                 lineSpace));

            float totalDisc = float.Parse(Orderproduct.discount);
            textElement.Text = "$" + totalDisc.ToString();
            layoutResult     = textElement.Draw(page, new PointF(layoutResult.Bounds.Right + 4, layoutResult.Bounds.Y));

            //graphics.DrawString("$" + totalDisc.ToString(), arialBoldFont, whiteBrush,
            //    new RectangleF(400, lineSpace, pageWidth - 400, headerHeight + 15), new
            //    PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));


            #endregion

            #region Seller information
            borderPen.DashStyle   = PdfDashStyle.Custom;
            borderPen.DashPattern = new float[] { 3, 3 };

            PdfLine line = new PdfLine(borderPen, new PointF(0, 0), new PointF(pageWidth, 0));
            layoutResult = line.Draw(page, new PointF(0, pageHeight - 100));

            textElement.Text = "IttezanPos";
            textElement.Font = arialRegularFont;
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + (lineSpace * 3)));
            textElement.Text = "Buradah,  AlQassim, Saudi Arabia";
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));
            textElement.Text = "Any Questions? ittezan.com";
            layoutResult     = textElement.Draw(page, new PointF(margin, layoutResult.Bounds.Bottom + lineSpace));

            #endregion

            //#region Create ZUGFeRD XML

            ////Create //ZUGFeRD Invoice
            //ZugferdInvoice invoice = new ZugferdInvoice("2058557939", DateTime.Now, CurrencyCodes.USD);

            ////Set ZUGFeRD profile to basic
            //invoice.Profile = ZugferdProfile.Basic;

            ////Add buyer details
            //invoice.Buyer = new UserDetails
            //{
            //    ID = "Abraham_12",
            //    Name = "Abraham Swearegin",
            //    ContactName = "Swearegin",
            //    City = "United States, California",
            //    Postcode = "9920",
            //    Country = CountryCodes.US,
            //    Street = "9920 BridgePointe Parkway"
            //};

            ////Add seller details
            //invoice.Seller = new UserDetails
            //{
            //    ID = "Adventure_123",
            //    Name = "AdventureWorks",
            //    ContactName = "Adventure support",
            //    City = "Austin,TX",
            //    Postcode = "78721",
            //    Country = CountryCodes.US,
            //    Street = "800 Interchange Blvd"
            //};


            //IEnumerable<Product> products = saleproducts;

            //foreach (Product product in products)
            //    invoice.AddProduct(product);


            //invoice.TotalAmount = totalAmount;

            //MemoryStream zugferdXML = new MemoryStream();
            //invoice.Save(zugferdXML);
            //#endregion

            #region Embed ZUGFeRD XML to PDF

            //Attach ZUGFeRD XML to PDF
            //PdfAttachment attachment = new PdfAttachment("ZUGFeRD-invoice.xml", zugferdXML);
            //attachment.Relationship = PdfAttachmentRelationship.Alternative;
            //attachment.ModificationDate = DateTime.Now;
            //attachment.Description = "ZUGFeRD-invoice";
            //attachment.MimeType = "application/xml";
            //document.Attachments.Add(attachment);
            #endregion
            //Creates an attachment
            MemoryStream stream = new MemoryStream();
            //    Stream invoiceStream = typeof(MainPage).GetTypeInfo().Assembly.GetManifestResourceStream("Sample.Assets.Data.ZUGFeRD-invoice.xml");

            PdfAttachment attachment = new PdfAttachment("ZUGFeRD-invoice.xml", stream);

            attachment.Relationship = PdfAttachmentRelationship.Alternative;

            attachment.ModificationDate = DateTime.Now;

            attachment.Description = "ZUGFeRD-invoice";

            attachment.MimeType = "application/xml";

            document.Attachments.Add(attachment);

            //Save the document into memory stream



            document.Save(stream);

            //Close the document

            document.Close(true);

            await Xamarin.Forms.DependencyService.Get <ISave>().SaveAndView("تقرير العملاء.pdf", "application/pdf", stream);
        }
        public ActionResult Conformance(string InsideBrowser, string conformance)
        {
            string basePath = _hostingEnvironment.WebRootPath;
            string dataPath = string.Empty;

            dataPath = basePath + @"/PDF/";

            PdfDocument document = null;

            if (conformance == "PDF/A-1a")
            {
                //Create a new document with PDF/A standard.
                document = new PdfDocument(PdfConformanceLevel.Pdf_A1A);
            }
            else if (conformance == "PDF/A-1b")
            {
                //Create a new document with PDF/A standard.
                document = new PdfDocument(PdfConformanceLevel.Pdf_A1B);
            }
            else if (conformance == "PDF/A-2a")
            {
                //Create a new document with PDF/A standard.
                document = new PdfDocument(PdfConformanceLevel.Pdf_A2A);
            }
            else if (conformance == "PDF/A-2b")
            {
                //Create a new document with PDF/A standard.
                document = new PdfDocument(PdfConformanceLevel.Pdf_A2B);
            }
            else if (conformance == "PDF/A-2u")
            {
                //Create a new document with PDF/A standard.
                document = new PdfDocument(PdfConformanceLevel.Pdf_A2U);
            }
            else
            {
                if (conformance == "PDF/A-3a")
                {
                    document = new PdfDocument(PdfConformanceLevel.Pdf_A3A);
                }
                else if (conformance == "PDF/A-3b")
                {
                    document = new PdfDocument(PdfConformanceLevel.Pdf_A3B);
                }
                else if (conformance == "PDF/A-3u")
                {
                    document = new PdfDocument(PdfConformanceLevel.Pdf_A3U);
                }
                //Read the file
                FileStream file = new FileStream(dataPath + "Text1.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                //Creates an attachment
                PdfAttachment attachment = new PdfAttachment("Text1.txt", file);

                attachment.Relationship     = PdfAttachmentRelationship.Alternative;
                attachment.ModificationDate = DateTime.Now;

                attachment.Description = "PDF_A";

                attachment.MimeType = "application/xml";

                document.Attachments.Add(attachment);
            }


            //Add a page to the document.
            PdfPage page = document.Pages.Add();
            //Create PDF graphics for the page.
            PdfGraphics graphics = page.Graphics;

            FileStream imageStream = new FileStream(dataPath + "AdventureCycle.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            //Load the image from the disk.
            PdfImage img = PdfImage.FromStream(imageStream);

            //Draw the image in the specified location and size.
            graphics.DrawImage(img, new RectangleF(150, 30, 200, 100));


            //Create font
            FileStream fontFileStream = new FileStream(dataPath + "arial.ttf", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            PdfFont    font           = new PdfTrueTypeFont(fontFileStream, 14);


            PdfTextElement textElement = new PdfTextElement("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 Bothell, Washington with 290 employees, several regional" +
                                                            " sales teams are located throughout their market base.")
            {
                Font = font
            };
            PdfLayoutResult layoutResult = textElement.Draw(page, new RectangleF(0, 150, page.GetClientSize().Width, page.GetClientSize().Height));

            MemoryStream stream = new MemoryStream();

            document.Save(stream);
            document.Close();
            stream.Position = 0;
            //Download the PDF document in the browser.
            FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf");

            fileStreamResult.FileDownloadName = "PDF_A.pdf";
            return(fileStreamResult);
        }
Ejemplo n.º 27
0
        public ActionResult Attachments(string Browser)
        {
            //Creates a new PDF document.
            doc = new PdfDocument();

            //Add a page
            PdfPage page = doc.Pages.Add();

            //Set the font
            font = new PdfStandardFont(PdfFontFamily.Helvetica, 18f, PdfFontStyle.Bold);

            System.Drawing.Color orangeColor = System.Drawing.Color.FromArgb(255, 255, 167, 73);

            //Draw the text
            page.Graphics.DrawString("Attachments", font, PdfBrushes.Black, new RectangleF(0, 0, page.GetClientSize().Width, page.GetClientSize().Height), new PdfStringFormat(PdfTextAlignment.Center));

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

            page.Graphics.DrawString("This PDF document contains image and text file as attachment.", font, PdfBrushes.Black, new PointF(0, 30));

            font = new PdfStandardFont(PdfFontFamily.Helvetica, 8f, PdfFontStyle.Regular);

            page.Graphics.DrawString("Click to open the attachment:", font, PdfBrushes.Black, new PointF(0, 50));

            page.Graphics.DrawString("Click to open the attachment:", font, PdfBrushes.Black, new PointF(0, 70));

            //Creates an attachment
            PdfAttachment attachment = new PdfAttachment(ResolveApplicationDataPath("Text1.txt"));

            attachment.ModificationDate = DateTime.Now;

            attachment.Description = "About Syncfusion";

            attachment.MimeType = "application/txt";

            //Adds the attachment to the document
            doc.Attachments.Add(attachment);

            //Creates an attachment
            attachment = new PdfAttachment(ResolveApplicationImagePath("Autumn Leaves.jpg"));

            attachment.ModificationDate = DateTime.Now;

            attachment.Description = "Autumn Leaves Image";

            attachment.MimeType = "application/jpg";

            doc.Attachments.Add(attachment);

            //Creates an attachment
            attachment = new PdfAttachment(ResolveApplicationDataPath("Text2.txt"));

            attachment.ModificationDate = DateTime.Now;

            attachment.Description = "List of Syncfusion Control";

            attachment.MimeType = "application/txt";

            doc.Attachments.Add(attachment);

            //Set document viewerpreference.
            doc.ViewerPreferences.HideWindowUI = false;
            doc.ViewerPreferences.HideMenubar  = false;
            doc.ViewerPreferences.HideToolbar  = false;
            doc.ViewerPreferences.FitWindow    = false;
            doc.ViewerPreferences.DisplayTitle = false;
            doc.ViewerPreferences.PageMode     = PdfPageMode.UseAttachments;

            //Disable the default appearance.
            doc.Form.SetDefaultAppearance(false);

            //Create pdfbuttonfield.
            PdfButtonField openSpecificationButton = new PdfButtonField(page, "openSpecification");

            openSpecificationButton.Bounds          = new RectangleF(105, 50, 62, 10);
            openSpecificationButton.TextAlignment   = PdfTextAlignment.Left;
            openSpecificationButton.Font            = new PdfStandardFont(PdfFontFamily.Helvetica, 7);
            openSpecificationButton.BorderStyle     = PdfBorderStyle.Underline;
            openSpecificationButton.BorderColor     = orangeColor;
            openSpecificationButton.BackColor       = new PdfColor(255, 255, 255);
            openSpecificationButton.ForeColor       = orangeColor;
            openSpecificationButton.Text            = "Autumn Leaves.jpg";
            openSpecificationButton.Actions.MouseUp = new PdfJavaScriptAction("this.exportDataObject({ cName: 'Autumn Leaves.jpg', nLaunch: 2 });");
            doc.Form.Fields.Add(openSpecificationButton);

            openSpecificationButton                 = new PdfButtonField(page, "openSpecification");
            openSpecificationButton.Bounds          = new RectangleF(105, 70, 30, 10);
            openSpecificationButton.TextAlignment   = PdfTextAlignment.Left;
            openSpecificationButton.Font            = new PdfStandardFont(PdfFontFamily.Helvetica, 7);
            openSpecificationButton.BorderStyle     = PdfBorderStyle.Underline;
            openSpecificationButton.BorderColor     = orangeColor;
            openSpecificationButton.BackColor       = new PdfColor(255, 255, 255);
            openSpecificationButton.ForeColor       = orangeColor;
            openSpecificationButton.Text            = "Text1.txt";
            openSpecificationButton.Actions.MouseUp = new PdfJavaScriptAction("this.exportDataObject({ cName: 'Text1.txt', nLaunch: 2 });");
            doc.Form.Fields.Add(openSpecificationButton);

            //Stream the output to the browser.
            if (Browser == "Browser")
            {
                return(doc.ExportAsActionResult("sample.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Open));
            }
            else
            {
                return(doc.ExportAsActionResult("sample.pdf", HttpContext.ApplicationInstance.Response, HttpReadType.Save));
            }
        }
Ejemplo n.º 28
0
        private async void GeneratePDF_Click(object sender, RoutedEventArgs e)
        {
            PdfDocument document = null;

            if (this.PdfConformance.SelectionBoxItem.ToString() == "PDF/A-1a")
            {
                // Create a new instance of PdfDocument class with PDF/A standard.
                document = new PdfDocument(PdfConformanceLevel.Pdf_A1A);
            }
            else if (this.PdfConformance.SelectionBoxItem.ToString() == "PDF/A-1b")
            {
                document = new PdfDocument(PdfConformanceLevel.Pdf_A1B);
            }
            else if (this.PdfConformance.SelectionBoxItem.ToString() == "PDF/A-2a")
            {
                document = new PdfDocument(PdfConformanceLevel.Pdf_A2A);
            }
            else if (this.PdfConformance.SelectionBoxItem.ToString() == "PDF/A-2b")
            {
                document = new PdfDocument(PdfConformanceLevel.Pdf_A2B);
            }
            else if (this.PdfConformance.SelectionBoxItem.ToString() == "PDF/A-2u")
            {
                document = new PdfDocument(PdfConformanceLevel.Pdf_A2U);
            }
            else
            {
                if (this.PdfConformance.SelectionBoxItem.ToString() == "PDF/A-3a")
                {
                    document = new PdfDocument(PdfConformanceLevel.Pdf_A3A);
                }
                else if (this.PdfConformance.SelectionBoxItem.ToString() == "PDF/A-3b")
                {
                    document = new PdfDocument(PdfConformanceLevel.Pdf_A3B);
                }
                else if (this.PdfConformance.SelectionBoxItem.ToString() == "PDF/A-3u")
                {
                    document = new PdfDocument(PdfConformanceLevel.Pdf_A3U);
                }
                Stream imgStream = typeof(Conformance).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.Products.xml");

                PdfAttachment attachment = new PdfAttachment("Products.xml", imgStream);
                attachment.Relationship     = PdfAttachmentRelationship.Alternative;
                attachment.ModificationDate = DateTime.Now;

                attachment.Description = "PDF_A";

                attachment.MimeType = "application/xml";

                document.Attachments.Add(attachment);
            }
            //Add a page to the document.
            PdfPage page = document.Pages.Add();

            //Create Pdf graphics for the page
            PdfGraphics g = page.Graphics;

            Stream jpegImage = typeof(Conformance).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.AdventureCycle.jpg");

            //Drawing a jpeg image
            PdfImage image = new PdfBitmap(jpegImage);

            g.DrawImage(image, new RectangleF(150, 30, 200, 100));

            //Text to draw in PDF
            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 Bothell, Washington with 290 employees, several regional" +
                          " sales teams are located throughout their market base";

            ////Set the formats for the text
            //PdfStringFormat format = new PdfStringFormat();
            //format.Alignment = PdfTextAlignment.Justify;
            //format.LineAlignment = PdfVerticalAlignment.Top;
            //format.ParagraphIndent = 35f;

            //Create a text element
            PdfTextElement element = new PdfTextElement(text);

            element.Brush = PdfBrushes.Black;
            // element.StringFormat = format;
            //Set the font
            Stream fontStream = typeof(Conformance).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.arial.ttf");

            element.Font = new PdfTrueTypeFont(fontStream, 14);

            //Set the properties to paginate the text.
            PdfLayoutFormat layoutFormat = new PdfLayoutFormat();

            layoutFormat.Break  = PdfLayoutBreakType.FitPage;
            layoutFormat.Layout = PdfLayoutType.Paginate;

            RectangleF bounds = new RectangleF(0, 150, page.GetClientSize().Width, page.GetClientSize().Height);

            //Draw the text element with the properties and formats set.
            element.Draw(page, bounds, layoutFormat);
            //Save and close the document.
            MemoryStream stream = new MemoryStream();
            await document.SaveAsync(stream);

            document.Close(true);
            Save(stream, "Sample.pdf");
        }
        void OnButtonClicked(object sender, EventArgs e)
        {
            PdfDocument document = null;

            if (this.comformance.Items[this.comformance.SelectedIndex] == "PDF/A-1a")
            {
                //Create a new PDF document
                document = new PdfDocument(PdfConformanceLevel.Pdf_A1A);
            }
            else if (this.comformance.Items[this.comformance.SelectedIndex] == "PDF/A-1b")
            {
                document = new PdfDocument(PdfConformanceLevel.Pdf_A1B);
            }
            else if (this.comformance.Items[this.comformance.SelectedIndex] == "PDF/A-2a")
            {
                document = new PdfDocument(PdfConformanceLevel.Pdf_A2A);
            }
            else if (this.comformance.Items[this.comformance.SelectedIndex] == "PDF/A-2b")
            {
                document = new PdfDocument(PdfConformanceLevel.Pdf_A2B);
            }
            else if (this.comformance.Items[this.comformance.SelectedIndex] == "PDF/A-2u")
            {
                document = new PdfDocument(PdfConformanceLevel.Pdf_A2U);
            }
            else
            {
                if (this.comformance.Items[this.comformance.SelectedIndex] == "PDF/A-3a")
                {
                    document = new PdfDocument(PdfConformanceLevel.Pdf_A3A);
                }
                else if (this.comformance.Items[this.comformance.SelectedIndex] == "PDF/A-3b")
                {
                    document = new PdfDocument(PdfConformanceLevel.Pdf_A3B);
                }
                else if (this.comformance.Items[this.comformance.SelectedIndex] == "PDF/A-3u")
                {
                    document = new PdfDocument(PdfConformanceLevel.Pdf_A3U);
                }
#if COMMONSB
                Stream imgStream = typeof(Conformance).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.Products.xml");
#else
                Stream imgStream = typeof(Conformance).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.Products.xml");
#endif

                PdfAttachment attachment = new PdfAttachment("PDF_A.xml", imgStream);
                attachment.Relationship     = PdfAttachmentRelationship.Alternative;
                attachment.ModificationDate = DateTime.Now;

                attachment.Description = "PDF_A";

                attachment.MimeType = "application/xml";

                document.Attachments.Add(attachment);
            }
            //Add a page
            PdfPage page = document.Pages.Add();

            //Create font
#if COMMONSB
            Stream arialFontStream = typeof(Conformance).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.arial.ttf");
            Stream imageStream     = typeof(Conformance).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Samples.Assets.AdventureCycle.jpg");
#else
            Stream arialFontStream = typeof(Conformance).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.arial.ttf");
            Stream imageStream     = typeof(Conformance).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.PDF.Samples.Assets.AdventureCycle.jpg");
#endif
            PdfFont font = new PdfTrueTypeFont(arialFontStream, 14);

            //Create PDF graphics for the page.
            PdfGraphics graphics = page.Graphics;
            //Load the image from the disk.
            PdfImage img = PdfImage.FromStream(imageStream);
            //Draw the image in the specified location and size.
            graphics.DrawImage(img, new RectangleF(150, 30, 200, 100));


            PdfTextElement textElement = new PdfTextElement("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 Bothell, Washington with 290 employees, several regional" +
                                                            " sales teams are located throughout their market base.")
            {
                Font = font
            };
            PdfLayoutResult layoutResult = textElement.Draw(page, new RectangleF(0, 150, page.GetClientSize().Width, page.GetClientSize().Height));


            MemoryStream stream = new MemoryStream();
            //Save the PDF document.
            document.Save(stream);

            //Close the PDF document.
            document.Close();

            stream.Position = 0;

            if (Device.RuntimePlatform == Device.UWP)
            {
                Xamarin.Forms.DependencyService.Get <ISaveWindowsPhone>().Save("PDF_A.pdf", "application/pdf", stream);
            }
            else
            {
                Xamarin.Forms.DependencyService.Get <ISave>().Save("PDF_A.pdf", "application/pdf", stream);
            }
        }
Ejemplo n.º 30
0
        public ActionResult InteractiveFeatures(string InsideBrowser)
        {
            #region Field Definitions
            document = new PdfDocument();
            document.PageSettings.Margins.All = 0;
            document.PageSettings.Size        = new SizeF(PdfPageSize.A4.Width, 600);
            interactivePage = document.Pages.Add();
            PdfGraphics g    = interactivePage.Graphics;
            RectangleF  rect = new RectangleF(0, 0, interactivePage.Graphics.ClientSize.Width, 100);

            PdfBrush whiteBrush  = new PdfSolidBrush(white);
            PdfPen   whitePen    = new PdfPen(white, 5);
            PdfBrush purpleBrush = new PdfSolidBrush(new PdfColor(255, 158, 0, 160));
            PdfFont  font        = new PdfStandardFont(PdfFontFamily.Helvetica, 25);
            Syncfusion.Drawing.Color maroonColor = Color.FromArgb(255, 188, 32, 60);
            Syncfusion.Drawing.Color orangeColor = Color.FromArgb(255, 255, 167, 73);
            #endregion

            #region Header
            g.DrawRectangle(purpleBrush, rect);
            g.DrawPie(whitePen, whiteBrush, new RectangleF(-20, 35, 700, 200), 20, -180);
            g.DrawRectangle(whiteBrush, new RectangleF(0, 99.5f, 700, 200));
            g.DrawString("Invoice", new PdfStandardFont(PdfFontFamily.TimesRoman, 24), PdfBrushes.White, new PointF(500, 10));

            string basePath = _hostingEnvironment.WebRootPath;
            string dataPath = string.Empty;
            dataPath = basePath + @"/PDF/";

            //Read the file
            FileStream file = new FileStream(dataPath + "AdventureCycle.jpg", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            g.DrawImage(PdfImage.FromStream(file), new RectangleF(100, 70, 390, 130));
            #endregion

            #region Body

            //Invoice Number
            Random invoiceNumber = new Random();
            g.DrawString("Invoice No: " + invoiceNumber.Next().ToString(), new PdfStandardFont(PdfFontFamily.Helvetica, 14), new PdfSolidBrush(maroonColor), new PointF(50, 210));
            g.DrawString("Date: ", new PdfStandardFont(PdfFontFamily.Helvetica, 14), new PdfSolidBrush(maroonColor), new PointF(350, 210));

            //Current Date
            PdfTextBoxField textBoxField = new PdfTextBoxField(interactivePage, "date");
            textBoxField.Font          = new PdfStandardFont(PdfFontFamily.Helvetica, 12);
            textBoxField.Bounds        = new RectangleF(384, 204, 150, 30);
            textBoxField.ForeColor     = new PdfColor(maroonColor);
            textBoxField.ReadOnly      = true;
            document.Actions.AfterOpen = new PdfJavaScriptAction(@"var newdate = new Date(); 
            var thisfieldis = this.getField('date');  
            
            var theday = util.printd('dddd',newdate); 
            var thedate = util.printd('d',newdate); 
            var themonth = util.printd('mmmm',newdate);
            var theyear = util.printd('yyyy',newdate);  
            
            thisfieldis.strokeColor=color.transparent;
            thisfieldis.value = theday + ' ' + thedate + ', ' + themonth + ' ' + theyear ;");
            document.Form.Fields.Add(textBoxField);

            //invoice table
            PdfLightTable table = new PdfLightTable();
            table.Style.ShowHeader = true;
            g.DrawRectangle(new PdfSolidBrush(Syncfusion.Drawing.Color.FromArgb(238, 238, 238, 248)), new RectangleF(50, 240, 500, 140));

            //Header Style
            PdfCellStyle headerStyle = new PdfCellStyle();
            headerStyle.Font            = new PdfStandardFont(PdfFontFamily.Helvetica, 12, PdfFontStyle.Bold);
            headerStyle.TextBrush       = whiteBrush;
            headerStyle.StringFormat    = new PdfStringFormat(PdfTextAlignment.Center);
            headerStyle.BackgroundBrush = new PdfSolidBrush(orangeColor);
            headerStyle.BorderPen       = new PdfPen(whiteBrush, 0);
            table.Style.HeaderStyle     = headerStyle;

            //Cell Style
            PdfCellStyle bodyStyle = new PdfCellStyle();
            bodyStyle.Font           = new PdfStandardFont(PdfFontFamily.Helvetica, 10);
            bodyStyle.StringFormat   = new PdfStringFormat(PdfTextAlignment.Left);
            bodyStyle.BorderPen      = new PdfPen(whiteBrush, 0);
            table.Style.DefaultStyle = bodyStyle;
            table.DataSource         = GetProductReport(_hostingEnvironment.WebRootPath);
            table.Columns[0].Width   = 90;
            table.Columns[1].Width   = 160;
            table.Columns[3].Width   = 100;
            table.Columns[4].Width   = 65;
            table.Style.CellPadding  = 3;
            table.BeginCellLayout   += table_BeginCellLayout;

            PdfLightTableLayoutResult result = table.Draw(interactivePage, new RectangleF(50, 240, 500, 140));

            g.DrawString("Grand Total:", new PdfStandardFont(PdfFontFamily.Helvetica, 12), new PdfSolidBrush(Syncfusion.Drawing.Color.FromArgb(255, 255, 167, 73)), new PointF(result.Bounds.Right - 150, result.Bounds.Bottom));
            CreateTextBox(interactivePage, "GrandTotal", "Grand Total", new RectangleF(result.Bounds.Width - 15, result.Bounds.Bottom - 2, 66, 18), true, "");


            //Send to Server
            PdfButtonField sendButton = new PdfButtonField(interactivePage, "OrderOnline");
            sendButton.Bounds      = new RectangleF(200, result.Bounds.Bottom + 70, 80, 25);
            sendButton.BorderColor = white;
            sendButton.BackColor   = maroonColor;
            sendButton.ForeColor   = white;
            sendButton.Text        = "Order Online";
            PdfSubmitAction submitAction = new PdfSubmitAction("http://stevex.net/dump.php");
            submitAction.DataFormat    = SubmitDataFormat.Html;
            sendButton.Actions.MouseUp = submitAction;
            document.Form.Fields.Add(sendButton);

            //Order by Mail
            PdfButtonField sendMail = new PdfButtonField(interactivePage, "sendMail");
            sendMail.Bounds      = new RectangleF(300, result.Bounds.Bottom + 70, 80, 25);
            sendMail.Text        = "Order By Mail";
            sendMail.BorderColor = white;
            sendMail.BackColor   = maroonColor;
            sendMail.ForeColor   = white;

            // Create a javascript action.
            PdfJavaScriptAction javaAction = new PdfJavaScriptAction("address = app.response(\"Enter an e-mail address.\",\"SEND E-MAIL\",\"\");"
                                                                     + "var aSubmitFields = [];"
                                                                     + "for( var i = 0 ; i < this.numFields; i++){"
                                                                     + "aSubmitFields[i] = this.getNthFieldName(i);"
                                                                     + "}"
                                                                     + "if (address){ cmdLine = \"mailto:\" + address;this.submitForm(cmdLine,true,false,aSubmitFields);}");

            sendMail.Actions.MouseUp = javaAction;
            document.Form.Fields.Add(sendMail);

            //Print
            PdfButtonField printButton = new PdfButtonField(interactivePage, "print");
            printButton.Bounds          = new RectangleF(400, result.Bounds.Bottom + 70, 80, 25);
            printButton.BorderColor     = white;
            printButton.BackColor       = maroonColor;
            printButton.ForeColor       = white;
            printButton.Text            = "Print";
            printButton.Actions.MouseUp = new PdfJavaScriptAction("this.print (true); ");
            document.Form.Fields.Add(printButton);
            file = new FileStream(dataPath + "Product Catalog.pdf", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            PdfAttachment attachment = new PdfAttachment("Product Catalog.pdf", file);
            attachment.ModificationDate = DateTime.Now;
            attachment.Description      = "Specification";
            document.Attachments.Add(attachment);

            //Open Specification
            PdfButtonField openSpecificationButton = new PdfButtonField(interactivePage, "openSpecification");
            openSpecificationButton.Bounds          = new RectangleF(50, result.Bounds.Bottom + 20, 87, 15);
            openSpecificationButton.TextAlignment   = PdfTextAlignment.Left;
            openSpecificationButton.Font            = new PdfStandardFont(PdfFontFamily.Helvetica, 10);
            openSpecificationButton.BorderStyle     = PdfBorderStyle.Underline;
            openSpecificationButton.BorderColor     = orangeColor;
            openSpecificationButton.BackColor       = new PdfColor(255, 255, 255);
            openSpecificationButton.ForeColor       = orangeColor;
            openSpecificationButton.Text            = "Open Specification";
            openSpecificationButton.Actions.MouseUp = new PdfJavaScriptAction("this.exportDataObject({ cName: 'Product Catalog.pdf', nLaunch: 2 });");
            document.Form.Fields.Add(openSpecificationButton);

            RectangleF     uriAnnotationRectangle = new RectangleF(interactivePage.Graphics.ClientSize.Width - 160, interactivePage.Graphics.ClientSize.Height - 30, 80, 20);
            PdfTextWebLink linkAnnot = new PdfTextWebLink();
            linkAnnot.Url   = "http://www.adventure-works.com";
            linkAnnot.Text  = "http://www.adventure-works.com";
            linkAnnot.Font  = new PdfStandardFont(PdfFontFamily.Helvetica, 8);
            linkAnnot.Brush = PdfBrushes.White;
            linkAnnot.DrawTextWebLink(interactivePage, uriAnnotationRectangle.Location);
            #endregion

            #region Footer
            g.DrawRectangle(purpleBrush, new RectangleF(0, interactivePage.Graphics.ClientSize.Height - 100, interactivePage.Graphics.ClientSize.Width, 100));
            g.DrawPie(whitePen, whiteBrush, new RectangleF(-20, interactivePage.Graphics.ClientSize.Height - 250, 700, 200), 0, 180);
            #endregion

            //Save the PDF to the MemoryStream
            MemoryStream ms = new MemoryStream();

            document.Save(ms);

            //If the position is not set to '0' then the PDF will be empty.
            ms.Position = 0;

            //Close the PDF document.
            document.Close(true);

            //Download the PDF document in the browser.
            FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf");
            fileStreamResult.FileDownloadName = "Interactive features.pdf";
            return(fileStreamResult);
        }
Ejemplo n.º 31
0
        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==";

            // 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();

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

                return(fileResult);
            }
            finally
            {
                document.Close();
                fileStream1.Close();
            }
        }