A generic Document class.
All kinds of Text-elements can be added to a HTMLDocument. The Document signals all the listeners when an element has been added.

  1. Once a document is created you can add some meta information.
  2. You can also set the headers/footers.
  3. You have to open the document before you can write content.
  4. You can only write content (no more meta-formation!) once a document is opened.
  5. When you change the header/footer on a certain page, this will be effective starting on the next page.
  6. Ater closing the document, every listener (as well as its OutputStream) is closed too.
Inheritance: IDocListener
        /// <summary>
        /// Fires when a page is finished, just before being written to the document.
        /// </summary>
        /// <param name="writer">PdfWriter</param>
        /// <param name="document">PDF Document</param>
        /// <param name="columnCellsSummaryData">List of all rows summaries data</param>
        public void PageFinished(PdfWriter writer, Document document, IList<SummaryCellData> columnCellsSummaryData)
        {
            var footerTable = AddPageFooter(new FooterData
            {
                PdfDoc = document,
                PdfWriter = writer,
                SummaryData = columnCellsSummaryData,
                CurrentPageNumber = writer.PageNumber,
                TotalPagesCountImage = _totalPageCountImage
            });

            var table = new PdfGrid(1)
            {
                RunDirection = (int)FooterProperties.RunDirection,
                WidthPercentage = FooterProperties.TableWidthPercentage
            };
            var tableCell = new PdfPCell(footerTable) { Border = 0 };
            table.AddCell(tableCell);

            var page = document.PageSize;
            table.SetTotalWidth(new[] { page.Width - document.LeftMargin - document.RightMargin });
            table.WriteSelectedRows(
                    rowStart: 0,
                    rowEnd: -1,
                    xPos: document.LeftMargin,
                    yPos: document.BottomMargin - FooterProperties.SpacingBeforeTable,
                    canvas: writer.DirectContent);
        }
Exemplo n.º 2
0
// ---------------------------------------------------------------------------    
    /**
     * Creates a PDF document.
     */
    public byte[] CreatePdf() {
      using (MemoryStream ms = new MemoryStream()) { 
        using (var c =  AdoDB.Provider.CreateConnection()) {
          c.ConnectionString = AdoDB.CS;
          c.Open();
          // step 1
          using (Document document = new Document(PageSize.A5)) {
            // step 2
            PdfWriter writer = PdfWriter.GetInstance(document, ms);
            // step 3
            document.Open();
            // step 4
            int[] start = new int[3];
            for (int i = 0; i < 3; i++) {
              start[i] = writer.PageNumber;
              AddParagraphs(document, c, SQL[i], FIELD[i]);
              document.NewPage();
            }
            PdfPageLabels labels = new PdfPageLabels();
            labels.AddPageLabel(start[0], PdfPageLabels.UPPERCASE_LETTERS);
            labels.AddPageLabel(start[1], PdfPageLabels.DECIMAL_ARABIC_NUMERALS);
            labels.AddPageLabel(
              start[2], PdfPageLabels.DECIMAL_ARABIC_NUMERALS, 
              "Movies-", start[2] - start[1] + 1
            );
            writer.PageLabels = labels;
          }
          return ms.ToArray();
        }
      }
    }
Exemplo n.º 3
0
        public void Go()
        {
            var outputFile = Helpers.IO.GetClassOutputPath(this);
            var fixedHtml = FixBrokenServerControlMarkup(HTML);
            using (FileStream stream = new FileStream(
                outputFile,
                FileMode.Create,
                FileAccess.Write))
            {
                using (var document = new Document())
                {
                    PdfWriter writer = PdfWriter.GetInstance(
                        document, stream
                    );
                    document.Open();
                    using (var xmlSnippet = new StringReader(fixedHtml))
                    {
                        XMLWorkerHelper.GetInstance().ParseXHtml(
                            writer, document, xmlSnippet
                        );
                    }

                }
            }
        }
Exemplo n.º 4
0
 virtual public void RunBugSamples() {
     bool success = true;
     foreach (String str in list) {
         try {
             Console.WriteLine(str);
             Document doc = new Document();
             PdfWriter writer = null;
             try {
                 writer = PdfWriter.GetInstance(doc, new FileStream(TARGET + "/bugs/" + str
                                                                    + ".pdf", FileMode.Create));
             }
             catch (DocumentException e) {
                 Console.WriteLine(e);
             }
             doc.Open();
             XMLWorkerHelper helper = XMLWorkerHelper.GetInstance();
             helper.ParseXHtml(writer, doc, File.OpenText(RESOURCES + "/bugs/" + str));
             doc.Close();
         }
         catch (Exception e) {
             Console.WriteLine(e);
             Console.WriteLine(e);
             success = false;
         }
     }
     if (!success) {
         Assert.Fail();
     }
 }
Exemplo n.º 5
0
 protected void btnPDF_Click(object sender, ImageClickEventArgs e)
 {
     Response.ContentType = "application/pdf";
     Response.AddHeader("content-disposition", "attachment;filename=UserDetails.pdf");
     Response.Cache.SetCacheability(HttpCacheability.NoCache);
     var sw = new StringWriter();
     var hw = new HtmlTextWriter(sw);
     gvdetails.AllowPaging = false;
     gvdetails.DataBind();
     gvdetails.RenderControl(hw);
     gvdetails.HeaderRow.Style.Add("width", "15%");
     gvdetails.HeaderRow.Style.Add("font-size", "10px");
     gvdetails.Style.Add("text-decoration", "none");
     gvdetails.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
     gvdetails.Style.Add("font-size", "8px");
     var sr = new StringReader(sw.ToString());
     var pdfDoc = new Document(PageSize.A2, 7f, 7f, 7f, 0f);
     var htmlparser = new HTMLWorker(pdfDoc);
     PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
     pdfDoc.Open();
     htmlparser.Parse(sr);
     pdfDoc.Close();
     Response.Write(pdfDoc);
     Response.End();
 }
        private void ExportToPDF()
        {
            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter hw = new HtmlTextWriter(sw))
                {
                    //To Export all pages
                    this.gvExportToPdf.AllowPaging = false;
                    //this.BindGridView();

                    this.gvExportToPdf.RenderControl(hw);
                    StringReader sr = new StringReader(sw.ToString());
                    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
                    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

                    Response.ContentType = "application/pdf";
                    Response.AddHeader("content-disposition", "attachment;filename=DashboardReport.pdf");
                    Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                    pdfDoc.Open();
                    htmlparser.Parse(sr);
                    pdfDoc.Close();
                    Response.Write(pdfDoc);
                    Response.End();
                }
            }
        }
Exemplo n.º 7
0
 public static void GeneratePdfSingleDataType(string filePath, string title, string content)
 {
     try
     {
         Logger.LogI("GeneratePDF -> " + filePath);
         var doc = new Document(PageSize.A3, 36, 72, 72, 144);
         using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
         {
             PdfWriter.GetInstance(doc, fs);
             doc.Open();
             doc.AddTitle(title);
             doc.AddAuthor(Environment.MachineName);
             doc.Add(
                 new Paragraph("Title : " + title + Environment.NewLine + "ServerName : " +
                               Environment.MachineName +
                               Environment.NewLine + "Author : " + Environment.UserName));
             doc.NewPage();
             doc.Add(new Paragraph(content));
             doc.Close();
         }
     }
     catch (Exception ex)
     {
         Logger.LogE(ex.Source + " -> " + ex.Message + "\n" + ex.StackTrace);
     }
 }
Exemplo n.º 8
0
 public override void OnOpenDocument(PdfWriter writer, Document document)
 {
     printTime = DateTime.Now;
     baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
     pdfContent = writer.DirectContent;
     pageNumberTemplate = pdfContent.CreateTemplate(50, 50);
 }
Exemplo n.º 9
0
// ---------------------------------------------------------------------------        
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) { 
        byte[] pdf = new Superimposing().CreatePdf();
        // Create a reader
        PdfReader reader = new PdfReader(pdf);
        using (MemoryStream ms = new MemoryStream()) {     
          // step 1
          using (Document document = new Document(PageSize.POSTCARD)) {
            // step 2
            PdfWriter writer = PdfWriter.GetInstance(document, ms);
            // step 3
            document.Open();
            // step 4
            PdfContentByte canvas = writer.DirectContent;
            PdfImportedPage page;
            for (int i = 1; i <= reader.NumberOfPages; i++) {
              page = writer.GetImportedPage(reader, i);
              canvas.AddTemplate(page, 1f, 0, 0, 1, 0, 0);
            }
          } 
          zip.AddEntry(RESULT, ms.ToArray());
        }
        zip.AddEntry(SOURCE, pdf);
        zip.Save(stream);            
      }        
    }
Exemplo n.º 10
0
// ---------------------------------------------------------------------------
    public void Write(Stream stream) {
      // use one of the previous examples to create a PDF
      MovieTemplates mt = new MovieTemplates();
      // Create a reader
      byte[] pdf = Utility.PdfBytes(mt);
      PdfReader reader = new PdfReader(pdf);
      // loop over all the pages in the original PDF
      int n = reader.NumberOfPages;      
      using (ZipFile zip = new ZipFile()) {
        for (int i = 0; i < n; ) {
          string dest = string.Format(RESULT, ++i);
          using (MemoryStream ms = new MemoryStream()) {
// We'll create as many new PDFs as there are pages
            // step 1
            using (Document document = new Document()) {
              // step 2
              using (PdfCopy copy = new PdfCopy(document, ms)) {
                // step 3
                document.Open();
                // step 4
                copy.AddPage(copy.GetImportedPage(reader, i));
              }
            }
            zip.AddEntry(dest, ms.ToArray());
          }
        }
        zip.AddEntry(Utility.ResultFileName(mt.ToString() + ".pdf"), pdf);
        zip.Save(stream);       
      }
    }
Exemplo n.º 11
0
 /**
  * Creates an instance of the concatenation class.
  * @param os    the Stream for the PDF document
  * @param smart do we want PdfCopy to detect redundant content?
  */
 public PdfConcatenate(Stream os, bool smart) {
     document = new Document();
     if (smart)
         copy = new PdfSmartCopy(document, os);
     else
         copy = new PdfCopy(document, os);   
 }
Exemplo n.º 12
0
 /**
 * Constructor
 * @param document
 * @param os outputstream
 */
 public PdfCopy(Document document, Stream os)
     : base(new PdfDocument(), os)
 {
     document.AddDocListener(pdf);
     pdf.AddWriter(this);
     indirectMap = new Dictionary<PdfReader,Dictionary<RefKey,IndirectReferences>>();
 }
Exemplo n.º 13
0
        public static bool generate(User user, string path)
        {
            document = new Document(PageSize.A4, 50, 50, 25, 25);

            var output = new MemoryStream();
            var writer = PdfWriter.GetInstance(document, new FileStream(path + "/BS-" + DateTime.Now.Month + "-" + DateTime.Now.Year + "-" + user.Firstname + "-" + user.Lastname + ".pdf", FileMode.Create));

            document.Open();

            // création du logo
            Image logo = iTextSharp.text.Image.GetInstance("logo.png");
            logo.ScaleAbsoluteWidth(200);
            logo.ScaleAbsoluteHeight(50);
            PdfPCell cellLogo = new PdfPCell(logo);
            cellLogo.Border = Rectangle.NO_BORDER;
            cellLogo.PaddingBottom = 8;

            // création du titre
            var title = new Paragraph("BULLETIN DE SALAIRE", titleFont);
            title.Alignment = Element.ALIGN_RIGHT;
            PdfPCell cellTitle = new PdfPCell(title);
            cellTitle.Border = Rectangle.NO_BORDER;
            cellTitle.HorizontalAlignment = 2; //0=Left, 1=Centre, 2=Right

            // création du tableau
            PdfPTable tableTitle = new PdfPTable(2);
            tableTitle.DefaultCell.Border = Rectangle.NO_BORDER;
            tableTitle.WidthPercentage = 100;

            PdfPCell cellAdresseSuperp = new PdfPCell(new Paragraph("89, quais des Chartrons \n33000 BORDEAUX", subTitleFont));
            cellAdresseSuperp.HorizontalAlignment = 0;
            cellAdresseSuperp.Border = Rectangle.NO_BORDER;

            PdfPCell cellDUMec = new PdfPCell(new Paragraph(user.Lastname + " " + user.Firstname + "\n" + user.Address, subTitleFont));
            cellDUMec.HorizontalAlignment = 2;
            cellDUMec.Border = Rectangle.NO_BORDER;

            // ajout de la cell du logo
            tableTitle.AddCell(cellLogo);

            // ajout de la cell du titre
            tableTitle.AddCell(cellTitle);

            tableTitle.AddCell(cellAdresseSuperp);
            tableTitle.AddCell(cellDUMec);

            // Ajout du titre principal
            tableTitle.AddCell(getTitle());

            //******************************************************************************/
            //***********************   ABSENCES   *****************************************/
            //******************************************************************************/

            generateAbsences(tableTitle, user);

            generateTableSalary(user);

            document.Close();
            return true;
        }
Exemplo n.º 14
0
        /// <summary>
        /// Save a pdf file in  "../../test.pdf".
        /// </summary>
        /// <param name="deals">Expect Collection of objects that have Name, Address, ProductName and formula.</param>
        public void GenerateReport(IEnumerable<PdfReportModel> deals)
        {
            FileStream fileStream = new FileStream(ReportsPath, FileMode.Create, FileAccess.Write, FileShare.None);
            Rectangle pageSize = new Rectangle(PageSize.A4);
            Document reportDocument = new Document(pageSize);
            PdfWriter pdfWriter = PdfWriter.GetInstance(reportDocument, fileStream);
            var boldFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 17);

            reportDocument.Open();

            PdfPTable reportTable = new PdfPTable(6);
            reportTable.HorizontalAlignment = Element.ALIGN_LEFT;
            PdfPCell headerCell = new PdfPCell(new Phrase("Produced products information", boldFont));
            headerCell.Colspan = 6;
            headerCell.HorizontalAlignment = 0;
            reportTable.AddCell(headerCell);

            this.PutHeadCells(reportTable);

            foreach (var deal in deals)
            {
                reportTable.AddCell(deal.ProductName);
                reportTable.AddCell(deal.Quantity);
                reportTable.AddCell(deal.PricePerUnit);
                reportTable.AddCell(deal.Formula);
                reportTable.AddCell(deal.Address);
                reportTable.AddCell(deal.Total);
            }

            reportDocument.Add(reportTable);
            reportDocument.Close();
        }
 // ===========================================================================
 public void Write(Stream stream)
 {
     // step 1
     using (Document document = new Document())
     {
         // step 2
         PdfWriter.GetInstance(document, stream);
         document.SetPageSize(PageSize.A5);
         document.SetMargins(36, 72, 108, 180);
         document.SetMarginMirroring(true);
         // step 3
         document.Open();
         // step 4
         document.Add(new Paragraph(
           "The left margin of this odd page is 36pt (0.5 inch); " +
           "the right margin 72pt (1 inch); " +
           "the top margin 108pt (1.5 inch); " +
           "the bottom margin 180pt (2.5 inch).")
         );
         Paragraph paragraph = new Paragraph();
         paragraph.Alignment = Element.ALIGN_JUSTIFIED;
         for (int i = 0; i < 20; i++)
         {
             paragraph.Add("Hello World! Hello People! " +
             "Hello Sky! Hello Sun! Hello Moon! Hello Stars!"
             );
         }
         document.Add(paragraph);
         document.Add(new Paragraph(
           "The right margin of this even page is 36pt (0.5 inch); " +
           "the left margin 72pt (1 inch).")
         );
     }
 }
Exemplo n.º 16
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.º 17
0
 private void InitializeDocument()
 {
     MemoryStream baos = new MemoryStream();
     document = new Document();
     writer = PdfWriter.GetInstance(document, baos);
     document.Open();
 }
Exemplo n.º 18
0
 /**
  * Initialize one of the headers, based on the chapter title;
  * reset the page number.
  * @see com.itextpdf.text.pdf.PdfPageEventHelper#onChapter(
  *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document, float,
  *      com.itextpdf.text.Paragraph)
  */
 public override void OnChapter(
   PdfWriter writer, Document document,
   float paragraphPosition, Paragraph title)
 {
     header[1] = new Phrase(title.Content);
     pagenumber = 1;
 }
Exemplo n.º 19
0
 /**
  * Adds the header and the footer.
  * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(
  *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
  */
 public override void OnEndPage(PdfWriter writer, Document document)
 {
     Rectangle rect = writer.GetBoxSize("art");
     switch (writer.PageNumber % 2)
     {
         case 0:
             ColumnText.ShowTextAligned(writer.DirectContent,
               Element.ALIGN_RIGHT,
               header[0],
               rect.Right, rect.Top, 0
             );
             break;
         case 1:
             ColumnText.ShowTextAligned(
               writer.DirectContent,
               Element.ALIGN_LEFT,
               header[1],
               rect.Left, rect.Top, 0
             );
             break;
     }
     ColumnText.ShowTextAligned(
       writer.DirectContent,
       Element.ALIGN_CENTER,
       new Phrase(String.Format("page {0}", pagenumber)),
       (rect.Left + rect.Right) / 2,
       rect.Bottom - 18, 0
     );
 }
Exemplo n.º 20
0
 public static void Export(DetailsView dvGetStudent)
 {
     int rows = dvGetStudent.Rows.Count;
     int columns = dvGetStudent.Rows[0].Cells.Count;
     int pdfTableRows = rows;
     iTextSharp.text.Table PdfTable = new iTextSharp.text.Table(2, pdfTableRows);
     PdfTable.BorderWidth = 1;
     PdfTable.Cellpadding = 0;
     PdfTable.Cellspacing = 0;
     for (int rowCounter = 0; rowCounter < rows; rowCounter++)
     {
         for (int columnCounter = 0; columnCounter < columns; columnCounter++)
         {
             string strValue = dvGetStudent.Rows[rowCounter].Cells[columnCounter].Text;
             PdfTable.AddCell(strValue);
         }
     }
     Document Doc = new Document();
     PdfWriter.GetInstance(Doc, HttpContext.Current.Response.OutputStream);
     Doc.Open();
     Doc.Add(PdfTable);
     Doc.Close();
     HttpContext.Current.Response.ContentType = "application/pdf";
     HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=StudentDetails.pdf");
     HttpContext.Current.Response.End();
 }
Exemplo n.º 21
0
		public void Print(Document document)
		{
			var table = PDFHelper.CreateTable(document, ReportData.DataTables[0].Columns.Count);
			table.HeaderRows = 3;
			table.SetWidths(new float[] { 3f, 3f, 4f, 2f });
			var cell = PDFHelper.GetCell("Параметры устройств" + Environment.NewLine + "на " + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss"), PDFStyle.HeaderFont, Element.ALIGN_CENTER, PDFStyle.HeaderBackground);
			cell.Colspan = 4;
			table.AddCell(cell);
			cell = PDFHelper.GetCell("Устройство", PDFStyle.TextFont, Element.ALIGN_CENTER, PDFStyle.HeaderBackground);
			cell.VerticalAlignment = Element.ALIGN_MIDDLE;
			cell.Colspan = 2;
			table.AddCell(cell);
			cell = PDFHelper.GetCell("Зона", PDFStyle.TextFont, Element.ALIGN_CENTER, PDFStyle.HeaderBackground);
			cell.VerticalAlignment = Element.ALIGN_MIDDLE;
			cell.Rowspan = 2;
			table.AddCell(cell);
			cell = PDFHelper.GetCell("Запыленность", PDFStyle.TextFont, Element.ALIGN_CENTER, PDFStyle.HeaderBackground);
			cell.VerticalAlignment = Element.ALIGN_MIDDLE;
			cell.Rowspan = 2;
			table.AddCell(cell);
			cell = PDFHelper.GetCell("Тип", PDFStyle.TextFont, Element.ALIGN_CENTER, PDFStyle.HeaderBackground);
			cell.VerticalAlignment = Element.ALIGN_MIDDLE;
			table.AddCell(cell);
			cell = PDFHelper.GetCell("Адрес", PDFStyle.TextFont, Element.ALIGN_CENTER, PDFStyle.HeaderBackground);
			cell.VerticalAlignment = Element.ALIGN_MIDDLE;
			table.AddCell(cell);
			PDFHelper.PrintTable(table, ReportData.DataTables[0]);
			document.Add(table);
		}
        protected override void MakePdf(string outPdf) {
            Document doc = new Document(PageSize.A4.Rotate());
            PdfWriter pdfWriter = PdfWriter.GetInstance(doc, new FileStream(outPdf, FileMode.Create));
            doc.SetMargins(45, 45, 0, 100);
            doc.Open();


            CssFilesImpl cssFiles = new CssFilesImpl();
            cssFiles.Add(
                XMLWorkerHelper.GetCSS(
                    File.OpenRead(RESOURCES + Path.DirectorySeparatorChar + testPath + Path.DirectorySeparatorChar + testName +
                                  Path.DirectorySeparatorChar + "complexDiv_files" + Path.DirectorySeparatorChar +
                                  "main.css")));
            cssFiles.Add(
                XMLWorkerHelper.GetCSS(
                    File.OpenRead(RESOURCES + Path.DirectorySeparatorChar + testPath + Path.DirectorySeparatorChar + testName +
                                  Path.DirectorySeparatorChar + "complexDiv_files" + Path.DirectorySeparatorChar +
                                  "widget082.css")));
            StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles);
            HtmlPipelineContext hpc =
                new HtmlPipelineContext(
                    new CssAppliersImpl(new XMLWorkerFontProvider(RESOURCES + @"\tool\xml\examples\fonts")));
            hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(Tags.GetHtmlTagProcessorFactory());
            hpc.SetImageProvider(new SampleTestImageProvider());
            hpc.SetPageSize(doc.PageSize);
            HtmlPipeline htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, pdfWriter));
            IPipeline pipeline = new CssResolverPipeline(cssResolver, htmlPipeline);
            XMLWorker worker = new XMLWorker(pipeline, true);
            XMLParser p = new XMLParser(true, worker, Encoding.GetEncoding("UTF-8"));
            p.Parse(File.OpenRead(inputHtml), Encoding.GetEncoding("UTF-8"));
            doc.Close();
        }
