AddTitle() публичный Метод

Adds the title to a Document.
public AddTitle ( string title ) : bool
title string the title
Результат bool
Пример #1
18
        public ReportPdf(Stream Output, Layout Layout, Template Template, Dictionary<string, string> ConfigParams)
            : base(Output, Layout, Template, ConfigParams)
        {
            Rectangle pageSize = new Rectangle(mm2pt(Template.PageSize.Width), mm2pt(Template.PageSize.Height));

            // Initialization
            m_Document = new Document(pageSize, mm2pt(Template.Margin.Left), mm2pt(Template.Margin.Right), mm2pt(Template.Margin.Top), mm2pt(Template.Margin.Bottom));
            m_Writer = PdfWriter.GetInstance(m_Document, Output);

            m_Document.AddCreationDate();
            m_Document.AddCreator("StrengthReport http://dev.progterv.info/strengthreport) and KeePass (http://keepass.info)");
            m_Document.AddKeywords("report");
            m_Document.AddTitle(Layout.Title+" (report)");

            // Header
            HeaderFooter header = new HeaderFooter(new Phrase(Layout.Title+", "+DateTime.Now.ToString(), m_Template.ReportFooter.getFont()), false);
            header.Alignment = Template.ReportFooter.getAlignment();
            m_Document.Header = header;

            // Footer
            HeaderFooter footer = new HeaderFooter(new Phrase(new Chunk("Page ", m_Template.ReportFooter.getFont())), new Phrase(new Chunk(".", m_Template.ReportFooter.getFont())));
            footer.Alignment = Template.ReportFooter.getAlignment();
            m_Document.Footer = footer;

            // TODO: Metadata
            // Open document
            m_Document.Open();

            // Report Heading
            {
                PdfPTable reportTitle = new PdfPTable(1);
                PdfPCell titleCell = new PdfPCell(new Phrase(Layout.Title, m_Template.ReportHeader.getFont()));
                titleCell.Border = 0;
                titleCell.FixedHeight = mm2pt(m_Template.ReportHeader.Height);
                titleCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                titleCell.HorizontalAlignment = m_Template.ReportHeader.getAlignment();
                reportTitle.AddCell(titleCell);
                reportTitle.WidthPercentage = 100;
                m_Document.Add(reportTitle);
            }

            // Create main table
            m_Table = new PdfPTable(Layout.GetColumnWidths());
            m_Table.WidthPercentage = 100;
            m_Table.HeaderRows = 1;
            foreach (LayoutElement element in Layout) {
                PdfPCell cell = new PdfPCell(new Phrase(element.Title, m_Template.Header.getFont()));
                cell.BackgroundColor = m_Template.Header.Background.ToColor();
                cell.MinimumHeight = mm2pt(m_Template.Header.Height);
                cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                m_Table.AddCell(cell);
            }

            m_colorRow = new CMYKColor[] { m_Template.Row.BackgroundA.ToColor(), m_Template.Row.BackgroundB.ToColor() };
        }
Пример #2
5
        private void btnCreateReport_Click(object sender, EventArgs e)
        {
            // _______________________________________________________1_______________________________________________________
            // Setting pagetype, margins and encryption
            iTextSharp.text.Rectangle pageType = iTextSharp.text.PageSize.A4;
            float marginLeft = 72;
            float marginRight = 36;
            float marginTop = 60;
            float marginBottom = 50;
            String reportName = "Test.pdf";

            Document report = new Document(pageType, marginLeft, marginRight, marginTop, marginBottom);
            PdfWriter writer = PdfWriter.GetInstance(report, new FileStream(reportName, FileMode.Create));
            //writer.SetEncryption(PdfWriter.STRENGTH40BITS, "Good", "Bad", PdfWriter.ALLOW_COPY);
            report.Open();

            // _______________________________________________________2_______________________________________________________
            // Setting Document properties(Meta data)
            // 1. Title
            // 2. Subject
            // 3. Keywords
            // 4. Creator
            // 5. Author
            // 6. Header
            report.AddTitle("Employee Details Report");
            report.AddSubject("This file is generated for administrative use only");
            report.AddKeywords("Civil Security Department, Employee Management System, Version 1.0.0, Report Generator");
            report.AddCreator("Ozious Technologies");
            report.AddAuthor("Eranga Heshan");
            report.AddHeader("Owner", "Civil Security Department");

            // _______________________________________________________3_______________________________________________________
            // Setup the font factory
            /*
            int totalFonts = FontFactory.RegisterDirectory("C:\\WINDOWS\\Fonts");
            StringBuilder sb = new StringBuilder();
            foreach (string fontname in FontFactory.RegisteredFonts) { sb.Append(fontname + "\n"); }
            report.Add(new Paragraph("All Fonts:\n" + sb.ToString()));
            */
            iTextSharp.text.Font fontHeader_1 = FontFactory.GetFont("Calibri", 30, iTextSharp.text.Font.BOLD, new iTextSharp.text.BaseColor(0, 0, 0));
            iTextSharp.text.Font fontHeader_2 = FontFactory.GetFont("Calibri", 15, iTextSharp.text.Font.BOLD, new iTextSharp.text.BaseColor(125, 125, 125));

            // _______________________________________________________x_______________________________________________________
            // Create header
            PdfContentByte cb = writer.DirectContent;
            cb.MoveTo(marginLeft, marginTop);
            cb.LineTo(500, marginTop);
            cb.Stroke();

            Paragraph paraHeader_1 = new Paragraph("Civil Security Department", fontHeader_1);
            paraHeader_1.Alignment = Element.ALIGN_CENTER;
            paraHeader_1.SpacingAfter = 0f;
            report.Add(paraHeader_1);

            Paragraph paraHeader_2 = new Paragraph("Employee Detailed Report", fontHeader_2);
            paraHeader_2.Alignment = Element.ALIGN_CENTER;
            paraHeader_2.SpacingAfter = 10f;
            report.Add(paraHeader_2);

            // _______________________________________________________x_______________________________________________________
            // Adding employee image
            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imgEmployee.ImageLocation);
            img.ScaleToFit(100f, 100f);
            img.Border = iTextSharp.text.Rectangle.BOX;
            img.BorderColor = iTextSharp.text.BaseColor.BLACK;
            img.BorderWidth = 5f;
            img.Alignment = iTextSharp.text.Image.TEXTWRAP | iTextSharp.text.Image.ALIGN_RIGHT | iTextSharp.text.Image.ALIGN_TOP;
            img.IndentationLeft = 50f;
            img.SpacingAfter = 20f;
            img.SpacingBefore = 20f;
            report.Add(img);

            Paragraph para1 = new Paragraph("Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... ");
            para1.Alignment = Element.ALIGN_JUSTIFIED;
            report.Add(para1);

            report.Close();
            this.Close();
        }
 /// <summary>
 /// 读取或创建Pdf文档并打开写入文件流
 /// </summary>
 /// <param name="fileName"></param>
 /// <param name="folderPath"></param>
 public Document GetOrCreatePDF(string fileName, string folderPath)
 {
     string filePath = folderPath + fileName;
     FileStream fs = null;
     if (!File.Exists(filePath))
     {
         fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
     }
     else
     {
         fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.None);
     }
     //获取A4纸尺寸
     Rectangle rec = new Rectangle(PageSize.A4);
     Document doc = new Document(rec);
     //创建一个 iTextSharp.text.pdf.PdfWriter 对象: 它有助于把Document书写到特定的FileStream:
     PdfWriter writer = PdfWriter.GetInstance(doc, fs);
     doc.AddTitle(fileName.Remove(fileName.LastIndexOf('.')));
     doc.AddSubject(fileName.Remove(fileName.LastIndexOf('.')));
     doc.AddKeywords("Metadata, iTextSharp 5.4.4, Chapter 1, Tutorial");
     doc.AddCreator("MCS");
     doc.AddAuthor("Chingy");
     doc.AddHeader("Nothing", "No Header");
     //打开 Document:
     doc.Open();
     ////关闭 Document:
     //doc.Close();
     return doc;
 }
Пример #4
1
        public void Build()
        {
            if (artUrls != null)
            {
                Build2();
                return;
            }
            Document document = new Document();
            PdfWriter.GetInstance(document, new FileStream(baseDir + _fileName, FileMode.Create));
            document.Open();
            document.AddTitle(_title);

            Font ft = new Font(baseFT, 12);

            int cnt = items.Count;

            for (int i = cnt - 1; i >= 0; i--)
            {
                var entity = items[i];
                if (!entity.IsDown)
                {
                    continue;
                }
                _callback("获取文章 " + (cnt - i) + "/" + cnt + ":" + entity.Title);

                document.Add(GetChapter(entity));
            }
            document.Close();
        }
Пример #5
1
        // From <ClickButt> -> PdfConnector PdfCreatora <- PdfCreator(naemBank,Bodytext)
        // Form <Image> <- PdfConnector -- tworzyć pdf |
        public Form1() 
        {
            while (!fileBanksLists.EndOfStream)
            {
                    InitializeComponent();
            
                     using (FileStream file = new FileStream(String.Format(path, nameBank), FileMode.Create))
                    {

                        Document document = new Document(PageSize.A7);
                        PdfWriter writer = PdfWriter.GetInstance(document, file);
              
                        /// Create metadate pdf file
                        document.AddAuthor(nameBank);
                        document.AddLanguage("pl");
                        document.AddSubject("Payment transaction");
                        document.AddTitle("Transaction");
                        document.AddKeywords("OutcomingNumber :" + OutcomingNumber);
                        document.AddKeywords("IncomingNumber :" + IncomingNumber);
                        /// Create text in pdf file
                        document.Open();
                        document.Add(new Paragraph(_przelew + "\n"));
                        document.Add(new Paragraph(String.Format("Bank {0}: zaprasza\n", nameBank)));
                        document.Add(new Paragraph(DateTime.Now.ToString()));
                        document.Close();
                        writer.Close();
                        file.Close();
                    }
            }
            
            
        }
Пример #6
1
        private static void Main()
        {
            const string path = @"C:\Users\Santhosh\AppData\test.pdf";
            if (File.Exists(path))
                File.Delete(path);
            var doc = new Document();
            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(path, FileMode.Create));
            // Metadata
            doc.AddCreator("");
            doc.AddTitle("General Receipt");
            // Add content
            doc.Open();

            PdfContentByte cb = writer.DirectContent;

            cb.SetLineWidth(0.1f);
            cb.Rectangle(50f, 300f, 500f, 70f);
            cb.Stroke();

            doc.Close();
        }
Пример #7
0
 public static void GeneratePdfSingleDataType(string filePath, string title, string content)
 {
     try
     {
         Logger.LogI("GeneratePDF -> " + filePath);
         var doc = new Document(PageSize.A3, 36, 72, 72, 144);
         using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
         {
             PdfWriter.GetInstance(doc, fs);
             doc.Open();
             doc.AddTitle(title);
             doc.AddAuthor(Environment.MachineName);
             doc.Add(
                 new Paragraph("Title : " + title + Environment.NewLine + "ServerName : " +
                               Environment.MachineName +
                               Environment.NewLine + "Author : " + Environment.UserName));
             doc.NewPage();
             doc.Add(new Paragraph(content));
             doc.Close();
         }
     }
     catch (Exception ex)
     {
         Logger.LogE(ex.Source + " -> " + ex.Message + "\n" + ex.StackTrace);
     }
 }
        public bool CreateReport(DataView theData)
        {
            bool isSuccessful = false;
            var  document     = new iTextSharp.text.Document(PageSize.HALFLETTER.Rotate());

            try
            {
                //set up RunReport event overrides & create doc
                PartialPaymentDetailReport events = this;

                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(reportTempFileFullName, FileMode.Create));
                writer.PageEvent = events;

                //set up tables, etc...
                var   table = new PdfPTable(10);
                var   cell  = new PdfPCell();
                Image gif   = Image.GetInstance(Resources.logo, BaseColor.WHITE);

                _reportFont          = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL);
                _reportFontLargeBold = FontFactory.GetFont("Arial", 10, iTextSharp.text.Font.BOLD);

                gif.ScalePercent(35);

                document.SetPageSize(PageSize.HALFLETTER.Rotate());
                document.SetMargins(5, 5, 10, 45);
                document.AddTitle(_title + ": " + DateTime.Now.ToString("MM/dd/yyyy"));

                ReportHeader(table, gif);

                CustomerData(table, theData);
                PartialPaymentData(table, theData);
                table.SetWidthPercentage(new float[]
                {
                    50F, 100F, 20F, 70F, 90F, 50F, 50F, 50F, 70F, 70F
                }, PageSize.HALFLETTER.Rotate());

                ReportDetailHeader(table);

                ReportDetail(table, theData);

                ReportLines(table, true, string.Empty, true, _reportFont);
                document.Open();
                document.Add(table);
                document.Close();

                isSuccessful = true;
            }
            catch (DocumentException de)
            {
                ReportError      = de.Message;
                ReportErrorLevel = (int)LogLevel.ERROR;
            }
            catch (IOException ioe)
            {
                ReportError      = ioe.Message;
                ReportErrorLevel = (int)LogLevel.ERROR;
            }

            return(isSuccessful);
        }
Пример #9
0
        public void CreatePdf(Project project, Stream writeStream)
        {
            var document = new Document();
            var writer = PdfWriter.GetInstance(document, writeStream);

            // landscape
            document.SetPageSize(PageSize.A4.Rotate());
            document.SetMargins(36f, 36f, 36f, 36f); // 0.5 inch margins

            // metadata
            document.AddCreator("EstimatorX.com");
            document.AddKeywords("estimation");
            document.AddAuthor(project.Creator);
            document.AddSubject(project.Name);
            document.AddTitle(project.Name);
            
            document.Open();

            AddName(project, document);
            AddDescription(project, document);
            AddAssumptions(project, document);
            AddFactors(project, document);
            AddTasks(project, document);
            AddSummary(project, document);

            writer.Flush();
            document.Close();
        }
Пример #10
0
        public bool TryCreatePdf(string nameBank)
        {
            try
            {
                using (FileStream file = new FileStream(String.Format(path,nameBank), FileMode.Create))
                {
                    Document document = new Document(PageSize.A7);
                    PdfWriter writer = PdfWriter.GetInstance(document, file);

                    /// Create metadate pdf file
                    document.AddAuthor("");
                    document.AddLanguage("pl");
                    document.AddSubject("Payment transaction");
                    document.AddTitle("Transaction");
                    /// Create text in pdf file
                    document.Open();
                    document.Add(new Paragraph(_przelew+"\n"));
                    document.Add(new Paragraph(String.Format("Bank {0}: zaprasza\n",nameBank)));
                    document.Add(new Paragraph(DateTime.Now.ToString()));
                    document.Close();
                    writer.Close();
                    file.Close();
                    return true;
                }
            }
            catch (SystemException ex)
            {
                return false;
            }
        }
Пример #11
0
        //Alım Geçmişi Pdf Rapor Butonu
        private void PdfButton_Click(object sender, EventArgs e)
        {
            iTextSharp.text.Document pdfDosya = new iTextSharp.text.Document();

            PdfWriter.GetInstance(pdfDosya, new FileStream("D:Rapor.pdf", FileMode.Create));
            pdfDosya.Open();
            pdfDosya.AddCreator("Swap - Modern Dünyada Tarıma Dair Alışveriş");
            pdfDosya.AddAuthor("Kullanıcı");
            pdfDosya.AddTitle("SATIN ALMA RAPORU");

            SqlCommand     komut = new SqlCommand("Select * From AlimKayitTablosu Where Tarih BETWEEN @t1 and @t2 and KullaniciID=" + Login.UserId, baglanti.baglanti());
            SqlDataAdapter data  = new SqlDataAdapter(komut);

            data.SelectCommand.Parameters.AddWithValue("@t1", StartDatePicker.Value);
            data.SelectCommand.Parameters.AddWithValue("@t2", EndDatePicker.Value);
            SqlDataReader oku = komut.ExecuteReader();

            string id, tarih, miktar, alimtutar, komisyon, metin;

            metin = "KullaniciID / Tarih / Miktar / AlimTutari / UygulamaKomsiyon \n";
            pdfDosya.Add(new Paragraph(metin));
            while (oku.Read())
            {
                id        = Convert.ToString(oku["KullaniciID"]);
                tarih     = Convert.ToString(oku["Tarih"]);
                miktar    = Convert.ToString(oku["Miktar"]);
                alimtutar = Convert.ToString(oku["AlimTutari"]);
                komisyon  = Convert.ToString(oku["UygulamaKomisyonu"]);
                metin     = id + "  -  " + tarih + "  -  " + miktar + "  -  " + alimtutar + "  -  " + komisyon + "\n";
                pdfDosya.Add(new Paragraph(metin));
            }
            pdfDosya.Close();
            baglanti.baglanti().Close();
        }
