AddSubject() public method

Adds the subject to a Document.
public AddSubject ( string subject ) : bool
subject string the subject
return bool
Exemplo n.º 1
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;
 }
Exemplo n.º 3
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();
                    }
            }
            
            
        }
Exemplo n.º 4
0
        //PDF Ayarları
        public void PdfHazirla()
        {
            iTextSharp.text.Document fis        = new iTextSharp.text.Document(new iTextSharp.text.Rectangle(300, 600));
            iTextSharp.text.Font     normalFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 10f, iTextSharp.text.Font.NORMAL);

            iTextSharp.text.Font italikFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 10f, iTextSharp.text.Font.ITALIC);



            iTextSharp.text.Font tahomaFont = iTextSharp.text.FontFactory.GetFont("Tahoma", 10f);


            PdfWriter.GetInstance(fis, new FileStream("D:e-fatura.pdf", FileMode.Create));
            fis.AddAuthor("Yunus Turhan");
            fis.AddCreationDate();
            fis.AddSubject("Bilgilendirme Maili");



            if (fis.IsOpen() == false)
            {
                fis.Open();
            }

            fis.Add(new Paragraph(mailicerigi.Text));

            fis.Close();
        }
Exemplo n.º 5
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();
        }
Exemplo n.º 6
0
        public bool TryCreatePdf(string nameBank)
        {
            try
            {
                using (FileStream file = new FileStream(String.Format(path,nameBank), FileMode.Create))
                {
                    Document document = new Document(PageSize.A7);
                    PdfWriter writer = PdfWriter.GetInstance(document, file);

                    /// Create metadate pdf file
                    document.AddAuthor("");
                    document.AddLanguage("pl");
                    document.AddSubject("Payment transaction");
                    document.AddTitle("Transaction");
                    /// Create text in pdf file
                    document.Open();
                    document.Add(new Paragraph(_przelew+"\n"));
                    document.Add(new Paragraph(String.Format("Bank {0}: zaprasza\n",nameBank)));
                    document.Add(new Paragraph(DateTime.Now.ToString()));
                    document.Close();
                    writer.Close();
                    file.Close();
                    return true;
                }
            }
            catch (SystemException ex)
            {
                return false;
            }
        }
Exemplo n.º 7
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();
        }
        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 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());
        }
Exemplo n.º 10
0
 public void SetDocumentProperties(Models.Document documentTemplate)
 {
     if (documentTemplate.Author != null)
     {
         _itextDocument.AddAuthor(documentTemplate.Author);
     }
     if (documentTemplate.Title != null)
     {
         _itextDocument.AddTitle(documentTemplate.Title);
     }
     if (documentTemplate.Subject != null)
     {
         _itextDocument.AddSubject(documentTemplate.Subject);
     }
 }
Exemplo n.º 11
0
        public void SendToPDF(string filename, clsFont jfont)
        {
            //New document, 8.5"x11" in landscape orientation.
            iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.LETTER.Rotate());

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

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

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

            writer.PageEvent = pdfevent;

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

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

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

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

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

                doc.NewPage();
            }

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

                action.Invoke(document);

                document.Close();
            }
    }
Exemplo n.º 13
0
 internal PdfGraphics(string filename, int width, int height)
 {
     originalWidth = currentWidth = width;
     originalHeight = currentHeight = height;
     document = new Document(new iTextSharp.text.Rectangle(width, height), 50, 50, 50, 50);
     document.AddAuthor("");
     document.AddSubject("");
     try{
         writer = PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create));
         document.Open();
         content = writer.DirectContent;
         template = topTemplate = content.CreateTemplate(width, height);
         content.AddTemplate(template, 0, 0);
     } catch (DocumentException de){
         throw new IOException(de.Message);
     }
 }
Exemplo n.º 14
0
 public PdfGraphics(Stream stream, int width, int height)
 {
     originalWidth = currentWidth = width;
     originalHeight = currentHeight = height;
     document = new Document(new Rectangle(width, height), 50, 50, 50, 50);
     document.AddAuthor("");
     document.AddSubject("");
     try{
         writer = PdfWriter.GetInstance(document, stream);
         document.Open();
         content = writer.DirectContent;
         template = topTemplate = content.CreateTemplate(width, height);
         content.AddTemplate(template, 0, 0);
     } catch (DocumentException de){
         throw new IOException(de.Message);
     }
 }
        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();
        }
Exemplo n.º 16
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();    
      }
    }    
Exemplo n.º 17
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();
        }
Exemplo n.º 18
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);
     }
 }
Exemplo n.º 19
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();
        }
