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

Closes the document.
Once all the content has been written in the body, you have to close the body. After that nothing can be written to the body anymore.
public Close ( ) : void
Результат void
Пример #1
5
        /// <summary>
        /// Extract a single page from PDF file.
        /// </summary>
        /// <param name="sourceFile">The source file.</param>
        /// <param name="outputFile">The output file.</param>
        /// <param name="pageNumber">The specific page number.</param>
        public static void ExtractPage(string sourceFile, string outputFile, int pageNumber)
        {
            try
            {
                PdfReader reader = new PdfReader(sourceFile);
                if (pageNumber > reader.NumberOfPages)
                {
                    Console.WriteLine("This page number is out of reach.");
                    return;
                }

                Document document = new Document();
                PdfCopy pdfCopy = new PdfCopy(document, new FileStream(outputFile, FileMode.Create));
                document.Open();

                PdfImportedPage importedPage = pdfCopy.GetImportedPage(reader, pageNumber);
                pdfCopy.AddPage(importedPage);

                document.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #2
1
        public static byte[] MergePdfs(IEnumerable<byte[]> inputFiles)
        {
            MemoryStream outputStream = new MemoryStream();
            Document document = new Document();
            PdfWriter writer = PdfWriter.GetInstance(document, outputStream);
            document.Open();
            PdfContentByte content = writer.DirectContent;

            foreach (byte[] input in inputFiles)
            {
                PdfReader reader = new PdfReader(input);
                for (int i = 1; i <= reader.NumberOfPages; i++)
                {
                    document.SetPageSize(reader.GetPageSizeWithRotation(i));
                    document.NewPage();
                    PdfImportedPage page = writer.GetImportedPage(reader, i);
                    int rotation = reader.GetPageRotation(i);
                    if (rotation == 90 || rotation == 270)
                    {
                        content.AddTemplate(page, 0, -1f, 1f, 0, 0,
                            reader.GetPageSizeWithRotation(i).Height);
                    }
                    else
                    {
                        content.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                    }
                }
            }

            document.Close();

            return outputStream.ToArray();
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            filePdf = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.InternetCache), "PDF_Temp.pdf");

            var document = new Document(PageSize.LETTER);

            // Create a new PdfWriter object, specifying the output stream
            var output = new FileStream(filePdf, FileMode.Create);
            var writer = PdfWriter.GetInstance(document, output);

            // Open the Document for writing
            document.Open();

            BaseFont bf = BaseFont.CreateFont (BaseFont.HELVETICA, BaseFont.CP1252, false);
            iTextSharp.text.Font font = new iTextSharp.text.Font (bf, 16, iTextSharp.text.Font.BOLD);
            var p = new Paragraph ("Sample text", font);

            document.Add (p);
            document.Close ();
            writer.Close ();

            //Close the Document - this saves the document contents to the output stream
            document.Close();
            writer.Close ();
        }
Пример #4
0
        public static void CreateTmpPDFFile(string tmpPDFFile, string jpgFile)
        {
            Document doc = new Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);
            try
            {
                string pdfFilePath = tmpPDFFile;
                //Create Document class object and set its size to letter and give space left, right, Top, Bottom Margin
                PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(pdfFilePath, FileMode.Create));
                doc.Open();//Open Document to write

                ////Write some content into pdf file
                //Paragraph paragraph = new Paragraph("This is my first line using Paragraph.");

                // Now image in the pdf file
                string imageFilePath = jpgFile;
                iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);

                //Resize image depend upon your need
                //jpg.ScalePercent(20);
                jpg.ScaleToFit(600f, 950f);

                //Give space before image
                //jpg.SpacingBefore = 30f;

                //Give some space after the image
                //jpg.SpacingAfter = 1f;
                jpg.Alignment = Element.ALIGN_CENTER;

                //doc.Add(paragraph); // add paragraph to the document

                doc.Add(jpg); //add an image to the created pdf document
                doc.Close();
            }
            catch (DocumentException docEx)
            {
                //handle pdf document exception if any
            }
            catch (IOException ioEx)
            {
                // handle IO exception
            }
            catch (Exception ex)
            {
                // ahndle other exception if occurs
            }
            finally
            {
                //Close document and writer
                doc.Close();

            }
        }
        public void DoPdf()
        {
            PdfPTable pdfPTable = new PdfPTable(diseaseWiseReportGridView.HeaderRow.Cells.Count);

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

            int count = 1;

            foreach (GridViewRow gridViewRow in diseaseWiseReportGridView.Rows)
            {
                if (count != 0)
                    foreach (TableCell tableCell in gridViewRow.Cells)
                    {
                        PdfPCell pdfCell = new PdfPCell(new Phrase(tableCell.Text));
                        pdfPTable.AddCell(pdfCell);
                    }
                count++;

            }

            Document document = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
            PdfWriter.GetInstance(document, Response.OutputStream);
            //PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("test.pdf", FileMode.Create));

            Paragraph diseaseName = new Paragraph("Disease Name: " + diseaseDropDownList.SelectedItem.Text);
            Paragraph strartingDate = new Paragraph("Starting Date: " + firstdateTextBox.Text);
            Paragraph lastdate = new Paragraph("Last Date: " + lastdateTextBox.Text);

            Paragraph text = new Paragraph("\n\n");

            document.Open();
            document.Add(diseaseName);
            document.Add(strartingDate);
            document.Add(lastdate);

            document.Add(text);
            document.Add(pdfPTable);
            document.Close();

            Response.ContentType = "Application";
            Response.AppendHeader("content-disposition", "attachment;filename=DiseaseWiseReport.pdf");
            Response.Write(document);
            Response.Flush();
            Response.End();
            document.Close();
        }
Пример #6
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();
            }
        }
    }
Пример #7
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 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();
    }
        // 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);
        }
Пример #10
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();
        }
Пример #11
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;
            }
        }
        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();
        }
Пример #13
0
        protected void btnExpotGraph_Click(object sender, EventArgs e)
        {
            //code obtained from here: http://www.aspsnippets.com/Articles/Export-ASPNet-Chart-Control-to-PDF-Document-using-iTextSharp-Library.aspx. Used under the site's license.

            if (cboFileSelectionGraExp.SelectedIndex == 0)
            {
                string timeStamp = DateTime.Now.Year.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Day.ToString() +
                    "-" + DateTime.Now.Hour.ToString() + "_" + DateTime.Now.Minute.ToString() + "_" + DateTime.Now.Second.ToString();

                Document pdfDoc = new Document(new RectangleReadOnly(1248,816), 88f, 88f, 10f, 10f);
                PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                pdfDoc.Open();
                using (MemoryStream stream = new MemoryStream())
                {
                    Chart1.SaveImage(stream, ChartImageFormat.Png);
                    iTextSharp.text.Image chartImage = iTextSharp.text.Image.GetInstance(stream.GetBuffer());
                    chartImage.ScalePercent(75f);
                    pdfDoc.Add(chartImage);
                    pdfDoc.Close();

                    Response.ContentType = "application/pdf";
                    Response.AddHeader("content-disposition", "attachment;filename=Chart_" + timeStamp + ".pdf");
                    Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    Response.Write(pdfDoc);
                    Response.End();
                }
            }
        }
        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();
        }
        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();
                }
            }
        }
Пример #16
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();
        }
Пример #18
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);
            }
        }
Пример #19
0
        public void TextLeadingTest() {
            String file = "phrases.pdf";

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

            Phrase p1 = new Phrase("first, leading of 150");
            p1.Leading = 150;
            document.Add(p1);
            document.Add(Chunk.NEWLINE);

            Phrase p2 = new Phrase("second, leading of 500");
            p2.Leading = 500;
            document.Add(p2);
            document.Add(Chunk.NEWLINE);

            Phrase p3 = new Phrase();
            p3.Add(new Chunk("third, leading of 20"));
            p3.Leading = 20;
            document.Add(p3);

            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);
            }
        }
Пример #20
0
 virtual public void CreateAllSamples() {
     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 + "/" + str + "Test.pdf", FileMode.Create));
             }
             catch (DocumentException e) {
                 Console.WriteLine(e);
             }
             doc.Open();
             StreamReader bis = File.OpenText(RESOURCE_TEST_PATH + "/snippets/" + str + "snippet.html");
             XMLWorkerHelper helper = XMLWorkerHelper.GetInstance();
             helper.ParseXHtml(writer, doc, bis);
             doc.Close();
         }
         catch (Exception e) {
             Console.Write(e);
             success = false;
         }
     }
     if (!success) {
         Assert.Fail();
     }
 }
Пример #21
0
        public Document CreatePdfDocument(Chart chart, string path)
        {
            RenderTargetBitmap renderBitmap = new RenderTargetBitmap(
                (int) chart.ActualWidth,
                (int) chart.ActualHeight,
                96d,
                96d,
                PixelFormats.Pbgra32);

            renderBitmap.Render(chart);

            MemoryStream stream = new MemoryStream();
            BitmapEncoder encoder = new BmpBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
            encoder.Save(stream);

            Bitmap bitmap = new Bitmap(stream);
            System.Drawing.Image image = bitmap;

            System.Drawing.Image resizedImage = ResizeImage(image, image.Width*2, image.Height);

            Document doc = new Document(PageSize.A4);
            PdfWriter.GetInstance(doc, new FileStream(path, FileMode.OpenOrCreate));
            doc.Open();
            Image pdfImage = Image.GetInstance(resizedImage, ImageFormat.Jpeg);
            doc.Add(pdfImage);
            doc.Close();
            
            return doc;
        }
    protected void btnExport_Click(object sender, EventArgs e)
    {
        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter hw = new HtmlTextWriter(sw))
            {
                //To Export all pages
                grid_monthly_attendanceDetailed.AllowPaging = false;
                //this.BindGrid();

                grid_monthly_attendanceDetailed.RenderBeginTag(hw);
                grid_monthly_attendanceDetailed.HeaderRow.RenderControl(hw);
                foreach (GridViewRow row in grid_monthly_attendanceDetailed.Rows)
                {
                    row.RenderControl(hw);
                }
                grid_monthly_attendanceDetailed.FooterRow.RenderControl(hw);
                grid_monthly_attendanceDetailed.RenderEndTag(hw);
                StringReader sr = new StringReader(sw.ToString());
                Document pdfDoc = new Document(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();
            }
        }
    }
Пример #23
0
        /// <summary>
        /// Creates a MemoryStream but does not dispose it.
        /// </summary>
        /// <param name="members"></param>
        /// <param name="expiration"></param>
        /// <returns></returns>
        public static MemoryStream CreateCards(IEnumerable<Member> members, DateTime expiration)
        {
            iTextSharp.text.Document doc = new iTextSharp.text.Document(new iTextSharp.text.Rectangle(CARD_WIDTH, CARD_HEIGHT));
            MemoryStream memStream = new MemoryStream();
            PdfWriter writer = PdfWriter.GetInstance(doc, memStream);
            writer.CloseStream = false;
            doc.Open();

            foreach (var member in members)
            {
                foreach (var passport in new[] { false, true})
                {
                    Render_FrontBase(writer.DirectContentUnder, expiration);
                    Render_FrontContent(writer.DirectContent, member);
                    doc.NewPage();
                    Render_BackBase(writer.DirectContentUnder);
                    Render_BackContent(writer.DirectContent, member, passport);
                    doc.NewPage();
                }
            }

            doc.Close();
            byte[] buf = new byte[memStream.Position];
            memStream.Position = 0;

            return memStream;
        }
Пример #24
0
        private void AusgangsrechnungenPDF_Click(object sender, EventArgs e)
        {
            string pdfString = "";
            Document pdfDoc = new Document();
            PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new System.IO.FileStream(System.IO.Directory.GetCurrentDirectory() + "\\exportAusgangsrechnungen.pdf",
               System.IO.FileMode.Create));

            pdfDoc.Open();

            foreach (DataGridViewRow row in dataGridViewAusgangsrechnung.SelectedRows)
            {

                foreach(DataGridViewCell cell in row.Cells)
                {

                    pdfString += cell.Value.ToString() + " ";
                }
                pdfDoc.Add(new Paragraph (pdfString));
                pdfString = "";

            }

            PdfContentByte cb = writer.DirectContent;
            cb.MoveTo(pdfDoc.PageSize.Width, pdfDoc.PageSize.Height);
            cb.LineTo(pdfDoc.PageSize.Width / 2, pdfDoc.PageSize.Height);
            cb.Stroke();

            pdfDoc.Close();
        }
Пример #25
0
        protected override void TransformHtml2Pdf() {
            Document doc = new Document(PageSize.A1.Rotate());
            PdfWriter pdfWriter = PdfWriter.GetInstance(doc, new FileStream(outPdf, FileMode.Create));
            doc.SetMargins(doc.LeftMargin - 10, doc.RightMargin - 10, doc.TopMargin, doc.BottomMargin);
            doc.Open();


            CssFilesImpl cssFiles = new CssFilesImpl();
            cssFiles.Add(
                XMLWorkerHelper.GetCSS(
                    File.OpenRead(RESOURCES + Path.DirectorySeparatorChar + testPath + testName +
                                  Path.DirectorySeparatorChar + "complexDiv02_files" + Path.DirectorySeparatorChar +
                                  "minimum0.css")));
            cssFiles.Add(
                XMLWorkerHelper.GetCSS(
                    File.OpenRead(RESOURCES + Path.DirectorySeparatorChar + testPath + testName +
                                  Path.DirectorySeparatorChar + "complexDiv02_files" + Path.DirectorySeparatorChar +
                                  "print000.css")));
            cssFiles.Add(XMLWorkerHelper.GetCSS(File.OpenRead(RESOURCES + @"\tool\xml\examples\" + "sampleTest.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());
            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();
        }
Пример #26
0
 virtual public void ParseXfaOnlyXML() {
     StreamReader bis = File.OpenText(RESOURCE_TEST_PATH + SNIPPETS + TEST + "snippet.html");
     Document doc = new Document(PageSize.A4);
     float margin = utils.ParseRelativeValue("10%", PageSize.A4.Width);
     doc.SetMargins(margin, margin, margin, margin);
     PdfWriter writer = null;
     try {
         writer = PdfWriter.GetInstance(doc, new FileStream(
             TARGET + TEST + "_charset.pdf", FileMode.Create));
     }
     catch (DocumentException e) {
         Console.WriteLine(e);
     }
     CssFilesImpl cssFiles = new CssFilesImpl();
     cssFiles.Add(XMLWorkerHelper.GetInstance().GetDefaultCSS());
     StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles);
     HtmlPipelineContext hpc = new HtmlPipelineContext(null);
     hpc.SetAcceptUnknown(true)
         .AutoBookmark(true)
         .SetTagFactory(Tags.GetHtmlTagProcessorFactory())
         .CharSet(Encoding.GetEncoding("ISO-8859-1"));
     IPipeline pipeline = new CssResolverPipeline(cssResolver,
         new HtmlPipeline(hpc, new PdfWriterPipeline(doc, writer)));
     XMLWorker worker = new XMLWorker(pipeline, true);
     doc.Open();
     XMLParser p = new XMLParser(true, worker);
     p.Parse(bis);
     doc.Close();
 }
Пример #27
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string html = GetHTMLOutput("~/render.aspx?id=1");

        if (!string.IsNullOrEmpty(html))
        {
            string file = Server.MapPath("~/pdf") + "\\using.pdf";

            using (Document doc = new Document(PageSize.LETTER, 25, 25, 25, 25))
            {
                using (PdfWriter pdf = PdfWriter.GetInstance(doc, new FileStream(file, FileMode.Create)))
                {
                    List<IElement> code = HTMLWorker.ParseToList(new StringReader(html), null);

                    doc.Open();

                    foreach (IElement el in code)
                    {
                        doc.Add(el);
                    }

                    doc.Close();
                }
            }
        }
    }
Пример #28
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);
     }
 }
Пример #29
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            Page.Title = "Contact List";
            MemoryStream PDFData = new MemoryStream();

            // step 1: creation of a document-object
            Document document = new Document();

            // step 2:
            // we create a writer that listens to the document
            // and directs a PDF-stream to a file

            PdfWriter.GetInstance(document, PDFData);

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

            // step 4: we add a paragraph to the document
            document.Add(new Paragraph(DateTime.Now.ToString()));
            Contact oContact = new Contact();
            DataTable dtContact = oContact.LoadAll();
            int numRow = dtContact.Rows.Count;
            int numCol = 5;
            iTextSharp.text.Table aTable = new iTextSharp.text.Table(numCol, numRow);
            aTable.AutoFillEmptyCells = true;
            aTable.Padding = 1;
            aTable.Spacing = 1;

            Cell cell = new Cell(new Phrase("Contact List", FontFactory.GetFont(FontFactory.TIMES, 14, Font.BOLD)));
            cell.Header = true;
            cell.Colspan = numCol;
            cell.BackgroundColor = Color.LIGHT_GRAY;
            cell.HorizontalAlignment = Element.ALIGN_CENTER;

            aTable.AddCell(cell);

            for (int i = 0; i < dtContact.Rows.Count; i++)
            {
                for (int n = 1; n <= numCol; n++)
                    aTable.AddCell(dtContact.Rows[i][n].ToString());

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

            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.ContentType = "application/pdf";
            Response.Charset = string.Empty;
            Response.Cache.SetCacheability(System.Web.HttpCacheability.Public);
            Response.AddHeader("Content-Disposition",
                "attachment; filename=" + Title.Replace(" ", "").Replace(":", "-") + ".pdf");

            Response.OutputStream.Write(PDFData.GetBuffer(), 0, PDFData.GetBuffer().Length);
            Response.OutputStream.Flush();
            Response.OutputStream.Close();
            Response.End();
        }
Пример #30
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();
 }
Пример #31
0
        public void CvAdd(CurriculumVitae curriculumVitae)
        {
            Document document = new iTextSharp.text.Document();

            PdfWriter.GetInstance(document, new FileStream(@"C:\Users\ademk\Desktop\PoldyMyCv.pdf", FileMode.Create));
            BaseFont arial = BaseFont.CreateFont("c:\\windows\\fonts\\arial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            Font     font  = new Font(arial, 12, Font.NORMAL);

            if (document.IsOpen() == false)
            {
                document.Open();

                // iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(@"C:\Users\ademk\source\repos\Poldy4\deneme\PoldyCv\vesikalik.jpg");
                // img.ScalePercent(30f, 20f);
                string text;

                if (curriculumVitae.MaritalStatus.ToString() == "False")
                {
                    this.medenidurum = "Bekar";
                }
                else if (curriculumVitae.MaritalStatus.ToString() == "True")
                {
                    this.medenidurum = "Evli";
                }
                text =
                    "Kişisel Bilgiler \n" +
                    "--------------------" +
                    "\n Ad :" + curriculumVitae.FirstName +
                    "\n Soyad : " + curriculumVitae.LastName +
                    "\n Doğum Tarihi : " + curriculumVitae.BirthDate +
                    "\n Doğum Yeri : " + curriculumVitae.PlaceOfBirth +
                    "\n Medeni Durum : " + this.medenidurum +
                    "\n ----------------------------------------" +
                    "\n Eğitim Bilgileri" +
                    "\n--------------------" +
                    "\n Öğrenim Seviyesi :" + curriculumVitae.EducationStatus +
                    "\n Okul Adı : " + curriculumVitae.School +
                    "\n Okul Başlangıç : " + curriculumVitae.SchoolStart +
                    "\n Okul Bitiş : " + curriculumVitae.SchoolFinish +
                    "\n --------------------" +
                    "\n İletişim Bilgileri" +
                    "\n ---------------------" +
                    "\n Cep Numarası : " + curriculumVitae.MobilTelefonNumber +
                    "\n Mail Adresi : " + curriculumVitae.Mail +
                    "\n Adres : " + curriculumVitae.Address +
                    "\n --------------------" +
                    "\n Yabancı Dil Bilgileri" +
                    "\n ---------------------" +
                    "\n Yabancı Dil : " + curriculumVitae.ForeignLanguage +
                    "\n Yabancı Dil Seviye : " + curriculumVitae.ForeignLanguageLevel +
                    "\n --------------------" +
                    "\n Yabancı Dil Bilgileri" +
                    "\n ---------------------" +
                    "\n Yetkinlikler : " + curriculumVitae.Competences +
                    "\n ----------------------------" +
                    "\n Referanslar : " + curriculumVitae.Reference
                ;
                //document.Add(img);

                text = Turkish1.TurkishCharacter(text);
                document.Add(new Paragraph(text, font));
                document.Close();
                this.CvPdf = File.ReadAllBytes(@"C:\Users\ademk\Desktop\PoldyMyCv.pdf");
            }
        }
Пример #32
0
        public bool GenerateMCDSlipDocument()
        {
            storeNumber  = GlobalDataAccessor.Instance.CurrentSiteId.StoreNumber;
            reportNumber = "CL-OP-68";
            DataTable checkInfoDetails;
            string    errorCode;
            string    errorText;

            //Get the report data
            ShopProcedures.GetStoreManualCheckDepositData(GlobalDataAccessor.Instance.OracleDA,
                                                          GlobalDataAccessor.Instance.CurrentSiteId.StoreId,
                                                          ShopDateTime.Instance.ShopDate,
                                                          out checkInfoDetails, out errorCode, out errorText);
            if (checkInfoDetails == null || checkInfoDetails.Rows.Count == 0)
            {
                FileLogger.Instance.logMessage(LogLevel.ERROR, this, "No data returned from stored procedure for manual check deposit slips " + errorText);
                return(false);
            }
            //Initialize fonts
            RptFont =
                FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL);
            this.HeaderTitleFont =
                new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 10);

            this.MCDSlipReportTitle =
                @"Check Cash Deposit Slip";

            document = new Document(PageSize.LETTER);
            document.AddTitle(MCDSlipReportTitle);
            PdfPTable table = new PdfPTable(8);

            rptFileName =
                SecurityAccessor.Instance.EncryptConfig.ClientConfig.GlobalConfiguration.BaseLogPath + "\\MCD" + DateTime.Now.ToString("MMddyyyyhhmmssFFFFFFF") + ".pdf";
            PdfWriter     writer = PdfWriter.GetInstance(document, new FileStream(rptFileName, FileMode.Create));
            MCDPageEvents events = new MCDPageEvents();

            writer.PageEvent = events;
            document.SetPageSize(PageSize.LETTER);
            document.SetMargins(0, 0, 10, 45);

            Image image = Image.GetInstance(Properties.Resources.logo, BaseColor.WHITE);

            image.ScalePercent(25);

            //Insert the report header
            InsertReportHeader(table, image);

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

            PdfPTable newtable = new PdfPTable(4);

            //Insert the column headers
            InsertColumnHeaders(newtable);
            table.HeaderRows = 7;
            decimal totalCheckAmount = 0;
            int     totalNumChecks   = 0;

            foreach (DataRow dr in checkInfoDetails.Rows)
            {
                string  makerName   = Common.Libraries.Utility.Utilities.GetStringValue(dr["makername"]);
                string  cdName      = Utilities.GetStringValue(dr["username"]);
                decimal chkAmount   = Utilities.GetDecimalValue(dr["checkamount"]);
                string  depositDate = Utilities.GetDateTimeValue(dr["creationdate"]).FormatDate();
                totalNumChecks++;
                totalCheckAmount += chkAmount;
                PdfPCell pCell = new PdfPCell();
                pCell.Colspan             = 1;
                pCell.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
                pCell.Border = Rectangle.NO_BORDER;
                pCell.Phrase = new Phrase(makerName, RptFont);
                newtable.AddCell(pCell);
                pCell.Phrase = new Phrase(cdName, RptFont);
                newtable.AddCell(pCell);
                pCell.Phrase = new Phrase(depositDate, RptFont);
                newtable.AddCell(pCell);
                pCell.Phrase = new Phrase(String.Format("{0:n}", chkAmount), RptFont);
                pCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                newtable.AddCell(pCell);
            }

            //Add a blank line before summary
            newtable.AddCell(generateBlankLine(8));

            //Insert summary table
            PdfPCell newCell = new PdfPCell(new Paragraph("", RptFont));

            newCell.HorizontalAlignment = Element.ALIGN_LEFT;
            newCell.Border  = Rectangle.TOP_BORDER;
            newCell.Colspan = 4;
            newtable.AddCell(newCell);
            newCell.Colspan             = 1;
            newCell.HorizontalAlignment = Element.ALIGN_LEFT;
            newCell.Border = Rectangle.NO_BORDER;
            newCell.Phrase = new Phrase("Count of all Checks", RptFont);
            newtable.AddCell(newCell);
            newCell.Phrase = new Phrase(totalNumChecks.ToString(), RptFont);
            newtable.AddCell(newCell);
            newCell.Phrase = new Phrase("Total Amount of all Checks:", RptFont);
            newtable.AddCell(newCell);
            newCell.Phrase = new Phrase(string.Format("{0:n}", totalCheckAmount), RptFont);
            newCell.HorizontalAlignment = Element.ALIGN_RIGHT;
            newtable.AddCell(newCell);
            newCell = new PdfPCell(new Paragraph("", RptFont));
            newCell.HorizontalAlignment = Element.ALIGN_LEFT;
            newCell.Border  = Rectangle.BOTTOM_BORDER;
            newCell.Colspan = 4;
            newtable.AddCell(newCell);

            document.Add(newtable);

            //Insert report footer
            PdfPTable finalSummaryTable = new PdfPTable(8);

            finalSummaryTable.TotalWidth = 500f;
            InsertReportFooter(ref finalSummaryTable);

            float yAbsolutePosition = newtable.CalculateHeights(true);

            finalSummaryTable.WriteSelectedRows(0, -1, document.LeftMargin + 30, yAbsolutePosition + 30, writer.DirectContent);

            document.Close();

            //Print and save the document
            PrintDocument();

            return(true);
        }