Пример #12
0
        public void CreatePDF()
        {
            System.IO.FileStream fs = new FileStream("GeneratedDocument.pdf", FileMode.Create);

            iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.A4, 25, 25, 30, 30);

            PdfWriter writer = PdfWriter.GetInstance(document, fs);

            document.AddAuthor("UCV");

            document.AddCreator("UCV");

            document.AddKeywords("Note");

            document.AddSubject("Situatie Scolara");

            document.AddTitle("Situatie scolara");

            document.Open();

            document.Close();

            writer.Close();

            fs.Close();
        }
        public bool CreateReport()
        {
            LoadPotentialCategories();
            _TotalIncome = new ReportObject.Snapshot();
            bool isSuccessful = false;

            iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.LEGAL);

            try
            {
                //set up RunReport event overrides & create doc
                string reportFileName = Path.GetFullPath(reportObject.ReportTempFileFullName);
                if (!Directory.Exists(Path.GetDirectoryName(reportFileName)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(reportFileName));
                }
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(reportFileName, FileMode.Create));
                writer.PageEvent = this;

                PdfPTable table = new PdfPTable(_Columns);
                Image     gif   = Image.GetInstance(Resources.logo, BaseColor.WHITE);
                gif.ScalePercent(35);

                _reportFont = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL);

                document.AddTitle(reportObject.ReportTitle);

                document.SetPageSize(PageSize.LETTER);
                document.SetMargins(-50, -55, 10, 45);

                table.HeaderRows = 2;
                PrintReportHeader(table, gif);
                PrintReportDetailHeader(table);
                table.SetWidths(new float[] { 1.5f, 2, 1, 1, 1.5f });
                foreach (PotentialCategoryInfo categoryInfo in _PotentialCategories)
                {
                    PrintReportDetail(table, categoryInfo);
                }
                PrintReportDetailDisclaimer(table);

                document.Open();
                document.Add(table);
                document.Close();

                isSuccessful = true;
            }
            catch (DocumentException de)
            {
                reportObject.ReportError      = de.Message;
                reportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            catch (IOException ioe)
            {
                reportObject.ReportError      = ioe.Message;
                reportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }

            return(isSuccessful);
        }
        public bool CreateReport()
        {
            bool isSuccessful = false;

            iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.LEGAL.Rotate());
            try
            {
                //set up RunReport event overrides & create doc
                //_pageCount = 1;
                ATFOpenRecordsReport events = this;
                PdfWriter            writer = PdfWriter.GetInstance(document, new FileStream(ReportObject.ReportTempFileFullName, FileMode.Create));
                writer.PageEvent = events;

                MultiColumnText columns = new MultiColumnText(document.PageSize.Top - 148, document.PageSize.Height - (170));
                columns.AddSimpleColumn(-51, document.PageSize.Width + 60);

                //set up tables, etc...
                var table = new PdfPTable(21);
                table.WidthPercentage = 85;// document.PageSize.Width;
                var cell = new PdfPCell();
                var gif  = Image.GetInstance(Common.Properties.Resources.logo, BaseColor.WHITE);
                gif.ScalePercent(25);
                runReport = new RunReport();
                document.Open();
                document.SetPageSize(PageSize.LEGAL.Rotate());
                document.SetMargins(-100, -100, 10, 35);
                document.AddTitle(string.Format("{0}: {1}", ReportObject.ReportTitle, DateTime.Now.ToString("MM/dd/yyyy")));

                //here add detail
                WriteDetail(table, 21);
                columns.AddElement(table);
                document.Add(columns);

                string          gunText          = "Total Number of Guns: " + TotalNumberOfGuns;
                MultiColumnText columnBottomPage = new MultiColumnText(document.PageSize.Bottom, 25);
                columnBottomPage.AddSimpleColumn(-51, document.PageSize.Width + 60);
                PdfPTable tableBottom = new PdfPTable(1);
                tableBottom.WidthPercentage = 85;// document.PageSize.Width;
                WriteCell(tableBottom, gunText, ReportFontLargeBold, 1, Element.ALIGN_LEFT, Rectangle.NO_BORDER);
                columnBottomPage.AddElement(tableBottom);
                document.Add(columnBottomPage);

                document.Close();
                //OpenFile(ReportObject.ReportTempFileFullName);
                //CreateReport();
                isSuccessful = true;
            }
            catch (DocumentException de)
            {
                ReportObject.ReportError      = de.Message;
                ReportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            catch (IOException ioe)
            {
                ReportObject.ReportError      = ioe.Message;
                ReportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            return(isSuccessful);
        }
Пример #15
0
 private void SetPageProperties()
 {
     this.pageSize = new PDFPageSize();
     doc.SetPageSize(new iTextSharp.text.Rectangle(pageSize.Width, pageSize.Height));
     doc.SetMargins(pageSize.LeftMargin, pageSize.RightMargin, pageSize.TopMargin, pageSize.BottomMargin);
     doc.AddTitle("POC - Principal form");
     doc.AddCreator("CD ABM Logic");
 }
        public bool CreateReport(System.Data.DataSet theData)
        {
            bool isSuccessful = false;

            iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.LETTER.Rotate());

            try
            {
                //set up RunReport event overrides & create doc
                LoanListingReport events = this;

                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(reportTempFileFullName, FileMode.Create));
                writer.PageEvent = events;

                //set up tables, etc...
                PdfPTable table = new PdfPTable(18);
                PdfPCell  cell  = new PdfPCell();
                Image     gif   = Image.GetInstance(Resources.logo, BaseColor.WHITE);

                _reportFont          = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL);
                _reportFontLargeBold = FontFactory.GetFont("Arial", 10, iTextSharp.text.Font.BOLD);

                gif.ScalePercent(35);

                document.SetPageSize(PageSize.LETTER.Rotate());
                document.SetMargins(20, 20, 10, 45);
                document.AddTitle("Loan Inquiry Listing Report : " + DateTime.Now.ToString("MM/dd/yyyy"));

                ReportHeader(table, gif);
                ColumnHeaders(table);

                table.SetWidthPercentage(new float[] { 35F, 45F, 45F, 45F, 75F, 40F, 45F, 55F, 40F, 55F, 45F, 45F, 40F, 50F, 25F, 25F, 25F, 25F },
                                         PageSize.LETTER.Rotate());

                table.HeaderRows = 8;

                ReportDetail(table, theData);
                ReportLines(table, true, "", true, _reportFont);

                document.Open();
                document.Add(table);
                document.Close();

                isSuccessful = true;
            }
            catch (DocumentException de)
            {
                ReportError      = de.Message;
                ReportErrorLevel = (int)LogLevel.ERROR;
            }
            catch (IOException ioe)
            {
                ReportError      = ioe.Message;
                ReportErrorLevel = (int)LogLevel.ERROR;
            }

            return(isSuccessful);
        }
        public void Build()
        {
            iTextSharp.text.Document doc = null;

            try
            {
                // Initialize the PDF document
                doc = new Document();
                iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc,
                    new System.IO.FileStream(System.IO.Directory.GetCurrentDirectory() + "\\ScienceReport.pdf",
                        System.IO.FileMode.Create));

                // Set margins and page size for the document
                doc.SetMargins(50, 50, 50, 50);
                // There are a huge number of possible page sizes, including such sizes as
                // EXECUTIVE, POSTCARD, LEDGER, LEGAL, LETTER_LANDSCAPE, and NOTE
                doc.SetPageSize(new iTextSharp.text.Rectangle(iTextSharp.text.PageSize.LETTER.Width,
                    iTextSharp.text.PageSize.LETTER.Height));

                // Add metadata to the document.  This information is visible when viewing the
                // document properities within Adobe Reader.
                doc.AddTitle("My Science Report");
                doc.AddCreator("M. Lichtenberg");
                doc.AddKeywords("paper airplanes");

                // Add Xmp metadata to the document.
                this.CreateXmpMetadata(writer);

                // Open the document for writing content
                doc.Open();

                // Add pages to the document
                this.AddPageWithBasicFormatting(doc);
                this.AddPageWithInternalLinks(doc);
                this.AddPageWithBulletList(doc);
                this.AddPageWithExternalLinks(doc);
                this.AddPageWithImage(doc, System.IO.Directory.GetCurrentDirectory() + "\\FinalGraph.jpg");

                // Add page labels to the document
                iTextSharp.text.pdf.PdfPageLabels pdfPageLabels = new iTextSharp.text.pdf.PdfPageLabels();
                pdfPageLabels.AddPageLabel(1, iTextSharp.text.pdf.PdfPageLabels.EMPTY, "Basic Formatting");
                pdfPageLabels.AddPageLabel(2, iTextSharp.text.pdf.PdfPageLabels.EMPTY, "Internal Links");
                pdfPageLabels.AddPageLabel(3, iTextSharp.text.pdf.PdfPageLabels.EMPTY, "Bullet List");
                pdfPageLabels.AddPageLabel(4, iTextSharp.text.pdf.PdfPageLabels.EMPTY, "External Links");
                pdfPageLabels.AddPageLabel(5, iTextSharp.text.pdf.PdfPageLabels.EMPTY, "Image");
                writer.PageLabels = pdfPageLabels;
            }
            catch (iTextSharp.text.DocumentException dex)
            {
                // Handle iTextSharp errors
            }
            finally
            {
                // Clean up
                doc.Close();
                doc = null;
            }
        }
Пример #18
0
        public bool CreateReport()
        {
            bool isSuccessful = false;
            var  document     = new iTextSharp.text.Document(PageSize.HALFLETTER.Rotate());

            try
            {
                //set up RunReport event overrides & create doc
                LayawayForefeitPickingSlip events = this;
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(ReportObject.ReportTempFileFullName, FileMode.Create));
                writer.PageEvent = events;

                MultiColumnText columns   = new MultiColumnText(document.PageSize.Top - 93, document.PageSize.Height - (93));
                float           pageLeft  = document.PageSize.Left;
                float           pageright = document.PageSize.Right;
                columns.AddSimpleColumn(-15, document.PageSize.Width + 13);

                //set up tables, etc...
                PdfPTable table = new PdfPTable(7);
                table.WidthPercentage = 85;// document.PageSize.Width;
                //table.WidthPercentage = 80;// document.PageSize.Width;
                table.TotalWidth = document.PageSize.Width;

                PdfPCell cell = new PdfPCell();
                Image    gif  = Image.GetInstance(Resources.logo, BaseColor.WHITE);
                gif.ScalePercent(25);
                runReport = new LayawayRunReports();
                document.Open();
                document.SetPageSize(PageSize.HALFLETTER.Rotate());
                document.SetMargins(-100, -100, 10, 45);
                document.AddTitle(ReportObject.ReportTitle + ": " + DateTime.Now.ToString("MM/dd/yyyy"));

                WritePaymentsDetails(table);
                columns.AddElement(table);
                document.Add(columns);
                document.Close();
                //OpenFile(ReportObject.ReportTempFileFullName);
                //CreateReport();
                isSuccessful = true;
            }
            catch (DocumentException de)
            {
                ReportObject.ReportError      = de.Message;;
                ReportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            catch (IOException ioe)
            {
                ReportObject.ReportError      = ioe.Message;;
                ReportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            catch (Exception e)
            {
                ReportObject.ReportError      = e.Message;;
                ReportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            return(isSuccessful);
        }
        public bool CreateReport(String icn, String description, System.Data.DataSet theData)
        {
            _icn         = icn;
            _description = description;

            bool isSuccessful = false;

            iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.LETTER.Rotate());
            try
            {
                //set up RunReport event overrides & create doc
                _pageCount = 1;
                StatusChangeReport events = this;
                PdfWriter          writer = PdfWriter.GetInstance(document, new FileStream(ReportObject.ReportTempFileFullName, FileMode.Create));
                writer.PageEvent = events;

                MultiColumnText columns   = new MultiColumnText(document.PageSize.Top - 100, document.PageSize.Height - (50));
                float           pageLeft  = document.PageSize.Left;
                float           pageright = document.PageSize.Right;
                columns.AddSimpleColumn(-150, document.PageSize.Width + 76);

                //set up tables, etc...
                PdfPTable table = new PdfPTable(6);
                table.WidthPercentage = 85;// document.PageSize.Width;
                PdfPCell cell = new PdfPCell();
                Image    gif  = Image.GetInstance(Resources.logo, BaseColor.WHITE);
                gif.ScalePercent(25);
                runReport = new RunReport();
                document.Open();
                document.SetPageSize(PageSize.LETTER.Rotate());
                document.SetMargins(-100, -100, 10, 45);
                document.AddTitle(ReportObject.ReportTitle + ": " + DateTime.Now.ToString("MM/dd/yyyy"));

                ReportColumns(table);

                //here add detail
                WriteDetail(table, 6, theData);
                columns.AddElement(table);
                document.Add(columns);
                document.Close();
                OpenFile(ReportObject.ReportTempFileFullName);
                //CreateReport(_icn, _description, theData);
                isSuccessful = true;
            }
            catch (DocumentException de)
            {
                ReportObject.ReportError      = de.Message;
                ReportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            catch (IOException ioe)
            {
                ReportObject.ReportError      = ioe.Message;
                ReportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            return(isSuccessful);
        }
        public bool CreateReport()
        {
            bool isSuccessful = false;

            iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.LETTER);
            try
            {
                //set up RunReport event overrides & create doc
                LayawayHistoryAndSchedule events = new LayawayHistoryAndSchedule();
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(reportObject.ReportTempFileFullName, FileMode.Create));
                writer.PageEvent = events;

                //set up tables, etc...
                PdfPTable table = new PdfPTable(8);
                Image     gif   = Image.GetInstance(Common.Properties.Resources.logo, BaseColor.WHITE);

                _reportFont          = FontFactory.GetFont("Arial", 7, iTextSharp.text.Font.NORMAL);
                _reportFontLargeBold = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.BOLD);
                _reportFontSmallBold = FontFactory.GetFont("Arial", 6, iTextSharp.text.Font.BOLD);
                gif.ScalePercent(25);
                runReport = new LayawayRunReports();

                document.SetPageSize(PageSize.LETTER);
                document.SetMargins(-50, -50, 10, 45);
                document.AddTitle(reportObject.ReportTitle + ": " + DateTime.Now.ToString("MM/dd/yyyy"));

                ReportHeader(table, gif);
                AddLines(1, table);
                ReportTitleAndOtherInfo(table);
                AddLines(1, table);
                ColumnHeaders(table);
                DrawLine(table, _reportFontLargeBold);
                //ReportDetail(table);
                //ReportSummary(table);
                WriteSchedule(table);
                table.HeaderRows = 11;
                document.Open();
                document.Add(table);
                document.Close();
                //OpenFile();
                //CreateReport();
                isSuccessful = true;
            }
            catch (DocumentException de)
            {
                reportObject.ReportError      = de.Message;
                reportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            catch (IOException ioe)
            {
                reportObject.ReportError      = ioe.Message;
                reportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            return(isSuccessful);
        }
        //create report
        public bool CreateReport()
        {
            bool isSuccessful = false;

            iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.LEGAL);

            try
            {
                //set up RunReport event overrides & create doc
                LoanAuditReport events = new LoanAuditReport();
                PdfWriter       writer = PdfWriter.GetInstance(document, new FileStream(reportObject.ReportTempFileFullName, FileMode.Create));
                writer.PageEvent = events;

                //set up tables, etc...
                PdfPTable table = new PdfPTable(23);
                PdfPCell  cell  = new PdfPCell();
                Image     gif   = Image.GetInstance(Resources.logo, BaseColor.WHITE);
                gif.ScalePercent(35);

                _reportFont               = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL);
                _reportFontLargeBold      = FontFactory.GetFont("Arial", 10, iTextSharp.text.Font.BOLD);
                _reportFontLargeUnderline = FontFactory.GetFont("Arial", 10, iTextSharp.text.Font.UNDERLINE);

                runReport = new RunReport();

                document.AddTitle(reportObject.ReportTitle + ": " + DateTime.Now.ToString("MM/dd/yyyy"));
                document.SetPageSize(PageSize.LEGAL.Rotate());
                document.SetMargins(-100, -100, 10, 45);

                ReportHeader(table, gif);
                ColumnHeaders(table);
                ReportDetail(table);
                ReportSummary(table);

                table.HeaderRows = 8;

                document.Open();
                document.Add(table);
                document.Close();

                isSuccessful = true;
            }
            catch (DocumentException de)
            {
                reportObject.ReportError      = de.Message;;
                reportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            catch (IOException ioe)
            {
                reportObject.ReportError      = ioe.Message;;
                reportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }

            return(isSuccessful);
        }
Пример #22
0
        public bool CreateReport(bool openFile)
        {
            var isSuccessful = false;

            //openFile = true; //comment out
            iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.HALFLETTER.Rotate());
            try
            {
                //set up RunReport event overrides & create doc
                InventoryChargeOffReport events = this;
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(ReportObject.ReportTempFileFullName, FileMode.Create));
                writer.PageEvent = events;

                MultiColumnText columns   = new MultiColumnText(document.PageSize.Top - 80, MultiColumnText.AUTOMATIC);
                float           pageLeft  = document.PageSize.Left;
                float           pageright = document.PageSize.Right;
                columns.AddSimpleColumn(1, document.PageSize.Width + 40);

                //set up tables, etc...
                PdfPTable table = new PdfPTable(5);
                table.WidthPercentage = 85;// document.PageSize.Width;
                PdfPCell cell = new PdfPCell();
                Image    gif  = Image.GetInstance(Resources.logo, BaseColor.WHITE);
                gif.ScalePercent(25);
                runReport = new RunReport();
                document.Open();
                document.SetPageSize(PageSize.HALFLETTER.Rotate());
                document.SetMargins(-100, -100, 10, 45);
                document.AddTitle(string.Format("{0}: {1}", ReportObject.ReportTitle, DateTime.Now.ToString("MM/dd/yyyy")));

                //here add detail
                WriteDetail(table, 5);
                columns.AddElement(table);
                document.Add(columns);
                document.Close();
                if (openFile)
                {
                    OpenFile(ReportObject.ReportTempFileFullName);
                }

                //CreateReport(true); //comment out
                isSuccessful = true;
            }
            catch (DocumentException de)
            {
                ReportObject.ReportError      = de.Message;
                ReportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            catch (IOException ioe)
            {
                ReportObject.ReportError      = ioe.Message;
                ReportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            return(isSuccessful);
        }
Пример #23
0
 protected void PDFOrganization_Click(object sender, EventArgs e)
 {
     Response.ContentType = "application/pdf";
     Response.AddHeader("content-disposition", "attachment;filename=LookupOrganization.pdf");
     Response.Cache.SetCacheability(HttpCacheability.NoCache);
     iTextSharp.text.Document orgListDoc = new iTextSharp.text.Document(PageSize.A4, 10f, 10f, 10f, 10f);
     orgListDoc.AddTitle("List of Registered Oranizations");
     orgListDoc.AddAuthor("Leban Mohamed");
     orgListDoc.AddLanguage("English");
     ExportPDF(OrganizationGrid, orgListDoc);
 }
Пример #24
0
 protected void ManagerPDF_Click(object sender, EventArgs e)
 {
     Response.ContentType = "application/pdf";
     Response.AddHeader("content-disposition", "attachment;filename=LookupManagers.pdf");
     Response.Cache.SetCacheability(HttpCacheability.NoCache);
     iTextSharp.text.Document managerListDoc = new iTextSharp.text.Document(PageSize.A4, 10f, 10f, 10f, 10f);
     managerListDoc.AddTitle("List of Managers");
     managerListDoc.AddAuthor("Leban Mohamed");
     managerListDoc.AddLanguage("English");
     ExportPDF(ManagerGrid, managerListDoc);
 }
        public bool CreateReport()
        {
            bool isSuccessful = false;

            iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.HALFLETTER);
            try
            {
                //set up RunReport event overrides & create doc
                PoliceSeizeReport events = new PoliceSeizeReport();
                PdfWriter         writer = PdfWriter.GetInstance(document, new FileStream(ReportTempFileFullName, FileMode.Create));
                writer.PageEvent = events;

                //set up tables, etc...
                PdfPTable table       = new PdfPTable(11);
                PdfPTable footerTable = new PdfPTable(11);
                PdfPCell  cell        = new PdfPCell();
                Image     gif         = Image.GetInstance(Common.Properties.Resources.logo, BaseColor.WHITE);
                footerTable.HorizontalAlignment = Rectangle.ALIGN_BOTTOM;
                _reportFont           = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL);
                _reportFontLargeBold  = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.BOLD);
                _reportFontUnderlined = FontFactory.GetFont("Arail", 8, iTextSharp.text.Font.UNDERLINE);

                gif.ScalePercent(20);
                runReport = new RunReport();

                document.SetPageSize(PageSize.HALFLETTER.Rotate());
                document.SetMargins(-40, -40, 5, 23);
                document.AddTitle(string.Empty);

                ReportHeader(table, writer);
                ReportDetail(table);
                ReportSummary(footerTable);

                table.HeaderRows = 11;
                document.Open();
                document.Add(table);
                document.Add(footerTable);
                document.Close();

                isSuccessful = true;
            }
            catch (DocumentException /*de*/)
            {
                //reportObject.ReportError = de.Message; ;
                //reportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            catch (IOException /*ioe*/)
            {
                //reportObject.ReportError = ioe.Message; ;
                //reportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            return(isSuccessful);
        }
Пример #26
0
        protected override void WriteDocument(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            if (File.Exists(FilePath))
                throw new Pdf2KTException("File already exists.");

            Document document = null;
            PdfWriter writer = null;

            while(Converter.MoveNext())
            {
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }

                BitmapEncoder encoder = BitmapProcessor.GetBitmapEncoder();
                BitmapSource processed = BitmapProcessor.Convert(Converter.Current);

                if (document == null)
                {
                    document = new Document(new Rectangle(processed.PixelWidth, processed.PixelHeight));
                    writer = PdfWriter.GetInstance(document, new FileStream(FilePath, FileMode.Create));

                    document.Open();
                    document.AddTitle(Converter.Document.Title);
                    document.AddAuthor(Converter.Document.Author);
                    document.AddCreationDate();
                    document.AddCreator("Pdf2KT");
                }

                document.NewPage();

                using (MemoryStream ms = new MemoryStream())
                {
                    encoder.Frames.Add(BitmapFrame.Create(processed));
                    encoder.Save(ms);

                    ms.Position = 0;

                    Image pdfpage = Image.GetInstance(ms);
                    pdfpage.SetAbsolutePosition(0, 0);

                    document.Add(pdfpage);
                }

                worker.ReportProgress((int)((Converter.CurrentProcessedPageNumber * 1f) / Converter.PageCount * 100));
            }

            document.Close();
        }