Exemplo n.º 23
0
        public int Convert(string from, string to)
        {
            _logger.DebugFormat("Text转换为Pdf, {0},到:{1}", from, to);

            try
            {
                var content = File.ReadAllText(@from, Encoding.Default);

                Document document = new Document();
                BaseFont bf = BaseFont.CreateFont("c:\\windows\\fonts\\SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

                Font font = new Font(bf);

                PdfWriter.GetInstance(document, new FileStream(@to, FileMode.Create));
                document.Open();

                document.Add(new Paragraph(content, font));
                document.Close();

                return ErrorMessages.Success;
            }
            catch(Exception ex)
            {
                throw new ConverterException(ErrorMessages.TextToPdfFailed, ex);
            }
        }
Exemplo n.º 24
0
        public void VerticalPositionTest0() {
            String file = "vertical_position.pdf";

            Document document = new Document();
            PdfWriter writer = PdfWriter.GetInstance(document, File.Create(OUTPUT_FOLDER + file));
            document.Open();

            writer.PageEvent = new CustomPageEvent();

            PdfPTable table = new PdfPTable(2);
            for (int i = 0; i < 100; i++) {
                table.AddCell("Hello " + i);
                table.AddCell("World " + i);
            }

            document.Add(table);

            document.NewPage();

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 1000; i++) {
                sb.Append("some more text ");
            }
            document.Add(new Paragraph(sb.ToString()));

            document.Close();

            // compare
            CompareTool compareTool = new CompareTool();
            String errorMessage = compareTool.CompareByContent(OUTPUT_FOLDER + file, TEST_RESOURCES_PATH + file,
                OUTPUT_FOLDER, "diff");
            if (errorMessage != null) {
                Assert.Fail(errorMessage);
            }
        }
        protected void generatePDFButton_Click(object sender, EventArgs e)
        {
            PdfPTable pdfPTable = new PdfPTable(CreatedStudentInformationGridView.HeaderRow.Cells.Count);

            foreach (TableCell headerCell in CreatedStudentInformationGridView.HeaderRow.Cells)
            {
                PdfPCell pfdPCell = new PdfPCell(new Phrase(headerCell.Text));
                //pfdPCell.BackgroundColor = new BaseColor(newCenterGridView.HeaderStyle.ForeColor);
                pdfPTable.AddCell(pfdPCell);
            }

            foreach (GridViewRow gridViewRow in CreatedStudentInformationGridView.Rows)
            {
                foreach (TableCell tableCell in gridViewRow.Cells)
                {

                    PdfPCell pfdPCell = new PdfPCell(new Phrase(tableCell.Text));
                    //pfdPCell.BackgroundColor = new BaseColor(newCenterGridView.HeaderStyle.ForeColor);
                    pdfPTable.AddCell(pfdPCell);
                }
            }
            Document pdfDocument = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
            PdfWriter.GetInstance(pdfDocument, Response.OutputStream);

            pdfDocument.Open();
            pdfDocument.Add(pdfPTable);
            pdfDocument.Close();

            Response.ContentType = "application/pdf";
            Response.AppendHeader("content-disposition", "attachment;filename=NewCenter.pdf");
            Response.Write(pdfDocument);
            Response.Flush();
            Response.End();
        }
        public void Go()
        {
            var outputFile = Helpers.IO.GetClassOutputPath(this);
            var parsedHtml = RemoveImage(HTML);
            Console.WriteLine(parsedHtml);

            using (var xmlSnippet = new StringReader(parsedHtml))
            {
                using (FileStream stream = new FileStream(
                    outputFile,
                    FileMode.Create,
                    FileAccess.Write))
                {
                    using (var document = new Document())
                    {
                        PdfWriter writer = PdfWriter.GetInstance(
                          document, stream
                        );
                        document.Open();
                        XMLWorkerHelper.GetInstance().ParseXHtml(
                          writer, document, xmlSnippet
                        );
                    }
                }
            }
        }
        // to generate the report call the GeneratePDFReport static method.
        // The pdf file will be generated in the SupermarketChain.ConsoleClient folder
        // TODO measures are missing
        // TODO code refactoring to limitr repeated chunks
        public static void GeneratePDFReport()
        {
            Document doc = new Document(iTextSharp.text.PageSize.A4, 10, 10, 40, 35);
            string filePath = @"..\..\..\..\Reports\salesReports.pdf";
            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Create));
            doc.Open();
            PdfPTable table = new PdfPTable(5);

            Font verdana = FontFactory.GetFont("Verdana", 16, Font.BOLD);
            Font verdana2 = FontFactory.GetFont("Verdana", 12, Font.BOLD);

            PdfPCell header = new PdfPCell(new Phrase("Aggregated Sales Report", verdana));
            header.Colspan = 5;
            header.HorizontalAlignment = 1;
            table.AddCell(header);

            double totalSales = PourReportData(table);

            PdfPCell totalSum = new PdfPCell(new Phrase("Grand total:"));
            totalSum.Colspan = 4;
            totalSum.HorizontalAlignment = 2;
            totalSum.BackgroundColor = new BaseColor(161, 212, 224);
            table.AddCell(totalSum);

            PdfPCell totalSumNumber = new PdfPCell(new Phrase(String.Format("{0:0.00}", totalSales), verdana));
            totalSumNumber.BackgroundColor = new BaseColor(161, 212, 224);
            table.AddCell(totalSumNumber);

            doc.Add(table);
            doc.Close();

            DirectoryInfo directoryInfo = new DirectoryInfo(filePath);
            Console.WriteLine("Pdf report generated.");
            Console.WriteLine("File:  {0}", directoryInfo.FullName);
        }
Exemplo n.º 28
0
 // ---------------------------------------------------------------------------
 public void Write(Stream stream)
 {
     // Use old example to create PDF
     MovieTemplates mt = new MovieTemplates();
     byte[] pdf = Utility.PdfBytes(mt);
     using (ZipFile zip = new ZipFile())
     {
         using (MemoryStream ms = new MemoryStream())
         {
             // step 1
             using (Document document = new Document())
             {
                 // step 2
                 PdfWriter writer = PdfWriter.GetInstance(document, ms);
                 // step 3
                 document.Open();
                 // step 4
                 PdfPTable table = new PdfPTable(2);
                 PdfReader reader = new PdfReader(pdf);
                 int n = reader.NumberOfPages;
                 PdfImportedPage page;
                 for (int i = 1; i <= n; i++)
                 {
                     page = writer.GetImportedPage(reader, i);
                     table.AddCell(Image.GetInstance(page));
                 }
                 document.Add(table);
             }
             zip.AddEntry(RESULT, ms.ToArray());
         }
         zip.AddEntry(Utility.ResultFileName(mt.ToString() + ".pdf"), pdf);
         zip.Save(stream);
     }
 }
Exemplo n.º 29
0
    public void ExportToPdf(DataTable table, string filename, HttpResponse Response)
    {
        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter hw = new HtmlTextWriter(sw))
            {
                //To Export all pages

                GridView gridView = new GridView();
                gridView.DataSource = table;
                gridView.DataBind();
                gridView.AllowPaging = false;

                gridView.RenderControl(hw);
                StringReader             sr     = new StringReader(sw.ToString());
                iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A2, 10f, 10f, 10f, 0f);
                HTMLWorker htmlparser           = new HTMLWorker(pdfDoc);
                PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                pdfDoc.Open();
                htmlparser.Parse(sr);
                pdfDoc.Close();

                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment;filename=Report.pdf");
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.Write(pdfDoc);
                Response.End();
            }
        }
    }
