AddKeywords() публичный метод

Adds the keywords to a Document.
public AddKeywords ( string keywords ) : bool
keywords string keywords to add
Результат 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
        // 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();
                    }
            }
            
            
        }
Пример #5
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();
        }
Пример #6
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();
        }
        private void btn_Update_Click(object sender, EventArgs e)
        {
            //the library for create a new pdf document
            iTextSharp.text.Document report = new iTextSharp.text.Document();
            //file path of newly created pdf file to save
            PdfWriter.GetInstance(report, new FileStream(@"C:\Users\Asus\Desktop\UPLOADFILES\" + textboxFileName.Text, FileMode.Create));
            //Author name, need for create a new pdf document
            report.AddAuthor(lbl_Author.Text);
            //Creation Date, need for create a new pdf document
            report.AddCreationDate();
            //Creator, need for create a new pdf document
            report.AddCreator(lbl_Creator.Text);
            //Subject, need for create a new pdf document
            report.AddSubject(lbl_Subject.Text);
            //Keywords, need for create a new pdf document
            report.AddKeywords(lbl_Keyword.Text);

            if (report.IsOpen() == false)
            {
                //open report for create a new pdf document
                report.Open();
            }
            //Paragraph, need for create a new pdf document
            report.Add(new Paragraph(rtxt_Paragraph.Text));

            //open the connection
            db.openConnection();
            //a command line for update the document
            SqlCommand query = new SqlCommand("UPDATE Table_DOCUMENT SET file_Path = @fp, u_ID = @uid WHERE file_ID = @fid", db.getConnection());

            //add the value in the label to @fp
            query.Parameters.AddWithValue("@fp", labelFilePath.Text);
            //add the value in the combobox to @uid
            query.Parameters.AddWithValue("@uid", comboboxUserID.Text);
            //add the value in the label to @fid
            query.Parameters.AddWithValue("@fid", labelFileID.Text);

            //ecevute the query
            if (query.ExecuteNonQuery() == 1)
            {
                MessageBox.Show("DATA WERE UPDATED", "Message Box", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
                //return the default values
                labelFilePath.Text     = @"C:\Users\Asus\Desktop\UPLOADFILES";
                textboxFilePath.Text   = "";
                labelFileID.Text       = "";
                lbl_FileName.Text      = "";
                labelCreationDate.Text = "";
                comboboxUserID.Text    = " ";
                rtxt_Paragraph.Text    = "";
            }
            else
            {
                MessageBox.Show("ERROR", "Message Box", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
            }
            //close the report
            report.Close();
            //close the connection
            db.closeConnection();
        }
        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;
            }
        }
    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();
            }
    }
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            iTextSharp.text.Document raporum = new iTextSharp.text.Document();
            PdfWriter.GetInstance(raporum, new FileStream("C:'" + LblHastaAdı.Text + LblRecerteKodu.Text + "'.pdf", FileMode.Create));
            raporum.AddAuthor(LblHastane.Text + "/" + LblDoktor.Text);
            raporum.AddCreationDate();
            raporum.AddCreator(LblHastane.Text + "/" + LblDoktor.Text);
            raporum.AddSubject("Recete" + LblRecerteKodu.Text);
            raporum.AddKeywords(LblHastaAdı.Text);

            if (raporum.IsOpen() == false)
            {
                raporum.Open();
            }
            raporum.Add(new Paragraph(LblRecete.Text));
            pictureBox1.Enabled = false;
            PdfOku();
        }
Пример #11
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();    
      }
    }    
Пример #12
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();
        }
Пример #13
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);
     }
 }
Пример #14
0
        private void btnAraToplam_Click(object sender, EventArgs e)
        //PDF DOSYASI OLARAK KAYDETME ORTAMI BURASI.
        {
            try
            {
                if (listView1.Items.Count > 0)
                {
                    DialogResult cevap = MessageBox.Show("Fiş istiyor musunuz?", "HESAP", MessageBoxButtons.YesNo);
                    if (cevap == DialogResult.Yes)
                    {
                        string fileName = "", tarih = "", kuver = "", fiyat = "", urunAdi = "";
                        int    fisID = 0;
                        int    temp = int.Parse(MainForm.Masa), fiyatUrun = 0;

                        using (var cafeContext = new CafeContext())
                        {
                            var result = from receipts in cafeContext.Receipts
                                         join orders in cafeContext.Orders
                                         on receipts.TableNumber equals orders.TableNumber
                                         where receipts.TableNumber == temp && orders.isAlive == true
                                         select new
                            {
                                orders,
                                receipts
                            };

                            foreach (var gez in result)
                            {
                                fileName = gez.receipts.ReceiptID.ToString();
                                tarih    = gez.receipts.Date;
                                fisID    = gez.receipts.ReceiptID;
                                kuver    = gez.receipts.Cover.ToString();
                                fiyat    = gez.receipts.TotalPrice.ToString();
                            }

                            var resultProduct = from orders in cafeContext.Orders
                                                join product in cafeContext.Products
                                                on orders.Product.ProductID equals product.ProductID
                                                where orders.isAlive == true & orders.TableNumber == temp
                                                select new
                            {
                                orders,
                                product
                            };

                            iTextSharp.text.Document raporum = new iTextSharp.text.Document();
                            PdfWriter.GetInstance(raporum, new FileStream("C:" + fileName + ".pdf", FileMode.Create));
                            raporum.AddAuthor("Cafelania");
                            raporum.AddCreationDate();
                            raporum.AddSubject("FIŞ BILGILERI");
                            raporum.AddKeywords("fis");
                            if (raporum.IsOpen() == false)
                            {
                                raporum.Open();
                            }
                            raporum.Add(new Paragraph("                                         CAFELANIA                                             " + tarih));
                            raporum.Add(new Paragraph("                                                                                                                              "));
                            raporum.Add(new Paragraph("Fis Numarasi:" + fisID.ToString() + "    Kuver Sayisi:" + kuver + "    Masa Numarasi:" + temp.ToString()));
                            raporum.Add(new Paragraph("                                                                                                                              "));

                            foreach (var gez in resultProduct)
                            {
                                urunAdi   = gez.product.ProductName;
                                fiyatUrun = int.Parse(gez.product.Amount.ToString()) * int.Parse(gez.orders.ProductCount.ToString());
                                raporum.Add(new Paragraph("Adet: " + gez.orders.ProductCount.ToString() + "                  " + urunAdi + "               " + fiyatUrun.ToString() + "TL"));
                                raporum.Add(new Paragraph("                                                                                                                              "));
                            }
                            raporum.Add(new Paragraph("                                                                                     TOPLAM TUTAR:" + lblfiyat.Text));
                            MessageBox.Show("Toplam hesap: " + lblfiyat.Text + "\nFiş Numarası: " + fisID.ToString());
                            raporum.Close();
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Fiş oluşturmak için lütfen sipariş giriniz.", "Uyarı", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch
            {
            }
        }
        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());
        }
Пример #16
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();
            }
        }
Пример #17
0
 private void UpdateProperties(Document document)
 {
     document.AddAuthor(_settings.Author);
     document.AddCreationDate();
     document.AddCreator(_settings.Creator);
     document.AddKeywords(_settings.Keywords);
     document.AddSubject(_settings.Subject);
     document.AddTitle(_settings.Title);
 }