Exemplo n.º 20
0
        private MemoryStream PrintTerms(IEnumerable<GlossaryItem> terms)
        {
            float ppi = 72.0F;
            float PageWidth = 8.5F;
            float PageHeight = 11.0F;
            float TopBottomMargin = 0.625F;
            float LeftRightMargin = 0.75F;
            float GutterWidth = 0.25F;
            float HeaderFooterHeight = 0.125F;
            float Column1Left = LeftRightMargin;
            float Column1Right = ((PageWidth - (LeftRightMargin * 2) - GutterWidth) / 2) + LeftRightMargin;
            float Column2Left = Column1Right + GutterWidth;
            float Column2Right = PageWidth - LeftRightMargin;

            bool HasMultipleDefinitions = (terms.Count() > 1);

            string version = DataAccess.GetKeyValue("glossaryversion").Value;

            Document doc = new Document(new Rectangle(0, 0, PageWidth * ppi, PageHeight * ppi));

            MemoryStream m = new MemoryStream();

            PdfWriter writer = PdfWriter.GetInstance(doc, m);
            writer.CloseStream = false;

            try {
                doc.AddTitle("The Glossary of Systematic Christian Theology");
                doc.AddSubject("A collection of technical terms and associated definitions as taught from the pulpit by Dr. Ron Killingsworth in classes at Rephidim Church.");
                doc.AddCreator("My program using iText#");
                doc.AddAuthor("Dr. Ron Killingsworth");
                doc.AddCreationDate();

                writer.SetEncryption(PdfWriter.STRENGTH128BITS, null, "xaris", PdfWriter.AllowCopy | PdfWriter.AllowPrinting | PdfWriter.AllowScreenReaders | PdfWriter.AllowDegradedPrinting);

                doc.Open();

                BaseFont bfArialBlack = BaseFont.CreateFont("C:\\windows\\fonts\\ariblk.ttf", BaseFont.WINANSI, false);
                BaseFont bfGaramond = BaseFont.CreateFont("C:\\windows\\fonts\\gara.ttf", BaseFont.WINANSI, false);
                Font fntTerm = new Font(bfArialBlack, 10, Font.BOLD, new BaseColor(57, 81, 145));
                Font fntDefinition = new Font(bfGaramond, 9, Font.NORMAL, new BaseColor(0, 0, 0));

                ///////////////////////////////////////////

                if (HasMultipleDefinitions) {
                    PdfContentByte cbCover = new PdfContentByte(writer);
                    cbCover = writer.DirectContent;

                    cbCover.BeginText();

                    cbCover.SetFontAndSize(bfGaramond, 42);
                    cbCover.SetRGBColorFill(57, 81, 145);
                    cbCover.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Glossary of", (PageWidth / 2) * ppi, ((PageHeight / 2) + Convert.ToSingle(1.5)) * ppi, 0);
                    cbCover.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Systematic Christian Theology", (PageWidth / 2) * ppi, ((PageHeight / 2) + 1) * ppi, 0);

                    cbCover.SetFontAndSize(bfGaramond, 16);
                    cbCover.SetRGBColorFill(0, 0, 0);
                    cbCover.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "A collection of technical terms and associated definitions", (PageWidth / 2) * ppi, ((PageHeight / 2) + Convert.ToSingle(0.6)) * ppi, 0);
                    cbCover.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "as taught by Dr. Ron Killingsworth, Rephidim Church, Wichita Falls, Texas", (PageWidth / 2) * ppi, ((PageHeight / 2) + Convert.ToSingle(0.4)) * ppi, 0);

                    cbCover.SetFontAndSize(bfGaramond, 12);
                    cbCover.SetRGBColorFill(0, 0, 0);
                    cbCover.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Published by:", (PageWidth / 2) * ppi, ((PageHeight / 2) - Convert.ToSingle(0.6)) * ppi, 0);
                    cbCover.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Rephidim Doctrinal Bible Studies, Inc.", (PageWidth / 2) * ppi, ((PageHeight / 2) - Convert.ToSingle(0.8)) * ppi, 0);
                    cbCover.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "4430 Allendale Rd., Wichita Falls, Texas 76310", (PageWidth / 2) * ppi, ((PageHeight / 2) - Convert.ToSingle(1.0)) * ppi, 0);
                    cbCover.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "(940) 691-1166     rephidim.org     [email protected]", (PageWidth / 2) * ppi, ((PageHeight / 2) - Convert.ToSingle(1.2)) * ppi, 0);

                    cbCover.SetFontAndSize(bfGaramond, 10);
                    cbCover.SetRGBColorFill(0, 0, 0);
                    cbCover.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Version: " + version + " / " + terms.Count() + " terms", (LeftRightMargin) * ppi, (TopBottomMargin) * ppi, 0);

                    cbCover.SetFontAndSize(bfGaramond, 10);
                    cbCover.SetRGBColorFill(0, 0, 0);
                    cbCover.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "© 1971-" + DateTime.Today.Year.ToString() + " Dr. Ron Killingsworth, Rephidim Doctrinal Bible Studies, Inc.", (PageWidth - LeftRightMargin) * ppi, (TopBottomMargin) * ppi, 0);

                    cbCover.EndText();

                    doc.NewPage();

                    ///////////////////////////////////////////

                    PdfContentByte cbBlank = new PdfContentByte(writer);
                    cbBlank = writer.DirectContent;

                    cbBlank.BeginText();

                    cbCover.SetFontAndSize(bfGaramond, 10);
                    cbCover.SetRGBColorFill(0, 0, 0);
                    cbCover.ShowTextAligned(PdfContentByte.ALIGN_LEFT, " ", (LeftRightMargin) * ppi, (TopBottomMargin) * ppi, 0);

                    cbBlank.EndText();

                    doc.NewPage();

                    ///////////////////////////////////////////

                }

                PdfContentByte cb = writer.DirectContent;
                ColumnText ct = new ColumnText(cb);

                int[] left = {
                    Convert.ToInt32(Column1Left * ppi),
                    Convert.ToInt32(Column2Left * ppi)
                };
                int[] right = {
                    Convert.ToInt32(Column1Right * ppi),
                    Convert.ToInt32(Column2Right * ppi)
                };

                foreach (var term in terms) {
                    ct.AddText(new Phrase(term.Term.Trim() + Environment.NewLine, fntTerm));
                    ct.AddText(new Phrase(Regex.Replace(term.Definition.Trim().Replace("<br/>", "\r"), @"<[^>]+>", "") + Environment.NewLine + Environment.NewLine, fntDefinition));
                }

                int status = 0;
                int column = 0;
                int PageNumber = 0;
                if (HasMultipleDefinitions) {
                    PageNumber = 3;
                } else {
                    PageNumber = 1;
                }
                while ((status & ColumnText.NO_MORE_TEXT) == 0) {
                    ///////////////////////////////////////////

                    PdfContentByte cbPage = new PdfContentByte(writer);
                    cbPage = writer.DirectContent;

                    cbPage.SetLineWidth(0.5f);
                    cbPage.SetRGBColorStroke(50, 50, 50);
                    cbPage.MoveTo(LeftRightMargin * ppi, (PageHeight - TopBottomMargin - (HeaderFooterHeight / 2)) * ppi);
                    cbPage.LineTo((PageWidth - LeftRightMargin) * ppi, (PageHeight - TopBottomMargin - (HeaderFooterHeight / 2)) * ppi);
                    cbPage.Stroke();

                    cbPage.SetLineWidth(0.5f);
                    cbPage.SetRGBColorStroke(50, 50, 50);
                    cbPage.MoveTo(LeftRightMargin * ppi, (TopBottomMargin + HeaderFooterHeight) * ppi);
                    cbPage.LineTo((PageWidth - LeftRightMargin) * ppi, (TopBottomMargin + HeaderFooterHeight) * ppi);
                    cbPage.Stroke();

                    cbPage.BeginText();

                    cbPage.SetFontAndSize(bfGaramond, 10);
                    cbPage.SetRGBColorFill(0, 0, 0);
                    cbPage.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "The Glossary of Systematic Christian Theology", (PageWidth / 2) * ppi, (PageHeight - TopBottomMargin) * ppi, 0);

                    if (PageNumber % 2 == 0) {
                        cbPage.SetFontAndSize(bfGaramond, 8);
                        cbPage.SetRGBColorFill(0, 0, 0);
                        cbPage.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "© 1971-" + DateTime.Today.Year.ToString() + " Dr. Ron Killingsworth, Rephidim Doctrinal Bible Studies, Inc.", (PageWidth - LeftRightMargin) * ppi, (TopBottomMargin) * ppi, 0);

                        cbPage.SetFontAndSize(bfGaramond, 8);
                        cbPage.SetRGBColorFill(0, 0, 0);
                        cbPage.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Page " + PageNumber.ToString(), (LeftRightMargin) * ppi, (TopBottomMargin) * ppi, 0);
                    } else {
                        cbPage.SetFontAndSize(bfGaramond, 8);
                        cbPage.SetRGBColorFill(0, 0, 0);
                        cbPage.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "© 1971-" + DateTime.Today.Year.ToString() + " Dr. Ron Killingsworth, Rephidim Doctrinal Bible Studies, Inc.", (LeftRightMargin) * ppi, (TopBottomMargin) * ppi, 0);

                        cbPage.SetFontAndSize(bfGaramond, 8);
                        cbPage.SetRGBColorFill(0, 0, 0);
                        cbPage.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Page " + PageNumber.ToString(), (PageWidth - LeftRightMargin) * ppi, (TopBottomMargin) * ppi, 0);

                    }

                    cbPage.EndText();

                    ///////////////////////////////////////////

                    //If HasMultipleDefinitions Then
                    //    ct.setSimpleColumn(left(column), (TopBottomMargin + (HeaderFooterHeight * 3 / 2)) * ppi, right(column), (PageHeight - TopBottomMargin - HeaderFooterHeight) * ppi, 10, Element.ALIGN_LEFT)
                    //Else
                    //    ct.setSimpleColumn(LeftRightMargin * ppi, (TopBottomMargin + (HeaderFooterHeight * 3 / 2)) * ppi, (PageWidth - LeftRightMargin) * ppi, (PageHeight - TopBottomMargin - HeaderFooterHeight) * ppi, 10, Element.ALIGN_LEFT)
                    //End If
                    //status = ct.go()
                    //If (status And ColumnText.NO_MORE_COLUMN) <> 0 Then
                    //    column += 1
                    //    If column > 1 Then

                    //        doc.newPage()
                    //        PageNumber += 1
                    //        column = 0
                    //    End If
                    //End If

                    if (HasMultipleDefinitions) {
                        ct.SetSimpleColumn(left[column], (TopBottomMargin + (HeaderFooterHeight * 3 / 2)) * ppi, right[column], (PageHeight - TopBottomMargin - HeaderFooterHeight) * ppi, 10, Element.ALIGN_LEFT);

                        status = ct.Go();
                        if ((status & ColumnText.NO_MORE_COLUMN) != 0) {
                            column += 1;

                            if (column > 1) {
                                doc.NewPage();
                                PageNumber += 1;
                                column = 0;
                            }
                        }
                    } else {
                        ct.SetSimpleColumn(LeftRightMargin * ppi, (TopBottomMargin + (HeaderFooterHeight * 3 / 2)) * ppi, (PageWidth - LeftRightMargin) * ppi, (PageHeight - TopBottomMargin - HeaderFooterHeight) * ppi, 10, Element.ALIGN_LEFT);

                        status = ct.Go();
                        if ((status) != 0) {
                            doc.NewPage();
                            PageNumber += 1;
                        }
                    }

                }

                doc.Close();
                m.Flush();
                m.Position = 0;
                return m;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 21
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");
        }
Exemplo n.º 22
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;
            }
        }
Exemplo n.º 23
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;
            }
        }
        //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();
            }
        }
Exemplo n.º 25
0
        private List<SOTable> Export(DbSchema schema, SODatabase db, List<SOTable> tableList, ExportTyep exportType)
        {
            if (schema == null) throw new ArgumentException("参数schema不能为空", "schema");
            if (db == null) throw new ArgumentException("参数dbName不能为空", "dbName");

            Document doc = new Document(PageSize.A4.Rotate(), 20, 20, 20, 20);
            DocWriter w;

            switch (exportType)
            {
                case ExportTyep.PDF:
                    w = PdfWriter.GetInstance(doc, new FileStream(fileName, FileMode.Create, FileAccess.Write));
                    break;
                case ExportTyep.RTF:
                    w = RtfWriter2.GetInstance(doc, new FileStream(fileName, FileMode.Create, FileAccess.Write));
                    break;
                //case ExportTyep.HTML:
                //    w = HtmlWriter.GetInstance(doc, new FileStream(fileName, FileMode.Create, FileAccess.Write));
                    //break;
                default:
                    break;
            }

            doc.Open();
            doc.NewPage();

            if (tableList == null) tableList = schema.GetTableList(db);

            Chapter cpt = new Chapter(db.Name, 1);
            Section sec;

            doc.AddTitle(db.Name);
            doc.AddAuthor("Kalman");
            doc.AddCreationDate();
            doc.AddCreator("Kalman");
            doc.AddSubject("数据库文档");

            foreach (SOTable table in tableList)
            {
                sec = cpt.AddSection(new Paragraph(table.Name, font));

                if (string.IsNullOrEmpty(table.Comment) == false)
                {
                    Chunk chunk = new Chunk(table.Comment, font);
                    sec.Add(chunk);
                }

                List<SOColumn> columnList = schema.GetTableColumnList(table);

                t = new Table(7, columnList.Count);

                t.AutoFillEmptyCells = true;
                t.CellsFitPage = true;
                t.TableFitsPage = true;
                t.Cellpadding = 3;
                //if (exportType == ExportTyep.PDF) t.Cellspacing = 2;
                t.DefaultVerticalAlignment = Element.ALIGN_MIDDLE;

                t.SetWidths(new int[] { 200, 150, 50, 50, 50, 100, 300 });

                t.AddCell(BuildHeaderCell("名称"));
                t.AddCell(BuildHeaderCell("数据类型"));
                t.AddCell(BuildHeaderCell("主键"));
                t.AddCell(BuildHeaderCell("标志"));
                t.AddCell(BuildHeaderCell("可空"));
                t.AddCell(BuildHeaderCell("默认值"));
                t.AddCell(BuildHeaderCell("注释"));

                foreach (SOColumn column in columnList)
                {
                    t.AddCell(BuildCell(column.Name));
                    t.AddCell(BuildCell(GetDbColumnType(column)));
                    t.AddCell(BuildCell(column.PrimaryKey ? " √" : ""));
                    t.AddCell(BuildCell(column.Identify ? " √" : ""));
                    t.AddCell(BuildCell(column.Nullable ? " √" : ""));
                    t.AddCell(BuildCell(column.DefaultValue == null ? "" : column.DefaultValue.ToString()));
                    t.AddCell(BuildCell(column.Comment));
                }

                sec.Add(t);
            }

            doc.Add(cpt);
            doc.Close();
            return tableList;
        }