Exemplo n.º 30
0
    private void LoadClinicRegistrationToBrowser(string htmlText)
    {
        //create a PDF document in MemoryStream
        System.IO.MemoryStream        m        = new System.IO.MemoryStream();
        iTextSharp.text.Document      document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER);
        iTextSharp.text.pdf.PdfWriter writer   = iTextSharp.text.pdf.PdfWriter.GetInstance(document, m);

        document.Open();

        //make an arraylist ....with STRINGREADER since its not reading file...
        List <iTextSharp.text.IElement> htmlarraylist = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StringReader(htmlText), null);

        //add the collection to the document
        for (int k = 0; k < htmlarraylist.Count; k++)
        {
            document.Add((iTextSharp.text.IElement)htmlarraylist[k]);
        }
        document.Close();

        //Stream PDF document back to browser
        Response.ContentType = "Application/pdf";
        Response.BinaryWrite(m.GetBuffer());
        Response.Flush();
        Response.SuppressContent = true;
        Response.End();
    }
        public void ASPXToPDF(HtmlTable objhtml1,  HtmlTable objhtml2)
        {
            string fileName = "AsignacionFolios.pdf";
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.Clear();

            StringWriter sw1 = new StringWriter();
            HtmlTextWriter hw1 = new HtmlTextWriter(sw1);
            objhtml1.RenderControl(hw1);

            StringWriter sw2 = new StringWriter();
            HtmlTextWriter hw2 = new HtmlTextWriter(sw2);
            objhtml2.RenderControl(hw2);

            StringReader sr1 = new StringReader(sw1.ToString());
            StringReader sr2 = new StringReader(sw2.ToString());

            Document pdfDoc = new Document(PageSize.A2, 5f, 5f, 5f, 5f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter.GetInstance(pdfDoc, HttpContext.Current.Response.OutputStream);
            pdfDoc.Open();
            htmlparser.Parse(sr1);
            pdfDoc.NewPage();

            htmlparser.Parse(sr2);
            pdfDoc.Close();

            HttpContext.Current.Response.ContentType = "application/pdf";
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
            HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            HttpContext.Current.Response.Write(pdfDoc);
            HttpContext.Current.Response.End();
        }
Exemplo n.º 32
0
        static void Main(string[] args)
        {
            // Path
            var path = "C:\\Workspace\\Personal\\Lourtec-2018-i\\MCSDAppBuilder2018I\\Clase-5\\holaMundo.txt";

            /* Tip sobre los strings de forma nativa/implicita
             * "" al crear string con comillas dobles necesitan caracteres de escape para algunos caracteres especiales para eso se utiliza un backslash \, un doble backslash para incluir uno en el text \\
             * @"" copia strings literales, todos sin caracteres de escape, incluye saltos de linea
             * $"" permite generar concatenacion con anclas dinamicas con {}
             */
            var parentDirectory = Path.GetDirectoryName(path);

            Console.WriteLine(parentDirectory);

            var extension = Path.GetExtension(path);

            Console.WriteLine(extension);

            var root = Path.GetPathRoot(path);

            Console.WriteLine(root);

            var randomName = Path.GetRandomFileName();

            Console.WriteLine(randomName);
            // Directory

            var randomDirectoryName = $"{Path.GetDirectoryName(path)}\\{Path.GetRandomFileName()}";

            if (!Directory.Exists(randomDirectoryName))
            {
                Directory.CreateDirectory(randomDirectoryName);

                Console.WriteLine(Directory.GetParent(randomDirectoryName));
                Directory.SetCreationTime(randomDirectoryName, new DateTime(1999, 12, 15));
                Console.WriteLine(Directory.GetCreationTime(randomDirectoryName));
            }

            // DirectoryInfo
            Console.Write("------------Directory Info------------------");
            DirectoryInfo d = new DirectoryInfo(randomDirectoryName);

            Console.WriteLine($"{d.FullName} {d.CreationTime} {d.Attributes.ToString()}");

            // File
            randomName = randomDirectoryName + "\\" + randomName + ".txt";
            if (!File.Exists(randomName))
            {
                using (var fileStream = File.CreateText(randomName))
                {
                    fileStream.WriteLine("Hola Mundo");
                    fileStream.Flush();
                }

                Console.WriteLine(File.ReadAllText(randomName));
            }
            // FileInfo
            FileInfo f = new FileInfo(randomName);

            Console.WriteLine($"{f.FullName} {f.CreationTime} {f.Attributes}");


            // Creacion de Fantasmas
            List <Fantasma> fantasmas   = new List <Fantasma>();
            var             phantonPath = $"{Path.GetDirectoryName(path)}\\Fantasmas";

            if (!Directory.Exists(phantonPath))
            {
                Directory.CreateDirectory(phantonPath);
            }

            if (Directory.Exists(phantonPath))
            {
                Console.WriteLine("----Binary---");
                SerializacionBinaria(phantonPath, fantasmas);

                Console.WriteLine("----XML---");
                SerializacionXml(phantonPath, fantasmas);


                Console.WriteLine("----JSON---");
                SerializacionJson(phantonPath, fantasmas);
            }

            // PDF ITextSharp
            string pdfPath      = @"C:\Workspace\Personal\Lourtec-2018-i\MCSDAppBuilder2018I\Clase-5\phdThesis.pdf";
            string pdfPathClone = @"C:\Workspace\Personal\Lourtec-2018-i\MCSDAppBuilder2018I\Clase-5\Clone.pdf";


            iTextSharp.text.Document document = null;
            try
            {
                document = new iTextSharp.text.Document();
                PdfWriter write  = PdfWriter.GetInstance(document, new FileStream(pdfPathClone, FileMode.Create));
                Anchor    anchor = new Anchor("Hola Mundo");
                iTextSharp.text.Paragraph paragraph = new iTextSharp.text.Paragraph();
                paragraph.Add(anchor);
                document.Open();
                document.OpenDocument();

                document.Add(new Chunk("Hola Mundo Chunk"));
                document.Add(paragraph);
                if (document.IsOpen())
                {
                    document.NewPage();
                }
                document.Close();
                write.Close();
            }
            catch (Exception ex)
            {
            }
        }
Exemplo n.º 33
0
        /// <summary>
        /// ExportToThermalPrinter
        /// </summary>
        public void ExportToPDFforThermalPrinter()
        {
            iTextSharp.text.Document pdfdoc = new iTextSharp.text.Document();
            try
            {
                DirectoryInfo dir1 = new DirectoryInfo(Application.StartupPath + "\\Barcode");
                if (!Directory.Exists(Application.StartupPath + "\\Barcode"))
                {
                    dir1.Create();
                }
                if (File.Exists(Application.StartupPath + "\\Barcode\\Barcode.pdf"))
                {
                    File.Delete(Application.StartupPath + "\\Barcode\\Barcode.pdf");
                }
                iTextSharp.text.Rectangle pgSize = new iTextSharp.text.Rectangle(227, 65);
                pdfdoc = new Document(pgSize, 6, 6, 0, 0);
                PdfWriter writer         = PdfWriter.GetInstance(pdfdoc, new FileStream(Application.StartupPath + "\\Barcode\\Barcode.pdf", FileMode.Create));
                PdfPTable tbl            = new PdfPTable(2);
                float[]   fltParentWidth = new float[] { 108f, 108f };
                tbl.TotalWidth  = 216;
                tbl.LockedWidth = true;
                tbl.SetWidths(fltParentWidth);
                tbl.DefaultCell.FixedHeight         = 57;
                tbl.DefaultCell.Border              = iTextSharp.text.Rectangle.NO_BORDER;
                tbl.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                tbl.DefaultCell.VerticalAlignment   = Element.ALIGN_MIDDLE;
                pdfdoc.Open();
                int intotalCount         = 0;
                BarcodeSettingsInfo Info = new BarcodeSettingsInfo();
                SettingsSP          Sp   = new SettingsSP();
                Info = spBarcodeSettings.BarcodeSettingsViewForBarCodePrinting();
                for (int i = 0; i < dgvBarcodePrinting.Rows.Count; i++)
                {
                    if (dgvBarcodePrinting.Rows[i].Cells["dgvProductCode"].Value != null && dgvBarcodePrinting.Rows[i].Cells["dgvProductCode"].Value.ToString() != string.Empty)
                    {
                        int inCopies = 0;
                        if (dgvBarcodePrinting.Rows[i].Cells["dgvCopies"].Value != null)
                        {
                            int.TryParse(dgvBarcodePrinting.Rows[i].Cells["dgvCopies"].Value.ToString(), out inCopies);
                        }
                        for (int j = 0; j < inCopies; j++)
                        {
                            string strCode        = dgvBarcodePrinting.Rows[i].Cells["dgvProductCode"].Value.ToString();
                            string strCompanyName = string.Empty;
                            if (Info.ShowCompanyName)
                            {
                                strCompanyName = Info.CompanyName;
                            }
                            string strProductCode = string.Empty;
                            if (Info.ShowProductCode)
                            {
                                strProductCode = strCode;
                            }
                            else
                            {
                                strProductCode = dgvBarcodePrinting.Rows[i].Cells["dgvproductName"].Value.ToString();
                            }

                            string strMRP = string.Empty;
                            if (Info.ShowMRP)
                            {
                                strMRP = new CurrencySP().CurrencyView(PublicVariables._decCurrencyId).CurrencySymbol + ": " + dgvBarcodePrinting.Rows[i].Cells["dgvMRP"].Value.ToString();
                            }

                            string strSecretPurchaseRateCode = string.Empty;
                            if (Info.ShowPurchaseRate)
                            {
                                string strPurchaseRate = dgvBarcodePrinting.Rows[i].Cells["dgvPurchaseRate"].Value.ToString();

                                if (strPurchaseRate.Contains("."))
                                {
                                    strPurchaseRate = strPurchaseRate.TrimEnd('0');
                                    if (strPurchaseRate[strPurchaseRate.Length - 1] == '.')
                                    {
                                        strPurchaseRate = strPurchaseRate.Replace(".", "");
                                    }
                                }
                                for (int k = 0; k < strPurchaseRate.Length; k++)
                                {
                                    switch (strPurchaseRate[k])
                                    {
                                    case '0':
                                        strSecretPurchaseRateCode += Info.Zero;
                                        break;

                                    case '1':
                                        strSecretPurchaseRateCode += Info.One;
                                        break;

                                    case '2':
                                        strSecretPurchaseRateCode += Info.Two;
                                        break;

                                    case '3':
                                        strSecretPurchaseRateCode += Info.Three;
                                        break;

                                    case '4':
                                        strSecretPurchaseRateCode += Info.Four;
                                        break;

                                    case '5':
                                        strSecretPurchaseRateCode += Info.Five;
                                        break;

                                    case '6':
                                        strSecretPurchaseRateCode += Info.Six;
                                        break;

                                    case '7':
                                        strSecretPurchaseRateCode += Info.Seven;
                                        break;

                                    case '8':
                                        strSecretPurchaseRateCode += Info.Eight;
                                        break;

                                    case '9':
                                        strSecretPurchaseRateCode += Info.Nine;
                                        break;

                                    case '.':
                                        strSecretPurchaseRateCode += Info.Point;
                                        break;
                                    }
                                }
                            }

                            PdfContentByte pdfcb   = writer.DirectContent;
                            Barcode128     code128 = new Barcode128();
                            code128.Code          = strCode;
                            code128.Extended      = false;
                            code128.CodeType      = iTextSharp.text.pdf.Barcode.CODE128;
                            code128.AltText       = strProductCode;
                            code128.BarHeight     = 16;
                            code128.Size          = 9;
                            code128.Baseline      = 9;
                            code128.TextAlignment = Element.ALIGN_CENTER;
                            iTextSharp.text.Image image128 = code128.CreateImageWithBarcode(pdfcb, null, null);
                            Phrase phrase = new Phrase();

                            BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);

                            phrase.Add(new Chunk(strCompanyName, new iTextSharp.text.Font(bfTimes, 9, iTextSharp.text.Font.BOLD)));
                            phrase.Add(new Chunk(Environment.NewLine + Environment.NewLine, new iTextSharp.text.Font(bfTimes, 4)));
                            PdfPCell cell = new PdfPCell(phrase);
                            cell.HorizontalAlignment = Element.ALIGN_CENTER;
                            cell.VerticalAlignment   = Element.ALIGN_MIDDLE;
                            cell.Border = iTextSharp.text.Rectangle.NO_BORDER;
                            phrase.Add(new Chunk(image128, 0, 0));
                            phrase.Add(new Chunk(Environment.NewLine, new iTextSharp.text.Font(bfTimes, 4)));
                            phrase.Add(new Chunk(strMRP, new iTextSharp.text.Font(bfTimes, 8)));
                            phrase.Add(new Chunk(Environment.NewLine + strSecretPurchaseRateCode, new iTextSharp.text.Font(bfTimes, 7)));
                            phrase.Add(new Chunk(Environment.NewLine + Environment.NewLine, new iTextSharp.text.Font(bfTimes, 1.2f)));
                            tbl.AddCell(cell);
                            intotalCount++;
                        }
                    }
                }
                int reminder = intotalCount % 2;
                if (reminder != 0)
                {
                    for (int i = reminder; i < 2; ++i)
                    {
                        tbl.AddCell("");
                    }
                }
                if (tbl.Rows.Count != 0)
                {
                    pdfdoc.Add(tbl);
                    pdfdoc.Close();
                    System.Diagnostics.Process.Start(Application.StartupPath + "\\Barcode\\Barcode.pdf");
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("The process cannot access the file") && ex.Message.Contains("Barcode.pdf' because it is being used by another process."))
                {
                    MessageBox.Show("Close the PDF file and try again", "Openmiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    formMDI.infoError.ErrorString = "BCP5:" + ex.Message;
                }
            }
            finally
            {
                try
                {
                    pdfdoc.Close();
                }
                catch
                {
                }
            }
        }
Exemplo n.º 34
0
 private void _utility_OnSave(text.Document document, text.pdf.PdfWriter writer, string saveDir)
 {
     writer.PageEvent = new DefaultPageEvent(this);
 }
Exemplo n.º 35
0
    public static ActionResult PDF(
        int companyId,
        string from,
        string to,
        bool statusIdnetified,
        bool statusAnalyzed,
        bool statusInProgress,
        bool statusClose,
        int origin,
        int departmentId,
        int providerId,
        int customerId,
        string listOrder,
        string filterText)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

        dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var    company = new Company(companyId);
        string path    = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(company.Name);
        var fileName            = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_IncidentList"],
            formatedDescription,
            DateTime.Now);

        // FONTS
        var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts);
        }

        var headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        var arial      = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50);
        var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc,
                                                               new FileStream(
                                                                   string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName),
                                                                   FileMode.Create));

        writer.PageEvent = new TwoColumnHeaderFooter()
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = user.UserName,
            CompanyId   = company.Id,
            CompanyName = company.Name,
            Title       = dictionary["Item_IncidentList"].ToUpperInvariant()
        };

        pdfDoc.Open();

        var backgroundColor = new iTS.BaseColor(225, 225, 225);
        var rowPair         = new iTS.BaseColor(255, 255, 255);
        var rowEven         = new iTS.BaseColor(240, 240, 240);

        // ------------ FONTS
        var awesomeFont     = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\fontawesome-webfont.ttf", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        var headerFontFinal = new iTS.Font(headerFont, 9, iTS.Font.NORMAL, iTS.BaseColor.BLACK);

        criteriaFont = new iTS.Font(arial, 10, iTS.Font.NORMAL, iTS.BaseColor.BLACK);
        var titleFont  = new iTS.Font(arial, 18, iTS.Font.BOLD, iTS.BaseColor.BLACK);
        var symbolFont = new iTS.Font(awesomeFont, 8, iTS.Font.NORMAL, iTS.BaseColor.BLACK);

        var fontAwesomeIcon = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\fontawesome-webfont.ttf", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        fontAwe = new Font(fontAwesomeIcon, 10);
        // -------------------

        var titleTable = new iTSpdf.PdfPTable(1);

        titleTable.SetWidths(new float[] { 50f });
        titleTable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_EquipmentList"], company.Name), titleFont))
        {
            HorizontalAlignment = iTS.Element.ALIGN_CENTER,
            Border = iTS.Rectangle.NO_BORDER
        });

        var borderNone = iTS.Rectangle.NO_BORDER;

        #region Criteria
        var criteriatable = new iTSpdf.PdfPTable(2)
        {
            WidthPercentage = 100
        };

        criteriatable.SetWidths(new float[] { 8f, 50f });

        #region texts

        var criteriaOrigin = dictionary["Item_Incident_Origin0"];
        if (origin == 1)
        {
            if (departmentId > 0)
            {
                var department = Department.ById(departmentId, companyId);
                criteriaOrigin = string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_Incident_Origin1"], department.Description);
            }
            else
            {
                criteriaOrigin = string.Format(CultureInfo.InvariantCulture, "{0} - ({1})", dictionary["Item_Incident_Origin1"], dictionary["Common_All_Male_Plural"]);
            }
        }
        if (origin == 2)
        {
            if (providerId > 0)
            {
                var provider = Provider.ById(providerId, companyId);
                criteriaOrigin = string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_Incident_Origin2"], provider.Description);
            }
            else
            {
                criteriaOrigin = string.Format(CultureInfo.InvariantCulture, "{0} - ({1})", dictionary["Item_Incident_Origin2"], dictionary["Common_All_Male_Plural"]);
            }
        }
        if (origin == 3)
        {
            if (customerId > 0)
            {
                var customer = Customer.ById(customerId, companyId);
                criteriaOrigin = string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_Incident_Origin3"], customer.Description);
            }
            else
            {
                criteriaOrigin = string.Format(CultureInfo.InvariantCulture, "{0} - ({1})", dictionary["Item_Incident_Origin3"], dictionary["Common_All_Male_Plural"]);
            }
        }

        var periode = string.Empty;
        if (!string.IsNullOrEmpty(from) && string.IsNullOrEmpty(to))
        {
            periode = dictionary["Item_Incident_List_Filter_From"] + " " + from;
        }
        else if (string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to))
        {
            periode = dictionary["Item_Incident_List_Filter_To"] + " " + to;
        }
        else if (!string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to))
        {
            periode = from + " " + to;
        }
        else
        {
            periode = dictionary["Common_All_Male"];
        }

        var typetext  = string.Empty;
        var firstType = false;

        var statusText  = string.Empty;
        var firstStatus = true;
        if (statusIdnetified)
        {
            firstStatus = false;
            statusText += dictionary["Item_IndicentAction_Status1"];
        }
        if (statusAnalyzed)
        {
            if (!firstStatus)
            {
                statusText += " - ";
            }

            statusText += dictionary["Item_IndicentAction_Status2"];
            firstStatus = false;
        }
        if (statusInProgress)
        {
            if (!firstStatus)
            {
                statusText += " - ";
            }

            statusText += dictionary["Item_IndicentAction_Status3"];
            firstType   = false;
        }
        if (statusClose)
        {
            if (!firstType)
            {
                statusText += " - ";
            }

            statusText += dictionary["Item_IndicentAction_Status4"];
            firstType   = false;
        }
        #endregion

        ToolsPdf.AddCriteria(criteriatable, dictionary["Common_Period"], periode);
        if (!string.IsNullOrEmpty(filterText))
        //{
        //    ToolsPdf.AddCriteria(criteriatable, string.Empty, string.Empty);
        //}
        //else
        {
            ToolsPdf.AddCriteria(criteriatable, dictionary["Common_PDF_Filter_Contains"], filterText);
        }

        ToolsPdf.AddCriteria(criteriatable, dictionary["Item_IncidentAction_Header_Status"], statusText);
        ToolsPdf.AddCriteria(criteriatable, dictionary["Item_IncidentAction_Header_Origin"], criteriaOrigin);
        pdfDoc.Add(criteriatable);
        #endregion

        var table = new iTSpdf.PdfPTable(8)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 20f,
            SpacingAfter        = 30f
        };

        table.SetWidths(new float[] { 5f, 35f, 10f, 10f, 20f, 8f, 10f, 10f });

        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Label_Number"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_Description"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_Open"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_Status"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_Origin"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_ActionNumber"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_Cost"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Header_Close"]));

        int     cont      = 0;
        decimal totalCost = 0;
        var     data      = HttpContext.Current.Session["IncidentFilterData"] as List <IncidentFilterItem>;
        bool    pair      = false;

        foreach (IncidentFilterItem item in data)
        {
            var originValue = string.Empty;
            if (!string.IsNullOrEmpty(item.Customer.Description))
            {
                originValue = item.Customer.Description;
            }
            if (!string.IsNullOrEmpty(item.Provider.Description))
            {
                originValue = item.Provider.Description;
            }
            if (!string.IsNullOrEmpty(item.Department.Description))
            {
                originValue = item.Department.Description;
            }

            item.OriginText = originValue;
        }

        switch (listOrder.ToUpperInvariant())
        {
        default:
        case "TH0|ASC":
            data = data.OrderBy(d => d.Description).ToList();
            break;

        case "TH0|DESC":
            data = data.OrderByDescending(d => d.Description).ToList();
            break;

        case "TH1|ASC":
            data = data.OrderBy(d => d.Open).ToList();
            break;

        case "TH1|DESC":
            data = data.OrderByDescending(d => d.Open).ToList();
            break;

        case "TH3|ASC":
            data = data.OrderBy(d => d.OriginText).ToList();
            break;

        case "TH3|DESC":
            data = data.OrderByDescending(d => d.OriginText).ToList();
            break;

        case "TH4|ASC":
            data = data.OrderBy(d => d.Action.Description).ToList();
            break;

        case "TH4|DESC":
            data = data.OrderByDescending(d => d.Action.Description).ToList();
            break;

        case "TH5|ASC":
            data = data.OrderBy(d => d.Amount).ToList();
            break;

        case "TH5|DESC":
            data = data.OrderByDescending(d => d.Amount).ToList();
            break;

        case "TH6|ASC":
            data = data.OrderBy(d => d.Close).ToList();
            break;

        case "TH6|DESC":
            data = data.OrderByDescending(d => d.Close).ToList();
            break;
        }

        foreach (var incidentFilter in data)
        {
            if (!string.IsNullOrEmpty(filterText))
            {
                var match = incidentFilter.Description;
                match += "|" + incidentFilter.Code;
                match += "|" + incidentFilter.Customer.Description;
                match += "|" + incidentFilter.Provider.Description;
                match += "|" + incidentFilter.Department.Description;


                if (match.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) == -1)
                {
                    continue;
                }
            }

            cont++;
            totalCost += incidentFilter.Amount;
            var incident = Incident.GetById(incidentFilter.Id, companyId);
            var action   = IncidentAction.ByIncidentId(incident.Id, companyId);

            var lineBackground = pair ? rowEven : rowPair;
            // pair = !pair;

            var statustext = string.Empty;
            switch (incidentFilter.Status)
            {
            case 1: statustext = dictionary["Item_IndicentAction_Status1"]; break;

            case 2: statustext = dictionary["Item_IndicentAction_Status2"]; break;

            case 3: statustext = dictionary["Item_IndicentAction_Status3"]; break;

            case 4: statustext = dictionary["Item_IndicentAction_Status4"]; break;

            default: statusText = string.Empty; break;
            }

            var actionDescription = string.Empty;
            if (!string.IsNullOrEmpty(action.Description))
            {
                actionDescription = dictionary["Common_Yes"];
            }

            var originText = string.Empty;
            switch (incidentFilter.Origin)
            {
            case 1: originText = dictionary["Item_IncidentAction_Origin1"]; break;

            case 2: originText = dictionary["Item_IncidentAction_Origin2"]; break;

            case 3: originText = dictionary["Item_IncidentAction_Origin3"]; break;

            case 4: originText = dictionary["Item_IncidentAction_Origin4"]; break;

            default: originText = string.Empty; break;
            }

            table.AddCell(ToolsPdf.DataCellCenter(incidentFilter.Code, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCell(incidentFilter.Description, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCellCenter(incidentFilter.Open, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCellCenter(statustext, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCell(incidentFilter.OriginText, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCellCenter(actionDescription, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCellMoney(incidentFilter.Amount, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCellCenter(incidentFilter.Close, ToolsPdf.LayoutFonts.Times));
        }

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(
                                                             CultureInfo.InvariantCulture,
                                                             @"{0}: {1}",
                                                             dictionary["Common_RegisterCount"],
                                                             cont), ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = rowEven,
            Padding         = 6f,
            PaddingTop      = 4f,
            Colspan         = 4
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant(), ToolsPdf.LayoutFonts.Times))
        {
            Border              = iTS.Rectangle.TOP_BORDER,
            BackgroundColor     = rowEven,
            Padding             = 6f,
            PaddingTop          = 4f,
            HorizontalAlignment = 2
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(Tools.PdfMoneyFormat(totalCost), ToolsPdf.LayoutFonts.Times))
        {
            Border              = iTS.Rectangle.TOP_BORDER,
            BackgroundColor     = rowEven,
            Padding             = 6f,
            PaddingTop          = 4f,
            HorizontalAlignment = 2
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = rowEven,
            Colspan         = 2
        });

        pdfDoc.Add(table);
        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
Exemplo n.º 36
0
        public bool CreateReport()
        {
            bool isSuccessful = false;

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

                //set up tables, etc...
                PdfPTable headerTableNoBorders   = new PdfPTable(11);
                PdfPTable headerTableWithBorders = new PdfPTable(11);
                PdfPTable detailsTable           = new PdfPTable(11);
                PdfPTable footerTableWithBorders = new PdfPTable(11);
                PdfPTable footerTableNoBorders   = new PdfPTable(11);
                PdfPCell  cell = new PdfPCell();
                Image     gif  = Image.GetInstance(Resources.logo, BaseColor.WHITE);
                _reportFont           = FontFactory.GetFont("Arial", 6, iTextSharp.text.Font.NORMAL);
                _reportFontLargeBold  = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.BOLD);
                _reportFontUnderlined = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.UNDERLINE);

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

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

                ReportHeaderNoBorder(headerTableNoBorders);
                ReportHeaderWithBorder(headerTableWithBorders);
                ReportDetails(detailsTable);
                ReportFooterNoBorders(footerTableNoBorders);
                ReportFooterWithBorders(footerTableWithBorders);

                //headerTableNoBorders.HeaderRows = 15;

                document.Open();
                document.Add(headerTableNoBorders);
                document.Add(headerTableWithBorders);
                document.Add(detailsTable);
                document.Add(footerTableWithBorders);
                document.Add(footerTableNoBorders);
                document.Close();

                isSuccessful = true;
            }
            catch (DocumentException /*de*/)
            {
                //reportObject.ReportError = de.Message; ;
                //reportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            catch (IOException /*ioe*/)
            {
                //reportObject.ReportError = ioe.Message; ;
                //reportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            return(isSuccessful);
        }
Exemplo n.º 37
0
 public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
 {
     base.OnEndPage(writer, document);
 }
Exemplo n.º 38
0
        //Exportaciones

        #region Crea_Pdf

        public ActionResult GetPdf()
        {
            try
            {
                using (var Deptos = new EmpleadosEntities())
                {
                    var ListDep = Deptos.Departamento.ToList();

                    MemoryStream ms = new MemoryStream();

                    iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 50, 50, 50, 50);
                    PdfWriter pdf = PdfWriter.GetInstance(document, ms);

                    //hace la insercion del pie de pagina
                    pdf.PageEvent = new HeadFooter();

                    document.Open();

                    //insercion de imagenes
                    string url = Server.MapPath("/Imagenes/bg.jpg");
                    iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(url);
                    image.ScaleToFit(140f, 120f);
                    image.Alignment = Element.ALIGN_LEFT;
                    document.Add(image);
                    // fin de insercion de imagenes

                    //tamaño y color de cabecera
                    BaseFont             bf        = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.EMBEDDED);
                    iTextSharp.text.Font fontText2 = new iTextSharp.text.Font(bf, 16, 4, BaseColor.BLUE);

                    //creacion e insercion de titulos al documento
                    iTextSharp.text.Paragraph titulo = new iTextSharp.text.Paragraph(string.Format("Listado de Departamentos"), fontText2);

                    titulo.Alignment = 1; //0-Left, 1 middle,2 Right
                                          //inserta al documento
                    document.Add(titulo);
                    //inserta nueva linea al texto
                    document.Add(Chunk.NEWLINE);

                    //esto es para estilo de letra de la tabla
                    BaseFont bf2 = BaseFont.CreateFont(BaseFont.TIMES_BOLD, BaseFont.CP1250, BaseFont.EMBEDDED);
                    //tamaño y color
                    iTextSharp.text.Font fontText  = new iTextSharp.text.Font(bf2, 10, 0, BaseColor.BLACK);
                    iTextSharp.text.Font fontText3 = new iTextSharp.text.Font(bf2, 10, 0, BaseColor.WHITE);

                    // instancia la tabla y le indica la cantidad de columnas
                    PdfPTable table = new PdfPTable(2);
                    //indica q ancho de la hoja va a ocupar la tabla
                    table.WidthPercentage = 95;

                    // instancia para la generacion de celdas en la tabla
                    PdfPCell _cell = new PdfPCell();

                    //genera la cabecera de la tabla
                    _cell = new PdfPCell(new iTextSharp.text.Paragraph("Código Departamento", fontText3));
                    _cell.BackgroundColor     = iTextSharp.text.BaseColor.DARK_GRAY;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    table.AddCell(_cell);

                    _cell = new PdfPCell(new iTextSharp.text.Paragraph("Nombre Departamento", fontText3));
                    _cell.BackgroundColor     = iTextSharp.text.BaseColor.DARK_GRAY;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    table.AddCell(_cell);

                    //llena la tabla y ademas le da la alineacion a los datos
                    foreach (var item in ListDep)
                    {
                        PdfPCell _cell2 = new PdfPCell();

                        _cell2 = new PdfPCell(new iTextSharp.text.Paragraph(item.Id_Depto.ToString(), fontText));
                        _cell2.HorizontalAlignment = Element.ALIGN_RIGHT;
                        table.AddCell(_cell2);

                        _cell2 = new PdfPCell(new iTextSharp.text.Paragraph(item.NomDepto, fontText));
                        _cell2.HorizontalAlignment = Element.ALIGN_CENTER;
                        table.AddCell(_cell2);
                    }

                    //agrega la tabla al documento
                    document.Add(table);

                    //cierra el documento
                    document.Close();

                    //vacia la memoria(documento) hacia memory stream
                    byte[] byteStream = ms.ToArray();
                    ms = new MemoryStream();
                    ms.Write(byteStream, 0, byteStream.Length);
                    ms.Position = 0;

                    //esto permite que el archivo pdf se muestre por pantalla en el explorador y a su vez sea guardado en el disco
                    return(File(ms, "application/pdf", "ListaDeptos.pdf"));
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Error On:", ex);
                Response.StatusCode        = 500;
                Response.StatusDescription = ex.Message;
                return(Json(Response));
            }
        }
Exemplo n.º 39
0
        /// <summary>
        /// Export the Barcodes to PDF format here
        /// </summary>
        public void ExportToPDF()
        {
            iTextSharp.text.Document pdfdoc = new iTextSharp.text.Document();
            try
            {
                DirectoryInfo dir1 = new DirectoryInfo(Application.StartupPath + "\\Barcode");
                if (!Directory.Exists(Application.StartupPath + "\\Barcode"))
                {
                    dir1.Create();
                }
                if (File.Exists(Application.StartupPath + "\\Barcode\\Barcode.pdf"))
                {
                    File.Delete(Application.StartupPath + "\\Barcode\\Barcode.pdf");
                }
                pdfdoc = new Document(PageSize.A4, 12, 1, 20, 20);
                PdfWriter writer = PdfWriter.GetInstance(pdfdoc, new FileStream(Application.StartupPath + "\\Barcode\\Barcode.pdf", FileMode.Create));
                PdfPTable tbl    = new PdfPTable(5); // assigning 5 columns to pdf
                tbl.WidthPercentage    = 100;
                tbl.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
                tbl.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                tbl.DefaultCell.VerticalAlignment   = Element.ALIGN_MIDDLE;
                pdfdoc.Open();
                int intotalCount         = 0;
                BarcodeSettingsInfo Info = new BarcodeSettingsInfo();
                Info = spBarcodeSettings.BarcodeSettingsViewForBarCodePrinting();
                for (int i = 0; i < dgvBarcodePrinting.Rows.Count; i++) // iterating grid to take each product
                {
                    if (dgvBarcodePrinting.Rows[i].Cells["dgvProductCode"].Value != null && dgvBarcodePrinting.Rows[i].Cells["dgvProductCode"].Value.ToString() != "")
                    {
                        int inCopies = 0;
                        if (dgvBarcodePrinting.Rows[i].Cells["dgvCopies"].Value != null)
                        {
                            int.TryParse(dgvBarcodePrinting.Rows[i].Cells["dgvCopies"].Value.ToString(), out inCopies); // number of copies of arcode to be printed
                        }
                        for (int j = 0; j < inCopies; j++)
                        {
                            string strCode = dgvBarcodePrinting.Rows[i].Cells["dgvBarcode"].Value.ToString();
                            // checking settings----------------------------------------------------------------------------------------------------------

                            string strCompanyName = " ";
                            if (Info.ShowCompanyName)
                            {
                                strCompanyName = Info.CompanyName;
                            }
                            //-----------------------------------
                            string strProductCode = " ";
                            if (Info.ShowProductCode)
                            {
                                strProductCode = strCode;
                            }
                            else
                            {
                                strProductCode = dgvBarcodePrinting.Rows[i].Cells["dgvproductName"].Value.ToString();
                            }
                            //-----------------------------------
                            string strMRP = " ";
                            if (Info.ShowMRP)
                            {
                                strMRP = new CurrencySP().CurrencyView(PublicVariables._decCurrencyId).CurrencySymbol + ": " + dgvBarcodePrinting.Rows[i].Cells["dgvMRP"].Value.ToString();
                            }
                            //-----------------------------------
                            string strSecretPurchaseRateCode = " ";
                            if (Info.ShowPurchaseRate)
                            {
                                string strPurchaseRate = dgvBarcodePrinting.Rows[i].Cells["dgvPurchaseRate"].Value.ToString();
                                //converting to secret code
                                if (strPurchaseRate.Contains("."))
                                {
                                    strPurchaseRate = strPurchaseRate.TrimEnd('0');
                                    if (strPurchaseRate[strPurchaseRate.Length - 1] == '.')
                                    {
                                        strPurchaseRate = strPurchaseRate.Replace(".", "");
                                    }
                                }
                                for (int k = 0; k < strPurchaseRate.Length; k++)
                                {
                                    switch (strPurchaseRate[k])
                                    {
                                    case '0':
                                        strSecretPurchaseRateCode += Info.Zero;
                                        break;

                                    case '1':
                                        strSecretPurchaseRateCode += Info.One;
                                        break;

                                    case '2':
                                        strSecretPurchaseRateCode += Info.Two;
                                        break;

                                    case '3':
                                        strSecretPurchaseRateCode += Info.Three;
                                        break;

                                    case '4':
                                        strSecretPurchaseRateCode += Info.Four;
                                        break;

                                    case '5':
                                        strSecretPurchaseRateCode += Info.Five;
                                        break;

                                    case '6':
                                        strSecretPurchaseRateCode += Info.Six;
                                        break;

                                    case '7':
                                        strSecretPurchaseRateCode += Info.Seven;
                                        break;

                                    case '8':
                                        strSecretPurchaseRateCode += Info.Eight;
                                        break;

                                    case '9':
                                        strSecretPurchaseRateCode += Info.Nine;
                                        break;

                                    case '.':
                                        strSecretPurchaseRateCode += Info.Point;
                                        break;
                                    }
                                }
                            }

                            // generating and assigning barcode to PDF

                            PdfContentByte pdfcb   = writer.DirectContent;
                            Barcode128     code128 = new Barcode128();
                            code128.Code          = strCode;
                            code128.Extended      = false;
                            code128.CodeType      = iTextSharp.text.pdf.Barcode.CODE128;
                            code128.AltText       = strProductCode;
                            code128.BarHeight     = 13;
                            code128.Size          = 6;
                            code128.Baseline      = 8;
                            code128.TextAlignment = Element.ALIGN_CENTER;
                            iTextSharp.text.Image image128 = code128.CreateImageWithBarcode(pdfcb, null, null);


                            Phrase phrase = new Phrase();
                            phrase.Font.Size = 8;
                            phrase.Add(new Chunk(strCompanyName + Environment.NewLine + Environment.NewLine));
                            PdfPCell cell = new PdfPCell(phrase);
                            cell.FixedHeight         = 61.69f;
                            cell.HorizontalAlignment = Element.ALIGN_CENTER;
                            cell.VerticalAlignment   = Element.ALIGN_MIDDLE;
                            cell.Border = iTextSharp.text.Rectangle.NO_BORDER;
                            phrase.Add(new Chunk(image128, 0, 0));
                            phrase.Add(new Chunk(Environment.NewLine + strMRP));
                            phrase.Add(new Chunk(Environment.NewLine + strSecretPurchaseRateCode));
                            tbl.AddCell(cell);
                            intotalCount++; // getting total number of barcode generated
                        }
                    }
                }
                // so we assign a null values to reaming columns
                int reminder = intotalCount % 5;
                if (reminder != 0)
                {
                    for (int i = reminder; i < 5; ++i)
                    {
                        tbl.AddCell("");
                    }
                }
                if (tbl.Rows.Count != 0)
                {
                    pdfdoc.Add(tbl);
                    pdfdoc.Close();
                    System.Diagnostics.Process.Start(Application.StartupPath + "\\Barcode\\Barcode.pdf");
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("The process cannot access the file") && ex.Message.Contains("Barcode.pdf' because it is being used by another process."))
                {
                    MessageBox.Show("Close the PDF file and try again", "Openmiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("BCD4:" + ex.Message, "Openmiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            finally
            {
                try
                {
                    pdfdoc.Close();
                }
                catch
                {
                }
            }
        }
    public static ActionResult PDF(
        int companyId,
        string from,
        string to,
        bool statusIdentified,
        bool statusAnalyzed,
        bool statusInProgress,
        bool statusClose,
        bool typeImprovement,
        bool typeFix,
        bool typePrevent,
        int origin,
        int reporter,
        string listOrder)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

        dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var    company = new Company(companyId);
        string path    = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(company.Name);

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_IncidentActionList"],
            formatedDescription,
            DateTime.Now);

        var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50);
        var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc,
                                                               new FileStream(
                                                                   string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName),
                                                                   FileMode.Create));

        writer.PageEvent = new TwoColumnHeaderFooter()
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = user.UserName,
            CompanyId   = company.Id,
            CompanyName = company.Name,
            Title       = dictionary["Item_IncidentActions"].ToUpperInvariant()
        };

        pdfDoc.Open();

        var backgroundColor = new iTS.BaseColor(225, 225, 225);
        var rowPair         = new iTS.BaseColor(255, 255, 255);
        var rowEven         = new iTS.BaseColor(240, 240, 240);

        var titleTable = new iTSpdf.PdfPTable(1);

        titleTable.SetWidths(new float[] { 50f });
        var titleCell = new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont))
        {
            HorizontalAlignment = iTS.Element.ALIGN_CENTER,
            Border = ToolsPdf.BorderNone
        };

        titleTable.AddCell(titleCell);

        #region Criteria
        var criteriatable = new iTSpdf.PdfPTable(4);
        criteriatable.SetWidths(new float[] { 20f, 50f, 15f, 100f });
        criteriatable.WidthPercentage = 100;

        #region texts

        string criteriaOrigin = dictionary["Common_All_Male"];
        if (origin == 1)
        {
            criteriaOrigin = dictionary["Item_IncidentAction_Origin1"];
        }
        if (origin == 2)
        {
            criteriaOrigin = dictionary["Item_IncidentAction_Origin2"];
        }
        if (origin == 3)
        {
            criteriaOrigin = dictionary["Item_IncidentAction_Origin3"];
        }
        if (origin == 4)
        {
            criteriaOrigin = dictionary["Item_IncidentAction_Origin46"];
        }
        if (origin == 5)
        {
            criteriaOrigin = dictionary["Item_IncidentAction_Origin5"];
        }

        string reporterText = dictionary["Common_All_Male"];
        if (reporter == 1)
        {
            reporterText = dictionary["Item_IncidentAction_ReporterType1"];
        }
        if (reporter == 2)
        {
            reporterText = dictionary["Item_IncidentAction_ReporterType2"];
        }
        if (reporter == 3)
        {
            reporterText = dictionary["Item_IncidentAction_ReporterType3"];
        }


        string periode = string.Empty;
        if (!string.IsNullOrEmpty(from) && string.IsNullOrEmpty(to))
        {
            periode = dictionary["Item_IncidentAction_List_Filter_From"] + " " + from;
        }
        else if (string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to))
        {
            periode = dictionary["Item_IncidentAction_List_Filter_To"] + " " + to;
        }
        else if (!string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to))
        {
            periode = from + " " + to;
        }
        else
        {
            periode = dictionary["Common_All_Male"];
        }

        string typetext = string.Empty;

        bool firstType = false;
        if (typeImprovement)
        {
            typetext  = dictionary["Item_IncidentAction_Type1"];
            firstType = false;
        }
        if (typeFix)
        {
            if (!firstType)
            {
                typetext += " - ";
            }
            typetext += dictionary["Item_IncidentAction_Type2"];
            firstType = false;
        }
        if (typePrevent)
        {
            if (!firstType)
            {
                typetext += " - ";
            }
            typetext += dictionary["Item_IncidentAction_Type3"];
        }

        string statusText  = string.Empty;
        bool   firstStatus = true;
        if (statusIdentified)
        {
            firstStatus = false;
            statusText += dictionary["Item_IndicentAction_Status1"];
        }

        if (statusAnalyzed)
        {
            if (!firstStatus)
            {
                statusText += " - ";
            }
            statusText += dictionary["Item_IndicentAction_Status2"];
            firstStatus = false;
        }

        if (statusInProgress)
        {
            if (!firstStatus)
            {
                statusText += " - ";
            }
            statusText += dictionary["Item_IndicentAction_Status3"];
            firstType   = false;
        }

        if (statusClose)
        {
            if (!firstType)
            {
                statusText += " - ";
            }
            statusText += dictionary["Item_IndicentAction_Status4"];

            firstType = false;
        }
        #endregion

        ToolsPdf.AddCriteria(criteriatable, dictionary["Common_Period"], periode);
        ToolsPdf.AddCriteria(criteriatable, dictionary["Item_Customer_Header_Type"], typetext);
        ToolsPdf.AddCriteria(criteriatable, dictionary["Item_IncidentAction_Header_Status"], statusText);
        ToolsPdf.AddCriteria(criteriatable, dictionary["Item_IncidentAction_Header_Origin"], criteriaOrigin);
        ToolsPdf.AddCriteria(criteriatable, dictionary["Item_IncidentAction_Label_Reporter"], reporterText);
        ToolsPdf.AddCriteria(criteriatable, string.Empty, string.Empty);
        pdfDoc.Add(criteriatable);
        #endregion

        var table = new iTSpdf.PdfPTable(9)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 20f,
            SpacingAfter        = 30f
        };

        table.SetWidths(new float[] { 2f, 30f, 10f, 10f, 10f, 10f, 10f, 10f, 10f });
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Incident_Label_Number"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Description"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Type"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Open"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Status"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Origin"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Cost"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_ImplementDate"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Close"]));

        int     cont      = 0;
        decimal totalCost = 0;
        var     data      = HttpContext.Current.Session["IncidentActionFilterData"] as List <IncidentActionFilterItem>;

        foreach (IncidentActionFilterItem item in data)
        {
            string originText = string.Empty;
            if (item.Origin == 1)
            {
                originText = dictionary["Item_IncidentAction_Origin1"];
            }
            if (item.Origin == 2)
            {
                originText = dictionary["Item_IncidentAction_Origin2"];
            }
            if (item.Origin == 3)
            {
                originText = dictionary["Item_IncidentAction_Origin3"];
            }
            if (item.Origin == 4)
            {
                originText = dictionary["Item_IncidentAction_Origin4"];
            }
            if (item.Origin == 5)
            {
                originText = dictionary["Item_IncidentAction_Origin5"];
            }
            if (item.Origin == 6)
            {
                originText = dictionary["Item_IncidentAction_Origin6"];
            }
            item.OriginText = originText;
        }

        switch (listOrder.ToUpperInvariant())
        {
        default:
        case "TH0|ASC":
            data = data.OrderBy(d => d.Description).ToList();
            break;

        case "TH0|DESC":
            data = data.OrderByDescending(d => d.Description).ToList();
            break;

        case "TH1|ASC":
            data = data.OrderBy(d => d.ActionType).ToList();
            break;

        case "TH1|DESC":
            data = data.OrderByDescending(d => d.ActionType).ToList();
            break;

        case "TH2|ASC":
            data = data.OrderBy(d => d.OpenDate).ToList();
            break;

        case "TH2|DESC":
            data = data.OrderByDescending(d => d.OpenDate).ToList();
            break;

        case "TH3|ASC":
            data = data.OrderBy(d => d.Status).ToList();
            break;

        case "TH3|DESC":
            data = data.OrderByDescending(d => d.Status).ToList();
            break;

        case "TH4|ASC":
            data = data.OrderBy(d => d.OriginText).ToList();
            break;

        case "TH4|DESC":
            data = data.OrderByDescending(d => d.OriginText).ToList();
            break;

        case "TH5|ASC":
            data = data.OrderBy(d => d.ImplementationDate).ToList();
            break;

        case "TH5|DESC":
            data = data.OrderByDescending(d => d.ImplementationDate).ToList();
            break;

        case "TH6|ASC":
            data = data.OrderBy(d => d.CloseDate).ToList();
            break;

        case "TH6|DESC":
            data = data.OrderByDescending(d => d.CloseDate).ToList();
            break;
        }

        foreach (IncidentActionFilterItem action in data)
        {
            int border = 0;
            totalCost += action.Amount;

            string actionTypeText = string.Empty;
            switch (action.ActionType)
            {
            default:
            case 1: actionTypeText = dictionary["Item_IncidentAction_Type1"]; break;

            case 2: actionTypeText = dictionary["Item_IncidentAction_Type2"]; break;

            case 3: actionTypeText = dictionary["Item_IncidentAction_Type3"]; break;
            }

            string statustext = string.Empty;
            if (action.Status == 1)
            {
                statustext = dictionary["Item_IndicentAction_Status1"];
            }
            if (action.Status == 2)
            {
                statustext = dictionary["Item_IndicentAction_Status2"];
            }
            if (action.Status == 3)
            {
                statustext = dictionary["Item_IndicentAction_Status3"];
            }
            if (action.Status == 4)
            {
                statustext = dictionary["Item_IndicentAction_Status4"];
            }

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(action.Description, ToolsPdf.LayoutFonts.Times))
            {
                Border          = border,
                BackgroundColor = ToolsPdf.LineBackgroundColor,
                Padding         = 6f,
                PaddingTop      = 4f
            });

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(actionTypeText, ToolsPdf.LayoutFonts.Times))
            {
                Border          = border,
                BackgroundColor = ToolsPdf.LineBackgroundColor,
                Padding         = 6f,
                PaddingTop      = 4f
            });

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.OpenDate), ToolsPdf.LayoutFonts.Times))
            {
                Border              = border,
                BackgroundColor     = ToolsPdf.LineBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = Rectangle.ALIGN_CENTER
            });

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(statustext, ToolsPdf.LayoutFonts.Times))
            {
                Border              = border,
                BackgroundColor     = ToolsPdf.LineBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = Rectangle.ALIGN_CENTER
            });

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(action.OriginText, ToolsPdf.LayoutFonts.Times))
            {
                Border              = border,
                BackgroundColor     = ToolsPdf.LineBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = Rectangle.ALIGN_CENTER
            });

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(Tools.PdfMoneyFormat(action.Amount), ToolsPdf.LayoutFonts.Times))
            {
                Border              = border,
                BackgroundColor     = ToolsPdf.LineBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = Rectangle.ALIGN_RIGHT
            });

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.ImplementationDate), ToolsPdf.LayoutFonts.Times))
            {
                Border              = border,
                BackgroundColor     = ToolsPdf.LineBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = Rectangle.ALIGN_CENTER
            });

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.CloseDate), ToolsPdf.LayoutFonts.Times))
            {
                Border              = border,
                BackgroundColor     = ToolsPdf.LineBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = Rectangle.ALIGN_CENTER
            });

            cont++;
        }

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(
                                                             CultureInfo.InvariantCulture,
                                                             @"{0}: {1}",
                                                             dictionary["Common_RegisterCount"],
                                                             cont), ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = ToolsPdf.SummaryBackgroundColor,
            Padding         = 6f,
            PaddingTop      = 4f,
            Colspan         = 4
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant(), ToolsPdf.LayoutFonts.Times))
        {
            Border              = iTS.Rectangle.TOP_BORDER,
            BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
            Padding             = 6f,
            PaddingTop          = 4f,
            HorizontalAlignment = 2
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(Tools.PdfMoneyFormat(totalCost), ToolsPdf.LayoutFonts.Times))
        {
            Border              = iTS.Rectangle.TOP_BORDER,
            BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
            Padding             = 6f,
            PaddingTop          = 4f,
            HorizontalAlignment = 2
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = ToolsPdf.SummaryBackgroundColor,
            Colspan         = 2
        });

        pdfDoc.Add(table);
        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