Пример #27
0
        public bool CreateReport()
        {
            bool isSuccessful = false;

            iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.LETTER);
            try
            {
                //set up RunReport event overrides & create doc
                TerminatedLayawaysListingReport events = this;
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(ReportObject.ReportTempFileFullName, FileMode.Create));
                writer.PageEvent = events;

                MultiColumnText columns   = new MultiColumnText(document.PageSize.Top - 90, document.PageSize.Height - (90));
                float           pageLeft  = document.PageSize.Left;
                float           pageright = document.PageSize.Right;
                columns.AddSimpleColumn(-22, document.PageSize.Width + 24);

                //set up tables, etc...
                PdfPTable table = new PdfPTable(9);
                table.WidthPercentage = 85;// document.PageSize.Width;
                PdfPCell cell = new PdfPCell();
                Image    gif  = Image.GetInstance(Resources.logo, BaseColor.WHITE);
                gif.ScalePercent(25);
                runReport = new LayawayRunReports();
                document.Open();
                document.SetPageSize(PageSize.LETTER);
                document.SetMargins(-100, -100, 10, 45);
                document.AddTitle(string.Format("{0}: {1}", ReportObject.ReportTitle, DateTime.Now.ToString("MM/dd/yyyy")));
                WriteDetail(table);
                DrawLine(table);
                WriteSummary(table);

                DrawLine(table);
                columns.AddElement(table);
                document.Add(columns);
                document.Close();
                //OpenFile();
                //CreateReport();
                isSuccessful = true;
            }
            catch (DocumentException de)
            {
                ReportObject.ReportError      = de.Message;;
                ReportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            catch (IOException ioe)
            {
                ReportObject.ReportError      = ioe.Message;;
                ReportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            return(isSuccessful);
        }
        public void Publish(IReadOnlyList<ReleaseNoteWorkItem> workItems)
        {
            var stream = new MemoryStream();
            try
            {
                _document = new Document(PageSize.A4, 36, 36, 90, 72);

                // Initialize pdf writer
                _writer = PdfWriter.GetInstance(_document, stream);
                _writer.PageEvent = new ReleaseNotesPdfPageEvents(Settings);

                // Open document to write
                _document.Open();
                _document.AddTitle(Settings.GetDocumentTitle());
                _document.AddSubject(Settings.ProductName + " Release Notes");
                _document.AddAuthor("ReleaseNotes Generator");
                _document.AddKeywords(Settings.ProductName + "Release Notes");
                _document.AddCreationDate();
                _document.AddCreator("ReleaseNotes Generator");

                // Add manual release notes for current release
                int chapterNumber = 1;

                if (!string.IsNullOrEmpty(Settings.MergeReleaseNotesFile) && File.Exists(Settings.MergeReleaseNotesFile))
                {
                    Bookmarks.AddRange(Merge(Settings.MergeReleaseNotesFile, 1));
                    if (Bookmarks.Count > 0)
                        chapterNumber = Bookmarks.Count;
                }

                // Add automatic releases notes for current release
                WriteWorkItems("How do I?", ref chapterNumber, workItems.Where(x => x.ResolutionType == "How do I" || x.ResolutionType == "As Designed"));
                WriteWorkItems("Bug Fixes", ref chapterNumber, workItems.Where(x => x.ResolutionType == "Bug Fix"));
                WriteWorkItems("Known Issues", ref chapterNumber, workItems.Where(x => x.ResolutionType == "Known Issue"));
                WriteWorkItems("User Manual", ref chapterNumber, workItems.Where(x => x.ResolutionType == "User Manual"));

                CreateBookmarks();
            }
            catch (Exception exception)
            {
                throw new Exception("There has an unexpected exception occured whilst creating the release notes: " + exception.Message, exception);
            }
            finally
            {
                _document.Close();
            }

            File.WriteAllBytes(Settings.OutputFile, stream.GetBuffer());
        }
Пример #29
0
 public void SetDocumentProperties(Models.Document documentTemplate)
 {
     if (documentTemplate.Author != null)
     {
         _itextDocument.AddAuthor(documentTemplate.Author);
     }
     if (documentTemplate.Title != null)
     {
         _itextDocument.AddTitle(documentTemplate.Title);
     }
     if (documentTemplate.Subject != null)
     {
         _itextDocument.AddSubject(documentTemplate.Subject);
     }
 }
        public bool CreateReport()
        {
            bool isSuccessful = false;

            iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.HALFLETTER.Rotate());
            try
            {
                //set up RunReport event overrides & create doc
                LayawayPickingSlip events = this;
                PdfWriter          writer = PdfWriter.GetInstance(document, new FileStream(ReportObject.ReportTempFileFullName, FileMode.Create));
                writer.PageEvent = events;

                MultiColumnText columns = new MultiColumnText(document.PageSize.Top - 125, MultiColumnText.AUTOMATIC);
                columns.AddSimpleColumn(-30, document.PageSize.Width + 20);

                //set up tables, etc...
                PdfPTable table = new PdfPTable(7);
                table.WidthPercentage = 85;// document.PageSize.Width;
                var gif = Image.GetInstance(Resources.logo, BaseColor.WHITE);
                gif.ScalePercent(25);
                runReport = new LayawayRunReports();
                document.Open();
                document.SetPageSize(PageSize.HALFLETTER.Rotate());
                document.SetMargins(-100, -100, 10, 45);
                document.AddTitle(string.Format("{0}: {1}", ReportObject.ReportTitle, DateTime.Now.ToString("MM/dd/yyyy")));

                ReportDetail(table);

                columns.AddElement(table);
                document.Add(columns);
                document.Close();
                //nnaeme
                //OpenFile(ReportObject.ReportTempFileFullName);
                //CreateReport();
                isSuccessful = true;
            }
            catch (DocumentException de)
            {
                ReportObject.ReportError      = de.Message;
                ReportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            catch (IOException ioe)
            {
                ReportObject.ReportError      = ioe.Message;
                ReportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            return(isSuccessful);
        }
Пример #31
0
        protected override void InitiateDocument(LnParameters lnParam, string language)
        {
            this.lnParameters    = lnParam;
            this.currentLanguage = language;

            pdf = new PdfDocument(PageSize.A4);
            foreach (string author in lnParam.authors)
            {
                pdf.AddAuthor(author);
            }
            pdf.AddCreationDate();
            pdf.AddLanguage(language);
            pdf.AddTitle(DocumentTitle);
            pdf.AddCreator(Globale.PUBLISHER);
            pdfChapters = new List <Chapter>();
        }
Пример #32
0
        public void SendToPDF(string filename, clsFont jfont)
        {
            //New document, 8.5"x11" in landscape orientation.
            iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.LETTER.Rotate());

            //add metadata
            doc.AddTitle("Font preview for font " + jfont.SelectedFontName());
            doc.AddSubject("font family " + jfont.SelectedFontName());
            doc.AddAuthor("JLION.COM jFONT font preview utility");
            doc.AddCreationDate();

            //create a pdfwriter
            iTextSharp.text.pdf.PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(filename, FileMode.Create));

            //trap events
            PDFPageEvent pdfevent = new PDFPageEvent();

            writer.PageEvent = pdfevent;

            //create the doc
            doc.Open();
            doc.SetMargins(.75f * 72, .75f * 72, 0, 0);

            for (int currentPage = 0; currentPage < jfont.CountOfPages(); currentPage++)
            {
                //convert image to a pdf image for inclusion in the doc
                System.Drawing.Image jfontimage = jfont.MakeCharList(currentPage);
                //System.Drawing.Image jfontimage = jfont.MakeCharacterSample();
                iTextSharp.text.Image convertedimage = iTextSharp.text.Image.GetInstance(jfontimage, System.Drawing.Imaging.ImageFormat.Bmp);

                //determine size to scale to. PDF is 72 dpi, so 1 point is 1/72.
                System.Drawing.Rectangle PDFImageSize = jfont.ImageSize(72);

                convertedimage.ScaleAbsolute(PDFImageSize.Width, PDFImageSize.Height);

                //Add some blank space at the top of the document
                doc.Add(new Paragraph("Font: " + jfont.SelectedFontName()));
                doc.Add(new Paragraph("Style: " + jfont.SelectedFontStyle()));
                doc.Add(new Paragraph(""));
                doc.Add(new Paragraph(""));
                doc.Add(convertedimage);

                doc.NewPage();
            }

            doc.Close();
        }
    public static void CreateDocument(Stream stream, Action<Document> action)
    {
        using (var document = new Document(PageSize.A4))
            {
                var writer = PdfWriter.GetInstance(document, stream);
                document.Open();
                document.AddAuthor(Author);
                document.AddCreator(DocumentCreator);
                document.AddKeywords(DocumentKeywords);
                document.AddSubject(DocumentSubject);
                document.AddTitle(DocumentTitle);

                action.Invoke(document);

                document.Close();
            }
    }
Пример #34
0
        private void InitializeDocument(String name, char pdfVersion) {
            output = OUT + name + ".pdf";
            document = new Document();
            writer = PdfWriter.GetInstance(document, new FileStream(output, FileMode.Create));
            writer.PdfVersion = pdfVersion;
            writer.SetTagged();
            document.Open();

            //Required for PDF/UA
            writer.ViewerPreferences = PdfWriter.DisplayDocTitle;
            document.AddLanguage("en-US");
            document.AddTitle("Some title");
            writer.CreateXmpMetadata();
            Chunk c = new Chunk("Document Header", new Font(Font.FontFamily.HELVETICA, 14, Font.BOLD, BaseColor.BLUE));
            h1 = new Paragraph(c);
            h1.Role = PdfName.H1;
        }
Пример #35
0
// ---------------------------------------------------------------------------
/**
 * Creates a PDF document.
 */
    public byte[] CreatePdf() {
      using (MemoryStream ms = new MemoryStream()) {
        // step 1
        using (Document document = new Document()) {
          // step 2
          PdfWriter.GetInstance(document, ms);
          // step 3
          document.AddTitle("Hello World example");
          document.AddAuthor("Bruno Lowagie");
          document.AddSubject("This example shows how to add metadata");
          document.AddKeywords("Metadata, iText, PDF");
          document.AddCreator("My program using iText");
          document.Open();
          // step 4
          document.Add(new Paragraph("Hello World"));
        }
        return ms.ToArray();    
      }
    }    