Exemplo n.º 26
0
    //public void GeneratePDF(DataSet _ms)
    public void GeneratePDF(String EstNum, String IsFinancial)
    {
        Whitfieldcore _wc = new Whitfieldcore();
        // MemoryStream m = new MemoryStream();
        // Document document = new Document();
        FileStream MyStream = null;
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        try
        {
            iTextSharp.text.Font[] fonts = new iTextSharp.text.Font[16];
            fonts[0] = FontFactory.GetFont(FontFactory.COURIER, 8, iTextSharp.text.Font.NORMAL);
            fonts[1] = FontFactory.GetFont(FontFactory.COURIER, 8, iTextSharp.text.Font.BOLD);
            fonts[2] = FontFactory.GetFont(FontFactory.COURIER, 8, iTextSharp.text.Font.ITALIC);
            fonts[3] = FontFactory.GetFont(FontFactory.COURIER, 8, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.ITALIC);
            fonts[4] = FontFactory.GetFont(FontFactory.HELVETICA, 8, iTextSharp.text.Font.NORMAL);
            fonts[5] = FontFactory.GetFont(FontFactory.HELVETICA, 8, iTextSharp.text.Font.BOLD);
            fonts[6] = FontFactory.GetFont(FontFactory.HELVETICA, 8, iTextSharp.text.Font.ITALIC);
            fonts[7] = FontFactory.GetFont(FontFactory.HELVETICA, 8, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.ITALIC);
            fonts[8] = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 10, iTextSharp.text.Font.NORMAL);
            fonts[9] = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 10, iTextSharp.text.Font.BOLD);
            fonts[10] = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 10, iTextSharp.text.Font.ITALIC);
            fonts[11] = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 10, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.ITALIC);
            fonts[12] = FontFactory.GetFont(FontFactory.SYMBOL, 10, iTextSharp.text.Font.NORMAL);
            fonts[13] = FontFactory.GetFont(FontFactory.ZAPFDINGBATS, 10, iTextSharp.text.Font.NORMAL);
            fonts[14] = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 10, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.UNDERLINE, iTextSharp.text.Color.GRAY);
            fonts[15] = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.GRAY);

            // Response.ContentType = "application/pdf";
            // Response.AddHeader("content-disposition", "attachment;filename=Proposal_Document.pdf");
            //<Current Date> - <Project Name>, Architectural Millwork - WhitfieldCo
            //String _filename = DateTime.Now.ToString("MM-dd-yyyy") + "-"  + txtprjname  + ", Architectural Millwork - WhitfieldCo.pdf"
            //PdfWriter.GetInstance(document, new FileStream(_filename, FileMode.Create));
            //PdfWriter writer = PdfWriter.GetInstance(document, m);
            //writer.CloseStream = false;

            IDataReader iReader = _wc.GetProjectInfo(Convert.ToInt32(EstNum));
            while (iReader.Read())
            {
                txtprjname = iReader["ProjName"] == DBNull.Value ? "" : iReader["ProjName"].ToString();
                lblPrjHeader = iReader["ProjName"] == DBNull.Value ? "" : iReader["ProjName"].ToString();
                txtbasebid = iReader["BaseBid"] == DBNull.Value ? "" : iReader["BaseBid"].ToString();
                txtfinalbid = iReader["FinalPrice"] == DBNull.Value ? "" : iReader["FinalPrice"].ToString();
                txtdesc = iReader["ProjDescr"] == DBNull.Value ? "" : iReader["ProjDescr"].ToString();
                txtNotes = iReader["Notes"] == DBNull.Value ? "" : iReader["Notes"].ToString();
                txtBidDate = iReader["BidDate"] == DBNull.Value ? "" : iReader["BidDate"].ToString();
                txtEditStartTime = iReader["BidTime"] == DBNull.Value ? "" : iReader["BidTime"].ToString();
                txtARDt = iReader["AwardDur"] == DBNull.Value ? "" : iReader["AwardDur"].ToString();
                txtawardDate = iReader["AwardDate"] == DBNull.Value ? "" : iReader["AwardDate"].ToString();
                txtConstStdate = iReader["ConstrStart"] == DBNull.Value ? "" : iReader["ConstrStart"].ToString();
                txtConstDuration = iReader["ConstrDur"] == DBNull.Value ? "" : iReader["ConstrDur"].ToString();
                txtConstEndDate = iReader["ConstrCompl"] == DBNull.Value ? DateTime.Now.ToString() : iReader["ConstrCompl"].ToString();
                //Adding New Fields
                txtfabEndDate = iReader["fab_end"] == DBNull.Value ? "" : iReader["fab_end"].ToString();
                txtfabStartdate = iReader["fab_start"] == DBNull.Value ? "" : iReader["fab_start"].ToString();
                txtfabdurationt = iReader["fab_duration"] == DBNull.Value ? "" : iReader["fab_duration"].ToString();
                txtStreet = iReader["prj_street"] == DBNull.Value ? "" : iReader["prj_street"].ToString();
                txtCity = iReader["prj_city"] == DBNull.Value ? "" : iReader["prj_city"].ToString();
                txtState = iReader["prj_state"] == DBNull.Value ? "" : iReader["prj_state"].ToString();
                txtzip = iReader["prj_zip"] == DBNull.Value ? "" : iReader["prj_zip"].ToString();
                //New Fields Ends
                txtrealprjNumbert = iReader["Real_proj_Number"] == DBNull.Value ? "" : iReader["Real_proj_Number"].ToString();
                prjArch = iReader["Architect"] == DBNull.Value ? "" : iReader["Architect"].ToString();
                prjEsti = iReader["loginid"] == DBNull.Value ? "" : iReader["loginid"].ToString();
                txtTotCotCost = iReader["Contengency"] == DBNull.Value ? "0" : iReader["Contengency"].ToString();
                txtEngRate = iReader["enghourrate"] == DBNull.Value ? "45.00" : iReader["enghourrate"].ToString();
                txtFabRate = iReader["fabhourrate"] == DBNull.Value ? "32.00" : iReader["fabhourrate"].ToString();
                txtInstRate = iReader["insthourrate"] == DBNull.Value ? "45.00" : iReader["insthourrate"].ToString();
                txtMiscRate = iReader["mischourrate"] == DBNull.Value ? "25.00" : iReader["mischourrate"].ToString();
                txtOverHeadRate = iReader["overheadrate"] == DBNull.Value ? "24.11" : iReader["overheadrate"].ToString();
                txtMarkUpPercent = iReader["profit_markup"] == DBNull.Value ? "15.00" : iReader["profit_markup"].ToString();
                txtDrawingDate = iReader["drawingdate"] == DBNull.Value ? "" : iReader["drawingdate"].ToString();
                txtTypeOfWork = iReader["typeofwork"] == DBNull.Value ? "" : iReader["typeofwork"].ToString();
            }

            Chunk chunkHeading;
            if (txtprjname.Length >= 30)
            {
                chunkHeading = new Chunk(txtprjname + "                                                                                                      ", fonts[15]);
            }
            else
            {
                chunkHeading = new Chunk(txtprjname + "                                                                                                                                      ", fonts[15]);
            }

            String _modetype = IsFinancial == "Y" ? "Proposal" : "Scope";

            Int32 _document_rev_number = GenerateseqNumberforDocs(Convert.ToInt32(EstNum), _modetype);

            _filename = DateTime.Now.ToString("MM-dd-yyyy") + "-" + txtprjname.Replace("."," ").Trim() + " Architectural Millwork - WhitfieldCo " + _modetype + "-REV 0" + _document_rev_number + ".pdf";

                //if (File.Exists(HttpContext.Current.Server.MapPath("~/attachments/") + _filename))  //If the file exists, create new one.
                //{
                //    //File.Delete(HttpContext.Current.Server.MapPath("~/attachments/") + _filename);
                //    char[] splitchar = { '.' };
                //    string[] strArr = null;
                //    strArr = _filename.Split(splitchar);
                //    String _filenmTest = strArr[0];
                //    int intIndexSubstring = 0;
                //    intIndexSubstring = _filenmTest.IndexOf("-REV#");
                //    _filename = DateTime.Now.ToString("MM-dd-yyyy") + "-" + txtprjname.Replace(".", " ").Trim() + " Architectural Millwork - WhitfieldCo " + _modetype  +"-REV#0" + (Convert.ToInt32(_filenmTest.Substring(intIndexSubstring).Substring(5)) + 1).ToString() + ".pdf";

                //}
                //FileStream MyStream;
                //MyStream = new FileStream(HttpContext.Current.Server.MapPath("~/attachments/") + _filename, FileMode.Create);
                //PdfWriter.GetInstance(document, new FileStream(HttpContext.Current.Server.MapPath("~/attachments/") + _filename, FileMode.Create));
                //using (StreamWriter sw = File.CreateText(mappath + "patientquery.txt"))

            using ( MyStream = new FileStream(HttpContext.Current.Server.MapPath("~/attachments/") + _filename, FileMode.Create))
            //using (FileStream MyStream = File.Create(HttpContext.Current.Server.MapPath("~/attachments/") + _filename))
            //new FileStream(HttpContext.Current.Server.MapPath("~/attachments/") + _filename, FileMode.Create)
            {
                PdfWriter.GetInstance(document, MyStream);
                //attachments
                document.AddAuthor("Whitfield Corporation");
                document.AddSubject("Proposal Generator");

                iTextSharp.text.Image img = this.DoGetImageFile(HttpContext.Current.Server.MapPath("~/assets/img/TWC Primary Logo1.JPG"));
                img.ScalePercent(50);
                Chunk ck = new Chunk(img, 0, -5);

                HeaderFooter headerRight = new HeaderFooter(new Phrase(chunkHeading), new Phrase(ck));
                document.Header = headerRight;
                headerRight.Alignment = iTextSharp.text.Rectangle.ALIGN_RIGHT;
                headerRight.Border = iTextSharp.text.Rectangle.NO_BORDER;

                // we Add a Footer that will show up on PAGE 1
                Phrase phFooter = new Phrase("The Whitfield Corporation, Incorporated  ", fonts[15]);
                phFooter.Add(new Phrase("P.O. Box 0385, Fulton, MD 20759  ", fonts[8]));
                phFooter.Add(new Phrase("Main: 301 483 0791 Fax: 301 483 0792  ", fonts[8]));
                phFooter.Add(new Phrase("\nDelivering on Promises", fonts[11]));
                //
                HeaderFooter footer = new HeaderFooter(phFooter, false);
                footer.Border = iTextSharp.text.Rectangle.NO_BORDER;
                footer.Alignment = iTextSharp.text.Rectangle.ALIGN_CENTER;
                document.Footer = footer;
                // step 3: we open the document
                document.Open();

                // we Add a Header that will show up on PAGE 2

                DateTime dt = DateTime.Now;
                //Chapters and Sections
                int ChapterSequence = 1;
                document.NewPage();
                iTextSharp.text.Font chapterFont = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 16, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK);
                iTextSharp.text.Font sectionFont = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
                iTextSharp.text.Font subsectionFont = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 14, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK);

                //Chapter 1 Overview
                Paragraph cTitle = new Paragraph(_modetype, chapterFont);
                Chapter chapter = new Chapter(cTitle, ChapterSequence);

                Paragraph ChapterDate = new Paragraph(dt.ToString("\nMMMM dd, yyyy \n\n"), fonts[8]);
                Paragraph ChapterRef = new Paragraph("RE:   " + txtprjname + "\n\n", fonts[8]);

                Paragraph ChapterText1;

                if (txtTypeOfWork.Trim() == "Time & Material")
                {

                    ChapterText1 = new Paragraph("Whitfield proposes to complete the scope of work on a Time & Material basis per the rates included in the Item Breakdown section of this proposal.\n\n", fonts[8]);
                }
                else
                {
                    ChapterText1 = new Paragraph("Whitfield proposes to furnish all materials and perform all labor necessary, including " + txtTypeOfWork + ", to complete the following scope of work as per the Scope of Work breakdown.\n\n", fonts[8]);
                }

                String _fnlAmt = "";
                String amtWithnoDecimal = "";

                if (txtbasebid != "")
                {
                    string[] txtBaseBidStr = txtbasebid.Split('.');
                    custom.util.NumberToEnglish num = new custom.util.NumberToEnglish();
                    _fnlAmt = num.changeCurrencyToWords(txtBaseBidStr[0].Replace("$", "").Trim());
                    amtWithnoDecimal = txtBaseBidStr[0] + ".00";
                }

                contingency _cont = new contingency();
                if (IsFinancial == "Y")
                {

                    Paragraph ChapterText2;
                    if (txtTypeOfWork.Trim() == "Time & Material")
                    {
                        ChapterText2 = new Paragraph("The Material cost in the amount of " + _fnlAmt + " Dollars and No Cents (" + Convert.ToDecimal(amtWithnoDecimal).ToString("C") + ") includes all profit markup and assumes a construction start on approximately " + Convert.ToDateTime(txtConstStdate).ToString("MMMM dd, yyyy") + " with a completion on or around " + Convert.ToDateTime(txtConstEndDate).ToString("MMMM dd, yyyy") + " .\n\n", fonts[8]);
                        //ChapterText2.Add(new Phrase(new Chunk("This cost is in addition to any Time & Material cost and will be calculated on a unit price basis as included in the Item Breakdown section of this proposal for any time extension beyond the agreed upon construction schedule as included in this proposal.\n\n", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 10, iTextSharp.text.Font.ITALIC | iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK))));
                    }
                    else
                    {
                        ChapterText2 = new Paragraph("This proposal assumes all of the above work completed by " + Convert.ToDateTime(txtConstEndDate).ToString("MMMM dd, yyyy") + " for the sum of ", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 8, iTextSharp.text.Font.ITALIC | iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK));
                        ChapterText2.Add(new Phrase(new Chunk(" " + _fnlAmt + "Dollars and No Cents (" + Convert.ToDecimal(amtWithnoDecimal).ToString("C") + ").\n\n", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 8, iTextSharp.text.Font.ITALIC | iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK))));
                    }

                    chapter.Add(ChapterDate);
                    chapter.Add(ChapterRef);
                    chapter.Add(ChapterText1);
                    chapter.Add(ChapterText2);

                    // Chapter Item Breakdown
                    DataSet dsCont = _cont.FetchProjectItemBreakdown(Convert.ToInt32(EstNum));
                    if (dsCont.Tables[0].Rows.Count > 0)
                    {
                        Paragraph cBreakDown = new Paragraph("Item Breakdown", chapterFont);
                        chapter.Add(cBreakDown);
                        DataTable myValues;
                        myValues = dsCont.Tables[0];
                        int icntBreakDown = 1;
                        foreach (DataRow dRow in myValues.Rows)
                        {
                            String _cntlDesc = dRow["Description"] == DBNull.Value ? "" : dRow["Description"].ToString();
                            String _cntlAmt = dRow["Amount"] == DBNull.Value ? "" : dRow["Amount"].ToString();
                            Paragraph itemAlternatives = new Paragraph(icntBreakDown.ToString() + ". " + _cntlDesc + "...." + _cntlAmt, fonts[8]);
                            icntBreakDown++;
                            chapter.Add(itemAlternatives);
                        }

                    }

                    // Chapter Alternatives
                    DataSet dsAlternatives = _cont.FetchAlternatives(Convert.ToInt32(EstNum));
                    if (dsAlternatives.Tables[0].Rows.Count > 0)
                    {
                        Paragraph c = new Paragraph("\nAlternates", fonts[14]);
                        chapter.Add(c);
                        DataTable myValues;
                        myValues = dsAlternatives.Tables[0];
                        int icntAlternatives = 1;
                        foreach (DataRow dRow in myValues.Rows)
                        {
                            String _altType = dRow["Type"] == DBNull.Value ? "" : dRow["Type"].ToString();
                            String _cntlDesc = dRow["Description"] == DBNull.Value ? "" : dRow["Description"].ToString();
                            String _cntlAmt = dRow["Amount"] == DBNull.Value ? "" : dRow["Amount"].ToString();
                            Paragraph itemAlternatives = new Paragraph(icntAlternatives.ToString() + ". " + _altType + ":" + _cntlDesc + "...." + _cntlAmt, fonts[8]);
                            icntAlternatives++;
                            chapter.Add(itemAlternatives);
                        }
                    }
                    //document.Add(chapter);
                    //Chapters and Sections Declarations End.
                }

                //**********************Chapter for Itemized Scope of Work Begins
                //ChapterSequence++;
                Paragraph cAssumptions = new Paragraph("\nItemized Scope of Work", chapterFont);
                chapter.Add(cAssumptions);
                //Chapter chapterAssumptions = new Chapter(cAssumptions, ChapterSequence);

                //Paragraph AssumptionsHeading = new Paragraph("Scope of Work\n\n", sectionFont);
                Paragraph AssumptionsText1 = new Paragraph("Provided hereto is an itemized clarification of the proposed scope. It has been developed and derived from the pricing documents to clarify various assumptions that were considered while compiling this estimate. The General Conditions (listed last) occur throughout the scope of work and apply to “typical applications”, which are subsequently itemized in the corresponding breakdown. " + ".\n\n", fonts[8]);
                //AssumptionsText1.Add(new Phrase(new Chunk("Proposed price includes " + txtTypeOfWork + ".\n\n", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 10, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK))));
                //chapterAssumptions.Add(AssumptionsHeading);
                chapter.Add(AssumptionsText1);

                DataSet dsScope = _wc.GetWorkOrders(EstNum);
                if (dsScope.Tables[0].Rows.Count > 0)
                {
                    LoadScopeOfWork(chapter, dsScope, fonts[14]);
                }

                Paragraph DrawingsPara1 = new Paragraph("Drawings:", fonts[14]);
                chapter.Add(DrawingsPara1);

                Paragraph itemDrawing = new Paragraph(txtprjname + " drawings prepared by " + _wc.GetArchitectName(Convert.ToInt32(prjArch)) + " dated " + txtDrawingDate + ".", fonts[8]);
                chapter.Add(itemDrawing);

                DataSet dsSpecs = _cont.FetchAmendmenList(Convert.ToInt32(EstNum));
                if (dsSpecs.Tables[0].Rows.Count > 0)
                {
                    Paragraph DrawingsPara = new Paragraph("\nAdditional Documents:", fonts[14]);
                    chapter.Add(DrawingsPara);
                    DataTable MyTerms;
                    MyTerms = dsSpecs.Tables[0];
                    int icntamendments = 1;
                    foreach (DataRow dRow in MyTerms.Rows)
                    {
                        String _AmedmentsType = dRow["type"] == DBNull.Value ? "" : dRow["type"].ToString();
                        String _AmedmentNumber = dRow["amendment_number"] == DBNull.Value ? "" : dRow["amendment_number"].ToString();
                        String _AmedmentDate = dRow["amendment_date"] == DBNull.Value ? "" : dRow["amendment_date"].ToString();
                        String amendment_impact = dRow["amendment_impact"] == DBNull.Value ? "" : dRow["amendment_impact"].ToString();
                        //if (_AmedmentsType == "Amendment")
                        //{
                        if (amendment_impact.ToLower() == "yes")
                        {
                            Paragraph itemAmendment = new Paragraph(icntamendments.ToString() + ". " + _AmedmentsType + " " + _AmedmentNumber + " dated " + _AmedmentDate + " impacts this scope of work.", fonts[8]);
                            chapter.Add(itemAmendment);
                            //Amendment 001 dated 11/19/2010; This Amendment has no impact to this scope of work.
                        }
                        else
                        {
                            Paragraph itemAmendment = new Paragraph(icntamendments.ToString() + ". " + _AmedmentsType + " " + _AmedmentNumber + " dated " + _AmedmentDate + " does not impact this scope of work.", fonts[8]);
                            chapter.Add(itemAmendment);
                        }

                        //}
                        //else
                        //{
                        //    Paragraph itemAmendment = new Paragraph(icntamendments.ToString() + ". " + _AmedmentsType + " " + _AmedmentNumber + " " + _AmedmentDate, fonts[8]);
                        //    chapter.Add(itemAmendment);
                        //}

                        icntamendments++;
                    }
                }
                //Qualifications
                DataSet dsConditions = _wc.GetSpecExcl(Convert.ToInt32(EstNum));
                if (dsConditions.Tables[0].Rows.Count > 0)
                {
                    Paragraph DrawingsPara = new Paragraph("\nQualifications:", fonts[14]);
                    chapter.Add(DrawingsPara);
                    int icnt = 1;
                    DataTable MyConditions;
                    MyConditions = dsConditions.Tables[0];
                    int tQualid = 0;
                    foreach (DataRow dRow in MyConditions.Rows)
                    {
                        if (Convert.ToInt32(dRow["qual_id"].ToString()) != tQualid)
                        {
                            Paragraph itemheading = new Paragraph(dRow["gName1"].ToString(), fonts[9]);
                            chapter.Add(itemheading);
                        }
                        String _cntlDesc = dRow["description"] == DBNull.Value ? "" : dRow["description"].ToString();
                        Paragraph itemTerms = new Paragraph(icnt.ToString() + ".  " + _cntlDesc, fonts[8]);
                        chapter.Add(itemTerms);
                        tQualid = Convert.ToInt32(dRow["qual_id"].ToString());
                        icnt++;
                    }
                }

                // document.Add(chapter);
                //************************Chapter for Itemized Scope of Work Ends

                //*******Chapter Terms Begins********************
                //ChapterSequence++;
                Paragraph cTerms = new Paragraph("\nTerms", fonts[14]);
                //Chapter chapterTerms = new Chapter(cTerms, ChapterSequence);
                chapter.Add(cTerms);
                //Chapter chapterTerms = new Chapter(cTerms, ChapterSequence);
                DataSet dsTerms = _wc.GetTerms(Convert.ToInt32(EstNum));

                if (dsTerms.Tables[0].Rows.Count > 0)
                {
                    DataTable MyTerms;
                    MyTerms = dsTerms.Tables[0];
                    int icntTerms = 1;
                    foreach (DataRow dRow in MyTerms.Rows)
                    {
                        String _cntlDesc = dRow["description"] == DBNull.Value ? "" : dRow["description"].ToString();
                        Paragraph itemTerms = new Paragraph(icntTerms.ToString() + ". " + _cntlDesc, fonts[8]);
                        chapter.Add(itemTerms);
                        icntTerms++;
                    }
                }

                Paragraph ChapterFooterText1 = new Paragraph("\nAll or part of the contract amount may be subject to change pending completion delay beyond agreed completion date and/or if changes to quantities are made. All agreements must be in writing prior to execution of any work.\n\n", fonts[8]);
                ChapterFooterText1.Add(Chunk.NEWLINE);
                ChapterFooterText1.Add(new Chunk("Respectfully submitted, ", fonts[8]));
                ChapterFooterText1.Add(new Chunk("                                                                  "));
                ChapterFooterText1.Add(new Chunk("Accepted By:, ", fonts[8]));
                ChapterFooterText1.Add(Chunk.NEWLINE);
                ChapterFooterText1.Add(new Chunk("The Whitfield Co., Inc., ", fonts[8]));
                ChapterFooterText1.Add(new Chunk("                                                                      "));
                ChapterFooterText1.Add(new Chunk("________________________ Date_________", fonts[8]));
                ChapterFooterText1.Add(Chunk.NEWLINE);
                ChapterFooterText1.Add(new Chunk("Jammie Whitfield, ", fonts[8]));
                ChapterFooterText1.Add(new Chunk("                                                                              "));
                ChapterFooterText1.Add(new Chunk("Name, Title", fonts[8]));
                //Paragraph ChapterFooterText2 = new Paragraph("Respectfully submitted,", fonts[8]);
                //Paragraph ChapterFooterText3 = new Paragraph("The Whitfield Co., Inc.\n\n", fonts[8]);
                //Paragraph ChapterFooterText4 = new Paragraph("Jammie Whitfield,", fonts[8]);
                //Paragraph ChapterFooterText5 = new Paragraph("Estimator", fonts[8]);

                chapter.Add(ChapterFooterText1);
                // Paragraph ChapterFooterText2 = new Paragraph("Respectfully submitted,", fonts[8]);
               // Paragraph ChapterFooterText3 = new Paragraph("The Whitfield Co., Inc.\n\n", fonts[8]);
                //Paragraph ChapterFooterText4 = new Paragraph("Jammie Whitfield,\n\n", fonts[8]);
                //Paragraph ChapterFooterText5 = new Paragraph("Accepted By:\n\n", fonts[8]);
               // Paragraph ChapterFooterText6 = new Paragraph("________________________ Date__________", fonts[8]);
               // Paragraph ChapterFooterText7 = new Paragraph("Name, Title", fonts[8]);

                chapter.Add(ChapterFooterText1);
               // chapter.Add(ChapterFooterText2);
               // chapter.Add(ChapterFooterText3);
               // chapter.Add(ChapterFooterText4);
               // chapter.Add(ChapterFooterText5);
                document.Add(chapter);

                //document.Add(new Chunk("Respectfully submitted, ", fonts[8]));
                //document.Add(new Chunk("                                                               "));
                //document.Add(new Chunk("Accepted By:, ", fonts[8]));
                //document.Add(Chunk.NEWLINE);
                //document.Add(new Chunk("The Whitfield Co., Inc., ", fonts[8]));
                //document.Add(new Chunk("                                                            "));
                //document.Add(new Chunk("________________________ Date_________", fonts[8]));
                //document.Add(Chunk.NEWLINE);
                //document.Add(new Chunk("Jammie Whitfield, ", fonts[8]));
                //document.Add(new Chunk("                                                                     "));
                //document.Add(new Chunk("Name, Title", fonts[8]));
                //*******Chapter Terms Ends********************
                document.Close();
                //MyStream.Flush();
                //MyStream.Close();
                //MyStream.Dispose();
                //}
                SetupEmailDocs(Convert.ToInt32(EstNum), _document_rev_number, _filename, _modetype);
                sendEmail(EstNum, _filename, IsFinancial);
            }
        }
        catch (DocumentException ex)
        {
            HttpResponse objResponse = HttpContext.Current.Response;
            objResponse.Write(ex.Message);
        }
        finally
        {
            if (MyStream != null)
            {
                MyStream.Close();
                MyStream.Dispose();
            }
        }

        //Response.Buffer = true;
        //Response.Clear();
        //Write pdf byes to outputstream
        //Response.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length);
        //Response.OutputStream.Flush();
        //Response.End();
    }