Exemplo n.º 41
0
        public override void OnStartPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
        {
            //Stream st = new Stream();
            var headerTable = new PdfPTable(3);

            headerTable.SpacingBefore = 0;
            var cnt       = data[0].GetType().GetProperties().Count();
            var pdfHTable = new PdfPTable(cnt);

            headerTable.HorizontalAlignment = Element.ALIGN_CENTER;
            //byte[] data21 = File.ReadAllBytes();
            //MemoryStream ms = new MemoryStream(data21);
            //iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(System.Web.HttpContext.Current.Server.MapPath("~/Content/images/EPGM-LOGO.png"));
            //logo.SetAbsolutePosition(120, document.PageSize.Height - 90);
            //logo.ScalePercent(7f);
            //PdfPCell logoCell = new PdfPCell();
            //logoCell.AddElement(logo);
            //logoCell.Border = 0;
            //logoCell.Colspan = 2;
            //logoCell.HorizontalAlignment = Element.ALIGN_CENTER;
            PdfPCell emptycel = new PdfPCell();

            emptycel.Border = 0;
            headerTable.AddCell(emptycel);
            //headerTable.AddCell("hai");
            //headerTable.AddCell("cell");
            //headerTable.AddCell(" ");
            var           count    = data[0].GetType().GetProperties().Count();
            List <object> headtext = new List <object>();

            headtext.Add(fileName);
            //if ((disname != ""))
            //    headtext.Add(disname);
            //headtext.Add("Report Generated for the Period of: " + fromdate + " To " + todate);
            var pdfheadertb = new PdfPTable(1);
            //headerTable.AddCell(logoCell);
            //headerTable.AddCell(" ");
            var celldat2 = new PdfPCell(new Phrase(12, "Growth Monitoring System", baseFontHeading));

            celldat2.HorizontalAlignment = Element.ALIGN_CENTER;
            celldat2.Border = 0;
            pdfheadertb.AddCell(celldat2);
            var celldat = new PdfPCell(new Phrase(14, "Government of Telangana", baseFontHeading1));

            celldat.HorizontalAlignment = Element.ALIGN_CENTER;
            celldat.Border = 0;
            pdfheadertb.AddCell(celldat);
            foreach (object colhead in headtext)
            {
                var celldata = new PdfPCell(new Phrase(12, colhead.ToString(), baseFontBold));
                celldata.HorizontalAlignment = Element.ALIGN_CENTER;
                celldata.Border = 0;
                PdfPCell[] coldata = new PdfPCell[] { celldata };
                PdfPRow    rowdata = new PdfPRow(coldata);
                pdfheadertb.Rows.Add(rowdata);
            }
            pdfheadertb.HorizontalAlignment = Element.ALIGN_CENTER;
            var celldat1 = new PdfPCell(new Phrase(12, "Report Generated Time:" + System.DateTime.Now.Day + "-" + System.DateTime.Now.Month + "-" + System.DateTime.Now.Year + " " + System.DateTime.Now.Hour + ":" + System.DateTime.Now.Minute, baseFontBig));

            celldat1.HorizontalAlignment = Element.ALIGN_LEFT;
            celldat1.Border = 0;
            //document.Add(logo);
            var myType = data[0].GetType();

            IList <PropertyInfo> properties = new List <PropertyInfo>(myType.GetProperties());
            List <PdfPCell>      cells      = new List <PdfPCell>();

            foreach (PropertyInfo prop in properties)
            {
                string propValue = prop.Name;   //.Humanize(LetterCasing.Title);
                var    cell      = new PdfPCell(new Phrase(12, propValue, baseFontBold));
                cells.Add(cell);
            }
            PdfPRow row = new PdfPRow(cells.ToArray <PdfPCell>());

            pdfHTable.Rows.Add(row);

            PdfPTable reporttb = new PdfPTable(9);
            var       col1     = new PdfPCell(new Phrase(12, " ", baseFontBig));

            col1.Colspan     = 5;
            col1.Border      = 0;
            celldat1.Colspan = 4;
            reporttb.AddCell(col1);
            reporttb.AddCell(celldat1);
            if (document.PageNumber == 1)
            {
                document.Add(headerTable);
                document.Add(pdfheadertb);
                document.Add(reporttb);
            }

            document.Add(pdfHTable);
            PdfPTable footerTable = new PdfPTable(1);

            //byte[] data12 = File.ReadAllBytes();
            //MemoryStream ms1 = new MemoryStream(data12);
            //iTextSharp.text.Image logo1 = iTextSharp.text.Image.GetInstance(System.Web.HttpContext.Current.Server.MapPath("~/Content/images/EPGM-LOGO.png"));
            //logo1.SetAbsolutePosition(10, 100);
            //logo1.ScalePercent(40f);
            //PdfPCell addressCell = new PdfPCell();
            //addressCell.HorizontalAlignment = Element.ALIGN_LEFT;
            //addressCell.AddElement(logo1);
            //addressCell.Border = 0;
            //footerTable.AddCell(addressCell);
            footerTable.TotalWidth      = document.PageSize.Width - 80f;
            footerTable.WidthPercentage = 100;
            footerTable.WriteSelectedRows(0, -1, 40, document.PageSize.GetBottom(500), writer.DirectContent);
        }
Exemplo n.º 42
0
        private void AnalysisOfMilkToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveFileDialog1.Title      = "Сохранение документа";
            saveFileDialog1.FileName   = "Анализ молока коров";
            saveFileDialog1.DefaultExt = "*.pdf";
            saveFileDialog1.Filter     = "Файлы PDF (*.pdf)|*.pdf|Все файлы (*.*)|*.*";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string SaveFileName = saveFileDialog1.FileName;

                //Объект документа пдф
                iTextSharp.text.Document doc = new iTextSharp.text.Document();
                //Создаем объект записи пдф-документа в файл
                PdfWriter.GetInstance(doc, new FileStream(SaveFileName, FileMode.Create));

                //Открываем документ
                doc.Open();

                //Определение шрифта необходимо для сохранения кириллического текста
                //Иначе мы не увидим кириллический текст
                //Если мы работаем только с англоязычными текстами, то шрифт можно не указывать
                string               FONT_LOCATION = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "arial.TTF"); //определяем В СИСТЕМЕ(чтобы не копировать файл) расположение шрифта arial.ttf
                BaseFont             baseFont      = BaseFont.CreateFont(FONT_LOCATION, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);        //создаем шрифт
                iTextSharp.text.Font fontParagraph = new iTextSharp.text.Font(baseFont, 17, iTextSharp.text.Font.NORMAL);                   //регистрируем + можно задать параметры для него(17 - размер, последний параметр - стиль)
                                                                                                                                            //Создаем объект таблицы и передаем в нее число столбцов таблицы из нашего датасета
                PdfPTable table = new PdfPTable(4);                                                                                         //MyDataSet.Tables[i].Columns.Count);
                                                                                                                                            //Добавим в таблицу общий заголовок
                PdfPCell cell = new PdfPCell(new Phrase("Анализ молока коров"));
                cell.Colspan             = 4;
                cell.HorizontalAlignment = 1;
                //Убираем границу первой ячейки, чтобы был как заголовок
                cell.Border = 0;
                table.AddCell(cell);
                //Сначала добавляем заголовки таблицы
                cell = new PdfPCell(new Phrase(new Phrase("Номер коровы", fontParagraph)));
                //Фоновый цвет (необязательно, просто сделаем по красивее)
                cell.BackgroundColor = BaseColor.LIGHT_GRAY;
                table.AddCell(cell);
                cell = new PdfPCell(new Phrase(new Phrase("Дата начала лактации", fontParagraph)));
                cell.BackgroundColor = BaseColor.LIGHT_GRAY;
                table.AddCell(cell);
                cell = new PdfPCell(new Phrase(new Phrase("МДБ", fontParagraph)))
                {
                    BackgroundColor = BaseColor.LIGHT_GRAY
                };
                table.AddCell(cell);
                cell = new PdfPCell(new Phrase(new Phrase("МДЖ", fontParagraph)));
                cell.BackgroundColor = BaseColor.LIGHT_GRAY;
                table.AddCell(cell);
                //Добавляем все остальные ячейки
                for (int j = 0; j < lactationDataGridView.RowCount - 1; j++)
                {
                    table.AddCell(new Phrase(lactationDataGridView.Rows[j].Cells[1].Value.ToString(), fontParagraph));
                    table.AddCell(new Phrase(lactationDataGridView.Rows[j].Cells[2].Value.ToString(), fontParagraph));
                    table.AddCell(new Phrase(lactationDataGridView.Rows[j].Cells[7].Value.ToString(), fontParagraph));
                    table.AddCell(new Phrase(lactationDataGridView.Rows[j].Cells[8].Value.ToString(), fontParagraph));
                }
                //Добавляем таблицу в документ
                doc.Add(table);
                //Закрываем документ
                doc.Close();
                Process.Start(saveFileDialog1.FileName);
            }
        }
