Ejemplo n.º 1
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

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

            //Draw the page
            DrawPage(page);

            //set document info
            doc.DocumentInformation.Author = "Harry Hu";
            doc.DocumentInformation.Creator = "Harry Hu";
            doc.DocumentInformation.Keywords = "pdf, demo, document information";
            doc.DocumentInformation.Producer = "Spire.Pdf";
            doc.DocumentInformation.Subject = "Demo of Spire.Pdf";
            doc.DocumentInformation.Title = "Document Information";

            //file info
            doc.FileInfo.CrossReferenceType = PdfCrossReferenceType.CrossReferenceStream;
            doc.FileInfo.IncrementalUpdate = false;
            doc.FileInfo.Version = PdfVersion.Version1_5;

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

            //Launching the Pdf file.
            PDFDocumentViewer("Properties.pdf");
        }
Ejemplo n.º 2
0
        private static void EncryptPdfWithPassword(string sourceFile, string passwordSource, string destinationFile, string passwordUser, string passwordOwner)
        {
            byte[] userPassword  = Encoding.ASCII.GetBytes(passwordUser);
            byte[] ownerPassword = Encoding.ASCII.GetBytes(passwordOwner);

            PdfReader reader = null;

            if (!string.IsNullOrEmpty(passwordSource))
            {
                byte[]           sourcePassword   = Encoding.ASCII.GetBytes(passwordSource);
                ReaderProperties readerProperties = new ReaderProperties().SetPassword(sourcePassword);
                reader = new PdfReader(sourceFile, readerProperties);
            }
            else
            {
                reader = new PdfReader(sourceFile);
            }

            WriterProperties props = new WriterProperties()
                                     .SetStandardEncryption(userPassword, ownerPassword, EncryptionConstants.ALLOW_PRINTING,
                                                            EncryptionConstants.ENCRYPTION_AES_256 | EncryptionConstants.DO_NOT_ENCRYPT_METADATA);

            using PdfWriter writer = new PdfWriter(destinationFile, props);
            PdfDocument pdfDoc = null;

            try
            {
                pdfDoc = new PdfDocument(reader, writer);
            }
            finally
            {
                pdfDoc?.Close();
            }
        }
Ejemplo n.º 3
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

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

            // Create one page
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin);
            Image img = Image.FromFile(@"..\..\..\..\..\..\Data\Background.png");
            page.BackgroundImage = img;

            //Draw table
            DrawPage(page);

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

            //Launching the Pdf file.
            PDFDocumentViewer("ImageWaterMark.pdf");
        }
Ejemplo n.º 4
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();            

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

            //Draw the text
            page.Canvas.DrawString("Hello, World!",
                                   new PdfFont(PdfFontFamily.Helvetica, 30f),
                                   new PdfSolidBrush(Color.Black),
                                   10, 10);
            //Draw the image
            PdfImage image = PdfImage.FromFile(@"..\..\..\..\..\..\Data\SalesReportChart.png");
            float width = image.Width * 0.75f;
            float height = image.Height * 0.75f;
            float x = (page.Canvas.ClientSize.Width - width) / 2;

            page.Canvas.DrawImage(image, x, 60, width, height);

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

            //Launching the Pdf file.
            PDFDocumentViewer("Image.pdf");
        }
Ejemplo n.º 5
0
        public PdfDocument CreateRekenPyramide(string filename)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

            // Create one page
            PdfPageBase page = doc.Pages.Add();
            int basislengte = 8;
            int maxbasisgetal = 14;

            Random rnd = new Random();
            for (int pyramide = 1; pyramide <= 3; pyramide++)
            {
                GeneratePyramid(basislengte, rnd, maxbasisgetal);

                int papierhoogte = ((int)page.Canvas.Size.Height / 3 - 40) * pyramide;

                TekenHelePyramideOpPapier(page, pyrArray, basislengte, papierhoogte);
            }
            //Save pdf file.
            doc.SaveToFile(filename);
            doc.Close();

            return doc;
        }
Ejemplo n.º 6
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

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

            //Draw the page
            DrawPage(page);

            //set view reference
            doc.ViewerPreferences.CenterWindow = true;
            doc.ViewerPreferences.DisplayTitle = false;
            doc.ViewerPreferences.FitWindow = false;
            doc.ViewerPreferences.HideMenubar = true;
            doc.ViewerPreferences.HideToolbar = true;
            doc.ViewerPreferences.PageLayout = PdfPageLayout.SinglePage;

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

            //Launching the Pdf file.
            PDFDocumentViewer("ViewerPreference.pdf");
        }
Ejemplo n.º 7
0
        private void button1_Click(object sender, EventArgs e)
        {
            //load two document
            PdfDocument doc1 = new PdfDocument();
            doc1.LoadFromFile(@"..\..\..\..\..\..\Data\Sample1.pdf");

            PdfDocument doc2 = new PdfDocument();
            doc2.LoadFromFile(@"..\..\..\..\..\..\Data\Sample3.pdf");

            //Create page template
            PdfTemplate template = doc1.Pages[0].CreateTemplate();

            foreach (PdfPageBase page in doc2.Pages)
            {
                page.Canvas.SetTransparency(0.25f, 0.25f, PdfBlendMode.Overlay);
                page.Canvas.DrawTemplate(template, PointF.Empty);
            }

            //Save pdf file.
            doc2.SaveToFile("Overlay.pdf");
            doc1.Close();
            doc2.Close();

            //Launching the Pdf file.
            PDFDocumentViewer("Overlay.pdf");
        }
Ejemplo n.º 8
0
        private static int AddPassword(string path, string password)
        {
            path = Path.GetFullPath(path);

            if (!File.Exists(path))
            {
                System.Console.WriteLine("File does not exists: {0}", path);
                return(1);
            }

            string outputPath = string.Format("{0}{1}{2}-encrypted{3}"
                                              , Path.GetDirectoryName(path)
                                              , Path.DirectorySeparatorChar
                                              , Path.GetFileNameWithoutExtension(path)
                                              , Path.GetExtension(path));

            //System.Console.WriteLine(outputPath);
            if (File.Exists(outputPath))
            {
                File.Delete(outputPath);
            }

            PdfDocument document = null;

            try
            {
                document = PdfReader.Open(path);
                var securitySettings = document.SecuritySettings;

                securitySettings.UserPassword = password;
                //securitySettings.OwnerPassword = options.OwnerPassword;

                securitySettings.PermitAccessibilityExtractContent = false;
                securitySettings.PermitAnnotations      = false;
                securitySettings.PermitAssembleDocument = false;
                securitySettings.PermitExtractContent   = false;
                securitySettings.PermitFormsFill        = false;
                securitySettings.PermitFullQualityPrint = false;
                securitySettings.PermitModifyDocument   = false;
                securitySettings.PermitPrint            = true;

                document.Save(outputPath);

                document.Close();

                return(0);
            }
            catch (Exception)
            {
                return(1);
            }
            finally
            {
                document?.Close();

                System.Console.WriteLine($"File {path} has been processed");
            }
        }
Ejemplo n.º 9
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

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

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

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

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

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

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

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

            //Launching the Pdf file.
            PDFDocumentViewer("SimpleList.pdf");
        }
Ejemplo n.º 10
0
        protected bool SavePDF(PdfDocument transferDetails)
        {
            if (File.Exists(Path.Combine(SieradzBankFilesPathHolder.TransferFilesPath, @"..\mBank\Transfers1.pdf")))
            {
                File.Open(Path.Combine(SieradzBankFilesPathHolder.TransferFilesPath, @"..\mBank\Transfers1.pdf"), FileMode.Open).Close();
                File.Delete(Path.Combine(SieradzBankFilesPathHolder.TransferFilesPath, @"..\mBank\Transfers1.pdf"));
            }
            transferDetails.SaveToFile(SieradzBankFilesPathHolder.TransferFilesPath + @"..\mBank\Transfers1.pdf",FileFormat.PDF);
            transferDetails.Close();

            return File.Exists(SieradzBankFilesPathHolder.TransferFilesPath + @"..\mBank\Transfers1.pdf");
        }
Ejemplo n.º 11
0
        static void Main(string[] args)
        {
            PdfDocument document = new PdfDocument(PdfConformanceLevel.Pdf_A1B);
            PdfPageBase page = document.Pages.Add();

            PdfPageBase page3 = document.Pages.Add();
            page3.Canvas.DrawString("Hello World2", new PdfFont(PdfFontFamily.Helvetica, 30f), new PdfSolidBrush(Color.Black), 10, 10);
            //save to PDF document
            document.Pages[1].Rotation = PdfPageRotateAngle.RotateAngle180;
            document.Pages.RemoveAt(0);
            document.SaveToFile("FromHTML.pdf", FileFormat.PDF);
            document.Close();
        }
Ejemplo n.º 12
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

            // Create one section
            PdfSection section = doc.Sections.Add();

            //Load image
            PdfImage image = PdfImage.FromFile(@"..\..\..\..\..\..\Data\SalesReportChart.png");
            float imageWidth = image.PhysicalDimension.Width / 2;
            float imageHeight = image.PhysicalDimension.Height / 2;
            foreach (PdfBlendMode mode in Enum.GetValues(typeof(PdfBlendMode)))
            {
                PdfPageBase page = section.Pages.Add();
                float pageWidth = page.Canvas.ClientSize.Width;
                float y = 0;

                //title
                y = y + 5;
                PdfBrush brush = new PdfSolidBrush(Color.OrangeRed);
                PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 12f, FontStyle.Bold));
                PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Center);
                String text = String.Format("Transparency Blend Mode: {0}", mode);
                page.Canvas.DrawString(text, font, brush, pageWidth / 2, y, format);
                SizeF size = font.MeasureString(text, format);
                y = y + size.Height + 6;

                page.Canvas.DrawImage(image, 0, y, imageWidth, imageHeight);
                page.Canvas.Save();
                float d = (page.Canvas.ClientSize.Width - imageWidth) / 5;
                float x = d;
                y = y + d / 2;
                for (int i = 0; i < 5; i++)
                {
                    float alpha = 1.0f / 6 * (5 - i);
                    page.Canvas.SetTransparency(alpha, alpha, mode);
                    page.Canvas.DrawImage(image, x, y, imageWidth, imageHeight);
                    x = x + d;
                    y = y + d / 2;
                }
                page.Canvas.Restore();
            }

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

            //Launching the Pdf file.
            PDFDocumentViewer("Transparency.pdf");
        }
Ejemplo n.º 13
0
 private static void crearPdf()
 {
     PdfDocument pdf = new PdfDocument();
     PdfPageBase pagina = pdf.Pages.Add();
     string[] lineasTxT = File.ReadAllLines(CFichero.rutaLibros);
     string salida = "";
     foreach (string linea in lineasTxT)
     {
         salida += linea + "\n";
     }
     pagina.Canvas.DrawString(salida, new PdfFont(PdfFontFamily.TimesRoman, 14), new PdfSolidBrush(Color.Black), 10, 10);
     pdf.SaveToFile("Recibo.pdf");
     pdf.Close();
 }
Ejemplo n.º 14
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

            //Draw pages
            PdfPageBase lastPage = DrawPages(doc);

            //script
            String script
                = "app.alert({"
                + "    cMsg: \"I'll lead; you must follow me.\","
                + "    nIcon: 3,"
                + "    cTitle: \"JavaScript Action\""
                + "});";
            PdfJavaScriptAction action1 = new PdfJavaScriptAction(script);
            doc.AfterOpenAction = action1;

            //script
            script
                = "app.alert({"
                + "    cMsg: \"The firt page!\","
                + "    nIcon: 3,"
                + "    cTitle: \"JavaScript Action\""
                + "});";
            PdfJavaScriptAction action2 = new PdfJavaScriptAction(script);
            action1.NextAction = action2;

            PdfDestination dest = new PdfDestination(lastPage);
            dest.Zoom = 1;
            PdfGoToAction action3 = new PdfGoToAction(dest);
            action2.NextAction = action3;

            //script
            script
                = "app.alert({"
                + "    cMsg: \"Oh sorry, it's the last page. I'm missing!\","
                + "    nIcon: 3,"
                + "    cTitle: \"JavaScript Action\""
                + "});";
            PdfJavaScriptAction action4 = new PdfJavaScriptAction(script);
            action3.NextAction = action4;

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

            //Launching the Pdf file.
            PDFDocumentViewer("ActionChain.pdf");
        }