Пример #36
0
        public void CreateGradesPDF(List <CourseModel> grades)
        {
            System.IO.FileStream fs = new FileStream("GeneratedDocument.pdf", FileMode.Create);

            iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.A4, 25, 25, 30, 30);

            PdfWriter writer = PdfWriter.GetInstance(document, fs);

            document.AddAuthor("UCV");

            document.AddCreator("UCV");

            document.AddKeywords("Note");

            document.AddSubject("Situatie Scolara");

            document.AddTitle("Situatie scolara");

            //document.Add(new Chunk(new LineSeparator(4f, 100f, BaseColor.GRAY, Element.ALIGN_CENTER, -1)));

            document.Open();

            document.Add(new Paragraph("UCV --- Situatie Scolara"));

            if (grades.Count == 0)
            {
                document.Add(new Paragraph("Nu exista situatie scolara."));
            }
            else
            {
                foreach (var grade in grades)
                {
                    document.Add(new Paragraph(grade.Name + "    " + grade.Teacher + "    " + grade.Credits));
                    //document.Add(new Chunk(new LineSeparator(4f, 100f, BaseColor.GRAY, Element.ALIGN_CENTER, -1)));
                }
            }
            document.Close();

            writer.Close();

            fs.Close();
        }
Пример #37
0
        public static MemoryStream GeneratePDF(Teacher teacher, SchoolClass schoolClass, string schoolYear)
        {
            Document document = new Document();
            MemoryStream stream = new MemoryStream();
            PdfWriter writer = PdfWriter.GetInstance(document, stream);

            writer.CloseStream = false;
            document.Open();
            document.AddCreationDate();
            document.AddAuthor("VaKEGrade");
            document.AddTitle("Certificate");

            foreach (Pupil pupil in teacher.PrimaryClasses.First().Pupils.OrderBy(x => x.LastName).ToList())
            {
                CertificateGenerator.GenerateCertificate(pupil, schoolClass, schoolYear, ref document);
            }
            document.Close();
            stream.Seek(0, SeekOrigin.Begin);
            return stream;
        }
Пример #38
0
 void CreatePdf()
 {
     Itext.Document idoc = new Itext.Document(Itext.PageSize.A4);
     try
     {
         if (saveCWFileDialog.ShowDialog() == DialogResult.OK)
         {
             var newfilePath = saveCWFileDialog.FileName;
             PdfWriter.GetInstance(idoc, new FileStream(newfilePath, FileMode.Create));
             #region 设置PDF的头信息,一些属性设置,在Document.Open 之前完成
             idoc.AddAuthor("");
             idoc.AddCreationDate();
             idoc.AddCreator("");
             idoc.AddSubject("");
             idoc.AddTitle("");
             idoc.AddKeywords("");
             idoc.AddHeader("cw", "export pdf");
             #endregion
             idoc.Open();
             //载入字体
             idoc.Add(new Itext.Paragraph(editContentBox.Text, new Itext.Font(BaseFontAndSize(""))));
             idoc.Close();
             if (MessageBox.Show("是否打开文件?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
             {
                 Process.Start(newfilePath);
             }
         }
     }
     catch (Itext.DocumentException de) {
         Console.WriteLine(de.Message); Console.ReadKey();
         WriteLog.Logging(de.Message);
     }
     catch (IOException io) {
         Console.WriteLine(io.Message); Console.ReadKey();
         WriteLog.Logging(io.Message);
     }
     catch (Exception err)
     {
         WriteLog.Logging(err);
     }
 }
        private void Btnpdfolustur_Click_1(object sender, EventArgs e)
        {
            iTextSharp.text.Document pdfdosya = new iTextSharp.text.Document();
            //pdf dosyamızı temsil edecek nesnemizi oluşturuyoruz
            PdfWriter.GetInstance(pdfdosya, new FileStream("C:CSharpPDF.pdf", FileMode.Create));
            //pdf dosyamızın yolunu belirledik ve dosyanın açılış biçimi olrarak pdf ayarladık
            pdfdosya.Open();                          //dosyayı aç
            pdfdosya.AddCreator(txtolusturulan.Text); //oluşturan ismi
            pdfdosya.AddCreationDate();               //tarih
            pdfdosya.AddAuthor(txticeriksahibi.Text); //yazarın ismi eklendi
            pdfdosya.AddHeader(txtustbaslik.Text, "PDF UYGULAMASI OLUŞTUR");
            pdfdosya.AddTitle(txtaltbaslik.Text);     //başlık ve title eklenmesi
            Paragraph eklenecekmetin = new Paragraph(txtaciklamametni.Text);

            pdfdosya.Add(eklenecekmetin);             //eklenecek metnimizin dosyaya eklenmesi
            decimal satir = numaricsatirsayisi.Value; //satir bilgisi
            decimal sutun = numaricsutunsayisi.Value; //sutun bilgisi

            iTextSharp.text.Table tablo = new Table((int)sutun, (int)satir);
            for (int i = 0; i < satir; i++)
            {
                for (int j = 0; j < sutun; j++)
                {
                    Cell hucre = new Cell((i + 1).ToString() + " " + (j + 1).ToString());
                    hucre.BackgroundColor = iTextSharp.text.Color.RED;
                    tablo.AddCell(hucre, i, j);
                }
            }
            tablo.cellspacing = 5;
            pdfdosya.Add(tablo);
            if (txtolusturulan.Text != "")
            {
                Uri yol = new Uri(txtolusturulan.Text);
                iTextSharp.text.Jpeg resim = new iTextSharp.text.Jpeg(yol);
                resim.ScalePercent((int)numaricsikistirmeorani.Value);
                pdfdosya.Add(resim);
            }
            pdfdosya.Close();
        }
Пример #40
0
        public override void Initialize()
        {
            // step 1 : creation of document object
            Rectangle rect = new Rectangle((float)bbox.Width * 1.1f, (float)bbox.Height * 1.1f);
            rect.BackgroundColor = BaseColor.WHITE;
            _pdfDocument = new iTextSharp.text.Document(rect);
            // step 2:
            // we create a writer that listens to the document
            // and directs a PDF-stream to a file
            PdfWriter writer = PdfWriter.GetInstance(_pdfDocument, _stream);
            // step 3: we open the document
            _pdfDocument.Open();
            // step 4: we add content to the document
            _pdfDocument.AddCreationDate();
            _pdfDocument.AddAuthor(author);
            _pdfDocument.AddTitle(title);

            _cb = writer.DirectContent;

            // initialize cotation
            PicCotation._globalCotationProperties._arrowLength = bbox.Height / 50.0;
        }
Пример #41
0
        private void GenerateReportButtonResultsView_Click(object sender, EventArgs e)
        {
            if (RepDirTextBox.Text == "" || RepDirTextBox.Text == "Set the folder where the pdf reports will be stored") { MessageBox.Show("Please select a folder on configuration tab to save the reports."); }
            else
            {
                GenerateReportResultsViewClicked = true;
                try
                {
                    // event fired when the contextual menu was clicked
                    //ToolStripMenuItem mi = (ToolStripMenuItem)e.ClickedItem;
                    // mi : item clicked in the contextual menu
                    // VStream tvs = (VStream)mi.Tag;

                    if (ReportNameResultsViewtextBox.Text == "")
                    {
                        MessageBox.Show("Report Title section cannot be empty, please enter a title to display in .pdf report.");
                    }
                    else
                    {

                        //CreatePDFFile();
                        string reportname = SaveReportAstextBox.Text;
                        if (reportname == "")
                        {
                            MessageBox.Show("Save Report As section cannot be empty, please enter a file name.");

                        }
                        else
                        {
                            IList Ltvs = ResultListView.GetSelectedObjects();
                            if (Ltvs.Count == 0)
                            {
                                MessageBox.Show("Please select a video to generate a report.");
                            }
                            else
                            {
                                //  string imagefoldercreate = AppDomain.CurrentDomain.BaseDirectory + "Reports";
                                // Directory.CreateDirectory(imagefoldercreate);

                                if (Directory.Exists(RepDirTextBox.Text))
                                {
                                    Document pdfdoc = new Document(iTextSharp.text.PageSize.LETTER, 40, 10, 42, 35);
                                    //string pdfFilePath = AppDomain.CurrentDomain.BaseDirectory + "Reports\\" + reportname + ".pdf";
                                    string pdfFilePath = RepDirTextBox.Text + reportname + ".pdf";
                                    PdfWriter wri = PdfWriter.GetInstance(pdfdoc, new FileStream(pdfFilePath, FileMode.Create));
                                    pdfdoc.Open();//Open Document to write
                                    Paragraph par = new Paragraph(" ");

                                    int i = 0;
                                    //reportdatedisplayed = false;
                                    //GenerateReportResultsViewClicked = true;
                                    foreach (object tvs in Ltvs)
                                    {
                                        try
                                        {
                                            if (CreateMultiplePDFFile(reportname, (VStream)tvs, pdfdoc)) i++;
                                            par.SpacingBefore = 10f;
                                            Paragraph parend = new Paragraph("------------------------------------------------------------------------------------------------------------------------------------------");
                                            pdfdoc.Add(parend);
                                        }
                                        catch { }
                                    }
                                    if (i == 1)
                                    {
                                        MessageBox.Show("PDF report for " + i + " video generated successfully. Located in " + RepDirTextBox.Text);
                                    } if (i > 1)
                                    {
                                        MessageBox.Show("PDF report for " + i + " videos generated successfully. Located in " + RepDirTextBox.Text);
                                    }

                                    //   par.Alignment = Element.ALIGN_CENTER;
                                    //Anchor anchor1 = new Anchor("Help", iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.HELVETICA, 12, iTextSharp.text.Font.NORMAL, new iTextSharp.text.BaseColor(0, 0, 255)));
                                    //anchor1.Reference = "http://www.path1.com";
                                    //anchor1.Name = "left";
                                    //par.Add(anchor1);
                                    //par.Add("/");

                                    //Anchor anchor2 = new Anchor("Contact", iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.HELVETICA, 12, iTextSharp.text.Font.NORMAL, new iTextSharp.text.BaseColor(0, 0, 255)));
                                    //anchor2.Reference = "http://www.path1.com";
                                    //anchor2.Name = "middle";
                                    //par.Add(anchor2);
                                    //par.Add("/");

                                    //Anchor anchor3 = new Anchor("Whatever we want to show", iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.HELVETICA, 12, iTextSharp.text.Font.NORMAL, new iTextSharp.text.BaseColor(0, 0, 255)));
                                    //anchor3.Reference = "http://www.path1.com";
                                    //anchor3.Name = "middle";
                                    //par.Add(anchor3);
                                    //par.Alignment = Element.ALIGN_CENTER;
                                    //doc.Add(par);

                                    pdfdoc.AddAuthor("Path1");
                                    pdfdoc.AddTitle("v.Cortex Report");
                                    pdfdoc.AddSubject("This report is created by v.Cortex");
                                    docopened = false;
                                    pdfdoc.Close();
                                }

                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }
        }
        protected void grvConsultaSolicitud_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            String strNombreArchivoPDF = String.Empty;
            string strRutUsuario = String.Empty;
            string strNombreAlumno = String.Empty;
            string strNombreCarrera = String.Empty;
            string strNumCelular = String.Empty;
            string strCorreo = String.Empty;
            string strDescTipoSolicitud = String.Empty;
            string strGlosaSolicitud = String.Empty;
            string strFechaSolicitud = String.Empty;
            string strGlosaEstadoSolicitud = String.Empty;
            int intCodTipoSolicitud = 0;

            DateTime Hoy = DateTime.Today;
            string fecha_actual = Hoy.ToString("dd-MM-yyyy");

            int intFolioSolicitud = (int)grvConsultaSolicitud.DataKeys[e.RowIndex].Values[0];

            strNombreArchivoPDF = @"C:\Solicitud" + "_" + intFolioSolicitud + "_" + fecha_actual + ".pdf";

            List<Solicitud> lstSolicitud = new List<Solicitud>();
            NegSolicitud NegSolicitudes = new NegSolicitud();

            Document doc = new Document(PageSize.LETTER);
            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(strNombreArchivoPDF, FileMode.Create));

            doc.AddTitle("Detalle de la Solicitud");
            doc.AddCreator("Workflow Solicitudes CIISA");
            string ruta = Server.MapPath("/") + "/imagenes/logoCiisaPDF.jpg";

            doc.Open();
            iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(@ruta);
            imagen.BorderWidth = 0;
            imagen.Alignment = Element.ALIGN_LEFT;
            float percentage = 0.0f;
            percentage = 45 / imagen.Width;
            imagen.ScalePercent(percentage * 100);
            doc.Add(imagen);

            iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

            lstSolicitud = NegSolicitudes.ObtenerSolicitudesByFolio(intFolioSolicitud);

            foreach (Solicitud Solicitudes in lstSolicitud)
            {
                strRutUsuario = Solicitudes.strRutAlumno;
                strNumCelular = Solicitudes.strCelularContacto;
                strCorreo = Solicitudes.strEmailContacto;
                strDescTipoSolicitud = Solicitudes.strDescripcionSolicitud;
                strGlosaSolicitud = Solicitudes.strGlosaSolicitud;
                strFechaSolicitud = Convert.ToString(Solicitudes.dtmFechaSolicitud);
                intCodTipoSolicitud = Solicitudes.intCodTipoSolicitud;
                strGlosaEstadoSolicitud = Solicitudes.strGlosaEstado;
            }

            // Escribimos el encabezamiento en el documento
            doc.Add(new Paragraph("Información de la Solicitud"));
            doc.Add(new Paragraph("Instituto de Ciencias Tecnológicas"));
            doc.Add(Chunk.NEWLINE);

            iTextSharp.text.Font myfontEncabezado = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 16, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
            Paragraph myParagraph = new Paragraph("Datos del solicitante \n\n", myfontEncabezado);
            doc.Add(myParagraph);

            doc.Add(new Paragraph("Rut Solicitante    :" + strRutUsuario));
            doc.Add(new Paragraph("Nombre Solicitante :" + strNombreAlumno));
            doc.Add(new Paragraph("N° Teléfono        :" + strNumCelular));
            doc.Add(new Paragraph("Correo Electrónico :" + strCorreo));
            doc.Add(new Paragraph("Unidad             :" + strNombreCarrera));
            doc.Add(Chunk.NEWLINE);

            Paragraph myParagraph2 = new Paragraph("Datos de la solicitud \n\n", myfontEncabezado);
            doc.Add(myParagraph2);

            doc.Add(new Paragraph("Folio Solicitud  :" + intFolioSolicitud));
            doc.Add(new Paragraph("Fecha Solicitud  :" + strFechaSolicitud));
            doc.Add(new Paragraph("Tipo Solicitud   :" + strDescTipoSolicitud));
            doc.Add(new Paragraph("Petición         :" + strGlosaSolicitud));
            doc.Add(new Paragraph("Estado Solicitud :" + strGlosaEstadoSolicitud));
            doc.Add(Chunk.NEWLINE);

            List<WorkflowSolicitudes.Entidades.DetalleSolicitud> LstHistory = new List<WorkflowSolicitudes.Entidades.DetalleSolicitud>();
            NegDetalleSolicitud NegDetSol = new NegDetalleSolicitud();
            LstHistory = NegDetSol.HistorialDetalleSolicitud(intFolioSolicitud);

            if (!LstHistory.Count.Equals(0))
            {

                Paragraph myParagraph3 = new Paragraph("Detalles de la Solicitud \n\n", myfontEncabezado);
                doc.Add(myParagraph3);

                PdfPTable tblPrueba = new PdfPTable(6);
                tblPrueba.WidthPercentage = 100;

                PdfPCell clSecuencia = new PdfPCell(new Phrase("Secuencia", _standardFont));
                clSecuencia.BorderWidth = 0;
                clSecuencia.BorderWidthBottom = 0.75f;

                PdfPCell clNombre = new PdfPCell(new Phrase("Nombre", _standardFont));
                clNombre.BorderWidth = 0;
                clNombre.BorderWidthBottom = 0.75f;

                PdfPCell clApellido = new PdfPCell(new Phrase("Apellido", _standardFont));
                clApellido.BorderWidth = 0;
                clApellido.BorderWidthBottom = 0.75f;

                PdfPCell clObservacion = new PdfPCell(new Phrase("Observación", _standardFont));
                clObservacion.BorderWidth = 0;
                clObservacion.BorderWidthBottom = 0.75f;

                PdfPCell clFechaResolucion = new PdfPCell(new Phrase("Fecha Resolución", _standardFont));
                clFechaResolucion.BorderWidth = 0;
                clFechaResolucion.BorderWidthBottom = 0.75f;

                PdfPCell clEstado = new PdfPCell(new Phrase("Estado", _standardFont));
                clEstado.BorderWidth = 0;
                clEstado.BorderWidthBottom = 0.75f;

                foreach (WorkflowSolicitudes.Entidades.DetalleSolicitud Detalle in LstHistory)
                {
                    // Añadimos las celdas a la tabla
                    tblPrueba.AddCell(clSecuencia);
                    tblPrueba.AddCell(clNombre);
                    tblPrueba.AddCell(clApellido);
                    tblPrueba.AddCell(clObservacion);
                    tblPrueba.AddCell(clFechaResolucion);
                    tblPrueba.AddCell(clEstado);

                    clSecuencia = new PdfPCell(new Phrase(Convert.ToString(Detalle.intSecuencia), _standardFont));
                    clSecuencia.BorderWidth = 0;

                    clNombre = new PdfPCell(new Phrase(Detalle.strnombre, _standardFont));
                    clNombre.BorderWidth = 0;

                    clApellido = new PdfPCell(new Phrase(Detalle.strApellido, _standardFont));
                    clApellido.BorderWidth = 0;

                    clObservacion = new PdfPCell(new Phrase(Detalle.StrGlosaDetalleSolictud, _standardFont));
                    clObservacion.BorderWidth = 0;

                    clFechaResolucion = new PdfPCell(new Phrase(Detalle.strApellido, _standardFont));
                    clFechaResolucion.BorderWidth = 0;

                    clEstado = new PdfPCell(new Phrase(Detalle.strEstado, _standardFont));
                    clEstado.BorderWidth = 0;

                    //tblPrueba.AddCell(clSecuencia);
                    //tblPrueba.AddCell(clNombre);
                    //tblPrueba.AddCell(clApellido);
                    //tblPrueba.AddCell(clObservacion);
                    //tblPrueba.AddCell(clFechaResolucion);
                    //tblPrueba.AddCell(clEstado);

                   doc.Add(tblPrueba);
                }

            }
            doc.Close();
            writer.Close();

            System.Diagnostics.Process.Start("AcroRd32.exe", strNombreArchivoPDF);
        }
Пример #43
0
        public LibroAtrasos(AufenPortalReportesDataContext db, EMPRESA empresa, vw_Ubicacione departamento, DateTime FechaDesde, DateTime FechaHasta, string path, string rut)
        {
            //Nombre del archivo y ubiación en el árbol de carpetas
            NombreArchivo = String.Format("{0}/{1}/LibroAtrasos.pdf", empresa.Descripcion, departamento.Descripcion);
            // Vamos a buscar los datos que nos permitirtán armar elreporte
            IEnumerable<sp_LibroAsistenciaResult> resultadoLibroAtrasos =
                                           db.sp_LibroAsistencia(
                                           FechaDesde.ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture),
                                           FechaHasta.ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture),
                                           int.Parse(empresa.Codigo).ToString(),
                                           departamento.Codigo,
                                           rut).ToList();
            IEnumerable<LibroAsistenciaDTO> libroAtrasos = Mapper.Map<IEnumerable<sp_LibroAsistenciaResult>,
                IEnumerable<LibroAsistenciaDTO>>(resultadoLibroAtrasos)
            .Where(x =>x.Entrada.HasValue && x.Salida.HasValue && x.SalidaTeorica.HasValue && x.EntradaTeorica.HasValue &&
                x.Entrada > x.EntradaTeorica);
            // Comenzaremos a crear el reporte
            if (libroAtrasos.Any())
            {
                Configuracion();
                Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 50, 35);
                using (var ms = new MemoryStream())
                {
                    PdfWriter pdfWriter = PdfWriter.GetInstance(doc, ms);
                    pdfWriter.PageEvent = new Header(empresa, path);
                    doc.Open();
                    foreach (var reporte in libroAtrasos.GroupBy(x => new { x.Rut, x.IdDepartamento, x.IdEmpresa }))
                    {
                        var empleado = db.vw_Empleados.FirstOrDefault(x => x.IdEmpresa == empresa.Codigo &&
                            x.IdUbicacion == reporte.Key.IdDepartamento &&
                                  x.Codigo == reporte.Key.Rut);
                        if (empleado == null)
                        {
                            empleado = new vw_Empleado();
                        }

                        doc.AddAuthor("Aufen");
                        doc.AddCreationDate();
                        doc.AddCreator("Aufen");
                        doc.AddTitle("Libro de Atrasos");
                        // Texto
                        Paragraph parrafo = new Paragraph();
                        parrafo.Add(new Paragraph(
                            String.Format("Departamento: {1}, Fecha de Reporte: {0}",
                            DateTime.Now.ToShortDateString(),
                            departamento.SucursalPlanta), Normal) { Alignment = Element.ALIGN_CENTER });
                        parrafo.Add(new Paragraph("Informe de Atrasos por Área", Titulo) { Alignment = Element.ALIGN_CENTER });
                        doc.Add(parrafo);
                        doc.Add(new Phrase());
                        doc.Add(new Phrase());

                        PdfPTable informacionPersonal = new PdfPTable(new float[] { 1,5});
                        informacionPersonal.AddCell(new PdfPCell(new Phrase("Rut:", Normal)));
                        informacionPersonal.AddCell(new PdfPCell(new Phrase(empleado.RutAufen, NormalNegrita)));
                        informacionPersonal.AddCell(new PdfPCell(new Phrase("Nombre:", Normal)));
                        informacionPersonal.AddCell(new PdfPCell(new Phrase(empleado.NombreCompleto, NormalNegrita)));
                        informacionPersonal.AddCell(new PdfPCell(new Phrase("Centro de Costos:", Normal)));
                        informacionPersonal.AddCell(new PdfPCell(new Phrase(String.Empty, NormalNegrita)));
                        doc.Add(new Phrase());

                        doc.Add(informacionPersonal);
                        // tabla
                        PdfPTable tabla = new PdfPTable(new float[] {2, 2, 2, 2, 2, 2, 2, 4 });
                        // Primera lìnea cabecera
                        tabla.AddCell(new PdfPCell(new Phrase("Fecha", Chico)) { Rowspan = 2 });
                        //tabla.AddCell(new PdfPCell(new Phrase("Empleado", Chico)) { Colspan = 3 });
                        tabla.AddCell(new PdfPCell(new Phrase("Horario", Chico)) { Colspan = 2 });
                        tabla.AddCell(new PdfPCell(new Phrase("Marcas", Chico)) { Colspan = 2 });
                        tabla.AddCell(new PdfPCell(new Phrase("Horas Trabajadas", Chico)) { Colspan = 2 });
                        tabla.AddCell(new PdfPCell(new Phrase("Autorizaciones", Chico)));
                        // Segunda lìnea cabecera
                        //tabla.AddCell(new PdfPCell(new Phrase("Rut", Chico)));
                        //tabla.AddCell(new PdfPCell(new Phrase("Apellidos", Chico)));
                        //tabla.AddCell(new PdfPCell(new Phrase("Nombres", Chico)));
                        tabla.AddCell(new PdfPCell(new Phrase("Ing.", Chico)));
                        tabla.AddCell(new PdfPCell(new Phrase("Sal.", Chico)));
                        tabla.AddCell(new PdfPCell(new Phrase("Ing.", Chico)));
                        tabla.AddCell(new PdfPCell(new Phrase("Sal.", Chico)));
                        tabla.AddCell(new PdfPCell(new Phrase("Atrasos", Chico)));
                        tabla.AddCell(new PdfPCell(new Phrase("H.T.N.", Chico)));
                        tabla.AddCell(new PdfPCell(new Phrase("Permisos", Chico)));

                        foreach (var atraso in reporte)
                        {
                            TimeSpan tiempoAtraso =
                                (atraso.Salida.HasValue && atraso.Entrada.HasValue ? atraso.Salida.Value.Subtract(atraso.Entrada.Value) : new TimeSpan(0)) -
                                (atraso.SalidaTeorica.HasValue && atraso.EntradaTeorica.HasValue ? atraso.SalidaTeorica.Value.Subtract(atraso.EntradaTeorica.Value) : new TimeSpan(0));
                            TimeSpan tiempoNormal = atraso.SalidaTeorica.HasValue && atraso.EntradaTeorica.HasValue ? atraso.SalidaTeorica.Value.Subtract(atraso.EntradaTeorica.Value) : new TimeSpan(0);
                            tabla.AddCell(new PdfPCell(new Phrase(atraso.Fecha.Value.ToString("ddd dd/MM"), Chico)) { HorizontalAlignment = Element.ALIGN_LEFT });
                            //tabla.AddCell(new PdfPCell(new Phrase(atraso.Rut.ToStringConGuion(), Chico)));
                            //tabla.AddCell(new PdfPCell(new Phrase(atraso.Apellidos, Chico)));
                            //tabla.AddCell(new PdfPCell(new Phrase(atraso.Nombres, Chico)));
                            tabla.AddCell(new PdfPCell(new Phrase(atraso.Entrada.HasValue ? atraso.Entrada.Value.ToString("HH:mm") : String.Empty, Chico)));
                            tabla.AddCell(new PdfPCell(new Phrase(atraso.Salida.HasValue ? atraso.Salida.Value.ToString("HH:mm") : String.Empty, Chico)));
                            tabla.AddCell(new PdfPCell(new Phrase(atraso.EntradaTeorica.HasValue ? atraso.EntradaTeorica.Value.ToString("HH:mm") : String.Empty, Chico)));
                            tabla.AddCell(new PdfPCell(new Phrase(atraso.SalidaTeorica.HasValue ? atraso.SalidaTeorica.Value.ToString("HH:mm") : String.Empty, Chico)));
                            tabla.AddCell(new PdfPCell(new Phrase(atraso.printAtraso, Chico)));
                            tabla.AddCell(new PdfPCell(new Phrase("", Chico)));
                            tabla.AddCell(new PdfPCell(new Phrase(atraso.Observacion, Chico)));
                        }
                        tabla.AddCell(new PdfPCell(new Phrase("Total", ChicoNegrita)) { Colspan=5 });
                        //TODO: aqí va la suma de astrasos
                        tabla.AddCell(new PdfPCell(new Phrase(reporte.CalculaAtrasoEntrada(), Chico)));
                        //TODO: aqí va la suma de H.T.N.
                        tabla.AddCell(new PdfPCell(new Phrase("", Chico)));
                        tabla.AddCell(new PdfPCell(new Phrase("", Chico)));
                        doc.Add(tabla);
                        doc.NewPage();
                    }
                    doc.Close();
                    _Archivo = ms.ToArray();
                }
            }
        }
Пример #44
0
 private void Speichern(string filename)
 {
     try
     {
         Document document = new Document();
         PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create));
         document.AddTitle("Webfuzzer Report");
         document.AddCreationDate();
         document.Open();
         document.Add(new Paragraph("WebFuzzer Found URLs", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 16, iTextSharp.text.Font.UNDERLINE)));
         document.Add(new Paragraph(" "));
         foreach (ListViewItem item in listViewResult.Items)
         {
             document.Add(new Paragraph(item.SubItems[1].Text));
             if (richTextBoxPOST.Text != string.Empty)
             {
                 document.Add(new Paragraph("POST data: " + richTextBoxPOST.Text));
             }
             document.Add(new Paragraph(" "));
         }
         document.Close();
     }
     catch (IOException)
     {
         MessageBox.Show("The file is in use. Please close all applications accessing this file and try again.", "Access not possible", MessageBoxButtons.OK);
     }
     catch (Exception ex)
     {
         Console.WriteLine("Fehler beim Speichern" + ex);
     }
 }