Exemplo n.º 43
0
        internal void stampaPDFFA()

        {
            try
            {
                using (System.IO.MemoryStream ms = new MemoryStream())
                {
                    iTextSharp.text.Document doc = new iTextSharp.text.Document();
                    IMTS_MINUTES.BusinessLogic.BLMinutes.BLWriteMiutes blw = new IMTS_MINUTES.BusinessLogic.BLMinutes.BLWriteMiutes();

                    IMTS_MINUTES.DataBase.IMTSDB_NEW.MinuteRow row = blw.getMinuteRow();


                    PdfWriter pdfw = PdfWriter.GetInstance(doc, new FileStream(Directory.GetParent(Application.ExecutablePath).Parent.Parent.FullName + "\\template\\stampe\\VerbaleChiusura.pdf", FileMode.Create));
                    pdfw.PageEvent = new PageHeaderFooter();
                    // step 3
                    doc.Open();

                    var Titolo             = FontFactory.GetFont("Colibri", 16, Font.BOLD, BaseColor.BLACK);
                    var sottoTitolo        = FontFactory.GetFont("Colibri", 14, Font.NORMAL, BaseColor.BLACK);
                    var testo              = FontFactory.GetFont("Colibri", 8, Font.NORMAL, BaseColor.BLACK);
                    var TestoB             = FontFactory.GetFont("Colibri", 8, Font.BOLD, BaseColor.BLACK);
                    var TitoloVerbale      = FontFactory.GetFont("Colibri", 10, Font.BOLD, BaseColor.BLACK);
                    var noto               = FontFactory.GetFont("Colibri", 12, Font.BOLD, BaseColor.BLACK);
                    var testoScheda        = FontFactory.GetFont("Colibri", 10, Font.NORMAL, BaseColor.BLACK);
                    var testoSchedaBoxato  = FontFactory.GetFont("Colibri", 12, Font.UNDERLINE, BaseColor.BLACK);
                    var intestazioneScheda = FontFactory.GetFont("Colibri", 12, Font.BOLD, BaseColor.BLACK);
                    var vuoto              = FontFactory.GetFont("Colibri", 12, Font.NORMAL, BaseColor.BLACK);
                    // Stream inputImageStream = new MemoryStream(System.IO.File.ReadAllBytes( Directory.GetParent(Application.ExecutablePath).Parent.Parent.FullName + "\\Images\\logoCOI.jpg"));
                    iTextSharp.text.Image gif = iTextSharp.text.Image.GetInstance(Directory.GetParent(Application.ExecutablePath).Parent.Parent.FullName + "\\Images\\logoCOI.jpg");

                    Paragraph paragraph = new Paragraph();
                    gif.Alignment = iTextSharp.text.Image.ALIGN_TOP;
                    gif.Alignment = Image.ALIGN_CENTER;
                    doc.Add(gif);
                    Chunk tit = new Chunk("COMANDO OPERATIVO di VERTICE INTERFORZE  \n", Titolo);
                    paragraph = new Paragraph();
                    doc.Add(paragraph);
                    paragraph = new Paragraph();
                    doc.Add(paragraph);
                    paragraph = new Paragraph();
                    Chunk  Stit   = new Chunk("VIA CENTOCELLE  NR 301   \n", sottoTitolo);
                    Chunk  SStit  = new Chunk("00175- ROMA  \n", sottoTitolo);
                    Phrase phrase = new Phrase();
                    phrase.Add(tit);
                    phrase.Add(Stit);
                    phrase.Add(SStit);

                    paragraph.Add(phrase);
                    paragraph.Alignment = Element.ALIGN_CENTER;
                    doc.Add(paragraph);

                    paragraph = new Paragraph();
                    doc.Add(paragraph);
                    paragraph = new Paragraph();
                    doc.Add(paragraph);
                    paragraph = new Paragraph();
                    doc.Add(paragraph);

                    Chunk     copia      = new Chunk("Copia nr." + row.NCopie.ToString() + " / " + row.Data_Acquisizione_Verbale.ToShortDateString(), testo);
                    Chunk     verbalenr  = new Chunk("Verbale nr." + row.Verbale_Number.ToString(), testo);
                    Phrase    lphrase    = new Phrase();
                    Phrase    rphrase    = new Phrase();
                    Paragraph lparagraph = new Paragraph();
                    Paragraph rparagraph = new Paragraph();
                    lphrase.Add(copia);
                    lparagraph.Add(lphrase);
                    lparagraph.Alignment = Element.ALIGN_LEFT;
                    doc.Add(lparagraph);


                    rphrase.Add(verbalenr);
                    rparagraph.Add(rphrase);
                    rparagraph.Alignment = Element.ALIGN_RIGHT;
                    doc.Add(rparagraph);

                    paragraph = new Paragraph("\n");
                    doc.Add(paragraph);
                    paragraph = new Paragraph();
                    doc.Add(paragraph);

                    Chunk titVerb = new Chunk("VERBALE CHIUSURA COLLI  \n", TitoloVerbale);
                    phrase = new Phrase();
                    phrase.Add(titVerb);
                    paragraph = new Paragraph();
                    paragraph.Add(phrase);
                    paragraph.Alignment = Element.ALIGN_CENTER;
                    doc.Add(paragraph);

                    Chunk TESTOb = new Chunk("In data " + row.Data_Provvedimento.ToShortDateString() + " presso " + row.Presso_Luogo + " situato presso la caserma " + row.Presso_Caserma, TestoB);
                    phrase = new Phrase();

                    paragraph = new Paragraph();
                    phrase.Add(TESTOb);
                    paragraph.Add(phrase);
                    paragraph.Alignment = Element.ALIGN_CENTER;
                    doc.Add(paragraph);

                    Chunk noto1 = new Chunk(" \n SIA NOTO ", noto);
                    phrase = new Phrase();

                    paragraph = new Paragraph();
                    phrase.Add(noto1);
                    paragraph.Add(phrase);
                    paragraph.Alignment = Element.ALIGN_CENTER;
                    doc.Add(paragraph);



                    Chunk testoNoto = new Chunk(" \n Che la sottotitolata commissione con supplemento all’ordine nr." + row.Ordine_Giorno_NR + " in data " + row.Data_Provvedimento.ToShortDateString() + " ha provveduto alla chiusura del " + row.Container_Descrizione + " con sigillo nr." + row._Matricola_targa + " destinato al " + row.Destinazione + " contenente materiale di proprietà dell’A.D. non destinato alla vendita o ad altri scopi di carattere commerciale, destinato al supporto de contingenti nazionali ovvero di rientro dalle Aree d’operazione.\n\n\n", testo);
                    phrase = new Phrase();

                    paragraph = new Paragraph();
                    phrase.Add(testoNoto);
                    paragraph.Add(phrase);
                    paragraph.Alignment = Element.ALIGN_CENTER;

                    doc.Add(paragraph);
                    Chunk skCaricamento = new Chunk("SHEDA CARICAMENTO PER                        \n\n", testoSchedaBoxato);
                    phrase = new Phrase();

                    paragraph = new Paragraph();

                    phrase.Add(skCaricamento);

                    paragraph.Add(phrase);
                    paragraph.Alignment = Element.ALIGN_LEFT;
                    doc.Add(paragraph);


                    PdfPTable table = new PdfPTable(2);

                    //table.WidthPercentage = 95;
                    PdfPCell cell1 = new PdfPCell(new Paragraph(new Phrase(new Chunk("(Tipo materiale)", TestoB))));
                    PdfPCell cell2 = new PdfPCell(new Paragraph(new Phrase(new Chunk("(Targa / matricola o numenro collo)", TestoB))));

                    PdfPCell cell3 = new PdfPCell(new Paragraph(new Phrase(new Chunk(row.Container_Descrizione, testoScheda))));
                    PdfPCell cell4 = new PdfPCell(new Paragraph(new Phrase(new Chunk(row._Matricola_targa, testoScheda))));
                    table.AddCell(cell1);
                    table.AddCell(cell2);
                    table.AddCell(cell3);
                    table.AddCell(cell4);
                    paragraph = new Paragraph();



                    paragraph.Add(table);

                    paragraph.Alignment = Element.ALIGN_CENTER;
                    doc.Add(table);

                    Chunk spazio = new Chunk("\n\n\n", testo);
                    phrase = new Phrase();

                    paragraph = new Paragraph();

                    phrase.Add(spazio);

                    paragraph.Add(phrase);

                    PdfPTable table1 = new PdfPTable(2);
                    table1.SetWidths(new int[] { 500, 500 });
                    //table.WidthPercentage = 95;



                    PdfPCell cell5 = new PdfPCell(new Paragraph(new Phrase(new Chunk("Reparto Mittente (From)", TestoB))));
                    PdfPCell cell6 = new PdfPCell(new Paragraph(new Phrase(new Chunk(row.Mittente, testo))));

                    PdfPCell cell7 = new PdfPCell(new Paragraph(new Phrase(new Chunk("Reparto Destinatario(To)", TestoB))));
                    PdfPCell cell8 = new PdfPCell(new Paragraph(new Phrase(new Chunk(row.Destinazione, testo))));

                    PdfPCell cell9  = new PdfPCell(new Paragraph(new Phrase(new Chunk("Luogo Destinazione (to)", TestoB))));
                    PdfPCell cell10 = new PdfPCell(new Paragraph(new Phrase(new Chunk(row.Destinazione_Container, testo))));

                    PdfPCell cell11 = new PdfPCell(new Paragraph(new Phrase(new Chunk("Termiale di stoccaggio (Container terminal)", TestoB))));
                    PdfPCell cell12 = new PdfPCell(new Paragraph(new Phrase(new Chunk(row.Terminale_Stoccaggio, testo))));


                    PdfPCell cell13 = new PdfPCell(new Paragraph(new Phrase(new Chunk("Vettore (Mode of transport)", TestoB))));
                    PdfPCell cell14 = new PdfPCell(new Paragraph(new Phrase(new Chunk(row.Vettore_Trasporto, testo))));

                    PdfPCell cell15 = new PdfPCell(new Paragraph(new Phrase(new Chunk("Matricola sigillo (eventuale)", TestoB))));
                    PdfPCell cell16 = new PdfPCell(new Paragraph(new Phrase(new Chunk(row.Operazione_Container, testo))));

                    table1.AddCell(cell5);
                    table1.AddCell(cell6);
                    table1.AddCell(cell7);
                    table1.AddCell(cell8);
                    table1.AddCell(cell9);
                    table1.AddCell(cell10);
                    table1.AddCell(cell11);
                    table1.AddCell(cell12);
                    table1.AddCell(cell13);
                    table1.AddCell(cell14);
                    table1.AddCell(cell15);
                    table1.AddCell(cell16);
                    table1.SpacingBefore = 20f;
                    doc.Add(table1);

                    PdfPTable table2 = new PdfPTable(2);
                    table2.SetWidths(new int[] { 500, 500 });
                    PdfPCell cell52 = new PdfPCell(new Paragraph(new Phrase(new Chunk("Numero telaio (Chassis Number)", TestoB))));
                    PdfPCell cell62 = new PdfPCell(new Paragraph(new Phrase(new Chunk(row.Telaio, testo))));
                    PdfPCell cell72 = new PdfPCell(new Paragraph(new Phrase(new Chunk("Matricola motore (Engine number)", TestoB))));
                    PdfPCell cell82 = new PdfPCell(new Paragraph(new Phrase(new Chunk(row.SNMotore, testo))));

                    PdfPCell cell92  = new PdfPCell(new Paragraph(new Phrase(new Chunk("Anno di costruzione (Year of construction)", TestoB))));
                    PdfPCell cell102 = new PdfPCell(new Paragraph(new Phrase(new Chunk(row.Anno_Costruzione, testo))));

                    PdfPCell cell112 = new PdfPCell(new Paragraph(new Phrase(new Chunk("Tipo di carburante(Type fuel)", TestoB))));
                    PdfPCell cell122 = new PdfPCell(new Paragraph(new Phrase(new Chunk(row.Tipo_Carburante, testo))));

                    table2.AddCell(cell52);
                    table2.AddCell(cell62);
                    table2.AddCell(cell72);
                    table2.AddCell(cell82);
                    table2.AddCell(cell92);
                    table2.AddCell(cell102);
                    table2.AddCell(cell112);
                    table2.AddCell(cell122);

                    table2.SpacingBefore = 20f;
                    doc.Add(table2);
                    IMTS_MINUTES.DataBase.IMTSDB_NEW.Materiale_ContainerDataTable matcont = blw.GetMateriale_Container();
                    CaclcolaTotali(matcont);

                    PdfPTable table3 = new PdfPTable(2);
                    table3.SetWidths(new int[] { 500, 500 });
                    CultureInfo cultures = new CultureInfo("it-IT");
                    PdfPCell    cell53   = new PdfPCell(new Paragraph(new Phrase(new Chunk("Peso totale (Total Weight)", TestoB))));
                    PdfPCell    cell63   = new PdfPCell(new Paragraph(new Phrase(new Chunk(Convert.ToString(row.Tara, cultures.NumberFormat), testo))));
                    PdfPCell    cell73   = new PdfPCell(new Paragraph(new Phrase(new Chunk("Valore(Value)", TestoB))));
                    PdfPCell    cell83   = new PdfPCell(new Paragraph(new Phrase(new Chunk(Convert.ToString(row.Valore, cultures.NumberFormat), testo))));
                    table3.AddCell(cell53);
                    table3.AddCell(cell63);
                    table3.AddCell(cell73);
                    table3.AddCell(cell83);

                    table3.SpacingBefore = 20f;
                    doc.Add(table3);

                    //costruisco tabellla materiale
                    PdfPTable table4 = new PdfPTable(7);
                    table4.SetWidths(new int[] { 50, 300, 100, 250, 300, 250, 250 });

                    PdfPCell cell54  = new PdfPCell(new Paragraph(new Phrase(new Chunk("NR.", TestoB))));
                    PdfPCell cell65  = new PdfPCell(new Paragraph(new Phrase(new Chunk("DENOMINAZIONE\nDESCRIPTION", TestoB))));
                    PdfPCell cell76  = new PdfPCell(new Paragraph(new Phrase(new Chunk("QTY'\n (QTY)", TestoB))));
                    PdfPCell cell87  = new PdfPCell(new Paragraph(new Phrase(new Chunk("PESO'\nWEIGHT", TestoB))));
                    PdfPCell cell88  = new PdfPCell(new Paragraph(new Phrase(new Chunk("VALORE COMMERCIALE\n (AMOUNT OF GOODS)", TestoB))));
                    PdfPCell cell89  = new PdfPCell(new Paragraph(new Phrase(new Chunk("MATRICOLA", TestoB))));
                    PdfPCell cell810 = new PdfPCell(new Paragraph(new Phrase(new Chunk("DANGEROUS", TestoB))));

                    table4.AddCell(cell54);
                    table4.AddCell(cell65);
                    table4.AddCell(cell76);
                    table4.AddCell(cell87);
                    table4.AddCell(cell88);
                    table4.AddCell(cell89);
                    table4.AddCell(cell810);


                    int i = 1;
                    foreach (DataRow dr in matcont.Rows)
                    {
                        PdfPCell cell111 = new PdfPCell(new Paragraph(new Phrase(new Chunk(i.ToString(), testo))));
                        PdfPCell cell114 = new PdfPCell(new Paragraph(new Phrase(new Chunk(dr.ItemArray[2].ToString(), testo))));
                        PdfPCell cell113 = new PdfPCell(new Paragraph(new Phrase(new Chunk(dr.ItemArray[1].ToString(), testo))));
                        PdfPCell cell115 = new PdfPCell(new Paragraph(new Phrase(new Chunk(dr.ItemArray[6].ToString(), testo))));
                        PdfPCell cell116 = new PdfPCell(new Paragraph(new Phrase(new Chunk(dr.ItemArray[7].ToString(), testo))));
                        PdfPCell cell117 = new PdfPCell(new Paragraph(new Phrase(new Chunk(dr.ItemArray[8].ToString(), testo))));
                        PdfPCell cell119 = new PdfPCell(new Paragraph(new Phrase(new Chunk(dr.ItemArray[9].ToString(), testo))));

                        table4.AddCell(cell111);
                        table4.AddCell(cell114);
                        table4.AddCell(cell113);
                        table4.AddCell(cell115);
                        table4.AddCell(cell116);
                        table4.AddCell(cell117);
                        table4.AddCell(cell119);
                        i++;
                    }

                    table4.SpacingBefore = 20f;
                    doc.Add(table4);



                    PdfPTable table6 = new PdfPTable(5);
                    table6.SetWidths(new int[] { 100, 250, 300, 250, 250 });

                    PdfPCell cell545 = new PdfPCell(new Paragraph(new Phrase(new Chunk("", TestoB))));
                    PdfPCell cell655 = new PdfPCell(new Paragraph(new Phrase(new Chunk("TTOTAL", TestoB))));
                    PdfPCell cell765 = new PdfPCell(new Paragraph(new Phrase(new Chunk("QTY: " + Convert.ToString(qtyT, cultures.NumberFormat), testo))));
                    PdfPCell cell875 = new PdfPCell(new Paragraph(new Phrase(new Chunk("WEIGHT: " + Convert.ToString(weightT, cultures.NumberFormat), testo))));
                    PdfPCell cell885 = new PdfPCell(new Paragraph(new Phrase(new Chunk("VALUE: " + Convert.ToString(valueT, cultures.NumberFormat), testo))));


                    table6.AddCell(cell545);
                    table6.AddCell(cell655);
                    table6.AddCell(cell765);
                    table6.AddCell(cell875);
                    table6.AddCell(cell885);
                    table6.SpacingBefore = 10f;
                    doc.Add(table6);

                    Chunk testoRespo = new Chunk(" \nIn merito, il responsabil del caricamento:" + row.Responsabile_Chiusura, testo);
                    phrase = new Phrase();

                    paragraph = new Paragraph();
                    phrase.Add(testoRespo);
                    paragraph.Add(phrase);
                    paragraph.Alignment = Element.ALIGN_CENTER;

                    doc.Add(paragraph);
                    Chunk testdich = new Chunk("\n\n  DICHIARA", TestoB);
                    phrase = new Phrase();

                    paragraph = new Paragraph();
                    phrase.Add(testdich);
                    paragraph.Add(phrase);
                    paragraph.Alignment = Element.ALIGN_CENTER;

                    doc.Add(paragraph);

                    Chunk testdichiarazione = new Chunk("\nChe NON è stato caricato materiale diverso da quanto sopra elencato, 'sostanze stupefacenti o materiale illegale'. Si precisa, inoltre, che il presente verbale viene redatto in nr. " + row.NCopie + " di cui nr.1 (una) affissa all'interno e all'esterno del " + row.Container_Descrizione + ".", testo);
                    phrase = new Phrase();

                    paragraph = new Paragraph();
                    phrase.Add(testdichiarazione);
                    paragraph.Add(phrase);
                    paragraph.Alignment = Element.ALIGN_LEFT;

                    doc.Add(paragraph);



                    Chunk firmaRespo = new Chunk("\n" + row.Responsabile_Chiusura + ", li " + row.Data_Chiusura.ToShortDateString() + "                                                                                                                           IL RESPONSABILE DEL CARICAMENTO", testo);
                    phrase = new Phrase();

                    paragraph = new Paragraph();
                    phrase.Add(firmaRespo);
                    paragraph.Add(phrase);
                    paragraph.Alignment = Element.ALIGN_LEFT;

                    doc.Add(paragraph);

                    Chunk firmaRespo1 = new Chunk(row.Responsabile_Chiusura, testo);
                    phrase = new Phrase();

                    paragraph = new Paragraph();
                    phrase.Add(firmaRespo1);
                    paragraph.Add(phrase);
                    paragraph.Alignment = Element.ALIGN_RIGHT;

                    doc.Add(paragraph);

                    Chunk commissione = new Chunk("LA COMMISSIONE", testoSchedaBoxato);
                    phrase = new Phrase();

                    paragraph = new Paragraph();
                    phrase.Add(commissione);
                    paragraph.Add(phrase);
                    paragraph.Alignment = Element.ALIGN_CENTER;

                    doc.Add(paragraph);

                    Chunk firmacommissione = new Chunk("IL PRESIDENTE", testo);
                    phrase = new Phrase();

                    paragraph = new Paragraph();
                    phrase.Add(firmacommissione);
                    paragraph.Add(phrase);
                    paragraph.Alignment = Element.ALIGN_CENTER;

                    doc.Add(paragraph);


                    Chunk presidente = new Chunk(row.Presidente_Commissione, testo);
                    phrase = new Phrase();

                    paragraph = new Paragraph();
                    phrase.Add(presidente);
                    paragraph.Add(phrase);
                    paragraph.Alignment = Element.ALIGN_CENTER;

                    doc.Add(paragraph);

                    Chunk membro = new Chunk("\nMEMBRO", testo);
                    phrase = new Phrase();

                    paragraph = new Paragraph();
                    phrase.Add(membro);
                    paragraph.Add(phrase);
                    paragraph.Alignment = Element.ALIGN_LEFT;

                    doc.Add(paragraph);
                    Chunk firmamembro = new Chunk(row.Membro_Commissione, testo);
                    phrase = new Phrase();

                    paragraph = new Paragraph();
                    phrase.Add(firmamembro);
                    paragraph.Add(phrase);
                    paragraph.Alignment = Element.ALIGN_LEFT;

                    doc.Add(paragraph);

                    Chunk memboroesegrrew = new Chunk("\nMEMBRO E SEGRETARIO", testo);
                    phrase = new Phrase();

                    paragraph = new Paragraph();
                    phrase.Add(memboroesegrrew);
                    paragraph.Add(phrase);
                    paragraph.Alignment = Element.ALIGN_RIGHT;

                    doc.Add(paragraph);
                    Chunk memboroesegrrewfirma = new Chunk(row.Membro_Commissione + " - " + row.Segretario_Commissione, testo);
                    phrase = new Phrase();

                    paragraph = new Paragraph();
                    phrase.Add(memboroesegrrewfirma);
                    paragraph.Add(phrase);
                    paragraph.Alignment = Element.ALIGN_RIGHT;

                    doc.Add(paragraph);


                    doc.Close();
                }
            }
            catch (Exception ex)
            {
            }
        }
        public bool CreateReport(DataView theData)
        {
            bool isSuccessful = false;
            var  document     = new iTextSharp.text.Document(PageSize.LETTER);

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

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

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

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

                gif.ScalePercent(35);

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

                ReportHeader(table, gif);

                CustomerData(table, theData);
                LoanData(table, theData);
                ItemHeader(table);
                table.SetWidthPercentage(new float[]
                {
                    50F, 50F, 20F, 70F, 70F, 50F, 50F, 50F, 70F, 70F
                }, PageSize.LETTER);

                table.HeaderRows = 14;

                ReportDetail(table, theData);

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

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

            return(isSuccessful);
        }
        public FileStreamResult GETPdf()
        {
            List <test> all = new List <test>();

            //  item1 = Session["selecdate"].ToString();
            //  Console.Write(item1);
            using (ReportSupEntities1 dc = new ReportSupEntities1())
            {
                //   all = (from e in dc).ToList();
                all = (from e in dc.sp_matrix_weekdays(15, "08 - 17 - 2015") select new test {
                    Nombre = e.name, FechaEntradaMonday = e.Hora_de_LLegada_Lunes, FechaSalidaMonday = e.Hora_de_salida_Lunes, HorasMonday = e.Monday, FechaEntradaTuesday = e.Hora_de_LLegada_Martes, FechaSalidaTuesday = e.Hora_de_salida_Martes, HorasTuesday = e.Tuesday, FechaEntradaWendnsday = e.Hora_de_LLegada_Miercoles, FechaSalidaWendnsday = e.Hora_de_salida_Miercoles, HorasWendnsday = e.Wednsday, FechaEntradaThursday = e.Hora_de_LLegada_Jueves, FechaSalidaThursday = e.Hora_de_salida_Jueves, HorasThursday = e.Thursday, FechaEntradaFriday = e.Hora_de_LLegada_Viernes, FechaSalidaFriday = e.Hora_de_salida_Viernes, HorasFriday = e.Friday, FechaEntradaSaturday = e.Hora_de_LLegada_Sabado, FechaSalidaSaturday = e.Hora_de_salida_Sabado, HorasSaturday = e.Saturday, FechaEntradaSunday = e.Hora_de_LLegada_Domingo, FechaSalidaSunday = e.Hora_de_salida_Domingo, HorasSunday = e.Sunday
                }).ToList();
            }

            WebGrid grid     = new WebGrid(source: all, canPage: false, canSort: false);
            string  gridHtml = grid.GetHtml(
                columns: grid.Columns(
                    grid.Column("Nombre", "Nombre", canSort: true, style: "name"),
                    grid.Column("FechaEntradaMonday", "Fecha de Entrada LUNES"),
                    grid.Column("FechaSalidaMonday", "Fecha de Salida"),
                    grid.Column("HorasMonday", "Horas Trabajadas Lunes"),
                    grid.Column("FechaEntradaTuesday", "Fecha de Entrada MARTES"),
                    grid.Column("FechaSalidaTuesday", "Fecha de Salida"),
                    grid.Column("HorasTuesday", "Horas Trabajadas Martes"),
                    grid.Column("FechaEntradaWendnsday", "Fecha de Entrada MIERCOLES"),
                    grid.Column("FechaSalidaWendnsday", "Fecha de Salida"),
                    grid.Column("HorasWendnsday", "Horas Trabajadas Miertcoles"),
                    grid.Column("FechaEntradaThursday", "Fecha de JUEVES"),
                    grid.Column("FechaSalidaThursday", "Fecha de Salida"),
                    grid.Column("HorasThursday", "Horas Trabajadas Jueves"),
                    grid.Column("FechaEntradaFriday", "Fecha de Entrada VIERNES"),
                    grid.Column("FechaSalidaFriday", "Fecha de Salida"),
                    grid.Column("HorasFriday", "Horas Trabajadas Viernes"),
                    grid.Column("FechaEntradaSaturday", "Fecha de Sabado"),
                    grid.Column("FechaSalidaSaturday", "Fecha de Salida"),
                    grid.Column("HorasSaturday", "Horas Trabajadas Sabado"),
                    grid.Column("FechaEntradaSunday", "Fecha de DOMINGO"),
                    grid.Column("FechaSalidaSunday", "Fecha de Salida")
                    )
                ).ToHtmlString();

            string exportData = String.Format("<html><head>{0}</head><body><div><span>Reporte</span></div>{1}</body></html>", "<style>table{ border-spacing: 1000px; border-collapse: separate; .name {width: 550px;} }</style>", gridHtml);
            var    bytes      = System.Text.Encoding.UTF8.GetBytes(exportData);

            using (var input = new MemoryStream(bytes))
            {
                var output   = new MemoryStream();
                var document = new iTextSharp.text.Document(PageSize.A0, 50, 50, 25, 50);
                var writer   = PdfWriter.GetInstance(document, output);
                writer.CloseStream = false;
                document.Open();

                var xmlWorker = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();
                xmlWorker.ParseXHtml(writer, document, input, System.Text.Encoding.UTF8);
                document.Close();
                output.Position = 0;
                string path = this.Server.MapPath(".") + "Libraries\\Documents\\doc.pdf";

                //        return new FileStreamResult(output, "C:\application.pdf");
                return(new FileStreamResult(output, "aplication/pdf")
                {
                    FileDownloadName = "PDFPERFORMACE" + ".pdf"
                });
            }
        }