Пример #18
0
        /// <summary>
        /// PDF生成
        /// </summary>
        public void MakePDF(List<System.Drawing.Image> list)
        {
            Document document = new Document(PageSize.A3);//创建一个Document实例
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(PDFSavePath, FileMode.Create));//创建Writer实例

            document.Open();

            #region 写入一些数据,包括:作者、标题、摘要、关键词、创建者、生产者、创建时间、头信息

            document.AddAuthor("重齿风电");
            document.AddCreationDate();
            document.AddCreator("重齿风电");
            //document.AddHeader("QQ", "346163801");
            //document.AddHeader("Email", "*****@*****.**");
            document.AddKeywords("重齿风电");
            document.AddProducer();
            document.AddSubject("重齿风电");
            document.AddTitle("重齿风电");

            #endregion

            BaseFont baseFont = CreateChineseFont();

            iTextSharp.text.Font titleFont = new iTextSharp.text.Font(baseFont, 22, iTextSharp.text.Font.BOLD);
            iTextSharp.text.Font fontUnderLine = new iTextSharp.text.Font(baseFont, 12, iTextSharp.text.Font.UNDERLINE);
            iTextSharp.text.Font normalFont = new iTextSharp.text.Font(baseFont, 12);
            iTextSharp.text.Font normalRedFont = new iTextSharp.text.Font(baseFont, 12, iTextSharp.text.Font.NORMAL | iTextSharp.text.Font.BOLD, BaseColor.RED);
            //float titleLineHeight = 45f;
            float normalLineHeight = 25f;
            Paragraph pBlank = new Paragraph(" ", normalFont);
            pBlank.Leading = normalLineHeight;
            foreach (var im in list)
            {
                iTextSharp.text.Image jpeg = iTextSharp.text.Image.GetInstance(DoConvert(im,827,1169,80), BaseColor.WHITE);
                jpeg.Alignment = Element.ALIGN_CENTER;
                document.Add(jpeg);
            }

            document.Close();
        }
Пример #19
0
        public static string GenerateHerinnering(Factuur factuur)
        {
            try
            {
                var filename = GenerateFileNameHerinnering(factuur);
                using (var fs = new FileStream(Path.Combine(HerinneringFolder.FullName, filename), FileMode.Create))
                {
                    var document = new Document(PageSize.A4, 25, 25, 30, 1);
                    var writer = PdfWriter.GetInstance(document, fs);

                    // Add meta information to the document
                    document.AddAuthor("Dura - Vanseveren");
                    document.AddCreator("DuraFact");
                    document.AddKeywords("Herinnering");
                    document.AddSubject(string.Format("Herinnering voor factuur {0}", factuur.FactuurNummer));
                    document.AddTitle("Herinnering");

                    // Open the document to enable you to write to the document
                    document.Open();

                    // Makes it possible to add text to a specific place in the document using
                    // a X & Y placement syntax.
                    var content = writer.DirectContent;
                    // Add a footer template to the document
                    //	content.AddTemplate(PdfFooter(content, factuur), 30, 1);

                    // Add a logo to the invoice
                    var img = DuraLogo;
                    img.ScalePercent(80);
                    img.SetAbsolutePosition(40, 650);
                    content.AddImage(img);

                    // First we must activate writing
                    content.BeginText();

                    // First we write out the header information
                    AddKlantData(factuur, content);
                    WriteText(content, string.Format("Tielt, {0}", DateTime.Now.ToShortDateString()), 40, 600, 10);
                    WriteText(content, "Herinnering", 40, 550, 20, true);

                    WriteText(content, "Geachte heer/mevrouw", 40, 520, 10);
                    WriteText(content, string.Format("Wij hebben bij u een betalingsachterstand van {0:C} geconstateerd.", factuur.TotaalIncl), 40, 500, 10);
                    WriteText(content, "Dit bedrag heeft betrekking op de onderstaande factuur:", 40, 485, 10);

                    const int aantalMargin = 230, ehprijsMargin = 300, totaalMargin = 460;

                    WriteText(content, "Factuur", 140, 460, 12, true, PdfContentByte.ALIGN_RIGHT);
                    WriteText(content, "Datum", aantalMargin, 460, 12, true, PdfContentByte.ALIGN_RIGHT);
                    WriteText(content, "Bedrag", ehprijsMargin, 460, 12, true, PdfContentByte.ALIGN_RIGHT);
                    WriteText(content, "Betalingskenmerk", totaalMargin, 460, 12, true, PdfContentByte.ALIGN_RIGHT);

                    WriteText(content, factuur.FactuurNummer.ToString(), 140, 440, 10, false, PdfContentByte.ALIGN_RIGHT);
                    WriteText(content, factuur.FacturatieDatum.ToShortDateString(), aantalMargin, 440, 10, false, PdfContentByte.ALIGN_RIGHT);
                    WriteText(content, string.Format("{0:C}", factuur.TotaalIncl), ehprijsMargin, 440, 10, false, PdfContentByte.ALIGN_RIGHT);
                    WriteText(content, factuur.FacturatieDatum.ToShortDateString(), totaalMargin, 440, 10, false, PdfContentByte.ALIGN_RIGHT);

                    WriteText(content, string.Format("Wij verzoeken u nu vriendelijk het bovenstaande bedrag zulks ten bedrage van {0:C} te doen overmaken.", factuur.TotaalIncl), 40, 400, 10);
                    WriteText(content, "Dit kan op rekeningnummer 733-0318587-69 bij KBC of 001-6090654-03 bij BNP Paribas Fortis onder vermelding", 40, 385, 10);
                    WriteText(content, "van uw betalingskenmerk.", 40, 370, 10);
                    WriteText(content, "Wanneer u vragen mocht hebben over deze herinnering, verzoeken wij u zo spoedig mogelijk contact op te nemen", 40, 355, 10);
                    WriteText(content, "op het telefoonnummer (051) 40 34 77.", 40, 340, 10);
                    WriteText(content, "Heeft u inmiddels uw betalingsachterstand voldaan, dan is deze herinnering voor u niet meer van toepassing.", 40, 325, 10);
                    WriteText(content, "Hoogachtend,", 40, 280, 10);
                    WriteText(content, "Filip Vanseveren", 40, 180, 10);

                    // End the writing of text
                    content.EndText();

                    // Close the document, the writer and the filestream!
                    document.Close();
                    writer.Close();
                    fs.Close();
                    return Path.Combine(HerinneringFolder.FullName, filename);
                }
            }
            catch
            {
                return string.Empty;
            }
        }