Ejemplo n.º 15
0
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (disposedValue)
            {
                return;
            }

            if (disposing)
            {
                writer?.Dispose();
                document?.Close();
            }

            disposedValue = true;
        }
Ejemplo n.º 16
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

            String url = "http://www.e-iceblue.com/";
            doc.LoadFromHTML(url, false, true, true);

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

            //Launching the Pdf file.
            PDFDocumentViewer("FromHTML.pdf");
        }
Ejemplo n.º 17
0
        // ToDo: Функция по закрытию документов точно нужна?
        private void Close()
        {
            if (!IsOpen)
            {
                throw new Exception("Pdf file is not open! Please first load and open file!");
            }

            _document?.Close();
            _reader?.Close();

            _document = null;
            _reader   = null;

            _isOpen = false;
        }
Ejemplo n.º 18
0
        protected void Button1_Click(object sender, System.EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

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

            DrawSpiro(page);
            DrawPath(page);

            //Save to browser
            doc.SaveToHttpResponse("Shape.pdf", Response, HttpReadType.Save);
            doc.Close();
        }
Ejemplo n.º 19
0
        private void button1_Click(object sender, EventArgs e)
        {
            //open pdf document
            PdfDocument doc = new PdfDocument(@"..\..\..\..\..\..\Data\Sample3.pdf");

            String pattern = "SplitDocument-{0}.pdf";
            doc.Split(pattern);

            String lastPageFileName
                = String.Format(pattern, doc.Pages.Count - 1);

            doc.Close();

            //Launching the Pdf file.
            PDFDocumentViewer(lastPageFileName);
        }
Ejemplo n.º 20
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();
            doc.ViewerPreferences.PageLayout = PdfPageLayout.TwoColumnLeft;

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

            SetDocumentTemplate(doc, PdfPageSize.A4, margin);

            //create section
            PdfSection section = doc.Sections.Add();
            section.PageSettings.Size = PdfPageSize.A4;
            section.PageSettings.Margins = new PdfMargins(0);
            SetSectionTemplate(section, PdfPageSize.A4, margin, "Section 1");

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

            //Draw page
            DrawPage(page); 

            page = section.Pages.Add();
            DrawPage(page);

            page = section.Pages.Add();
            DrawPage(page);

            page = section.Pages.Add();
            DrawPage(page);

            page = section.Pages.Add();
            DrawPage(page);

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

            //Launching the Pdf file.
            PDFDocumentViewer("Template.pdf");
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Split specific pages from the source file and save them in the destination file.
        /// </summary>
        /// <param name="sourceFile">The source file to split pages from it</param>
        /// <param name="destinationFile">The destination file to save splitted pages into it</param>
        /// <param name="pageRange">Specific pages to split them</param>
        public void Split(string sourceFile, string destinationFile, int[] pageRange)
        {
            PdfDocument pdfDestination = null;
            PdfDocument pdfSource      = null;
            PdfMerger   pdfMerger      = null;

            try
            {
                // Step 1: Temporary file to prevent rewrite on the original file.
                //         Destination file will be changed with the original in the last step.
                //         In case if the destination file in an existing file
                pdfDestination = new PdfDocument(new PdfWriter(destinationFile + "temp"));
                pdfMerger      = new PdfMerger(pdfDestination);

                pdfSource = new PdfDocument(new PdfReader(sourceFile));

                // Extract and merge each page from the source page.
                for (var i = 0; i < pageRange.Length; i++)
                {
                    pdfMerger.Merge(pdfSource, pageRange[i], pageRange[i]);

                    OnUpdateProgress?.Invoke(i);
                }

                pdfDestination.Close();
                pdfMerger.Close();
                pdfSource.Close();

                // Step 5: Replace the original file with the temp one.
                File.Delete(destinationFile);
                File.Move(destinationFile + "temp", destinationFile);
            }
            catch (Exception e)
            {
                if (pdfDestination != null && !pdfDestination.IsClosed())
                {
                    pdfDestination.AddNewPage();
                    pdfDestination.Close();

                    pdfMerger?.Close();
                    pdfSource?.Close();
                }

                File.Delete(destinationFile + "temp");
                throw new Exception(e.Message);
            }
        }
Ejemplo n.º 22
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            String encryptedPdf = @"..\..\..\..\..\..\Data\Encrypted.pdf";
            PdfDocument doc = new PdfDocument(encryptedPdf, "test");

            //extract image
            Image image = doc.Pages[0].ImagesInfo[0].Image;

            doc.Close();

            //Save image file.
            image.Save("Wikipedia_Science.png", System.Drawing.Imaging.ImageFormat.Png);

            //Launching the image file.
            ImageViewer("Wikipedia_Science.png");
        }
Ejemplo n.º 23
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

            String srcPdf = @"..\..\..\..\..\..\Data\Sample2.pdf";
            float width = PdfPageSize.A4.Width * 2;
            float height = PdfPageSize.A4.Height;
            doc.CreateBooklet(srcPdf, width, height, true);

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

            //Launching the Pdf file.
            PDFDocumentViewer("Booklet.pdf");
        }
Ejemplo n.º 24
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();            

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

            DrawSpiro(page);
            DrawPath(page);

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

            //Launching the Pdf file.
            PDFDocumentViewer("DrawShape.pdf");
        }
Ejemplo n.º 25
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();            

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

            DrawText(page);
            AlignText(page);
            AlignTextInRectangle(page);
            TransformText(page);
            RotateText(page);

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

            //Launching the Pdf file.
            PDFDocumentViewer("DrawText.pdf");

        }
Ejemplo n.º 26
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

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

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

            PdfTilingBrush brush
                = new PdfTilingBrush(new SizeF(page.Canvas.ClientSize.Width / 2, page.Canvas.ClientSize.Height / 3));
            brush.Graphics.SetTransparency(0.3f);
            brush.Graphics.Save();
            brush.Graphics.TranslateTransform(brush.Size.Width / 2, brush.Size.Height / 2);
            brush.Graphics.RotateTransform(-45);
            brush.Graphics.DrawString("Spire.Pdf Demo",
                new PdfFont(PdfFontFamily.Helvetica, 24), PdfBrushes.Violet, 0, 0,
                new PdfStringFormat(PdfTextAlignment.Center));
            brush.Graphics.Restore();
            brush.Graphics.SetTransparency(1);
            page.Canvas.DrawRectangle(brush, new RectangleF(new PointF(0, 0), page.Canvas.ClientSize));

            //Draw the page
            DrawPage(page);

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

            //Launching the Pdf file.
            PDFDocumentViewer("TextWaterMark.pdf");
        }
Ejemplo n.º 27
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

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

            //Draw the text
            page.Canvas.DrawString("Hello, World!",
                                   new PdfFont(PdfFontFamily.Helvetica, 30f),
                                   new PdfSolidBrush(Color.Black),
                                   10, 10);

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

            //Launching the Pdf file.
            PDFDocumentViewer("HelloWorld.pdf");

        }
Ejemplo n.º 28
0
        public static Downloads.File ConvertImageToPdf(Downloads.File file)
        {
            PdfDocument doc = new PdfDocument();
            PdfSection section = doc.Sections.Add();
            PdfPageBase page = doc.Pages.Add();
            //Load a tiff image from system
            PdfImage image = PdfImage.FromStream(file.FileStream);
            //Set image display location and size in PDF
            float widthFitRate = image.PhysicalDimension.Width / page.Canvas.ClientSize.Width;
            float heightFitRate = image.PhysicalDimension.Height / page.Canvas.ClientSize.Height;
            float fitRate = Math.Max(widthFitRate, heightFitRate);
            float fitWidth = image.PhysicalDimension.Width / fitRate;
            float fitHeight = image.PhysicalDimension.Height / fitRate;
            page.Canvas.DrawImage(image, 30, 30, fitWidth, fitHeight);

            var docId = Guid.NewGuid().ToString();

            try {

                string path = Path.GetTempPath();
                var filePath = path + @"\" + docId +"-" + file.FileName;
                //save and launch the file
                doc.SaveToFile(filePath);
                file.TempLink = filePath;

            } catch (Exception) {

                var tempPath = Environment.GetEnvironmentVariable("TEMP");
                var filePath = tempPath + @"\" + docId + "-" + file.FileName;
                doc.SaveToFile(filePath);
                file.TempLink = filePath;
            }

            doc.Close();
            file.FileStream.Close();

            return file;
        }
Ejemplo n.º 29
0
        public PdfDocument CreateHelloWordlPdf(string filename)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

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

            int vanlinks = 0;
            for (int aantal = 76; aantal <= 82; aantal++)
            {
                string inhoud = Tafeltje(aantal);

                MaakHetPdfDocument(page, inhoud, vanlinks);
                vanlinks += 70;
            }

            //Save pdf file.
            doc.SaveToFile(filename);
            doc.Close();

            return doc;
        }
Ejemplo n.º 30
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

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

            //Draw the page
            DrawPage(page);

            //encrypt
            doc.Security.KeySize = PdfEncryptionKeySize.Key128Bit;
            doc.Security.OwnerPassword = "******";
            doc.Security.UserPassword = "******";
            doc.Security.Permissions = PdfPermissionsFlags.Print | PdfPermissionsFlags.FillFields;

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

            //Launching the Pdf file.
            PDFDocumentViewer("Encryption.pdf");
        }
Ejemplo n.º 31
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();
            doc.DocumentInformation.Author = "Spire.Pdf";

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

            for (int i = 1; i < 4; i++)
            {
                //create section
                PdfSection section = doc.Sections.Add();
                section.PageSettings.Size = PdfPageSize.A4;
                section.PageSettings.Margins = margin;

                for (int j = 0; j < i; j++)
                {
                    // Create one page
                    PdfPageBase page = section.Pages.Add();
                    DrawAutomaticField(page);
                }
            }

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

            //Launching the Pdf file.
            PDFDocumentViewer("AutomaticField.pdf");
        }
Ejemplo n.º 32
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile(@"..\..\..\..\..\..\Data\Sample2.pdf");

            StringBuilder buffer = new StringBuilder();
            IList<Image> images = new List<Image>();

            foreach (PdfPageBase page in doc.Pages)
            {
                buffer.Append(page.ExtractText());
                foreach (Image image in page.ExtractImages())
                {
                    images.Add(image);
                }
            }

            doc.Close();

            //save text
            String fileName = "TextInPdf.txt";
            File.WriteAllText(fileName, buffer.ToString());

            //save image
            int index = 0;
            foreach (Image image in images)
            {
                String imageFileName
                    = String.Format("Image-{0}.png", index++);
                image.Save(imageFileName, ImageFormat.Png);
            }

            //Launching the Pdf file.
            PDFDocumentViewer(fileName);
        }
Ejemplo n.º 33
0
        public ActionResult Pay(OrderViewModel order)
        {
            // create a new pdf document
            PdfDocument doc = new PdfDocument();

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

            // create a new pdf font
            PdfFont font = doc.AddFont(PdfStandardFont.Helvetica);
            font.Size = 20;

            // create a new text element and add it to the page
            PdfTextElement text = new PdfTextElement(50, 50, "Date: " + order.OrderDate.ToString(), font);
            page.Add(text);
            page.Add(new PdfTextElement(50, 100, "CustomerId:" + order.CustomerId.ToString(), font));

            // save pdf document
            var bytes = doc.Save();

            // close pdf document
            doc.Close();
            return new FileContentResult(bytes, "application/pdf");
        }