Exemplo n.º 46
0
        public void GenerateReport(List <ISimulationObject> objects, string format, Stream ms)
        {
            string ptext = "";

            switch (format)
            {
            case "PDF":

                iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.A4, 25, 25, 30, 30);
                var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms);

                var bf = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.COURIER, iTextSharp.text.pdf.BaseFont.CP1252, true);

                var regfont  = new Font(bf, 12, Font.NORMAL);
                var boldfont = new Font(bf, 12, Font.BOLD);

                document.Open();
                document.Add(new Paragraph("DWSIM Simulation Results Report", boldfont));
                document.Add(new Paragraph("Simulation Name: " + Options.SimulationName, boldfont));
                document.Add(new Paragraph("Date created: " + System.DateTime.Now.ToString() + "\n\n", boldfont));

                foreach (var obj in objects)
                {
                    ptext = obj.GetDisplayName() + ": " + obj.GraphicObject.Tag + "\n\n";
                    document.Add(new Paragraph(ptext, boldfont));
                    ptext  = obj.GetReport(Options.SelectedUnitSystem, System.Globalization.CultureInfo.CurrentCulture, Options.NumberFormat);
                    ptext += "\n";
                    document.Add(new Paragraph(ptext, regfont));
                }

                document.Close();

                writer.Close();

                break;

            case "TXT":

                string report = "";

                report += "DWSIM Simulation Results Report\nSimulation Name: " + Options.SimulationName + "\nDate created: " + System.DateTime.Now.ToString() + "\n\n";

                foreach (var obj in objects)
                {
                    ptext   = "";
                    ptext  += obj.GetDisplayName() + ": " + obj.GraphicObject.Tag + "\n\n";
                    ptext  += obj.GetReport(Options.SelectedUnitSystem, System.Globalization.CultureInfo.CurrentCulture, Options.NumberFormat);
                    ptext  += "\n";
                    report += ptext;
                }


                using (StreamWriter wr = new StreamWriter(ms))
                {
                    wr.Write(report);
                }
                break;

            default:

                throw new NotImplementedException("Sorry, this feature is not yet available.");
            }
        }
Exemplo n.º 47
0
        public void ExtractPdf(DataGridView dataGridView, bool selectedParameter)
        {
            Phrase p = new Phrase("\n");

            #region Font seç
            BaseFont             trArial              = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\tahoma.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            iTextSharp.text.Font fontArial            = new iTextSharp.text.Font(trArial, 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.DARK_GRAY);
            iTextSharp.text.Font fontArialHeader      = new iTextSharp.text.Font(trArial, 11, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);
            iTextSharp.text.Font fontArialbold        = new iTextSharp.text.Font(trArial, 9, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.DARK_GRAY);
            iTextSharp.text.Font fontArialboldgeneral = new iTextSharp.text.Font(trArial, 10, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);
            #endregion

            #region Fatura pdf oluştur
            SaveFileDialog save = new SaveFileDialog();
            save.OverwritePrompt = false;
            save.Title           = "PDF Dosyaları";
            save.DefaultExt      = "pdf";
            save.Filter          = "pdf Dosyaları (*.pdf)|*.pdf|Tüm Dosyalar(*.*)|*.*";
            if (save.ShowDialog() == DialogResult.OK)
            {
                iTextSharp.text.Document pdfFile = new iTextSharp.text.Document();
                PdfWriter.GetInstance(pdfFile, new FileStream(save.FileName, FileMode.Create));
                pdfFile.Open();

                #region Fatura oluşturan bilgileri
                pdfFile.AddCreator("Hakedis");                     //Oluşturan kişinin isminin eklenmesi
                pdfFile.AddCreationDate();                         //Oluşturulma tarihinin eklenmesi
                pdfFile.AddAuthor("Hakedis" + applicationVersion); //Yazarın isiminin eklenmesi
                pdfFile.AddHeader(DateTime.Now.ToLongDateString(), "Hakediş " + DateTime.Now.ToLongDateString());
                pdfFile.AddTitle("Hakediş Rapor");                 //Başlık ve title eklenmesi
                #endregion

                #region Tablo Başlık tarih ve marka bilgileri
                PdfPTable markAndDateTable = new PdfPTable(2);
                markAndDateTable.TotalWidth         = 250f;
                markAndDateTable.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;

                PdfPCell markName = new PdfPCell(new Phrase("Hakediş " + applicationVersion, fontArialbold));
                markName.HorizontalAlignment = Element.ALIGN_LEFT;
                markName.VerticalAlignment   = Element.ALIGN_LEFT;
                markName.Border = 0;

                PdfPCell dateTimeReport = new PdfPCell(new Phrase(DateTime.Now.ToLongDateString(), fontArialbold));
                dateTimeReport.VerticalAlignment   = Element.ALIGN_RIGHT;
                dateTimeReport.HorizontalAlignment = Element.ALIGN_RIGHT;
                dateTimeReport.Border = 0;
                dateTimeReport.ExtraParagraphSpace = 5f;

                markAndDateTable.AddCell(markName);
                markAndDateTable.AddCell(dateTimeReport);
                #endregion

                #region Veri Tablosu İşlemleri

                #region Pdf Kolon Başlıklarını Belirleme
                int       columnCount     = dataGridView.Columns.Count;
                PdfPTable pdfColumnheader = new PdfPTable(columnCount - 2);
                pdfColumnheader.TotalWidth         = 400f;
                pdfColumnheader.LockedWidth        = true;
                pdfColumnheader.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
                if (selectedParameter == true)
                {
                    for (int i = 0; i < columnCount; i++)
                    {
                        if (i != 0 && i != 1)
                        {
                            PdfPCell columnName = new PdfPCell(new Phrase(dataGridView.Columns[i].HeaderText, fontArialHeader));
                            columnName.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                            columnName.VerticalAlignment   = PdfPCell.ALIGN_MIDDLE;
                            columnName.FixedHeight         = 30f;
                            columnName.Border = 1;
                            pdfColumnheader.AddCell(columnName);
                        }
                    }
                }
                else
                {
                    pdfColumnheader = new PdfPTable(columnCount - 1);
                    for (int i = 0; i < columnCount; i++)
                    {
                        if (i != 0)
                        {
                            PdfPCell columnName = new PdfPCell(new Phrase(dataGridView.Columns[i].HeaderText, fontArialHeader));
                            columnName.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                            columnName.VerticalAlignment   = PdfPCell.ALIGN_MIDDLE;
                            columnName.FixedHeight         = 30f;
                            columnName.Border = 1;
                            pdfColumnheader.AddCell(columnName);
                        }
                    }
                }

                #region Satır işlemleri

                int       rowsCount    = dataGridView.Rows.Count;
                PdfPTable pdfDataTable = new PdfPTable(columnCount - 2);
                if (selectedParameter == true)
                {
                    for (int i = 0; i <= rowsCount - 1; i++)
                    {
                        for (int j = 0; j < dataGridView.Rows[i].Cells.Count; j++)
                        {
                            if (j != 0 && j != 2)
                            {
                                PdfPCell cell2 = new PdfPCell(new Phrase(dataGridView.Rows[i].Cells[j].Value.ToString(), fontArial));
                                pdfDataTable.AddCell(cell2);
                            }
                        }
                    }
                }
                else
                {
                    pdfDataTable = new PdfPTable(columnCount - 1);
                    for (int i = 0; i <= rowsCount - 1; i++)
                    {
                        for (int j = 0; j < dataGridView.Rows[i].Cells.Count; j++)
                        {
                            if (j != 0)
                            {
                                PdfPCell cell2 = new PdfPCell(new Phrase(dataGridView.Rows[i].Cells[j].Value.ToString(), fontArial));
                                pdfDataTable.AddCell(cell2);
                            }
                        }
                    }
                }


                #endregion

                #region Toplam Bilgi Verileri
                PdfPTable tableTotalInfo = new PdfPTable(2);
                tableTotalInfo.TotalWidth         = 250f;
                tableTotalInfo.LockedWidth        = true;
                tableTotalInfo.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
                double totalManOfDay = 0;
                if (selectedParameter == true)
                {
                    for (int i = 0; i < dataGridView.Rows.Count; i++)
                    {
                        totalManOfDay += double.Parse(dataGridView.Rows[i].Cells[6].Value.ToString());
                    }
                }
                else
                {
                    for (int i = 0; i < dataGridView.Rows.Count; i++)
                    {
                        totalManOfDay += double.Parse(dataGridView.Rows[i].Cells[2].Value.ToString());
                    }
                }

                PdfPCell cellTotalManOfDay = new PdfPCell(new Phrase(totalManOfDay.ToString(), fontArial));
                cellTotalManOfDay.HorizontalAlignment = Element.ALIGN_CENTER;
                cellTotalManOfDay.VerticalAlignment   = Element.ALIGN_LEFT;
                PdfPCell cellTotal = new PdfPCell(new Phrase("Toplam İş Günü", fontArial));
                cellTotal.HorizontalAlignment = Element.ALIGN_CENTER;
                cellTotal.VerticalAlignment   = Element.ALIGN_LEFT;
                tableTotalInfo.AddCell(cellTotal);
                tableTotalInfo.AddCell(cellTotalManOfDay);
                #endregion

                #endregion

                #region Pdf Dosyasını yaz ve kapat
                if (pdfFile.IsOpen() == false)
                {
                    pdfFile.Open();
                }
                pdfFile.Add(markAndDateTable);
                pdfFile.Add(p);
                pdfFile.Add(pdfColumnheader);
                pdfFile.Add(p);
                pdfFile.Add(pdfDataTable);
                pdfFile.Add(p);
                pdfFile.Add(tableTotalInfo);
                //pdfFile.Add(p);
                //pdfFile.Add(p);
                //pdfFile.Add(p);
                //pdfFile.Add(nameSurname);
                //pdfFile.Add(p);
                //pdfFile.Add(signature);
                pdfFile.Close();
                #endregion
                #endregion
            }
            #endregion
        }
Exemplo n.º 48
0
        private void button6_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count == 0)
            {
                MessageBox.Show("Search Data & Try Again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            else
            {
                var pgSize = new iTextSharp.text.Rectangle(841, 594);
                var doc    = new iTextSharp.text.Document(pgSize, 22, 22, 22, 22);

                PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "\\Documents\\Item List" + DateTime.Now.Date.ToString("ddMMyyyy") + ".pdf", FileMode.Create));



                MessageBox.Show("Your Document Is Ready To Be Printed. Press OK Button.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);

                doc.Open();

                iTextSharp.text.Image headerImage = iTextSharp.text.Image.GetInstance("logo.jpg");
                headerImage.ScalePercent(16f);
                headerImage.SetAbsolutePosition(doc.PageSize.Width - 510f - 22f, doc.PageSize.Height - 30f - 16f);
                //doc.Add(headerImage);

                iTextSharp.text.Font fontTitle = FontFactory.GetFont("Arial", 16, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

                Paragraph title = new Paragraph(shopName, fontTitle);

                title.Alignment = Element.ALIGN_CENTER;

                doc.Add(title);



                iTextSharp.text.Font fontAddress = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

                Paragraph address = new Paragraph(shopAddress, fontAddress);

                address.Alignment = Element.ALIGN_CENTER;

                doc.Add(address);


                iTextSharp.text.Font fontTable3 = FontFactory.GetFont("Times New Roman", 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);


                PdfPTable tableInfo = new PdfPTable(3);

                tableInfo.SpacingBefore   = 16f;
                tableInfo.WidthPercentage = 100;
                PdfPCell cell = new PdfPCell(new Phrase("Item List"));

                cell.Colspan = 3;

                cell.HorizontalAlignment = 1;

                cell.BackgroundColor = BaseColor.LIGHT_GRAY;

                tableInfo.AddCell(cell);

                tableInfo.AddCell(new Phrase("Time: " + DateTime.Now.ToString("hh:mm:ss tt"), fontTable3));
                tableInfo.AddCell(new Phrase("Date: " + DateTime.Now.ToString("dd/MM/yyyy"), fontTable3));
                tableInfo.AddCell(new Phrase("Printed By: " + realName, fontTable3));
                tableInfo.AddCell(new Phrase("Search By: " + comboBoxSearchBy.Text, fontTable3));
                tableInfo.AddCell(new Phrase("Query: " + textBoxQuery.Text, fontTable3));
                tableInfo.AddCell(new Phrase("Date Period: Not Applicable", fontTable3));
                tableInfo.AddCell(new Phrase("Total Item: " + labelTotalItem.Text, fontTable3));
                tableInfo.AddCell(new Phrase("Total Quantity: Not Applicable", fontTable3));
                tableInfo.AddCell(new Phrase("Total Price: Not Applicable", fontTable3));


                doc.Add(tableInfo);



                iTextSharp.text.Font fontTable = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

                PdfPTable table = new PdfPTable(dataGridView1.Columns.Count - 1);

                table.SpacingBefore       = 2f;
                table.WidthPercentage     = 100;
                table.HorizontalAlignment = Element.ALIGN_CENTER;

                for (int j = 1; j < dataGridView1.Columns.Count; j++)
                {
                    table.AddCell(new Phrase(dataGridView1.Columns[j].HeaderText, fontTable));
                }

                table.HeaderRows = 1;

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    for (int k = 1; k < dataGridView1.Columns.Count; k++)
                    {
                        if (dataGridView1[k, i].Value != null)
                        {
                            table.AddCell(new Phrase(dataGridView1[k, i].Value.ToString(), fontTable));
                        }
                    }
                }

                doc.Add(table);

                iTextSharp.text.Font footerFont = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
                Paragraph            footer     = new Paragraph("", footerFont);
                footer.SpacingBefore = 20f;
                footer.Alignment     = Element.ALIGN_RIGHT;
                doc.Add(footer);


                doc.Close();



                System.Diagnostics.Process.Start(System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "\\Documents\\Item List" + DateTime.Now.Date.ToString("ddMMyyyy") + ".pdf");
            }
        }
        public void ExportInvoicePDF(DataTable dataTable, String savePath, string title)
        {
            System.IO.FileStream     fs       = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None);
            iTextSharp.text.Document document = new iTextSharp.text.Document();
            document.SetPageSize(iTextSharp.text.PageSize.A4);
            PdfWriter writer = PdfWriter.GetInstance(document, fs);

            document.Open();

            //Report Header
            BaseFont  bfntHead   = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Paragraph prgHeading = new Paragraph();

            prgHeading.Alignment = Element.ALIGN_CENTER;
            prgHeading.Add(new Chunk(title.ToUpper()));
            document.Add(prgHeading);

            //Author
            Paragraph prgData = new Paragraph();
            BaseFont  btnData = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

            prgData.Alignment = Element.ALIGN_RIGHT;
            prgData.Add(new Chunk("Series : 167141"));
            prgData.Add(new Chunk("\nNumber : 000564363"));
            prgData.Add(new Chunk("\nDate : " + DateTime.Now.ToShortDateString()));
            document.Add(prgData);

            //Add a line seperation
            Paragraph p = new Paragraph();

            document.Add(p);

            //Add line break
            document.Add(new Chunk("\n"));
            document.Add(new Chunk("A.C.E. Craiova.\n"));
            document.Add(new Chunk("Address : Str. A. I. Cuza Nr.13.\n"));
            document.Add(new Chunk("City : Craiova, Dolj\n"));
            document.Add(new Chunk("Tel. : 0251788787.\n"));
            document.Add(new Chunk("\n"));
            document.Add(new Chunk("\n"));

            //Write the table
            PdfPTable table = new PdfPTable(dataTable.Columns.Count);
            //Table header
            BaseFont btnColumnHeader = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                document.Add(new Chunk(dataTable.Columns[i].ColumnName + " : " + dataTable.Rows[0][i].ToString()));
                document.Add(new Chunk("\n"));
            }

            document.Add(new Chunk("\n"));
            document.Add(new Chunk("\n"));
            document.Add(new Chunk("Services : Failed Exam.\n"));
            document.Add(new Chunk("Price : 50 LIONS."));
            document.Add(new Chunk("\n"));

            document.Close();
            writer.Close();
            fs.Close();
        }
Exemplo n.º 50
0
    void CreateFromFolder(string folderPath)
    {
        pdfdoc = new iTextSharp.text.Document();
        pdfdoc.SetPageSize(iTextSharp.text.PageSize.A0);

        Debug.Log("000000");

        string pdfPath = Path.Combine(folderPath, "output.pdf");

        if (File.Exists(pdfPath))
        {
            File.Delete(pdfPath);
        }
        Debug.Log("1111111");

        pdfwriter = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfdoc, new FileStream(pdfPath, FileMode.CreateNew));

        Debug.Log("22222");
        pdfdoc.Open();

        pdfdoc.NewPage();

        string[] paths = Directory.GetFiles(folderPath);

        int rows;
        int columns;

        int rowIndex  = 1;
        int pageIndex = 1;

        float pageWidth  = iTextSharp.text.PageSize.A0.Width;
        float pageHeight = iTextSharp.text.PageSize.A0.Height;

        pdfImg = iTextSharp.text.Image.GetInstance(paths[0]);

        rows    = (int)(pageHeight / pdfImg.Height);
        columns = (int)(pageWidth / pdfImg.Width);
        Debug.Log("Rows:" + rows);
        Debug.Log("Columns:" + columns);

        for (int i = 0; i < paths.Length; i++)
        {
            if (paths[i].EndsWith(".png"))
            {
                Debug.Log(paths[i]);
                pdfImg = iTextSharp.text.Image.GetInstance(paths[i]);

                if (i == columns * rows * pageIndex)
                {
                    pageIndex++;
                    Debug.Log("pageIndex:" + pageIndex);

                    pdfdoc.NewPage();
                    rowIndex = 1;
                    Debug.Log("rowIndex:" + rowIndex);
                }
                else if (i != 0 && i % columns == 0)
                {
                    rowIndex++;
                    Debug.Log("rowIndex:" + rowIndex);
                }
                pdfImg.SetAbsolutePosition(pdfImg.Width * (i % columns), pageHeight - pdfImg.Height * rowIndex);

                pdfdoc.Add(pdfImg);
            }
        }

        pdfdoc.Dispose();
    }