Exemplo n.º 27
0
    protected void GeneratePDF()
    {
        // Refresh the summary grid else there will be nothing to generate (no postback)
        this.PopulateGrid();

        // Create and initialize a new document object
        iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LEGAL, 24, 24, 24, 24);
        document.PageSize.Rotate();
        System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();

        try
        {
            // Create an instance of the writer object
            iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, memoryStream);

            // Add some meta information to the document
            Label lblPageTitle = (Label)(this.Page.Master.FindControl("lblDefaultMasterPageTitle"));
            document.AddAuthor(lblPageTitle.Text);
            document.AddSubject(this.lblReportTitle.Text);

            // Open the document
            document.Open();

            // Create a table to match our current summary grid
            iTextSharp.text.Table table = null;

            if (this.DateRangeType == DateRangeTypes.UserSpecified)
                table = new iTextSharp.text.Table(6);
            else if (this.DateRangeType == DateRangeTypes.Daily)
                table = new iTextSharp.text.Table(7);
            else
                table = new iTextSharp.text.Table(8);

            table.TableFitsPage = true;

            // Apply spacing/padding/borders/column widths to the table
            table.Padding = 2;
            table.Spacing = 0;
            table.DefaultCellBorderWidth = 1;

            if (this.DateRangeType == DateRangeTypes.UserSpecified)
            {
                float[] headerwidths1 = { 30, 30, 30, 30, 30, 30 };
                table.Widths = headerwidths1;
            }
            else if (this.DateRangeType == DateRangeTypes.Daily)
            {
                float[] headerwidths2 = { 40, 30, 30, 30, 30, 30, 30 };
                table.Widths = headerwidths2;
            }
            else
            {
                float[] headerwidths3 = { 40, 30, 30, 30, 30, 30, 30, 35 };
                table.Widths = headerwidths3;
            }

            table.Width = 100;

            // Add report title spanning all columns
            iTextSharp.text.Font titleFont = new iTextSharp.text.Font(Font.GetFamilyIndex("Tahoma"), 6, Font.BOLD);
            titleFont.Color = new iTextSharp.text.Color(System.Drawing.Color.Firebrick);

            iTextSharp.text.Cell titleCell = new iTextSharp.text.Cell();
            titleCell.SetHorizontalAlignment("Left");
            titleCell.SetVerticalAlignment("Top");
            titleCell.BackgroundColor = new iTextSharp.text.Color(System.Drawing.Color.White);
            titleCell.BorderWidth = 0;

            if (this.DateRangeType == DateRangeTypes.UserSpecified)
                titleCell.Colspan = 6;
            else if (this.DateRangeType == DateRangeTypes.Daily)
                titleCell.Colspan = 7;
            else
                titleCell.Colspan = 8;

            titleCell.AddElement(new iTextSharp.text.Phrase(this.lblReportTitle.Text, titleFont));
            table.AddCell(titleCell);

            // Add table headers
            for (int i = 0; i < this.grdRaveForm.Columns.Count; i++)
            {
                iTextSharp.text.Font headerCellFont = new iTextSharp.text.Font(Font.GetFamilyIndex("Tahoma"), 8, Font.NORMAL + Font.UNDERLINE);
                headerCellFont.Color = new iTextSharp.text.Color(System.Drawing.Color.White);

                iTextSharp.text.Cell headerCell = new iTextSharp.text.Cell();
                headerCell.SetHorizontalAlignment("Left");
                headerCell.SetVerticalAlignment("Top");
                headerCell.BackgroundColor = new iTextSharp.text.Color(System.Drawing.Color.SteelBlue);
                headerCell.BorderColor = new iTextSharp.text.Color(System.Drawing.Color.White);

                headerCell.AddElement(new iTextSharp.text.Phrase(this.grdRaveForm.Columns[i].HeaderText, headerCellFont));
                table.AddCell(headerCell);
            }

            table.EndHeaders();

            // Add data to the table
            int j = 0;
            int k = 0;
            string phrase = "";

            foreach (System.Data.DataRow row in this._pdfDataTable.Rows)
            {
                j++; // Increment the row counter
                k = 0; // Reset the column counter for the new row

                foreach (System.Data.DataColumn col in this._pdfDataTable.Columns)
                {
                    k++; // Increment the column counter

                    iTextSharp.text.Font cellFont = new iTextSharp.text.Font(Font.GetFamilyIndex("Tahoma"), 6, Font.NORMAL);

                    if (j % 2 == 0)
                    {
                        cellFont.Color = new iTextSharp.text.Color(System.Drawing.Color.DarkRed);
                    }
                    else
                    {
                        cellFont.Color = new iTextSharp.text.Color(System.Drawing.Color.Black);
                    }

                    iTextSharp.text.Cell cell = new iTextSharp.text.Cell();
                    cell.SetHorizontalAlignment("Left");
                    cell.SetVerticalAlignment("Top");
                    cell.BorderColor = new iTextSharp.text.Color(System.Drawing.Color.White);

                    if (j % 2 == 0)
                    {
                        cell.BackgroundColor = new iTextSharp.text.Color(System.Drawing.Color.LightGray);
                    }
                    else
                    {
                        cell.BackgroundColor = new iTextSharp.text.Color(System.Drawing.Color.White);
                    }

                    // Generate formatted phrase for cell.
                    switch (col.ColumnName)
                    {
                        case "SummaryDate":
                        case "MaxDate":
                            phrase = String.Format("{0,10:MM/dd/yyyy}", row[col]);
                            break;
                        case "AvgSecs":
                        case "StdDevSecs":
                            phrase = String.Format("{0:F2}", row[col]);
                            break;
                        case "FormIDCount":
                            phrase = String.Format("{0:G}", row[col]);
                            break;
                        default:
                            phrase = row[col].ToString();
                            break;
                    }

                    cell.AddElement(new iTextSharp.text.Phrase(phrase, cellFont));
                    table.AddCell(cell);
                }
            }

            // Add the table to the document
            document.Add(table);

            // Close the document
            document.Close();

            // Show the document
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;filename=" + Enum.GetName(typeof(DateRangeTypes), this.DateRangeType) + "Performance" + ((DropDownList)this.Page.Master.FindControl("ddlReport")).SelectedItem.Text.Replace(" ", String.Empty) + ".pdf");
            Response.ContentType = "application/pdf";
            Response.BinaryWrite(memoryStream.ToArray());
            Response.End();
        }
        catch (Exception xcptn)
        {
            Response.Write(xcptn.Message);
        }
    }