Пример #45
0
        /// <summary>
        /// Exports the chart to the specified output stream as binary. When 
        /// exporting to a web response the WriteToHttpResponse() method is likely
        /// preferred.
        /// </summary>
        /// <param name="outputStream">An output stream.</param>
        internal void WriteToStream(Stream outputStream)
        {
            switch (this.ContentType)
              {
            case "image/jpeg":
              CreateSvgDocument().Draw().Save(
            outputStream,
            ImageFormat.Jpeg);
              break;

            case "image/png":
              // PNG output requires a seekable stream.
              using (MemoryStream seekableStream = new MemoryStream())
              {
            CreateSvgDocument().Draw().Save(
                seekableStream,
                ImageFormat.Png);
            seekableStream.WriteTo(outputStream);
              }
              break;

            case "application/pdf":
              SvgDocument svgDoc = CreateSvgDocument();

              // Create PDF document.
              using (Document pdfDoc = new Document())
              {
            // Scalar to convert from 72 dpi to 150 dpi.
            float dpiScalar = 150f / 72f;

            // Set page size. Page dimensions are in 1/72nds of an inch.
            // Page dimensions are scaled to boost dpi and keep page
            // dimensions to a smaller size.
            pdfDoc.SetPageSize(new Rectangle(
              svgDoc.Width / dpiScalar,
              svgDoc.Height / dpiScalar));

            // Set margin to none.
            pdfDoc.SetMargins(0f, 0f, 0f, 0f);

            // Create PDF writer to write to response stream.
            using (PdfWriter pdfWriter = PdfWriter.GetInstance(
              pdfDoc,
              outputStream))
            {
              // Configure PdfWriter.
              pdfWriter.SetPdfVersion(PdfWriter.PDF_VERSION_1_5);
              pdfWriter.CompressionLevel = PdfStream.DEFAULT_COMPRESSION;

              // Add meta data.
              pdfDoc.AddCreator(PdfMetaCreator);
              pdfDoc.AddTitle(this.Name);

              // Output PDF document.
              pdfDoc.Open();
              pdfDoc.NewPage();

              // Create image element from SVG image.
              Image image = Image.GetInstance(svgDoc.Draw(), ImageFormat.Bmp);
              image.CompressionLevel = PdfStream.DEFAULT_COMPRESSION;

              // Must match scaling performed when setting page size.
              image.ScalePercent(100f / dpiScalar);

              // Add image element to PDF document.
              pdfDoc.Add(image);

              pdfDoc.CloseDocument();
            }
              }

              break;

            case "image/svg+xml":
              using (StreamWriter writer = new StreamWriter(outputStream))
              {
            writer.Write(this.Svg);
            writer.Flush();
              }

              break;

            default:
              throw new InvalidOperationException(string.Format(
            "ContentType '{0}' is invalid.", this.ContentType));
              }

              outputStream.Flush();
        }
        //create report
        public bool CreateReport()//ReportObject rptObj)
        {
            bool isSuccessful = false;

            iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.LEGAL);

            try
            {
                //set up RunReport event overrides & create doc
                GunAuditReport events = new GunAuditReport();
                PdfWriter      writer = PdfWriter.GetInstance(document, new FileStream(reportObject.ReportTempFileFullName, FileMode.Create));
                writer.PageEvent = events;

                //set up tables, etc...
                PdfPTable table = new PdfPTable(21);
                PdfPCell  cell  = new PdfPCell();
                Image     gif   = Image.GetInstance(Resources.logo, BaseColor.WHITE);

                _reportFont               = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL);
                _reportFontLargeBold      = FontFactory.GetFont("Arial", 10, iTextSharp.text.Font.BOLD);
                _reportFontLargeUnderline = FontFactory.GetFont("Arial", 10, iTextSharp.text.Font.UNDERLINE);

                gif.ScalePercent(35);
                runReport = new RunReport();

                if (reportObject.ReportDetail.Equals("Summary"))
                {
                    document.AddTitle(reportObject.ReportTitle + " - Summary: " + DateTime.Now.ToString("MM/dd/yyyy"));

                    document.SetPageSize(PageSize.LETTER);
                    document.SetMargins(-50, -55, 10, 45);

                    SummaryReportHeader(table, gif);
                    Int32[,] gunStatus;
                    gunStatus = new Int32[6, 4];
                    SummaryReportDetail(table, out gunStatus, false);
                    SummaryReportSummary(table, gunStatus, false);

                    table.HeaderRows = 10;
                }
                else//detail version
                {
                    document.AddTitle(reportObject.ReportTitle + " - Detailed: " + DateTime.Now.ToString("MM/dd/yyyy"));

                    document.SetPageSize(PageSize.LEGAL.Rotate());
                    document.SetMargins(-100, -100, 10, 45);

                    DetailReportHeader(table, gif);
                    DetailColumnHeaders(table);
                    DetailReportDetail(table);
                    DetailReportSummary(table);//calls summary methods

                    table.HeaderRows = 7;
                }

                document.Open();
                document.Add(table);
                document.Close();

                isSuccessful = true;
            }
            catch (DocumentException de)
            {
                reportObject.ReportError      = de.Message;;
                reportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            catch (IOException ioe)
            {
                reportObject.ReportError      = ioe.Message;;
                reportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }

            return(isSuccessful);
        }