Exemplo n.º 51
0
        private void button1_Click(object sender, EventArgs e)
        {
            var datecombination = listBox1.SelectedValue.ToString();

            datecombination = datecombination.Replace(" To ", " , ");
            var           arrayelement = datecombination.Split(',');
            List <string> queryList    = Utilities.DataBaseUtility.GetList("select distinct start_date,end_date from Timesheets");
            //var stringvalue = String.Format("select e.FirstName,e.LastName,e.Role,g.gross_amt,n.netpay_amt,n.deduction_amt from ((employees e join netpay n on e.DocNum=n.Emp_id) join grosspay g on e.docnum=g.emp_id) where e.docNum=104 and n.paystartdate='{0}' and n.payenddate='{1}'", arrayelement[0].Substring(0, arrayelement[0].Length - 15).Trim(), arrayelement[1].Substring(0, arrayelement[0].Length - 14).Trim());
            int employeeID = 0;

            try
            {
                employeeID = Convert.ToInt32(employeesAdmin.Text);
            }
            catch (Exception ex)
            {
                employeeID = 104;
            }

            if (employeeID < 111 && employeeID > 100)
            {
            }
            else
            {
                employeeID = 104;
            }
            arrayelement[0] = arrayelement[0].Remove(arrayelement[0].Length - 15);

            //var stringvalue = "SELECT e.FirstName,e.LastName,e.Role,n.netpay_amt,n.deduction_amt from employees e inner join netpay n on e.DocNum=n.Emp_id";
            var stringvalue = "SELECT * FROM ([employees] AS [e] INNER JOIN [grosspay] AS [g] ON [e].[DocNum] = [g].[emp_id]) INNER JOIN [NETPAY] AS [N] ON [N].[emp_id]=[e].[DocNum] where [e].docNum=" + employeeID + " and [g].PayStartDate like '%" + arrayelement[0] + "%' and [N].PayStartDate like '%" + arrayelement[0] + "%'";
            //var stringvalue = String.Format("SELECT EMPLOYEES.FirstName, EMPLOYEES.Role, EMPLOYEES.gross_amt, EMPLOYEES.Role, NetPay.NetPay_Amt, NetPay.Benefits_Amt, NetPay.Deductions_Amt, GrossPay.GrossPay, GrossPay.PayStartDate, GrossPay.PayEndDateFROM EMPLOYEES, NetPay, GrossPay;");
            var value = Utilities.DataBaseUtility.GetList(stringvalue);

            String[] finalValue = value[1].Split(',');

            if (button1.Text.Equals("Download PaySlip"))
            {
                String     path     = System.AppDomain.CurrentDomain.BaseDirectory;
                String     fileName = "payslip.pdf";
                FileStream fs       = new FileStream(System.AppDomain.CurrentDomain.BaseDirectory + fileName, FileMode.Create, FileAccess.Write, FileShare.None);
                iTextSharp.text.Document      doc    = new iTextSharp.text.Document();
                iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, fs);
                doc.Open();
                String spacing   = "                                                                                         ";
                String imagepath = Directory.GetCurrentDirectory();

                imagepath = imagepath.Replace("\\bin\\Debug", "\\Images\\HawkLogo.bmp");
                //  + "\\Images\\HawkLogo.bmp";
                iTextSharp.text.Image gif = iTextSharp.text.Image.GetInstance(imagepath);



                doc.Add(new Paragraph("-------------------------------------PAYSLIP - METRO VIDEO PHOTO -------------------------------------              "));
                doc.Add(gif);
                doc.Add(new Paragraph(spacing + "Employee ID : " + finalValue[0]));
                doc.Add(new Paragraph(spacing + "First Name : " + finalValue[2]));
                doc.Add(new Paragraph(spacing + "Last Name : " + finalValue[3]));
                doc.Add(new Paragraph(spacing + "Email ID : " + finalValue[12]));
                doc.Add(new Paragraph(" "));
                doc.Add(new Paragraph(" "));
                doc.Add(new Paragraph(" "));
                doc.Add(new Paragraph(" "));
                doc.Add(new Paragraph(" "));
                doc.Add(new Paragraph("Pay Period:"));
                doc.Add(new Paragraph("Start Date : " + finalValue[23]));
                doc.Add(new Paragraph("--------------------------------------------"));
                doc.Add(new Paragraph("End Date : " + finalValue[24]));
                doc.Add(new Paragraph("---------------------------"));
                doc.Add(new Paragraph("Total Overtime Pay : " + finalValue[25]));
                doc.Add(new Paragraph("---------------------------------------------"));
                doc.Add(new Paragraph("Gross Pay : " + finalValue[26]));
                doc.Add(new Paragraph("--------------------------------------------"));
                doc.Add(new Paragraph("Benefit Amount : " + finalValue[31]));
                doc.Add(new Paragraph("--------------------------------------------"));
                doc.Add(new Paragraph("Deduction Amount : " + finalValue[32]));
                doc.Add(new Paragraph("--------------------------------------------"));
                doc.Add(new Paragraph("Final Pay (Net Pay) : " + finalValue[36]));



                doc.Close();
                string FileLocation = System.AppDomain.CurrentDomain.BaseDirectory + fileName;
                //string WatermarkLocation = "C:\\Users\\Prithiviraj\\Desktop\\PDF Document\\Myimage.png";
                String WatermarkLocation = Directory.GetCurrentDirectory();

                WatermarkLocation = WatermarkLocation.Replace("\\bin\\Debug", "\\Applications\\Payroll\\Images\\bgconfidential.png");

                Document document = new Document();
                iTextSharp.text.pdf.PdfReader  pdfReader = new iTextSharp.text.pdf.PdfReader(FileLocation);
                iTextSharp.text.pdf.PdfStamper stamp     = new iTextSharp.text.pdf.PdfStamper(pdfReader, new FileStream(FileLocation.Replace(".pdf", "_" + finalValue[0] + ".pdf"), FileMode.Create));

                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(WatermarkLocation);
                img.SetAbsolutePosition(0, 5); // set the position in the document where you want the watermark to appear (0,0 = bottom left corner of the page)

                iTextSharp.text.pdf.PdfContentByte waterMark;
                for (int page = 1; page <= pdfReader.NumberOfPages; page++)
                {
                    waterMark = stamp.GetUnderContent(page);
                    waterMark.AddImage(img);
                }
                stamp.FormFlattening = true;
                stamp.Close();
                label1.Visible = true;
                label1.Text    = "Your file (payslip.pdf) is succssfully downloaded";
            }

            else if (button1.Text.Equals("View Gross Pay"))
            {
                label1.Visible = true;
                label1.Text    = "Gross Pay";

                heading1.Visible = true;
                heading2.Visible = true;
                heading3.Visible = true;
                heading4.Visible = true;
                heading5.Visible = true;
                heading6.Visible = true;

                value1.Visible = true;
                value2.Visible = true;
                value3.Visible = true;
                value4.Visible = true;
                value5.Visible = true;
                value6.Visible = true;


                heading1.Text = "Employee ID: ";
                heading2.Text = "Regular Hourly Pay Rate: ";
                heading3.Text = "Overtime Hourly Pay Rate: ";
                heading4.Text = "Num of Regular Hours: ";
                heading5.Text = "Num of overtime Hours: ";
                heading6.Text = "Gross Pay: ";

                int regHours      = Convert.ToInt32(finalValue[22]) / Convert.ToInt32(finalValue[20]);
                int overTimeHours = Convert.ToInt32(finalValue[25]) / Convert.ToInt32(finalValue[21]);

                value1.Text = finalValue[0];
                value2.Text = "$" + finalValue[20];
                value3.Text = "$" + finalValue[21];
                value4.Text = regHours.ToString();
                value5.Text = overTimeHours.ToString();
                value6.Text = "$" + finalValue[26];
            }
            else if (button1.Text.Equals("View Net Pay"))
            {
                label1.Visible = true;
                label1.Text    = "Net Pay";

                heading1.Visible = true;
                heading2.Visible = true;
                heading3.Visible = true;
                heading4.Visible = true;
                heading5.Visible = true;
                //  heading6.Visible = true;

                value1.Visible = true;
                value2.Visible = true;
                value3.Visible = true;
                value4.Visible = true;
                value5.Visible = true;
                //   value6.Visible = true;


                heading1.Text = "Employee ID: ";
                heading2.Text = "Gross Pay: ";
                heading3.Text = "Total Benefits: ";
                heading4.Text = "Total Deductions: ";
                heading5.Text = "Net Pay: ";
                //  heading6.Text = "Gross Pay: ";

                value1.Text = finalValue[0];
                value2.Text = "$" + finalValue[26];
                value3.Text = "$" + finalValue[31];
                value4.Text = "$" + finalValue[32];
                value5.Text = "$" + finalValue[36];
                // value6.Text = finalValue[26];
            }
        }
Exemplo n.º 52
0
 public override void OnOpenDocument(PdfWriter writer, iTextSharp.text.Document document)
 {
     total = writer.DirectContent.CreateTemplate(40, 16);
 }
Exemplo n.º 53
0
    void CreateFromRawdataFile(string sourceTxtPath, string destinationPDFPath)
    {
        pdfdoc = new iTextSharp.text.Document();
        pdfdoc.SetPageSize(currentPageSize);

        gridCountInBlockRowHorizontal = (int)(currentPageSize.Width / gridSideLength);
        blockRowHeight         = gridSideLength * gridCountInBlockRowVertical;
        blockRowCount          = (int)(currentPageSize.Height / (blockRowHeight + blockRowInterval));
        rawDataCountInBlockRow = (int)(gridCountInBlockRowHorizontal * 40 * 512 / 1000);
        rawDataInterval        = currentPageSize.Width / rawDataCountInBlockRow;

        Debug.Log("gridCountInBlockRowHorizontal:" + gridCountInBlockRowHorizontal);
        Debug.Log("rawDataCountInBlockRow" + rawDataCountInBlockRow);

        if (File.Exists(destinationPDFPath))
        {
            File.Delete(destinationPDFPath);
        }

        pdfwriter = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfdoc, new FileStream(destinationPDFPath, FileMode.CreateNew));

        pdfdoc.Open();

        iTextSharp.text.pdf.PdfContentByte cb = pdfwriter.DirectContent;

        pdfdoc.NewPage();
        blockRowIndex = 0;
        rawDataIndex  = 0;

        iTextSharp.text.pdf.BaseFont font = iTextSharp.text.pdf.BaseFont.CreateFont();
        cb.SetFontAndSize(font, 60);
        cb.BeginText();
        cb.SetTextMatrix(100, currentPageSize.Height - 50);
        cb.ShowText("Test String .......");
        cb.EndText();

        System.IO.StreamReader reader = new StreamReader(sourceTxtPath);
        string theLine;
        int    rawData;

        while (!reader.EndOfStream)
        {
            theLine = reader.ReadLine();
            try{
                rawData = int.Parse(theLine);
            }catch (Exception e) {
                Debug.Log("Exception");
                continue;
            }

            rawData       = rawData > maxRawData ? maxRawData : rawData;
            rawData       = rawData < -maxRawData ? -maxRawData : rawData;
            scaledRawData = (rawData * (blockRowHeight / 2)) / maxRawData;

            if (rawDataIndex == 0)
            {
                currentBaseLine = currentPageSize.Height - (firstBlockRowOffsetInVertical + blockRowIndex * (blockRowHeight + blockRowInterval) + (blockRowHeight / 2));

                cb.SetColorStroke(iTextSharp.text.BaseColor.RED);

                //draw horizontal lines
                for (int i = 0; i <= gridCountInBlockRowVertical; i++)
                {
                    if (i % 5 == 0)
                    {
                        cb.SetLineWidth(2.5f);
                    }
                    else
                    {
                        cb.SetLineWidth(0.5f);
                    }
                    cb.MoveTo(0, currentPageSize.Height - (firstBlockRowOffsetInVertical + blockRowIndex * (blockRowHeight + blockRowInterval) + i * gridSideLength));
                    cb.LineTo(currentPageSize.Width, currentPageSize.Height - (firstBlockRowOffsetInVertical + blockRowIndex * (blockRowHeight + blockRowInterval) + i * gridSideLength));
                    cb.Stroke();
                }

                //draw vertical lines
                for (int j = 0; j <= gridCountInBlockRowHorizontal; j++)
                {
                    if (j % 5 == 0)
                    {
                        cb.SetLineWidth(2.5f);
                    }
                    else
                    {
                        cb.SetLineWidth(0.5f);
                    }
                    cb.MoveTo(j * gridSideLength, currentPageSize.Height - (firstBlockRowOffsetInVertical + blockRowIndex * (blockRowHeight + blockRowInterval)));
                    cb.LineTo(j * gridSideLength, currentPageSize.Height - (firstBlockRowOffsetInVertical + blockRowIndex * (blockRowHeight + blockRowInterval) + blockRowHeight));
                    cb.Stroke();
                }
                //prepare to draw ECG
                cb.SetLineWidth(1.5f);
                cb.SetColorStroke(iTextSharp.text.BaseColor.BLACK);

                cb.MoveTo(0, currentBaseLine);
            }

            cb.LineTo(rawDataIndex * rawDataInterval, currentBaseLine + scaledRawData);
            rawDataIndex++;
            if (rawDataIndex >= rawDataCountInBlockRow)
            {
                cb.Stroke();
                rawDataIndex = 0;
                blockRowIndex++;
            }
        }
        cb.Stroke();
        reader.Close();



        pdfdoc.Dispose();
        System.Diagnostics.Process.Start(destinationPDFPath);
    }