Exemplo n.º 28
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());
            }
        }
Exemplo n.º 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(f.Brief);
            using (MemoryStream stream = new MemoryStream())
            {
                PdfWriter writer = PdfWriter.GetInstance(doc, stream);
                writer.SetEncryption(true, null, null, PdfWriter.ALLOW_PRINTING);
                writer.ViewerPreferences = PdfWriter.PageModeUseOutlines;
                writer.PageEvent = new HeaderFooterPdfPageEventHelper();

                doc.Open();

                foreach (var w in f.Webcasts.Where(w => w.Script != null).OrderBy(w => w.Aired))
                {
                    Paragraph p = new Paragraph(w.Title, font);
                    p.Alignment = 1;
                    Chapter chapter = new Chapter(p, 1);
                    chapter.NumberDepth = 0;
                    chapter.BookmarkTitle = w.Title;
                    chapter.TriggerNewPage = true;
                    doc.Add(chapter);

                    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());
            }
        }
        protected void Exportchart(ArrayList chart)
        {
            string uid = Session["UserID"].ToString();
            MemoryStream msReport = new MemoryStream();

            try
            {
                document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER, 72, 72, 82, 72);
                iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, msReport);
                document.AddAuthor("Test");
                document.AddSubject("Export to PDF");
                document.Open();

                for (int i = 0; i < chart.Count; i++)
                {
                    iTextSharp.text.Chunk c = new iTextSharp.text.Chunk("Export chart to PDF", iTextSharp.text.FontFactory.GetFont("VERDANA", 15));
                    iTextSharp.text.Paragraph p = new iTextSharp.text.Paragraph();
                    p.Alignment = iTextSharp.text.Element.ALIGN_CENTER;
                    iTextSharp.text.Image hImage = null;
                    hImage = iTextSharp.text.Image.GetInstance(MapPath(chart[i].ToString()));

                    float NewWidth = 500;
                    float MaxHeight = 400;

                    if (hImage.Width <= NewWidth) { NewWidth = hImage.Width; } float NewHeight = hImage.Height * NewWidth / hImage.Width; if (NewHeight > MaxHeight)
                    {
                        NewWidth = hImage.Width * MaxHeight / hImage.Height;
                        NewHeight = MaxHeight;
                    }

                    float ratio = hImage.Width / hImage.Height;
                    hImage.ScaleAbsolute(NewWidth, NewHeight);
                    document.Add(p);
                    document.Add(hImage);
                }
                // close it
                document.Close();
                string filename = "Appraisal Overview for " + Session["StaffName"].ToString() + ".pdf";
                Response.AddHeader("Content-type", "application/pdf");
                Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
                Response.OutputStream.Write(msReport.GetBuffer(), 0, msReport.GetBuffer().Length);

            }
            catch (System.Threading.ThreadAbortException ex)
            {
                throw new Exception("Error occured: " + ex);
            }
        }