Пример #33
0
        private static string exportAsPDF(string path, Event ev, User user, string logo)
        {
            string filename = "billet_" + ev.Name + "_" + user.Firstname + "_" + user.Lastname;

            PDF.Document doc = new PDF.Document(PDF.PageSize.A4, 20, 20, 42, 42);

            FileStream file = new FileStream(path + filename + ".pdf", FileMode.OpenOrCreate);
            PdfWriter  pdf  = PdfWriter.GetInstance(doc, file);

            doc.Open();

            /* Réservation */
            PDF.Paragraph par = new PDF.Paragraph("Réservation");
            PDF.Paragraph ph  = new PDF.Paragraph("Merci de votre réservation pour l'événement " + ev.Name);
            PDF.Paragraph ph2 = new PDF.Paragraph(user.Firstname + " " + user.Lastname);

            /* Logo */
            PDF.Image logoBilleterie = PDF.Image.GetInstance(logo);
            logoBilleterie.ScalePercent(20.0f);


            /* QRcode */
            PDF.Image qrcode = PDF.Image.GetInstance(QRCode.getImage(ev.Name + "(^_^)" + user.Id), PDF.BaseColor.WHITE);


            /* Receipt */
            PdfPTable table2 = new PdfPTable(4);
            PdfPCell  cell21 = new PdfPCell();
            PdfPCell  cell22 = new PdfPCell();
            PdfPCell  cell23 = new PdfPCell();
            PdfPCell  cell24 = new PdfPCell();

            cell21.AddElement(new PDF.Paragraph("Billet"));
            cell22.AddElement(new PDF.Paragraph("Date de début"));
            cell23.AddElement(new PDF.Paragraph("Date de fin"));
            cell24.AddElement(new PDF.Paragraph("Prix"));

            table2.AddCell(cell21);
            table2.AddCell(cell22);
            table2.AddCell(cell23);
            table2.AddCell(cell24);


            PdfPCell cell31 = new PdfPCell();
            PdfPCell cell32 = new PdfPCell();
            PdfPCell cell33 = new PdfPCell();
            PdfPCell cell34 = new PdfPCell();

            Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");

            float  price_value = -1;
            string price_name  = "";

            try
            {
                object[] tmp = Database.Database.database.RequestLine("f_get_participant", 2, user.Id, ev.Name);
                price_name  = (string)tmp[0];
                price_value = (float)tmp[1];
            }
            catch (Exception) { }

            cell31.AddElement(new PDF.Paragraph(price_name));
            cell32.AddElement(new PDF.Paragraph(ev.Begin.ToShortDateString() + " " + ev.Begin.ToShortTimeString()));
            cell33.AddElement(new PDF.Paragraph(ev.End.ToShortDateString() + " " + ev.End.ToShortTimeString()));
            cell34.AddElement(new PDF.Paragraph(price_value.ToString("C")));


            table2.AddCell(cell31);
            table2.AddCell(cell32);
            table2.AddCell(cell33);
            table2.AddCell(cell34);

            /* Add */
            doc.Add(logoBilleterie);
            doc.Add(par);
            doc.Add(ph);
            doc.Add(ph2);
            doc.Add(qrcode);
            doc.Add(table2);


            doc.Close();

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

            doc.Open();

            //Cabecera
            BaseFont bfntHead = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

            iTextSharp.text.Font fntHead    = new iTextSharp.text.Font(bfntHead, 16, 1, iTextSharp.text.BaseColor.GREEN.Darker());
            Paragraph            prgHeading = new Paragraph();

            prgHeading.Alignment = 1;
            prgHeading.Add(new Chunk("Taller de Reparaciones".ToUpper(), fntHead));
            doc.Add(prgHeading);
            doc.Add(Chunk.NEWLINE);
            //Generado By
            Paragraph prgGeneratedBY = new Paragraph();
            BaseFont  btnAuthor      = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

            iTextSharp.text.Font fntAuthor = new iTextSharp.text.Font(btnAuthor, 12, 2, iTextSharp.text.BaseColor.BLACK);
            prgGeneratedBY.Alignment = Element.ALIGN_RIGHT;
            prgGeneratedBY.Add(new Chunk("Generado por: " + LogEmpleado.nombreyapellido, fntAuthor));  //Agregar LOG Empleado
            prgGeneratedBY.Add(new Chunk("\nFecha : " + DateTime.Now.ToShortDateString(), fntAuthor));
            prgGeneratedBY.Add(new Chunk("\nN° de Orden : " + OrdenActual.id_orden, fntAuthor));
            doc.Add(prgGeneratedBY);
            Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, iTextSharp.text.BaseColor.BLACK, Element.ALIGN_LEFT, 1)));

            doc.Add(p);
            //Espacio
            doc.Add(new Chunk("\n", fntHead));
            //Datos
            Paragraph Datos     = new Paragraph();
            BaseFont  bfntDatos = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

            iTextSharp.text.Font fntDatos = new iTextSharp.text.Font(bfntDatos, 12, 0, iTextSharp.text.BaseColor.BLACK);
            Datos.Alignment = Element.ALIGN_CENTER;
            Datos.Add(new Chunk("\nPatente: " + OrdenActual.vehiculo.patente + "   Modelo:" + OrdenActual.vehiculo.modelo.nombre + "  Marca:  " + OrdenActual.vehiculo.modelo.marca.nombre, fntDatos));
            doc.Add(Datos);
            //Espacio
            doc.Add(new Chunk("\n", fntHead));

            foreach (servicio oservicio in LSUSO)
            {
                doc.Add(p);
                Paragraph Dato = new Paragraph();
                Dato.Alignment = Element.ALIGN_LEFT;
                Dato.Add(new Chunk("\nServicio: " + oservicio.detalle, fntDatos));
                doc.Add(Dato);
                //Espacio
                doc.Add(new Chunk("\n", fntHead));
                //Creo una tabla
                DataTable dt = new DataTable();
                dt.Columns.AddRange(new DataColumn[4] {
                    new DataColumn("Codigo"), new DataColumn("Detalle"), new DataColumn("Marca"), new DataColumn("Cantidad")
                });                                                                                                                                                     //nombre de las columnas
                List <stock> Lstock = bus.Lstockuso(oservicio.id_servicios.ToString());
                foreach (stock ostock in Lstock)
                {
                    dt.Rows.Add(ostock.codigo, ostock.detalle, ostock.marca, ostock.cantidad);     //Agrego las filas a la tabla
                }
                //Tabla
                PdfPTable table = new PdfPTable(dt.Columns.Count);

                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    string   cellText = Server.HtmlDecode(dt.Columns[i].ColumnName);
                    PdfPCell cell     = new PdfPCell();
                    cell.Phrase              = new Phrase(cellText, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 10, 1, new BaseColor(System.Drawing.ColorTranslator.FromHtml("#000000"))));
                    cell.BackgroundColor     = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#C8C8C8"));
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.PaddingBottom       = 5;
                    table.AddCell(cell);
                }
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        table.AddCell(dt.Rows[i][j].ToString());
                    }
                }
                doc.Add(table);


                //Espacio
                doc.Add(new Chunk("\n", fntHead));
            }


            doc.Close();
            Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('Taller.pdf','_newtab');", true);
        }
Пример #35
0
        private bool PrintMemo(ExtensionMemoInfo extnInfo)

        {
            try
            {
                //Set Font for the report
                rptFont     = FontFactory.GetFont("Arial", 8, Font.NORMAL);
                rptFontBold = FontFactory.GetFont("Arial", 8, Font.BOLD);

                var rptFileName = RptObject.ReportTempFileFullName.Replace(".pdf", "_" + extnInfo.TicketNumber + ".pdf");
                if (!string.IsNullOrEmpty(rptFileName))
                {
                    document = new Document(PageSize.HALFLETTER.Rotate());
                    document.AddTitle(RptObject.ReportTitle);
                    const int mainTableColumns = 6;
                    var       writer           = PdfWriter.GetInstance(document, new FileStream(rptFileName, FileMode.Create));
                    var       mainTable        = new PdfPTable(mainTableColumns)
                    {
                        WidthPercentage = 100
                    };

                    //Insert the report header
                    var headerTable = new PdfPTable(5);
                    BuildReportHeaderTable(headerTable, extnInfo);
                    mainTable.AddCell(new PdfPCell(headerTable)
                    {
                        Colspan = mainTableColumns, Border = Rectangle.NO_BORDER
                    });
                    mainTable.AddCell(new PdfPCell(new Phrase())
                    {
                        Border = Rectangle.NO_BORDER, Colspan = mainTableColumns
                    });                                                                                                         // empty row

                    //Set number of header rows
                    mainTable.HeaderRows = 0;

                    document.Open();

                    var topDataTable = new PdfPTable(5)
                    {
                        WidthPercentage = 100
                    };
                    topDataTable.AddCell(new PdfPCell(new Paragraph("Previous Maturity Date :", rptFont))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                    });
                    topDataTable.AddCell(new PdfPCell(new Paragraph(extnInfo.DueDate.FormatDate(), rptFont))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                    });
                    topDataTable.AddCell(new PdfPCell(new Phrase())
                    {
                        Border = Rectangle.NO_BORDER
                    });
                    topDataTable.AddCell(new PdfPCell(new Paragraph("New Maturity Date :", rptFont))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
                    });
                    topDataTable.AddCell(new PdfPCell(new Paragraph(extnInfo.NewDueDate.FormatDate(), rptFont))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
                    });

                    topDataTable.AddCell(new PdfPCell(new Paragraph("Previous Default Date :", rptFont))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                    });
                    topDataTable.AddCell(new PdfPCell(new Paragraph(extnInfo.OldPfiEligible.FormatDate(), rptFont))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                    });
                    topDataTable.AddCell(new PdfPCell(new Phrase())
                    {
                        Border = Rectangle.NO_BORDER
                    });
                    topDataTable.AddCell(new PdfPCell(new Paragraph("Last Day of Grace :", rptFont))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
                    });
                    topDataTable.AddCell(new PdfPCell(new Paragraph(extnInfo.NewPfiEligible.FormatDate(), rptFont))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
                    });

                    topDataTable.AddCell(new PdfPCell(new Paragraph("Pawn Charge Paid Today :", rptFont))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                    });
                    topDataTable.AddCell(new PdfPCell(new Paragraph(extnInfo.ExtensionAmount.ToString("c"), rptFont))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                    });
                    topDataTable.AddCell(new PdfPCell(new Phrase())
                    {
                        Border = Rectangle.NO_BORDER
                    });
                    topDataTable.AddCell(new PdfPCell(new Paragraph("Pawn Charge Paid to :", rptFont))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
                    });
                    topDataTable.AddCell(new PdfPCell(new Paragraph(extnInfo.DueDate.FormatDate(), rptFont))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
                    });

                    mainTable.AddCell(new PdfPCell(topDataTable)
                    {
                        Colspan = mainTableColumns, Border = Rectangle.NO_BORDER
                    });
                    mainTable.AddCell(new PdfPCell(new Phrase())
                    {
                        Border = Rectangle.NO_BORDER, Colspan = mainTableColumns, FixedHeight = 10
                    });                                                                                                                           // empty row

                    var bottomDataTable = new PdfPTable(5)
                    {
                        WidthPercentage = 100
                    };
                    bottomDataTable.AddCell(new PdfPCell(new Paragraph("AMOUNTS DUE AT MATURITY DATE", rptFont))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, Colspan = 2
                    });
                    bottomDataTable.AddCell(new PdfPCell(new Phrase())
                    {
                        Border = Rectangle.NO_BORDER
                    });
                    bottomDataTable.AddCell(new PdfPCell(new Paragraph("AMOUNTS DUE ON LAST DAY TO REDEEM", rptFont))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, Colspan = 2
                    });

                    bottomDataTable.AddCell(new PdfPCell(new Paragraph("Amount Financed :", rptFont))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                    });
                    bottomDataTable.AddCell(new PdfPCell(new Paragraph(extnInfo.Amount.ToString("c"), rptFont))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                    });
                    bottomDataTable.AddCell(new PdfPCell(new Phrase())
                    {
                        Border = Rectangle.NO_BORDER
                    });
                    bottomDataTable.AddCell(new PdfPCell(new Paragraph("Amount Financed :", rptFont))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
                    });
                    bottomDataTable.AddCell(new PdfPCell(new Paragraph(extnInfo.Amount.ToString("c"), rptFont))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
                    });

                    if (GlobalDataAccessor.Instance.CurrentSiteId.State.Equals(States.Ohio))
                    {
                        bottomDataTable.AddCell(new PdfPCell(new Paragraph("Pawn Charge :", rptFont))
                        {
                            Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                        });
                        bottomDataTable.AddCell(new PdfPCell(new Paragraph((extnInfo.InterestAmount + extnInfo.Fees).ToString("c"), rptFont))
                        {
                            Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                        });
                        bottomDataTable.AddCell(new PdfPCell(new Phrase())
                        {
                            Border = Rectangle.NO_BORDER
                        });
                        bottomDataTable.AddCell(new PdfPCell(new Paragraph("Pawn Charge :", rptFont))
                        {
                            Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
                        });
                        bottomDataTable.AddCell(new PdfPCell(new Paragraph(((extnInfo.InterestAmount + extnInfo.Fees) * extnInfo.ExtendedBy).ToString("c"), rptFont))
                        {
                            Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
                        });

                        bottomDataTable.AddCell(new PdfPCell(new Paragraph("**TOTAL** :", rptFont))
                        {
                            Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                        });
                        bottomDataTable.AddCell(new PdfPCell(new Paragraph((extnInfo.Amount + extnInfo.InterestAmount + extnInfo.Fees).ToString("c"), rptFont))
                        {
                            Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                        });
                        bottomDataTable.AddCell(new PdfPCell(new Phrase())
                        {
                            Border = Rectangle.NO_BORDER
                        });
                        bottomDataTable.AddCell(new PdfPCell(new Paragraph("**TOTAL** :", rptFont))
                        {
                            Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
                        });
                        bottomDataTable.AddCell(new PdfPCell(new Paragraph((extnInfo.Amount + ((extnInfo.InterestAmount + extnInfo.Fees) * extnInfo.ExtendedBy)).ToString("c"), rptFont))
                        {
                            Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
                        });

                        mainTable.AddCell(new PdfPCell(bottomDataTable)
                        {
                            Colspan = mainTableColumns, Border = Rectangle.NO_BORDER
                        });
                        mainTable.AddCell(new PdfPCell(new Phrase())
                        {
                            Border = Rectangle.NO_BORDER, Colspan = mainTableColumns
                        });                                                                                                         // empty row
                    }
                    else
                    {
                        //Indiana

                        bottomDataTable.AddCell(new PdfPCell(new Paragraph("Pawn Charge :", rptFont))
                        {
                            Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                        });
                        bottomDataTable.AddCell(new PdfPCell(new Paragraph((extnInfo.InterestAmount + extnInfo.Fees).ToString("c"), rptFont))
                        {
                            Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                        });
                        bottomDataTable.AddCell(new PdfPCell(new Phrase())
                        {
                            Border = Rectangle.NO_BORDER
                        });
                        bottomDataTable.AddCell(new PdfPCell(new Paragraph("Pawn Charge :", rptFont))
                        {
                            Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
                        });
                        bottomDataTable.AddCell(new PdfPCell(new Paragraph(((extnInfo.InterestAmount + extnInfo.Fees) * extnInfo.ExtendedBy).ToString("c"), rptFont))
                        {
                            Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
                        });

                        bottomDataTable.AddCell(new PdfPCell(new Paragraph("**TOTAL** :", rptFont))
                        {
                            Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                        });
                        bottomDataTable.AddCell(new PdfPCell(new Paragraph((extnInfo.Amount + extnInfo.InterestAmount + extnInfo.Fees).ToString("c"), rptFont))
                        {
                            Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                        });
                        bottomDataTable.AddCell(new PdfPCell(new Phrase())
                        {
                            Border = Rectangle.NO_BORDER
                        });
                        bottomDataTable.AddCell(new PdfPCell(new Paragraph("**TOTAL** :", rptFont))
                        {
                            Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
                        });
                        bottomDataTable.AddCell(new PdfPCell(new Paragraph((extnInfo.Amount + ((extnInfo.InterestAmount + extnInfo.Fees) * extnInfo.ExtendedBy)).ToString("c"), rptFont))
                        {
                            Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
                        });

                        mainTable.AddCell(new PdfPCell(bottomDataTable)
                        {
                            Colspan = mainTableColumns, Border = Rectangle.NO_BORDER
                        });
                        mainTable.AddCell(new PdfPCell(new Phrase())
                        {
                            Border = Rectangle.NO_BORDER, Colspan = mainTableColumns
                        });                                                                                                         // empty row
                    }

                    if (GlobalDataAccessor.Instance.CurrentSiteId.State.Equals(States.Ohio))
                    {
                        mainTable.AddCell(new PdfPCell(new Phrase())
                        {
                            Border = Rectangle.NO_BORDER, Colspan = mainTableColumns
                        });
                        mainTable.AddCell(new PdfPCell(new Paragraph("IF THE PLEDGOR FAILS TO REDEEM OR EXTEND THE LOAN BEFORE THE", rptFontBold))
                        {
                            Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, Colspan = mainTableColumns
                        });
                        mainTable.AddCell(new PdfPCell(new Paragraph("CLOSE OF BUSINESS ON THE LAST DAY OF GRACE, THE LICENSEE BECOMES THE OWNER", rptFontBold))
                        {
                            Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, Colspan = mainTableColumns
                        });
                        mainTable.AddCell(new PdfPCell(new Paragraph("OF THE PLEDGED PROPERTY.", rptFontBold))
                        {
                            Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, Colspan = mainTableColumns
                        });
                        mainTable.AddCell(new PdfPCell(new Phrase())
                        {
                            Border = Rectangle.NO_BORDER, Colspan = mainTableColumns
                        });                                                                                                     // empty row
                    }
                    else
                    {
                        //Indiana

                        mainTable.AddCell(new PdfPCell(new Paragraph("Daily Rate of Pawn Charge Accrual If Redeemed After Maturity:", rptFont))
                        {
                            Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, Colspan = 3
                        });
                        mainTable.AddCell(new PdfPCell(new Paragraph((extnInfo.DailyAmount).ToString("c"), rptFont))
                        {
                            Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                        });

                        mainTable.AddCell(new PdfPCell(new Phrase())
                        {
                            Border = Rectangle.NO_BORDER, Colspan = mainTableColumns
                        });                                                                                                     // empty row


                        mainTable.AddCell(new PdfPCell(new Phrase())
                        {
                            Border = Rectangle.NO_BORDER, Colspan = mainTableColumns
                        });
                        mainTable.AddCell(new PdfPCell(new Paragraph("UNREDEEMED PLEDGED GOODS MUST BE HELD BY PAWNBROKER FOR SIXTY (60 DAYS", rptFontBold))
                        {
                            Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, Colspan = mainTableColumns
                        });
                        mainTable.AddCell(new PdfPCell(new Paragraph("(NOT NECESSARILY TWO (2) MONTHS FROM NEW MATURITY DATE.", rptFontBold))
                        {
                            Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, Colspan = mainTableColumns
                        });
                        mainTable.AddCell(new PdfPCell(new Phrase())
                        {
                            Border = Rectangle.NO_BORDER, Colspan = mainTableColumns
                        });                                                                                                     // empty row
                    }

                    if (GlobalDataAccessor.Instance.CurrentSiteId.State.Equals(States.Ohio))
                    {
                        mainTable.AddCell(new PdfPCell(new Paragraph("Last Day Of Grace :", rptFontBold))
                        {
                            Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, Colspan = mainTableColumns / 2
                        });
                        mainTable.AddCell(new PdfPCell(new Paragraph(extnInfo.NewPfiEligible.FormatDate(), rptFontBold))
                        {
                            Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, Colspan = mainTableColumns / 2
                        });
                        mainTable.AddCell(new PdfPCell(new Phrase())
                        {
                            Border = Rectangle.NO_BORDER, Colspan = mainTableColumns, FixedHeight = 20
                        });                                                                                                                        // empty row
                    }
                    mainTable.AddCell(new PdfPCell(new Phrase())
                    {
                        Border = Rectangle.NO_BORDER, Colspan = mainTableColumns
                    });
                    mainTable.AddCell(new PdfPCell(new Paragraph("Pledger :", rptFont))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                    });
                    mainTable.AddCell(new PdfPCell(new Paragraph(extnInfo.CustomerName, rptFont))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                    });
                    mainTable.AddCell(new PdfPCell(new Paragraph(new Phrase()))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
                    });
                    mainTable.AddCell(new PdfPCell(new Paragraph("_________________________________________", rptFont))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, Colspan = 3
                    });

                    mainTable.AddCell(new PdfPCell(new Paragraph(new Phrase()))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, Colspan = 3
                    });
                    mainTable.AddCell(new PdfPCell(new Paragraph("Pledger", rptFont))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, Colspan = 3
                    });

                    mainTable.AddCell(new PdfPCell(new Phrase())
                    {
                        Border = Rectangle.NO_BORDER, Colspan = mainTableColumns, FixedHeight = 20
                    });                                                                                                                           // empty row
                    mainTable.AddCell(new PdfPCell(new Paragraph("PAWNBROKER:", rptFont))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, Colspan = mainTableColumns
                    });
                    mainTable.AddCell(new PdfPCell(new Paragraph("Prepare in duplicate; original to Pledgor; second copy for store file.", rptFont))
                    {
                        Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, Colspan = mainTableColumns
                    });

                    document.Add(mainTable);
                    document.Close();

                    AddDocument(extnInfo, rptFileName);
                    return(true);
                }

                FileLogger.Instance.logMessage(LogLevel.ERROR, this, "Extension memo printing failed since file name is not set");
                return(false);
            }
            catch (Exception de)
            {
                FileLogger.Instance.logMessage(LogLevel.ERROR, this, "Extension memo printing" + de.Message);
                return(false);
            }
        }