Exemplo n.º 54
0
        public void Arrange(Supply sup)
        {
            try
            {
                string FileName = "Накладная №" + sup.Id + ".pdf";
                iTextSharp.text.Document doc = new iTextSharp.text.Document();
                PdfWriter.GetInstance(doc, new FileStream(FileName, FileMode.Create));

                doc.Open();

                BaseFont             baseFont = BaseFont.CreateFont("C:/Windows/Fonts/arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                iTextSharp.text.Font font     = new iTextSharp.text.Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.NORMAL);

                Paragraph par = new Paragraph("от " + DateTime.Parse(sup.ArrangementDate.ToString()).ToShortDateString(), font);
                par.Alignment = Element.ALIGN_RIGHT;
                doc.Add(par);

                font.Size     = 24;
                par           = new Paragraph("НАКЛАДНАЯ №" + sup.Id, font);
                par.Alignment = Element.ALIGN_CENTER;
                doc.Add(par);

                font.Size = iTextSharp.text.Font.DEFAULTSIZE;
                par       = new Paragraph("Кому: ООО \"Sirius Smoke\"", font);
                par.SetLeading(font.Size, 2);
                par.Alignment = Element.ALIGN_LEFT;
                doc.Add(par);

                font.Size = iTextSharp.text.Font.DEFAULTSIZE;
                string provider = db.getProviders().Where(i => i.Id == sup.ProviderId).Select(i => i.CompanyName).FirstOrDefault().ToString();
                par = new Paragraph("От кого: " + provider, font);
                par.SetLeading(font.Size, 2);
                par.Alignment = Element.ALIGN_LEFT;
                doc.Add(par);

                PdfPTable table = new PdfPTable(4);
                table.SpacingBefore = 20;
                PdfPCell HeaderCell = new PdfPCell(new Phrase("Наименование", font));
                HeaderCell.HorizontalAlignment = 1;
                table.AddCell(HeaderCell);
                HeaderCell = new PdfPCell(new Phrase("Количество", font));
                HeaderCell.HorizontalAlignment = 1;
                table.AddCell(HeaderCell);
                HeaderCell = new PdfPCell(new Phrase("Цена единицы товара, р", font));
                HeaderCell.HorizontalAlignment = 1;
                table.AddCell(HeaderCell);
                HeaderCell = new PdfPCell(new Phrase("Общая стоимость, р", font));
                HeaderCell.HorizontalAlignment = 1;
                table.AddCell(HeaderCell);

                decimal TotalSum      = 0;
                int     TotalQuantity = 0;

                foreach (SupplyLine item in sup.Lines)
                {
                    PdfPCell BasicCell = new PdfPCell(new Phrase(item.CommodityName.ToString(), font));
                    BasicCell.HorizontalAlignment = 1;
                    table.AddCell(BasicCell);
                    BasicCell = new PdfPCell(new Phrase(item.Quantity.ToString() + " шт.", font));
                    BasicCell.HorizontalAlignment = 1;
                    table.AddCell(BasicCell);
                    BasicCell = new PdfPCell(new Phrase((item.Cost / item.Quantity).ToString(), font));
                    BasicCell.HorizontalAlignment = 1;
                    table.AddCell(BasicCell);
                    BasicCell = new PdfPCell(new Phrase((item.Cost).ToString(), font));
                    BasicCell.HorizontalAlignment = 1;
                    table.AddCell(BasicCell);
                    TotalQuantity += item.Quantity;
                    TotalSum      += item.Cost;
                }
                HeaderCell = new PdfPCell(new Phrase("Итого", font));
                HeaderCell.HorizontalAlignment = 1;
                table.AddCell(HeaderCell);
                HeaderCell = new PdfPCell(new Phrase(TotalQuantity.ToString() + " шт.", font));
                HeaderCell.HorizontalAlignment = 1;
                table.AddCell(HeaderCell);
                HeaderCell = new PdfPCell(new Phrase("", font));
                HeaderCell.HorizontalAlignment = 1;
                table.AddCell(HeaderCell);
                HeaderCell = new PdfPCell(new Phrase(TotalSum.ToString(), font));
                HeaderCell.HorizontalAlignment = 1;
                table.AddCell(HeaderCell);
                table.WidthPercentage = 95;

                doc.Add(table);

                font.Size     = iTextSharp.text.Font.DEFAULTSIZE;
                par           = new Paragraph("Принял: ______________ ______________________", font);
                par.Alignment = Element.ALIGN_LEFT;
                par.SetLeading(font.Size, 2);
                doc.Add(par);

                font.Size     = iTextSharp.text.Font.DEFAULTSIZE - 2;
                par           = new Paragraph("                         подпись                                 Ф.И.О", font);
                par.Alignment = Element.ALIGN_LEFT;
                doc.Add(par);
                doc.Close();
                MessageBox.Show("Файл накладной \"" + FileName + "\" создан");
            }
            catch (IOException ex)
            {
                MessageBox.Show("Возникла ошибка при записи страниц", ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Возникла ошибка", ex.Message);
            }
        }
Exemplo n.º 55
0
 public override void OnCloseDocument(PdfWriter writer, iTextSharp.text.Document document)
 {
     ColumnText.ShowTextAligned(total, Element.ALIGN_LEFT, new Phrase((writer.CurrentPageNumber - 1).ToString(), font2), 4, 4, 0);
 }
Exemplo n.º 56
0
    protected void btnExport_Click(object sender, EventArgs e)
    { //String HTML = "resources/xml/walden.html";
      //String CSS = "resources/xml/walden.css";
      //String DEST = "results/xmlworker/walden3.pdf";

        //string filename = "Application";
        //Response.ContentType = "application/pdf";
        //Response.AddHeader("content-disposition", "attachment;filename="+ filename+".pdf");
        //Response.Cache.SetCacheability(HttpCacheability.NoCache);
        //StringWriter sw = new StringWriter();
        //HtmlTextWriter hw = new HtmlTextWriter(sw);
        //Pdfsave.RenderControl(hw);
        //StringReader sr = new StringReader(sw.ToString());
        ////Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
        //Document pdfDoc = new Document(PageSize.A4, 50, 50, 25, 25);
        //HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        //PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        //pdfDoc.Open();
        //htmlparser.Parse(sr);
        //pdfDoc.Close();
        //Response.Write(pdfDoc);
        //Response.End();

        string         strFileShortName = "Application" + DateTime.Now.Ticks + ".pdf";
        var            memStrOutput     = new MemoryStream();
        StringWriter   strWriter        = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(strWriter);

        Pdfsave.RenderControl(hw);

        StringWriter   strWriter2 = new StringWriter();
        HtmlTextWriter hw2        = new HtmlTextWriter(strWriter2);

        pdfsign.RenderControl(hw2);

        // Server.Execute(pdfurl, strWriter);
        string strHtml = strWriter.ToString();

        strHtml = Regex.Replace(strHtml, "</?(a|A).*?>", "");
        strHtml = strHtml.Replace("\r\n", "");
        string value     = "<hr*?.*?/>";
        Regex  regScript = new Regex(value.ToLower(), RegexOptions.IgnoreCase);

        strHtml = regScript.Replace(strHtml, "");

        string strHtml2 = strWriter2.ToString();

        strHtml2 = Regex.Replace(strHtml2, "</?(a|A).*?>", "");
        strHtml2 = strHtml2.Replace("\r\n", "");
        strHtml2 = regScript.Replace(strHtml2, "");

        using (iTextSharp.text.Document docWorkingDocument = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 1, 1, 0, 0))
        {
            PdfWriter pdfWrite = PdfWriter.GetInstance(docWorkingDocument, memStrOutput);
            docWorkingDocument.Open();
            try
            {
                StringReader srOutDoc = new StringReader(strHtml);
                XMLWorkerHelper.GetInstance().ParseXHtml(pdfWrite, docWorkingDocument, srOutDoc);
                docWorkingDocument.NewPage();

                StringReader srOutDoc2 = new StringReader(strHtml2);
                XMLWorkerHelper.GetInstance().ParseXHtml(pdfWrite, docWorkingDocument, srOutDoc2);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment; filename=" + strFileShortName);
        Response.BinaryWrite(memStrOutput.ToArray());
    }
Exemplo n.º 57
0
        public string PrintVoucher(ReceiptVoucherHeader pvh, List <ReceiptVoucherDetail> rvDetails)
        {
            string fileName = "";
            string payMode  = "";

            if (pvh.BookType.Equals("BANKBOOK"))
            {
                payMode = "Bank";
            }
            else
            {
                payMode = "Cash";
            }
            //string HeaderString = "No; " + pvh.VoucherNo + ";Date; " + pvh.VoucherDate.ToString("dd-MM-yyyy") +
            //                ";Received Through;" + payMode + ";Payer;" + pvh.SLName + ";Amount;" + pvh.VoucherAmount + ";Amount In Words;" + NumberToString.convert(pvh.VoucherAmount.ToString()) +
            //                ";Narration;" + pvh.Narration;
            string HeaderString = "No : " + pvh.VoucherNo + Main.delimiter1 + "Date : " + pvh.VoucherDate.ToString("dd-MM-yyyy") +
                                  Main.delimiter1 + "Receipt Mode" + Main.delimiter1 + payMode + Main.delimiter1 + "Received From" + Main.delimiter1 +
                                  pvh.SLName + Main.delimiter1 + "Amount(" + pvh.CurrencyID + ")" + Main.delimiter1 + pvh.VoucherAmount +
                                  Main.delimiter1 + "Amount In Words" + Main.delimiter1 +
                                  NumberToString.convert(pvh.VoucherAmount.ToString()).Trim().Replace("INR", pvh.CurrencyID) +
                                  Main.delimiter1 + "Narration" + Main.delimiter1 + pvh.Narration;
            string ColHeader       = "SI No.;Bill No;Date;Amount(" + pvh.CurrencyID + ");Account Name";
            string footer3         = "Receiver's Signature;Authorised Signatory";
            int    n               = 1;
            string ColDetailString = "";
            var    count           = rvDetails.Count();

            List <string> billNos   = new List <string>();
            List <string> billDates = new List <string>();

            string[] billdetail = pvh.BillDetails.Split(Main.delimiter2); // 0: doctype, 1: billno, 2 : billdate
            foreach (string str in billdetail)
            {
                if (str.Trim().Length != 0)
                {
                    string[] subStr = str.Split(Main.delimiter1);
                    billNos.Add(subStr[1]);
                    billDates.Add(Convert.ToDateTime(subStr[2]).ToString("dd-MM-yyyy"));
                }
            }

            //string[] billdetail = pvh.BillDetails.Split(Main.delimiter1); // 0: doctype, 1: billno, 2 : billdate
            foreach (ReceiptVoucherDetail rvd in rvDetails)
            {
                if (rvd.AmountDebit != 0)
                {
                    if (pvh.BillDetails.Trim().Length != 0)
                    {
                        ColDetailString = ColDetailString + n + Main.delimiter1 + String.Join(",", billNos.ToArray()) + Main.delimiter1 +
                                          string.Join(",", billDates.ToArray()) +
                                          Main.delimiter1 + rvd.AmountDebit + Main.delimiter1
                                          + rvd.AccountName + Main.delimiter2;
                    }
                    else
                    {
                        ColDetailString = ColDetailString + n + Main.delimiter1 + "" + Main.delimiter1 +
                                          "" +
                                          Main.delimiter1 + rvd.AmountDebit + Main.delimiter1
                                          + rvd.AccountName + Main.delimiter2;
                    }
                    n++;
                }
            }

            //var count = rvDetails.Count();
            //foreach (ReceiptVoucherDetail rvd in rvDetails)
            //{
            //    if(n == count)
            //        ColDetailString = ColDetailString + n + "+" + rvd.BillNo + "+" + rvd.BillDate.ToString("dd-MM-yyyy") + "+" + rvd.AmountCredit + "+"
            //                            + rvd.AccountNameCredit;
            //    else
            //        ColDetailString = ColDetailString + n + "+" + rvd.BillNo + "+" + rvd.BillDate.ToString("dd-MM-yyyy") + "+" + rvd.AmountCredit + "+"
            //                            + rvd.AccountNameCredit + ";";
            //    //totQuant = totQuant + pod.Quantity;
            //    //totAmnt = totAmnt + (pod.Quantity * pod.Price);
            //    n++;
            //}
            try
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Title            = "Save As PDF";
                sfd.Filter           = "Pdf files (*.Pdf)|*.pdf";
                sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                sfd.FileName         = pvh.DocumentID + "-" + pvh.VoucherNo;
                if (sfd.ShowDialog() == DialogResult.Cancel || sfd.FileName == "")
                {
                    return("");
                }
                FileStream fs = new FileStream(sfd.FileName, FileMode.Create, FileAccess.Write);
                fileName = sfd.FileName;
                Rectangle rec = new Rectangle(PageSize.A4);
                iTextSharp.text.Document doc = new iTextSharp.text.Document(rec);
                PdfWriter writer             = PdfWriter.GetInstance(doc, fs);
                MyEvent   evnt = new MyEvent();
                writer.PageEvent = evnt;

                doc.Open();
                Font font1 = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
                Font font2 = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
                Font font3 = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.ITALIC, BaseColor.BLACK);
                //String imageURL = @"D:\Smrutiranjan\PurchaseOrder\index.jpg";
                //iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageURL);
                String URL = "Cellcomm2.JPG";
                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(URL);
                img.Alignment = Element.ALIGN_LEFT;

                PdfPTable tableMain = new PdfPTable(2);
                tableMain.WidthPercentage = 100;
                PdfPCell  cellImg = new PdfPCell();
                Paragraph pp      = new Paragraph();
                pp.Add(new Chunk(img, 0, 0));
                cellImg.AddElement(pp);
                cellImg.Border = 0;
                tableMain.AddCell(cellImg);
                PdfPCell        cellAdd = new PdfPCell();
                Paragraph       ourAddr = new Paragraph("");
                CompanyDetailDB compDB  = new CompanyDetailDB();
                cmpnydetails    det     = compDB.getdetails().FirstOrDefault(comp => comp.companyID == 1);
                if (det != null)
                {
                    string addr = det.companyname + "\n" + det.companyAddress;
                    ourAddr           = new Paragraph(new Phrase(addr, font2));
                    ourAddr.Alignment = Element.ALIGN_RIGHT;
                }
                cellAdd.AddElement(ourAddr);
                cellAdd.Border = 0;
                tableMain.AddCell(cellAdd);

                Paragraph paragraph2 = new Paragraph(new Phrase("Receipt Voucher", font2));
                paragraph2.Alignment = Element.ALIGN_CENTER;

                //PrintPurchaseOrder prog = new PrintPurchaseOrder();
                string[] HeaderStr = HeaderString.Split(Main.delimiter1);

                PdfPTable table = new PdfPTable(4);

                table.SpacingBefore   = 20f;
                table.WidthPercentage = 100;
                float[] HWidths = new float[] { 2f, 1f, 1f, 2f };
                table.SetWidths(HWidths);
                PdfPCell cell = null;
                for (int i = 0; i < HeaderStr.Length; i++)
                {
                    if ((i % 2) != 0)
                    {
                        cell                     = new PdfPCell(new Phrase(HeaderStr[i].Trim(), font1));
                        cell.Colspan             = 3;
                        cell.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
                        table.AddCell(cell);
                    }
                    else
                    {
                        table.AddCell(new PdfPCell(new Phrase(HeaderStr[i].Trim(), font1)));
                    }
                    //if (i > 4 && (i % 2) != 0)
                    //{
                    //    if (i % 2 == 0)
                    //    {
                    //        cell = new PdfPCell(new Phrase(HeaderStr[i].Trim(), font2));
                    //    }
                    //    else
                    //        cell = new PdfPCell(new Phrase(HeaderStr[i].Trim(), font1));
                    //    cell.Colspan = 3;
                    //    cell.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
                    //    table.AddCell(cell);
                    //}
                    //else
                    //{
                    //    if (i % 2 == 0)
                    //    {
                    //        table.AddCell(new PdfPCell(new Phrase(HeaderStr[i].Trim(), font2)));
                    //    }
                    //    else
                    //        table.AddCell(new PdfPCell(new Phrase(HeaderStr[i].Trim(), font1)));
                    //}
                }
                Paragraph paragraph3 = new Paragraph(new Phrase("Bill Details", font2));
                paragraph3.Alignment     = Element.ALIGN_CENTER;
                paragraph3.SpacingBefore = 10;
                paragraph3.SpacingAfter  = 10;
                string[] ColHeaderStr = ColHeader.Split(';');

                PdfPTable table1 = new PdfPTable(5);
                table1.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                table1.WidthPercentage = 100;
                float[] width = new float[] { 0.5f, 2f, 3f, 3f, 7f };
                table1.SetWidths(width);

                for (int i = 0; i < ColHeaderStr.Length; i++)
                {
                    PdfPCell hcell = new PdfPCell(new Phrase(ColHeaderStr[i].Trim(), font2));
                    hcell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                    table1.AddCell(hcell);
                }
                //---
                PdfPCell foot = new PdfPCell(new Phrase(""));
                foot.Colspan        = 5;
                foot.BorderWidthTop = 0;
                foot.MinimumHeight  = 0.5f;
                table1.AddCell(foot);

                table1.HeaderRows = 2;
                table1.FooterRows = 1;

                table1.SkipFirstHeader = false;
                table1.SkipLastFooter  = true;
                //---
                string[] DetailStr = ColDetailString.Split(Main.delimiter2);
                float    hg        = 0f;
                for (int i = 0; i < DetailStr.Length; i++)
                {
                    if (DetailStr[i].Length != 0)
                    {
                        hg = table1.GetRowHeight(i + 1);
                        string[] str = DetailStr[i].Split(Main.delimiter1);
                        for (int j = 0; j < str.Length; j++)
                        {
                            PdfPCell pcell;
                            //if (j == 1 || j == 3 || j == 4)
                            //{
                            //    pcell = new PdfPCell(new Phrase(str[j], font2));
                            //}
                            //else
                            pcell = new PdfPCell(new Phrase(str[j], font1));
                            pcell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                            table1.AddCell(pcell);
                        }
                    }
                    //hg = table1.GetRowHeight(i + 1);
                    //string[] str = DetailStr[i].Split('+');
                    //for (int j = 0; j < str.Length; j++)
                    //{
                    //    PdfPCell pcell;
                    //    if (j == 1 || j == 3 || j == 4)
                    //    {
                    //        pcell = new PdfPCell(new Phrase(str[j], font2));
                    //    }
                    //    else
                    //        pcell = new PdfPCell(new Phrase(str[j], font1));
                    //    pcell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                    //    table1.AddCell(pcell);
                    //}
                }
                string[] ft = footer3.Split(';');

                PdfPTable tableFooter = new PdfPTable(3);
                tableFooter.SpacingBefore = 30;
                tableFooter.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                tableFooter.WidthPercentage = 100;
                PdfPCell fcell1 = new PdfPCell(new Phrase(ft[0], font2));
                fcell1.Border = 0;
                fcell1.HorizontalAlignment = PdfPCell.ALIGN_CENTER;

                PdfPCell fcell2 = new PdfPCell(new Phrase(ft[1], font2));
                fcell2.Border = 0;
                fcell2.HorizontalAlignment = PdfPCell.ALIGN_CENTER;

                PdfPCell fcell3 = new PdfPCell();
                fcell3.Border = 0;

                tableFooter.AddCell(fcell1);
                tableFooter.AddCell(fcell3);
                tableFooter.AddCell(fcell2);
                if (table1.Rows.Count > 10)
                {
                    table1.KeepRowsTogether(table1.Rows.Count - 4, table1.Rows.Count);
                }
                doc.Add(tableMain);
                //doc.Add(img);
                //doc.Add(paragraph1);
                doc.Add(paragraph2);
                doc.Add(table);
                doc.Add(paragraph3);
                doc.Add(table1);
                doc.Add(tableFooter);
                doc.Close();

                //-----watermark
                String wmurl = "";
                if (pvh.status == 98)
                {
                    //cancelled
                    wmurl = "003.png";
                }
                else
                {
                    wmurl = "001.png";
                }

                ////String wmurl = "napproved-1.jpg";
                iTextSharp.text.Image wmimg = iTextSharp.text.Image.GetInstance(URL);
                PrintWaterMark.PdfStampWithNewFile(wmurl, sfd.FileName);
                //-----
                MessageBox.Show("Saved Sucessfully");
            }
            catch (Exception ie)
            {
                MessageBox.Show("Failed to save.\n" + ie.Message);
            }
            return(fileName);
        }
Exemplo n.º 58
0
        public void PrintIndent(indentheader ioh, List <indentdetail> IODetails)
        {
            string[] Purchasesrce = ioh.PurchaseSource.Split(';');
            string   ColHeader    = "SI No.;Item Code;Item Name;Last\nPurcahse\nPrice;Quoted\nPrice;Expected\nPurchase\nPrice" +
                                    ";Quotation\nNo;Quantity;Buffer\nQuantity;Warranty\nDays ";
            int    n = 1;
            string ColDetailString = "";
            var    count           = IODetails.Count();

            foreach (indentdetail iod in IODetails)
            {
                if (n == count)
                {
                    ColDetailString = ColDetailString + n + Main.delimiter1 + iod.StockItemID + Main.delimiter1 + iod.StockItemName + Main.delimiter1 + iod.LastPurchasedPrice + Main.delimiter1
                                      + iod.QuotedPrice + Main.delimiter1 + iod.ExpectedPurchasePrice + Main.delimiter1 + iod.QuotationNo + Main.delimiter1 + iod.Quantity + Main.delimiter1 + iod.BufferQuantity + Main.delimiter1 + iod.WarrantyDays + "\n";
                }
                else
                {
                    ColDetailString = ColDetailString + n + Main.delimiter1 + iod.StockItemID + Main.delimiter1 + iod.StockItemName + Main.delimiter1 + iod.LastPurchasedPrice + Main.delimiter1
                                      + iod.QuotedPrice + Main.delimiter1 + iod.ExpectedPurchasePrice + Main.delimiter1 + iod.QuotationNo + Main.delimiter1 + iod.Quantity + Main.delimiter1 + iod.BufferQuantity + Main.delimiter1 + iod.WarrantyDays + "\n" + Main.delimiter2;
                }
                n++;
            }
            try
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Title            = "Save As PDF";
                sfd.Filter           = "Pdf files (*.Pdf)|*.pdf";
                sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                sfd.FileName         = ioh.DocumentID + "-" + ioh.TemporaryNo;

                if (sfd.ShowDialog() == DialogResult.Cancel || sfd.FileName == "")
                {
                    return;
                }
                FileStream fs  = new FileStream(sfd.FileName, FileMode.Create, FileAccess.Write);
                Rectangle  rec = new Rectangle(PageSize.A4);
                iTextSharp.text.Document doc = new iTextSharp.text.Document(rec);
                PdfWriter writer             = PdfWriter.GetInstance(doc, fs);
                MyEvent   evnt = new MyEvent();
                writer.PageEvent = evnt;

                doc.Open();
                Font   font1        = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
                Font   font2        = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
                Font   font3        = FontFactory.GetFont("Arial", 8, Font.BOLD | Font.UNDERLINE);
                Font   font4        = FontFactory.GetFont("Arial", 7, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
                string HeaderString = "Temporary No : " + ioh.TemporaryNo +
                                      "    Temporary Date : " + String.Format("{0:dd MMMM, yyyy}", ioh.TemporaryDate) + Main.delimiter2 +
                                      "Target Date : " + String.Format("{0:dd MMMM, yyyy}", ioh.TargetDate) + Main.delimiter2 +
                                      "Purchase Source : " + getPurchaseSoursestring(ioh.PurchaseSource);

                Paragraph paragraph = new Paragraph(new Phrase("" + ioh.DocumentName + "", FontFactory.GetFont("Arial", 10, iTextSharp.text.Font.BOLD, BaseColor.BLACK)));
                paragraph.Alignment    = Element.ALIGN_CENTER;
                paragraph.SpacingAfter = 10;

                PdfPTable tableMain = new PdfPTable(1);
                tableMain.WidthPercentage = 100;

                string[] header = HeaderString.Split(Main.delimiter2);
                foreach (string str in header)
                {
                    PdfPCell cell = new PdfPCell(new Phrase(str, font1));
                    cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    cell.Border = 0;
                    tableMain.AddCell(cell);
                }

                if (ioh.DocumentID == "INDENT")
                {
                    System.Data.DataTable dt         = IndentHeaderDB.getPODetailsInDatatable(ioh);
                    PdfPTable             tablePODet = new PdfPTable(7);

                    tablePODet.SpacingBefore   = 10;
                    tablePODet.WidthPercentage = 100;
                    float[] widthmain = new float[] { 2f, 2f, 2f, 2f, 2f, 2f, 5f };
                    tablePODet.SetWidths(widthmain);
                    tablePODet.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;

                    PdfPCell cellHEad = new PdfPCell(new Phrase("Internal Order Detail", font3));
                    cellHEad.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                    cellHEad.Border        = 0;
                    cellHEad.Colspan       = 7;
                    cellHEad.MinimumHeight = 20;
                    tablePODet.AddCell(cellHEad);

                    foreach (DataColumn c in dt.Columns)
                    {
                        tablePODet.AddCell(new Phrase(c.ColumnName, font2));
                    }

                    foreach (DataRow r in dt.Rows)
                    {
                        if (dt.Rows.Count > 0)
                        {
                            tablePODet.AddCell(new Phrase(r[0].ToString(), font1));
                            tablePODet.AddCell(new Phrase(r[1].ToString(), font1));
                            tablePODet.AddCell(new Phrase(r[2].ToString(), font1));
                            tablePODet.AddCell(new Phrase(r[3].ToString(), font1));
                            tablePODet.AddCell(new Phrase(r[4].ToString(), font1));
                            tablePODet.AddCell(new Phrase(r[5].ToString(), font1));
                            tablePODet.AddCell(new Phrase(r[6].ToString(), font1));
                        }
                    }
                    PdfPCell cellPODet = new PdfPCell(tablePODet);
                    cellPODet.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                    cellPODet.Border = 0;
                    tableMain.AddCell(cellPODet);

                    //tableMain.AddCell(cellAdd);
                }
                Paragraph subHeadPara = new Paragraph(new Phrase("Indent Detail", font3));
                subHeadPara.Alignment = Element.ALIGN_CENTER;

                string[] ColHeaderStr = ColHeader.Split(';');

                PdfPTable table1 = new PdfPTable(10);
                table1.SpacingBefore = 10f;
                table1.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                table1.WidthPercentage = 100;
                float[] width = new float[] { 1f, 2f, 4f, 1.2f, 1f, 1.2f, 1.3f, 1.2f, 1.2f, 1.2f };
                table1.SetWidths(width);

                for (int i = 0; i < ColHeaderStr.Length; i++)
                {
                    PdfPCell hcell = new PdfPCell(new Phrase(ColHeaderStr[i].Trim(), font2));
                    hcell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                    table1.AddCell(hcell);
                }

                int      track     = 0;
                string[] DetailStr = ColDetailString.Split(Main.delimiter2);
                float    hg        = 0f;
                for (int i = 0; i < DetailStr.Length; i++)
                {
                    track = 0;
                    hg    = table1.GetRowHeight(i + 1);
                    string[] str = DetailStr[i].Split(Main.delimiter1);
                    for (int j = 0; j < str.Length; j++)
                    {
                        PdfPCell pcell;
                        if (j > 2)
                        {
                            decimal p = 1;
                            if (Decimal.TryParse(str[j], out p))
                            {
                                pcell = new PdfPCell(new Phrase(String.Format("{0:0.00}", Convert.ToDecimal(str[j])), font1));
                            }
                            else
                            {
                                pcell = new PdfPCell(new Phrase(""));
                            }
                            pcell.Border = 0;
                        }
                        else
                        {
                            pcell        = new PdfPCell(new Phrase(str[j], font1));
                            pcell.Border = 0;
                        }
                        pcell.MinimumHeight = 10;
                        if (j == 0 || j > 2)
                        {
                            pcell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                        }
                        else
                        {
                            pcell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        }
                        pcell.BorderWidthLeft   = 0.01f;
                        pcell.BorderWidthRight  = 0.01f;
                        pcell.BorderWidthBottom = 0.5f;
                        table1.AddCell(pcell);
                    }
                }


                ///
                PdfPCell pcelNo = new PdfPCell(new Phrase("", font1));
                pcelNo.BorderWidthTop   = 0;
                pcelNo.BorderWidthRight = 0;
                table1.AddCell(pcelNo);

                PdfPCell pcelMid = new PdfPCell(new Phrase("", font1));
                pcelMid.Colspan          = 3;
                pcelMid.Border           = 0;
                pcelMid.BorderWidthTop   = 0;
                pcelMid.BorderWidthLeft  = 0;
                pcelMid.BorderWidthRight = 0;
                table1.AddCell(pcelMid);

                doc.Add(paragraph);
                doc.Add(tableMain);
                doc.Add(subHeadPara);
                doc.Add(table1);
                doc.Close();
                MessageBox.Show("Document Saved");

                String wmurl = "";
                wmurl = "004.png";
                PrintWaterMark.PdfStampWithNewFile(wmurl, sfd.FileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this.ToString() + "-" + System.Reflection.MethodBase.GetCurrentMethod().Name + "() : Error-" + ex.ToString());
                MessageBox.Show("Failed TO Save");
            }
        }
Exemplo n.º 59
0
        public void CreateForm(Supply sup)
        {
            try
            {
                string FileName = "Заявка на поставку №" + sup.Id + ".pdf";
                iTextSharp.text.Document doc = new iTextSharp.text.Document();
                PdfWriter.GetInstance(doc, new FileStream(FileName, FileMode.Create));

                doc.Open();

                BaseFont             baseFont          = BaseFont.CreateFont("C:/Windows/Fonts/arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                var                  arial_italic_path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ariali.ttf");
                BaseFont             ItalicBaseFont    = BaseFont.CreateFont(arial_italic_path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                iTextSharp.text.Font font       = new iTextSharp.text.Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.NORMAL);
                iTextSharp.text.Font ItalicFont = new iTextSharp.text.Font(ItalicBaseFont, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.NORMAL);

                Paragraph par = new Paragraph("Кому: " + db.getProviders().Where(i => i.Id == sup.ProviderId).Select(i => i.CompanyName).FirstOrDefault().ToString(), font);
                par.Alignment = Element.ALIGN_RIGHT;
                doc.Add(par);

                string Initials = db.getProviders().Where(i => i.Id == sup.ProviderId).Select(i => i.Initials).FirstOrDefault().ToString();
                string FamName  = db.getProviders().Where(i => i.Id == sup.ProviderId).Select(i => i.FamilyName).FirstOrDefault().ToString();
                if (FamName[FamName.Length - 1] == 'н' || FamName[FamName.Length - 1] == 'в')
                {
                    FamName = FamName + "у";
                }
                string FulName = FamName + " " + Initials;

                par           = new Paragraph("Директору " + FulName, font);
                par.Alignment = Element.ALIGN_RIGHT;
                doc.Add(par);

                par           = new Paragraph("От ООО \"Sirius Smoke\"", font);
                par.Alignment = Element.ALIGN_RIGHT;
                doc.Add(par);

                string warehousename = db.getWarehouses().Where(i => i.Id == sup.WarehouseId).Select(i => i.Address).FirstOrDefault().ToString();

                par           = new Paragraph("г. Иваново, " + warehousename, font);
                par.Alignment = Element.ALIGN_RIGHT;
                doc.Add(par);

                par           = new Paragraph("т. 8 (567) 63-87-69", font);
                par.Alignment = Element.ALIGN_RIGHT;
                doc.Add(par);

                par           = new Paragraph(DateTime.Parse(sup.ApplicationDate.ToString()).ToShortDateString(), font);
                par.Alignment = Element.ALIGN_RIGHT;
                doc.Add(par);

                par           = new Paragraph("ЗАЯВКА", font);
                par.Alignment = Element.ALIGN_CENTER;
                par.SetLeading(font.Size, 2);
                doc.Add(par);

                par           = new Paragraph("на поставку товара", font);
                par.Alignment = Element.ALIGN_CENTER;
                doc.Add(par);

                par = new Paragraph(" ", font);
                doc.Add(par);

                string str = "Прошу зарезервировать и поставить до " + DateTime.Parse(sup.DeliveryDate.ToString()).ToShortDateString() + " следующие наименования товаров:";
                par = new Paragraph(str, font);
                doc.Add(par);

                PdfPTable table = new PdfPTable(4);
                table.SpacingBefore = 20;
                PdfPCell HeaderCell = new PdfPCell(new Phrase("Наименование", font));
                HeaderCell.HorizontalAlignment = 1;
                table.AddCell(HeaderCell);
                HeaderCell = new PdfPCell(new Phrase("Количество", font));
                HeaderCell.HorizontalAlignment = 1;
                table.AddCell(HeaderCell);
                HeaderCell = new PdfPCell(new Phrase("Цена единицы товара, р", font));
                HeaderCell.HorizontalAlignment = 1;
                table.AddCell(HeaderCell);
                HeaderCell = new PdfPCell(new Phrase("Общая стоимость, р", font));
                HeaderCell.HorizontalAlignment = 1;
                table.AddCell(HeaderCell);

                decimal TotalSum      = 0;
                int     TotalQuantity = 0;

                foreach (SupplyLine item in sup.Lines)
                {
                    PdfPCell BasicCell = new PdfPCell(new Phrase(item.CommodityName.ToString(), font));
                    BasicCell.HorizontalAlignment = 1;
                    table.AddCell(BasicCell);
                    BasicCell = new PdfPCell(new Phrase(item.Quantity.ToString() + " шт.", font));
                    BasicCell.HorizontalAlignment = 1;
                    table.AddCell(BasicCell);
                    BasicCell = new PdfPCell(new Phrase((item.Cost).ToString(), font));
                    BasicCell.HorizontalAlignment = 1;
                    table.AddCell(BasicCell);
                    BasicCell = new PdfPCell(new Phrase((item.Cost * item.Quantity).ToString(), font));
                    BasicCell.HorizontalAlignment = 1;
                    table.AddCell(BasicCell);
                    TotalQuantity += item.Quantity;
                    TotalSum      += item.Cost * item.Quantity;
                }
                HeaderCell = new PdfPCell(new Phrase("Итого", font));
                HeaderCell.HorizontalAlignment = 1;
                table.AddCell(HeaderCell);
                HeaderCell = new PdfPCell(new Phrase(TotalQuantity.ToString() + " шт.", font));
                HeaderCell.HorizontalAlignment = 1;
                table.AddCell(HeaderCell);
                HeaderCell = new PdfPCell(new Phrase("", font));
                HeaderCell.HorizontalAlignment = 1;
                table.AddCell(HeaderCell);
                HeaderCell = new PdfPCell(new Phrase(TotalSum.ToString(), font));
                HeaderCell.HorizontalAlignment = 1;
                table.AddCell(HeaderCell);
                table.WidthPercentage = 95;
                doc.Add(table);

                par = new Paragraph("Директор ООО \"Sirius Smoke\"", font);
                font.SetStyle(iTextSharp.text.Font.ITALIC);
                par.Add(new Chunk("                 Воронов", ItalicFont));
                font.SetStyle(iTextSharp.text.Font.NORMAL);
                par.Add(new Chunk("                 Воронов И.С.", font));
                par.Alignment = Element.ALIGN_CENTER;
                par.SetLeading(font.Size, 2);
                doc.Add(par);
                doc.Close();
                MessageBox.Show("Файл заявки \"" + FileName + "\" создан");
            }
            catch (IOException ex)
            {
                MessageBox.Show("Возникла ошибка при записи страниц", ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Возникла ошибка", ex.Message);
            }
        }
Exemplo n.º 60
-1
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            base.OnEndPage(writer, document);

            int pageN = writer.PageNumber;
            string text = pageN + " - ";
            float len = baseFont.GetWidthPoint(text, 8);

            Rectangle pageSize = document.PageSize;
            pdfContent = writer.DirectContent;
            pdfContent.SetRGBColorFill(100, 100, 100);

            pdfContent.BeginText();
            pdfContent.SetFontAndSize(baseFont, 8);
            pdfContent.SetTextMatrix(pageSize.Width / 2, pageSize.GetBottom(30));
            pdfContent.ShowText(text);
            pdfContent.EndText();

            pdfContent.AddTemplate(pageNumberTemplate, (pageSize.Width / 2) + len, pageSize.GetBottom(30));

            pdfContent.BeginText();
            pdfContent.SetFontAndSize(baseFont, 8);
            pdfContent.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, printTime.ToString(), pageSize.GetRight(40), pageSize.GetBottom(30), 0);
            pdfContent.EndText();
        }