Ejemplo n.º 34
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;

            DrawCover(doc.Sections.Add(), margin);
            DrawContent(doc.Sections.Add(), margin);
            DrawPageNumber(doc.Sections[1], margin, 1, doc.Sections[1].Pages.Count);

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

            //Launching the Pdf file.
            PDFDocumentViewer("Pagination.pdf");
        }
Ejemplo n.º 35
0
        private void button1_Click(object sender, System.EventArgs e)
        {
            try
            {
                // Get XML file path.
                string dataPath = Application.StartupPath + @"..\..\..\..\..\..\..\common\Data\DocIO\";
                //Opens an existing Word document
                WordDocument document = new WordDocument(dataPath + "Mathematical Equation.docx");

                //Gets the last section in the document
                WSection section = document.LastSection;
                //Gets paragraph from Word document
                WParagraph paragraph = document.LastSection.Body.ChildEntities[3] as WParagraph;

                //Gets MathML from the paragraph
                WMath math = paragraph.ChildEntities[0] as WMath;
                //Gets the radical equation
                IOfficeMathRadical mathRadical = math.MathParagraph.Maths[0].Functions[1] as IOfficeMathRadical;
                //Gets the fraction equation in radical
                IOfficeMathFraction mathFraction = mathRadical.Equation.Functions[0] as IOfficeMathFraction;
                //Gets the n-array in fraction
                IOfficeMathNArray mathNAry = mathFraction.Numerator.Functions[0] as IOfficeMathNArray;
                //Gets the math script in n-array
                IOfficeMathScript mathScript = mathNAry.Equation.Functions[0] as IOfficeMathScript;
                //Gets the delimiter in math script
                IOfficeMathDelimiter mathDelimiter = mathScript.Equation.Functions[0] as IOfficeMathDelimiter;
                //Gets the math script in delimiter
                mathScript = mathDelimiter.Equation[0].Functions[0] as IOfficeMathScript;
                //Gets the math run element in math script
                IOfficeMathRunElement mathParaItem = mathScript.Equation.Functions[0] as IOfficeMathRunElement;
                //Modifies the math text value
                (mathParaItem.Item as WTextRange).Text = "x";

                //Gets the math bar in delimiter
                IOfficeMathBar mathBar = mathDelimiter.Equation[0].Functions[2] as IOfficeMathBar;
                //Gets the math run element in bar
                mathParaItem = mathBar.Equation.Functions[0] as IOfficeMathRunElement;
                //Modifies the math text value
                (mathParaItem.Item as WTextRange).Text = "x";

                //Gets the paragraph from Word document
                paragraph = document.LastSection.Body.ChildEntities[6] as WParagraph;
                //Gets MathML from the paragraph
                math = paragraph.ChildEntities[0] as WMath;
                //Gets the math script equation
                mathScript = math.MathParagraph.Maths[0].Functions[0] as IOfficeMathScript;
                //Gets the math run element in math script
                mathParaItem = mathScript.Equation.Functions[0] as IOfficeMathRunElement;
                //Modifies the math text value
                (mathParaItem.Item as WTextRange).Text = "x";

                //Gets the paragraph from Word document
                paragraph = document.LastSection.Body.ChildEntities[7] as WParagraph;
                //Gets MathML from the paragraph
                WMath math2 = paragraph.ChildEntities[0] as WMath;
                //Gets bar equation
                mathBar = math2.MathParagraph.Maths[0].Functions[0] as IOfficeMathBar;
                //Gets the math run element in bar
                mathParaItem = mathBar.Equation.Functions[0] as IOfficeMathRunElement;
                //Gets the math text
                (mathParaItem.Item as WTextRange).Text = "x";

                //Save as docx format
                if (wordDocxRadioBtn.Checked)
                {
                    //Saving the document as .docx
                    document.Save("Edit Equation.docx", FormatType.Docx);
                    //Message box confirmation to view the created document.
                    if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        try
                        {
                            //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
#if NETCORE
                            System.Diagnostics.Process process = new System.Diagnostics.Process();
                            process.StartInfo = new System.Diagnostics.ProcessStartInfo("Edit Equation.docx")
                            {
                                UseShellExecute = true
                            };
                            process.Start();
#else
                            System.Diagnostics.Process.Start("Edit Equation.docx");
#endif
                            //Exit
                            this.Close();
                        }
                        catch (Win32Exception ex)
                        {
                            MessageBoxAdv.Show("Microsoft Word Viewer or Microsoft Word is not installed in this system");
                            Console.WriteLine(ex.ToString());
                        }
                    }
                }
                //Save as pdf format
                else if (pdfRadioBtn.Checked)
                {
                    DocToPDFConverter converter = new DocToPDFConverter();
                    //Convert word document into PDF document
                    PdfDocument pdfDoc = converter.ConvertToPDF(document);
                    //Save the pdf file
                    pdfDoc.Save("Edit Equation.pdf");
                    converter.Dispose();
                    pdfDoc.Close();
                    //Message box confirmation to view the created document.
                    if (MessageBoxAdv.Show("Do you want to view the generated PDF?", " Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        try
                        {
#if NETCORE
                            System.Diagnostics.Process process = new System.Diagnostics.Process();
                            process.StartInfo = new System.Diagnostics.ProcessStartInfo("Edit Equation.pdf")
                            {
                                UseShellExecute = true
                            };
                            process.Start();
#else
                            System.Diagnostics.Process.Start("Edit Equation.pdf");
#endif

                            //Exit
                            this.Close();
                        }
                        catch (Exception ex)
                        {
                            MessageBoxAdv.Show("PDF Viewer is not installed in this system");
                            Console.WriteLine(ex.ToString());
                        }
                    }
                }
                else
                {
                    // Exit
                    this.Close();
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            }
        }
Ejemplo n.º 36
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 GeneratePDF_Click(object sender, RoutedEventArgs e)
        {
            Stream   image1     = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.AutoTag.jpg");
            Stream   image2     = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.autotagSmall.jpg");
            PdfColor blackColor = new PdfColor(System.Drawing.Color.FromArgb(255, 0, 0, 0));


            #region content string
            string toc      = "\r\n What can I do with C#? ..................................................................................................................................... 3 \r\n \r\n What is .NET? .................................................................................................................................................... 3 \r\n \r\n Writing, Running, and Deploying a C# Program .............................................................................................. 3 \r\n \r\n Starting a New Program..................................................................................................................................... 3";
            string Csharp   = "Welcome to C# Succinctly. True to the Succinctly series concept, this book is very focused on a single topic: the C# programming language. I might briefly mention some technologies that you can write with C# or explain how a feature fits into those technologies, but the whole of this book is about helping you become familiar with C# syntax. \r\n \r\n In this chapter, Ill start with some introductory information and then jump straight into a simple C# program.";
            string whatToD0 = "C# is a general purpose, object-oriented, component-based programming language. As a general purpose language, you have a number of ways to apply C# to accomplish many different tasks. You can build web applications with ASP.NET, desktop applications with Windows Presentation Foundation (WPF), or build mobile applications for Windows Phone. Other applications include code that runs in the cloud via Windows Azure, and iOS, Android, and Windows Phone support with the Xamarin platform. There might be times when you need a different language, like C or C++, to communicate with hardware or real-time systems. However, from a general programming perspective, you can do a lot with C#.";
            string dotnet   = "The runtime is more formally named the Common Language Runtime (CLR). Programming languages that target the CLR compile to an Intermediate Language (IL). The CLR itself is a virtual machine that runs IL and provides many services such as memory management, garbage collection, exception management, security, and more.\r\n \r\n The Framework Class Library (FCL) is a set of reusable code that provides both general services and technology-specific platforms. The general services include essential types such as collections, cryptography, networking, and more. In addition to general classes, the FCL includes technology-specific platforms like ASP.NET, WPF, web services, and more. The value the FCL offers is to have common components available for reuse, saving time and money without needing to write that code yourself. \r\n \r\n There is a huge ecosystem of open-source and commercial software that relies on and supports .NET. If you visit CodePlex, GitHub, or any other open-source code repository site, you will see a multitude of projects written in C#. Commercial offerings include tools and services that help you build code, manage systems, and offer applications. Syncfusion is part of this ecosystem, offering reusable components for many of the .NET technologies I have mentioned.";
            string prog     = "The previous section described plenty of great things you can do with C#, but most of them are so detailed that they require their own book. To stay focused on the C# programming language, the code in this book will be for the console application. A console application runs on the command line, which you will learn about in this section. You can write your code with any editor, but this book uses Visual Studio.";

            #endregion

            //Create a new PDF document.

            PdfDocument document = new PdfDocument();

            //Auto Tag the document

            document.AutoTag = true;
            document.DocumentInformation.Title = "AutoTag";
            #region page1
            //Add a page to the document.

            PdfPage page1 = document.Pages.Add();

            //Load the image from the disk.

            PdfBitmap image = new PdfBitmap(image1);

            //Draw the image

            page1.Graphics.DrawImage(image, 0, 0, page1.GetClientSize().Width, page1.GetClientSize().Height - 20);

            #endregion

            #region page2
            PdfPage page2 = document.Pages.Add();

            PdfFont fontnormal = new PdfStandardFont(PdfFontFamily.TimesRoman, 10);
            PdfFont fontTitle  = new PdfStandardFont(PdfFontFamily.TimesRoman, 22, PdfFontStyle.Bold);
            PdfFont fontHead   = new PdfStandardFont(PdfFontFamily.TimesRoman, 10, PdfFontStyle.Bold);
            PdfFont fontHead2  = new PdfStandardFont(PdfFontFamily.TimesRoman, 16, PdfFontStyle.Bold);

            page2.Graphics.DrawString("Table of Contents", fontTitle, PdfBrushes.Black, new PointF(300, 0));
            page2.Graphics.DrawLine(new PdfPen(PdfBrushes.Black, 0.5f), new PointF(0, 40), new PointF(page2.GetClientSize().Width, 40));

            page2.Graphics.DrawString("Chapter 1 Introducing C# and .NET .............................................................................................................. 3 \r\n ", fontHead, PdfBrushes.Black, new PointF(0, 60));
            page2.Graphics.DrawString(toc, fontnormal, PdfBrushes.Black, new PointF(0, 80));

            #endregion

            #region page3

            PdfPage page3 = document.Pages.Add();

            page3.Graphics.DrawString("C# Succinctly", new PdfStandardFont(PdfFontFamily.TimesRoman, 32, PdfFontStyle.Bold), PdfBrushes.Black, new PointF(160, 0));

            page3.Graphics.DrawLine(PdfPens.Black, new PointF(0, 40), new PointF(page3.GetClientSize().Width, 40));

            page3.Graphics.DrawString("Chapter 1 Introducing C# and .NET", fontTitle, PdfBrushes.Black, new PointF(160, 60));


            PdfTextElement element1 = new PdfTextElement(Csharp, fontnormal);
            element1.Brush = new PdfSolidBrush(blackColor);
            element1.Draw(page3, new RectangleF(0, 100, page3.GetClientSize().Width, 80));

            page3.Graphics.DrawString("What can I do with C#?", fontHead2, PdfBrushes.Black, new PointF(0, 180));
            PdfTextElement element2 = new PdfTextElement(whatToD0, fontnormal);
            element2.Brush = new PdfSolidBrush(blackColor);
            element2.Draw(page3, new RectangleF(0, 210, page3.GetClientSize().Width, 80));


            page3.Graphics.DrawString("What is .Net", fontHead2, PdfBrushes.Black, new PointF(0, 300));
            PdfTextElement element3 = new PdfTextElement(dotnet, fontnormal);
            element3.Brush = new PdfSolidBrush(blackColor);
            element3.Draw(page3, new RectangleF(0, 330, page3.GetClientSize().Width, 180));


            page3.Graphics.DrawString("Writing, Running, and Deploying a C# Program", fontHead2, PdfBrushes.Black, new PointF(0, 520));
            PdfTextElement element4 = new PdfTextElement(prog, fontnormal);
            element4.Brush = new PdfSolidBrush(blackColor);
            element4.Draw(page3, new RectangleF(0, 550, page3.GetClientSize().Width, 60));

            PdfBitmap img = new PdfBitmap(image2);
            page3.Graphics.DrawImage(img, new PointF(0, 630));
            page3.Graphics.DrawString("Note: The code samples in this book can be downloaded at", fontnormal, PdfBrushes.DarkBlue, new PointF(20, 630));
            page3.Graphics.DrawString("https://bitbucket.org/syncfusiontech/c-succinctly", fontnormal, PdfBrushes.Blue, new PointF(20, 640));
            SizeF      linkSize  = fontnormal.MeasureString("https://bitbucket.org/syncfusiontech/c-succinctly");
            RectangleF rectangle = new RectangleF(20, 640, linkSize.Width, linkSize.Height);

            //Creates a new Uri Annotation

            PdfUriAnnotation uriAnnotation = new PdfUriAnnotation(rectangle, "https://bitbucket.org/syncfusiontech/c-succinctly");
            uriAnnotation.Color = new PdfColor(255, 255, 255);
            //Adds this annotation to a new page
            page3.Annotations.Add(uriAnnotation);

            #endregion



            //Save the document and dispose it.

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

            document.Close(true);
            Save(stream, "AutotagSample.pdf");
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Create a simple PDF document
        /// </summary>
        /// <returns>Return the created PDF document as stream</returns>
        public MemoryStream CreatePdfDocument()
        {
            #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);
            PdfColor    white       = new PdfColor(255, 255, 255);
            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));



            //Read the file
            FileStream file = new FileStream(ResolveApplicationPath("adventure-cycle.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(ResolveApplicationPath("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);

            return(ms);
        }
Ejemplo n.º 38
0
        /// <summary>
        /// Convert To PDF
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConvert_Click(object sender, EventArgs e)
        {
            //Step 1 : Instantiate the spreadsheet creation engine.
            ExcelEngine excelEngine = new ExcelEngine();
            //Step 2 : Instantiate the excel application object.
            IApplication application = excelEngine.Excel;

            application.DefaultVersion = ExcelVersion.Excel2016;
            // Accessing workbook
            string    inputPath = GetFullTemplatePath("PivotLayout.xlsx");
            IWorkbook workbook  = application.Workbooks.Open(inputPath);

            CreatePivotTable(workbook);
            //Intialize the ExcelToPdfConverter class
            ExcelToPdfConverter converter = new ExcelToPdfConverter(workbook);
            //Intialize the ExcelToPdfConverterSettings class
            ExcelToPdfConverterSettings settings = new ExcelToPdfConverterSettings();

            //Set the Layout Options for the output Pdf page.
            settings.LayoutOptions = LayoutOptions.FitSheetOnOnePage;
            //Convert the Excel document to PDF
            PdfDocument pdfDoc = converter.Convert(settings);
            //Save the document as PDF
            string outputFileName = "PivotLayoutCompact.pdf";

            if (rdBtnOutline.Checked)
            {
                outputFileName = "PivotLayoutOutline.pdf";
            }
            else if (rdBtnTabular.Checked)
            {
                outputFileName = "PivotLayoutTabular.pdf";
            }
            try
            {
                pdfDoc.Save(outputFileName);

                pdfDoc.Close();
                converter.Dispose();
                //Close the workbook.
                workbook.Close();

                //No exception will be thrown if there are unsaved workbooks.
                excelEngine.ThrowNotSavedOnDestroy = false;
                excelEngine.Dispose();

                //Message box confirmation to view the created spreadsheet.
                if (MessageBox.Show("Do you want to view the PDF?", "PDF has been created",
                                    MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    try
                    {
                        //Launching the PDF file using the default Application.
#if NETCORE
                        System.Diagnostics.Process process = new System.Diagnostics.Process();
                        process.StartInfo = new System.Diagnostics.ProcessStartInfo(outputFileName)
                        {
                            UseShellExecute = true
                        };
                        process.Start();
#else
                        Process.Start(outputFileName);
#endif
                    }
                    catch (Win32Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }
                else
                {
                    // Exit
                    this.Close();
                }
            }
            catch
            {
                MessageBox.Show("Sorry, PDF can't opened", "File is already open", MessageBoxButtons.OK);
            }

            workbook.Close();
            excelEngine.Dispose();
        }
Ejemplo n.º 39
0
        public ActionResult AnnotationFlatten(string InsideBrowser, string checkboxFlatten)
        {
            //Creates a new PDF document.
            PdfDocument document = new PdfDocument();

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

            document.PageSettings.SetMargins(0);

            //Create new PDF color
            PdfColor blackColor = new PdfColor(0, 0, 0);


            PdfFont  font  = new PdfStandardFont(PdfFontFamily.Helvetica, 10f);
            PdfBrush brush = new PdfSolidBrush(blackColor);
            string   text  = "Adventure Works Cycles, the fictitious company on which the AdventureWorks sample databases are based, is a large, multinational manufacturing company. The company manufactures and sells metal and composite bicycles to North American, European and Asian commercial markets. While its base operation is located in Washington with 290 employees, several regional sales teams are located throughout their market base.";

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

            string markupText = "North American, European and Asian commercial markets";
            PdfTextMarkupAnnotation textMarkupAnnot = new PdfTextMarkupAnnotation("sample", "Highlight", markupText, new PointF(147, 63.5f), font);

            textMarkupAnnot.Author                   = "Annotation";
            textMarkupAnnot.Opacity                  = 1.0f;
            textMarkupAnnot.Subject                  = "Comments and Reviews";
            textMarkupAnnot.ModifiedDate             = new DateTime(2015, 1, 18);
            textMarkupAnnot.TextMarkupAnnotationType = PdfTextMarkupAnnotationType.Highlight;
            textMarkupAnnot.TextMarkupColor          = new PdfColor(Color.Yellow);
            textMarkupAnnot.InnerColor               = new PdfColor(Color.Red);
            textMarkupAnnot.Color = new PdfColor(Color.Yellow);
            if (checkboxFlatten == "Flatten")
            {
                textMarkupAnnot.Flatten = true;
            }
            //Create a new comment.
            PdfPopupAnnotation userQuery = new PdfPopupAnnotation();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            polygonannotation.Bounds = new RectangleF(30, 210, 300, 200);
            PdfPen pen = new PdfPen(Color.Red);

            polygonannotation.Text       = "polygon";
            polygonannotation.Color      = new PdfColor(Color.Red);
            polygonannotation.InnerColor = new PdfColor(Color.LightPink);
            page.Graphics.DrawString("Polygon Annotation", font, brush, new PointF(50, 420));
            page.Annotations.Add(polygonannotation);

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

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

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

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

            PdfPage secondPage = document.Pages.Add();

            //Creates a new TextMarkup annotation.
            string s = "This is TextMarkup annotation!!!";

            secondPage.Graphics.DrawString(s, font, brush, new PointF(30, 70));
            PdfTextMarkupAnnotation textannot = new PdfTextMarkupAnnotation("sample", "Strikeout", s, new PointF(30, 70), font);

            textannot.Author                   = "Annotation";
            textannot.Opacity                  = 1.0f;
            textannot.Subject                  = "pdftextmarkupannotation";
            textannot.ModifiedDate             = new DateTime(2015, 1, 18);
            textannot.TextMarkupAnnotationType = PdfTextMarkupAnnotationType.StrikeOut;
            textannot.TextMarkupColor          = new PdfColor(Color.Yellow);
            textannot.InnerColor               = new PdfColor(Color.Red);
            textannot.Color = new PdfColor(Color.Yellow);
            if (checkboxFlatten == "Flatten")
            {
                textannot.Flatten = true;
            }
            secondPage.Graphics.DrawString("TextMarkup Annotation", font, brush, new PointF(30, 40));
            secondPage.Annotations.Add(textannot);

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

            popupAnnotation.Border.Width            = 4;
            popupAnnotation.Border.HorizontalRadius = 20;
            popupAnnotation.Border.VerticalRadius   = 30;
            popupAnnotation.Opacity    = 1;
            popupAnnotation.Open       = true;
            popupAnnotation.Text       = "Popup Annotation";
            popupAnnotation.Color      = Color.Green;
            popupAnnotation.InnerColor = Color.Blue;
            popupAnnotation.Bounds     = popupRect;
            if (checkboxFlatten == "Flatten")
            {
                popupAnnotation.FlattenPopUps = true;
                popupAnnotation.Flatten       = true;
            }
            secondPage.Graphics.DrawString("Popup Annotation", font, brush, new PointF(400, 40));
            secondPage.Annotations.Add(popupAnnotation);



            //Creates a new Line measurement annotation.
            points = new int[] { 400, 630, 550, 630 };
            PdfLineMeasurementAnnotation lineMeasureAnnot = new PdfLineMeasurementAnnotation(points);

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

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

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


            MemoryStream SourceStream = new MemoryStream();

            document.Save(SourceStream);
            document.Close(true);

            //Creates a new Loaded document.
            PdfLoadedDocument lDoc   = new PdfLoadedDocument(SourceStream);
            PdfLoadedPage     lpage1 = lDoc.Pages[0] as PdfLoadedPage;
            PdfLoadedPage     lpage2 = lDoc.Pages[1] as PdfLoadedPage;

            if (checkboxFlatten == "Flatten")
            {
                lpage1.Annotations.Flatten = true;
                lpage2.Annotations.Flatten = true;
            }

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

            lDoc.Save(ms);

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

            lDoc.Close(true);

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

            fileStreamResult.FileDownloadName = "Annotation.pdf";
            return(fileStreamResult);
        }
Ejemplo n.º 40
0
        protected void buttonCreatePdf_Click(object sender, EventArgs e)
        {
            // create a PDF document
            PdfDocument document = new PdfDocument();

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

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

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

            float crtYPos = 20;
            float crtXPos = 5;

            PdfLayoutInfo textLayoutInfo     = null;
            PdfLayoutInfo graphicsLayoutInfo = null;

            #region Layout lines

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

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

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

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

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

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

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

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

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

            #endregion

            #region Layout circles

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

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

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

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

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

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

            graphicsLayoutInfo = page1.Layout(pdfThickBorderDisc);

            crtYPos = graphicsLayoutInfo.LastPageRectangle.Bottom + 10;

            #endregion

            #region Layout ellipses and arcs

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

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

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

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

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

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

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

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


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

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

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

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

            crtYPos = graphicsLayoutInfo.LastPageRectangle.Bottom + 10;

            #endregion

            #region Layout rectangles

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

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

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

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

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

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

            crtYPos = graphicsLayoutInfo.LastPageRectangle.Bottom + 10;

            #endregion

            #region Layout Bezier curves

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

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

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

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

            // draw the Bezier curve

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

            #endregion

            #region Layout a polygons

            // layout a polygon without fill color

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

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

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

            // layout a polygon with fill color

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

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

            #endregion

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

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

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

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

                // call End() method of HTTP response to stop ASP.NET page processing
                HttpContext.Current.Response.End();
            }
            finally
            {
                document.Close();
            }
        }
Ejemplo n.º 41
0
        void OnButtonClicked(object sender, EventArgs e)
        {
            string   resourcePath = "SampleBrowser.Samples.DocIO.Templates.CreateEquation.docx";
            Assembly assembly     = Assembly.GetExecutingAssembly();
            Stream   fileStream   = assembly.GetManifestResourceStream(resourcePath);

            // Loads the stream into Word Document.
            WordDocument document = new WordDocument(fileStream, Syncfusion.DocIO.FormatType.Automatic);
            //Gets the last section in the document
            WSection section = document.LastSection;

            //Sets page margins
            document.LastSection.PageSetup.Margins.All = 72;
            //Adds new paragraph to the section
            IWParagraph paragraph = section.AddParagraph();

            //Appends text to paragraph
            IWTextRange textRange = paragraph.AppendText("Mathematical equations");

            textRange.CharacterFormat.FontSize            = 28;
            paragraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center;
            paragraph.ParagraphFormat.AfterSpacing        = 12;

            #region Sum to the power of n
            //Adds new paragraph to the section
            paragraph = AddParagraph(section, "This is an expansion of the sum (1+X) to the power of n.");
            //Creates an equation with sum to the power of N
            CreateSumToThePowerOfN(paragraph);
            #endregion

            #region Fourier series
            //Adds new paragraph to the section
            paragraph = AddParagraph(section, "This is a Fourier series for the function of period 2L");
            //Creates a Fourier series equation
            CreateFourierseries(paragraph);
            #endregion

            #region Triple scalar product
            //Adds new paragraph to the section
            paragraph = AddParagraph(section, "This is an expansion of triple scalar product");
            //Creates a triple scalar product equation
            CreateTripleScalarProduct(paragraph);
            #endregion

            #region Gamma function
            //Adds new paragraph to the section
            paragraph = AddParagraph(section, "This is an expansion of gamma function");
            //Creates a gamma function equation
            CreateGammaFunction(paragraph);
            #endregion

            #region Vector relation
            //Adds new paragraph to the section
            paragraph = AddParagraph(section, "This is an expansion of vector relation ");
            //Creates a vector relation equation
            CreateVectorRelation(paragraph);
            #endregion

            MemoryStream stream = new MemoryStream();
            //Set file content type
            string contentType = null;
            string fileName    = null;
            if (docxButton.Checked)
            {
                fileName    = "CreateEquation.docx";
                contentType = "application/msword";
                document.Save(stream, FormatType.Docx);
            }
            else
            {
                fileName    = "CreateEquation.pdf";
                contentType = "application/pdf";
                DocIORenderer renderer = new DocIORenderer();
                PdfDocument   pdfDoc   = renderer.ConvertToPDF(document);
                pdfDoc.Save(stream);

                pdfDoc.Close();
            }

            document.Dispose();
            if (stream != null)
            {
                SaveAndroid androidSave = new SaveAndroid();
                androidSave.Save(fileName, contentType, stream, m_context);
            }
        }
Ejemplo n.º 42
0
        /// <summary>
        /// Create a simple PDF document
        /// </summary>
        /// <returns>Return the created PDF document as stream</returns>
        public MemoryStream CreatePdfDocument()
        {
            //Create a new PDF document.
            PdfDocument doc = new PdfDocument();

            //Set compression level
            doc.Compression = PdfCompressionLevel.None;

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

            string basePath = _hostingEnvironment.WebRootPath;
            //Read the file
            FileStream file = new FileStream(ResolveApplicationPath("manual.txt"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            //Read the text from the text file
            StreamReader reader = new StreamReader(file, System.Text.Encoding.ASCII);
            string       text   = reader.ReadToEnd();

            reader.Dispose();

            //Set the font
            PdfFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);

            //Set the formats for the text
            PdfStringFormat format = new PdfStringFormat();

            format.Alignment       = PdfTextAlignment.Justify;
            format.LineAlignment   = PdfVerticalAlignment.Top;
            format.ParagraphIndent = 15f;

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

            element.Brush        = new PdfSolidBrush(Color.Black);
            element.StringFormat = format;
            element.Font         = new PdfStandardFont(PdfFontFamily.Helvetica, 12);

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

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

            RectangleF bounds = new RectangleF(PointF.Empty, page.Graphics.ClientSize);

            //Raise the events to draw the graphic elements for each page.
            element.BeginPageLayout += new BeginPageLayoutEventHandler(BeginPageLayout);
            element.EndPageLayout   += new EndPageLayoutEventHandler(EndPageLayout);

            //Draw the text element with the properties and formats set.
            PdfTextLayoutResult result = element.Draw(page, bounds, layoutFormat);

            //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);
            return(ms);
        }
Ejemplo n.º 43
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("Sales Report", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1);
            y = y + font1.MeasureString("Sales Report", format1).Height;
            y = y + 5;

            PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", 11f, FontStyle.Bold));
            PdfTrueTypeFont font3 = new PdfTrueTypeFont(new Font("Arial", 10f, FontStyle.Bold));

            using (OleDbConnection conn = new OleDbConnection())
            {
                conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\..\..\..\..\..\..\Data\demo.mdb";
                conn.Open();

                OleDbCommand partQueryCommand      = PreparePartQueryCommand(conn);
                OleDbCommand orderItemQueryCommand = PrepareOrderItemQueryCommand(conn);

                DataTable vendors = GetVendors(conn);
                for (int i = 0; i < vendors.Rows.Count; i++)
                {
                    if (i > 0)
                    {
                        //next page
                        page = section.Pages.Add();
                        y    = 0;
                    }
                    //draw vendor
                    String          vendorTitle            = String.Format("{0}. {1}", i + 1, vendors.Rows[i].ItemArray[1]);
                    PdfLayoutResult drawVendorLayoutResult = DrawVendor(page, vendors, i, vendorTitle, y);

                    //add vendor bookmark
                    PdfDestination vendorBookmarkDest = new PdfDestination(page, new PointF(0, y));
                    PdfBookmark    vendorBookmark     = doc.Bookmarks.Add(vendorTitle);
                    vendorBookmark.Color        = Color.SaddleBrown;
                    vendorBookmark.DisplayStyle = PdfTextStyle.Bold;
                    vendorBookmark.Action       = new PdfGoToAction(vendorBookmarkDest);

                    y    = drawVendorLayoutResult.Bounds.Bottom + 5;
                    page = drawVendorLayoutResult.Page;

                    //get parts of vendor
                    DataTable parts = GetParts(partQueryCommand, (double)vendors.Rows[i].ItemArray[0]);
                    for (int j = 0; j < parts.Rows.Count; j++)
                    {
                        if (j > 0)
                        {
                            //next page
                            page = section.Pages.Add();
                            y    = 0;
                        }
                        //draw part
                        String          partTitle            = String.Format("{0}.{1}. {2}", i + 1, j + 1, parts.Rows[j].ItemArray[1]);
                        PdfLayoutResult drawPartLayoutResult = DrawPart(page, parts, j, partTitle, y);

                        //add part bookmark
                        PdfDestination partBookmarkDest = new PdfDestination(page, new PointF(0, y));
                        PdfBookmark    partBookmark     = vendorBookmark.Add(partTitle);
                        partBookmark.Color        = Color.Coral;
                        partBookmark.DisplayStyle = PdfTextStyle.Italic;
                        partBookmark.Action       = new PdfGoToAction(partBookmarkDest);

                        y    = drawPartLayoutResult.Bounds.Bottom + 5;
                        page = drawPartLayoutResult.Page;

                        //get order items
                        String    orderItemsTitle = String.Format("{0} - Order Items", parts.Rows[j].ItemArray[1]);
                        DataTable orderItems      = GetOrderItems(orderItemQueryCommand, (double)parts.Rows[j].ItemArray[0]);
                        DrawOrderItems(page, orderItems, orderItemsTitle, y);
                    }
                }
            }

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

            //Launching the Pdf file.
            PDFDocumentViewer("Bookmark.pdf");
        }
Ejemplo n.º 44
0
        private void button1_Click(object sender, EventArgs e)
        {
            //Create a pdf document.
            PdfDocument doc = new PdfDocument();

            //Set margins
            PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
            PdfMargins       margin   = new PdfMargins();

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

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

            float           y    = 100;
            float           x    = 10;
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Lucida Sans Unicode", 14));

            String          label  = "Simple Text Link: ";
            PdfStringFormat format = new PdfStringFormat();

            format.MeasureTrailingSpaces = true;
            page.Canvas.DrawString(label, font, PdfBrushes.Orange, 0, y, format);
            x = font.MeasureString(label, format).Width;
            PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Lucida Sans Unicode", 14, FontStyle.Underline));
            String          url1  = "http://www.e-iceblue.com";

            page.Canvas.DrawString(url1, font1, PdfBrushes.CadetBlue, x, y);
            y = y + font1.MeasureString(url1).Height + 25;

            label = "Web Link: ";
            page.Canvas.DrawString(label, font, PdfBrushes.Orange, 0, y, format);
            x = font.MeasureString(label, format).Width;
            String         text  = "E-iceblue home";
            PdfTextWebLink link2 = new PdfTextWebLink();

            link2.Text  = text;
            link2.Url   = url1;
            link2.Font  = font1;
            link2.Brush = PdfBrushes.CadetBlue;
            link2.DrawTextWebLink(page.Canvas, new PointF(x, y));
            y = y + font1.MeasureString(text).Height + 30;

            label = "URI Annonation: ";
            page.Canvas.DrawString(label, font, PdfBrushes.Orange, 0, y, format);
            x    = font.MeasureString(label, format).Width;
            text = "Google";
            PointF           location   = new PointF(x, y);
            SizeF            size       = font1.MeasureString(text);
            RectangleF       linkBounds = new RectangleF(location, size);
            PdfUriAnnotation link3      = new PdfUriAnnotation(linkBounds);

            link3.Border = new PdfAnnotationBorder(0);
            link3.Uri    = "http://www.google.com";
            (page as PdfNewPage).Annotations.Add(link3);
            page.Canvas.DrawString(text, font1, PdfBrushes.CadetBlue, x, y);
            y = y + size.Height + 30;

            label = "URI Annonation Action: ";
            page.Canvas.DrawString(label, font, PdfBrushes.Orange, 0, y, format);
            x          = font.MeasureString(label, format).Width;
            text       = "JavaScript Action (Click Me)";
            location   = new PointF(x - 2, y - 2);
            size       = font1.MeasureString(text);
            size       = new SizeF(size.Width + 5, size.Height + 5);
            linkBounds = new RectangleF(location, size);
            PdfUriAnnotation link4 = new PdfUriAnnotation(linkBounds);

            link4.Border = new PdfAnnotationBorder(0.75f);
            link4.Color  = Color.CadetBlue;
            //Script
            String script
                = "app.alert({"
                  + "    cMsg: \"Hello.\","
                  + "    nIcon: 3,"
                  + "    cTitle: \"JavaScript Action\""
                  + "});";
            PdfJavaScriptAction action = new PdfJavaScriptAction(script);

            link4.Action = action;
            (page as PdfNewPage).Annotations.Add(link4);
            page.Canvas.DrawString(text, font1, PdfBrushes.CadetBlue, x, y);
            y = y + size.Height + 30;

            label = "Need Help:  ";
            page.Canvas.DrawString(label, font, PdfBrushes.Orange, 0, y, format);
            x           = font.MeasureString(label, format).Width;
            text        = "Go to forum to ask questions";
            link2       = new PdfTextWebLink();
            link2.Text  = text;
            link2.Url   = "https://www.e-iceblue.com/forum/components-f5.html";
            link2.Font  = font1;
            link2.Brush = PdfBrushes.CadetBlue;
            link2.DrawTextWebLink(page.Canvas, new PointF(x, y));
            y = y + font1.MeasureString(text).Height + 30;

            label = "Contct us:  ";
            page.Canvas.DrawString(label, font, PdfBrushes.Orange, 0, y, format);
            x           = font.MeasureString(label, format).Width;
            text        = "Send an email";
            link2       = new PdfTextWebLink();
            link2.Text  = text;
            link2.Url   = "mailto:[email protected]";
            link2.Font  = font1;
            link2.Brush = PdfBrushes.CadetBlue;
            link2.DrawTextWebLink(page.Canvas, new PointF(x, y));
            y = y + font1.MeasureString(text).Height + 30;

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

            //Launch the file.
            PDFDocumentViewer("Link.pdf");
        }
Ejemplo n.º 45
0
        private async void GeneratePDF_Click(object sender, RoutedEventArgs e)
        {
            // Create a new document class object.
            PdfDocument doc        = new PdfDocument();
            PdfColor    blackColor = new PdfColor(System.Drawing.Color.FromArgb(255, 0, 0, 0));

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

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

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

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

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

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

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

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

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

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

            pen.Width = 6f;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            doc.Close(true);
            Save(stream, "PageSettings.pdf");
        }
        public void SendInvoice(decimal recordId, decimal userId)
        {
            try
            {
                decimal id = userId;
                using (MailMessage mailMessage = new MailMessage())
                {
                    List <User_Transaction_Master> user_Transaction_Master = db.User_Transaction_Master
                                                                             .Include(u => u.User_Profile)
                                                                             .Where(u => u.User_ID == id).ToList();

                    mailMessage.From = new MailAddress("*****@*****.**", "Lexnarro");
                    mailMessage.To.Add(new MailAddress(user_Transaction_Master[0].User_Profile.EmailAddress));
                    mailMessage.Subject = "Lexnarro Payment Invoice";
                    mailMessage.Body    = "<p>Lexnarro Payment Invoice</p>";


                    HtmlToPdf   converter     = new HtmlToPdf();
                    string      pdf_page_size = "A4";
                    PdfPageSize pageSize      = (PdfPageSize)Enum.Parse(typeof(PdfPageSize),
                                                                        pdf_page_size, true);
                    string             pdf_orientation = "Portrait";
                    PdfPageOrientation pdfOrientation  =
                        (PdfPageOrientation)Enum.Parse(typeof(PdfPageOrientation),
                                                       pdf_orientation, true);
                    int webPageWidth  = 800;
                    int webPageHeight = 0;

                    converter.Options.PdfPageSize        = pageSize;
                    converter.Options.PdfPageOrientation = pdfOrientation;
                    converter.Options.WebPageWidth       = webPageWidth;
                    converter.Options.WebPageHeight      = webPageHeight;

                    string myurl = "https://www.lexnarro.com.au/Invoice/Index?v=" + id + "&r=" + recordId;

                    PdfDocument doc = converter.ConvertUrl(myurl);
                    doc.Save(Server.MapPath("~/Reports/Invoice_" + id + ".pdf"));
                    doc.Close();
                    doc.DetachStream();

                    mailMessage.Attachments.Add(new Attachment(Server.MapPath("~/Reports/Invoice_" + id + ".pdf")));

                    mailMessage.IsBodyHtml = true;
                    SmtpClient client = new SmtpClient();

                    SmtpClient smtp = new SmtpClient
                    {
                        Host           = "mail.lexnarro.com.au",
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        Port           = 25,
                        //smtp.EnableSsl = true;
                        UseDefaultCredentials = false,
                        Credentials           = new System.Net.NetworkCredential("*****@*****.**", "lexnarro@123")
                    };
                    smtp.Send(mailMessage);

                    //TempData["message"] = ToasterMessage.Message(ToastType.success, "Invoice emailed.");
                    //var categories = (new
                    //{
                    //    status = "success"
                    //});

                    //return Json(new { data = categories }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception dd)
            {
                //var categories = (new
                //{
                //    status = dd.ToString()
                //});
                //return Json(new { data = categories }, JsonRequestBehavior.AllowGet);
            }
        }
Ejemplo n.º 47
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(ofdSingleFile.SafeFileName))
            {
                MessageBox.Show("Please select a pdf file");
                return;
            }
            btnRun.Enabled = false;

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

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

                    pdfTemp.Pages.RemoveAt(0);
                    #endregion

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

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

                var newFile = filePath.Remove(filePath.LastIndexOf('.'), 4) + "_cut" + DateTime.Now.ToFileTime() + ".pdf";
                docWillSave.SaveToFile(newFile);
                docWillSave.Close();
                lblMsg.Text = "File has been save as " + newFile;
                System.Diagnostics.Process.Start(newFile);
            });
        }
        public IActionResult PrintAll()
        {
            //Create a new PDF document.
            PdfDocument doc = new PdfDocument();
            //Add a page.
            PdfPage page = doc.Pages.Add();
            //Create a PdfGrid.
            PdfGrid pdfGrid = new PdfGrid();
            //Loads the image as stream
            FileStream imageStream = new FileStream("img/1.jpg", FileMode.Open, FileAccess.Read);
            RectangleF bounds      = new RectangleF(10, 0, 505, 100);
            PdfImage   image       = PdfImage.FromStream(imageStream);

            //Draws the image to the PDF page
            page.Graphics.DrawImage(image, bounds);

            ///////////////////////Text///////////////////////
            /////Create PDF graphics for the page.
            PdfGraphics graphics = page.Graphics;
            //Set the standard font.
            PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 15);
            //Draw the text.
            string text = "All Students Records!!!";

            graphics.DrawString(text, font, new PdfSolidBrush(new PdfColor(26, 155, 203)), new Syncfusion.Drawing.PointF(180, 120));
            //Add values to list
            // var data = _Context.Students.ToList();

            var data = from student in _context.Students
                       orderby student.FirstMidName descending
                       select new
            {
                student.LastName,
                student.FirstMidName,
                student.EnrollmentDate,
                student.Enrollments.Count
            };
            //Add list to IEnumerable
            IEnumerable <object> dataTable = data;

            //Assign data source.
            pdfGrid.DataSource = dataTable;
            /////// Header/////////////
            PdfGridRow header = pdfGrid.Headers[0];

            header.Cells[0].Value = "First Name";

            header.Cells[1].Value = "Last Name";

            header.Cells[2].Value = "Enrollment Date";

            header.Cells[3].Value        = "Enrollment courses number";
            header.Style.TextBrush       = new PdfSolidBrush(new PdfColor(255, 255, 255));
            header.Style.BackgroundBrush = new PdfSolidBrush(new PdfColor(126, 155, 203));
            header.Style.Font            = new PdfStandardFont(PdfFontFamily.TimesRoman, 11f, PdfFontStyle.Bold);

            for (int i = 0; i < header.Cells.Count; i++)
            {
                header.Cells[i].StringFormat      = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
                header.Cells[i].Style.CellPadding = new PdfPaddings(10, 10, 10, 10);
            }
            /////////////////////Rows/////////////////////
            //Adds cell customizations
            for (int i = 0; i < pdfGrid.Rows.Count; i++)
            {
                pdfGrid.Rows[i].Style.TextBrush = new PdfSolidBrush(new PdfColor(126, 155, 203));

                pdfGrid.Rows[i].Style.Font = new PdfStandardFont(PdfFontFamily.TimesRoman, 10f, PdfFontStyle.Bold);
                for (int j = 0; j < pdfGrid.Rows[i].Cells.Count; j++)
                {
                    pdfGrid.Rows[i].Cells[j].Style.CellPadding = new PdfPaddings(10, 10, 10, 10);
                }
            }

            //Draw grid to the page of PDF document.
            pdfGrid.Draw(page, new Syncfusion.Drawing.PointF(10, 150));


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

            doc.Save(stream);
            //If the position is not set to '0' then the PDF will be empty.
            stream.Position = 0;
            //Close the document.
            doc.Close(true);
            //Defining the ContentType for pdf file.
            string contentType = "application/pdf";
            //Define the file name.
            string fileName = "AllStudents.pdf";

            //Creates a FileContentResult object by using the file contents, content type, and file name.
            return(File(stream, contentType, fileName));
        }