Пример #47
0
        /// <summary>
        /// Construction du Rapport en PDF 
        /// </summary>
        /// <param name="data">Data.</param>
        public void BuildReport(DataSet data)
        {
            System.IO.FileStream fs = new FileStream ("Rapport.pdf", FileMode.Create);

            Document document = new Document (PageSize.A4, 25, 25, 30, 30);

            PdfWriter writer = PdfWriter.GetInstance (document, fs);

            document.AddSubject ("Rapport de paiements");
            document.AddTitle("Rapport Multi-Location");

            document.Open ();
            PdfContentByte cb = writer.DirectContent;
            string nomClient = data.Tables[0].Rows[0].ItemArray[0].ToString();
            string prenomClient = data.Tables [0].Rows [0].ItemArray [1].ToString ();
            int y = 485;
            double montantPayetotal = 0;
            int nbrPaiement = 0;
            int numeroPage = 1;

            for (int i = 0; i < data.Tables [0].Rows.Count ; i++)
            {

                cb.SetFontAndSize(FontFactory.GetFont(FontFactory.HELVETICA_BOLD).BaseFont, 10);
                string nomSuivant = GetNextNom (data, i);
                string prenomSuivant = GetNextPrenom (data, i);

                if ((nomClient == data.Tables[0].Rows[i].ItemArray[0].ToString() && prenomClient == data.Tables[0].Rows[i].ItemArray[1].ToString() )&& nbrPaiement == 0) {
                    cb.BeginText();

                    string today = DateTime.Now.ToString ("MM/dd/yyyy");

                    cb.ShowTextAligned (PdfContentByte.ALIGN_LEFT, "Rapport de paiements du : " + today, 100, 750, 0);
                    cb.ShowTextAligned (PdfContentByte.ALIGN_LEFT, "Location de : ", 100, 700, 0);
                    cb.ShowTextAligned (PdfContentByte.ALIGN_LEFT, data.Tables [0].Rows [i].ItemArray [0].ToString () +
                    ", " + data.Tables [0].Rows [i].ItemArray [1].ToString (), 165, 700, 0);

                    cb.ShowTextAligned (PdfContentByte.ALIGN_LEFT, data.Tables [0].Rows [i].ItemArray [2].ToString (), 100, 690, 0);
                    cb.ShowTextAligned (PdfContentByte.ALIGN_LEFT, data.Tables [0].Rows [i].ItemArray [3].ToString (), 100, 680, 0);
                    cb.ShowTextAligned (PdfContentByte.ALIGN_LEFT, data.Tables [0].Rows [i].ItemArray [4].ToString (), 100, 670, 0);
                    nomClient = data.Tables [0].Rows [i].ItemArray [0].ToString ();
                    prenomClient = data.Tables [0].Rows [i].ItemArray [1].ToString ();

                    cb.ShowTextAligned (PdfContentByte.ALIGN_CENTER, "Modèle", 100, 520, 0);
                    cb.ShowTextAligned (PdfContentByte.ALIGN_CENTER, "ID de paiement", 200, 520, 0);
                    cb.ShowTextAligned (PdfContentByte.ALIGN_CENTER, "Date du paiement", 300, 520, 0);
                    cb.ShowTextAligned (PdfContentByte.ALIGN_CENTER, "Montant payé", 400, 520, 0);
                    cb.ShowTextAligned (PdfContentByte.ALIGN_CENTER, "__________________________________________________________________", 260, 515, 0);
                    cb.ShowTextAligned (PdfContentByte.ALIGN_CENTER, data.Tables [0].Rows [i].ItemArray [5].ToString (), 100, 500, 0);
                    cb.ShowTextAligned (PdfContentByte.ALIGN_CENTER, data.Tables [0].Rows [i].ItemArray [6].ToString (), 200, 500, 0);
                    cb.ShowTextAligned (PdfContentByte.ALIGN_CENTER, data.Tables [0].Rows [i].ItemArray [7].ToString (), 300, 500, 0);
                    cb.ShowTextAligned (PdfContentByte.ALIGN_CENTER, data.Tables [0].Rows [i].ItemArray [8].ToString (), 400, 500, 0);
                    cb.ShowTextAligned (PdfContentByte.ALIGN_CENTER, "Page " + numeroPage.ToString (), 550, 10, 0);

                    nbrPaiement++;
                    montantPayetotal = double.Parse (data.Tables [0].Rows [i].ItemArray [8].ToString ());
                    cb.EndText ();

                    if (nomClient != nomSuivant ||prenomClient != prenomSuivant) {
                        cb.BeginText ();
                        cb.ShowTextAligned (PdfContentByte.ALIGN_LEFT, "Montant total payé : " + montantPayetotal.ToString (), 75, y - 30, 0);
                        cb.ShowTextAligned (PdfContentByte.ALIGN_LEFT, "Nombre de paiement fait : " + nbrPaiement.ToString (), 75, y - 40, 0);
                        cb.ShowTextAligned (PdfContentByte.ALIGN_LEFT, "Montant en souffrance : 0,00$", 75, y - 50, 0);
                        numeroPage++;
                        nbrPaiement = 0;
                        montantPayetotal = 0;
                        y = 485;
                        prenomClient = prenomSuivant;
                        nomClient = nomSuivant;
                        cb.EndText ();
                        document.NewPage ();
                    }

                } else if (nomClient == data.Tables [0].Rows [i].ItemArray [0].ToString () && prenomClient == data.Tables [0].Rows [i].ItemArray [1].ToString ()) {
                    cb.BeginText ();

                    cb.ShowTextAligned (PdfContentByte.ALIGN_CENTER, data.Tables [0].Rows [i].ItemArray [5].ToString (), 100, y, 0);
                    cb.ShowTextAligned (PdfContentByte.ALIGN_CENTER, data.Tables [0].Rows [i].ItemArray [6].ToString (), 200, y, 0);
                    cb.ShowTextAligned (PdfContentByte.ALIGN_CENTER, data.Tables [0].Rows [i].ItemArray [7].ToString (), 300, y, 0);
                    cb.ShowTextAligned (PdfContentByte.ALIGN_CENTER, data.Tables [0].Rows [i].ItemArray [8].ToString (), 400, y, 0);
                    double montant = double.Parse (data.Tables [0].Rows [i].ItemArray [8].ToString ());
                    montantPayetotal += montant;
                    nbrPaiement++;
                    y -= 15;

                    cb.EndText ();
                    if (nomClient != nomSuivant && prenomClient != prenomSuivant) {
                        cb.BeginText ();
                        cb.SetFontAndSize(FontFactory.GetFont(FontFactory.HELVETICA_BOLD).BaseFont, 10);
                        cb.ShowTextAligned (PdfContentByte.ALIGN_LEFT, "Montant total payé : " + montantPayetotal.ToString (), 75, y - 30, 0);
                        cb.ShowTextAligned (PdfContentByte.ALIGN_LEFT, "Nombre de paiement fait : " + nbrPaiement.ToString (), 75, y - 40, 0);
                        cb.ShowTextAligned (PdfContentByte.ALIGN_LEFT, "Montant en souffrance : 0,00$", 75, y - 50, 0);
                        numeroPage++;
                        nbrPaiement = 0;
                        montantPayetotal = 0;
                        y = 485;
                        prenomClient = "";
                        nomClient = "";

                        cb.EndText ();
                        document.NewPage ();
                        nomClient = nomSuivant;
                        prenomClient = prenomSuivant;

                    }

                }

            }

            document.Close ();
            writer.Close ();
            fs.Close ();
        }
        public bool CreateReport()
        {
            bool isSuccessful = false;

            _document = new iTextSharp.text.Document(PageSize.LEGAL);

            try
            {
                //set up RunReport event overrides & create doc
                _ReportObject = new ReportObject();
                _ReportObject.CreateTemporaryFullName();

                if (!Directory.Exists(_logPath))
                {
                    Directory.CreateDirectory(_logPath);
                }
                reportFileName = _logPath + "\\" + _ReportObject.ReportTempFileFullName;
                PdfWriter writer = PdfWriter.GetInstance(_document, new FileStream(reportFileName, FileMode.Create));
                //writer.PageEvent = this;

                //set up tables, etc...
                int       columns = 6;
                PdfPTable table   = new PdfPTable(columns);
                Image     gif     = Image.GetInstance(Common.Properties.Resources.logo, BaseColor.WHITE);
                // Image gif = Image.GetInstance(PawnReportResources.calogo, BaseColor.WHITE);
                _reportFont          = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL);
                _reportFontLargeBold = FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.BOLD);

                gif.ScalePercent(35);
                //gif.ScalePercent(75);

                _document.AddTitle(_reportTitle);

                _document.SetPageSize(PageSize.LETTER);
                _document.SetMargins(-50, -55, 10, 45);
                writer.PageEvent = this;
                _document.Open();   //Go ahead and open the document so tables can be added.

                //PrintReportHeader(table, gif, columns);
                PrintReportHeader(gif);
                PrintReportDetail();

                if (!_catcoTransferType.Equals("Appraisal", StringComparison.CurrentCultureIgnoreCase) && !_catcoTransferType.Equals("Wholesale", StringComparison.CurrentCultureIgnoreCase))
                {
                    PopulateMetalTypes();
                    AggregateData();
                    PrintTotalSummaryRow(table, writer);
                }
                table.HeaderRows = 3;

                _document.Add(table);
                _document.Close();
                //OpenFile(reportFileName);
                //CreateReport();
                isSuccessful = true;
            }
            catch (DocumentException de)
            {
                _ReportObject.ReportError      = de.Message;
                _ReportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            catch (IOException ioe)
            {
                _ReportObject.ReportError      = ioe.Message;
                _ReportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }


            return(isSuccessful);
        }
Пример #49
0
        public void PDFESTADOCERO()
        {
            Buscadores bus    = new Buscadores();
            var        doc    = new iTextSharp.text.Document(PageSize.A4.Rotate());
            string     path   = Server.MapPath("~");
            PdfWriter  writer = PdfWriter.GetInstance(doc, new FileStream(path + "/Presupuesto.pdf", FileMode.Create));

            doc.Open();

            doc.AddTitle("Presupuesto");

            Paragraph p = new Paragraph("Presupuesto");

            p.Alignment = 1;
            p.Font.Size = 24;
            doc.Add(p);
            PdfContentByte cb = writer.DirectContent;

            cb.MoveTo(100, 0);
            cb.LineTo(0, 0);
            cb.Stroke();
            doc.Add(Chunk.NEWLINE);
            Paragraph d = new Paragraph("Orden N°: " + OrdenActual.id_orden);

            d.Alignment = 2;
            d.Font.Size = 12;
            doc.Add(d);

            //////////////////////////////////////////desde aca yo me mando las cagadas////////////////////////////////////////////////

            Paragraph fe = new Paragraph(DateTime.Now.ToString("dd-MM-yyyy"));

            fe.Alignment = 2;
            fe.Font.Size = 12;
            doc.Add(fe);

            Paragraph op = new Paragraph("Operario: " + LogEmpleado.nombreyapellido);

            op.Alignment = 2;
            op.Font.Size = 12;
            doc.Add(op);
            doc.Add(Chunk.NEWLINE);

            /////////////////////////////////////////hasta aca llego mi cagada/////////////////////////////////////////////////////////

            vehiculo ovehiculo = bus.buscarvehiculo(txtpatente.Value);
            cliente  ocliente  = bus.ocliente(ovehiculo);
            modelo   omarca    = bus.buscarmodelo(ovehiculo);
            marca    omodelo   = bus.buscarmarca(omarca);

            Paragraph Cliente = new Paragraph("Apellido y Nombre: " + ocliente.nombre + "                 DNI: " + ocliente.dni + "            Telefono: " + ocliente.telefono + "        Correo Electronico: " + ocliente.email);

            doc.Add(Cliente);
            doc.Add(Chunk.NEWLINE);
            Paragraph Vehiculo = new Paragraph("Patente: " + ovehiculo.patente + "          Modelo: " + omodelo.nombre + "       Marca: " + omarca.nombre);

            doc.Add(Vehiculo);
            doc.Add(Chunk.NEWLINE);



            PdfPTable pdfTable = new PdfPTable(GridView2.HeaderRow.Cells.Count);

            foreach (TableCell headerCell in GridView2.HeaderRow.Cells)
            {
                PdfPCell pdfCell = new PdfPCell(new Phrase(headerCell.Text));
                pdfTable.AddCell(pdfCell);
            }

            foreach (GridViewRow gridViewRow in GridView2.Rows)
            {
                foreach (TableCell tableCell in gridViewRow.Cells)
                {
                    PdfPCell pdfCell = new PdfPCell(new Phrase(tableCell.Text));
                    pdfTable.AddCell(pdfCell);
                }
            }
            doc.Add(pdfTable);
            Paragraph tt = new Paragraph("Total: $" + lblprecio.Text);

            tt.Alignment = 2;
            tt.Font.Size = 12;
            doc.Add(tt);
            doc.Add(Chunk.NEWLINE);

            doc.Close();
            Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('Presupuesto.pdf','_newtab');", true);
            //Response.Redirect("Presupuesto.pdf");
        }
Пример #50
0
        public void PrintPDF()
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog()
            {
                Filter = "pdf|*.pdf"
            };

            saveFileDialog.ShowDialog();
            string fileName = saveFileDialog.FileName;

            iTextSharp.text.Document oDoc = new iTextSharp.text.Document(PageSize.A4, 25, 25, 30, 30);

            try {
                PdfWriter.GetInstance(oDoc, new FileStream(fileName, FileMode.Create));

                oDoc.Open();

                //Meta data
                oDoc.AddAuthor("Dariusz Momot & Łukasz Kudzia");
                oDoc.AddCreator("NutritionApp");
                oDoc.AddTitle("Grocery List");

                //Fonts
                Font titleFont = FontFactory.GetFont("Verdana", 8, Font.ITALIC);
                titleFont.Color = BaseColor.DARK_GRAY;

                Font cellFonnt = FontFactory.GetFont(FontFactory.COURIER, 12, BaseColor.DARK_GRAY);

                //Title
                Paragraph title = new Paragraph("Your grocery list from " + DateTime.Now, titleFont);
                title.Alignment = Element.ALIGN_CENTER;
                oDoc.Add(title);
                oDoc.Add(new Paragraph("\n"));
                oDoc.Add(new Paragraph("\n"));

                //Table
                PdfPTable table = new PdfPTable(3);
                foreach (var item in GroceryList)
                {
                    table.AddCell(item.Count.ToString());
                    table.AddCell(item.Units.ToString());
                    table.AddCell(item.Name);
                }
                table.HorizontalAlignment = Element.ALIGN_CENTER;
                table.PaddingTop          = 20f;
                oDoc.Add(table);
                oDoc.Add(new Paragraph("\n"));
                oDoc.Add(new Paragraph("\n"));

                Paragraph foter = new Paragraph("Create by NutritionApp", titleFont);
                oDoc.Add(foter);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Cannot save your list", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            finally
            {
                oDoc.Close();
            }
        }
Пример #51
0
 public override void Write(PdfWriter writer, Document doc) {
     doc.AddTitle(content);
 }