Exemplo n.º 31
0
        private void GenerateReportButtonResultsView_Click(object sender, EventArgs e)
        {
            if (RepDirTextBox.Text == "" || RepDirTextBox.Text == "Set the folder where the pdf reports will be stored") { MessageBox.Show("Please select a folder on configuration tab to save the reports."); }
            else
            {
                GenerateReportResultsViewClicked = true;
                try
                {
                    // event fired when the contextual menu was clicked
                    //ToolStripMenuItem mi = (ToolStripMenuItem)e.ClickedItem;
                    // mi : item clicked in the contextual menu
                    // VStream tvs = (VStream)mi.Tag;

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

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

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

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

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

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

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

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

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

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

            }
        }
Exemplo n.º 32
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);
 }
Exemplo n.º 33
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());
            }
        }
Exemplo n.º 34
0
        private void EndOfProductionButton_Click(object sender, EventArgs e)
        {
            string filename = "C:/OP2GUI/";

            if (System.IO.Directory.Exists(filename))
            {
            }
            else
            {
                Directory.CreateDirectory(filename);
            }



            DateTime now = DateTime.Now;

            rapor = new iTextSharp.text.Document();
            PdfWriter.GetInstance(rapor, new FileStream("C:/OP2GUI/" + Initialize.name + DateTime.Now.ToString("yyyyMMddHHmmss") + "OP2GUI.pdf", FileMode.Create));
            rapor.SetMargins(80, 80, 80, 80);
            Initialize.name = TurkceKarakter(Initialize.name);
            rapor.AddAuthor(Initialize.name);
            rapor.AddCreationDate();
            rapor.AddCreator(Initialize.name);
            rapor.AddSubject(Initialize.name + "|OP2-GUI");


            if (rapor.IsOpen() == false)
            {
                rapor.Open();
            }


            BaseFont times  = BaseFont.CreateFont("c:\\windows\\fonts\\times.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            Font     font16 = new Font(times, 16);
            Font     font14 = new Font(times, 14);
            Font     font12 = new Font(times, 12);

            ///Tarih Ekle
            Paragraph head0 = new Paragraph(now.ToString(), font12);

            head0.Alignment = Element.ALIGN_RIGHT;
            rapor.Add(head0);

            ////Başlık
            Paragraph head = new Paragraph("OP2-GUI", font16);

            head.Alignment = Element.ALIGN_CENTER;
            rapor.Add(head);

            ///Üretimden Sorumlu kişi
            Paragraph head2 = new Paragraph("Üretimden Sorumlu Kisi: " + Initialize.name, font14);

            head2.Alignment = Element.ALIGN_CENTER;
            rapor.Add(head2);

            /// Yeni Veriler
            PdfNewDataLeft("\n");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataCenter("Başlangıçta Belirlenen Parametreler");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataLeft("\n");


            PdfNewDataLeft("--------------------------------------------------");
            PdfNewDataLeft("Malzemenin Adı: " + RefProduction.materialNameTextRP);
            PdfNewDataLeft("Numume Adedi: " + RefProduction.numberOfSamplesTextRP);
            PdfNewDataLeft("Numune Boyutları: " + RefProduction.sampleSizeTextRP);
            PdfNewDataLeft("Üretim Türü: " + Initialize.publicrefProductiontext);
            PdfNewDataLeft("Solüsyon Bilgisi: " + ProductionParameters.publicsolutionInfoText);
            PdfNewDataLeft("--------------------------------------------------");

            PdfNewDataLeft("Başlangıç Saati: " + DateTime.Now.ToShortTimeString());
            PdfNewDataLeft("Kullanılan Program: " + programNameLabelOP.Text);
            PdfNewDataLeft("Alt-taş Sıcaklığı: " + substrateHeaterLabelOP.Text);
            PdfNewDataLeft("Akış Miktarı: " + flowRateLabelOP.Text);
            PdfNewDataLeft("Geçiş Sayısı: " + passCountLabelOP.Text);
            PdfNewDataLeft("Nozzle Gaz: " + nozzleGasPressureLabelOP.Text);
            PdfNewDataLeft("Oksijen Seviyesi (SET): " + oxygenLevelSetLabelOP.Text);
            PdfNewDataLeft("Oksijen Seviyesi (Başlangıç): " + oxygenLevelStartLabelOP.Text);
            PdfNewDataLeft("Ortam Sıcaklığı (SET): " + ambienceTemperatureSetLabelOP.Text);
            PdfNewDataLeft("Ortam Sıcaklığı (Başlangıç) :" + ambienceTemperatureStartLabelOP.Text);
            PdfNewDataLeft("Nem Seviyesi (SET) :" + humidityLevelSetLabelOP.Text);
            PdfNewDataLeft("Nem Seviyesi (Başlangıç) :" + humidityLevelStartLabelOP.Text);
            PdfNewDataLeft("Nemlendirici Gerilimi: " + humidityVoltageLabelOP.Text);
            PdfNewDataLeft("Fan Hızı : " + fanRPMLabelOP.Text);
            PdfNewDataLeft("--------------------------------------------------");

            PdfNewDataLeft("\n");
            PdfNewDataLeft("\n");
            PdfNewDataLeft("\n");
            PdfNewDataLeft("\n");
            PdfNewDataLeft("\n");
            PdfNewDataLeft("\n");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataCenter("Üretim Sırasında Belirlenen Parametreler");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataLeft("\n");


            if (changesListBox.Items.Count > 0)
            {
                PdfNewDataLeft("--------------------------------------------------");
                foreach (string item in changesListBox.Items)
                {
                    PdfNewDataLeft(item);
                }
                PdfNewDataLeft("--------------------------------------------------");
            }



            PdfNewDataLeft("\n");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataCenter("Üretim Sırasında Anlık Parametreler");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataLeft("\n");


            if (instantDataListBox.Items.Count > 0)
            {
                PdfNewDataLeft("--------------------------------------------------");
                foreach (string item in instantDataListBox.Items)
                {
                    PdfNewDataLeft(item);
                    Console.WriteLine(item);
                }
                PdfNewDataLeft("--------------------------------------------------");
            }


            PdfNewDataLeft("\n");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataCenter("Temizlik");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataLeft("\n");

            if (!(CleaningProcess.cleaningProcessCP == ""))
            {
                PdfNewDataLeft("--------------------------------------------------");
                PdfNewDataLeft(CleaningProcess.cleaningProcessCP);
                PdfNewDataLeft("--------------------------------------------------");
            }


            PdfNewDataLeft("\n");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataCenter("İleri İşlemler");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataLeft("\n");


            if (!(PostProcessing.postProcessPOP == ""))
            {
                PdfNewDataLeft("--------------------------------------------------");
                PdfNewDataLeft(PostProcessing.postProcessPOP);
                PdfNewDataLeft("--------------------------------------------------");
            }


            PdfNewDataLeft("\n");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataCenter("Alınacak Olçümler");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataLeft("\n");


            if (Measurements.measumentsMP.Length > 0)
            {
                PdfNewDataLeft("--------------------------------------------------");
                foreach (var item in Measurements.measumentsMP)
                {
                    PdfNewDataLeft(item);
                }
                PdfNewDataLeft("--------------------------------------------------");
            }


            PdfNewDataLeft("\n");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataCenter("Notlar");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataLeft("\n");


            if (!(takeNotesText.Text == ""))
            {
                PdfNewDataLeft("--------------------------------------------------");
                PdfNewDataLeft(takeNotesText.Text);
                PdfNewDataLeft("--------------------------------------------------");
            }

            rapor.Close();



            MessageBox.Show("Dosya Oluşturuldu.\n" + "C:/OP2GUI/" + Initialize.name + DateTime.Now.ToString("yyyyMMddHHmmss") + "OP2GUI.pdf");

            System.Diagnostics.Process.Start("C:/OP2GUI/");
        }
Exemplo n.º 35
0
        //public void PDModel2Html(PDModel m)
        //{
        //    Export(m, ExportTyep.HTML);
        //}

        private void Export(IList<PDTable> tableList,string title, ExportTyep exportType)
        {
            Document doc = new Document(PageSize.A4.Rotate(), 20, 20, 20, 20);
            DocWriter w;

            switch (exportType)
            {
                case ExportTyep.PDF:
                    w = PdfWriter.GetInstance(doc, new FileStream(fileName, FileMode.Create, FileAccess.Write));
                    break;
                case ExportTyep.RTF:
                    w = RtfWriter2.GetInstance(doc, new FileStream(fileName, FileMode.Create, FileAccess.Write));
                    break;
                //case ExportTyep.HTML:
                //    w = HtmlWriter.GetInstance(doc, new FileStream(fileName, FileMode.Create, FileAccess.Write));
                //break;
                default:
                    break;
            }

            doc.Open();
            doc.NewPage();

            //IList<PDTable> tableList = m.AllTableList;

            //Chapter cpt = new Chapter(m.Name, 1);
            Chapter cpt = new Chapter(title, 1);
            Section sec;

            //doc.AddTitle(m.Name);
            doc.AddTitle(title);
            doc.AddAuthor("Kalman");
            doc.AddCreationDate();
            doc.AddCreator("Kalman");
            doc.AddSubject("PDM数据库文档");

            foreach (PDTable table in tableList)
            {
                sec = cpt.AddSection(new Paragraph(string.Format("{0}[{1}]", table.Name, table.Code), font));

                if (string.IsNullOrEmpty(table.Comment) == false)
                {
                    Chunk chunk = new Chunk(table.Comment, font);
                    sec.Add(chunk);
                }

                t = new Table(9, table.ColumnList.Count);

                //t.Border = 15;
                //t.BorderColor = Color.BLACK;
                //t.BorderWidth = 1.0f;
                t.AutoFillEmptyCells = true;
                t.CellsFitPage = true;
                t.TableFitsPage = true;
                t.Cellpadding = 3;
                //if (exportType == ExportTyep.PDF) t.Cellspacing = 2;
                t.DefaultVerticalAlignment = Element.ALIGN_MIDDLE;

                t.SetWidths(new int[] { 200, 200, 150, 50, 50, 50, 50, 50, 300 });

                t.AddCell(BuildHeaderCell("名称"));
                t.AddCell(BuildHeaderCell("代码"));
                t.AddCell(BuildHeaderCell("数据类型"));
                t.AddCell(BuildHeaderCell("长度"));
                t.AddCell(BuildHeaderCell("精度"));
                t.AddCell(BuildHeaderCell("主键"));
                t.AddCell(BuildHeaderCell("外键"));
                t.AddCell(BuildHeaderCell("可空"));
                t.AddCell(BuildHeaderCell("注释"));

                foreach (PDColumn column in table.ColumnList)
                {
                    t.AddCell(BuildCell(column.Name));
                    t.AddCell(BuildCell(column.Code));
                    t.AddCell(BuildCell(column.DataType));
                    t.AddCell(BuildCell(column.Length == 0 ? "" : column.Length.ToString()));
                    t.AddCell(BuildCell(column.Precision == 0 ? "" : column.Precision.ToString()));
                    t.AddCell(BuildCell(column.IsPK ? " √" : ""));
                    t.AddCell(BuildCell(column.IsFK ? " √" : ""));
                    t.AddCell(BuildCell(column.Mandatory ? "" : " √"));
                    t.AddCell(BuildCell(column.Comment));
                }

                sec.Add(t);
            }

            doc.Add(cpt);
            doc.Close();
        }
Exemplo n.º 36
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"));
        }