Ejemplo n.º 49
0
        private void BtnCreatePdf_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            string file = "Document.pdf";

            try
            {
                // read parameters from the webpage
                string url = TxtUrl.Text;

                string page_layout             = DdlPageLayout.SelectedItem.ToString();
                PdfViewerPageLayout pageLayout = (PdfViewerPageLayout)Enum.Parse(
                    typeof(PdfViewerPageLayout), page_layout, true);

                string            page_mode = DdlPageMode.SelectedItem.ToString();
                PdfViewerPageMode pageMode  = (PdfViewerPageMode)Enum.Parse(
                    typeof(PdfViewerPageMode), page_mode, true);

                bool centerWindow    = ChkCenterWindow.Checked;
                bool displayDocTitle = ChkDisplayDocTitle.Checked;
                bool fitWindow       = ChkFitWindow.Checked;
                bool hideMenuBar     = ChkHideMenuBar.Checked;
                bool hideToolbar     = ChkHideToolbar.Checked;
                bool hideWindowUI    = ChkHideWindowUI.Checked;

                // instantiate a html to pdf converter object
                HtmlToPdf converter = new HtmlToPdf();

                // set converter options
                converter.Options.ViewerPreferences.CenterWindow    = centerWindow;
                converter.Options.ViewerPreferences.DisplayDocTitle = displayDocTitle;
                converter.Options.ViewerPreferences.FitWindow       = fitWindow;
                converter.Options.ViewerPreferences.HideMenuBar     = hideMenuBar;
                converter.Options.ViewerPreferences.HideToolbar     = hideToolbar;
                converter.Options.ViewerPreferences.HideWindowUI    = hideWindowUI;

                converter.Options.ViewerPreferences.PageLayout            = pageLayout;
                converter.Options.ViewerPreferences.PageMode              = pageMode;
                converter.Options.ViewerPreferences.NonFullScreenPageMode =
                    PdfViewerFullScreenExitMode.UseNone;

                // create a new pdf document converting an url
                PdfDocument doc = converter.ConvertUrl(url);

                // save pdf document
                doc.Save(file);

                // close pdf document
                doc.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(String.Format("Error: {0}", ex.Message),
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            finally
            {
                Cursor = Cursors.Arrow;
            }

            // open generated pdf
            try
            {
                System.Diagnostics.Process.Start(file);
            }
            catch
            {
                MessageBox.Show("Could not open generated pdf document",
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Ejemplo n.º 50
0
        private async void Button_Clicked(object sender, EventArgs e)
        {
            //Create a new PDF document.
            PdfDocument doc = new PdfDocument();
            //Add a page.
            PdfPage page = doc.Pages.Add();

            Stream      fontStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("IttezanPos.Assets.arial.ttf");
            PdfTemplate header     = PdfHelper.AddHeader(doc, "الأرصدة الإفتتاحية", "Ittezan Pos" + " " + DateTime.Now.ToString());

            PdfCellStyle headerStyle = new PdfCellStyle();

            headerStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
            page.Graphics.DrawPdfTemplate(header, new PointF());

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

            //String format

            //  PdfFont pdfFont = new PdfTrueTypeFont(fontStream1, 12);

            //Create a DataTable.
            DataTable dataTable = new DataTable("EmpDetails");
            List <SuplierTotalAmount> customerDetails = new List <SuplierTotalAmount>();

            //Add columns to the DataTable
            dataTable.Columns.Add("ID");
            dataTable.Columns.Add("Name");
            dataTable.Columns.Add("Address");
            dataTable.Columns.Add("Total");

            //Add rows to the DataTable.
            foreach (var item in clients)
            {
                SuplierTotalAmount customer = new SuplierTotalAmount();
                customer.name         = item.name;
                customer.remaining    = item.remaining;
                customer.creditorit   = item.creditorit;
                customer.total_amount = item.total_amount;
                customerDetails.Add(customer);
                dataTable.Rows.Add(new string[] { customer.total_amount.ToString(), customer.remaining.ToString(), customer.creditorit.ToString(), customer.name });
            }

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

            pdfGrid.Headers.Add(1);
            PdfGridRow pdfGridRowHeader = pdfGrid.Headers[0];

            pdfGridRowHeader.Cells[3].Value = "الإسم";
            pdfGridRowHeader.Cells[2].Value = "المبلغ دائن/ له";
            pdfGridRowHeader.Cells[1].Value = "المبلغ المدين / عليه";
            pdfGridRowHeader.Cells[0].Value = "الرصيد";
            PdfGridStyle pdfGridStyle = new PdfGridStyle();

            pdfGridStyle.Font = new PdfTrueTypeFont(fontStream, 12);

            PdfGridLayoutFormat format1 = new PdfGridLayoutFormat();

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

            PdfStringFormat format = new PdfStringFormat();

            format.TextDirection = PdfTextDirection.RightToLeft;
            format.Alignment     = PdfTextAlignment.Center;
            format.LineAlignment = PdfVerticalAlignment.Middle;

            pdfGrid.Columns[0].Format = format;
            pdfGrid.Columns[1].Format = format;
            pdfGrid.Columns[2].Format = format;
            pdfGrid.Columns[3].Format = format;
            pdfGrid.Style             = pdfGridStyle;
            //Draw grid to the page of PDF document.
            pdfGrid.Draw(page, new Syncfusion.Drawing.Point(0, (int)header.Height + 10), format1);
            MemoryStream stream = new MemoryStream();

            //Save the document.
            doc.Save(stream);
            //close the document
            doc.Close(true);
            await Xamarin.Forms.DependencyService.Get <ISave>().SaveAndView("الأرصدة الإفتتاحية .pdf", "application/pdf", stream);
        }
Ejemplo n.º 51
0
 private void CleanUp(PdfDocument pdfDocument, IList <iText.PdfCleanup.PdfCleanUpLocation> cleanUpLocations)
 {
     PdfCleaner.CleanUp(pdfDocument, cleanUpLocations);
     pdfDocument.Close();
 }
Ejemplo n.º 52
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 jpegImage = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.Autumn Leaves.jpg");
            Stream pngImage  = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.syncfusion_logo.png");

#if STORE_SB
            Stream tiffImage = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.image.tif");
#else
            Stream tiffImage = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.image.tiff");
#endif
            Stream gifImage = typeof(ImageInsertion).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.Ani.gif");


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

            // Set font.
            PdfStandardFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 22, PdfFontStyle.Bold);

            // Create brush.
            PdfBrush textBrush = PdfBrushes.DarkBlue;

            #region Jpeg image
            // Add a new section to the document.
            PdfSection section = document.Sections.Add();
            // Add a new page to the newly created section.
            PdfPage     page = section.Pages.Add();
            PdfGraphics g    = page.Graphics;

            g.DrawString("JPEG Image Drawing", font, textBrush, new PointF(10, 0));

            //Drawing a jpeg image
            PdfImage image = new PdfBitmap(jpegImage);
            g.DrawImage(image, 0, 30);

            #endregion

            #region PNG Image
            page = section.Pages.Add();
            g    = page.Graphics;
            g.DrawString("PNG Image drawing", font, textBrush, new PointF(10, 0));

            image = new PdfBitmap(pngImage);

            g.DrawImage(image, 0, 30);
            #endregion

            #region Multiframe Tiff
            PdfBitmap multiFrameImage = new PdfBitmap(tiffImage);

            int frameCount = multiFrameImage.FrameCount;

            for (int i = 0; i < frameCount; i++)
            {
                // Every frame in a new page.
                page = section.Pages.Add();
                section.PageSettings.Margins.All = 0;
                g = page.Graphics;

                // Set the acive frame.
                multiFrameImage.ActiveFrame = i;

                // Draw active frame.
                g.DrawImage(multiFrameImage, 0, 0, page.Size.Width, page.Size.Height);

                if (i == 0)
                {
#if STORE_SB
                    g.DrawString("Tiff Image", font, textBrush, new PointF(10, 10));
#else
                    g.DrawString("Multiframe Tiff Image", font, textBrush, new PointF(10, 10));
#endif
                }
            }
            #endregion
            #region Gif
            page = section.Pages.Add();
            g    = page.Graphics;

            // Draw gif image.
            image = new PdfBitmap(gifImage);
            g.DrawImage(image, 0, 0, g.ClientSize.Width, image.Height);

            g.DrawString("Gif Image", font, textBrush, new PointF(10, 0));

            #endregion

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

            document.Close(true);
            Save(stream, "Sample.pdf");
        }
        public ActionResult TiffToPDF(string viewTemplate, string createPDF)
        {
            string dataPath = _hostingEnvironment.WebRootPath + @"/PDF/";

            //Load TIFF image to stream
            FileStream imageFileStream = new FileStream(dataPath + "image.tiff", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            if (viewTemplate == "View Template")
            {
                return(File(imageFileStream, "application/image", "image.tiff"));
            }
            else if (createPDF == "Generate PDF")
            {
                //Create a new PDF document
                PdfDocument document = new PdfDocument();

                //Set margin to the page
                document.PageSettings.Margins.All = 0;

                //Load Multiframe Tiff image
                PdfTiffImage tiffImage = new PdfTiffImage(imageFileStream);

                //Get the frame count
                int frameCount = tiffImage.FrameCount;

                //Access each frame and draw into the page
                for (int i = 0; i < frameCount; i++)
                {
                    //Add new page for each frames
                    PdfPage page = document.Pages.Add();

                    //Get page graphics
                    PdfGraphics graphics = page.Graphics;

                    //Set active frame.
                    tiffImage.ActiveFrame = i;

                    //Draw Tiff image into page
                    graphics.DrawImage(tiffImage, 0, 0, page.GetClientSize().Width, page.GetClientSize().Height);
                }

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

                document.Save(stream);

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

                stream.Position = 0;

                //Download the PDF document in the browser.
                FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf");
                fileStreamResult.FileDownloadName = "TiffToPDF.pdf";
                return(fileStreamResult);
            }
            else
            {
                return(View());
            }
        }
Ejemplo n.º 54
0
        void OnButtonClicked(object sender, EventArgs e)
        {
            //Creates a new Word document
            WordDocument document = new WordDocument();
            //Adds new section to the document
            IWSection section = document.AddSection();

            //Sets page setup options
            section.PageSetup.Orientation = PageOrientation.Landscape;
            section.PageSetup.Margins.All = 72;
            section.PageSetup.PageSize    = new SizeF(792f, 612f);
            //Adds new paragraph to the section
            WParagraph paragraph = section.AddParagraph() as WParagraph;
            //Creates new group shape
            GroupShape groupShape = new GroupShape(document);

            //Adds group shape to the paragraph.
            paragraph.ChildEntities.Add(groupShape);

            //Create a RoundedRectangle shape with "Management" text
            CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(324f, 107.7f, 144f, 45f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(50, 48, 142), "Management", groupShape, document);

            //Create a BentUpArrow shape to connect with "Development" shape
            CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(177.75f, 176.25f, 210f, 50f), 180, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document);

            //Create a BentUpArrow shape to connect with "Sales" shape
            CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(403.5f, 175.5f, 210f, 50f), 180, true, false, Syncfusion.Drawing.Color.White, null, groupShape, document);

            //Create a DownArrow shape to connect with "Production" shape
            CreateChildShape(AutoShapeType.DownArrow, new RectangleF(381f, 153f, 29.25f, 72.5f), 0, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document);

            //Create a RoundedRectangle shape with "Development" text
            CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(135f, 226.45f, 110f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(104, 57, 157), "Development", groupShape, document);

            //Create a RoundedRectangle shape with "Production" text
            CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(341f, 226.5f, 110f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(149, 50, 118), "Production", groupShape, document);

            //Create a RoundedRectangle shape with "Sales" text
            CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(546.75f, 226.5f, 110f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(179, 63, 62), "Sales", groupShape, document);

            //Create a DownArrow shape to connect with "Software" and "Hardware" shape
            CreateChildShape(AutoShapeType.DownArrow, new RectangleF(177f, 265.5f, 25.5f, 20.25f), 0, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document);

            //Create a DownArrow shape to connect with "Series" and "Parts" shape
            CreateChildShape(AutoShapeType.DownArrow, new RectangleF(383.25f, 265.5f, 25.5f, 20.25f), 0, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document);

            //Create a DownArrow shape to connect with "North" and "South" shape
            CreateChildShape(AutoShapeType.DownArrow, new RectangleF(588.75f, 266.25f, 25.5f, 20.25f), 0, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document);

            //Create a BentUpArrow shape to connect with "Software" shape
            CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(129.5f, 286.5f, 60f, 33f), 180, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document);

            //Create a BentUpArrow shape to connect with "Hardware" shape
            CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(190.5f, 286.5f, 60f, 33f), 180, true, false, Syncfusion.Drawing.Color.White, null, groupShape, document);

            //Create a BentUpArrow shape to connect with "Series" shape
            CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(336f, 287.25f, 60f, 33f), 180, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document);

            //Create a BentUpArrow shape to connect with "Parts" shape
            CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(397f, 287.25f, 60f, 33f), 180, true, false, Syncfusion.Drawing.Color.White, null, groupShape, document);

            //Create a BentUpArrow shape to connect with "North" shape
            CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(541.5f, 288f, 60f, 33f), 180, false, false, Syncfusion.Drawing.Color.White, null, groupShape, document);

            //Create a BentUpArrow shape to connect with "South" shape
            CreateChildShape(AutoShapeType.BentUpArrow, new RectangleF(602.5f, 288f, 60f, 33f), 180, true, false, Syncfusion.Drawing.Color.White, null, groupShape, document);

            //Create a RoundedRectangle shape with "Software" text
            CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(93f, 320.25f, 90f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(23, 187, 189), "Software", groupShape, document);

            //Create a RoundedRectangle shape with "Hardware" text
            CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(197.2f, 320.25f, 90f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(24, 159, 106), "Hardware", groupShape, document);

            //Create a RoundedRectangle shape with "Series" text
            CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(299.25f, 320.25f, 90f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(23, 187, 189), "Series", groupShape, document);

            //Create a RoundedRectangle shape with "Parts" text
            CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(404.2f, 320.25f, 90f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(24, 159, 106), "Parts", groupShape, document);

            //Create a RoundedRectangle shape with "North" text
            CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(505.5f, 321.75f, 90f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(23, 187, 189), "North", groupShape, document);

            //Create a RoundedRectangle shape with "South" text
            CreateChildShape(AutoShapeType.RoundedRectangle, new RectangleF(609.7f, 321.75f, 90f, 40f), 0, false, false, Syncfusion.Drawing.Color.FromArgb(24, 159, 106), "South", groupShape, document);

            string       filename     = "";
            string       contenttype  = "";
            MemoryStream outputStream = new MemoryStream();

            if (this.pdfButton.IsChecked != null && (bool)this.pdfButton.IsChecked)
            {
                filename    = "GroupShapes.pdf";
                contenttype = "application/pdf";
                DocIORenderer renderer = new DocIORenderer();
                PdfDocument   pdfDoc   = renderer.ConvertToPDF(document);
                pdfDoc.Save(outputStream);
                pdfDoc.Close();
            }
            else
            {
                filename    = "GroupShapes.docx";
                contenttype = "application/msword";
                document.Save(outputStream, FormatType.Docx);
            }
            document.Close();
            if (Device.RuntimePlatform == Device.UWP)
            {
                DependencyService.Get <ISaveWindowsPhone>()
                .Save(filename, contenttype, outputStream);
            }
            else
            {
                DependencyService.Get <ISave>().Save(filename, contenttype, outputStream);
            }
        }