Пример #52
0
    public static void ExportToSpreadsheet(DataTable table, string reportOIDStr, String reportType)
    {
        try
        {
            Reports report = null;
            if (!string.IsNullOrEmpty(reportOIDStr))
            {
                report = new Reports().GetReportByOID(Int32.Parse(reportOIDStr));
            }
            if ((report == null) || (table == null))
            {
                return;
            }
            else
            {
                String gridColumnsStr = Convert.ToString(report.GridColumns);
                String[] gridColumns = gridColumnsStr.Split('&');

                foreach (String gridColumn in gridColumns)
                {
                    String[] nameValue = gridColumn.Split('=');
                    if (nameValue[1] == "true")
                    {
                        try
                        {
                            table.Columns.Remove(nameValue[0]);
                        }
                        catch
                        { }
                    }
                }
            }

            if (reportType == "CSV")
            {
                //Remove Comma from Text
                string tempStr = "";
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    for (int j = 0; j < table.Columns.Count; j++)
                    {
                        tempStr = Convert.ToString(table.Rows[i][j]);
                        if (tempStr.Contains(','))
                        {
                            table.Rows[i][j] = tempStr.Replace(',', ' ');
                        }
                    }
                }

                HttpContext context = HttpContext.Current;
                context.Response.Clear();
                context.Response.ContentType = "text/csv";
                context.Response.AddHeader("Content-Disposition", "attachment; filename=" + report.ReportName +"_"+DateTime .Now .ToShortDateString ()+ ".csv");

                //Write a row for column names
                foreach (DataColumn dataColumn in table.Columns)
                context.Response.Write(dataColumn.ColumnName + ",");
                context.Response.Write(Environment.NewLine);

                //Write one row for each DataRow
                foreach (DataRow dataRow in table.Rows)
                {
                    for (int dataColumnCount = 0; dataColumnCount < table.Columns.Count; dataColumnCount++)
                        context.Response.Write(dataRow[dataColumnCount].ToString() + ",");
                    context.Response.Write(Environment.NewLine);
                }
                context.Response.End();
            }
            else if (reportType == "Excel")
            {
                DataGrid dtaFinal = new DataGrid();
                dtaFinal.DataSource = table;
                dtaFinal.DataBind();

                dtaFinal.HeaderStyle.ForeColor = System.Drawing.Color.White;
                dtaFinal.HeaderStyle.BackColor = System.Drawing.Color.DarkGray;
                dtaFinal.ItemStyle.BackColor = System.Drawing.Color.White;
                dtaFinal.AlternatingItemStyle.BackColor = System.Drawing.Color.AliceBlue;

                StringWriter sw = new StringWriter();
                HtmlTextWriter hw = new HtmlTextWriter(sw);
                dtaFinal.RenderControl(hw);

                HttpContext context = HttpContext.Current;
                context.Response.Buffer = true;
                context.Response.Clear();

                context.Response.ContentType = "application/ms-excel";
                context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + report.ReportName + ".xls");

                context.Response.Write(sw.ToString());
                context.Response.Flush();
                context.Response.Close();
                context.Response.End();
            }
            else if (reportType == "PDF")
            {
                HttpResponse Response = HttpContext.Current.Response;
                Response.Clear();
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + report.ReportName +"_"+DateTime .Now.ToShortDateString ()+ ".pdf");

                // step 1: creation of a document-object
                Document document = new Document(new Rectangle(880f, 612f), 20, 20, 30, 20);

                // step 2: we create a writer that listens to the document
                PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);

                document.AddTitle(report.ReportName);

                //Phrase phFooter = new Phrase(""); //empty phrase for page numbering
                //HeaderFooter footer = new HeaderFooter(phFooter, true);
                //document.Footer = footer;

                // step 3: we open the document
                document.Open();

                // step 4: we add content to the document

                ////document.Add(FormatHeaderPhrase(table.TableName));
                PdfPTable pdfTable = new PdfPTable(table.Columns.Count);
                pdfTable.DefaultCell.Padding = 3;
                pdfTable.WidthPercentage = 100; // percentage
                pdfTable.DefaultCell.BorderWidth = 2;
                pdfTable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;

                foreach (DataColumn column in table.Columns)
                {
                    pdfTable.AddCell(column.ColumnName);
                }
                pdfTable.HeaderRows = 1;  // this is the end of the table header
                pdfTable.DefaultCell.BorderWidth = 1;
                Color altRow = new Color(242, 242, 242);
                int i = 0;
                foreach (DataRow row in table.Rows)
                {
                    i++;
                    if (i % 2 == 1)
                    {
                        pdfTable.DefaultCell.BackgroundColor = altRow;
                    }
                    foreach (object cell in row.ItemArray)
                    {
                        //assume toString produces valid output
                        ////pdfTable.AddCell(FormatPhrase(cell.ToString()));
                        pdfTable.AddCell(Convert.ToString(cell));
                    }
                    if (i % 2 == 1)
                    {
                        pdfTable.DefaultCell.BackgroundColor = Color.WHITE;
                    }
                }
                document.Add(pdfTable);

                // step 5: we close the document
                document.Close();
            }

        }
        catch (Exception ex)
        { }
    }
Пример #53
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (openFile1.SafeFileName == "" || openFile2.SafeFileName == "")
            {
                MessageBox.Show("No haz seleccionado ningún PDF", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            MessageBox.Show("Se unira \"" + openFile1.SafeFileName + "\" con \"" + openFile2.SafeFileName + "\"");
            saveFile.Filter = "Adobe Acrobat Document PDF (*.pdf)|*.pdf";
            saveFile.FilterIndex = 1;
            if (saveFile.ShowDialog() == DialogResult.OK)
            {
                MessageBox.Show("Se guardara en la siguiente ruta:\n" + saveFile.FileName);

                FileStream myStream = new FileStream(saveFile.FileName,FileMode.OpenOrCreate);

                PdfReader reader  = new PdfReader(openFile1.FileName);
                PdfReader reader2 = new PdfReader(openFile2.FileName);
                Document document = new Document(reader.GetPageSizeWithRotation(1));
                PdfCopy writer = new PdfCopy(document, myStream);
                document.Open();
                document.AddCreationDate();
                if (txtAutor.Text != null)
                {
                    document.AddAuthor(txtAutor.Text);
                }
                if (txtHeader.Text != null)
                {
                    document.AddHeader(txtHeader.Text, "Document");
                }
                if (txtKeywords.Text != null)
                {
                    document.AddKeywords(txtKeywords.Text);
                }

                document.AddProducer();

                if (txtTitulo.Text != null)
                {
                    document.AddTitle(txtTitulo.Text);
                }
                // Calculando incremento
                progressBar.Refresh();
                int incremento = (int)(100 / (reader.NumberOfPages + reader2.NumberOfPages));
                MessageBox.Show("Incremento es: " + incremento);
                for (int i = 1; i <= reader.NumberOfPages; i++)
                {
                    writer.AddPage(writer.GetImportedPage(reader, i));
                    progressBar.PerformStep();
                    progressBar.Increment(++incremento);
                }
                progressBar.Increment(50);
                for (int i = 1; i <= reader2.NumberOfPages; i++)
                {
                    writer.AddPage(writer.GetImportedPage(reader2, i));
                    progressBar.PerformStep();
                }
                progressBar.Increment(100);
                document.Close();
            }
        }
Пример #54
0
        public bool Print()
        {
            try
            {
                rptFont       = FontFactory.GetFont("Arial", 8, Font.NORMAL);
                rptFontBold   = FontFactory.GetFont("Arial", 8, Font.BOLD);
                rptFontHeader = FontFactory.GetFont("Arial", 10, Font.BOLD);

                if (string.IsNullOrWhiteSpace(Context.OutputPath))
                {
                    FileLogger.Instance.logMessage(LogLevel.ERROR, this, "Indiana Lost Ticket Affidavit printing failed since file name is not set");
                    return(false);
                }

                document = new Document(PageSize.HALFLETTER.Rotate());
                document.AddTitle("Lost Ticket Affidavit");
                var writer = PdfWriter.GetInstance(document, new FileStream(Context.OutputPath, FileMode.Create));

                const int mainTableColumns = 2;
                var       mainTable        = new PdfPTable(mainTableColumns)
                {
                    WidthPercentage = 100
                };
                mainTable.SetWidths(new float[] { .5F, 10 });

                mainTable.AddCell(new PdfPCell(new Paragraph("Lost Ticket Affidavit", rptFontHeader))
                {
                    Border = Rectangle.BOTTOM_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, Colspan = mainTableColumns
                });

                mainTable.AddCell(new PdfPCell()
                {
                    Border = Rectangle.NO_BORDER
                });
                mainTable.AddCell(new PdfPCell(new Paragraph("I, " + Context.CustomerName + ", hereby affirm as follows:", rptFont))
                {
                    Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE
                });
                mainTable.AddCell(new PdfPCell(new Phrase("1.", rptFont))
                {
                    Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                });
                mainTable.AddCell(new PdfPCell(new Paragraph("I am the pledgor of a pawn ticket issued by", rptFont))
                {
                    Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                });
                mainTable.AddCell(new PdfPCell()
                {
                    Border = Rectangle.NO_BORDER
                });
                mainTable.AddCell(new PdfPCell(new Paragraph(Context.StoreName + " " + Context.StoreNumber + ", IN", rptFont))
                {
                    Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                });
                mainTable.AddCell(new PdfPCell()
                {
                    Border = Rectangle.NO_BORDER
                });
                mainTable.AddCell(new PdfPCell(new Paragraph("number " + Context.TicketNumber + " and dated " + Context.LoanDateMade.FormatDate(), rptFont))
                {
                    Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                });
                mainTable.AddCell(new PdfPCell(new Phrase("2.", rptFont))
                {
                    Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                });
                mainTable.AddCell(new PdfPCell(new Paragraph("The above-described pawn ticket has not been sold, negotiated or transferred in any other manner by me.", rptFont))
                {
                    Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                });
                mainTable.AddCell(new PdfPCell(new Phrase("3.", rptFont))
                {
                    Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                });
                mainTable.AddCell(new PdfPCell(new Paragraph("The above-described pawn ticket was " + Context.ReasonMissing + " as follows:", rptFont))
                {
                    Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                });
                mainTable.AddCell(new PdfPCell()
                {
                    Border = Rectangle.NO_BORDER
                });
                mainTable.AddCell(new PdfPCell(new Paragraph(string.Empty, rptFont))
                {
                    Border = Rectangle.BOTTOM_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, FixedHeight = 15
                });
                mainTable.AddCell(new PdfPCell(new Phrase("4.", rptFont))
                {
                    Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                });
                mainTable.AddCell(new PdfPCell(new Paragraph("The pledge represented by this pawn ticket is", rptFont))
                {
                    Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, FixedHeight = 20
                });
                mainTable.AddCell(new PdfPCell()
                {
                    Border = Rectangle.NO_BORDER
                });
                mainTable.AddCell(new PdfPCell(new Paragraph(Context.MerchandiseDescription, rptFont))
                {
                    Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, MinimumHeight = 50
                });
                mainTable.AddCell(new PdfPCell(new Phrase("5.", rptFont))
                {
                    Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                });
                mainTable.AddCell(new PdfPCell(new Paragraph("I affirm, under the penalties for perjury, that the foregoing representations are true.", rptFont))
                {
                    Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                });
                mainTable.AddCell(new PdfPCell(new Paragraph("", rptFont))
                {
                    Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                });

                var signatureTable = new PdfPTable(2)
                {
                    WidthPercentage = 100
                };

                signatureTable.SetWidths(new float[] { 1, 1 });

                signatureTable.AddCell(new PdfPCell()
                {
                    Border = Rectangle.NO_BORDER
                });
                signatureTable.AddCell(new PdfPCell(new Phrase(string.Empty))
                {
                    Border = Rectangle.BOTTOM_BORDER, FixedHeight = 30
                });
                signatureTable.AddCell(new PdfPCell()
                {
                    Border = Rectangle.NO_BORDER
                });
                signatureTable.AddCell(new PdfPCell(new Phrase("Affiant", rptFont))
                {
                    Border = Rectangle.NO_BORDER
                });

                mainTable.AddCell(new PdfPCell(signatureTable)
                {
                    Colspan = 2, Border = Rectangle.NO_BORDER
                });

                document.Open();
                document.Add(mainTable);
                document.Close();
            }
            catch (Exception de)
            {
                FileLogger.Instance.logMessage(LogLevel.ERROR, this, "Indiana Lost Ticket Affidavit printing" + de.Message);
                return(false);
            }

            return(true);
        }
        private void Speichern(string filename)
        {
            try
            {
                Document document = new Document();
                PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create));
                document.AddTitle("Portscanner Report");
                document.AddCreationDate();
                document.Open();
                document.Add(new Paragraph("Portscanner: IP/Port list", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 16, iTextSharp.text.Font.UNDERLINE)));
                document.Add(new Paragraph(" "));

                foreach (ListViewItem item in lv_Port.Items)
                {
                    document.Add(new Paragraph("IP:        " + item.SubItems[0].Text + item.SubItems[1].Text));
                    document.Add(new Paragraph("Port:     " + item.SubItems[1].Text));
                    document.Add(new Paragraph("Status:  " + item.SubItems[4].Text));
                    document.Add(new Paragraph(" "));
                }
                document.Close();
            }
            catch (IOException)
            {
                MessageBox.Show("The file is in use. Please close all applications accessing this file and try again.", "Access not possible", MessageBoxButtons.OK);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Fehler beim Speichern" + ex);
            }
        }