Exemplo n.º 37
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
            {
            }
        }
Exemplo n.º 38
0
        public void SendToPDF(string filename, clsFont jfont)
        {
            int countOfPages = _unicodeCharList.CharCodes.Count() / LINES_PER_PAGE; //fifty lines per page.

            //New document, 8.5"x11" in landscape orientation.
            iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.LETTER);

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

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

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

            writer.PageEvent = pdfevent;

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

            //Create our base font
            string   FontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");
            BaseFont baseFont = BaseFont.CreateFont(FontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

            iTextSharp.text.Font x = FontFactory.GetFont(jfont.SelectedFontName());

            for (int currentPage = 0; currentPage < countOfPages; currentPage++)
            {
                PdfPTable table = new PdfPTable(5);
                table.AddCell("Char");
                table.AddCell("Dec");
                table.AddCell("Hex");
                table.AddCell("Desc");
                table.AddCell("AltDesc");

                //convert image to a pdf image for inclusion in the doc
                for (int curChar = currentPage * LINES_PER_PAGE; curChar < (currentPage * LINES_PER_PAGE + LINES_PER_PAGE); curChar++)
                {
                    UnicodeCharList.CharEntry oneEntry = _unicodeCharList.CharCodes[curChar];
                    string charString = char.ConvertFromUtf32(Convert.ToInt32(oneEntry.CodeDec)).ToString();

                    Phrase codedChar = new Phrase(charString, x);
                    table.AddCell(codedChar);
                    table.AddCell(oneEntry.CodeDec);
                    table.AddCell(oneEntry.CodeHex);
                    table.AddCell(oneEntry.Desc);
                    table.AddCell(oneEntry.AltDesc);
                }

                doc.Add(table);

                doc.NewPage();
            }

            doc.Close();
        }