Ejemplo n.º 55
0
        private void OnConvertButtonClicked(object sender, EventArgs e)
        {
            //Instantiate excel engine
            ExcelEngine excelEngine = new ExcelEngine();
            //Excel application
            IApplication application = excelEngine.Excel;

            //Get assembly manifest resource
            Assembly assembly = Assembly.GetExecutingAssembly();
            Stream   fileStream;

            if (this.checkfontName.Checked || this.checkfontStream.Checked)
            {
                application.SubstituteFont += new Syncfusion.XlsIO.Implementation.SubstituteFontEventHandler(SubstituteFont);
                fileStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Template.InvoiceTemplate.xlsx");
            }
            else
            {
                fileStream = assembly.GetManifestResourceStream("SampleBrowser.Samples.XlsIO.Template.ExcelToPDF.xlsx");
            }

            //Open Workbook
            IWorkbook workbook = application.Workbooks.Open(fileStream);

            XlsIORenderer         renderer = new XlsIORenderer();
            XlsIORendererSettings settings = new XlsIORendererSettings();

            settings.IsConvertBlankPage = false;

            int index = spinner.SelectedItemPosition;

            if (index == 0)
            {
                settings.LayoutOptions = LayoutOptions.NoScaling;
            }
            else if (index == 1)
            {
                settings.LayoutOptions = LayoutOptions.FitAllRowsOnOnePage;
            }
            else if (index == 2)
            {
                settings.LayoutOptions = LayoutOptions.FitAllColumnsOnOnePage;
            }
            else
            {
                settings.LayoutOptions = LayoutOptions.FitSheetOnOnePage;
            }

            settings.EnableFormFields = true;

            PdfDocument  pdfDocument  = renderer.ConvertToPDF(workbook, settings);
            MemoryStream memoryStream = new MemoryStream();

            pdfDocument.Save(memoryStream);
            pdfDocument.Close(true);

            workbook.Close();
            excelEngine.Dispose();

            //Save and view the generated file.
            SaveAndView(memoryStream, "application/pdf");
        }