Пример #20
0
        public static string CreateFactuur(Factuur factuur)
        {
            try
            {
                var filename = GenerateFileName(factuur);
                using (var fs = new FileStream(Path.Combine(FactuurFolder.FullName, filename), FileMode.Create))
                {
                    var document = new Document(PageSize.A4, 25, 25, 30, 1);
                    var writer = PdfWriter.GetInstance(document, fs);
                    writer.PageEvent = new FactuurHelper();
                    // Add meta information to the document
                    document.AddAuthor("Dura - Vanseveren");
                    document.AddCreator("DuraFact");
                    document.AddKeywords("Factuur");
                    document.AddSubject(string.Format("Factuur {0}", factuur.FactuurNummer));
                    document.AddTitle("Factuur");

                    // Open the document to enable you to write to the document
                    document.Open();

                    // Makes it possible to add text to a specific place in the document using
                    // a X & Y placement syntax.
                    var content = writer.DirectContent;
                    // Add a footer template to the document
                    //	content.AddTemplate(PdfFooter(content, factuur), 30, 1);

                    // Add a logo to the invoice
                    var img = DuraLogo;
                    img.ScalePercent(80);
                    img.SetAbsolutePosition(40, 650);
                    content.AddImage(img);

                    // First we must activate writing
                    content.BeginText();

                    // First we write out the header information
                    AddKlantData(factuur, content);
                    WriteText(content, "Factuur", 40, 600, 20, true);
                    AddFactuurData(factuur, content);

                    // You need to call the EndText() method before we can write graphics to the document!
                    content.EndText();
                    // Separate the header from the rows with a line
                    // Draw a line by setting the line width and position
                    content.SetLineWidth(0f);
                    content.MoveTo(40, 590);
                    content.LineTo(560, 590);
                    content.Stroke();
                    // Don't forget to call the BeginText() method when done doing graphics!
                    content.BeginText();
                    // Before we write the lines, it's good to assign a "last position to write"
                    // variable to validate against if we need to make a page break while outputting.
                    // Change it to 510 to write to test a page break; the fourth line on a new page
                    const int lastwriteposition = 150;

                    // Loop thru the table of items and set the linespacing to 12 points.
                    // Note that we use the -= operator, the coordinates goes from the bottom of the page!
                    var topMargin = 570;
                    if (!string.IsNullOrEmpty(factuur.Opmerking))
                    {
                        WriteText(content, "Opmerking", 40, topMargin, 12, true);
                        topMargin -= 20;
                        foreach (string s in factuur.Opmerking.Split(new string[] { Environment.NewLine }, StringSplitOptions.None))
                        {
                            WriteText(content, s, 40, topMargin, 10);
                            topMargin -= 16;
                        }
                        topMargin -= 4;
                    }

                    AddItemData(factuur, document, lastwriteposition, content, ref topMargin);

                    // You need to call the EndText() method before we can write graphics to the document!
                    content.EndText();
                    // Separate the header from the rows with a line
                    // Draw a line by setting the line width and position
                    content.SetLineWidth(0f);
                    content.MoveTo(40, topMargin);
                    content.LineTo(560, topMargin);
                    content.Stroke();
                    // Don't forget to call the BeginText() method when done doing graphics!
                    content.BeginText();
                    topMargin -= 15;
                    AddBTWData(factuur, content, topMargin);

                    // End the writing of text
                    content.EndText();

                    // Close the document, the writer and the filestream!
                    document.Close();
                    writer.Close();
                    fs.Close();
                    return Path.Combine(FactuurFolder.FullName, filename);
                }
            }
            catch
            {
                return string.Empty;
            }
        }
Пример #21
0
        public void generarPDF(string NC,string asesor,string secretario,string vocal,string suplente,string nombre)
        {
            folder();
            Document document = new Document(PageSize.A4, 25, 25, 30, 30);
            // Indicamos donde vamos a guardar el documento
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(@"C:\\CartasAsignacion\\" + (NC.ToString())+".pdf", FileMode.Create));
            //new FileStream(@"C:\Users\Angel\Documents\OficioTitulacion.pdf", FileMode.Create));

            //string image = "C:\\Users\\Angel\\Documents\\SharpDevelop Projects\\ProtocoloTitulacion\\ProtocoloTitulacion\\Recursos\\tec laguna.png";
            //ResourceManager rm = Resources.ResourceManager;
            //Bitmap myImage2 = (Bitmap)rm.GetObject("logo_pdf.png");
            //string image = myImage2.ToString() ;
            //Add the meta information
            document.AddAuthor("ITL Sistem Departament");
            document.AddCreator("Sistem Asignacion de Revisores");
            document.AddKeywords("PDF");
            document.AddTitle("The document title - Asignacion de Comisión Revisora");

            //open the document to enable you to wirte to the document
            document.Open();

            #region logo
            string patimagen = Path.Combine(Application.StartupPath, "..\\..\\Recursos\\logo_pdf.png");
            iTextSharp.text.Image myImage = iTextSharp.text.Image.GetInstance(patimagen);
            //iTextSharp.text.Image myImage = iTextSharp.text.Image.GetInstance(image);
            myImage.ScaleToFit(400, 233f);
            myImage.SpacingBefore = 50f;
            myImage.SpacingAfter = 10f;
            myImage.Alignment = Element.ALIGN_RIGHT;

            #endregion

            #region cabecera
            //estilos
            iTextSharp.text.Font title = FontFactory.GetFont("georgia",20f);
            Paragraph titulo = new Paragraph("Instituto Tecnológico de la Laguna", title);
            titulo.Alignment = Element.ALIGN_CENTER;
            //document.Add(titulo);
            document.Add(myImage);
            document.Add(Chunk.NEWLINE);
            //Indicamos la fecha de sistema
            string Date = DateTime.Today.Date.ToString();
            string aux="";
            for (int i = 0; i < 10; i++) {
                    aux += Date[i].ToString();
            }

            Paragraph fecha = new Paragraph("Torreon,Coah.," + aux);
            fecha.Alignment = Element.ALIGN_RIGHT;
            document.Add(fecha);
            //Fin de la fecha
            document.Add(Chunk.NEWLINE);
            Paragraph Asunto = new Paragraph("Asunto: Asignacion de comisión revisora ");
            Asunto.Alignment = Element.ALIGN_CENTER;
            document.Add(Asunto);

            #endregion

            document.Add(new Paragraph("COORDINADOR(A) DE "));
            document.Add(Chunk.NEWLINE);
            document.Add(new Paragraph("Por medio del presente informo a usted la asignacion de los integrantes de la comision"));
            document.Add(Chunk.NEWLINE);
            String texto = "revisora del trabajo de titulacion, del trabajo de titulacion de (la) C."+nombre+" " ;
            document.Add(new Paragraph(texto));
            document.Add(Chunk.NEWLINE);
            document.Add(new Paragraph("cuya opcion es : "));
            document.Add(Chunk.NEWLINE);
            document.Add(new Paragraph("Egresado(a) del instituto Tecnologico de la Laguna, con número de control " + NC +" pasante de la Carrera de Ingenieria en Sistemas"));

            #region Comision

            document.Add(Chunk.NEWLINE);
            string comision = "Presidente(a): " + asesor +
                               "\nSecretario(a): " + secretario +
                               "\nVocal : " + vocal +
                               "\nVocal Suplente : " + suplente;
            Paragraph textoComision = new Paragraph(comision);
            textoComision.Alignment = Element.ALIGN_MIDDLE;
            /*string presidente = "Presidente(a): " + asesor;
            document.Add(new Paragraph(presidente));
            string secretariodoc = "Secretario(a): " + secretario;
            document.Add(new Paragraph(secretariodoc));
            string vocaldoc = "Vocal: " + vocal;
            document.Add(new Paragraph(vocaldoc));
            string suplentedoc = "Vocal Suplente: "+suplente;
            document.Add(new Paragraph(suplentedoc));*/
            document.Add(textoComision);
            document.Add(Chunk.NEWLINE);
            document.Add(new Paragraph("Agradezco su atención al presente y envío un cordial saludo"));
            document.Add(Chunk.NEWLINE);

            #endregion

            iTextSharp.text.Font ateFont = FontFactory.GetFont("georgia", 10);
            ateFont.IsBold();
            Paragraph Ate = new Paragraph("Atentamente",ateFont);
            Ate.Alignment = Element.ALIGN_CENTER;
            document.Add(Ate);
            document.Add(Chunk.NEWLINE);
            document.Add(Chunk.NEWLINE);
            document.Add(Chunk.NEWLINE);
            Paragraph linea = new Paragraph("-------------------------------------------");
            linea.Alignment = Element.ALIGN_CENTER;
            document.Add(linea);
            document.Add(Chunk.NEWLINE);
            Paragraph jefatura = new Paragraph("Jefatura del Departamento de Sistemas Computacionales");
            jefatura.Alignment = Element.ALIGN_CENTER;
            document.Add(jefatura);
            //Close the document
            document.Close();
            //close the writer instance
            writer.Close();
            MessageBox.Show("Oficio creado satisfactoriamente");
        }