Exemplo n.º 39
0
        /// <summary>
        /// Construction du Rapport en PDF 
        /// </summary>
        /// <param name="data">Data.</param>
        public void BuildReport(DataSet data)
        {
            System.IO.FileStream fs = new FileStream ("Rapport.pdf", FileMode.Create);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                    }

                }

            }

            document.Close ();
            writer.Close ();
            fs.Close ();
        }
Exemplo n.º 40
0
    public void GeneratePDF(DataSet _ms)
    {
        String rpt_date = "";
        String Daily_notes = "";
        String Daily_comments = "";
        String Change_order_notes = "";

        DataTable dtPDFData = _ms.Tables[0];
        foreach (DataRow dRow in dtPDFData.Rows)
        {
            rpt_date            = dRow["rpt_date"] == DBNull.Value ? "" : dRow["rpt_date"].ToString();
            Daily_notes         = dRow["Daily_notes"] == DBNull.Value ? "" : dRow["Daily_notes"].ToString();
            Daily_comments      = dRow["Daily_comments"] == DBNull.Value ? "" : dRow["Daily_comments"].ToString();
            Change_order_notes  = dRow["Change_order_notes"] == DBNull.Value ? "" : dRow["Change_order_notes"].ToString();
        }

        MemoryStream m = new MemoryStream();
        //Document document = new Document();
        Document document = new Document(PageSize.A4.Rotate(), 50, 50, 50, 50);
        try
        {
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition","attachment;filename=DailyProjectReport.pdf");

            //PdfWriter.GetInstance(document, new FileStream("HarishTesting.pdf", FileMode.Create));
            PdfWriter writer = PdfWriter.GetInstance(document, m);
            writer.CloseStream = false;

            document.AddAuthor("Whitfield Corporation");
            document.AddSubject("Daily Production REPORT");
            Phrase  phrase4 = new  Phrase();
            phrase4.Add(BuildNewCellSpanRows("Whitfield Corporation Daily Production Report for ", rpt_date));
            HeaderFooter headerFooter2 = new HeaderFooter(phrase4, false);
            headerFooter2.Border = 0;
            HeaderFooter headerFooter1 = new HeaderFooter(new Phrase("Page: ", FontFactory.GetFont("Times-Roman", 8.0F, 0, new iTextSharp.text.Color(0, 0, 0))), true);
            headerFooter1.Border = 0;
            document.Footer = headerFooter1;
            document.Header = headerFooter2;
            document.Open();
            iTextSharp.text.Table table1 = new iTextSharp.text.Table(2);
            table1.Padding = 4.0F;
            table1.Spacing = 0.0F;
            float[] fArr2 = new float[] { 24.0F, 24.0F };
            float[] fArr1 = fArr2;
            table1.WidthPercentage = 100.0F;
            Cell cell = new Cell(new Phrase("General Information", FontFactory.GetFont(FontFactory.HELVETICA, 18, iTextSharp.text.Font.BOLD)));
            cell.HorizontalAlignment =  1;
            cell.VerticalAlignment = 1;
            cell.Leading = 8.0F;
            cell.Colspan = 2;
            cell.Border = 0;
            cell.BackgroundColor = new iTextSharp.text.Color(190, 190, 190);
            table1.AddCell(cell);
            table1.DefaultCellBorderWidth = 1.0F;
            table1.DefaultRowspan = 1;
            table1.DefaultHorizontalAlignment = 0;

            //table1.AddCell(BuildNewCell("Report Date:", rpt_date.Trim()));

            //cell = new Cell(BuildNewCell("Daily Notes:", Daily_notes));
            //cell.Colspan = 2;
            //table1.AddCell(cell);

            cell = new Cell(BuildNewCell("Daily Comments:", Daily_comments));
            cell.Colspan = 2;
            table1.AddCell(cell);

            //cell = new Cell(BuildNewCell("Change Order Notes:", Change_order_notes));
            //cell.Colspan = 2;
            //table1.AddCell(cell);

            //table1.AddCell("");
            document.Add(table1);

            document.Add(GenerateCoreReport(rpt_date));

        }
        catch (DocumentException)
        {
            throw;
        }
        document.Close();
        Response.Buffer = true;
        Response.Clear();
        //Write pdf byes to outputstream
        Response.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length);
        Response.OutputStream.Flush();
        Response.End();
    }
Exemplo n.º 41
0
        private void ExportToPDF(DataTable dt)
        {
            var attachment = "attachment; filename=" + _propertyName + " Budget " + _year + ".pdf";
            var pdfDoc = new Document(PageSize.A4.Rotate());
            var pdfStream = new MemoryStream();
            var pdfWriter = PdfWriter.GetInstance(pdfDoc, pdfStream);

            pdfDoc.Open();//Open Document to write
            pdfDoc.AddSubject(_year);
            pdfDoc.AddTitle(_propertyName);

            pdfDoc.AddCreationDate();
            pdfDoc.NewPage();

            var fontH = FontFactory.GetFont("ARIAL", 9, Font.BOLD);
            var fontT = FontFactory.GetFont("ARIAL", 12, Font.BOLD);
            var font8 = FontFactory.GetFont("ARIAL", 8);
            var font8B = FontFactory.GetFont("ARIAL", 8, Font.  BOLD);

            var preface = new Paragraph();
            var prefacedate = new Paragraph();

            // Lets write a big header
            preface.Add(new Paragraph("[" + _currency + "] " + _propertyName + " Budget " + _year, fontT));
            prefacedate.Add(new Paragraph("Print Date: [" + DateTime.Now + "] ", font8B));

            var pdfTable = new PdfPTable(dt.Columns.Count);
            pdfTable.HorizontalAlignment = 0;
            pdfTable.TotalWidth = 781f;
            pdfTable.LockedWidth = true;

            PdfPCell pdfPCell = null;

            //Add Header of the pdf table
            for (var column = 0; column < dt.Columns.Count; column++)
            {
                pdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Columns[column].Caption, fontH)));
                pdfTable.AddCell(pdfPCell);
            }

            //How add the data from datatable to pdf table
            for (var rows = 0; rows < dt.Rows.Count; rows++)
            {
                for (var column = 0; column < dt.Columns.Count; column++)
                {
                    if (rows == dt.Rows.Count - 1)
                    {
                        pdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8B)));

                    }
                    else
                    {
                        pdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8)));

                    }
                    if (column != 0) pdfPCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    pdfTable.AddCell(pdfPCell);
                }
            }

            var widths = new float[] { 55, 75f, 75f, 72f, 72f, 72f, 72f };
            pdfTable.SetWidths(widths);
            pdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table

            pdfDoc.SetMargins(5.0f, 5.0f, 40.0f, 0f);
            pdfDoc.Add(preface);
            pdfDoc.Add(pdfTable); // add pdf table to the document
            pdfDoc.Add(prefacedate);
            pdfDoc.Close();
            pdfWriter.Close();

            Response.ClearContent();
            Response.ClearHeaders();
            Response.ContentType = "application/pdf";
            Response.AppendHeader("Content-Disposition", attachment);
            Response.BinaryWrite(pdfStream.ToArray());
            Response.End();
        }
Exemplo n.º 42
0
        public void bill(string siparisNo, string Kullaniciid)
        {
            this.siparisNo   = siparisNo;
            this.Kullaniciid = Kullaniciid;

            iTextSharp.text.pdf.BaseFont STF_Helvetica_Turkish = iTextSharp.text.pdf.BaseFont.CreateFont("Helvetica", "CP1254", iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED);
            iTextSharp.text.Font         fontTitle             = new iTextSharp.text.Font(STF_Helvetica_Turkish, 11, iTextSharp.text.Font.NORMAL);

            SqlCommand cdname = new SqlCommand("select *from Tbl_Kullanici where KullaniciId=@p1", conn.connection());

            cdname.Parameters.AddWithValue("@p1", Kullaniciid);
            SqlDataReader drname = cdname.ExecuteReader();

            while (drname.Read())
            {
                name   = drname[1].ToString() + " " + drname[2].ToString();
                e_mail = drname[3].ToString();
            }

            conn.connection().Close();

            iTextSharp.text.Document pdf = new iTextSharp.text.Document();
            filePath = HttpContext.Current.Server.MapPath("~/Bills/" + siparisNo + "_Fatura.Pdf");
            PdfWriter.GetInstance(pdf, new FileStream(filePath, FileMode.Create));
            pdf.AddAuthor("BookSite");
            pdf.AddCreator("BookSite");
            pdf.AddCreationDate();
            pdf.AddSubject("Fatura");


            PdfPTable table = new PdfPTable(4);
            PdfPCell  cell  = new PdfPCell(new Phrase(name + "        FATURA - " + siparisNo, fontTitle));

            cell.Colspan             = 4;
            cell.HorizontalAlignment = 1;
            table.AddCell(cell);

            table.AddCell(new Phrase("Kitap Adı", fontTitle));
            table.AddCell(new Phrase("Miktar", fontTitle));
            table.AddCell(new Phrase("Birim Fiyat", fontTitle));
            table.AddCell(new Phrase("Toplam Fiyat", fontTitle));

            SqlCommand cd = new SqlCommand("select *from Tbl_Sepet where SiparisNo=@p1", conn.connection());

            cd.Parameters.AddWithValue("@p1", siparisNo);
            SqlDataReader dr = cd.ExecuteReader();

            while (dr.Read())
            {
                table.AddCell(new Phrase(dr[7].ToString(), fontTitle));
                table.AddCell(new Phrase(dr[2].ToString(), fontTitle));
                table.AddCell(new Phrase(dr[6].ToString(), fontTitle));
                table.AddCell(new Phrase(dr[3].ToString(), fontTitle));
            }
            conn.connection().Close();


            if (pdf.IsOpen() == false)
            {
                pdf.Open();
            }
            pdf.Add(table);
            pdf.Close();
        }
Exemplo n.º 43
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();
      }
    }  
Exemplo n.º 44
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;
        }