Пример #36
0
        public JsonResult AddPdfByHtml(string CoANo, string Html, string titles, string CASNo, string Specification)
        {
            titles        = titles.Substring(0, titles.Length - 1);
            Specification = Specification.Substring(0, Specification.Length - 1);
            ChemCloud_COA model             = Newtonsoft.Json.JsonConvert.DeserializeObject <ChemCloud_COA>(Html);
            List <string> titlelist         = titles.Split(';').ToList <string>();
            List <string> SpecificationList = Specification.Split(';').ToList <string>();
            string        serverFilepath    = Server.MapPath(string.Format("/Storage/PDF/{0}/ ", base.CurrentUser.Id));

            if (!System.IO.Directory.Exists(serverFilepath))
            {
                System.IO.Directory.CreateDirectory(serverFilepath);
            }
            string serverFileName = "CoAReports" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".pdf";
            Result res            = new Result();

            iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.A4);
            try
            {
                iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(serverFilepath + serverFileName, FileMode.Create));
                document.Open();
                iTextSharp.text.pdf.BaseFont bfChinese     = iTextSharp.text.pdf.BaseFont.CreateFont("C:\\WINDOWS\\Fonts\\simsun.ttc,1", iTextSharp.text.pdf.BaseFont.IDENTITY_H, iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED);
                iTextSharp.text.Font         Titlefont     = new iTextSharp.text.Font(bfChinese, 16, iTextSharp.text.Font.BOLD);
                iTextSharp.text.Font         titleDetial   = new iTextSharp.text.Font(bfChinese, 11, iTextSharp.text.Font.BOLD);
                iTextSharp.text.Font         normall       = new iTextSharp.text.Font(bfChinese, 11, iTextSharp.text.Font.NORMAL);
                iTextSharp.text.Font         newtable      = new iTextSharp.text.Font(bfChinese, 12, iTextSharp.text.Font.BOLD);
                iTextSharp.text.Font         newtableInner = new iTextSharp.text.Font(bfChinese, 12, iTextSharp.text.Font.NORMAL);
                Paragraph p = new Paragraph("CERTIFICATE OF ANALYSIS" + "\n\n", Titlefont);
                p.Alignment = iTextSharp.text.Element.ALIGN_CENTER;
                document.Add(p);
                PdfPTable table = new PdfPTable(4);
                table.DefaultCell.MinimumHeight = 30;
                table.SetWidths(new int[] { 35, 15, 35, 15 });
                PdfPCell cell;
                cell = new PdfPCell();
                Paragraph pCell;
                pCell = new Paragraph("CertificateNumber", titleDetial);
                table.AddCell(pCell);
                pCell = new Paragraph(model.CertificateNumber, normall);
                table.AddCell(pCell);
                pCell = new Paragraph("Suppiler", titleDetial);
                table.AddCell(pCell);
                pCell = new Paragraph(ServiceHelper.Create <IShopService>().GetShopName(base.CurrentSellerManager.ShopId), normall);
                table.AddCell(pCell);
                cell  = new PdfPCell();
                pCell = new Paragraph("Product Code", titleDetial);
                table.AddCell(pCell);
                pCell = new Paragraph(model.ProductCode, normall);
                table.AddCell(pCell);
                pCell = new Paragraph("Manufacturer's Batch #", titleDetial);
                table.AddCell(pCell);
                pCell = new Paragraph(model.ManufacturersBatchNo, normall);
                table.AddCell(pCell);
                cell  = new PdfPCell();
                pCell = new Paragraph("Product", titleDetial);
                table.AddCell(pCell);
                pCell = new Paragraph(model.ProductName, normall);
                table.AddCell(pCell);
                pCell = new Paragraph("Sydco's Lab.Batch #", titleDetial);
                table.AddCell(pCell);
                pCell = new Paragraph(model.SydcosLabBatchNo, normall);
                table.AddCell(pCell);
                cell  = new PdfPCell();
                pCell = new Paragraph("Date of Manufacture", titleDetial);
                table.AddCell(pCell);
                pCell = new Paragraph(model.DateofManufacture.ToShortDateString(), normall);
                table.AddCell(pCell);
                pCell = new Paragraph("ExpiryDate", titleDetial);
                table.AddCell(pCell);
                pCell = new Paragraph(model.ExpiryDate.ToShortDateString(), normall);
                table.AddCell(pCell);
                document.Add(table);
                Paragraph pfoot = new Paragraph("\n           The undersigned hereby certifies the following data to be true specification" + "\n\n\n\n\n", titleDetial);
                p.Alignment = iTextSharp.text.Element.ALIGN_CENTER;
                document.Add(pfoot);
                foreach (ChemCloud_COADetails item in model.ChemCloud_COADetails)
                {
                    PdfPTable table1 = new PdfPTable(3);
                    table1.DefaultCell.MinimumHeight = 30;
                    table1.SetWidths(new int[] { 40, 20, 35 });
                    pCell = new Paragraph("Tests", newtable);

                    table1.AddCell(pCell);
                    pCell = new Paragraph("Results", newtable);
                    table1.AddCell(pCell);
                    pCell = new Paragraph("Specifications(BP)", newtable);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(titlelist[0], newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(item.Appearance, newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(SpecificationList[0], newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(titlelist[1], newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(item.IIdentity, newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(SpecificationList[1], newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(titlelist[2], newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(item.Carbonates, newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(SpecificationList[2], newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(titlelist[3], newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(item.Solubility, newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(SpecificationList[3], newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(titlelist[4], newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(item.Ammonium, newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(SpecificationList[4], newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(titlelist[5], newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(item.Calcium, newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(SpecificationList[5], newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(titlelist[6], newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(item.Arsenic, newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(SpecificationList[6], newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(titlelist[7], newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(item.HeavyMetals, newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(SpecificationList[7], newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(titlelist[8], newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(item.Iron, newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(SpecificationList[8], newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(titlelist[9], newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(item.Sulphates, newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(SpecificationList[9], newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(titlelist[10], newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(item.Chlorides, newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(SpecificationList[10], newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(titlelist[11], newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(item.Appearanceofsolution, newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(SpecificationList[11], newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(titlelist[12], newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(item.MicroStatus, newtableInner);
                    table1.AddCell(pCell);
                    pCell = new Paragraph(SpecificationList[12], newtableInner);
                    table1.AddCell(pCell);
                    document.Add(table1);
                    Paragraph ppp = new Paragraph("\n\n\n\n\n\n", titleDetial);
                    ppp.Alignment = iTextSharp.text.Element.ALIGN_CENTER;
                    document.Add(ppp);
                }
            }

            catch (Exception de)
            {
                res.success = false;
                return(Json(res));
            }
            document.Close();
            res.success = true;
            //string pdfpath1 = string.Format("/Storage/PDF/{0}/", base.CurrentUser.Id);
            string  str = ImgHelper.PostImg(serverFilepath + serverFileName, "coapic");
            COAList cr  = new COAList()
            {
                Addtime     = DateTime.Now,
                CoANo       = CoANo,
                URL         = str,
                UserId      = base.CurrentUser.Id,
                AddUserType = 2,
                CASNo       = CASNo
            };

            ServiceHelper.Create <ICOAListService>().AddCoAReportInfo(cr);
            return(Json(res));
        }
Пример #37
0
        private void ToolStripButton8_Click(object sender, EventArgs e)
        {
            SaveFileDialog s = new SaveFileDialog
            {
                Filter = "pdf files (*.pdf)|*.pdf|All files (*.*)|*.*"
            };
            string path = "";

            if (s.ShowDialog() == DialogResult.OK)
            {
                path = s.FileName;
            }

            try
            {
                MySqlDataAdapter mda = new MySqlDataAdapter("SELECT Orders.Order_id, Service_type.Type_name, Services.Service_name, Orders.Order_date, Orders.Price, Status.Status_name FROM Orders INNER JOIN Services on(Services.Service_id=Orders.Service_id) INNER JOIN Service_type on(Services.Type_id=Service_type.Type_id) INNER JOIN Status on(Status.Status_id=Orders.Status_id) WHERE Orders.Worker_id=" + Id + " " + Search + ";", conn);
                DataSet          ds  = new DataSet();
                mda.Fill(ds, "Orders");

                iTextSharp.text.Document doc = new iTextSharp.text.Document();

                PdfWriter.GetInstance(doc, new FileStream(path, 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);

                PdfPTable table = new PdfPTable(ds.Tables["Orders"].Columns.Count);

                PdfPCell cell = new PdfPCell(new Phrase(" " + "Orders" + " ", font))
                {
                    Colspan             = ds.Tables["Orders"].Columns.Count,
                    HorizontalAlignment = PdfPCell.ALIGN_CENTER,
                    Border = 0
                };
                table.AddCell(cell);
                for (int j = 0; j < dataGridView1.ColumnCount; j++)
                {
                    cell = new PdfPCell(new Phrase(new Phrase(dataGridView1.Columns[j].HeaderText, font)))
                    {
                        BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY
                    };
                    table.AddCell(cell);
                }

                for (int j = 0; j < ds.Tables["Orders"].Rows.Count; j++)
                {
                    for (int k = 0; k < ds.Tables["Orders"].Columns.Count; k++)
                    {
                        table.AddCell(new Phrase(ds.Tables["Orders"].Rows[j][k].ToString(), font));
                    }
                }
                doc.Add(table);

                doc.Close();

                MessageBox.Show("Pdf-document saved!");
            }
            catch (Exception)
            {
                MessageBox.Show("Problems with saving to PDF format!");
            }
        }
Пример #38
0
        public void getClentOrderList(ReportBindingModel model, int clientId)
        {
            if (!File.Exists("TIMCYR.TTF"))
            {
                File.WriteAllBytes("TIMCYR.TTF", Properties.Resources.TIMCYR);
            }
            //открываем файл для работы
            FileStream fs = new FileStream(model.FileName, FileMode.OpenOrCreate, FileAccess.Write);

            //создаем документ, задаем границы, связываем документ и поток
            iTextSharp.text.Document doc = new iTextSharp.text.Document();
            doc.SetMargins(0.5f, 0.5f, 0.5f, 0.5f);
            PdfWriter writer = PdfWriter.GetInstance(doc, fs);

            doc.Open();
            BaseFont baseFont = BaseFont.CreateFont("TIMCYR.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);


            //вставляем заголовок
            var phraseTitle = new Phrase("Заказы клиента",
                                         new iTextSharp.text.Font(baseFont, 16, iTextSharp.text.Font.BOLD));

            iTextSharp.text.Paragraph paragraph = new iTextSharp.text.Paragraph(phraseTitle)
            {
                Alignment    = Element.ALIGN_CENTER,
                SpacingAfter = 12
            };
            doc.Add(paragraph);
            var phrasePeriod = new Phrase("c " + model.DateFrom.Value.ToShortDateString() +
                                          " по " + model.DateTo.Value.ToShortDateString(),
                                          new iTextSharp.text.Font(baseFont, 14, iTextSharp.text.Font.BOLD));

            paragraph = new iTextSharp.text.Paragraph(phrasePeriod)
            {
                Alignment    = Element.ALIGN_CENTER,
                SpacingAfter = 12
            };
            doc.Add(paragraph);


            //вставляем таблицу, задаем количество столбцов, и ширину колонок
            PdfPTable table = new PdfPTable(6)
            {
                TotalWidth = 800F
            };

            table.SetTotalWidth(new float[] { 160, 140, 160, 100, 100, 140 });


            //вставляем шапку
            PdfPCell cell            = new PdfPCell();
            var      fontForCellBold = new iTextSharp.text.Font(baseFont, 10, iTextSharp.text.Font.BOLD);

            table.AddCell(new PdfPCell(new Phrase("ФИО клиента", fontForCellBold))
            {
                HorizontalAlignment = Element.ALIGN_CENTER
            });
            table.AddCell(new PdfPCell(new Phrase("Дата создания", fontForCellBold))
            {
                HorizontalAlignment = Element.ALIGN_CENTER
            });
            table.AddCell(new PdfPCell(new Phrase("Изделие", fontForCellBold))
            {
                HorizontalAlignment = Element.ALIGN_CENTER
            });
            table.AddCell(new PdfPCell(new Phrase("Количество", fontForCellBold))
            {
                HorizontalAlignment = Element.ALIGN_CENTER
            });
            table.AddCell(new PdfPCell(new Phrase("Сумма", fontForCellBold))
            {
                HorizontalAlignment = Element.ALIGN_CENTER
            });
            table.AddCell(new PdfPCell(new Phrase("Статус", fontForCellBold))
            {
                HorizontalAlignment = Element.ALIGN_CENTER
            });


            //заполняем таблицу
            var list = context.Orders.Where(o => o.ClientId == clientId).Select(o => new OrderViewModel
            {
                Id         = o.Id,
                ClientId   = o.ClientId,
                Sum        = o.Sum,
                Reserved   = o.Reserved,
                Status     = o.Status.ToString(),
                DateCreate = SqlFunctions.DateName("dd", o.DateCreate) + " " +
                             SqlFunctions.DateName("mm", o.DateCreate) + " " +
                             SqlFunctions.DateName("yyyy", o.DateCreate)
            }).ToList();

            iTextSharp.text.Font fontForCells = new iTextSharp.text.Font(baseFont, 10);
            foreach (var order in list)
            {
                foreach (var op in context.OrderProducts.Where(op => op.OrderId == order.Id))
                {
                    cell = new PdfPCell(new Phrase(context.Clients.First(c => c.Id == order.ClientId).Name, fontForCells));
                    table.AddCell(cell);
                    cell = new PdfPCell(new Phrase(order.DateCreate, fontForCells));
                    table.AddCell(cell);

                    cell = new PdfPCell(new Phrase(context.Products.First(p => p.Id == op.ProductId).Name, fontForCells));
                    table.AddCell(cell);
                    cell = new PdfPCell(new Phrase(op.Count.ToString(), fontForCells));
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    table.AddCell(cell);

                    cell = new PdfPCell(new Phrase((context.Products.First(p => p.Id == op.ProductId).Price *op.Count).ToString(), fontForCells));
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    table.AddCell(cell);
                    cell = new PdfPCell(new Phrase(order.Status, fontForCells));
                    table.AddCell(cell);
                }
            }

            //вставляем итого
            cell = new PdfPCell(new Phrase("Итого:", fontForCellBold))
            {
                HorizontalAlignment = Element.ALIGN_RIGHT,
                Colspan             = 4,
                Border = 0
            };
            table.AddCell(cell);
            cell = new PdfPCell(new Phrase(list.Sum(rec => rec.Sum).ToString(), fontForCellBold))
            {
                HorizontalAlignment = Element.ALIGN_RIGHT,
                Border = 0
            };
            table.AddCell(cell);
            cell = new PdfPCell(new Phrase("", fontForCellBold))
            {
                Border = 0
            };
            table.AddCell(cell);


            //вставляем таблицу
            doc.Add(table);
            doc.Close();

            SendEmail(model.Email, "Оповещение по заказам", "", model.FileName);
        }
Пример #39
0
 public void End()
 {
     document.Close();
 }
Пример #40
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.");
            }
        }
        private void Button_Click(object sender, RoutedEventArgs e)   //Sauvgarder le profile topographique en pdf
        {
            RenderTargetBitmap rtb = new RenderTargetBitmap((int)chart.ActualWidth, (int)chart.ActualHeight, 96, 96, PixelFormats.Pbgra32);

            rtb.Render(visual: chart);
            PngBitmapEncoder png = new PngBitmapEncoder();

            png.Frames.Add(BitmapFrame.Create(rtb));
            MemoryStream stream = new MemoryStream();

            png.Save(stream);
            SaveToPng(chart, "MyChart.png");                                                                          //le nom de l'image

            iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A3, 10, 40, 42, 35); //les dimensions du fichier pdf


            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName   = "Document"; // Default file name
            dlg.DefaultExt = ".pdf";     // Default file extension
                                         //dlg.Filter = "Text documents (.topo)|*.topo"; // Filter files by extension

            // Show open file dialog box
            Nullable <bool> result = dlg.ShowDialog();

            // Process open file dialog box results
            string filename = null;

            if (result == true)
            {
                // Open document
                filename = dlg.FileName;
            }
            try
            {
                PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(filename, FileMode.Create));
            }
            catch (ArgumentNullException excp)
            {
                MessageBox.Show("il faut specifier un fichier pdf"); //le cas de ne pas selectioner un fichier
            }


            //L'exportation en pdf


            doc.Open();
            iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance("./MyChart.PNG");
            jpg.Border      = iTextSharp.text.Rectangle.BOX;
            jpg.BorderWidth = 5f;
            doc.Add(jpg);
            iTextSharp.text.Paragraph paragraph = new iTextSharp.text.Paragraph();
            paragraph.Font      = new Font(FontFactory.GetFont("Arial", 16, Font.BOLD));
            paragraph.Alignment = Element.ALIGN_CENTER;//here is the change
            paragraph.Add("Profile Topographique");
            doc.Add(paragraph);

            Viewbox viewbox = new Viewbox(); //Ajuster la photo dans un cadre



            doc.Close();
            Export.IsEnabled = false; //desactivation du button de l'exportation
        }
Пример #42
0
        public static string test(string path, string filename)
        {
            PDF.Document doc  = new PDF.Document(PDF.PageSize.A4, 20, 20, 42, 42);
            FileStream   file = new FileStream(path + filename, FileMode.OpenOrCreate);
            PdfWriter    pdf  = PdfWriter.GetInstance(doc, file);

            doc.Open();



            /* LOGO BILLET */
            PDF.Image logoBilleterie = PDF.Image.GetInstance("~/Content/logo_bg1.png");
            logoBilleterie.ScalePercent(20.0f);



            PdfPTable table1 = new PdfPTable(2);

            table1.DefaultCell.Border = 0;
            table1.WidthPercentage    = 80;


            PdfPCell cell11 = new PdfPCell();

            cell11.Colspan = 1;
            cell11.AddElement(new PDF.Paragraph("ABC Traders Receipt"));
            cell11.AddElement(new PDF.Paragraph("Thankyou for shoping at ABC traders,your order details are below"));


            cell11.VerticalAlignment = PDF.Element.ALIGN_LEFT;

            PdfPCell cell12 = new PdfPCell();


            cell12.VerticalAlignment = PDF.Element.ALIGN_CENTER;


            table1.AddCell(cell11);

            table1.AddCell(cell12);


            PdfPTable table2 = new PdfPTable(3);

            //One row added

            PdfPCell cell21 = new PdfPCell();

            cell21.AddElement(new PDF.Paragraph("Photo Type"));

            PdfPCell cell22 = new PdfPCell();

            cell22.AddElement(new PDF.Paragraph("No. of Copies"));

            PdfPCell cell23 = new PdfPCell();

            cell23.AddElement(new PDF.Paragraph("Amount"));


            table2.AddCell(cell21);

            table2.AddCell(cell22);

            table2.AddCell(cell23);


            //New Row Added

            PdfPCell cell31 = new PdfPCell();

            cell31.AddElement(new PDF.Paragraph("Safe"));

            cell31.FixedHeight = 300.0f;

            PdfPCell cell32 = new PdfPCell();

            cell32.AddElement(new PDF.Paragraph("2"));

            cell32.FixedHeight = 300.0f;

            PdfPCell cell33 = new PdfPCell();

            cell33.AddElement(new PDF.Paragraph("20.00 * " + "2" + " = " + (20 * Convert.ToInt32("2")) + ".00"));

            cell33.FixedHeight = 300.0f;



            table2.AddCell(cell31);

            table2.AddCell(cell32);

            table2.AddCell(cell33);


            PdfPCell cell2A = new PdfPCell(table2);

            cell2A.Colspan = 2;

            table1.AddCell(cell2A);

            PdfPCell cell41 = new PdfPCell();

            cell41.AddElement(new PDF.Paragraph("Name : " + "ABC"));

            cell41.AddElement(new PDF.Paragraph("Advance : " + "advance"));

            cell41.VerticalAlignment = PDF.Element.ALIGN_LEFT;

            PdfPCell cell42 = new PdfPCell();

            cell42.AddElement(new PDF.Paragraph("Customer ID : " + "011"));

            cell42.AddElement(new PDF.Paragraph("Balance : " + "3993"));

            cell42.VerticalAlignment = PDF.Element.ALIGN_RIGHT;


            table1.AddCell(cell41);

            table1.AddCell(cell42);


            doc.Add(table1);
            doc.Close();
            return(filename);
        }
        private void button5_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\\Account Report" + 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("Account Report"));

                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 Account: " + labelTotalAccount.Text, fontTable3));
                tableInfo.AddCell(new Phrase("Total Balance: " + labelTotalBalance.Text, 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\\Account Report" + DateTime.Now.Date.ToString("ddMMyyyy") + ".pdf");
            }
        }
Пример #44
0
        private void button1_Click(object sender, EventArgs e)
        {
            int AA;

            button1.Enabled = true;
            if (TotalPriceLib.Text != "0" || Total_in_Cafe.Text != "0")
            {
                double a;
                string first1  = TotalPriceLib.Text;
                string second1 = Total_in_Cafe.Text;
                double.TryParse(second1, out double secondD);
                double.TryParse(first1, out double firstD);
                a = firstD + secondD;
                TotalTotalLbl.Text = a.ToString();

                using (SaveFileDialog sfd = new SaveFileDialog()
                {
                    Filter = "PDF file|.pdf", ValidateNames = true
                })
                {
                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.A4.Rotate());
                        try
                        {
                            PdfWriter.GetInstance(doc, new FileStream(sfd.FileName, FileMode.OpenOrCreate));
                            doc.Open();
                            doc.Add(new iTextSharp.text.Paragraph("Total price : \n"));
                            doc.Add(new iTextSharp.text.Paragraph(TotalTotalLbl.Text));
                            doc.Add(new iTextSharp.text.Paragraph("\nEnd!"));

                            //doc.Pages.Add
                            //    doc.Add(new iTextSharp.text.Paragraph(DateTime.Now));
                            //Image image = new Image(@"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ9zJZcEV_YhZbsxSPbG8asz92NCpzao9r9pw&usqp=CAU", 0, 0);
                            //  page.Elements.Add(image);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        finally {
                            doc.Close();
                        }
                    }
                }



                // button1.Enabled=false;


                // button1.Enabled = false;
            }
            if (TotalPriceLib.Text == "0" || Total_in_Cafe.Text == "0")
            {
                button1.Enabled = true;
            }
            button1.Enabled = false;
            //TotalTotalLbl.Text;
            //TotalPriceLib

            //Total_in_Cafe
        }
Пример #45
0
        public ResultResponse GenerateWorkerBarcode(List <UserInformation> users)
        {
            ResultResponse resultResponse = new ResultResponse();

            var pgSize = new iTextSharp.text.Rectangle(225, 75);                             //100,65 //200,65

            iTextSharp.text.Document doc = new iTextSharp.text.Document(pgSize, 0, 0, 2, 2); //0,0,0,0
            string   path     = HttpContext.Current.Server.MapPath("~/GenaratePDF/");
            DateTime dt       = DateTime.Now;
            string   fileName = dt.Minute.ToString() + dt.Second.ToString() + dt.Millisecond.ToString();

            PdfWriter.GetInstance(doc, new FileStream(path + fileName + ".pdf", FileMode.Create));
            //open the document for writing
            doc.Open();
            // doc.SetPageSize(new iTextSharp.text.Rectangle(100,65));
            PdfPTable pdftable = new PdfPTable(1);

            for (int i = 0; i < users.Count; i++)
            {
                int count = 0;
                iTextSharp.text.Font font = FontFactory.GetFont("Calibri", 6.0f, BaseColor.BLACK);     // from 5.0f
                count++;
                // var bw = new ZXing.BarcodeWriter();
                //var encOptions = new ZXing.Common.EncodingOptions() { Margin = 0 }; // margin 0 to 1
                //bw.Options = encOptions;
                //bw.Format = ZXing.BarcodeFormat.PDF_417;
                var bw = new ZXing.BarcodeWriter()
                {
                    Format = ZXing.BarcodeFormat.PDF_417
                };
                bw.Options = new ZXing.Common.EncodingOptions()
                {
                    Margin = 1
                };
                var result = new Bitmap(bw.Write(users[i].UserSQNumber), new Size(210, 55));   //200,50
                result.Save(path + users[i].UserSQNumber, System.Drawing.Imaging.ImageFormat.Png);
                string first = "Employee Code : " + users[i].UserSQNumber;
                string last  = users[i].UserInformationName.ToString() + " - " + users[i].DesignationName.ToString();
                iTextSharp.text.Paragraph paragraph     = new iTextSharp.text.Paragraph(first, font);
                iTextSharp.text.Paragraph lastparagraph = new iTextSharp.text.Paragraph(last, font);
                paragraph.SetLeading(0.8f, 0.8f);
                paragraph.SpacingAfter = 1;
                lastparagraph.SetLeading(0.8f, 0.8f);
                lastparagraph.SpacingBefore = 1;
                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(path + users[i].UserSQNumber);
                // image.ScaleToFit(new iTextSharp.text.Rectangle(85, 100));
                //image.SetAbsolutePosition(0.0f,0.0f);
                //  image.PaddingTop = 5;
                PdfPCell cell = new PdfPCell {
                    PaddingLeft = 0, PaddingTop = 0, PaddingBottom = 0, PaddingRight = 0
                };
                // cell.FixedHeight = 60;
                cell.AddElement(paragraph);
                cell.AddElement(image);
                cell.AddElement(lastparagraph);
                cell.Border = 0;
                pdftable.AddCell(cell);
                File.Delete(path + users[i].UserSQNumber);
            }
            doc.Add(pdftable);
            doc.Close();
            resultResponse.isSuccess = true;
            resultResponse.data      = path + fileName + ".pdf";
            return(resultResponse);
        }
Пример #46
0
        private void Button4_Click(object sender, EventArgs e)
        {
            SaveFileDialog s = new SaveFileDialog
            {
                Filter = "pdf files (*.pdf)|*.pdf|All files (*.*)|*.*"
            };
            string path = "";

            if (s.ShowDialog() == DialogResult.OK)
            {
                path = s.FileName;
            }

            try
            {
                string sql = "";
                if (Search == "")
                {
                    sql = "SELECT Detail_order.D_Order_id, Detail.Detail_name, Detail.Prod_country, Detail.Price, Detail_order.D_Order_date, Detail_order.D_Count, Worker.Worker_surname, Worker.Worker_name, Status.Status_name FROM Detail_order INNER JOIN Detail on(Detail_order.Detail_id=Detail.Detail_id) INNER JOIN Status on(Detail_order.Status_id=Status.Status_id) INNER JOIN Worker on(Worker.Worker_id=Detail_order.Worker_id);";
                }
                else
                {
                    sql = "SELECT Detail_order.D_Order_id, Detail.Detail_name, Detail.Prod_country, Detail.Price, Detail_order.D_Order_date, Detail_order.D_Count, Worker.Worker_surname, Worker.Worker_name, Status.Status_name FROM Detail_order INNER JOIN Detail on(Detail_order.Detail_id=Detail.Detail_id) INNER JOIN Status on(Detail_order.Status_id=Status.Status_id) INNER JOIN Worker on(Worker.Worker_id=Detail_order.Worker_id) WHERE" + Search + ";";
                }
                MySqlDataAdapter mda = new MySqlDataAdapter(sql, conn);
                DataSet          ds  = new DataSet();
                mda.Fill(ds, "Detail_order");

                iTextSharp.text.Document doc = new iTextSharp.text.Document();

                PdfWriter.GetInstance(doc, new FileStream(path, 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);

                PdfPTable table = new PdfPTable(ds.Tables["Detail_order"].Columns.Count);

                PdfPCell cell = new PdfPCell(new Phrase(" " + this.Text + " ", font))
                {
                    Colspan             = ds.Tables["Detail_order"].Columns.Count,
                    HorizontalAlignment = PdfPCell.ALIGN_CENTER,
                    Border = 0
                };
                table.AddCell(cell);
                for (int j = 0; j < dataGridView1.ColumnCount; j++)
                {
                    cell = new PdfPCell(new Phrase(new Phrase(dataGridView1.Columns[j].HeaderText, font)))
                    {
                        BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY
                    };
                    table.AddCell(cell);
                }

                for (int j = 0; j < ds.Tables["Detail_order"].Rows.Count; j++)
                {
                    for (int k = 0; k < ds.Tables["Detail_order"].Columns.Count; k++)
                    {
                        table.AddCell(new Phrase(ds.Tables["Detail_order"].Rows[j][k].ToString(), font));
                    }
                }
                doc.Add(table);

                doc.Close();

                MessageBox.Show("Pdf-документ збережено!");
            }
            catch (Exception)
            {
                MessageBox.Show("Проблеми конвертації до PDF формату!");
            }
        }
Пример #47
0
        public override byte[] Render(global::Campus.Report.Base.Report report)
        {
            byte[] buffer;

            using (var outputMemoryStream = new MemoryStream())
            {
                var pdfDocument = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 50, 25, 15, 10);

                var arialuniTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "arial.ttf");
                FontFactory.Register(arialuniTff);

                //FontFactory.Register(Environment.GetFolderPath(Environment.SpecialFolder.Fonts));

                var pdfWriter = PdfWriter.GetInstance(pdfDocument, outputMemoryStream);

                pdfWriter.CloseStream = false;
                pdfDocument.Open();

                //pdfDocument.NewPage();
                pdfDocument.Add(new Paragraph(new Phrase(" ")));

                foreach (var x in report)
                {
                    if (x is TextElement)
                    {
                        var element = x as TextElement;

                        if (Render(element, pdfDocument, arialuniTff))
                        {
                            continue;
                        }
                    }

                    if (x is TableElement)
                    {
                        var element = x as TableElement;
                        if (Render(element, pdfDocument, arialuniTff))
                        {
                            continue;
                        }
                    }

                    if (x is ImageElement)
                    {
                        var element = x as ImageElement;

                        if (Render(element, pdfDocument))
                        {
                            continue;
                        }
                    }

                    if (x is ComplexHeaderCell)
                    {
                        var element = x as ComplexHeaderCell;

                        if (Render(element, pdfDocument))
                        {
                            continue;
                        }
                    }

                    if (x is ComplexHeader)
                    {
                        var element = x as ComplexHeader;

                        if (Render(element, pdfDocument))
                        {
                            continue;
                        }
                    }
                }

                pdfDocument.Close();
                pdfDocument.CloseDocument();

                buffer = new byte[outputMemoryStream.Position];
                outputMemoryStream.Position = 0;
                outputMemoryStream.Read(buffer, 0, buffer.Length);
            }

            return(buffer);
        }
Пример #48
0
    protected void Page_Load(object sender, EventArgs e)
    {
        var learningId = Convert.ToInt32(Request.QueryString["id"]);
        var companyId = Convert.ToInt32(Request.QueryString["companyId"]);
        var company = new Company(companyId);
        var res = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;
        var dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary<string, string>;
        var learning = new Learning(learningId, companyId);

        string path = HttpContext.Current.Request.PhysicalApplicationPath;

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

        var formatedDescription = ToolsPdf.NormalizeFileName(learning.Description);

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

        // FONTS
        var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;
        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts);
        }

        this.headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        this.arial = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        var descriptionFont = new Font(this.headerFont, 12, Font.BOLD, BaseColor.BLACK);

        var document = new iTextSharp.text.Document(PageSize.A4, 40, 40, 65, 55);

        var writer = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create));
        var pageEventHandler = new TwoColumnHeaderFooter()
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId),
            IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy = string.Format(CultureInfo.InvariantCulture, "{0}", user.UserName),
            CompanyId = learning.CompanyId,
            CompanyName = company.Name,
            Title = dictionary["Item_Learning"]
        };

        writer.PageEvent = pageEventHandler;

        var borderSides = Rectangle.RIGHT_BORDER + Rectangle.LEFT_BORDER + Rectangle.BOTTOM_BORDER;

        document.Open();

        #region Dades bàsiques
        // Ficha pincipal
        var table = new PdfPTable(6)
        {
            WidthPercentage = 100,
            HorizontalAlignment = 0
        };

        table.SetWidths(new float[] { 30f, 30f, 30f, 30f, 30f, 30f });

        table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_Course"]));
        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(learning.Description, descriptionFont))
        {
            Border = 0,
            BackgroundColor = new iTS.BaseColor(255, 255, 255),
            Padding = 6f,
            PaddingTop = 4f,
            HorizontalAlignment = Rectangle.ALIGN_LEFT,
            Colspan = 5
        });

        table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_EstimatedDate"]));
        table.AddCell(ToolsPdf.DataCell(learning.DateEstimated, descriptionFont));

        table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_Hours"]));
        table.AddCell(ToolsPdf.DataCell(learning.Hours, descriptionFont));

        string statusText = string.Empty;
        switch (learning.Status)
        {
            case 1: statusText = dictionary["Item_Learning_Status_Started"]; break;
            case 2: statusText = dictionary["Item_Learning_Status_Finished"]; break;
            case 3: statusText = dictionary["Item_Learning_Status_Evaluated"]; break;
            default: statusText = dictionary["Item_Learning_Status_InProgress"]; break;
        }

        table.AddCell(TitleLabel(dictionary["Item_Learning_ListHeader_Status"]));
        table.AddCell(ToolsPdf.DataCell(statusText, descriptionFont));

        table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_StartDate"]));
        table.AddCell(ToolsPdf.DataCell(learning.RealStart, descriptionFont));

        table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_EndDate"]));
        table.AddCell(ToolsPdf.DataCell(learning.RealFinish, descriptionFont));

        table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_Amount"]));
        table.AddCell(ToolsPdf.DataCellMoney(learning.Amount, descriptionFont));

        table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_Coach"]));
        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(learning.Master, descriptionFont))
        {
            Border = 0,
            BackgroundColor = new iTS.BaseColor(255, 255, 255),
            Padding = 6f,
            PaddingTop = 4f,
            HorizontalAlignment = Rectangle.ALIGN_LEFT,
            Colspan = 5
        });

        // Objective
        table.AddCell(SeparationRow());
        table.AddCell(TitleAreaCell(dictionary["Item_Learning_Objetive"]));
        table.AddCell(TextAreaCell(Environment.NewLine + learning.Objective, borderSides, Rectangle.ALIGN_LEFT, 6));

        // Methodology
        table.AddCell(SeparationRow());
        table.AddCell(TitleAreaCell(dictionary["Item_Learning_FieldLabel_Methodology"]));
        table.AddCell(TextAreaCell(Environment.NewLine + learning.Methodology, borderSides, Rectangle.ALIGN_LEFT, 6));

        // Notes
        table.AddCell(SeparationRow());
        table.AddCell(TitleAreaCell(dictionary["Item_Learning_FieldLabel_Notes"]));
        table.AddCell(TextAreaCell(Environment.NewLine + learning.Notes, borderSides, Rectangle.ALIGN_LEFT, 6));

        document.Add(table);
        #endregion

        #region Asistentes
        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 headerFontFinal = new iTS.Font(headerFont, 9, iTS.Font.NORMAL, iTS.BaseColor.BLACK);

        document.SetPageSize(PageSize.A4.Rotate());
        document.NewPage();

        var tableAssistants = new iTSpdf.PdfPTable(3)
        {
            WidthPercentage = 100,
            HorizontalAlignment = 1,
            SpacingBefore = 20f
        };

        tableAssistants.SetWidths(new float[] { 90f, 20f, 20f });
        tableAssistants.AddCell(new PdfPCell(new Phrase(learning.Description, descriptionFont))
        {
            Colspan = 5,
            Border = Rectangle.NO_BORDER,
            PaddingTop = 20f,
            PaddingBottom = 20f,
            HorizontalAlignment = Element.ALIGN_CENTER
        });

        tableAssistants.AddCell(ToolsPdf.HeaderCell(dictionary["Item_LearningAssistants"]));
        tableAssistants.AddCell(ToolsPdf.HeaderCell(dictionary["Item_LearningAssistant_Status_Done"]));
        tableAssistants.AddCell(ToolsPdf.HeaderCell(dictionary["Item_LearningAssistant_Status_Evaluated"]));

        int cont = 0;
        bool pair = false;
        var times = new iTS.Font(arial, 8, iTS.Font.NORMAL, iTS.BaseColor.BLACK);
        var timesBold = new iTS.Font(arial, 8, iTS.Font.BOLD, iTS.BaseColor.BLACK);
        learning.ObtainAssistance();
        foreach (var assistance in learning.Assistance)
        {
            int border = 0;
            var lineBackground = pair ? rowEven : rowPair;

            tableAssistants.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(assistance.Employee.FullName, times))
            {
                Border = border,
                BackgroundColor = lineBackground,
                Padding = ToolsPdf.PaddingTableCell,
                PaddingTop = ToolsPdf.PaddingTopTableCell
            });

            string completedText = string.Empty;
            if (assistance.Completed.HasValue)
            {
                completedText = assistance.Completed.Value ? dictionary["Common_Yes"] : dictionary["Common_No"];
            }

            tableAssistants.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(completedText, times))
            {
                Border = border,
                BackgroundColor = lineBackground,
                HorizontalAlignment = Element.ALIGN_CENTER,
                Padding = ToolsPdf.PaddingTableCell,
                PaddingTop = ToolsPdf.PaddingTopTableCell
            });

            string successText = string.Empty;
            if (assistance.Success.HasValue)
            {
                successText = assistance.Success.Value ? dictionary["Common_Yes"] : dictionary["Common_No"];
            }

            tableAssistants.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(successText, times))
            {
                Border = border,
                BackgroundColor = lineBackground,
                HorizontalAlignment = Element.ALIGN_CENTER,
                Padding = ToolsPdf.PaddingTableCell,
                PaddingTop = ToolsPdf.PaddingTopTableCell
            });
            cont++;
        }

        // TotalRow
        if(learning.Assistance.Count == 0)
        {
            tableAssistants.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_LearningList_NoAssistants"], descriptionFont))
            {
                Border = iTS.Rectangle.TOP_BORDER,
                BackgroundColor = rowEven,
                Padding = ToolsPdf.PaddingTableCell,
                PaddingTop = ToolsPdf.PaddingTopTableCell,
                Colspan = 3,
                HorizontalAlignment = Rectangle.ALIGN_CENTER
            });
        }

        tableAssistants.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(
            CultureInfo.InvariantCulture,
            @"{0}: {1}",
            dictionary["Common_RegisterCount"],
            cont), times))
        {
            Border = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = rowEven,
            Padding = ToolsPdf.PaddingTableCell,
            PaddingTop = ToolsPdf.PaddingTopTableCell,
            Colspan = 3
        });

        document.Add(tableAssistants);
        #endregion

        document.Close();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf");
        Response.ContentType = "application/pdf";
        Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName);
        Response.Flush();
        Response.Clear();
    }
        protected void SonucYazdır_Click(object sender, EventArgs e)
        {
            MongoClient client        = new MongoClient();
            var         database      = client.GetDatabase("hastane");
            var         collection    = database.GetCollection <yatanhastalar>("yatanhastalar");
            var         servislistesi = collection.Find(x => x._id != null).ToList().SelectMany(x => x.ServisList).ToList();
            var         hastalistesi  = servislistesi.SelectMany(x => x.HastaList).ToList().Where(x => x._id == ObjectId.Parse(ddlHasta2.SelectedValue)).ToList().FirstOrDefault();

            var sonuc = database.GetCollection <islemsonuc>("sonuclistesi").Find(x => x._id == ObjectId.Parse(ddlsonuctarih.SelectedValue) && x.sonuc_cesidi == "Laboratuvar").ToList().SelectMany(x => x.SonucList).ToList();



            #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, 13, 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 Sonuç pdf oluştur
            iTextSharp.text.Document pdfFile = new iTextSharp.text.Document();
            PdfWriter.GetInstance(pdfFile, new FileStream("C:\\Users\\Önder\\Desktop\\Yeni klasör\\Kan Sonucu (" + hastalistesi.hasta_adi + " " + hastalistesi.hasta_soyadi + " " + ddlsonuctarih.SelectedItem.Text + ").pdf", FileMode.Create));
            pdfFile.Open();
            #endregion

            #region Sonuç oluşturan bilgileri
            pdfFile.AddCreator("Önder");      //Oluşturan kişinin isminin eklenmesi
            pdfFile.AddCreationDate();        //Oluşturulma tarihinin eklenmesi
            pdfFile.AddAuthor("Laboratuvar"); //Yazarın isiminin eklenmesi
            pdfFile.AddHeader("Başlık", "PDF UYGULAMASI OLUSTUR");
            pdfFile.AddTitle("Sonuç Raporu"); //Başlık ve title eklenmesi
            #endregion

            #region Sonuç firma resmi ve tarihi oluştur
            iTextSharp.text.Image jpgimg = iTextSharp.text.Image.GetInstance(@"C:/Users/Önder/Desktop/Önder Fatih Buhurcu Staj Projesi/WebApplicationHastane/WebApplicationHastane/login/images/İsimsiz-1.png");
            jpgimg.ScalePercent(35);
            jpgimg.Alignment = iTextSharp.text.Image.LEFT_ALIGN;

            PdfPTable pdfTableHeader = new PdfPTable(3);
            pdfTableHeader.TotalWidth         = 500f;
            pdfTableHeader.LockedWidth        = true;
            pdfTableHeader.DefaultCell.Border = Rectangle.NO_BORDER;

            PdfPCell cellheader1 = new PdfPCell(jpgimg);
            cellheader1.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
            cellheader1.VerticalAlignment   = PdfPCell.ALIGN_BOTTOM;
            cellheader1.FixedHeight         = 60f;
            cellheader1.Border = 0;
            pdfTableHeader.AddCell(cellheader1);

            PdfPCell cellheader2 = new PdfPCell(new Phrase("SONUÇ RAPORU", fontArialHeader));
            cellheader2.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            cellheader2.VerticalAlignment   = PdfPCell.ALIGN_MIDDLE;
            cellheader2.FixedHeight         = 60f;
            cellheader2.Border = 0;
            pdfTableHeader.AddCell(cellheader2);


            PdfPCell cellheader3 = new PdfPCell(new Phrase(DateTime.Now.ToShortDateString(), fontArial));
            cellheader3.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
            cellheader3.VerticalAlignment   = PdfPCell.ALIGN_MIDDLE;
            cellheader3.FixedHeight         = 60f;
            cellheader3.Border = 0;
            pdfTableHeader.AddCell(cellheader3);
            #endregion

            Phrase p = new Phrase("\n");

            Paragraph yazi = new Paragraph("Hasta TC: " + hastalistesi.hasta_tc + "\nHasta Adı: " + hastalistesi.hasta_adi + "\nHasta Soyadı: " + hastalistesi.hasta_soyadi + "\n\n\n");


            #region Tabloyu Oluştur
            PdfPTable pdfTable = new PdfPTable(2);
            pdfTable.TotalWidth              = 500f;
            pdfTable.LockedWidth             = true;
            pdfTable.HorizontalAlignment     = 1;
            pdfTable.DefaultCell.Padding     = 5;
            pdfTable.DefaultCell.BorderColor = iTextSharp.text.BaseColor.GRAY;
            foreach (var item in sonuc)
            {
                pdfTable.AddCell(new Phrase(item.tahlil_adi, fontArialboldgeneral));
                pdfTable.AddCell(new Phrase(item.sonuc, fontArial));
            }
            #endregion

            #region Pdfe yaz ve dosyayı kapat
            if (pdfFile.IsOpen() == false)
            {
                pdfFile.Open();
            }
            pdfFile.Add(pdfTableHeader);
            pdfFile.Add(p);
            pdfFile.Add(yazi);
            pdfFile.Add(pdfTable);
            pdfFile.Close();
            #endregion
        }
Пример #50
0
        public ResultResponse SaveBarcodes(BarcodeGenarateModal barcodeGenarateModal, int userId)
        {
            ResultResponse resultResponse   = new ResultResponse();
            int            masterPrimaryKey = 0;

            try
            {
                accessManager.SqlConnectionOpen(DataBase.WorkerInsentive);
                List <SqlParameter> aParameters = new List <SqlParameter>();
                aParameters.Add(new SqlParameter("@StyleNo", barcodeGenarateModal.StyleID));
                aParameters.Add(new SqlParameter("@GenarateDate", barcodeGenarateModal.SelectDate));
                aParameters.Add(new SqlParameter("@BundleQuantity", barcodeGenarateModal.Quantity));
                aParameters.Add(new SqlParameter("@Size", barcodeGenarateModal.BundleSize));
                aParameters.Add(new SqlParameter("@Color", barcodeGenarateModal.Color));
                aParameters.Add(new SqlParameter("@CreateBy", userId));
                aParameters.Add(new SqlParameter("@CutNo", barcodeGenarateModal.CutNo));
                aParameters.Add(new SqlParameter("@ShadeNo", barcodeGenarateModal.ShadeNO));
                aParameters.Add(new SqlParameter("@BuyerId", barcodeGenarateModal.BuyerID));
                aParameters.Add(new SqlParameter("@PONumber", barcodeGenarateModal.PONumber));
                aParameters.Add(new SqlParameter("@QuantityGenarate", (barcodeGenarateModal.Quantity * barcodeGenarateModal.NoOfBundle)));
                aParameters.Add(new SqlParameter("@BusinessUnitId", barcodeGenarateModal.BusinessUnitId));
                aParameters.Add(new SqlParameter("@MachineId", barcodeGenarateModal.MachineId));
                aParameters.Add(new SqlParameter("@LotNo", barcodeGenarateModal.LotNo));
                masterPrimaryKey = accessManager.SaveDataReturnPrimaryKey("sp_SaveGenaratedMasterTable", aParameters);
            }
            catch (Exception exception)
            {
                accessManager.SqlConnectionClose(true);
                throw exception;
            }
            finally
            {
                accessManager.SqlConnectionClose();
            }
            var pgSize = new iTextSharp.text.Rectangle(225, 75);                             //225,75

            iTextSharp.text.Document doc = new iTextSharp.text.Document(pgSize, 0, 0, 2, 2); //0,0,0,0
            string   path     = HttpContext.Current.Server.MapPath("~/GenaratePDF/");
            DateTime dt       = DateTime.Now;
            string   fileName = dt.Minute.ToString() + dt.Second.ToString() + dt.Millisecond.ToString();

            PdfWriter.GetInstance(doc, new FileStream(path + fileName + ".pdf", FileMode.Create));
            //open the document for writing
            doc.Open();
            // doc.SetPageSize(new iTextSharp.text.Rectangle(100,65));
            PdfPTable pdftable = new PdfPTable(1);

            for (int i = 0; i < barcodeGenarateModal.NoOfBundle; i++)
            {
                int count = 0;
                iTextSharp.text.Font font     = FontFactory.GetFont("Calibri", 6f, BaseColor.BLACK); // from 5.0f
                iTextSharp.text.Font fontlast = FontFactory.GetFont("Calibri", 6f, BaseColor.BLACK); // from 5.0f
                //String header = "Buyer Name : " + barcodeGenarateModal.BuyerName+"\nStyle : " + barcodeGenarateModal.StyleName + "\nBundle Quantity : " + barcodeGenarateModal.Quantity +
                //        "\nBundle No : " + (i+1) + "\nColor : " + barcodeGenarateModal.Color + ", Size : " + barcodeGenarateModal.BundleSize+ "\nPO Number : " + barcodeGenarateModal.PONumber;
                //iTextSharp.text.Paragraph paraheader = new iTextSharp.text.Paragraph(header, font);
                //PdfPCell cell1 = new PdfPCell { PaddingLeft = 0, PaddingTop = 0, PaddingBottom = 0, PaddingRight = 0 };
                // cell1.AddElement(paraheader);
                // cell1.Border = 0;
                //pdftable.AddCell(cell1);
                foreach (CommonModel barcodeGenarate in barcodeGenarateModal.OprationList)
                {
                    count++;
                    int barcodeNo = BarcodePrimaryKey(masterPrimaryKey, i + 1, barcodeGenarate, barcodeGenarateModal.BusinessUnitId);
                    var bw        = new ZXing.BarcodeWriter()
                    {
                        Format = ZXing.BarcodeFormat.PDF_417
                    };
                    bw.Options = new ZXing.Common.EncodingOptions()
                    {
                        Margin = 1
                    };

                    // var encOptions = new ZXing.Common.EncodingOptions() { Margin = 0}; // margin 0 to 1

                    //bw.Format = ZXing.BarcodeFormat.CODE_128;
                    var    bitmap = bw.Write(barcodeNo + "," + barcodeGenarate.OperationSMV);
                    Bitmap result = new Bitmap(bitmap, new Size(210, 55));  //100,60 // 210,60
                    //var result = new Bitmap();
                    result.Save(path + barcodeGenarate.OperationName, System.Drawing.Imaging.ImageFormat.Png);
                    //barcodeNo + "-" +
                    string first = barcodeNo + " , " + barcodeGenarateModal.StyleName + ", " + barcodeGenarate.OperationName + "," + barcodeGenarateModal.BundleSize;
                    string last  = barcodeGenarate.OperationSMV +
                                   ", " + barcodeGenarateModal.SelectDate + ","
                                   + barcodeGenarateModal.Quantity +
                                   ", " + (i + 1) + "-" + count + ", " + barcodeGenarateModal.Color + "," + barcodeGenarateModal.PONumber;

                    iTextSharp.text.Paragraph paragraph     = new iTextSharp.text.Paragraph(first, font);
                    iTextSharp.text.Paragraph lastparagraph = new iTextSharp.text.Paragraph(last, fontlast);
                    paragraph.SetLeading(0.8f, 0.8f);
                    paragraph.SpacingAfter = 1;    //2
                    lastparagraph.SetLeading(0.8f, 0.8f);
                    iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(path + barcodeGenarate.OperationName);
                    //image.SpacingAfter = 5;// for code 128
                    //image.ScaleAbsolute(85,50);
                    // image.PaddingTop = 3.0f;
                    PdfPCell cell = new PdfPCell {
                        PaddingLeft = 0, PaddingTop = 0, PaddingBottom = 0, PaddingRight = 0
                    };
                    // cell.FixedHeight = 60;
                    cell.AddElement(paragraph);
                    cell.AddElement(image);
                    cell.AddElement(lastparagraph);
                    cell.Border = 0;
                    pdftable.AddCell(cell);
                    File.Delete(path + barcodeGenarate.OperationName);
                }
            }
            doc.Add(pdftable);
            doc.Close();
            resultResponse.isSuccess = true;
            resultResponse.data      = path + fileName + ".pdf";
            return(resultResponse);
        }
Пример #51
0
        public string PrintVoucher(paymentvoucher pvh, List <paymentvoucherdetail> pvDetails)
        {
            string fileName = "";

            try
            {
                string payMode = "";
                if (pvh.BookType.Equals("BANKBOOK"))
                {
                    payMode = "Bank";
                }
                else
                {
                    payMode = "Cash";
                }
                string HeaderString = "No : " + pvh.VoucherNo + Main.delimiter1 + "Date : " + pvh.VoucherDate.ToString("dd-MM-yyyy") +
                                      Main.delimiter1 + "Payment Mode" + Main.delimiter1 + payMode + Main.delimiter1 + "Paied To" + 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           = pvDetails.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"));
                    }
                }
                foreach (paymentvoucherdetail pvd in pvDetails)
                {
                    if (pvd.AmountCredit != 0)
                    {
                        if (pvh.BillDetails.Trim().Length != 0)
                        {
                            //ColDetailString = ColDetailString + n + Main.delimiter1 + billdetail[1] + Main.delimiter1 +
                            //  Convert.ToDateTime(billdetail[2].Replace(Main.delimiter2.ToString(), "")).ToString("dd-MM-yyyy") +
                            //  Main.delimiter1 + pvd.AmountCreditINR + Main.delimiter1
                            //                      + pvd.AccountName + Main.delimiter2;
                            ColDetailString = ColDetailString + n + Main.delimiter1 + String.Join(",", billNos.ToArray()) + Main.delimiter1 +
                                              string.Join(",", billDates.ToArray()) +
                                              Main.delimiter1 + pvd.AmountCredit + Main.delimiter1
                                              + pvd.AccountName + Main.delimiter2;
                        }
                        else
                        {
                            ColDetailString = ColDetailString + n + Main.delimiter1 + "" + Main.delimiter1 +
                                              "" +
                                              Main.delimiter1 + pvd.AmountCredit + Main.delimiter1
                                              + pvd.AccountName + Main.delimiter2;
                        }
                        n++;
                    }
                }

                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("Payment 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)));
                    }
                }
                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, 6f };
                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);
                        }
                    }
                }
                string[] ft = footer3.Split(';');

                PdfPTable tableFooter = new PdfPTable(3);
                tableFooter.SpacingBefore = 50;
                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(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("Document Saved");
            }
            catch (Exception ie)
            {
                MessageBox.Show("Failed to save.\n" + ie.Message);
            }
            return(fileName);
        }
Пример #52
0
        /// <summary>
        /// Utility function to crop a png into page-sized portions and embed each png into the pdf.
        /// </summary>
        /// <param name="png"></param>
        /// <returns></returns>
        public static byte[] ConvertPngToPdf(byte[] png)
        {
            using (MemoryStream pdfStream = new MemoryStream())
            {
                Document pdfDocument = new iTextSharp.text.Document(PageSize.LETTER, 36, 36, 36, 36);

                var writer = PdfWriter.GetInstance(pdfDocument, pdfStream);
                writer.CloseStream = false;

                pdfDocument.Open();

                var maxImageHeight = pdfDocument.PageSize.Height + 36;

                using (var source = new System.Drawing.Bitmap(new MemoryStream(png)))
                {
                    if (source.Height > maxImageHeight)
                    {
                        int heightOffset = 0;

                        while (heightOffset < source.Height)
                        {
                            Rectangle sourceRect = heightOffset + (int)(maxImageHeight) > source.Height
                                                     ? new System.Drawing.Rectangle(0, heightOffset, source.Width, source.Height)
                                                     : new System.Drawing.Rectangle(0, heightOffset, source.Width, (int)(maxImageHeight));

                            using (var target = new System.Drawing.Bitmap(sourceRect.Width, sourceRect.Height))
                            {
                                using (var g = Graphics.FromImage(target))
                                {
                                    g.DrawImage(source, new System.Drawing.Rectangle(0, 0, target.Width, target.Height),
                                                sourceRect,
                                                GraphicsUnit.Pixel);
                                }

                                using (MemoryStream ms = new MemoryStream())
                                {
                                    target.Save(ms, ImageFormat.Png);
                                    pdfDocument.Add(new Paragraph());
                                    Image img = Image.GetInstance(ms.GetBuffer());
                                    img.ScaleToFit(pdfDocument.PageSize.Width - 72, img.Height);
                                    pdfDocument.Add(img);
                                    if (sourceRect.Height >= maxImageHeight)
                                    {
                                        pdfDocument.NewPage();
                                    }
                                }
                            }

                            heightOffset += sourceRect.Height;
                        }
                    }
                    else
                    {
                        pdfDocument.Add(new Paragraph());

                        Image img = Image.GetInstance(png);
                        img.ScaleToFit(pdfDocument.PageSize.Width - 72, img.Height);
                        pdfDocument.Add(img);
                    }
                }

                if (pdfDocument.IsOpen())
                {
                    pdfDocument.Close();
                }

                pdfStream.Flush();
                pdfStream.Seek(0, SeekOrigin.Begin);
                return(pdfStream.GetBuffer());
            }
        }
        private void CreateReport(string filePath)
        {
            AppFileTemplate f = (AppFileTemplate)DataContext;

            // margins
            float left   = 30;
            float right  = 10;
            float top    = 10;
            float bottom = 10;
            float headH  = 20;
            float indent = 5;

            //string fontName = "C:\\WINDOWS\\FONTS\\CALIBRI.TTF";
            string fontName = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "CALIBRI.TTF");

            iText.Font     NormalSatirFont  = iText.FontFactory.GetFont(fontName, "CP1254", 10, iText.Font.NORMAL);
            iText.Font     BoldSatirFont    = iText.FontFactory.GetFont(fontName, "CP1254", 10, iText.Font.BOLD);
            iText.Font     NormalRiseFont   = iText.FontFactory.GetFont(fontName, "CP1254", 8, iText.Font.NORMAL);
            iText.Font     NormalSymbolFont = iText.FontFactory.GetFont(iText.FontFactory.SYMBOL, 10, iText.Font.NORMAL);
            iText.Document doc = new iText.Document(iText.PageSize.A4, left, right, top, bottom);

            float xLL = doc.GetLeft(left);
            float yLL = doc.GetBottom(bottom);
            float xUR = doc.GetRight(right);
            float yUR = doc.GetTop(top);
            float w   = xUR - xLL;
            float h   = yUR - yLL;
            float xUL = xLL;
            float yUL = yUR;
            float xLR = xUR;
            float yLR = yLL;
            //float graphW = w - 10;
            //float graphH = graphW * 2 / 3;


            float graphH = 3 * h / 5;
            float graphW = w - 10;


            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Create));

            doc.Open();

            // direct content
            PdfContentByte cb = writer.DirectContent;

            // çizgiler
            DrawLine(cb, xUR - w, yUR, xUR, yUR);
            DrawLine(cb, xUR - w, yUR, xLL, yLL);
            DrawLine(cb, xLL, yLL, xLL + w, yLL);
            DrawLine(cb, xLL + w, yLL, xUR, yUR);
            DrawLine(cb, xUL, yUL - headH, xUR, yUR - headH);
            DrawLine(cb, xUL, yUL - headH - graphH, xUR, yUR - headH - graphH);

            // başlık
            ColumnText ct = new ColumnText(cb);

            ct.Indent = indent;
            iText.Phrase txt = new iText.Phrase();
            txt.Add(new iText.Chunk(f.ReportTitle, NormalSatirFont));
            ct.SetSimpleColumn(txt, xUL, yUL - headH, xUR, yUR, headH / 1.5f, iText.Element.ALIGN_LEFT | iText.Element.ALIGN_MIDDLE);
            ct.Go();

            var stream      = new MemoryStream();
            var pngExporter = new PngExporter {
                Width = (int)graphW, Height = (int)graphH, Background = OxyColors.White
            };

            pngExporter.Export(PlotView.Model, stream);

            iText.Image png = iText.Image.GetInstance(stream.GetBuffer());
            png.Alignment = iText.Element.ALIGN_CENTER | iText.Element.ALIGN_MIDDLE;
            png.SetAbsolutePosition(xUL, yUL - headH - graphH);
            doc.Add(png);

            float      kstW    = w / 2;
            float      kstH    = (h - headH - graphH) / 1.5f;
            ColumnText ctKesit = new ColumnText(cb);

            ctKesit.Indent = indent;
            txt            = new iText.Phrase();
            txt.Add(new iText.Chunk("Kesit\n", BoldSatirFont));
            txt.Add(new iText.Chunk(String.Format("Genişlik, b = {0:0} cm\n", f.b), NormalSatirFont));
            txt.Add(new iText.Chunk(String.Format("Yükseklik, h = {0:0} cm\n", f.h), NormalSatirFont));
            txt.Add(new iText.Chunk(String.Format("Alan, bxh = {0:0} cm²\n", f.b * f.h), NormalSatirFont));
            txt.Add(new iText.Chunk("\nMalzeme\n", BoldSatirFont));
            txt.Add(new iText.Chunk("f", NormalSatirFont));
            txt.Add(new iText.Chunk("c", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(String.Format(" = {0:0} MPa   ", f.Beton().fc.TonnesForcePerSquareMeter().Megapascals), NormalSatirFont));
            txt.Add(new iText.Chunk("f", NormalSatirFont));
            txt.Add(new iText.Chunk("y", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(String.Format(" = {0:0} MPa\n", f.DonatiCeligi().fy.TonnesForcePerSquareMeter().Megapascals), NormalSatirFont));

            txt.Add(new iText.Chunk("f", NormalSatirFont));
            txt.Add(new iText.Chunk("cd", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(String.Format(" = {0:0} MPa   ", f.Beton().fcd.TonnesForcePerSquareMeter().Megapascals), NormalSatirFont));

            txt.Add(new iText.Chunk("f", NormalSatirFont));
            txt.Add(new iText.Chunk("yd", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(String.Format(" = {0:0} MPa\n", f.DonatiCeligi().fyd.TonnesForcePerSquareMeter().Megapascals), NormalSatirFont));

            txt.Add(new iText.Chunk("E", NormalSatirFont));
            txt.Add(new iText.Chunk("c", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(String.Format(" = {0:0} MPa   ", f.Beton().E.TonnesForcePerSquareMeter().Megapascals), NormalSatirFont));
            txt.Add(new iText.Chunk("E", NormalSatirFont));
            txt.Add(new iText.Chunk("s", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(String.Format(" = {0:0} MPa\n", f.DonatiCeligi().E.TonnesForcePerSquareMeter().Megapascals), NormalSatirFont));
            txt.Add(new iText.Chunk("e", NormalSymbolFont));
            txt.Add(new iText.Chunk("cu", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(String.Format(" = {0:0.0000} m/m   ", f.Beton().Ecu), NormalSatirFont));
            txt.Add(new iText.Chunk("e", NormalSymbolFont));
            txt.Add(new iText.Chunk("yd", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(String.Format(" = {0:0.00000} m/m\n", f.DonatiCeligi().Eyd), NormalSatirFont));
            txt.Add(new iText.Chunk("k", NormalSatirFont));
            txt.Add(new iText.Chunk("1", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(String.Format(" = {0:0.000}\n", f.Beton().k1), NormalSatirFont));

            ctKesit.SetSimpleColumn(txt, xUL, yUL - headH - graphH - kstH, xUL + kstW, yUL - headH - graphH, 15, iText.Element.ALIGN_LEFT);
            ctKesit.Go();

            ColumnText ctDonati = new ColumnText(cb);

            txt = new iText.Phrase();
            txt.Add(new iText.Chunk("Donatı\n", BoldSatirFont));
            int j = 1;

            foreach (var rb in f.ReinforcingBars)
            {
                txt.Add(new iText.Chunk("A", NormalSatirFont));
                txt.Add(new iText.Chunk(string.Format("s{0}", j), NormalRiseFont).SetTextRise(-1.0f));
                txt.Add(new iText.Chunk(string.Format("={0:0.00} cm², ", rb.As), NormalSatirFont));
                txt.Add(new iText.Chunk("d", NormalSatirFont));
                txt.Add(new iText.Chunk(string.Format("{0}", j), NormalRiseFont).SetTextRise(-1.0f));
                txt.Add(new iText.Chunk(string.Format("={0:0.00} cm\n", rb.di), NormalSatirFont));
                j++;
            }
            txt.Add(new iText.Chunk("r", NormalSymbolFont));
            txt.Add(new iText.Chunk(string.Format("=%{0:0.00}\n", 100.0 * f.ReinforcingBars.Sum(i => i.As) / (f.b * f.h)), NormalSatirFont));
            txt.Add(new iText.Chunk("(d", NormalSatirFont));
            txt.Add(new iText.Chunk("i", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(":Kesit basınç yüzeyinin donatı eksenine uzaklığı)\n", NormalSatirFont));
            txt.Add(new iText.Chunk("\nDayanım Azaltma Katsayıları\n", BoldSatirFont));
            txt.Add(new iText.Chunk("f", NormalSymbolFont));
            txt.Add(new iText.Chunk("a", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(string.Format(" = {0:0.00}, ", f.PhiA), NormalSatirFont));
            txt.Add(new iText.Chunk("f", NormalSymbolFont));
            txt.Add(new iText.Chunk("b", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(string.Format(" = {0:0.00}, ", f.PhiB), NormalSatirFont));
            txt.Add(new iText.Chunk("f", NormalSymbolFont));
            txt.Add(new iText.Chunk("c", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(string.Format(" = {0:0.00}", f.PhiC), NormalSatirFont));
            //txt.Add(new iText.Chunk("\n\nTasarım:\n", BoldSatirFont));
            //txt.Add(new iText.Chunk(f.Code.ToString(), NormalSatirFont));
            ctDonati.SetSimpleColumn(txt, xUL + kstW, yUL - headH - graphH - kstH, xUL + 2 * kstW, yUL - headH - graphH, 15, iText.Element.ALIGN_LEFT);
            ctDonati.Go();

            ColumnText ctTesir = new ColumnText(cb);

            ctTesir.Indent = indent;
            txt            = new iText.Phrase();
            txt.Add(new iText.Chunk("Maksimum eksenel basınç, N", NormalSatirFont));
            txt.Add(new iText.Chunk("max", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(string.Format(" = {0:0.00} t\n", f.Pmax), NormalSatirFont));
            txt.Add(new iText.Chunk("Maksimum eksenel çekme, N", NormalSatirFont));
            txt.Add(new iText.Chunk("min", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(string.Format(" = {0:0.00} t\n\n", f.Pmin), NormalSatirFont));

            txt.Add(new iText.Chunk("Yönetmelik maksimum eksenel basınç sınırı, N", NormalSatirFont));
            txt.Add(new iText.Chunk("max", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(string.Format(" = {0:0.00} t", f.ActualPmax), NormalSatirFont));
            ctTesir.SetSimpleColumn(txt, xUL, yUL - headH - graphH - 1.5f * kstH, xUL + kstW, yUL - headH - graphH - kstH, 15, iText.Element.ALIGN_LEFT);
            ctTesir.Go();

            doc.Close();
        }
Пример #54
0
        public ActionResult Imprimir(int id)
        {
            var empleado      = db.Empleadoes.FirstOrDefault(e => e.ID_Empleado == id);
            var cargoEmpleado = empleado.Cargo_Empleado.FirstOrDefault();
            var nomina        = empleado.Nominas.FirstOrDefault();

            decimal recargo           = 0;
            decimal auxilioTransporte = 0;

            if (cargoEmpleado.ID_Jornada == (int)WorkingDay.Night)
            {
                recargo = CalcularRecargoNocturno(cargoEmpleado.Salario_Basico, nomina.Extras_Nocturnas);
            }


            if (cargoEmpleado.Salario_Basico <= 1656232)
            {
                auxilioTransporte += 97032;
            }

            var horasextrasdiurnas = CalcularExtrasDiurnas(cargoEmpleado.Salario_Basico, nomina.Extras_Diurnas);

            var TotalDevengado = cargoEmpleado.Salario_Basico + recargo + horasextrasdiurnas + auxilioTransporte
                                 - empleado.Nominas.FirstOrDefault().Aporte_Salud - empleado.Nominas.FirstOrDefault().Aporte_Pension;



            iTextSharp.text.Document doc = new iTextSharp.text.Document();
            PdfWriter.GetInstance(doc, new FileStream($"{MapPath("~/Pdf")}/hola.pdf", FileMode.Create));
            doc.Open();

            Paragraph title = new Paragraph();

            title.Font = FontFactory.GetFont(FontFactory.TIMES, 18f, BaseColor.BLUE);
            title.Add("NomiProSA");
            doc.Add(title); doc.Add(new Paragraph("NIT: 900565456-9"));
            doc.Add(new Paragraph("CORREO:  [email protected]"));
            doc.Add(new Paragraph("Direccion:  Calle 8 sur # 78-67"));
            doc.Add(new Paragraph("-------------------------------------------------------------------------------------------------------------------------------"));

            doc.Add(new Paragraph($"Empleado: {empleado.Apellido} {empleado.Nombre}"));
            doc.Add(new Paragraph("Documento de Identidad:" + empleado.Numero_Documento));
            doc.Add(new Paragraph("Básico:" + empleado.Cargo_Empleado.FirstOrDefault().Salario_Basico));
            doc.Add(new Paragraph("Cargo:" + cargoEmpleado.Cargo.Descripción_Cargo));
            doc.Add(new Paragraph("Cargo:" + cargoEmpleado.TipoContrato));
            doc.Add(new Paragraph("Jornada:" + cargoEmpleado.Jornada.Nombre));
            doc.Add(new Paragraph("Periodo de Liquidacion Inicial:" + empleado.Nominas.LastOrDefault().Fecha_Inicial_Pago));
            doc.Add(new Paragraph("Periodo de Liquidacion Final:" + empleado.Nominas.LastOrDefault().Fecha_Final_Pago));

            doc.Add(new Paragraph("-------------------------------------------------------------------------------------------------------------------------------"));


            doc.Add(new Paragraph("Recibo de pago"));
            doc.Add(new Paragraph("========================================================================="));


            PdfPTable table = new PdfPTable(9);

            table.AddCell("Basico");
            table.AddCell("Total Horas");
            table.AddCell("Auxi.Transporte");
            table.AddCell("Salud");
            table.AddCell("Pension");
            table.AddCell("Extras Dia");
            table.AddCell("Extras Noche");
            table.AddCell("Recargo");
            table.AddCell("Neto");



            table.AddCell("" + empleado.Cargo_Empleado.FirstOrDefault().Salario_Basico);
            table.AddCell("" + empleado.Nominas.LastOrDefault().Total_Horas_Laboradas);
            table.AddCell("" + auxilioTransporte);
            table.AddCell("" + nomina.Aporte_Salud);
            table.AddCell("" + nomina.Aporte_Pension);
            table.AddCell("" + nomina.Extras_Diurnas);
            table.AddCell("" + nomina.Extras_Nocturnas);
            table.AddCell("" + recargo);
            table.AddCell("" + TotalDevengado);


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



            // db.Nominas.Add(imprimir);
            //  db.SaveChanges();
            //  return RedirectToAction("Index", "Roster");

            //byte[] fileBytes = System.IO.File.ReadAllBytes($"{MapPath("~/Pdf")}/hola.pdf");
            //string fileName = "myfile.pdf";
            //return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);

            return(Redirect("/Pdf/hola.pdf"));
        }
Пример #55
0
        public byte[] ToPDF()
        {
            try
            {
                byte[] pdfBytes;

                using (MemoryStream ms = new MemoryStream())
                {
                    iTextSharp.text.Document doc = new iTextSharp.text.Document();
                    PdfWriter             writer = PdfWriter.GetInstance(doc, ms);
                    iTextSharp.text.Image jpg    = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("~/Content/Images/InvoiceSheet/blank_invoice.jpg"));
                    doc.SetPageSize(iTextSharp.text.PageSize.A4);

                    jpg.ScaleToFit(iTextSharp.text.PageSize.A4.Width, iTextSharp.text.PageSize.A4.Height);
                    jpg.Alignment = iTextSharp.text.Image.UNDERLYING;
                    jpg.SetAbsolutePosition(10, -5);

                    doc.Open();
                    doc.Add(jpg);

                    Font defaultFont = new Font(Font.FontFamily.HELVETICA, 7);

                    var cb = writer.DirectContent;

                    ColumnText desc_col            = new ColumnText(cb);
                    ColumnText item_col            = new ColumnText(cb);
                    ColumnText item_price_col      = new ColumnText(cb);
                    ColumnText purchase_col        = new ColumnText(cb);
                    ColumnText invoice_col         = new ColumnText(cb);
                    ColumnText invoice_date_col    = new ColumnText(cb);
                    ColumnText total_sub_price_col = new ColumnText(cb);
                    ColumnText vat_col             = new ColumnText(cb);
                    ColumnText total_price_col     = new ColumnText(cb);
                    ColumnText job_title_col       = new ColumnText(cb);

                    job_title_col.SetSimpleColumn(165, doc.Top - 200, 500, 200, 15, Element.ALIGN_TOP);


                    invoice_col.SetSimpleColumn(doc.Right - 110, doc.Top - 154.2f, 500, 100, 15, Element.ALIGN_TOP);
                    invoice_date_col.SetSimpleColumn(doc.Right - 110, doc.Top - 166.3f, 500, 100, 15, Element.ALIGN_TOP);

                    purchase_col.SetSimpleColumn(200, doc.Top - 270, 500, 100, 15, Element.ALIGN_TOP);
                    desc_col.SetSimpleColumn(165, doc.Top - 320, 415, 200, 15, Element.ALIGN_TOP);
                    item_col.SetSimpleColumn(165, doc.Top - 340, 415, 200, 15, Element.ALIGN_TOP);

                    item_price_col.SetSimpleColumn(doc.Right - 110, doc.Top - 340, 500, 100, 15, Element.ALIGN_TOP);
                    total_sub_price_col.SetSimpleColumn(doc.Right - 110, doc.Bottom - 100, 500, 145, 15, Element.ALIGN_TOP);
                    vat_col.SetSimpleColumn(doc.Right - 110, doc.Bottom - 100, 500, 125, 15, Element.ALIGN_TOP);
                    total_price_col.SetSimpleColumn(doc.Right - 110, doc.Bottom, 500, 105, 15, Element.ALIGN_TOP);

                    job_title_col.AddElement(CreateInfo(this.Title));
                    invoice_col.AddElement(CreateInfo(this.InvoiceNumber.ToString()));
                    invoice_date_col.AddElement(CreateInfo(this.CreatedDate.ToString("dd MMM yyyy")));
                    purchase_col.AddElement(CreateInfo(this.PurchaseOrder));
                    desc_col.AddElement(CreateInfoLight(this.Description));
                    vat_col.AddElement(CreateInfoLight("20%"));

                    // add invoice items to page
                    var items = this.Items;
                    foreach (var item in items)
                    {
                        item_col.AddElement(CreateInfoLight("item title"));
                        item_price_col.AddElement(CreateInfoLight(item.Value.ToString()));
                    }

                    //totals
                    total_sub_price_col.AddElement(CreateInfo(this.SubValue.ToString("C")));
                    total_price_col.AddElement(CreateInfo(this.TotalValue.ToString("C")));


                    job_title_col.Go();
                    purchase_col.Go();
                    invoice_col.Go();
                    invoice_date_col.Go();
                    desc_col.Go();
                    item_col.Go();
                    item_price_col.Go();
                    total_sub_price_col.Go();
                    total_price_col.Go();
                    vat_col.Go();
                    //   column9.Go();
                    //    column10.Go();
                    //  column11.Go();

                    doc.Close();

                    pdfBytes = ms.ToArray();
                }

                return(pdfBytes);
            }
            catch (Exception)
            {
                throw;
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {//Logging Start
        string id = string.Format("Id: {0} Uri: {1}", Guid.NewGuid(), HttpContext.Current.Request.Url);

        using (Utils utility = new Utils())
        {
            utility.MethodStart(id, System.Reflection.MethodBase.GetCurrentMethod());
        }
        try
        {
            if (Request.QueryString["caseid"] != null && Request.QueryString["cmpid"] != null)
            {
                string szCaseID    = Request.QueryString["caseid"].ToString();
                string szCompanyID = Request.QueryString["cmpid"].ToString();

                DataSet             ds          = new DataSet();
                MUVGenerateFunction objSettings = new MUVGenerateFunction();
                ds = GetPatienView(szCaseID, szCompanyID);
                string szfirstname = "";
                string szlastname  = "";
                if (ds.Tables[0].Rows[0]["SZ_PATIENT_FIRST_NAME"].ToString() != "")
                {
                    szfirstname = ds.Tables[0].Rows[0]["SZ_PATIENT_FIRST_NAME"].ToString();
                    szfirstname = szfirstname.Replace(" ", string.Empty);
                    szfirstname = szfirstname.Replace(".", string.Empty);
                    szfirstname = szfirstname.Replace(",", string.Empty);
                }
                if (ds.Tables[0].Rows[0]["SZ_PATIENT_LAST_NAME"].ToString() != "")
                {
                    szlastname = ds.Tables[0].Rows[0]["SZ_PATIENT_LAST_NAME"].ToString();
                    szlastname = szlastname.Replace(" ", string.Empty);
                    szlastname = szlastname.Replace(".", string.Empty);
                    szlastname = szlastname.Replace(",", string.Empty);
                }
                string path = ApplicationSettings.GetParameterValue("PatientInfoSaveFilePath");

                string OpenFilepath = ApplicationSettings.GetParameterValue("PatientInfoOpenFilePath");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                string                   newPdfFilename = szfirstname.Trim() + "_" + szlastname.Trim() + "_" + DateTime.Now.ToString("MM_dd_yyyyhhmm") + ".pdf";
                string                   pdfPath        = path + newPdfFilename;
                MemoryStream             m        = new MemoryStream();
                iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.A4, 36, 36, 20, 20);
                float[]                  wBase    = { 4f };
                PdfPTable                tblBase  = new PdfPTable(wBase);
                tblBase.DefaultCell.Border = Rectangle.NO_BORDER;
                tblBase.WidthPercentage    = 100;
                PdfWriter writer = PdfWriter.GetInstance(document, m);
                document.Open();
                #region "for printed by"
                float[]   width      = { 4f, 4f };
                PdfPTable tblprintby = new PdfPTable(width);
                tblprintby.TotalWidth         = document.PageSize.Width - document.LeftMargin - document.RightMargin;
                tblprintby.DefaultCell.Border = Rectangle.NO_BORDER;
                tblprintby.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT;
                tblprintby.DefaultCell.VerticalAlignment   = iTextSharp.text.Element.ALIGN_TOP;
                tblprintby.AddCell(new Phrase("Printed By : " + ((Bill_Sys_UserObject)Session["USER_OBJECT"]).SZ_USER_NAME, iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                tblprintby.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT;
                tblprintby.AddCell(new Phrase("Printed on : " + DateTime.Now.ToString("MM/dd/yyyy"), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                tblBase.AddCell(tblprintby);
                #endregion
                tblBase.AddCell(" ");

                #region "for patient information"
                float[]   wdh        = { 4f };
                PdfPTable tblheading = new PdfPTable(wdh);
                tblheading.TotalWidth         = document.PageSize.Width - document.LeftMargin - document.RightMargin;
                tblheading.DefaultCell.Border = Rectangle.NO_BORDER;
                tblheading.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER;
                tblheading.DefaultCell.VerticalAlignment   = iTextSharp.text.Element.ALIGN_MIDDLE;
                tblheading.AddCell(new Phrase("Patient Information", iTextSharp.text.FontFactory.GetFont("Arial", 14, Font.BOLD, iTextSharp.text.Color.BLACK)));
                tblBase.AddCell(tblheading);
                #endregion

                #region for Personal Information
                float[]   w11   = { 3f, 3f, 3f, 3f };
                PdfPTable table = new PdfPTable(w11);
                table.WidthPercentage         = 100;
                table.DefaultCell.BorderColor = Color.BLACK;
                PdfPCell cell1 = new PdfPCell(new Phrase("Personal Information", iTextSharp.text.FontFactory.GetFont("Arial", 12, iTextSharp.text.Color.BLACK)));
                cell1.Colspan         = 4;
                cell1.BackgroundColor = Color.LIGHT_GRAY;
                cell1.BorderColor     = Color.BLACK;
                table.AddCell(cell1);
                table.AddCell(new Phrase("First Name", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_PATIENT_FIRST_NAME"].ToString() != "")
                {
                    table.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_PATIENT_FIRST_NAME"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    table.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                table.AddCell(new Phrase("Middle Name", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["MI"].ToString() != "")
                {
                    table.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["MI"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    table.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                table.AddCell(new Phrase("Last Name", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_PATIENT_LAST_NAME"].ToString() != "")
                {
                    table.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_PATIENT_LAST_NAME"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    table.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                table.AddCell(new Phrase("D.O.B", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["DOB"].ToString() != "")
                {
                    table.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["DOB"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    table.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                table.AddCell(new Phrase("Gender", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_GENDER"].ToString() != "")
                {
                    table.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_GENDER"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    table.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                table.AddCell(new Phrase("Address", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_PATIENT_ADDRESS"].ToString() != "")
                {
                    table.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_PATIENT_ADDRESS"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    table.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                table.AddCell(new Phrase("City", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_PATIENT_CITY"].ToString() != "")
                {
                    table.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_PATIENT_CITY"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    table.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                table.AddCell(new Phrase("State", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_PATIENT_STATE"].ToString() != "")
                {
                    table.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_PATIENT_STATE"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    table.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                table.AddCell(new Phrase("Cell Phone #", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["sz_patient_cellno"].ToString() != "")
                {
                    table.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["sz_patient_cellno"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    table.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }

                table.AddCell(new Phrase("Home Phone", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_PATIENT_PHONE"].ToString() != "")
                {
                    table.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_PATIENT_PHONE"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    table.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }

                table.AddCell(new Phrase("Work", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_WORK_PHONE"].ToString() != "")
                {
                    table.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_WORK_PHONE"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    table.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                table.AddCell(new Phrase("Zip", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_PATIENT_ZIP"].ToString() != "")
                {
                    table.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_PATIENT_ZIP"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    table.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                table.AddCell(new Phrase("Email", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_PATIENT_EMAIL"].ToString() != "")
                {
                    table.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_PATIENT_EMAIL"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    table.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                table.AddCell(new Phrase("Extn.", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_WORK_PHONE_EXTENSION"].ToString() != "")
                {
                    table.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_WORK_PHONE_EXTENSION"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    table.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                table.AddCell(new Phrase("Attorney", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_ATTORNEY"].ToString() != "")
                {
                    table.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_ATTORNEY"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    table.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                table.AddCell(new Phrase("Case Type", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_CASE_TYPE"].ToString() != "")
                {
                    table.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_CASE_TYPE"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    table.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }

                table.AddCell(new Phrase("Attorney Address", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_ATTORNEY_ADDRESS"].ToString() != "")
                {
                    table.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_ATTORNEY_ADDRESS"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    table.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }

                table.AddCell(new Phrase("Attorney Phone", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["sz_attorney_phone"].ToString() != "")
                {
                    table.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["sz_attorney_phone"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    table.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }

                table.AddCell(new Phrase("Case Status", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_CASE_STATUS"].ToString() != "")
                {
                    table.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_CASE_STATUS"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    table.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                table.AddCell(new Phrase("SSN", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_SOCIAL_SECURITY_NO"].ToString() != "")
                {
                    table.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_SOCIAL_SECURITY_NO"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    table.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }



                PdfPCell cell2 = new PdfPCell(new Phrase(""));
                cell2.Colspan     = 2;
                cell2.BorderColor = Color.BLACK;
                table.AddCell(cell2);
                tblBase.AddCell(table);
                #endregion

                tblBase.AddCell(" ");

                #region for Insurance Information
                float[]   wd1          = { 3f, 3f, 3f, 3f };
                PdfPTable tblInsurance = new PdfPTable(wd1);
                tblInsurance.WidthPercentage         = 100;
                tblInsurance.DefaultCell.BorderColor = Color.BLACK;
                PdfPCell cell3 = new PdfPCell(new Phrase("Insurance Information", iTextSharp.text.FontFactory.GetFont("Arial", 12, iTextSharp.text.Color.BLACK)));
                cell3.Colspan         = 4;
                cell3.BorderColor     = Color.BLACK;
                cell3.BackgroundColor = Color.LIGHT_GRAY;
                tblInsurance.AddCell(cell3);
                tblInsurance.AddCell(new Phrase("Policy Holder", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_POLICY_HOLDER"].ToString() != "")
                {
                    tblInsurance.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_POLICY_HOLDER"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblInsurance.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }

                tblInsurance.AddCell(new Phrase("Name", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_INSURANCE_NAME"].ToString() != "")
                {
                    tblInsurance.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_INSURANCE_NAME"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblInsurance.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblInsurance.AddCell(new Phrase("Address", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_INSURANCE_ADDRESS"].ToString() != "")
                {
                    tblInsurance.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_INSURANCE_ADDRESS"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblInsurance.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblInsurance.AddCell(new Phrase("City", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_INSURANCE_CITY"].ToString() != "")
                {
                    tblInsurance.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_INSURANCE_CITY"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblInsurance.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblInsurance.AddCell(new Phrase("State", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_INSURANCE_STATE"].ToString() != "")
                {
                    tblInsurance.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_INSURANCE_STATE"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblInsurance.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblInsurance.AddCell(new Phrase("Zip", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_INSURANCE_ZIP"].ToString() != "")
                {
                    tblInsurance.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_INSURANCE_ZIP"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblInsurance.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblInsurance.AddCell(new Phrase("Phone", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_INSURANCE_PHONE"].ToString() != "")
                {
                    tblInsurance.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_INSURANCE_PHONE"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblInsurance.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblInsurance.AddCell(new Phrase("Fax", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_FAX_NUMBER"].ToString() != "")
                {
                    tblInsurance.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_FAX_NUMBER"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblInsurance.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblInsurance.AddCell(new Phrase("Contact Person", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_CONTACT_PERSON"].ToString() != "")
                {
                    tblInsurance.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_CONTACT_PERSON"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblInsurance.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblInsurance.AddCell(new Phrase("Claim File #", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_CLAIM_NUMBER"].ToString() != "")
                {
                    tblInsurance.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_CLAIM_NUMBER"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblInsurance.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblInsurance.AddCell(new Phrase("Policy #", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_POLICY_NUMBER"].ToString() != "")
                {
                    tblInsurance.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_POLICY_NUMBER"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblInsurance.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }

                PdfPCell cell14 = new PdfPCell(new Phrase(""));
                cell14.Colspan     = 2;
                cell14.BorderColor = Color.BLACK;
                tblInsurance.AddCell(cell14);
                tblBase.AddCell(tblInsurance);
                #endregion

                tblBase.AddCell(" ");

                #region for Accident Information
                float[]   wd2         = { 3f, 3f, 3f, 3f };
                PdfPTable tblAccident = new PdfPTable(wd2);
                tblAccident.WidthPercentage         = 100;
                tblAccident.DefaultCell.BorderColor = Color.BLACK;
                PdfPCell cell4 = new PdfPCell(new Phrase("Accident Information", iTextSharp.text.FontFactory.GetFont("Arial", 12, iTextSharp.text.Color.BLACK)));
                cell4.Colspan         = 4;
                cell4.BorderColor     = Color.BLACK;
                cell4.BackgroundColor = Color.LIGHT_GRAY;
                tblAccident.AddCell(cell4);
                tblAccident.AddCell(new Phrase("Accident Date", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["DT_ACCIDENT_DATE"].ToString() != "")
                {
                    tblAccident.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["DT_ACCIDENT_DATE"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblAccident.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblAccident.AddCell(new Phrase("Plate Number", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_PLATE_NO"].ToString() != "")
                {
                    tblAccident.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_PLATE_NO"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblAccident.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblAccident.AddCell(new Phrase("Report Number", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_REPORT_NO"].ToString() != "")
                {
                    tblAccident.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_REPORT_NO"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblAccident.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblAccident.AddCell(new Phrase("Address", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_ACCIDENT_ADDRESS"].ToString() != "")
                {
                    tblAccident.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_ACCIDENT_ADDRESS"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblAccident.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblAccident.AddCell(new Phrase("City", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_ACCIDENT_CITY"].ToString() != "")
                {
                    tblAccident.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_ACCIDENT_CITY"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblAccident.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblAccident.AddCell(new Phrase("State", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_ACCIDENT_INSURANCE_STATE"].ToString() != "")
                {
                    tblAccident.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_ACCIDENT_INSURANCE_STATE"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblAccident.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblAccident.AddCell(new Phrase("Hospital Name", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_HOSPITAL_NAME"].ToString() != "")
                {
                    tblAccident.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_HOSPITAL_NAME"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblAccident.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblAccident.AddCell(new Phrase("Hospital Address", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_HOSPITAL_ADDRESS"].ToString() != "")
                {
                    tblAccident.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_HOSPITAL_ADDRESS"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblAccident.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblAccident.AddCell(new Phrase("Date of Admission", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["DT_ADMISSION_DATE"].ToString() != "")
                {
                    tblAccident.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["DT_ADMISSION_DATE"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblAccident.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblAccident.AddCell(new Phrase("Additional Patient", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_PATIENT_FROM_CAR"].ToString() != "")
                {
                    tblAccident.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_PATIENT_FROM_CAR"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblAccident.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblAccident.AddCell(new Phrase("Describe Injury", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_DESCRIBE_INJURY"].ToString() != "")
                {
                    tblAccident.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_DESCRIBE_INJURY"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblAccident.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblAccident.AddCell(new Phrase("Patient Type", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_PATIENT_TYPE"].ToString() != "")
                {
                    tblAccident.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_PATIENT_TYPE"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblAccident.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }

                tblBase.AddCell(tblAccident);
                #endregion

                tblBase.AddCell(" ");

                #region for Employer Information
                float[]   wd3         = { 3f, 3f, 3f, 3f };
                PdfPTable tblEmployer = new PdfPTable(wd3);
                tblEmployer.WidthPercentage         = 100;
                tblEmployer.DefaultCell.BorderColor = Color.BLACK;
                PdfPCell cell5 = new PdfPCell(new Phrase("Employer Information", iTextSharp.text.FontFactory.GetFont("Arial", 12, iTextSharp.text.Color.BLACK)));
                cell5.Colspan         = 4;
                cell5.BorderColor     = Color.BLACK;
                cell5.BackgroundColor = Color.LIGHT_GRAY;
                tblEmployer.AddCell(cell5);
                tblEmployer.AddCell(new Phrase("Name", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_EMPLOYER_NAME"].ToString() != "")
                {
                    tblEmployer.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_EMPLOYER_NAME"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblEmployer.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblEmployer.AddCell(new Phrase("Address", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_EMPLOYER_ADDRESS"].ToString() != "")
                {
                    tblEmployer.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_EMPLOYER_ADDRESS"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblEmployer.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblEmployer.AddCell(new Phrase("City", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_EMPLOYER_CITY"].ToString() != "")
                {
                    tblEmployer.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_EMPLOYER_CITY"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblEmployer.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblEmployer.AddCell(new Phrase("State", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_EMPLOYER_STATE"].ToString() != "")
                {
                    tblEmployer.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_EMPLOYER_STATE"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblEmployer.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblEmployer.AddCell(new Phrase("Zip", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_EMPLOYER_ZIP"].ToString() != "")
                {
                    tblEmployer.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_EMPLOYER_ZIP"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblEmployer.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblEmployer.AddCell(new Phrase("Phone", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_EMPLOYER_PHONE"].ToString() != "")
                {
                    tblEmployer.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_EMPLOYER_PHONE"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblEmployer.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblEmployer.AddCell(new Phrase("Date of First Treatment", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["DT_FIRST_TREATMENT"].ToString() != "")
                {
                    tblEmployer.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["DT_FIRST_TREATMENT"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblEmployer.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblEmployer.AddCell(new Phrase("Chart #", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_CHART_NO"].ToString() != "")
                {
                    tblEmployer.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_CHART_NO"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblEmployer.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }

                tblBase.AddCell(tblEmployer);
                #endregion

                tblBase.AddCell(" ");

                #region for Adjuster Information
                float[]   wd4         = { 3f, 3f, 3f, 3f };
                PdfPTable tblAdjuster = new PdfPTable(wd4);
                tblAdjuster.WidthPercentage         = 100;
                tblAdjuster.DefaultCell.BorderColor = Color.BLACK;
                PdfPCell cell6 = new PdfPCell(new Phrase("Adjuster Information", iTextSharp.text.FontFactory.GetFont("Arial", 12, iTextSharp.text.Color.BLACK)));
                cell6.Colspan         = 4;
                cell6.BorderColor     = Color.BLACK;
                cell6.BackgroundColor = Color.LIGHT_GRAY;
                tblAdjuster.AddCell(cell6);
                tblAdjuster.AddCell(new Phrase("Name", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_ADJUSTER_NAME"].ToString() != "")
                {
                    tblAdjuster.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_ADJUSTER_NAME"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblAdjuster.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblAdjuster.AddCell(new Phrase("Phone", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_PHONE"].ToString() != "")
                {
                    tblAdjuster.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_PHONE"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblAdjuster.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblAdjuster.AddCell(new Phrase("Extension", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_EXTENSION"].ToString() != "")
                {
                    tblAdjuster.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_EXTENSION"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblAdjuster.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblAdjuster.AddCell(new Phrase("Fax", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_FAX"].ToString() != "")
                {
                    tblAdjuster.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_FAX"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblAdjuster.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                tblAdjuster.AddCell(new Phrase("Email", iTextSharp.text.FontFactory.GetFont("Arial", 8, Font.BOLD, iTextSharp.text.Color.BLACK)));
                if (ds.Tables[0].Rows[0]["SZ_EMAIL"].ToString() != "")
                {
                    tblAdjuster.AddCell(new Phrase(Convert.ToString(ds.Tables[0].Rows[0]["SZ_EMAIL"]), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblAdjuster.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                PdfPCell cell7 = new PdfPCell(new Phrase(""));
                cell7.Colspan     = 2;
                cell7.BorderColor = Color.BLACK;
                tblAdjuster.AddCell(cell7);
                tblBase.AddCell(tblAdjuster);
                #endregion
                tblBase.AddCell(" ");
                tblBase.AddCell(" ");
                tblBase.AddCell(" ");
                tblBase.AddCell(" ");
                tblBase.AddCell(" ");
                tblBase.AddCell(" ");
                tblBase.AddCell(" ");
                tblBase.AddCell(" ");
                tblBase.AddCell(" ");
                tblBase.AddCell(" ");
                tblBase.AddCell(" ");


                #region "for websource information"
                float[]   wd5       = { 4f };
                PdfPTable tblSource = new PdfPTable(wd5);
                tblSource.TotalWidth         = document.PageSize.Width - document.LeftMargin - document.RightMargin;
                tblSource.DefaultCell.Border = Rectangle.NO_BORDER;
                tblSource.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT;
                tblSource.DefaultCell.VerticalAlignment   = iTextSharp.text.Element.ALIGN_BOTTOM;
                if (ds.Tables[0].Rows[0]["SZ_WEBSOURCE"].ToString() != "")
                {
                    tblSource.AddCell(new Phrase("Source : " + ds.Tables[0].Rows[0]["SZ_WEBSOURCE"].ToString(), iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }
                else
                {
                    tblAdjuster.AddCell(new Phrase("-", iTextSharp.text.FontFactory.GetFont("Arial", 8, iTextSharp.text.Color.BLACK)));
                }

                tblBase.AddCell(tblSource);
                #endregion
                document.Add(tblBase);
                document.Close();

                System.IO.File.WriteAllBytes(pdfPath, m.GetBuffer());
                string OpenPdfFilepath = OpenFilepath + newPdfFilename;
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "sandeep", "<script type='text/javascript'>window.location.href='" + OpenPdfFilepath + "'</script>");
            }
        }
        catch (Exception ex)
        {
            Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
            using (Utils utility = new Utils())
            {
                utility.MethodEnd(id, System.Reflection.MethodBase.GetCurrentMethod());
            }
            string str2 = "Error Request=" + id + ".Please share with Technical support.";
            base.Response.Redirect("../Bill_Sys_ErrorPage.aspx?ErrMsg=" + str2);
        }
        //Method End
        using (Utils utility = new Utils())
        {
            utility.MethodEnd(id, System.Reflection.MethodBase.GetCurrentMethod());
        }
    }
Пример #57
0
        public void PDFESTADOCERO()
        {
            Buscadores bus    = new Buscadores();
            var        doc    = new iTextSharp.text.Document(PageSize.A4);
            string     path   = Server.MapPath("~");
            PdfWriter  writer = PdfWriter.GetInstance(doc, new FileStream(path + "/Factura.pdf", FileMode.Create));


            vehiculo ovehiculo = bus.buscarvehiculoid(Ordenn.id_vehiculo ?? default(int));
            cliente  ocliente  = bus.ocliente(ovehiculo);
            modelo   omodelo   = bus.buscarmodelo(ovehiculo);
            marca    omarca    = bus.buscarmarca(omodelo);

            doc.Open();

            //Cabecera
            BaseFont bfntHead = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

            iTextSharp.text.Font fntHead    = new iTextSharp.text.Font(bfntHead, 16, 1, iTextSharp.text.BaseColor.BLUE.Darker());
            Paragraph            prgHeading = new Paragraph();

            prgHeading.Alignment = 1;
            prgHeading.Add(new Chunk("Factura".ToUpper(), fntHead));
            doc.Add(prgHeading);
            doc.Add(Chunk.NEWLINE);

            //Generado By
            Paragraph prgGeneratedBY = new Paragraph();
            BaseFont  btnAuthor      = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

            iTextSharp.text.Font fntAuthor = new iTextSharp.text.Font(btnAuthor, 12, 2, iTextSharp.text.BaseColor.BLACK);
            prgGeneratedBY.Alignment = Element.ALIGN_RIGHT;
            prgGeneratedBY.Add(new Chunk("Generado por: " + LogEmpleado.nombreyapellido, fntAuthor));  //Agregar LOG Empleado
            prgGeneratedBY.Add(new Chunk("\nFecha : " + DateTime.Now.ToShortDateString(), fntAuthor));
            prgGeneratedBY.Add(new Chunk("\nN° de Orden : " + Ordenn.id_orden, fntAuthor));
            doc.Add(prgGeneratedBY);
            doc.Add(Chunk.NEWLINE);

            doc.Add(Chunk.NEWLINE);

            //tablados
            PdfPTable tabla2 = new PdfPTable(2);

            tabla2.WidthPercentage = 100;
            tabla2.SpacingAfter    = 20;

            PdfPCell vehiculoTitulo = new PdfPCell(new Phrase("Vehiculo"));

            vehiculoTitulo.BorderWidth         = 0;
            vehiculoTitulo.BorderWidthRight    = 0.75f;
            vehiculoTitulo.BorderWidthTop      = 0.75f;
            vehiculoTitulo.BorderWidthLeft     = 0.75f;
            vehiculoTitulo.HorizontalAlignment = Element.ALIGN_CENTER;
            vehiculoTitulo.BackgroundColor     = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#C8C8C8"));

            PdfPCell clienteTitulo = new PdfPCell(new Phrase("Cliente"));

            clienteTitulo.BorderWidth         = 0;
            clienteTitulo.BorderWidthTop      = 0.75f;
            clienteTitulo.BorderWidthRight    = 0.75f;
            clienteTitulo.HorizontalAlignment = Element.ALIGN_CENTER;
            clienteTitulo.BackgroundColor     = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#C8C8C8"));



            PdfPCell patente = new PdfPCell(new Phrase("Patente: " + ovehiculo.patente));

            patente.BorderWidth       = 0;
            patente.BorderWidthRight  = 0.75f;
            patente.BorderWidthBottom = 0.75f;
            patente.BorderWidthLeft   = 0.75f;
            patente.BackgroundColor   = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#C8C8C8"));

            PdfPCell marca = new PdfPCell(new Phrase("Marca: " + omarca.nombre));

            marca.BorderWidth      = 0;
            marca.BorderWidthRight = 0.75f;
            marca.BorderWidthLeft  = 0.75f;
            marca.BackgroundColor  = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#C8C8C8"));

            PdfPCell modelo = new PdfPCell(new Phrase("Modelo: " + omodelo.nombre));

            modelo.BorderWidth      = 0;
            modelo.BorderWidthRight = 0.75f;
            modelo.BorderWidthLeft  = 0.75f;
            modelo.BackgroundColor  = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#C8C8C8"));

            PdfPCell nombre = new PdfPCell(new Phrase("Apellido y Nombre: " + ocliente.nombre));

            nombre.BorderWidth       = 0;
            nombre.BorderWidthLeft   = 0.75f;
            nombre.BorderWidthBottom = 0.75f;
            nombre.BorderWidthRight  = 0.75f;
            nombre.BackgroundColor   = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#C8C8C8"));

            PdfPCell dni = new PdfPCell(new Phrase("DNI: " + ocliente.dni));

            dni.BorderWidth       = 0;
            dni.BorderWidthBottom = 0.75f;
            dni.BorderWidthRight  = 0.75f;
            dni.BackgroundColor   = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#C8C8C8"));

            tabla2.AddCell(vehiculoTitulo);
            tabla2.AddCell(clienteTitulo);

            tabla2.AddCell(marca);
            tabla2.AddCell(modelo);
            tabla2.AddCell(nombre);
            tabla2.AddCell(patente);
            tabla2.AddCell(dni);

            doc.Add(tabla2);
            dt.Rows.Add("", "", "Total", lblprecio.Text);
            PdfPTable table = new PdfPTable(dt.Columns.Count);

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                string   cellText = Server.HtmlDecode(dt.Columns[i].ColumnName);
                PdfPCell cell     = new PdfPCell();
                cell.Phrase              = new Phrase(cellText, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 10, 1, new BaseColor(System.Drawing.ColorTranslator.FromHtml("#000000"))));
                cell.BackgroundColor     = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#C8C8C8"));
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                cell.VerticalAlignment   = Element.ALIGN_CENTER;
                cell.PaddingBottom       = 5;

                table.AddCell(cell);
            }
            //Agregando Campos a la tabla
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    PdfPCell cell = new PdfPCell();
                    cell.Phrase = new Phrase(dt.Rows[i][j].ToString(), new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 10, 0, new BaseColor(System.Drawing.ColorTranslator.FromHtml("#000000"))));

                    if (j == 1)
                    {
                        cell.HorizontalAlignment = Element.ALIGN_LEFT;
                    }
                    else
                    {
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    }
                    if (dt.Rows[i][j].ToString() == "Total")
                    {
                        cell.Phrase = new Phrase(dt.Rows[i][j].ToString(), new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 10, 1, new BaseColor(System.Drawing.ColorTranslator.FromHtml("#000000"))));
                    }
                    table.AddCell(cell);
                }
            }
            table.SetWidths(new float[] { 2, 8, 1, 1 });
            doc.Add(table);
            //Espacio


            doc.Close();
            Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('Factura.pdf','_newtab');", true);
            //Response.Redirect("Presupuesto.pdf");
        }
Пример #58
0
        public void PrintIO(invoiceoutheader ioh, List <invoiceoutdetail> IODetails, string taxStr, string podocID)
        {
            try
            {
                Dictionary <string, string> companyInfo = getCompanyInformation();
                string[] pos        = ioh.TrackingNos.Split(';');
                int      b          = 0;
                int[]    a          = (from s in pos where int.TryParse(s, out b) select b).ToArray();
                int      min        = a.Min();
                string[] dates      = ioh.TrackingDates.Split(';');
                string   poStr      = "";
                string   billingAdd = "";
                string   othRef     = "";
                for (int i = 0; i < pos.Length - 1; i++)
                {
                    string   custPOStr = POPIHeaderDB.getCustomerPOAndDateForInvoiceOut(Convert.ToInt32(pos[i]), Convert.ToDateTime(dates[i]), podocID);
                    string[] custPO    = custPOStr.Split(Main.delimiter1);
                    ////if (Convert.ToInt32(pos[i]) == min)
                    ////billingAdd = custPO[2];
                    poStr  = poStr + custPO[0] + ", Date: " + String.Format("{0:dd MMMM, yyyy}", Convert.ToDateTime(custPO[1])) + "\n";
                    othRef = othRef + pos[i] + ",";
                }
                companybank cb         = CompanyBankDB.getCompBankDetailForIOPrint(ioh.BankAcReference);
                customer    custDetail = CustomerDB.getCustomerDetailForPO(ioh.ConsigneeID);

                string[] companyBillingAdd = CompanyAddressDB.getCompTopBillingAdd(Login.companyID);
                string   ConsgAdd          = "Consignee:\n" + custDetail.name + Main.delimiter2 + "\n" + ioh.DeliveryAddress + "\n";
                string   buyer             = "Buyer:\n" + custDetail.name + Main.delimiter2 + "\n" + custDetail.BillingAddress + "\n";
                if (custDetail.StateName.ToString().Length != 0)
                {
                    ConsgAdd = ConsgAdd + "Sate Name:" + custDetail.StateName;
                    buyer    = buyer + "Sate Name:" + custDetail.StateName;
                    if (custDetail.StateCode.ToString().Length != 0)
                    {
                        ConsgAdd = ConsgAdd + " ,\nState Code:" + custDetail.StateCode;
                        buyer    = buyer + " ,\nState Code:" + custDetail.StateCode;
                    }
                }
                else
                {
                    if (custDetail.StateCode.ToString().Length != 0)
                    {
                        ConsgAdd = ConsgAdd + "\nState Code:" + custDetail.StateCode;
                        buyer    = buyer + "\nState Code:" + custDetail.StateCode;
                    }
                }
                if (custDetail.OfficeName.ToString().Length != 0)
                {
                    ConsgAdd = ConsgAdd + "\nGST:" + custDetail.OfficeName; // For GST Code
                    buyer    = buyer + "\nGST:" + custDetail.OfficeName;    // For GST Code
                }
                if (CustomerDB.getCustomerPANForInvoicePrint(ioh.ConsigneeID).Length != 0)
                {
                    ConsgAdd = ConsgAdd + "\nPAN:" + custDetail.OfficeName; // For PAN Code
                    buyer    = buyer + "\nPAN:" + custDetail.OfficeName;    // For PAN Code
                }

                string HeaderString = buyer +

                                      Main.delimiter1 + "Invoice No : " + ioh.InvoiceNo + " , Date: " + String.Format("{0:dd MMMM, yyyy}", ioh.InvoiceDate) +
                                      Main.delimiter1 + "Buyer's Reference : " + poStr.Trim() +
                                      Main.delimiter1 + "Mode of Dispatch : " + ioh.TransportationModeName +
                                      Main.delimiter1 + "Terms of Payment : " + ioh.TermsOfPayment + Main.delimiter1 + //Description : Name of terms of payment

                                      ConsgAdd +

                                      Main.delimiter1 + "Supplier's Reference : " + othRef.Trim().Substring(0, othRef.Length - 1) +
                                      Main.delimiter1 + "Reverse Charge : " + ioh.ReverseCharge +
                                      Main.delimiter1 + ioh.SpecialNote;

                string footer1   = "Amount in words\n\n";
                string ColHeader = "";
                if (ioh.DocumentID == "PRODUCTINVOICEOUT" || ioh.DocumentID == "PRODUCTEXPORTINVOICEOUT")
                {
                    ColHeader = "SI No.;Description of Goods;HSN;Quantity;Unit;Unit Rate;Amount";
                }
                else
                {
                    ColHeader = "SI No.;Description of Goods;SAC;Quantity;Unit;Unit Rate;Amount";
                }
                CompanyDetailDB compDB   = new CompanyDetailDB();
                cmpnydetails    det      = compDB.getdetails().FirstOrDefault(comp => comp.companyID == 1);
                string          compName = "";
                if (det != null)
                {
                    compName = det.companyname;
                }
                string footer2 = "\n\nAccount Name : " + compName + "\nAccount No : " + cb.AccountCode + "\nAccount Type : " + cb.AccountType + "\nBank : " + cb.BankName + "\nBranch : " + cb.BranchName + "\nIFSC : " + cb.CreateUser;
                //"\nSWIFT Code : " + cb.CompanyID +
                string footer3         = "For Cellcomm Solutions Limited;Authorised Signatory";
                double totQuant        = 0.00;
                double totAmnt         = 0.00;
                int    n               = 1;
                string ColDetailString = "";
                var    count           = IODetails.Count();

                foreach (invoiceoutdetail iod in IODetails)
                {
                    if (ioh.DocumentID == "PRODUCTINVOICEOUT")
                    {
                        iod.HSNCode = iod.HSNCode.Substring(0, 4);
                    }
                    else if (ioh.DocumentID == "SERVICEINVOICEOUT")
                    {
                        iod.HSNCode = iod.HSNCode.Substring(0, 6);
                    }
                    if (n == count)
                    {
                        //if (ioh.DocumentID == "PRODUCTINVOICEOUT")
                        ColDetailString = ColDetailString + n + Main.delimiter1 + iod.CustomerItemDescription + Main.delimiter1 + iod.HSNCode + Main.delimiter1 + iod.Quantity + Main.delimiter1
                                          + iod.Unit + Main.delimiter1 + iod.Price + Main.delimiter1 + (iod.Quantity * iod.Price);
                        //else
                        //    ColDetailString = ColDetailString + n + Main.delimiter1 + iod.CustomerItemDescription + Main.delimiter1 + iod.HSNCode.Substring(0, 4) + Main.delimiter1 + iod.Quantity + Main.delimiter1
                        //                   + iod.Price + Main.delimiter1 + (iod.Quantity * iod.Price);
                    }
                    else
                    {
                        //if (ioh.DocumentID == "PRODUCTINVOICEOUT")
                        ColDetailString = ColDetailString + n + Main.delimiter1 + iod.CustomerItemDescription + Main.delimiter1 + iod.HSNCode + Main.delimiter1 + iod.Quantity + Main.delimiter1
                                          + iod.Unit + Main.delimiter1 + iod.Price + Main.delimiter1 + (iod.Quantity * iod.Price) + Main.delimiter2;
                        //else
                        //    ColDetailString = ColDetailString + n + Main.delimiter1 + iod.CustomerItemDescription + Main.delimiter1 + iod.HSNCode.Substring(0, 4) + Main.delimiter1 + iod.Quantity + Main.delimiter1
                        //                   + iod.Price + Main.delimiter1 + (iod.Quantity * iod.Price) + Main.delimiter2;
                    }
                    totQuant = totQuant + iod.Quantity;
                    totAmnt  = totAmnt + (iod.Quantity * iod.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);
                    if (ioh.status == 0 && ioh.DocumentStatus < 99)
                    {
                        sfd.FileName = ioh.DocumentID + "-Temp-" + ioh.TemporaryNo;
                    }
                    else
                    {
                        sfd.FileName = ioh.DocumentID + "-" + ioh.InvoiceNo;
                    }

                    if (sfd.ShowDialog() == DialogResult.Cancel || sfd.FileName == "")
                    {
                        return;
                    }
                    FileStream fs  = new FileStream(sfd.FileName, FileMode.Create, FileAccess.Write);
                    Rectangle  rec = new Rectangle(PageSize.A4);
                    rec.Bottom = 10;
                    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);
                    Font font4 = FontFactory.GetFont("Arial", 5, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

                    String URL = "Cellcomm2.JPG";
                    iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(URL);
                    img.Alignment = Element.ALIGN_LEFT;

                    PdfPTable tableHeader = new PdfPTable(2);

                    tableHeader.WidthPercentage = 100;
                    PdfPCell  cellImg = new PdfPCell();
                    Paragraph pp      = new Paragraph();
                    pp.Add(new Chunk(img, 0, 0));
                    cellImg.AddElement(pp);
                    cellImg.Border = 0;
                    tableHeader.AddCell(cellImg);

                    PdfPCell  cellAdd = new PdfPCell();
                    Paragraph ourAddr = new Paragraph("");

                    if (det != null)
                    {
                        ourAddr.Add(new Chunk(det.companyname + "\n", font2));
                        ourAddr.Add(new Chunk(det.companyAddress.Replace("\r\n", "\n"), font4));
                        StringBuilder sb = new StringBuilder();
                        sb.Append("\nGST : " + companyInfo["GST"] + "\nState Code for GST : " + companyInfo["StateCode"] + "\nCIN : " + companyInfo["CIN"] + "\nPAN : " + companyInfo["PAN"]);
                        ourAddr.Add(new Chunk(sb.ToString(), font4));
                        ourAddr.Alignment = Element.ALIGN_RIGHT;
                        ourAddr.SetLeading(0.0f, 1.5f);
                    }
                    cellAdd.AddElement(ourAddr);
                    cellAdd.Border = 0;
                    tableHeader.AddCell(cellAdd);

                    Paragraph ParagraphDocumentName = new Paragraph(new Phrase("Tax Invoice", font2));
                    ParagraphDocumentName.Alignment = Element.ALIGN_CENTER;

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

                    PdfPTable TableAddress = new PdfPTable(7);

                    TableAddress.SpacingBefore   = 20f;
                    TableAddress.WidthPercentage = 100;
                    float[] HWidths = new float[] { 1f, 8f, 1.5f, 2f, 1.5f, 2f, 3f };
                    TableAddress.SetWidths(HWidths);
                    PdfPCell cell;
                    int[]    arr = { 3, 7, 9, 10 };
                    float    wid = 0;
                    for (int i = 0; i < HeaderStr.Length; i++)
                    {
                        if (i == 0 || i == 5)
                        {
                            string[] format = HeaderStr[i].Split(Main.delimiter2);
                            Phrase   phr    = new Phrase();
                            phr.Add(new Chunk(format[0], font2));
                            phr.Add(new Chunk(format[1], font1));
                            cell = new PdfPCell(phr);
                            if (i == 0)
                            {
                                cell.Rowspan = 4;
                            }
                            else
                            {
                                cell.Rowspan = 3;
                            }
                            cell.Colspan             = 2;
                            cell.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
                            TableAddress.AddCell(cell);
                        }
                        else
                        {
                            cell               = new PdfPCell(new Phrase(HeaderStr[i].Trim(), font1));
                            cell.Colspan       = 5;
                            cell.MinimumHeight = wid;
                            TableAddress.AddCell(cell);
                        }
                    }
                    string[] ColHeaderStr = ColHeader.Split(';');

                    PdfPTable TableItemDetail = new PdfPTable(7);
                    TableItemDetail.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                    TableItemDetail.WidthPercentage = 100;
                    float[] widthProd = new float[] { 1f, 8f, 1.5f, 2f, 1.5f, 2f, 3f };
                    float[] widthServ = new float[] { 1f, 8f, 1.5f, 2f, 0f, 2f, 3f };
                    if (ioh.DocumentID == "PRODUCTINVOICEOUT" || ioh.DocumentID == "PRODUCTEXPORTINVOICEOUT")
                    {
                        TableItemDetail.SetWidths(widthProd);
                    }
                    else
                    {
                        TableItemDetail.SetWidths(widthServ);
                    }


                    //Table Row No : 1 (Header Column)
                    for (int i = 0; i < ColHeaderStr.Length; i++)
                    {
                        if (i == (ColHeaderStr.Length - 1) || i == (ColHeaderStr.Length - 2))
                        {
                            PdfPCell hcell = new PdfPCell(new Phrase(ColHeaderStr[i].Trim() + "\n(" + ioh.CurrencyID + ")", font2));
                            hcell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                            TableItemDetail.AddCell(hcell);
                        }
                        else
                        {
                            PdfPCell hcell = new PdfPCell(new Phrase(ColHeaderStr[i].Trim(), font2));
                            hcell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                            TableItemDetail.AddCell(hcell);
                        }
                    }
                    //---
                    //Table Row No : 2 (Footer Column)
                    PdfPCell foot = new PdfPCell(new Phrase(""));
                    foot.Colspan        = 7;
                    foot.BorderWidthTop = 0;
                    foot.MinimumHeight  = 0.5f;
                    TableItemDetail.AddCell(foot);

                    TableItemDetail.HeaderRows = 2;
                    TableItemDetail.FooterRows = 1;

                    TableItemDetail.SkipFirstHeader = false;
                    TableItemDetail.SkipLastFooter  = true;
                    //---
                    int     track = 0;
                    decimal dc1   = 0;
                    decimal dc2   = 0;

                    //Table Row No : 3 (Header Column)
                    string[] DetailStr = ColDetailString.Split(Main.delimiter2);
                    float    hg        = 0f;
                    for (int i = 0; i < DetailStr.Length; i++)
                    {
                        track = 0;
                        hg    = TableItemDetail.GetRowHeight(i + 1);
                        string[] str = DetailStr[i].Split(Main.delimiter1);
                        for (int j = 0; j < str.Length; j++)
                        {
                            PdfPCell pcell;
                            if (j == 3 || j == 5 || j == 6)
                            {
                                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;
                                if (j == 6)
                                {
                                    dc1 = Convert.ToDecimal(str[j]);
                                }
                            }
                            else
                            {
                                if (j == 2)
                                {
                                    if (str[j].Trim().Length == 0)
                                    {
                                        pcell = new PdfPCell(new Phrase("", font1));
                                    }
                                    else
                                    {
                                        pcell = new PdfPCell(new Phrase(str[j], font1));
                                    }
                                }
                                else if (j == 4)
                                {
                                    int m = 1;
                                    if (Int32.TryParse(str[j], out m) == true)
                                    {
                                        if (Convert.ToInt32(str[j]) == 0)
                                        {
                                            pcell = new PdfPCell(new Phrase("", font1));
                                        }
                                        else
                                        {
                                            pcell = new PdfPCell(new Phrase(str[j], font1));
                                        }
                                    }
                                    else
                                    {
                                        pcell = new PdfPCell(new Phrase(str[j], font1));
                                    }
                                }
                                else
                                {
                                    pcell = new PdfPCell(new Phrase(str[j], font1));
                                }
                                pcell.Border = 0;
                            }

                            pcell.MinimumHeight = 10;
                            if (j == 1)
                            {
                                pcell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                            }
                            else
                            {
                                pcell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                            }
                            pcell.BorderWidthLeft  = 0.01f;
                            pcell.BorderWidthRight = 0.01f;

                            TableItemDetail.AddCell(pcell);
                        }
                    }
                    PdfPCell Temp = new PdfPCell(new Phrase(""));
                    Temp.Border           = 0;
                    Temp.BorderWidthLeft  = 0.01f;
                    Temp.BorderWidthRight = 0.01f;

                    int dd = 0;
                    if (ioh.TaxAmount != 0)
                    {
                        ////Table Row No : 4 (Total Amount)
                        PdfPCell Temp1 = new PdfPCell(new Phrase(""));
                        Temp1.Border           = 0;
                        Temp1.BorderWidthTop   = 0.01f;
                        Temp1.BorderWidthLeft  = 0.01f;
                        Temp1.BorderWidthRight = 0.01f;
                        TableItemDetail.AddCell(Temp1); //blank cell
                        TableItemDetail.AddCell(Temp1);
                        PdfPCell cellCom = new PdfPCell(new Phrase("", font1));
                        cellCom.Colspan             = 4;
                        cellCom.Border              = 0;
                        cellCom.BorderWidthLeft     = 0.01f;
                        cellCom.BorderWidthRight    = 0.01f;
                        cellCom.BorderWidthTop      = 0.01f;
                        cellCom.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                        TableItemDetail.AddCell(cellCom);

                        PdfPCell cellTot = new PdfPCell(new Phrase(String.Format("{0:0.00}", Convert.ToDecimal(totAmnt)), font2));
                        cellTot.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                        TableItemDetail.AddCell(cellTot);
                        dd++;

                        string[] tax = taxStr.Split(Main.delimiter2);
                        for (int i = 0; i < tax.Length - 1; i++)
                        {
                            TableItemDetail.AddCell(Temp); //blank cell
                            TableItemDetail.AddCell(Temp);

                            string[] subtax     = tax[i].Split(Main.delimiter1);
                            PdfPCell cellinrtax = new PdfPCell(new Phrase(subtax[0], font1));
                            cellinrtax.Colspan             = 4;
                            cellinrtax.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                            TableItemDetail.AddCell(cellinrtax);

                            PdfPCell pcell2;
                            pcell2 = new PdfPCell(new Phrase(String.Format("{0:0.00}", Convert.ToDecimal(subtax[1])), font1));
                            pcell2.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                            TableItemDetail.AddCell(pcell2);
                            dd++;
                        }
                        double taxAmRnd = Math.Round(ioh.TaxAmount, 0);
                        if (taxAmRnd != ioh.TaxAmount)
                        {
                            TableItemDetail.AddCell(Temp); //blank cell
                            TableItemDetail.AddCell(Temp);
                            PdfPCell cellTotTax = new PdfPCell(new Phrase("", font1));
                            cellTotTax.Colspan          = 4;
                            cellTotTax.Border           = 0;
                            cellTotTax.BorderWidthLeft  = 0.01f;
                            cellTotTax.BorderWidthRight = 0.01f;
                            //cellCom.BorderWidthTop = 0.01f;
                            cellTotTax.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                            TableItemDetail.AddCell(cellTotTax);

                            PdfPCell cellTotTaxValue = new PdfPCell(new Phrase(String.Format("{0:0.00}", Convert.ToDecimal(totAmnt + ioh.TaxAmount)), font2));
                            cellTotTaxValue.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                            TableItemDetail.AddCell(cellTotTaxValue);
                            dd++;
                        }
                    }



                    double roundedAmt = Math.Round(ioh.InvoiceAmount, 0);
                    double diffAmount = roundedAmt - ioh.InvoiceAmount;

                    if (diffAmount != 0)
                    {
                        TableItemDetail.AddCell("");
                        TableItemDetail.AddCell("");
                        PdfPCell cellRound = new PdfPCell(new Phrase("Rounding off", font1));
                        cellRound.Colspan             = 4;
                        cellRound.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                        TableItemDetail.AddCell(cellRound);
                        TableItemDetail.AddCell(new Phrase(String.Format("{0:0.00}", diffAmount), font1));
                        //table1.AddCell("");
                        dd++;
                    }

                    TableItemDetail.AddCell("");
                    TableItemDetail.AddCell("");
                    PdfPCell cellRoundTot = new PdfPCell(new Phrase("Total", font1));
                    cellRoundTot.Colspan             = 4;
                    cellRoundTot.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    TableItemDetail.AddCell(cellRoundTot);

                    PdfPCell roundTot = new PdfPCell(new Phrase(String.Format("{0:0.00}", roundedAmt), font2));
                    roundTot.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                    TableItemDetail.AddCell(roundTot);

                    //table1.AddCell("");
                    string   total  = footer1 + NumberToString.convert(roundedAmt.ToString()).Replace("INR", ioh.CurrencyID) + "\n\n";
                    PdfPCell fcell1 = new PdfPCell(new Phrase((total), font1));
                    fcell1.Border              = 0;
                    fcell1.Colspan             = 6;
                    fcell1.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    fcell1.BorderWidthLeft     = 0.5f;
                    fcell1.BorderWidthBottom   = 0.5f;
                    fcell1.BorderWidthRight    = 0;
                    fcell1.BorderWidthTop      = 0;
                    TableItemDetail.AddCell(fcell1);

                    PdfPCell fcell4 = new PdfPCell(new Phrase("E. & O.E", font1));
                    fcell4.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    fcell4.Border            = 0;
                    fcell4.BorderWidthBottom = 0.5f;
                    fcell4.BorderWidthRight  = 0.5f;
                    fcell4.BorderWidthLeft   = 0;
                    fcell4.BorderWidthTop    = 0;
                    TableItemDetail.AddCell(fcell4);
                    TableItemDetail.KeepRowsTogether(TableItemDetail.Rows.Count - (dd + 4), TableItemDetail.Rows.Count);
                    //int HSNMappCount = TaxDataTable.Rows.Count + 6;
                    //int itemCount = DetailStr.Length;
                    //int tableCount = table1.Rows.Count;

                    //=================================================
                    //DataTable TaxDataTable = new DataTable("TaxDetails");
                    //DataColumn[] colArr = { new DataColumn("HSN Code"), new DataColumn("Taxable Value"), new DataColumn("CGST %"),
                    //    new DataColumn("CGST Amt"), new DataColumn("SGST %"), new DataColumn("SGST Amt"), new DataColumn("IGST %"),
                    //    new DataColumn("IGST Amt"), new DataColumn("Total Amt") };
                    //TaxDataTable.Columns.AddRange(colArr);

                    //DataRow myDataRow = TaxDataTable.NewRow();
                    //myDataRow[colArr[0]] = "1111";
                    //myDataRow[colArr[1]] = "1000";
                    //myDataRow[colArr[2]] = "9";
                    //myDataRow[colArr[3]] = "200";
                    //myDataRow[colArr[4]] = "9";
                    //myDataRow[colArr[5]] = "200";
                    //myDataRow[colArr[6]] = "14";
                    //myDataRow[colArr[7]] = "600";
                    //myDataRow[colArr[8]] = "2000";
                    //TaxDataTable.Rows.Add(myDataRow);
                    //DataRow myDataRow1 = TaxDataTable.NewRow();
                    //myDataRow1[colArr[0]] = "2222";
                    //myDataRow1[colArr[1]] = "2000";
                    //myDataRow1[colArr[2]] = "9";
                    //myDataRow1[colArr[3]] = "300";
                    //myDataRow1[colArr[4]] = "9";
                    //myDataRow1[colArr[5]] = "400";
                    //myDataRow1[colArr[6]] = "14";
                    //myDataRow1[colArr[7]] = "1300";
                    //myDataRow1[colArr[8]] = "4000";
                    //TaxDataTable.Rows.Add(myDataRow1);
                    //==============================================
                    InvoiceOutHeaderDB iohDB        = new InvoiceOutHeaderDB();
                    DataTable          TaxDataTable = iohDB.taxDetails4Print(IODetails, ioh.DocumentID);


                    PdfPTable TabTaxDetail = new PdfPTable(TaxDataTable.Columns.Count);
                    TabTaxDetail.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                    TabTaxDetail.WidthPercentage = 100;
                    //TabTaxDetail.SpacingBefore = 10;
                    PdfPCell cellTax = new PdfPCell();
                    //Adding columns in table
                    List <string>            colListStr    = new List <string>();
                    List <string>            colListSubStr = new List <string>();
                    double                   amtTot        = 0;
                    double                   TaxTot1       = 0;
                    double                   TaxTot2       = 0;
                    double                   TaxTot3       = 0;
                    double                   TaxTot        = 0;
                    Dictionary <int, string> dictTot       = new Dictionary <int, string>();
                    for (int p = 0; p < TaxDataTable.Columns.Count; p++)
                    {
                        if (p != 0 && p != 1 && p != TaxDataTable.Columns.Count - 1)
                        {
                            TaxTot1 = 0;
                            string substr = TaxDataTable.Columns[p].ColumnName;
                            colListStr.Add(substr.Trim());                             //CGST
                            colListSubStr.Add(TaxDataTable.Columns[p].ColumnName);     //CGST% in subList
                            colListSubStr.Add(TaxDataTable.Columns[p + 1].ColumnName); //CGST amount in subList
                            p++;
                            if (p % 2 != 0)
                            {
                                TaxTot1 = TaxDataTable.AsEnumerable().Sum(c => c.Field <double>(TaxDataTable.Columns[p].ColumnName));
                                dictTot.Add(p, String.Format("{0:0.00}", Convert.ToDecimal(TaxTot1)));
                            }
                        }
                        else
                        {
                            colListStr.Add(TaxDataTable.Columns[p].ColumnName);
                            if (p == 1)
                            {
                                amtTot = TaxDataTable.AsEnumerable().Sum(c => c.Field <double>(TaxDataTable.Columns[p].ColumnName));
                                dictTot.Add(p, String.Format("{0:0.00}", Convert.ToDecimal(amtTot)));
                            }
                            if (p == TaxDataTable.Columns.Count - 1)
                            {
                                TaxTot = TaxDataTable.AsEnumerable().Sum(c => c.Field <double>(TaxDataTable.Columns[p].ColumnName));
                                dictTot.Add(p, String.Format("{0:0.00}", Convert.ToDecimal(TaxTot)));
                            }
                        }
                    }
                    foreach (string str in colListStr)
                    {
                        int index = colListStr.FindIndex(x => x == str);
                        if (index == 0 || index == 1 || index == colListStr.Count - 1)
                        {
                            cellTax         = new PdfPCell();
                            cellTax.Rowspan = 2;
                            Paragraph p = new Paragraph(str, font2);
                            p.Alignment = Element.ALIGN_CENTER;
                            cellTax.AddElement(p);
                            TabTaxDetail.AddCell(cellTax);
                        }
                        else
                        {
                            cellTax         = new PdfPCell();
                            cellTax.Colspan = 2;
                            Paragraph p = new Paragraph(str, font2);
                            p.Alignment = Element.ALIGN_CENTER;
                            cellTax.AddElement(p);
                            TabTaxDetail.AddCell(cellTax);
                        }
                    }
                    foreach (string str in colListSubStr)
                    {
                        cellTax = new PdfPCell();
                        Paragraph p = new Paragraph(str, font2);
                        p.Alignment = Element.ALIGN_CENTER;
                        cellTax.AddElement(p);
                        TabTaxDetail.AddCell(cellTax);
                    }
                    int t = 0;
                    foreach (DataRow row in TaxDataTable.Rows)
                    {
                        int l = 0;
                        foreach (DataColumn col in TaxDataTable.Columns)
                        {
                            cellTax = new PdfPCell();
                            if (l == 1 || l % 2 != 0 || l == TaxDataTable.Columns.Count - 1)
                            {
                                Paragraph p = new Paragraph(String.Format("{0:0.00}", Convert.ToDecimal(row[col].ToString())), font1);
                                p.Alignment = Element.ALIGN_CENTER;
                                cellTax.AddElement(p);
                                TabTaxDetail.AddCell(cellTax);
                            }
                            else
                            {
                                Paragraph p = new Paragraph(row[col].ToString(), font1);
                                p.Alignment = Element.ALIGN_CENTER;
                                cellTax.AddElement(p);
                                TabTaxDetail.AddCell(cellTax);
                            }
                            t++;
                            l++;
                        }
                    }
                    for (int k = 0; k < TaxDataTable.Columns.Count; k++)
                    {
                        if (k == 0)
                        {
                            cellTax = new PdfPCell();
                            Paragraph p = new Paragraph("Total", font2);
                            p.Alignment = Element.ALIGN_CENTER;
                            cellTax.AddElement(p);
                            TabTaxDetail.AddCell(cellTax);
                        }
                        else if (dictTot.ContainsKey(k))
                        {
                            cellTax = new PdfPCell();
                            Paragraph p = new Paragraph(dictTot[k], font2);
                            p.Alignment = Element.ALIGN_CENTER;
                            cellTax.AddElement(p);
                            TabTaxDetail.AddCell(cellTax);
                        }
                        else
                        {
                            cellTax = new PdfPCell();
                            Paragraph p = new Paragraph("", font1);
                            p.Alignment = Element.ALIGN_CENTER;
                            cellTax.AddElement(p);
                            TabTaxDetail.AddCell(cellTax);
                        }
                    }
                    //TabTaxDetail.KeepRowsTogether(TabTaxDetail.Rows.Count - 10, TabTaxDetail.Rows.Count);
                    TabTaxDetail.KeepTogether = true;

                    //Bank dtails and authorised Signature
                    PdfPTable tableFooter = new PdfPTable(2);
                    tableFooter.WidthPercentage = 100;
                    Phrase phrs = new Phrase();
                    phrs.Add(new Chunk("\nBank Details for Payment", font2));

                    phrs.Add(new Chunk(footer2, font1));

                    PdfPCell fcell2 = new PdfPCell(phrs);
                    fcell2.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    fcell2.BorderWidthRight    = 0;
                    tableFooter.AddCell(fcell2);

                    string[] ft = footer3.Split(';');

                    PdfPCell fcell3 = new PdfPCell();
                    Chunk    ch1    = new Chunk(ft[0], font1);
                    Chunk    ch2    = new Chunk(ft[1], font1);
                    Phrase   phrase = new Phrase();
                    phrase.Add(ch1);
                    for (int i = 0; i < 3; i++)
                    {
                        phrase.Add(Chunk.NEWLINE);
                    }
                    phrase.Add(ch2);

                    Paragraph para = new Paragraph();
                    para.Add(phrase);
                    para.Alignment = Element.ALIGN_RIGHT;
                    fcell3.AddElement(para);
                    fcell3.Border            = 0;
                    fcell3.BorderWidthRight  = 0.5f;
                    fcell3.BorderWidthBottom = 0.5f;
                    fcell3.MinimumHeight     = 50;
                    tableFooter.AddCell(fcell3);

                    PdfPTable tableSub = new PdfPTable(1);
                    tableSub.DefaultCell.Border = 0;
                    tableSub.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                    tableSub.AddCell(new Phrase("Subject To Bangalore Jurisdiction", font2));

                    PdfPCell celSub = new PdfPCell(tableSub);
                    celSub.Border  = 0;
                    celSub.Colspan = 2;
                    tableFooter.AddCell(celSub);

                    //=======


                    doc.Add(tableHeader);
                    doc.Add(ParagraphDocumentName);
                    doc.Add(TableAddress);
                    doc.Add(TableItemDetail);
                    doc.Add(TabTaxDetail);
                    doc.Add(tableFooter);


                    doc.Close();

                    if (ioh.status == 0 && ioh.DocumentStatus < 99)
                    {
                        String wmurl = "";
                        wmurl = "004.png";
                        PrintWaterMark.PdfStampWithNewFile(wmurl, sfd.FileName);
                    }
                    if (ioh.status == 98)
                    {
                        String wmurl = "";
                        wmurl = "003.png";
                        PrintWaterMark.PdfStampWithNewFile(wmurl, sfd.FileName);
                    }
                    MessageBox.Show("Document Saved");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this.ToString() + "-" + System.Reflection.MethodBase.GetCurrentMethod().Name + "() : Error-" + ex.ToString());
                    MessageBox.Show("Failed TO Save");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception : " + ex.ToString());
                MessageBox.Show("Failed TO Save");
            }
        }
Пример #59
-1
 /// <summary>
 /// Concatenates two or more PDF files into one file.
 /// </summary>
 /// <param name="inputFiles">A string array containing the names of the pdf files to concatenate</param>
 /// <param name="outputFile">Name of the concatenated file.</param>
 public void ConcatenatePDFFiles(String[] inputFiles, String outputFile)
 {
     if (inputFiles != null && inputFiles.Length > 0)
     {
         if (!String.IsNullOrEmpty(outputFile) && !String.IsNullOrWhiteSpace(outputFile))
         {
             var concatDocument = new iTextSharpText.Document();
             var outputCopy = new iTextSharpPDF.PdfCopy(concatDocument, new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite));
             concatDocument.Open();
             try
             {
                 for (int loop = 0; loop <= inputFiles.GetUpperBound(0); loop++)
                 {
                     var inputDocument = new iTextSharpPDF.PdfReader(inputFiles[loop]);
                     for (int pageLoop = 1; pageLoop <= inputDocument.NumberOfPages; pageLoop++)
                     {
                         concatDocument.SetPageSize(inputDocument.GetPageSizeWithRotation(pageLoop));
                         outputCopy.AddPage(outputCopy.GetImportedPage(inputDocument, pageLoop));
                     }
                     inputDocument.Close();
                     outputCopy.FreeReader(inputDocument);
                     inputDocument = null;
                 }
                 concatDocument.Close();
                 outputCopy.Close();
             }
             catch
             {
                 if (concatDocument != null && concatDocument.IsOpen()) concatDocument.Close();
                 if (outputCopy != null) outputCopy.Close();
                 if (File.Exists(outputFile))
                 {
                     try
                     {
                         File.Delete(outputFile);
                     }
                     catch { }
                 }
                 throw;
             }
         }
         else
         {
             throw new ArgumentNullException("outputFile", exceptionArgumentNullOrEmptyString);
         }
     }
     else
     {
         throw new ArgumentNullException("inputFiles", exceptionArgumentNullOrEmptyString);
     }
 }
Пример #60
-2
        protected void Page_Load(object sender, EventArgs e)
        {
            iTextSharp.text.pdf.BarcodeQRCode qrcode = new BarcodeQRCode("testing", 50, 50, null);
            iTextSharp.text.Image img1 = qrcode.GetImage();
            Document doc = new Document();

            try
            {
                PdfWriter.GetInstance(doc, new FileStream(Server.MapPath("css") + "/Images.pdf", FileMode.Create));
                doc.Open();
                doc.Add(new Paragraph("GIF"));

                doc.Add(img1);
                MemoryStream ms = new MemoryStream(img1.OriginalData);
                System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);

               // img = returnImage.Save(new Stream(), System.Drawing.Imaging.ImageFormat.Jpeg);

            }
            catch (Exception ex)
            {
            }
            finally
            {
                doc.Close();
            }
        }