Пример #22
0
// ---------------------------------------------------------------------------  
    /**
     * Creates a PDF document.
     */
    public byte[] CreatePdfAutomatic() {
      using (MemoryStream ms = new MemoryStream()) {
        // step 1
        using (Document document = new Document()) {
          // step 2
          PdfWriter writer = PdfWriter.GetInstance(document, ms);
          document.AddTitle("Hello World example");
          document.AddSubject("This example shows how to add metadata & XMP");
          document.AddKeywords("Metadata, iText, step 3");
          document.AddCreator("My program using 'iText'");
          document.AddAuthor("Bruno Lowagie & Paulo Soares");
          writer.CreateXmpMetadata();
          // step 3
          document.Open();
          // step 4
          document.Add(new Paragraph("Hello World"));
        }
        return ms.ToArray();
      }
    }  
Пример #23
0
 /// <summary>
 /// Настройка метаданных создаваемого PDF отчета
 /// </summary>
 /// <param name="doc">Документ</param>
 private static void SetPdfMetadata(Document doc)
 {
     doc.AddAuthor("ToDoApp by Digiman");
     doc.AddCreator("ToDoApp application");
     doc.AddTitle("Report for To-Do list");
     doc.AddSubject("Report file");
     doc.AddKeywords("Metadata, PDF, iText, ToDoList, Report");
 }
Пример #24
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());
            }
        }
Пример #25
0
        public string GenerateAgendaPDF()
        {
            // Set up the fonts to be used on the pages
            Font _largeFont_UnderLine = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD|Font.UNDERLINE, BaseColor.BLACK);
            Font _largeFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD, BaseColor.BLACK);
            Font _standardFont = new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.NORMAL, BaseColor.BLACK);
            Font _smallFont = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.NORMAL, BaseColor.BLACK);
            string datePatten = "MMMM dd, yyyy";
            string timePatten = "h:mm tt";

            GetKeyMappingFiles();

            IEnumerable<ArtistViewModel> models = attendeeService.GetAllArtists();

            string downloadPath = HttpContext.Current.Server.MapPath("~/File/Download/");

            foreach (ArtistViewModel item in models)
            {

                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(downloadPath + item.Value + ".pdf",
                            System.IO.FileMode.OpenOrCreate));
                    doc.Open();
                    // 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, 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("Edmonton International Fringe Theatre Festival");
                    doc.AddCreator("Fringe Theatre ");
                    doc.AddKeywords("Edmonton International Fringe Theatre Festival");

                    this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont_UnderLine, new Chunk(string.Format("Venue #{0} {1}", item.VenueNo, item.VenueName)));

                    this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk(string.Format("{0} : {1}", keys["Ref"].ToString(), item.Value)));
                    this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk(string.Format("{0} #: {1}", "Venue", item.VenueNo)));
                    this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk(string.Format("{0} #: {1}", "Venue", item.VenueName)));
                    this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk(string.Format("{0} : {1}\n\n", keys["VenueAddress"].ToString(), item.VenueAddress)));

                    this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk(string.Format("{0} : {1}", keys["ShowTitle"].ToString(), item.Text)));
                    this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk(string.Format("{0} : {1}", keys["Company"].ToString(), item.Company)));
                    this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk(string.Format("{0} : {1}, {2}, {3}", "Location", item.PrimaryCity, item.PrimaryProvState, item.PrimaryCountry)));
                    this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk(string.Format("{0} : {1} min", keys["RunningTime"].ToString(), item.Length)));
                    this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk(string.Format("{0} : {1}", keys["Genre"].ToString(), item.Genre)));
                    this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk(string.Format("{0} : Adult: {1}", "Ticket Price", item.GeneralAdmission)));
                    this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk(string.Format("{0} : Student/Senior: {1}\n\n", "Ticket Price", item.StudentSenior)));

                    this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk(string.Format("{0} : {1}\n\n", keys["ShowDescription"].ToString(), item.ShowDescription)));

                    this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk(string.Format("{0} : {1}", keys["Playwright"].ToString(), item.Playwright)));
                    this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk(string.Format("{0} : {1}", keys["Director"].ToString(), item.Director)));
                    this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk(string.Format("{0} : {1}", keys["CastMembers"].ToString(), item.CastMembers)));
                    this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk(string.Format("{0} : {1}", keys["StageManager"].ToString(), item.StageManager)));
                    this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk(string.Format("{0} : {1}\n\n", keys["Designer"].ToString(), item.Designer)));

                    this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk(string.Format("{0} : {1}", keys["ContentAdvisory"].ToString(), item.ContentAdvisory)));
                    this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk(string.Format("{0} : {1}", keys["ShowRating"].ToString(), item.ShowRating)));
                    this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk(string.Format("{0} : {1}", keys["AgeRestriction"].ToString(), item.AgeRestriction)));
                    this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk(string.Format("{0} : {1}", keys["NewWork"].ToString(), item.NewWork)));
                    this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk(string.Format("{0} : {1}\n\n", keys["Website"].ToString(), item.Website)));

                    this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk(string.Format("{0} :\n\n", "Schedule")));

                    // table for the date start end
                    List<Meeting> meetings = schedulerMeetingService.GetMeetingsByAttendee(item.Value);

                    PdfPTable table = new PdfPTable(3);
                    table.HorizontalAlignment = Element.ALIGN_LEFT;
                    table.TotalWidth = 300f;
                    table.LockedWidth = true;
                    float[] widths = new float[] { 120f, 90f, 90f};
                    table.SetWidths(widths);

                    table.AddCell(new PdfPCell(new Phrase("Date")) { VerticalAlignment = Element.ALIGN_CENTER, HorizontalAlignment = Element.ALIGN_CENTER, Border = Rectangle.NO_BORDER });
                    table.AddCell(new PdfPCell(new Phrase("Start Time")) { VerticalAlignment = Element.ALIGN_CENTER, HorizontalAlignment = Element.ALIGN_RIGHT, Border = Rectangle.NO_BORDER });
                    table.AddCell(new PdfPCell(new Phrase("End Time")) { VerticalAlignment = Element.ALIGN_CENTER, HorizontalAlignment = Element.ALIGN_RIGHT, Border = Rectangle.NO_BORDER });

                    foreach (Meeting meeting in meetings)
                    {
                        table.AddCell(new PdfPCell(new Phrase(meeting.Start.ToString(datePatten))) { VerticalAlignment = Element.ALIGN_CENTER, HorizontalAlignment = Element.ALIGN_RIGHT, Border = Rectangle.NO_BORDER });
                        table.AddCell(new PdfPCell(new Phrase(meeting.Start.ToString(timePatten))) { VerticalAlignment = Element.ALIGN_CENTER, HorizontalAlignment = Element.ALIGN_RIGHT, Border = Rectangle.NO_BORDER });
                        table.AddCell(new PdfPCell(new Phrase(meeting.End.ToString(timePatten))) { VerticalAlignment = Element.ALIGN_CENTER, HorizontalAlignment = Element.ALIGN_RIGHT, Border = Rectangle.NO_BORDER });
                    }
                     doc.Add(table);

                    // Clean up
                    doc.Close();
                    doc = null;
                }
                catch (iTextSharp.text.DocumentException dex)
                {
                    return string.Format("PDF agenda file failed at {0}, caused by {1}", item.Value, dex.Message);
                }
                catch (Exception e)
                {
                    return string.Format("PDF agenda file failed at {0}, caused by {1}", item.Value, e.Message);
                }
            }
            return "";
        }