Ejemplo n.º 56
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 outlines when the document is opened
            document.Viewer.PageMode = PdfPageMode.Outlines;

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

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

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

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

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

            float crtXPos = 10;
            float crtYPos = 20;

            #region Create Table of contents

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            #endregion

            #region Create Chapter 1 content and the link from TOC

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

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

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

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

            #endregion

            #region Create Subchapter 1 content and the link from TOC

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

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

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

            #endregion

            #region Create Subchapter 2 content and the link from TOC

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

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

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

            #endregion

            #region Create Chapter 2 content and the link from TOC

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

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

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

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

            #endregion

            #region Create Subchapter 1 content and the link from TOC

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

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

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

            #endregion

            #region Create Subchapter 2 content and the link from TOC

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

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

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

            #endregion

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

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

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

                return(fileResult);
            }
            finally
            {
                document.Close();
            }
        }
Ejemplo n.º 57
0
 public void Dispose()
 {
     document?.Close();
 }
Ejemplo n.º 58
0
        void Button_Click(object sender, RoutedEventArgs e)
        {
            File.WriteAllText("file.html", html);
            string file = "File.pdf";

            try
            {
                MessageBox.Show("Conversion  ... ");
                // read parameters from the form
                string htmlString = html;
                string baseUrl    = ".";


                int webPageWidth = 1024;
                try
                {
                    webPageWidth = Convert.ToInt32(htmlString);
                }
                catch { }

                int webPageHeight = 0;
                try
                {
                    webPageHeight = Convert.ToInt32(htmlString);
                }
                catch { }

                // instantiate a html to pdf converter object
                HtmlToPdf converter = new HtmlToPdf();

                // set converter options
                converter.Options.AutoFitWidth = HtmlToPdfPageFitMode.AutoFit;
                converter.Options.PdfPageSize  = PdfPageSize.A4;
                converter.Options.WebPageWidth = 630;

                converter.Options.PdfPageOrientation = PdfPageOrientation.Portrait;
                converter.Options.MarginLeft         = 10;
                converter.Options.MarginRight        = 10;
                converter.Options.MarginTop          = 20;
                converter.Options.MarginBottom       = 20;


                // create a new pdf document converting an url
                PdfDocument doc = converter.ConvertHtmlString(htmlString, baseUrl);

                // save pdf document
                doc.Save(file);

                // close pdf document
                doc.Close();
            }
            catch (Exception ex)
            {
                return;
            }
            try
            {
                System.Diagnostics.Process.Start("File.pdf");
            }
            catch
            {
            }

            MessageBox.Show("Done");
        }
        private void button1_Click(object sender, System.EventArgs e)
        {
            try
            {
                // Creating a new document.
                WordDocument document = new WordDocument();
                document.EnsureMinimal();
                //Set Margin of the document
                document.LastSection.PageSetup.Margins.All = 72;
                // Reading Arabic text from text file.
                StreamReader s    = new StreamReader(@"..\..\..\..\..\..\..\Common\Data\DocIO\Arabic.txt", System.Text.Encoding.ASCII);
                string       text = s.ReadToEnd();

                // Appending Arabic text to the document.
                document.LastParagraph.ParagraphFormat.Bidi = true;
                IWTextRange txtRange = document.LastParagraph.AppendText(text);
                txtRange.CharacterFormat.Bidi = true;

                // Set the RTL text font size.
                txtRange.CharacterFormat.FontSizeBidi = 16;

                //Save as doc format
                if (wordDocRadioBtn.Checked)
                {
                    //Saving the document to disk.
                    document.Save("Sample.doc");

                    //Message box confirmation to view the created document.
                    if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
                        System.Diagnostics.Process.Start("Sample.doc");
                        //Exit
                        this.Close();
                    }
                }
                //Save as docx format
                else if (wordDocxRadioBtn.Checked)
                {
                    //Saving the document as .docx
                    document.Save("Sample.docx", FormatType.Docx);
                    //Message box confirmation to view the created document.
                    if (MessageBoxAdv.Show("Do you want to view the generated Word document?", "Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        try
                        {
                            //Launching the MS Word file using the default Application.[MS Word Or Free WordViewer]
                            System.Diagnostics.Process.Start("Sample.docx");
                            //Exit
                            this.Close();
                        }
                        catch (Win32Exception ex)
                        {
                            MessageBoxAdv.Show("Microsoft Word Viewer or Microsoft Word is not installed in this system");
                            Console.WriteLine(ex.ToString());
                        }
                    }
                }
                //Save as pdf format
                else if (pdfRadioBtn.Checked)
                {
                    DocToPDFConverter converter = new DocToPDFConverter();
                    //Convert word document into PDF document
                    PdfDocument pdfDoc = converter.ConvertToPDF(document);
                    document.Close();
                    converter.Dispose();
                    //Save the pdf file
                    pdfDoc.Save("Sample.pdf");
                    pdfDoc.Close(true);
                    //Message box confirmation to view the created document.
                    if (MessageBoxAdv.Show("Do you want to view the generated PDF?", " Document has been created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    {
                        try
                        {
                            System.Diagnostics.Process.Start("Sample.pdf");
                            //Exit
                            this.Close();
                        }
                        catch (Exception ex)
                        {
                            MessageBoxAdv.Show("PDF Viewer is not installed in this system");
                            Console.WriteLine(ex.ToString());
                        }
                    }
                }
                else
                {
                    // Exit
                    this.Close();
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            }
        }
Ejemplo n.º 60
0
        public virtual void XObjectIterativeReference()
        {
            // The input file contains circular references chain, see: 8 0 R -> 10 0 R -> 4 0 R -> 8 0 R.
            // Copying of such file even with smart mode is expected to be handled correctly.
            String      src               = SOURCE_FOLDER + "checkboxes_XObject_iterative_reference.pdf";
            String      dest              = DESTINATION_FOLDER + "checkboxes_XObject_iterative_reference_out.pdf";
            PdfDocument pdf               = new PdfDocument(new PdfWriter(dest).SetSmartMode(true));
            PdfReader   pdfReader         = new PdfReader(src);
            PdfDocument sourceDocumentPdf = new PdfDocument(pdfReader);

            sourceDocumentPdf.CopyPagesTo(1, sourceDocumentPdf.GetNumberOfPages(), pdf);
            //map <object pdf, count>
            Dictionary <String, int?> mapIn  = new Dictionary <String, int?>();
            Dictionary <String, int?> mapOut = new Dictionary <String, int?>();
            //map <object pdf, list of object id referenceing that podf object>
            Dictionary <String, IList <int> > mapOutId = new Dictionary <String, IList <int> >();
            PdfObject obj;

            //create helpful data structures from pdf output
            for (int i = 1; i < pdf.GetNumberOfPdfObjects(); i++)
            {
                obj = pdf.GetPdfObject(i);
                String      objString = obj.ToString();
                int?        count     = mapOut.Get(objString);
                IList <int> list;
                if (count == null)
                {
                    count = 1;
                    list  = new List <int>();
                    list.Add(i);
                }
                else
                {
                    count++;
                    list = mapOutId.Get(objString);
                }
                mapOut.Put(objString, count);
                mapOutId.Put(objString, list);
            }
            //create helpful data structures from pdf input
            for (int i = 1; i < sourceDocumentPdf.GetNumberOfPdfObjects(); i++)
            {
                obj = sourceDocumentPdf.GetPdfObject(i);
                String objString = obj.ToString();
                int?   count     = mapIn.Get(objString);
                if (count == null)
                {
                    count = 1;
                }
                else
                {
                    count++;
                }
                mapIn.Put(objString, count);
            }
            pdf.Close();
            //the following object is copied and reused. it appears 6 times in the original pdf file. just once in the output file
            String case1     = "<</BBox [0 0 20 20 ] /Filter /FlateDecode /FormType 1 /Length 12 /Matrix [1 0 0 1 0 0 ] /Resources <<>> /Subtype /Form /Type /XObject >>";
            int?   countOut1 = mapOut.Get(case1);
            int?   countIn1  = mapIn.Get(case1);

            NUnit.Framework.Assert.IsTrue(countOut1.Equals(1) && countIn1.Equals(6));
            //the following object appears 1 time in the original pdf file and just once in the output file
            String case2     = "<</BaseFont /ZapfDingbats /Subtype /Type1 /Type /Font >>";
            int?   countOut2 = mapOut.Get(case2);
            int?   countIn2  = mapIn.Get(case2);

            NUnit.Framework.Assert.IsTrue(countOut2.Equals(countIn2) && countOut2.Equals(1));
            //from the original pdf the object "<</BBox [0 0 20 20 ] /Filter /FlateDecode /FormType 1 /Length 70 /Matrix [1 0 0 1 0 0 ] /Resources <</Font <</ZaDb 2 0 R >> >> /Subtype /Form /Type /XObject >>";
            //is going to be found changed in the output pdf referencing the referenced object with another id which is retrieved through the hashmap
            String case3     = "<</BaseFont /ZapfDingbats /Subtype /Type1 /Type /Font >>";
            int?   countIdIn = mapOutId.Get(case3)[0];
            //EXPECTED to be as the original but with different referenced object and marked as modified
            String expected = "<</BBox [0 0 20 20 ] /Filter /FlateDecode /FormType 1 /Length 70 /Matrix [1 0 0 1 0 0 ] /Resources <</Font <</ZaDb "
                              + countIdIn + " 0 R Modified; >> >> /Subtype /Form /Type /XObject >>";

            NUnit.Framework.Assert.IsTrue(mapOut.Get(expected).Equals(1));
        }