Пример #56
0
        private void generateReport()
        {
            try
            {
                String equipmentName = "";

                document = new Document(PageSize.LETTER);

                String FilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\\Resources\\" + inspectionType.Text + "_" + DateTime.Today.ToString("yyyy-MM-dd") +".pdf";

                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(FilePath, FileMode.OpenOrCreate));
                document.Open();

                document.AddTitle("Report");
                document.AddSubject("Equipment Report");
                document.AddKeywords("Csharp, PDF, iText");
                document.AddAuthor("");
                document.AddCreator("");

                iTextSharp.text.Image pdfLogo = iTextSharp.text.Image.GetInstance(AppDomain.CurrentDomain.BaseDirectory + "\\Resources\\" + "logo.JPG");

                pdfLogo.Alignment = iTextSharp.text.Image.ALIGN_RIGHT;
                pdfLogo.ScaleAbsolute(150, 85);

                document.Add(pdfLogo);
                Paragraph preface = new Paragraph("Fire-Alert" + "\n" + "Report of " + inspectionType.Text + "\n", TimesTitle);

                preface.Alignment = Element.ALIGN_CENTER;

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

                #region Inspection table

                PdfPTable inspectionTable = new PdfPTable(1);

                if (inspectionType.Text.Contains("Extinguisher"))
                    equipmentName = "Extinguisher";
                else if (inspectionType.Text.Contains("Hose"))
                    equipmentName = "FireHoseCabinet";
                else if (inspectionType.Text.Contains("Light"))
                    equipmentName = "EmergencyLight";

                // Load XML inspection file from resources
                string url = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\\Resources\\inspection.xml";
                XmlDocument doc = new System.Xml.XmlDocument();
                doc.Load(url);
                XmlElement docElement = doc.DocumentElement;

                // loop through all childNodes
                XmlNode start = docElement.FirstChild;              // franchisee
                foreach (XmlNode c1 in start)                       // contracts
                {
                    foreach (XmlNode c2 in c1.ChildNodes)        // addresses
                    {

                        // Skip if not matching contract ID
                        if (Convert.ToInt32(c2.Attributes["id"].InnerText) == Convert.ToInt32(addressBox.SelectedValue))
                        {
                            Console.WriteLine(Convert.ToInt32(c1.Attributes["id"].InnerText));
                            Console.WriteLine(Convert.ToInt32(addressBox.SelectedValue));

                            #region Address info table

                            PdfPTable addrTable = new PdfPTable(4);
                            addrTable.HorizontalAlignment = Element.ALIGN_LEFT;
                            addrTable.TotalWidth = 530f;
                            addrTable.LockedWidth = true;

                            float[] addrWidths = new float[] { 50f, 100f, 50f, 100f };
                            addrTable.SetWidths(addrWidths);

                            XmlAttributeCollection billTo = c1.ParentNode.Attributes;
                            XmlAttributeCollection location = c2.Attributes;

                            string[] billToAddr = billTo["address"].InnerText.Split(',');

                            addCell(addrTable, "Bill To:", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);
                            addCell(addrTable, billTo["name"].InnerText, 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);

                            addCell(addrTable, "Location:", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);

                            addCell(addrTable, location["contact"].InnerText, 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);
                            addCell(addrTable, " ", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);
                            addCell(addrTable, billToAddr[0], 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);

                            addCell(addrTable, " ", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);
                            addCell(addrTable, location["address"].InnerText, 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);
                            addCell(addrTable, " ", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);
                            addCell(addrTable, billToAddr[2] + "," + billToAddr[1], 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);

                            addCell(addrTable, " ", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);
                            addCell(addrTable, location["city"].InnerText, 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);
                            addCell(addrTable, " ", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);
                            addCell(addrTable, billToAddr[3], 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);

                            addCell(addrTable, " ", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);
                            addCell(addrTable, location["postalCode"].InnerText, 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);

                            addCell(addrTable, "Tel:", 2, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);
                            addCell(addrTable, new Franchisee().getAddress(Convert.ToInt32(start.Attributes["id"].InnerText))[0], 2, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);

                            String clientInfo = new Client().get(new ClientContract().getClient(addressBox.SelectedValue.ToString()));
                            String[] client = new String[9];
                            client = clientInfo.Split(',');

                            if (client.Length < 6)
                                client = new String[6] {"", "", "", "", "", "No client found" };

                            addCell(addrTable, "Contact:", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);
                            addCell(addrTable, client[5], 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);
                            addCell(addrTable, "Tel:", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);
                            addCell(addrTable, client[3], 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);

                            addCell(addrTable, " ", 4, 4, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);

                            string technicianID = c2.Attributes["InspectorID"].InnerText;
                            string technicianName = new Users().getName(Convert.ToInt32(technicianID));
                            if (technicianName == null || technicianName == "")
                                technicianName = "Technician Not Found";

                            addCell(addrTable, "Technician: ", 2, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);
                            addCell(addrTable, technicianName, 2, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);

                            addCell(addrTable, "Date: ", 2, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);
                            addCell(addrTable, DateTime.Now.ToString("MMMM d, yyyy"), 2, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);

                            for (int i = 0; i < addrTable.Rows.Count; i++)
                                for (int j = 0; j < addrTable.Rows[i].GetCells().Length; j++)
                                {
                                    if (addrTable.Rows[i].GetCells()[j] == null)
                                        continue;

                                    if (j % 2 != 0)     // Add bottom border to info cells
                                        addrTable.Rows[i].GetCells()[j].Border = iTextSharp.text.Rectangle.BOTTOM_BORDER;
                                    else                // Remove bottom border from titles
                                        addrTable.Rows[i].GetCells()[j].Border = iTextSharp.text.Rectangle.NO_BORDER;
                                }

                            #endregion

                            document.Add(addrTable);

                            foreach (XmlNode c3 in c2.ChildNodes)   // floors
                            {
                                foreach (XmlNode c4 in c3.ChildNodes)    //rooms
                                {
                                    bool isFirstEquipment = true;
                                    int itemNum = 1;
                                    foreach (XmlNode c5 in c4.ChildNodes)    // equipment
                                    {
                                        if (c5.Name.Equals(equipmentName))
                                        {
                                            #region Set up header

                                            if (isFirstEquipment)   // Set up table header based on first piece of equipment
                                            {
                                                isFirstEquipment = false;

                                                inspectionTable = new PdfPTable(c5.Attributes.Count + c5.ChildNodes.Count + 1);
                                                inspectionTable.HorizontalAlignment = 0;
                                                inspectionTable.TotalWidth = 530f;
                                                inspectionTable.LockedWidth = true;
                                                float []iWidths = new float[c5.Attributes.Count + c5.ChildNodes.Count + 1];

                                                iWidths[0] = 20f;
                                                for (int i = 1; i < iWidths.Length; i++)
                                                {
                                                    if (i < c5.Attributes.Count + 1)
                                                        iWidths[i] = 35f;
                                                    else
                                                        iWidths[i] = 20f;
                                                }
                                                inspectionTable.SetWidths(iWidths);

                                                createHeader(inspectionTable, c5);
                                            }

                                            #endregion

                                            addEquipmentRow(inspectionTable, c5, itemNum);
                                            itemNum++;
                                        }

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

                #endregion

                document.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not display the document because " + ex.ToString());
            }
        }
Пример #57
0
        public ActionResult InformeEmpleado(int empno)
        {
            EMP empleado = this.entidad.EMP.Find(empno);
            Document doc = new Document(PageSize.LETTER);
            //CAPTURAMOS LA RUTA AL DOCUMENTO
            String ruta = HttpContext.Server.MapPath("/PDF/");
            ruta = ruta + "informe" + empno.ToString() + ".pdf";
            //PREGUNTAMOS SI EL DOCUMENTO EXISTE PREVIAMENTE
            if (System.IO.File.Exists(ruta))
            {
                return File(ruta, "application/pdf");
            }
            else
            {
                //CREAMOS EL DOCUMENTO
                PdfWriter writer = PdfWriter.GetInstance(doc,
                                            new FileStream(ruta, FileMode.Create));

                //INCLUIMOS TITULO Y AUTOR DEL DOCUMENTO
                doc.AddTitle("Informe empleado " + empleado.APELLIDO);
                doc.AddCreator("Ejemplo MVC");

                //ABRIMOS EL DOCUMENTO
                doc.Open();
                //DEFINIMOS LA FUENTE DEL DOCUMENTO
                iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 11, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

                //ENCABEZADO DEL DOCUMENTO
                doc.Add(new Paragraph("Informe del empleado: " + empleado.APELLIDO + ", " + DateTime.Now.ToLongDateString()));
                //DAMOS UN SALTO DE LINEA
                doc.Add(Chunk.NEWLINE);

                //CREAMOS UNA TABLA CON LOS DATOS PARA EL EMPLEADO
                //CON CUATRO DATOS A REPRESENTAR
                PdfPTable tabla = new PdfPTable(4);
                tabla.WidthPercentage = 100;

                //CREAMOS LAS COLUMNAS CON SU TITULO Y SU VALOR
                PdfPCell colapellido = new PdfPCell(new Phrase("APELLIDO", _standardFont));
                colapellido.BorderWidth = 0;
                colapellido.BorderWidthBottom = 0.75f;

                PdfPCell coloficio = new PdfPCell(new Phrase("OFICIO", _standardFont));
                coloficio.BorderWidth = 0;
                coloficio.BorderWidthBottom = 0.75f;

                PdfPCell colfecha = new PdfPCell(new Phrase("FECHA DE ALTA", _standardFont));
                colfecha.BorderWidth = 0;
                colfecha.BorderWidthBottom = 0.75f;

                PdfPCell colsalario = new PdfPCell(new Phrase("SALARIO", _standardFont));
                colsalario.BorderWidth = 0;
                colsalario.BorderWidthBottom = 0.75f;

                //AÑADIMOS LAS CELDAS A LA TABLA
                tabla.AddCell(colapellido);
                tabla.AddCell(coloficio);
                tabla.AddCell(colfecha);
                tabla.AddCell(colsalario);

                //AGREGAMOS DATOS A LAS CELDAS
                colapellido = new PdfPCell(new Phrase(empleado.APELLIDO, _standardFont));
                colapellido.BorderWidth = 0;

                coloficio = new PdfPCell(new Phrase(empleado.OFICIO, _standardFont));
                coloficio.BorderWidth = 0;

                colfecha = new PdfPCell(new Phrase(empleado.FECHA_ALT.ToString(), _standardFont));
                colfecha.BorderWidth = 0;

                colsalario = new PdfPCell(new Phrase(empleado.SALARIO.ToString() + "€", _standardFont));
                colsalario.BorderWidth = 0;

                //AÑADIMOS LAS CELDAS A LA TABLA
                tabla.AddCell(colapellido);
                tabla.AddCell(coloficio);
                tabla.AddCell(colfecha);
                tabla.AddCell(colsalario);
                //AGREGAMOS LA TABLA AL DOCUMENTO
                doc.Add(tabla);
                //CERRAMOS EL DOCUMENTO
                doc.Close();
                writer.Close();
                //DEVOLVEMOS EL DOCUMENTO CREADO
                return File(ruta, "application/pdf");

            }
        }
Пример #58
0
        void CreateRem()
        {
            string namefile = comboBox1.Text + "-Рем.pdf";
            //var Документ = new iTextSharp.text.Document();
            var Документ = new Document(); //создаем pdf документ iTextSharp.text.
            var Писатель = PdfWriter.GetInstance(Документ, new System.IO.FileStream(namefile, System.IO.FileMode.Create)); // в текущем каталоге, если файл есть - создаст новый
            Документ.SetPageSize(PageSize.A4.Rotate());
            Документ.AddAuthor("Безверхий О.А.");
            Документ.AddTitle("Отчёт");
            Документ.AddCreator("Программа учёта ТО и Ремонта");
            Документ.Open();
            //Rectangle rec2 = new Rectangle(PageSize.A4);
            //var БазовыйШрифт = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\comic.ttf", "CP1251", BaseFont.EMBEDDED);
            var БазовыйШрифт = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\times.ttf", "CP1251", BaseFont.EMBEDDED);
            var Шрифт = new Font(БазовыйШрифт, 12, iTextSharp.text.Font.NORMAL);

            Paragraph para = new Paragraph("КАРТА УЧЕТА РЕМОНТА " + comboBox2.Text.ToUpper() + "\n", Шрифт);
            para.Alignment = Element.ALIGN_CENTER;
            Документ.Add(para);

            para = new Paragraph(label2.Text, Шрифт);
            para.Alignment = Element.ALIGN_LEFT;
            Документ.Add(para);

            /*para = new Paragraph("МАРКА: КЗС-1218-40 гос. № А283БВ 28rus инв. № 27" + "\n", Шрифт);
            para.Alignment = Element.ALIGN_LEFT;
            Документ.Add(para);

            para = new Paragraph("МЕХАНИЗАТОР: Вася Петя" + "\n\n", Шрифт);
            Документ.Add(para);*/

            /**/
            para = new Paragraph("" + "\n", Шрифт);
            Документ.Add(para);

            /*var Tabla = new PdfPTable(6);
            Документ.Add(Tabla);*/
            PdfPTable table = new PdfPTable(dataGridView1.Columns.Count);
            for (int j = 0; j < dataGridView1.Columns.Count; j++)
            {
                table.AddCell(new Phrase(dataGridView1.Columns[j].HeaderText, Шрифт));
            }
            table.HeaderRows = 1;
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                for (int k = 0; k < dataGridView1.Columns.Count; k++)
                {
                    if (dataGridView1[k, i].Value != null)
                    {
                        table.AddCell(new Phrase(dataGridView1[k, i].Value.ToString(), Шрифт));
                    }
                }
            }
            Документ.Add(table);

            para = new Paragraph("" + "\n", Шрифт);
            Документ.Add(para);

            para = new Paragraph("Подпись руководителя: ", Шрифт);
            para.Alignment = Element.ALIGN_LEFT;
            Документ.Add(para);

            //Документ.Add(new iTextSharp.text.Paragraph("Текст после таблицы", Шрифт));
            Документ.Close();
            Писатель.Close();
            System.Diagnostics.Process.Start(namefile);
        }
Пример #59
0
        public bool CreateReport()
        {
            bool isSuccessful = false;
            var  document     = new iTextSharp.text.Document(PageSize.LETTER);

            try
            {
                //set up RunReport event overrides & create doc
                //ReportObject.BuildChargeOffsList();
                ReportObject.ReportTempFile = "c:\\Program Files\\Phase2App\\logs\\AuditReportsTemp\\";
                ReportObject.CreateTemporaryFullName("InventorySummaryResponseReport");
                _pageCount = 1;
                var events = this;
                var writer = PdfWriter.GetInstance(document, new FileStream(ReportObject.ReportTempFileFullName, FileMode.Create));
                writer.PageEvent = events;

                MultiColumnText columns   = new MultiColumnText(document.PageSize.Top - 120, document.PageSize.Height);
                float           pageLeft  = document.PageSize.Left;
                float           pageright = document.PageSize.Right;
                columns.AddSimpleColumn(20, document.PageSize.Width - 20);

                //set up tables, etc...

                var cell = new PdfPCell();
                var gif  = Image.GetInstance(Common.Properties.Resources.logo, BaseColor.WHITE);
                gif.ScalePercent(25);
                runReport = new RunReport();
                document.Open();
                document.SetPageSize(PageSize.LETTER);
                document.SetMargins(-100, -100, 10, 45);
                document.AddTitle(ReportObject.ReportTitle + ": " + DateTime.Now.ToString("MM/dd/yyyy"));


                var additionalCommentsSectionTable = new PdfPTable(1);
                additionalCommentsSectionTable.WidthPercentage = 100;// document.PageSize.Width;
                WriteAdditionalCommentsSection(additionalCommentsSectionTable);
                columns.AddElement(additionalCommentsSectionTable);

                var deficiencesSectionTable = new PdfPTable(4);
                deficiencesSectionTable.WidthPercentage = 100;// document.PageSize.Width;
                WriteDeficiencesSection(deficiencesSectionTable);
                columns.AddElement(deficiencesSectionTable);

                var inventoryHistorySectionTable = new PdfPTable(9);
                inventoryHistorySectionTable.WidthPercentage = 100;// document.PageSize.Width;
                WriteInventoryHistorySection(inventoryHistorySectionTable);
                columns.AddElement(inventoryHistorySectionTable);

                document.Add(columns);
                document.Close();
                OpenFile(ReportObject.ReportTempFileFullName);
                //CreateReport();
                isSuccessful = true;
            }
            catch (DocumentException de)
            {
                ReportObject.ReportError = de.Message;
                //ReportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            catch (IOException ioe)
            {
                ReportObject.ReportError = ioe.Message;
                //ReportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            return(isSuccessful);
        }
Пример #60
0
        private Boolean AñadirDatos()
        {
            Document  doc    = new Document(PageSize.LETTER);
            PdfWriter writer = null;
            // Indicamos donde vamos a guardar el documento
            int numero = 0;

            for (int i = 0; i <= numero; i++)
            {
                if (System.IO.File.Exists("C:/Users/vichg/OneDrive/Escritorio/ControlAlumnos" + numero + ".pdf"))
                {
                    numero++;
                }
                else
                {
                    writer = PdfWriter.GetInstance(doc,
                                                   new FileStream(@"C:\Users\vichg\OneDrive\Escritorio\ControlAlumnos" + numero + ".pdf", FileMode.Create));
                }
            }

            // Le colocamos el título y el autor
            // **Nota: Esto no será visible en el documento
            doc.AddTitle("Lista de Alumnos ");
            doc.AddCreator("Luis Enrique García Rodríguez y Victor Hugo Gonzales Arreola");

            // Abrimos el archivo
            doc.Open();

            iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

            // Escribimos el encabezamiento en el documento
            doc.Add(new Paragraph("         Lista de ALumnos 2019 Clase Desarrollo Asp.NET"));
            doc.Add(Chunk.NEWLINE);

            // Creamos una tabla que contendrá el nombre, apellido y país
            // de nuestros visitante.
            PdfPTable tblPrueba = new PdfPTable(5);

            tblPrueba.WidthPercentage = 100;

            // Configuramos el título de las columnas de la tabla
            PdfPCell clControl = new PdfPCell(new Phrase("Numero Control", _standardFont));

            clControl.BorderWidth       = 0;
            clControl.BorderWidthBottom = 0.50f;

            PdfPCell clNombre = new PdfPCell(new Phrase("Nombre Alumno", _standardFont));

            clNombre.BorderWidth       = 0;
            clNombre.BorderWidthBottom = 0.50f;

            PdfPCell clCarrera = new PdfPCell(new Phrase("Carrera", _standardFont));

            clCarrera.BorderWidth       = 0;
            clCarrera.BorderWidthBottom = 0.50f;

            PdfPCell clSemestre = new PdfPCell(new Phrase("Semestre", _standardFont));

            clSemestre.BorderWidth       = 0;
            clSemestre.BorderWidthBottom = 0.50f;

            PdfPCell clCorreo = new PdfPCell(new Phrase("Correo", _standardFont));

            clCorreo.BorderWidth       = 0;
            clCorreo.BorderWidthBottom = 0.50f;


            // Añadimos las celdas a la tabla
            tblPrueba.AddCell(clControl);
            tblPrueba.AddCell(clNombre);
            tblPrueba.AddCell(clCarrera);
            tblPrueba.AddCell(clSemestre);
            tblPrueba.AddCell(clCorreo);

            int iPosicion = 0;

            foreach (GridViewRow row in GrdAlumnos.Rows)
            {
                doc.Add(Chunk.NEWLINE);
                iPosicion++;

                // Llenamos la tabla con información
                clControl             = new PdfPCell(new Phrase(row.Cells[0].Text, _standardFont));
                clControl.BorderWidth = 0;

                clNombre             = new PdfPCell(new Phrase(row.Cells[1].Text, _standardFont));
                clNombre.BorderWidth = 0;

                clCarrera             = new PdfPCell(new Phrase(row.Cells[2].Text, _standardFont));
                clCarrera.BorderWidth = 0;

                clSemestre             = new PdfPCell(new Phrase(row.Cells[3].Text, _standardFont));
                clSemestre.BorderWidth = 0;

                clCorreo             = new PdfPCell(new Phrase(row.Cells[4].Text, _standardFont));
                clCorreo.BorderWidth = 0;

                // Añadimos las celdas a la tabla
                tblPrueba.AddCell(clControl);
                tblPrueba.AddCell(clNombre);
                tblPrueba.AddCell(clCarrera);
                tblPrueba.AddCell(clSemestre);
                tblPrueba.AddCell(clCorreo);
            }
            doc.Add(tblPrueba);

            doc.Close();
            writer.Close();
            return(true);
        }