Пример #26
0
        private void button1_Click(object sender, EventArgs e)
        {
            //creamos el documento
            //...ahora configuramos para que el tamaño de hoja sea A4
            Document document = new Document(iTextSharp.text.PageSize.A4);
            //document.PageSize.BackgroundColor = new iTextSharp.text.BaseColor(255, 255, 255);
            document.PageSize.Rotate();

            //...definimos el autor del documento.
            document.AddAuthor("Arbis Percy Reyes Paredes");

            //...el creador, que será el mismo eh!
            document.AddCreator("Arbis Percy Reyes Paredes");

            //hacemos que se inserte la fecha de creación para el documento
            document.AddCreationDate();
            //...título

            document.AddTitle("Generación de un pdf con itextSharp");
            //... el asunto

            document.AddSubject("Este es un paso muy important");
            //... palabras claves

            document.AddKeywords("pdf, PdfWriter; Documento; iTextSharp");

            //creamos un instancia del objeto escritor de documento
            PdfWriter writer = PdfWriter.GetInstance(document, new System.IO.FileStream
            ("Code.pdf", System.IO.FileMode.Create));

            //encriptamos el pdf, dándole como clave de usuario "key" y la clave del dueño será "owner"
            //si quitas los comentarios (en writer.SetEncryption...), entonces el documento generado
            //no mostrarà tanto la información de autor, titulo, fecha de creacion...
            //que habiamos establecio más arriba. y sólo podrás abrirlo con una clave

            //writer.SetEncryption(PdfWriter.STRENGTH40BITS,"key","owner", PdfWriter.CenterWindow);

            //definimos la manera de inicialización de abierto del documento.
            //esto, hará que veamos al inicio, todas la páginas del documento
            //en la parte izquierda
            writer.ViewerPreferences = PdfWriter.PageModeUseThumbs;

            //con esto conseguiremos que el documento sea presentada de dos en dos
            writer.ViewerPreferences = PdfWriter.PageLayoutTwoColumnLeft;

            //con esto podemos oculta las barras de herramienta y de menú respectivamente.
            //(quite las dos barras de comentario de la siguiente línea para ver los efectos)
            //PdfWriter.HideToolbar | PdfWriter.HideMenubar

            //abrimos el documento para agregarle contenido
            document.Open();

            //este stream es para jalar el código
            string TemPath = Application.StartupPath.ToString();
            TemPath = TemPath.Substring(0, TemPath.Length - 10);
            string pathFileForm1cs = TemPath + @"\Form1.cs";
            System.IO.StreamReader reader = new System.IO.StreamReader(pathFileForm1cs);

            //leemos primera línea
            string linea = reader.ReadLine();

            //creamos la fuente
            iTextSharp.text.Font myfont = new iTextSharp.text.Font(
            FontFactory.GetFont(FontFactory.COURIER, 10, iTextSharp.text.Font.ITALIC));

            //creamos un objeto párrafo, donde insertamos cada una de las líneas que
            //se vaya leyendo mediante el reader
            Paragraph myParagraph = new Paragraph("Código fuente en Visual C# \n\n", myfont);

            do
            {
                //leyendo linea de texto
                linea = reader.ReadLine();
                //concatenando cada parrafo que estará formado por una línea
                myParagraph.Add(new Paragraph(linea, myfont));
            } while (linea != null);  //mientras no llegue al final de documento, sigue leyendo

            //agregar todo el paquete de texto
            document.Add(myParagraph);

            //esto es importante, pues si no cerramos el document entonces no se creara el pdf.
            document.Close();

            //esto es para abrir el documento y verlo inmediatamente después de su creación
            System.Diagnostics.Process.Start("C:\\Program Files (x86)\\Foxit PhantomPDF\\FoxitPhantomPDF.exe", "Code.pdf");
        }
Пример #27
0
        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 the margins and page size
                this.SetStandardPageSize(doc);

                // Add metadata to the document.  This information is visible when viewing the
                // document properities within Adobe Reader.
                doc.AddTitle("My Science Report");
                doc.AddHeader("title", "My Science Report");
                doc.AddHeader("author", "M. Lichtenberg");
                doc.AddCreator("M. Lichtenberg");
                doc.AddKeywords("paper airplanes");
                doc.AddHeader("subject", "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);

                // Add a page with an image to the document.  The page will be sized to match the image size.
                this.AddPageWithImage(doc, System.IO.Directory.GetCurrentDirectory() + "\\FinalGraph.jpg");

                // Add a final page
                this.SetStandardPageSize(doc);  // Reset the margins and page size
                this.AddPageWithExternalLinks(doc);

                // 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, "Image");
                pdfPageLabels.AddPageLabel(5, iTextSharp.text.pdf.PdfPageLabels.EMPTY, "External Links");
                writer.PageLabels = pdfPageLabels;
            }
            catch (iTextSharp.text.DocumentException dex)
            {
                // Handle iTextSharp errors
            }
            finally
            {
                // Clean up
                doc.Close();
                doc = null;
            }
        }
        public string GeneratePdfFile(List <Photo> photos, string tag, string fileName, int mode, int columnsNumber)
        {
            string root = null;

            if (ContextCompat.CheckSelfPermission(Application.Context, Manifest.Permission.WriteExternalStorage)
                != Permission.Granted)
            {
                ActivityCompat.RequestPermissions((Android.App.Activity)
                                                  Application.Context, new string[] { Manifest.Permission.WriteExternalStorage }, 1);
            }

            if (Android.OS.Environment.IsExternalStorageEmulated)
            {
                root = Android.OS.Environment.ExternalStorageDirectory.ToString();
            }
            else
            {
                root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
            }

            Java.IO.File myDir = new Java.IO.File(root + "/DocAndComPDFs");
            if (myDir.Exists() == false)
            {
                myDir.Mkdir();
            }

            var _path = Path.Combine(root, "DocAndComPDFs", fileName);

            FileStream fs = new FileStream(_path, FileMode.Create, FileAccess.Write);

            var doc = new iTextSharp.text.Document(PageSize.A4, 14f, 14f, 30f, 0);

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

            writer.StrictImageSequence = true;

            doc.Open();
            doc.AddTitle($"docAndCompare result for {tag} tag");
            doc.AddKeywords("docAndCompare");
            doc.AddCreator("iTextSharp lib");

            var titleFont = FontFactory.GetFont("Arial", 34.0f, Color.BLACK);
            var title     = new Paragraph(ResourceLoader.Instance.GetString("pdfTitle"), titleFont);

            var subTitleFont = FontFactory.GetFont("Arial", 14.0f, Color.BLACK);
            var subTitle     = new Paragraph(ResourceLoader.Instance.GetString("pdfSubTitle"), subTitleFont);

            var subSubTitleFont = FontFactory.GetFont("Arial", 10.0f, Color.BLACK);
            var subSubTitle     = new Paragraph(ResourceLoader.Instance.GetString("pdfSubSubTitle") + tag, subSubTitleFont);

            doc.Add(title);
            doc.Add(subTitle);
            doc.Add(subSubTitle);

            doc.Add(new Paragraph(" ")
            {
                SpacingBefore = 8f
            });

            if (mode == 0) // List
            {
                foreach (var photo in photos)
                {
                    var p = new Paragraph(
                        ResourceLoader.Instance.GetString("pdfDataText") + photo.CreatedOn.ToString("dd.MM.yyyy"));
                    p.SpacingAfter = 75f;
                    var img = Image.GetInstance(photo.Path);
                    img.ScalePercent(12f);
                    p.Alignment   = Element.ALIGN_TOP;
                    img.Alignment = Element.ALIGN_MIDDLE;
                    doc.Add(p);
                    doc.Add(img);
                    doc.NewPage();
                }
            }
            else if (mode == 1)   // Tabular
            {
                var numberOfImages = photos.Count;
                var numberOfRows   = 0;

                if (numberOfImages == 3)
                {
                    numberOfRows = 2;
                }
                else if (numberOfImages > 3)
                {
                    numberOfRows = CalculateRowsAmount(numberOfImages, columnsNumber);
                }

                PdfPTable table = new PdfPTable(columnsNumber);
                table.KeepTogether    = true;
                table.WidthPercentage = 90;

                int dateId  = 0;
                int photoId = 0;

                for (int i = 0; i < numberOfRows; i++)
                {
                    for (int x = 0; x < columnsNumber; x++)
                    {
                        // even
                        if (i % 2 == 0)
                        {
                            Paragraph p;

                            if (dateId < numberOfImages)
                            {
                                p = new Paragraph(photos[dateId].CreatedOn.ToString("dd.MM.yyyy"));
                            }
                            else
                            {
                                p = new Paragraph(ResourceLoader.Instance.GetString("pdfEmptyText"));
                            }
                            p.Alignment = Element.ALIGN_CENTER;
                            table.AddCell(p);
                            dateId++;
                        }
                        else
                        {
                            if (photoId < numberOfImages)
                            {
                                var img = Image.GetInstance(photos[photoId].Path);
                                img.ScalePercent(22f);
                                img.Alignment = Element.ALIGN_CENTER;
                                table.AddCell(img);
                            }
                            else
                            {
                                Paragraph p = new Paragraph(ResourceLoader.Instance.GetString("pdfEmptyText"));
                                p.Alignment = Element.ALIGN_CENTER;
                                table.AddCell(p);
                            }
                            photoId++;
                        }
                    }
                }

                doc.Add(table);
            }

            doc.Close();

            return(_path);
        }
Пример #29
0
        protected override Stream Read()
        {
            Document doc = new Document(PageSize.A4, 50, 50, 50, 50);
            doc.AddTitle(Title);
            doc.AddCreationDate();
            doc.AddCreator("iTextSharp");
            doc.AddAuthor("文化中国");
            doc.AddSubject(w.Excerpt);
            doc.AddKeywords(w.Tags);
            using (MemoryStream stream = new MemoryStream())
            {
                PdfWriter writer = PdfWriter.GetInstance(doc, stream);
                writer.SetEncryption(true, null, null, 0);
                writer.PageEvent = new HeaderFooterPdfPageEventHelper();

                doc.Open();

                Paragraph p = new Paragraph(Title, font);
                p.Alignment = 1;
                doc.Add(p);

                MatchCollection matches = regex.Matches(w.Script.Text);
                foreach (Match m in matches)
                {
                    Chunk chunk = new Chunk(m.Groups["cont"].Value);
                    switch (m.Groups["tag"].Value.ToLower())
                    {
                        case "h1":
                            font.Color = BaseColor.WHITE;
                            chunk.SetBackground(BaseColor.DARK_GRAY);
                            break;
                        case "p":
                            font.Color = BaseColor.BLACK;
                            break;
                    }
                    chunk.Font = font;
                    p = new Paragraph(chunk);
                    p.SetLeading(0.0f, 2.0f);
                    p.FirstLineIndent = 20f;
                    p.Alignment = 0;
                    doc.Add(p);
                }
                doc.Close();

                return new MemoryStream(stream.GetBuffer());
            }
        }
        //create a new pdf document
        private void btn_Prepare_Click(object sender, EventArgs e)
        {
            //if all of these null
            if ((textboxAuthor.Text == "" || textboxCreator.Text == "" || textboxSubject.Text == "" || textboxKeyword.Text == "" || rtextboxParagraph.Text == "") || checkTextboxValues())
            {
                MessageBox.Show("PLEASE FILL IN THE TEXTBOXES", "Message Box", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            }
            else
            {
                //the library for create a new pdf document
                iTextSharp.text.Document report = new iTextSharp.text.Document();
                //file path of newly created pdf file to save
                PdfWriter.GetInstance(report, new FileStream(@"C:\Users\Asus\Desktop\UPLOADFILES\" + textboxFileName.Text, FileMode.Create));
                //Author name, need for create a new pdf document
                report.AddAuthor(textboxAuthor.Text);
                //Creation Date, need for create a new pdf document
                report.AddCreationDate();
                //Creator, need for create a new pdf document
                report.AddCreator(textboxCreator.Text);
                //Subject, need for create a new pdf document
                report.AddSubject(textboxSubject.Text);
                //Keywords, need for create a new pdf document
                report.AddKeywords(textboxKeyword.Text);

                if (report.IsOpen() == false)
                {
                    //open report for create a new pdf document
                    report.Open();
                }
                //Paragraph, need for create a new pdf document
                report.Add(new Paragraph(rtextboxParagraph.Text));
                //open the connection
                db.openConnection();
                //a command line for add a new document
                SqlCommand query = new SqlCommand("INSERT INTO Table_DOCUMENT(file_Name,file_Path,file_CreationDate,u_ID) VALUES(@fn, @fp, @cd,@uid)", db.getConnection());
                //add the value in the textbox to @fn
                query.Parameters.AddWithValue("@fn", textboxFileName.Text);
                //add the value in the textbox to @fp
                query.Parameters.AddWithValue("@fp", textboxFilePath.Text + @"\" + textboxFileName.Text);
                //add the value in the combobox to @uid
                query.Parameters.AddWithValue("@uid", comboboxUserID.Text);
                //add the value in the textbox to @cd
                query.Parameters.AddWithValue("@cd", textboxFileDate.Text);

                if (textboxFileDate.Text == "" || textboxFileName.Text == "" || comboboxUserID.Text == "")
                {
                    MessageBox.Show("PLEASE ENTER THE NAME OF THE FILE: FILE NAME, CREATION DATE, OR USER ID", "Message Box", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                }
                else if (checkFileName())
                {
                    MessageBox.Show("This File Name Already Exist, Select A Different One", "Message Box", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                    textboxFileName.Text = "";
                }
                else
                {
                    //execute the query
                    if (query.ExecuteNonQuery() == 1)
                    {
                        //the record is successfully
                        MessageBox.Show("DATA WERE RECORDED", "Message Box", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);

                        //return the default values and colors
                        dateTimePicker1.ResetText();
                        textboxFileID.Text        = "file ID";
                        textboxFileID.ForeColor   = Color.DimGray;
                        textboxFileName.Text      = "filename.pdf";
                        textboxFileName.ForeColor = Color.DimGray;
                        comboboxUserID.Text       = "user id";
                        comboboxUserID.ForeColor  = Color.DimGray;
                        textboxFilePath.Text      = "file path";
                        textboxFilePath.ForeColor = Color.DimGray;
                        dateTimePicker1.ResetText();
                        textboxFileDate.Text      = "DD.MM.YYYY";
                        textboxFileDate.ForeColor = Color.DimGray;
                        textboxSubject.Text       = "";
                        rtextboxParagraph.Text    = "";
                        dateTimePicker1.Text      = "";
                        textboxAuthor.Text        = "";
                        textboxCreator.Text       = "";
                        textboxKeyword.Text       = "";
                    }
                    else
                    {
                        MessageBox.Show("ERROR", "Message Box", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                    }
                }
                //close the report
                report.Close();
                //close the connection
                db.closeConnection();
            }
        }
Пример #31
0
        private void btnGo_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            pbStatusBar.Visible = true;
            allStatus(false);
            string nSourceI = txtSourceI.Text;
            string nSourceP = txtSourceP.Text;
            string nOutput = txtOutput.Text;
            if (string.IsNullOrWhiteSpace(nSourceI) || string.IsNullOrWhiteSpace(nSourceP) || string.IsNullOrWhiteSpace(nOutput))
            {
                MessageBox.Show(e401, "Nawras Pages Merge");
            }
            else
            {
                if (File.Exists(nSourceI) && File.Exists(nSourceP))
                {
                    try
                    {
                        PdfReader nI = new PdfReader(nSourceI);
                        PdfReader nP = new PdfReader(nSourceP);
                        
                        if (nI.NumberOfPages != nP.NumberOfPages)
                        {
                            MessageBox.Show(e300, "Nawras Pages Merge");
                        }
                        else
                        {
                            pbStatusBar.Maximum = nI.NumberOfPages * 2;
                            Document nSave = new Document(nI.GetPageSizeWithRotation(nI.NumberOfPages));
                            PdfCopy nCopy = new PdfCopy(nSave, new FileStream(nOutput, FileMode.Create));

                            //Add PDF metadata
                            nSave.AddAuthor(txtAuthor.Text);
                            nSave.AddCreator("Nawras Pages Merge");                            
                            nSave.AddKeywords(txtKeywords.Text);
                            nSave.AddSubject(txtSubject.Text);
                            nSave.AddTitle(txtTitle.Text);
                            PdfImportedPage nPageI, nPageP;
                            PdfDictionary nPageIp, nPagePp;
                            nSave.Open();
                            
                            //Apply pages rotation
                            for (int i = 1; i <= nI.NumberOfPages; i++)
                            {
                                nPageIp = nI.GetPageN(i);
                                nPagePp = nP.GetPageN(i);
                                nPageIp.Put(PdfName.ROTATE, new PdfNumber(rotateLeft));
                                nPagePp.Put(PdfName.ROTATE, new PdfNumber(rotateRight));
                            }
                            //Apply pages merging
                            for (int i = 1; i <= nI.NumberOfPages; i++)
                            {
                                nPageI = nCopy.GetImportedPage(nI, i);
                                pbStatusBar.Value += 1;
                                nPageP = nCopy.GetImportedPage(nP, i);
                                pbStatusBar.Value += 1;
                                nCopy.AddPage(nPageI);
                                nCopy.AddPage(nPageP);
                            }

                            nSave.Close();
                            nI.Close();
                            nP.Close();
                            MessageBox.Show(e200, "Nawras Pages Merge");
                            pbStatusBar.Value = 0;
                        }
                    }
                    catch (Exception nErr)
                    {
                        MessageBox.Show("Erreur : " + nErr.Message);
                    }
                }
                else
                {
                    MessageBox.Show(e404, "Nawras Pages Merge");
                }
            }
            allStatus(true);
            pbStatusBar.Visible = false;
            Cursor.Current = Cursors.Default;
        }
Пример #32
0
        public Tuple <bool, string> GeneratePDF(DocumentStockReceiptList stockReceipt = null)
        {
            string fPath = string.Empty, subF_Path = string.Empty, fileName = string.Empty, filePath = string.Empty;

            try
            {
                fileName = stockReceipt.ReceivingCode + GlobalVariable.ReceiptAckFileName;
                fPath    = GlobalVariable.ReportPath + "Reports";
                report.CreateFolderIfnotExists(fPath);          // create a new folder if not exists
                subF_Path = fPath + "//" + stockReceipt.UserID; //ManageReport.GetDateForFolder();
                report.CreateFolderIfnotExists(subF_Path);
                //delete file if exists
                filePath = subF_Path + "//" + fileName + ".pdf";
                report.DeleteFileIfExists(filePath);

                iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.A4, 5f, 5f, 5f, 5f);
                //Create PDF Table
                FileStream fs = new FileStream(filePath, FileMode.Create);
                //Create a PDF file in specific path
                PdfWriter writer = PdfWriter.GetInstance(document, fs);
                // Add meta information to the document
                document.AddAuthor("Dulasiayya from BonTon");
                document.AddCreator("Acknolowdgement for particuar document");
                document.AddKeywords("TNCSC- Webcopy ");
                document.AddSubject("Document subject - Ack Web Copy ");
                document.AddTitle("The document title - PDF creation for Receipt Document");

                //Open the PDF document
                document.Open();
                string imagePath          = GlobalVariable.ReportPath + "layout\\images\\dashboard\\tncsc-logo.PNG";
                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imagePath);
                img.Alignment = Element.ALIGN_CENTER;
                img.ScaleToFit(80f, 60f);

                imagePath = GlobalVariable.ReportPath + "layout\\images\\dashboard\\watermark.PNG";
                iTextSharp.text.Image imgWaterMark = iTextSharp.text.Image.GetInstance(imagePath);
                imgWaterMark.ScaleToFit(300, 450);
                imgWaterMark.Alignment = iTextSharp.text.Image.UNDERLYING;
                imgWaterMark.SetAbsolutePosition(120, 450);
                document.Add(imgWaterMark);
                //|----------------------------------------------------------------------------------------------------------|
                //Create the table
                PdfPTable table = new PdfPTable(2);
                table.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
                //table.setBorder(Border.NO_BORDER);
                //set overall width
                table.WidthPercentage = 100f;
                //set column widths
                int[] firstTablecellwidth = { 20, 80 };
                table.SetWidths(firstTablecellwidth);
                //iTextSharp.text.Font fontTable = FontFactory.GetFont("Arial", "16", iTextSharp.text.Font.NORMAL);
                PdfPCell cell = new PdfPCell(img);
                cell.Rowspan     = 3;
                cell.BorderWidth = 0;
                // cell.Border = (Border.NO_BORDER);
                table.AddCell(cell);
                PdfPCell cell1 = new PdfPCell(new Phrase("TAMILNADU CIVIL SUPPLIES CORPORATION"));
                cell1.HorizontalAlignment = Element.ALIGN_CENTER;
                cell1.BorderWidth         = 0;
                table.AddCell(cell1);


                cell1 = new PdfPCell(new Phrase("Region Name : " + stockReceipt.RegionName));
                cell1.HorizontalAlignment = Element.ALIGN_CENTER;
                cell1.BorderWidth         = 0;
                table.AddCell(cell1);

                cell1             = new PdfPCell(new Phrase(""));
                cell1.BorderWidth = 0;
                table.AddCell(cell1);

                document.Add(table);
                Paragraph heading = new Paragraph("           STOCK RECEIPT ACKNOWLEDGMENT         WEB COPY");
                heading.Alignment = Element.ALIGN_CENTER;
                document.Add(heading);
                AddSpace(document);
                AddHRLine(document);
                //add header values
                AddheaderValues(document, stockReceipt);
                AddSpace(document);
                AddDetails(document, stockReceipt);
                AddSpace(document);
                AddLorryInfo(document, stockReceipt);
                AddSpace(document);
                AddFSSAI(document);
                AddSign(document, stockReceipt.ReceivingCode);
                AddSpace(document);
                AddRemarks(document, stockReceipt);
                AddSpace(document);
                AddHRLine(document);
                AddFooter(document, stockReceipt);
                //Add border to page
                PdfContentByte content   = writer.DirectContent;
                Rectangle      rectangle = new Rectangle(document.PageSize);
                rectangle.Left   += document.LeftMargin;
                rectangle.Right  -= document.RightMargin;
                rectangle.Top    -= document.TopMargin;
                rectangle.Bottom += document.BottomMargin;
                content.SetColorStroke(BaseColor.Black);
                content.Rectangle(rectangle.Left, rectangle.Bottom, rectangle.Width, rectangle.Height);
                content.Stroke();
                // Close the document
                document.Close();
                // Close the writer instance
                writer.Close();
                // Always close open filehandles explicity
                fs.Close();
            }
            catch (Exception ex)
            {
                AuditLog.WriteError(" GeneratePDF :  " + ex.Message + " " + ex.StackTrace);
                return(new Tuple <bool, string>(false, "Please Contact system Admin"));
            }
            return(new Tuple <bool, string>(true, "Print Generated Successfully"));
        }
        static void Dump(IEnumerable<ICrew> crews, int showAthlete)
        {
            ILog logger = LogManager.GetCurrentClassLogger ();

            string json = JsonConvert.SerializeObject (crews.Select (cr => new { cr.StartNumber, cr.Name}).OrderBy(cr => cr.StartNumber));
            logger.InfoFormat ("JSON: {0}", json);

            DateTime racedate = DateTime.MinValue;
            if(!DateTime.TryParse(ConfigurationManager.AppSettings["racedate"].ToString(), out racedate))
                racedate = DateTime.MinValue;

            string raceDetails = string.Format("{0} - {1} - Draw", ConfigurationManager.AppSettings["racenamelong"], racedate.ToLongDateString());
            string updated = "Updated: \t" + DateTime.Now.ToShortTimeString () + " " + DateTime.Now.ToShortDateString ();
            StringBuilder sb = new StringBuilder ();
            sb.AppendLine (updated);
            StringBuilder sql = new StringBuilder ();

            var orders = new Dictionary<string, IOrderedEnumerable<ICrew>> {
                {string.Empty, crews.OrderBy (cr => cr.StartNumber)},
                {" by boating location", crews.OrderBy (cr => cr.BoatingLocation.Name).ThenBy (cr => cr.StartNumber)},
                {" by club name", crews.OrderBy (cr => cr.Name).ThenBy (cr => cr.StartNumber)},
            };

            foreach(var kvp in orders)
            {
                using (var fs = new FileStream (string.Format ("{0} {1} Draw{2}.pdf", ConfigurationManager.AppSettings ["racenamelong"], racedate.ToString ("yyyy"), kvp.Key), FileMode.Create)) {

                    using (Document document = new Document (PageSize.A4.Rotate ())) {

                        Font font = new Font (Font.FontFamily.HELVETICA, 7f, Font.NORMAL);
                        Font italic = new Font (Font.FontFamily.HELVETICA, 7f, Font.ITALIC);
                        Font bold = new Font (Font.FontFamily.HELVETICA, 7f, Font.BOLD);
                        Font strike = new Font (Font.FontFamily.HELVETICA, 7f, Font.STRIKETHRU);

                        // step 2:
                        // we create a writer that listens to the document and directs a PDF-stream to a file
                        PdfWriter.GetInstance (document, fs);

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

                        // entitle the document
                        document.Add (new Paragraph (raceDetails));
                        document.AddSubject (raceDetails);

                        // grab the header and seed the table
                        // todo these need to be wider for the vets because of the composites
                        float[] widths = new float[] { 1f, 3f, 4f, 2f, 2f, 3f, 3f, 2f };
                        PdfPTable table = new PdfPTable (widths.Count ()) {
                            TotalWidth = 800f,
                            LockedWidth = true,
                            HorizontalAlignment = 0,
                            SpacingBefore = 20f,
                            SpacingAfter = 30f,
                        };
                        table.SetWidths (widths);

                        foreach (var h in new List<string> { "Start", "BROE Entry", "Club Names", showAthlete == 1 ? "Sculler" : "BROE CrewID", "Category", "Boating", "Other prizes","Notes" }) {
                            table.AddCell (new PdfPCell (new Phrase (h)) { Border = 1, HorizontalAlignment = 2, Rotation = 90 });
                            sb.AppendFormat ("{0}\t", h);
                        }
                        sb.AppendLine ();

                        string UNPAID = String.Empty; //  "UNPAID";
                        foreach (var crew in kvp.Value) { //  crews.OrderBy(cr => cr.StartNumber))
                            ICategory primary;
                            string extras = String.Empty;
                            // todo - transfer this into the crew itself
                            if (crew.Categories.Any (c => c is TimeOnlyCategory)) {
                                primary = crew.Categories.First (c => c is TimeOnlyCategory);
                            } else {
                                primary = crew.Categories.First (c => c is EventCategory);
                                extras = crew.Categories.Where (c => !(c is EventCategory) && !(c is OverallCategory) && c.Offered).Select (c => c.Name).Delimited ();
                            }
                            var objects = new List<Tuple<string, Font>> {
                                new Tuple<string, Font> (crew.StartNumber.ToString (), font),
                                new Tuple<string, Font> (crew.RawName, crew.IsScratched ? strike : font),
                                new Tuple<string, Font> (crew.Name, crew.IsScratched ? strike : font),

                                new Tuple<string, Font> (showAthlete  == 1 ? crew.AthleteName (showAthlete, false) : crew.CrewId.ToString(), crew.IsScratched ? strike : font),
                                new Tuple<string, Font> (crew.CategoryName, font), //, primary.Offered ? font : italic),
                                new Tuple<string, Font> (crew.BoatingLocation.Name, font),
                                new Tuple<string, Font> (extras, font),
                                new Tuple<string, Font> ((crew.IsScratched ? "SCRATCHED" : String.Empty) + " "
                                    + (crew.IsPaid && !crew.IsAccepted ? String.Empty : UNPAID) + " "
                                    + crew.VoecNotes, bold),
                            };
                            sql.AppendFormat ("connection.Execute(\"insert into Boats (_race, _number, _name) values (?, ?, ?)\", \"{0}\", {1}, \"[{2} / {3} / {4}]\");{5}",
                                ConfigurationManager.AppSettings ["racecode"].ToString (), crew.StartNumber,
                                crew.Name, crew.AthleteName (showAthlete, false), primary.Name, Environment.NewLine);

                            sb.AppendFormat ("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}{8}", objects [0].Item1, objects [1].Item1, objects [2].Item1, objects [3].Item1, objects [4].Item1, objects [5].Item1, objects [6].Item1, crew.ShortName, Environment.NewLine);
                            foreach (var l in objects)
                                table.AddCell (new PdfPCell (new Phrase (l.Item1.TrimEnd (), l.Item2)) { Border = 0 });
                        }

                        if (string.IsNullOrEmpty (kvp.Key)) {
                            using (System.IO.StreamWriter file = new System.IO.StreamWriter (ConfigurationManager.AppSettings ["racecode"].ToString () + ".txt")) {
                                file.Write (sb.ToString ());
                            }
                            using (System.IO.StreamWriter file = new System.IO.StreamWriter (ConfigurationManager.AppSettings ["racecode"].ToString () + ".sql")) {
                                file.Write (sql.ToString ());
                            }

                            // todo - need a crew index to be written out
                            // todo - this might well break with timeonly crews
                            json = JsonConvert.SerializeObject (crews
                                .Select (cr =>
                                    new { cr.StartNumber, Name = cr.Name + " - " + cr.AthleteName (showAthlete, false), Category = cr.EventCategory.Name, Scratched = cr.IsScratched})
                                .OrderBy (cr => cr.StartNumber));

                            using (System.IO.StreamWriter file = new System.IO.StreamWriter (Path.Combine (ConfigurationManager.AppSettings ["dbpath"].ToString (), ConfigurationManager.AppSettings ["racecode"].ToString () + "-draw.json"))) {
                                file.Write (json.ToString ());
                            }
                        }

                        document.Add (table);
                                            document.Add (new Paragraph ("Any queries should be directed to [email protected]", bold)); // todo - race-dependent email address
                        //					document.Add (new Paragraph ("Crews that have scratched but are unpaid run the risk of future sanction.", bold));
                        // document.Add (new Paragraph ("Categories shown in italics have not attracted sufficient entries to qualify for a category prize.", italic));
                        document.Add (new Paragraph ("Any adjusted prizes are open to all indicated crews and will be awarded based on adjusted times as calculated according to the tables in the Rules of Racing", font));
                        document.Add (new Paragraph (updated, font));
                        document.AddTitle ("Designed by www.vestarowing.co.uk");
                        document.AddAuthor (string.Format ("Chris Harrison, {0} Timing and Results", ConfigurationManager.AppSettings ["racenamelong"]));
                        document.AddKeywords (string.Format ("{0}, {1}, Draw", ConfigurationManager.AppSettings ["racenamelong"], racedate.Year));

                        document.Close ();
                    }
                }
            }
        }