Пример #1
0
 /**
  * Parses the PDF using PRTokeniser
  * @param src  the path to the original PDF file
  * @param dest the path to the resulting text file
  */
 public string[] parsePdfToHtml(string src)
 {
     iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(src);
     //StreamWriter output = new StreamWriter();
     SimpleTextExtractionStrategy strategy = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
     List<string> text = new List<string>(); ;
     int pageCount = reader.NumberOfPages;
     for (int pg = 1; pg <= pageCount; pg++)
     {
         text.Add(PdfTextExtractor.GetTextFromPage(reader, pg, strategy));
     }
     return text.ToArray();
 }
Пример #2
0
        /**
         * Parses the PDF using PRTokeniser
         * @param src  the path to the original PDF file
         * @param dest the path to the resulting text file
         */
        public string[] ParsePdfToText(string src)
        {
            iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(src);
            //reader.t
            //StreamWriter output = new StreamWriter();
            LocationTextExtractionStrategy strategy = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();
            List<string> text = new List<string>();
            int pageCount = reader.NumberOfPages;
            for (int pg = 1; pg <= pageCount; pg++)
            {

                string content=PdfTextExtractor.GetTextFromPage(reader, pg, strategy);
                text.Add(content);
            }
            return text.ToArray();
        }
Пример #3
0
        public void Split(string pdfPath, string destPath, BackgroundWorker worker = null)
        {
            //Inicjalizacja raportowania
            if (this.ReportCheckBox.Checked) {
                this.logsFile = new StreamWriter(Path.Combine(destPath, DateTime.Now.ToString("yyyyMMddHHmmss") + "RAPORT.txt"));
            }

            #region Wstępne rozpoznawanie

            BitmapPDF pdfBitmap = new BitmapPDF(pdfPath);
            PdfReader pdfDoc = new PdfReader(pdfPath);

            int[] results = new int[pdfDoc.NumberOfPages];
            for (int i = 0; i < pdfDoc.NumberOfPages && !worker.CancellationPending; i++) {
                try {
                    results[i] = pdfBitmap.Current.AvgContent;
                    if (logsFile != null) {
                        logsFile.WriteLine(String.Format("Strona {0}: {1}", i + 1, results[i]));
                    }

                    worker.ReportProgress(((i + 1) * 100) / pdfDoc.NumberOfPages);
                    pdfBitmap.MoveNext();
                } catch (Exception ex) {
                    //Będzie zawsze na końcu
                    Console.WriteLine(ex.Message);
                }
            }

            pdfDoc.Close();
            pdfBitmap.Dispose();
            if (logsFile != null)
                logsFile.Close();
            #endregion

            #region Właściwe rozdzielanie
            if (!worker.CancellationPending) {
                int j = 1;
                List<int> pages = new List<int>();

                foreach (int result in results) {
                    if (result > int.Parse(Properties.Settings.Default.MaxSensitivity)) {
                        if (pages.Count > 0) {
                            try {
                                string pdfDest = Path.Combine(destPath, DateTime.Now.ToString("yyyyMMddHHmmss") + j.ToString().PadLeft(4, '0') + ".pdf");
                                this.ExtractPages(pdfPath, pdfDest, pages.ToArray());
                            } catch (Exception ex) {
                                MessageBox.Show("Wystąpił błąd! " + ex.Message, "To jakiś straszny błąd!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }

                            pages.Clear();
                        }
                    } else if (result > int.Parse(Properties.Settings.Default.MinSensitivity)) {
                        pages.Add(j);
                    }

                    j++;
                }

                //Na wszelki wypadek, gdyby końcówka została
                if (pages.Count > 0) {
                    try {
                        string pdfDest = Path.Combine(destPath, DateTime.Now.ToString("yyyyMMddHHmmss") + j.ToString().PadLeft(4, '0') + ".pdf");
                        this.ExtractPages(pdfPath, pdfDest, pages.ToArray());
                    } catch (Exception ex) {
                        MessageBox.Show("Wystąpił błąd! " + ex.Message, "To jakiś straszny błąd!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            #endregion

            worker.ReportProgress(0);
        }
Пример #4
0
        public JsonResult RetrieveSPFs(int pupilID)
        {
            if (IsAuthorized())
            {
                Teacher user = VaKEGradeRepository.Instance.GetTeacher(((Teacher)Session["User"]).ID);
                Session["User"] = user;
                Pupil pupil = VaKEGradeRepository.Instance.GetPupil(pupilID);
                //Session["SelPupilID"] = pupil.ID;
                if (pupil != null)
                {
                    List<Database.SPF> spfs = pupil.SPFs.ToList();
                    GridData gData = new GridData() { page = 1 };
                    List<RowData> rows = new List<RowData>();
                    Session["pupilID"] = pupilID;

                    foreach (SPF spf in spfs)
                    {
                        rows.Add(new RowData() { id = spf.ID, cell = new string[] { spf.Subject.Name, spf.Level.ToString() } });
                    }

                    gData.records = rows.Count();
                    gData.total = rows.Count();
                    gData.rows = rows.ToArray();

                    return Json(gData, JsonRequestBehavior.AllowGet);
                }
                return null;
            }
            return null;
        }
Пример #5
0
        protected static string mergeDocuments(string sourcepath, string destinationPath, int leadID, int claimID)
        {
            List<LeadsDocument> documents = null;
            List<ClaimDocument> claimDocuments = null;
            List<string> pdfs = new List<string>();

            string mergedReportPath = null;

            documents = LeadsUploadManager.getLeadsDocumentForExportByLeadID(leadID);
            claimDocuments = ClaimDocumentManager.GetAll(claimID);

            // add original document to list
            pdfs.Insert(0, sourcepath);

            // lead documents
            if (documents != null && documents.Count > 0) {

                List<string> leadPDFs = (from x in documents
                                 where x.DocumentName.Contains(".pdf")
                                 select string.Format("{0}/LeadsDocument/{1}/{2}/{3}", appPath, x.LeadId, x.LeadDocumentId, x.DocumentName)
                              ).ToList();

                foreach(string pdf in leadPDFs) {
                    pdfs.Add(pdf);
                }
            }

            // claim documents
            if (claimDocuments != null && claimDocuments.Count > 0) {

                List<string> claimPDFs = (from x in claimDocuments
                                    where x.DocumentName.Contains(".pdf")
                                    select string.Format("{0}/ClaimDocuments/{1}/{2}/{3}", appPath, x.ClaimID, x.ClaimDocumentID, x.DocumentName)
                              ).ToList();

                foreach (string pdf in claimPDFs) {
                    pdfs.Add(pdf);
                }
            }

            // mergedReportPath = Path.GetDirectoryName(sourcepath) + "\\" + Guid.NewGuid().ToString() + ".pdf";
            // mergePDFFiles(mergedReportPath, pdfs.ToArray());

            mergePDFFiles(destinationPath, pdfs.ToArray());

            return destinationPath;
        }
Пример #6
0
        private void setPublicKeyEncryption(List<int> permissionsList)
        {
            if (DocumentSecurity.EncryptionPreferences.EncryptionType != EncryptionType.PublicKeyEncryption) return;

            if (permissionsList.Count == 0) permissionsList.Add(PdfWriter.AllowScreenReaders);
            var certs = PfxReader.ReadCertificate(DocumentSecurity.EncryptionPreferences.PublicKeyEncryption.PfxPath, DocumentSecurity.EncryptionPreferences.PublicKeyEncryption.PfxPassword);
            PdfWriter.SetEncryption(
                      certs: certs.X509PrivateKeys,
                      permissions: permissionsList.ToArray(),
                      encryptionType: PdfWriter.ENCRYPTION_AES_128);
        }
Пример #7
0
 float[] AnchoDeColumnas()
 {
     var anchos = new List<float> ();
     foreach (var columna in Columnas) {
         anchos.Add (columna.Ancho);
     }
     return anchos.ToArray ();
 }
Пример #8
0
        /// <summary>
        /// Create the PDF using the defined page size, label type and content provided
        /// Ensure you have added something first using either AddImage() or AddText()
        /// </summary>
        /// <returns></returns>
        public Stream CreatePDF()
        {
            //Get the itext page size
            Rectangle pageSize;
            switch (_label.PageSize)
            {
                case Enums.PageSize.A4:
                    pageSize = iTextSharp.text.PageSize.A4;
                    break;
                default:
                    pageSize = iTextSharp.text.PageSize.A4;
                    break;
            }

            //Create a new iText document object, define the paper size and the margins required
            var doc = new Document(pageSize,
                                   _label.PageMarginLeft,
                                   _label.PageMarginRight,
                                   _label.PageMarginTop,
                                   _label.PageMarginBottom);

            //Create a stream to write the PDF to
            var output = new MemoryStream();

            //Creates the document tells the PdfWriter to use the output stream when Document.Close() is called
            var writer = PdfWriter.GetInstance(doc, output);

            //Ensure stream isn't closed when done - we need to return it
            writer.CloseStream = false;

            //Open the document to begin adding elements
            doc.Open();

            //Create a new table with label and gap columns
            var numOfCols = _label.LabelsPerRow + (_label.LabelsPerRow - 1);
            var tbl = new PdfPTable(numOfCols);

            //Build the column width array, even numbered index columns will be gap columns
            var colWidths = new List<float>();
            for (int i = 1; i <= numOfCols; i++)
            {
                if (i % 2 > 0)
                {
                    colWidths.Add(_label.Width);
                }
                else
                {
                    //Even numbered columns are gap columns
                    colWidths.Add(_label.HorizontalGapWidth);
                }
            }

            /* The next 3 lines are the key to making SetWidthPercentage work */
            /* "size" specifies the size of the page that equates to 100% - even though the values passed are absolute not relative?! */
            /* (I will never get those 3 hours back) */
            var w = iTextSharp.text.PageSize.A4.Width - (doc.LeftMargin + doc.RightMargin);
            var h = iTextSharp.text.PageSize.A4.Height - (doc.TopMargin + doc.BottomMargin);
            var size = new iTextSharp.text.Rectangle(w, h);

            //Set the column widths (in points) - take note of the size parameter mentioned above
            tbl.SetWidthPercentage(colWidths.ToArray(), size);

            //Create the rows for the table
            for (int iRow = 0; iRow < _label.LabelRowsPerPage; iRow++)
            {

                var rowCells = new List<PdfPCell>();

                //Build the row - even numbered index columns are gaps
                for (int iCol = 1; iCol <= numOfCols; iCol++)
                {
                    if (iCol % 2 > 0)
                    {

                        // Create a new Phrase and add the image to it
                        var cellContent = new Phrase();

                        foreach (var img in _images)
                        {
                            var pdfImg = iTextSharp.text.Image.GetInstance(img);
                            cellContent.Add(new Chunk(pdfImg, 0, 0));
                        }

                        foreach (var txt in _textChunks)
                        {
                            var font = FontFactory.GetFont(txt.FontName, BaseFont.CP1250, txt.EmbedFont, txt.FontSize, txt.FontStyle);
                            cellContent.Add(new Chunk("\n" + txt.Text, font));
                        }

                        //Create a new cell specifying the content
                        var cell = new PdfPCell(cellContent);

                        //Ensure our label height is adhered to
                        cell.FixedHeight = _label.Height;

                        //Centre align the content
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;

                        cell.Border = IncludeLabelBorders ? Rectangle.BOX : Rectangle.NO_BORDER;

                        //Add to the row
                        rowCells.Add(cell);
                    }
                    else
                    {
                        //Create a empty cell to use as a gap
                        var gapCell = new PdfPCell();
                        gapCell.FixedHeight = _label.Height;
                        gapCell.Border = Rectangle.NO_BORDER;
                        //Add to the row
                        rowCells.Add(gapCell);
                    }
                }

                //Add the new row to the table
                tbl.Rows.Add(new PdfPRow(rowCells.ToArray()));

                //On all but the last row, add a gap row if needed
                if ((iRow + 1) < _label.LabelRowsPerPage && _label.VerticalGapHeight > 0)
                {
                    tbl.Rows.Add(CreateGapRow(numOfCols));
                }

            }

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

            //Close the document, writing to the stream we specified earlier
            doc.Close();

            //Set the stream back to position 0 so we can use it when it's returned
            output.Position = 0;

            return output;
        }
        public MemoryStream GeneratePdf(MemoryStream stream, List<BarcodeGroup> barcodes, int barcodeCount)
        {
            Document document = new Document(PageSize.A4, MmToPoint(7.2), MmToPoint(7.2), MmToPoint(15.1),
                MmToPoint(15.1));

            PdfWriter msWriter = PdfWriter.GetInstance(document, stream);
            document.Open();
            int numOfCols = 5;
            PdfPTable tbl = new PdfPTable(numOfCols);
            List<float> colWidths = new List<float>();
            for (var i = 1; i <= numOfCols; i++)
            {
                colWidths.Add(i % 2 > 0 ? MmToPoint(63.5) : MmToPoint(2.5));
            }
            float w = PageSize.A4.Width - (MmToPoint(7.2) + MmToPoint(7.2));
            float h = PageSize.A4.Height - (MmToPoint(15.1) + MmToPoint(15.1));
            Rectangle size = new Rectangle(w, h);
            tbl.SetWidthPercentage(colWidths.ToArray(), size);
            int index = 0;
            double div = Convert.ToDouble(barcodeCount) / 21.0;
            double dbl = Math.Ceiling(div);
            for (var i = 0; i < dbl; i++)
            {
                document.NewPage();
                tbl = new PdfPTable(numOfCols);
                tbl.SetWidthPercentage(colWidths.ToArray(), size);
                for (var iRow = 0; iRow < 7; iRow++)
                {
                    List<PdfPCell> rowCells = new List<PdfPCell>();
                    for (var iCol = 1; iCol <= numOfCols; iCol++)
                    {
                        if (iCol % 2 > 0)
                        {
                            if (index < barcodes.Count)
                            {
                                Phrase cellContent = new Phrase();
                                var img = barcodes[index].image;
                                Image pic = Image.GetInstance(img, ImageFormat.Bmp);
                                pic.ScaleAbsolute(MmToPoint(60), MmToPoint(24));
                                Image pdfImg = Image.GetInstance(pic);
                                cellContent.Add(new Chunk(pdfImg, 0, -70f));
                                cellContent.Add(new Chunk("\n"));
                                cellContent.Add(new Chunk("\n"));
                                cellContent.Add(new Chunk("\n"));
                                cellContent.Add(new Chunk("\n"));
                                cellContent.Add(new Chunk("\n"));
                                cellContent.Add(new Chunk("\n"));
                                BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
                                Font f = new Font(bf, 5.0f, Font.NORMAL, BaseColor.BLACK);
                                cellContent.Add(
                                    new Chunk(
                                        "\n" + barcodes[index].serial.ToString().PadLeft(6, '0') +
                                        "                                                              " +
                                        barcodes[index].from + " " + barcodes[index].to, f));
                                PdfPCell cell = new PdfPCell(cellContent)
                                {
                                    FixedHeight = MmToPoint(38.1),
                                    HorizontalAlignment = Element.ALIGN_CENTER,
                                    Border = false ? Rectangle.BOX : Rectangle.NO_BORDER
                                };
                                rowCells.Add(cell);
                                index++;
                            }
                            else
                            {
                                Phrase cellContent = new Phrase();
                                PdfPCell cell = new PdfPCell(cellContent)
                                {
                                    FixedHeight = MmToPoint(38.1),
                                    HorizontalAlignment = Element.ALIGN_CENTER,
                                    Border = false ? Rectangle.BOX : Rectangle.NO_BORDER
                                };
                                rowCells.Add(cell);
                                index++;
                            }
                        }
                        else
                        {
                            PdfPCell gapCell = new PdfPCell
                            {
                                FixedHeight = MmToPoint(38.1),
                                Border = Rectangle.NO_BORDER
                            };
                            rowCells.Add(gapCell);
                        }
                    }
                    tbl.Rows.Add(new PdfPRow(rowCells.ToArray()));
                }
                document.Add(tbl);
            }
            document.Close();

            return stream;
        }
Пример #10
0
 private static CountryInfo[] ReadCountryInfo()
 {
     List<CountryInfo> countryInfoList = new List<CountryInfo>();
     string country = String.Empty;
     try
     {
         CsvReader reader = new CsvReader();
         CsvLines lines = reader.Load(HttpContext.Current.Server.MapPath("~/country.info"));
         foreach (CsvLine line in lines)
         {
             country = line.Fields[0];
             CountryInfo ci = new CountryInfo(
                 line.Fields[0],
                 line.Fields[1],
                 line.Fields[2],
                 Convert.ToInt32(line.Fields[3]),
                 line.Fields[4],
                 line.Fields[5],
                 line.Fields[6],
                 line.Fields[7]);
             countryInfoList.Add(ci);
         }
     }
     catch (Exception ex)
     {
         string err = country + " " + ex.Message;
     }
     return countryInfoList.ToArray();
 }
Пример #11
0
        internal static string CreateInvoice(long userId, string status, string transid, string paymentmethod, ProductInfo productInfo, ProductPriceInfo ppi)
        {
            string companyName = string.Empty;
            string userPath = String.Empty;
            string password = HttpContext.Current.Session["access"] as string;
            UserInfo userInfo = null;
            ClientInfo clientInfo = null;
            using (Database db = new MySqlDatabase())
            {
                userPath = db.GetUserDocumentPath(userId, password);

                userPath = userPath.Replace("\\", "/");

                if (!Directory.Exists(userPath))
                    Directory.CreateDirectory(userPath);

                userInfo = db.GetUser(userId, password);
                clientInfo = db.GetClientInfo(userId);

                companyName = clientInfo.CompanyName;
            }
            // complete userPath with document name
            string filename = String.Format("INV{0}.pdf", transid);
            userPath = Path.Combine(userPath, filename);

            // Get the invoice template from the proper location
            string templatePath = Resource.InvoiceTemplate;
            string invoiceTemplate = HttpContext.Current.Server.MapPath(templatePath);
            try
            {
                InvoiceForm form = new InvoiceForm(invoiceTemplate);
                string culture = "nl-NL";
                if (HttpContext.Current.Session["culture"] != null)
                    culture = HttpContext.Current.Session["culture"] as string;
                CultureInfo cultureInfo = new CultureInfo(culture);

                List<string> fields = new List<string>();
                fields.Add(clientInfo.GetFullName());
                fields.Add(clientInfo.AddressLine1);
                if (!string.IsNullOrEmpty(clientInfo.AddressLine2))
                    fields.Add(clientInfo.AddressLine2);
                string tmpResidence = clientInfo.ZipCode + " " + clientInfo.City.ToUpper();
                if (!string.IsNullOrEmpty(tmpResidence))
                    fields.Add(tmpResidence);
                if (!string.IsNullOrEmpty(clientInfo.Country))
                    fields.Add(clientInfo.Country);
                while (fields.Count < 5)
                    fields.Add(" ");

                form.ClientAddress = fields.ToArray();
                form.InvoiceDate = DateTime.Now.ToString("d", cultureInfo);
                form.InvoiceNumber = transid;
                using (Database db = new MySqlDatabase())
                {
                    Transaction transaction = db.GetTransaction(Util.UserId, transid);
                    foreach (TransactionLine tl in transaction.TransactionLines)
                    {
                        form.InvoiceLines.Add(new PdfInvoiceLine()
                        {
                            Description = tl.Description,
                            Quantity = tl.Quantity,
                            UnitPrice = tl.Price,
                            VatRate = tl.VatPercentage
                        });
                    }
                }
                form.GenerateInvoice(userPath, companyName);
            }
            catch (Exception ex)
            {
                Logger.Instance.Write(LogLevel.Error, ex, "[CreateInvoice]");
            }

            SendInvoice(userId, userPath);

            return userPath;
        }
Пример #12
0
        private static void SendInvoice(long userId, string userPath)
        {
            UserInfo ui = null;
            ClientInfo ci = null;
            using (Database db = new MySqlDatabase())
            {
                ui = db.GetUser(userId);
                ci = db.GetClientInfo(userId);
            }

            string email = ui.Email;
            if (!String.IsNullOrEmpty(ci.EmailReceipt))
                email = ci.EmailReceipt;

            List<string> attachments = new List<string>();

            attachments.Add(userPath);
            using (TextReader rdr = new StreamReader(HttpContext.Current.Server.MapPath(Resources.Resource.tplInvoice)))
            {
                string body = rdr.ReadToEnd();

                body = body.Replace("{%EmailHeaderLogo%}", ConfigurationManager.AppSettings["EmailHeaderLogo"]);
                body = body.Replace("{%EmailmailToLink%}", ConfigurationManager.AppSettings["EmailmailToLink"]);
                body = body.Replace("{%SiteNavigationLink%}", ConfigurationManager.AppSettings["SiteNavigationLink"]);
                body = body.Replace("{%EmailFooterLogo%}", ConfigurationManager.AppSettings["EmailFooterLogo"]);
                body = body.Replace("{%EmailFBlink%}", ConfigurationManager.AppSettings["EmailFBlink"]);
                body = body.Replace("{%EmailFBLogo%}", ConfigurationManager.AppSettings["EmailFBLogo"]);
                body = body.Replace("{%EmailTwitterLink%}", ConfigurationManager.AppSettings["EmailTwitterLink"]);
                body = body.Replace("{%EmailTwitterLogo%}", ConfigurationManager.AppSettings["EmailTwitterLogo"]);
                body = body.Replace("{%EmailSoundCloudLink%}", ConfigurationManager.AppSettings["EmailSoundCloudLink"]);
                body = body.Replace("{%EmailSoundCloudLogo%}", ConfigurationManager.AppSettings["EmailSoundCloudLogo"]);

                body = body.Replace("{%receivingRelation%}", ci.GetFullName());
                SendEmail(new string[] { email }, null, Resource.SubjectYourInvoice, body,
                          attachments.ToArray(), 0);
            }
        }
Пример #13
0
 private static LanguageInfo[] ReadLanguageInfo()
 {
     List<LanguageInfo> languageInfoList = new List<LanguageInfo>();
     try
     {
         CsvReader reader = new CsvReader();
         CsvLines lines = reader.Load(HttpContext.Current.Server.MapPath("~/language.info"));
         foreach (CsvLine line in lines)
         {
             LanguageInfo li = new LanguageInfo(
                 line.Fields[0],
                 line.Fields[1],
                 line.Fields[2]);
             languageInfoList.Add(li);
         }
     }
     catch (Exception)
     {
     }
     return languageInfoList.ToArray();
 }
Пример #14
0
        /// <summary>
        /// Create the PDF using the defined page size, label type and content provided
        /// Ensure you have added something first using either AddImage() or AddText()
        /// </summary>
        /// <returns></returns>
        public Stream CreatePDF()
        {
            //Get the itext page size
            Rectangle pageSize;
            switch (_labelDefinition.PageSize)
            {
                case Enums.PageSize.A4:
                    pageSize = iTextSharp.text.PageSize.A4;
                    break;
                default:
                    pageSize = iTextSharp.text.PageSize.A4;
                    break;
            }

            //Create a new iText document object, define the paper size and the margins required
            var doc = new Document(pageSize,
                                   _labelDefinition.PageMarginLeft,
                                   _labelDefinition.PageMarginRight,
                                   _labelDefinition.PageMarginTop,
                                   _labelDefinition.PageMarginBottom);

            //Create a stream to write the PDF to
            var output = new MemoryStream();

            //Creates the document tells the PdfWriter to use the output stream when Document.Close() is called
            var writer = PdfWriter.GetInstance(doc, output);

            //Ensure stream isn't closed when done - we need to return it
            writer.CloseStream = false;

            //Open the document to begin adding elements
            doc.Open();

            //Create a new table with label and gap columns
            var numOfCols = _labelDefinition.LabelsPerRow + (_labelDefinition.LabelsPerRow - 1);
               // var tbl = new PdfPTable(numOfCols);

            //Build the column width array, even numbered index columns will be gap columns
            var colWidths = new List<float>();
            for (int i = 1; i <= numOfCols; i++)
            {
                if (i % 2 > 0)
                {
                    colWidths.Add(_labelDefinition.Width);
                }
                else
                {
                    //Even numbered columns are gap columns
                    colWidths.Add(_labelDefinition.HorizontalGapWidth);
                }
            }

            /* The next 3 lines are the key to making SetWidthPercentage work */
            /* "size" specifies the size of the page that equates to 100% - even though the values passed are absolute not relative?! */
            /* (I will never get those 3 hours back) */
            var w = iTextSharp.text.PageSize.A4.Width - (doc.LeftMargin + doc.RightMargin);
            var h = iTextSharp.text.PageSize.A4.Height - (doc.TopMargin + doc.BottomMargin);
            var size = new iTextSharp.text.Rectangle(w, h);

            // loop over the labels

            var rowNumber = 0;
            var colNumber = 0;

            PdfPTable tbl = null;
            foreach (var label in _labels)
            {
                if (rowNumber == 0)
                {
                    tbl = new PdfPTable(numOfCols);
                    tbl.SetWidthPercentage(colWidths.ToArray(), size);
                    rowNumber = 1; // so we start with row 1
                    doc.NewPage();
                }
                colNumber++; // so we start with col 1

                // add the label cell.
                var cell = FormatCell(label.GetLabelCell());

                //Add to the row
                tbl.AddCell(cell);

                //Create a empty cell to use as a gap
                if (colNumber < numOfCols)
                {
                    tbl.AddCell(CreateGapCell());
                    colNumber++; // increment for the gap row
                }

                //On all but the last row, after the last column, add a gap row if needed
                if (colNumber == numOfCols && ((rowNumber) < _labelDefinition.LabelRowsPerPage && _labelDefinition.VerticalGapHeight > 0))
                {
                    tbl.Rows.Add(CreateGapRow(numOfCols));
                }

                if (colNumber == numOfCols)
                {
                    // add the row to the table and re-initialize
                    tbl.CompleteRow();

                    rowNumber++;
                    colNumber = 0;
                }

                if (rowNumber > _labelDefinition.LabelRowsPerPage)
                {
                    //Add the table to the document
                    doc.Add(tbl);
                    rowNumber = 0;
                    colNumber = 0;
                }

            }

            if (colNumber < numOfCols)
            {
                // finish the row that was being built
                while (colNumber < numOfCols)
                {
                    if (colNumber % 2 == 1)
                    {
                        tbl.AddCell(CreateEmptyLabelCell());
                    }
                    else
                    {
                        tbl.AddCell(CreateGapCell());
                    }
                    colNumber++;
                }

                tbl.CompleteRow();
            }

            // make sure the last table gets added to the document
            if (rowNumber > 0)
            {
                //Add the table to the document
                doc.Add(tbl);
            }

            //Close the document, writing to the stream we specified earlier
            doc.Close();

            //Set the stream back to position 0 so we can use it when it's returned
            output.Position = 0;

            return output;
        }
Пример #15
0
        private PdfPRow CreateGapRow(int numOfCols)
        {
            var cells = new List<PdfPCell>();

            for (int i = 0; i < numOfCols; i++)
            {
                cells.Add(CreateGapCell());
            }
            return new PdfPRow(cells.ToArray());
        }
Пример #16
0
        /// <summary>
        /// 创建测试者信息和测试信息表格
        /// </summary>
        /// <param name="tableEle"></param>
        /// <param name="columnCount"></param>
        protected void CreateTestInfoTable(XElement tableEle, int columnCount)
        {
            string remark = tableEle.Attribute("remark").Value;
            Paragraph parTableRemark = new Paragraph(remark, fontTableRemark);
            parTableRemark.IndentationLeft = 24;
            parTableRemark.SpacingBefore = 20;
            pdfDoc.Add(parTableRemark);

            PdfPTable table = new iTextSharp.text.pdf.PdfPTable(columnCount);
            List<PdfPRow> rowList = new List<iTextSharp.text.pdf.PdfPRow>();
            foreach (XElement rowEle in tableEle.Elements())
            {
                List<PdfPCell> cellList = new List<iTextSharp.text.pdf.PdfPCell>();
                foreach (XElement cellEle in rowEle.Elements())
                {
                    string label = cellEle.Attribute("label").Value;
                    string value = cellEle.Attribute("value").Value;
                    if (value.Trim().Equals(""))
                    {
                        value = "/";
                    }

                    iTextSharp.text.pdf.PdfPCell cellLabel = new iTextSharp.text.pdf.PdfPCell(new Phrase(label, fontLabel));
                    cellLabel.FixedHeight = 24;
                    cellLabel.Padding = 4;
                    cellLabel.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    cellLabel.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;

                    PdfPCell cellContent = new iTextSharp.text.pdf.PdfPCell(new Phrase(value, fontContent));
                    cellContent.FixedHeight = 24;
                    cellContent.PaddingTop = 4;
                    cellContent.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
                    XAttribute colSpanAtt = cellEle.Attribute("colspan");
                    if (colSpanAtt != null)
                    {
                        string colspan = colSpanAtt.Value;
                        if (colspan != "")
                        {
                            cellContent.Colspan = int.Parse(colspan);
                        }
                    }
                    cellList.Add(cellLabel);
                    cellList.Add(cellContent);
                }
                PdfPRow row = new iTextSharp.text.pdf.PdfPRow(cellList.ToArray<PdfPCell>());
                rowList.Add(row);
            }
            table.Rows.AddRange(rowList);
            table.KeepTogether = true;
            table.SpacingBefore = 10;
            table.TotalWidth = 750;
            table.LockedWidth = true;
            Paragraph pTable = new Paragraph();
            pTable.Add(table);
            pdfDoc.Add(pTable);
        }
Пример #17
0
        private PdfPRow CreateGapRow(int numOfCols)
        {
            var cells = new List<PdfPCell>();

            for (int i = 0; i < numOfCols; i++)
            {
                var cell = new PdfPCell();
                cell.FixedHeight = _label.VerticalGapHeight;
                cell.Border = Rectangle.NO_BORDER;
                cells.Add(cell);
            }
            return new PdfPRow(cells.ToArray());
        }
        double[] convertStringToArray(string elements)
        {

            var stringArray = elements.Split(',').ToList();
            var doubleArray = new List<double>();

            stringArray.ForEach(c => { doubleArray.Add(!string.IsNullOrEmpty(c) ? Convert.ToDouble(c) : 0); });

            return doubleArray.ToArray();

        }
Пример #19
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            string pdfPathSql = string.Empty;
            pathstr = User.rootpath + "\\" + drawing;
            if (!Directory.Exists(pathstr))//若文件夹不存在则新建文件夹
            {
                Directory.CreateDirectory(pathstr); //新建文件夹
            }
            DataSet ds = new DataSet();
            if (indicator == 0)
            {
                pdfPathSql = @"select t.pdfpath,t.spoolname
              from sp_pdf_tab t
             where t.spoolname in
               (select s.spoolname
              from sp_spool_tab s
             where s.flag = 'Y'
               and s.drawingno = '" + drawing + "' and s.projectid = '" + pid + "' ) and t.flag = 'Y' order by t.spoolname";
                User.DataBaseConnect(pdfPathSql, ds);
            }
            if (indicator == 1)
            {
                pdfPathSql = @"select t.pdfpath
              from sp_pdf_tab t
             where t.spoolname in
               (select s.spoolname
              from sp_spool_tab s
             where s.flag = 'Y'
               and s.MODIFYDRAWINGNO = '" + drawing + "' and s.projectid = '" + pid + "' ) and t.flag = 'Y' order by t.spoolname";
                User.DataBaseConnect(pdfPathSql, ds);
            }
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                string pdfpath = ds.Tables[0].Rows[i][0].ToString();
                if (string.IsNullOrEmpty(pdfpath))
                {
                    MessageBox.Show("该小票缺少目标存储地址,请与管理员联系!");
                    continue;
                }
                if (System.IO.File.Exists(@pdfpath))
                {
                    string filenamestr = pdfpath.Substring(pdfpath.LastIndexOf("\\"));
                    if (filenamestr.Contains("_"))
                    {
                        filenamestr = filenamestr.Substring(filenamestr.IndexOf("_") + 1);
                        System.IO.File.Copy(pdfpath, pathstr + "\\" + filenamestr, true);
                        //this.backgroundWorker1.ReportProgress(progressStr, String.Format("当前值是 {0} ", progressStr));
                        this.backgroundWorker1.ReportProgress(i + 1, String.Format("当前值是 {0} ", i + 1));
                    }
                    else
                    {
                        System.IO.File.Copy(pdfpath, pathstr + "\\" + filenamestr, true);
                        //this.backgroundWorker1.ReportProgress(progressStr, String.Format("当前值是 {0} ", progressStr));
                        this.backgroundWorker1.ReportProgress(i + 1, String.Format("当前值是 {0} ", i + 1));
                    }
                }
                else
                {
                    //MessageBox.Show("目标地址未能查找到该管路小票,请与管理员联系!");
                    continue;
                }
            }
            if (indicator == 0)
            {
                string drawingstatus = DBConnection.GetDrawingStatus("SP_GETDRAWINGSTATUS", drawing, version);
                if (drawingstatus == "1")
                {
                    for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
                    {
                        string spoolstr = ds.Tables[0].Rows[j][1].ToString();
                        int page_no = j + 3;
                        DBConnection.InsertSpoolPageNo("SP_InsertSpoolPageNo", pid, drawing, spoolstr, page_no);
                    }
                }
            }
            ds.Dispose();

            pathstr = User.rootpath + "\\" + drawing;
            if (!Directory.Exists(pathstr))//若文件夹不存在则新建文件夹
            {
                MessageBox.Show("请确认小票是否已上传");
                return;
            }

            OracleDataReader dr = null;
            OracleConnection conn = new OracleConnection(DataAccess.OIDSConnStr);
            conn.Open();
            OracleCommand cmd = conn.CreateCommand();
            cmd.CommandType = CommandType.Text;
            if (indicator == 0)
            {
                cmd.CommandText = "select UPDATEDFRONTPAGE from SP_CREATEPDFDRAWING where PROJECTID = '" + pid + "' AND DRAWINGNO = '" + drawing + "' and FLAG = 'Y'";
            }
            else
            {
                cmd.CommandText = "select MODIFYDRAWINGFRONTPAGE from SP_CREATEPDFDRAWING where PROJECTID = '" + pid + "' AND DRAWINGNO = '" + drawing + "' and FLAG = 'Y'";
            }
            dr = cmd.ExecuteReader();
            byte[] File = null;
            if (dr.Read())
            {
                File = (byte[])dr[0];
            }
            string filestr = User.rootpath + "\\" + drawing + "_frontpage" + ".pdf";
            FileStream fs = new FileStream(filestr, FileMode.Create);
            BinaryWriter bw = new BinaryWriter(fs);
            bw.Write(File, 0, File.Length);
            bw.Close();
            fs.Close();
            conn.Close();

            filename = PdfFiles();

            if (System.IO.File.Exists(pathstr + "\\" + drawing + "_frontpage" + ".pdf"))
            {
                filename.Insert(0, drawing + "_frontpage" + ".pdf");
                System.IO.File.Delete(filestr);
            }
            else
            {
                System.IO.File.Move(filestr, pathstr + "\\" + drawing + "_frontpage" + ".pdf");
                filename.Insert(0, drawing + "_frontpage" + ".pdf");
            }
            if (pid == "COSL H256")
            {
                if (indicator == 0)
                {
                    if (System.IO.File.Exists(pathstr + "\\" + drawing + "CSL4附图.pdf"))
                    {
                        filename.Insert(1, drawing + "CSL4附图.pdf");
                    }
                    else
                    {
                        System.IO.File.Copy(Application.StartupPath + "\\Resources\\CSL4附图.pdf", pathstr + "\\" + drawing + "CSL4附图.pdf");
                        filename.Insert(1, drawing + "CSL4附图.pdf");
                    }
                }
            }
            else
            {
                if (System.IO.File.Exists(pathstr + "\\" + drawing + "附图1.pdf"))
                {
                    filename.Insert(1, drawing + "附图1.pdf");
                }
                else
                {
                    System.IO.File.Copy(Application.StartupPath + "\\Resources\\附图1.pdf", pathstr + "\\" + drawing + "附图1.pdf");
                    filename.Insert(1, drawing + "附图1.pdf");
                }
            }
            if (pid == "COSL H256")
            {
                if (System.IO.File.Exists(pathstr + "\\" + drawing + "CSL4附图1.pdf"))
                {
                    filename.Add(drawing + "CSL4附图1.pdf");
                }
                else
                {
                    System.IO.File.Copy(Application.StartupPath + "\\Resources\\CSL4附图1.pdf", pathstr + "\\" + drawing + "CSL4附图1.pdf");
                    filename.Add(drawing + "CSL4附图1.pdf");
                }
            }
            else
            {
                if (System.IO.File.Exists(pathstr + "\\" + drawing + "附图2.pdf"))
                {
                    filename.Add(drawing + "附图2.pdf");
                }
                else
                {
                    System.IO.File.Copy(Application.StartupPath + "\\Resources\\附图2.pdf", pathstr + "\\" + drawing + "附图2.pdf");
                    filename.Add(drawing + "附图2.pdf");
                }
            }

            int totalpages = filename.Count;
            NoCount = totalpages + 1;
            if (pid == "COSL H256" && indicator == 1)
            {
                pageNoStr = "共" + NoCount.ToString() + "页";
            }
            else
            {
                pageNoStr = "共" + totalpages.ToString() + "页";
            }

            DirectoryInfo mydir = new DirectoryInfo(pathstr);
            FileInfo[] files = mydir.GetFiles();
            if (files.Length <= 1)
            {
                MessageBox.Show("数据库中暂没有查询到相关数据");
                this.Close();
                Directory.Delete(pathstr, true);
                return;
            }

            Thread.Sleep(1000);
            StartMerge(filename.ToArray(), pathstr + "\\" + drawing + ".pdf");
        }
Пример #20
0
        void GeneratePDF(object argumentsObject)
        {
            try
            {
                GeneratePDFArguments arguments = argumentsObject as GeneratePDFArguments;

                FileStream outputStream = new FileStream(arguments.OutputFilename, FileMode.Create);

                List<string> fileNamesSortList = new List<string>(arguments.InputFilenames);
                fileNamesSortList.Sort(StringComparer.CurrentCultureIgnoreCase);
                arguments.InputFilenames = fileNamesSortList.ToArray();

                int totalNmberOfFiles = arguments.InputFilenames.Length;
                int numberOfFilesProcessed = 0;

                Document document = new Document();
                PdfWriter writer = PdfWriter.GetInstance(document, outputStream);
                writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_5);
                writer.CompressionLevel = PdfStream.BEST_COMPRESSION;

                document.Open();
                PdfContentByte content = writer.DirectContent;
                
                foreach (string file in arguments.InputFilenames)
                {
                    string dliName = String.Empty;

                    try
                    {
                        FileInfo info = new FileInfo(file);
                        string name = info.Name.Split(new char[] { '.' })[0];
                        string formatString = string.Empty;

                        if (System.IO.File.Exists(outputFolderLabel.Text + @"\formatString.txt"))
                        {
                            formatString = System.IO.File.ReadAllText(outputFolderLabel.Text + @"\formatString.txt");
                        }
                        dliName = string.Format(formatString, name);
                    }
                    catch
                    {
                    }

                    try
                    {
                        iTextSharp.text.Image image;

                        if (arguments.useOriginalImages)
                        {
                            image = iTextSharp.text.Image.GetInstance(file);
                        }
                        else
                        {
                            image = iTextSharp.text.Image.GetInstance(ConvertImage(file, arguments.imageScaleFactor, arguments.imageQuality));
                        }

                        // scale image to fit either the 8.5 or 11 inch margins
                        // default dpi is 72

                        float scaleFactor = 1f;
                        if (image.Height > 11*72f)
                        {
                            scaleFactor = 11f / (image.Height/72f);
                        }
                        if (image.Width > 8.5*72f)
                        {
                            float widthScaleFactor = 8.5f / (image.Width/72f);
                            if (widthScaleFactor > scaleFactor)
                            {
                                scaleFactor = widthScaleFactor;
                            }
                        }

                        if (scaleFactor != 1f)
                        {
                            image.ScalePercent(scaleFactor * (float)100.0);
                        }

                        document.SetPageSize(new iTextSharp.text.Rectangle(image.Width*scaleFactor, image.Height*scaleFactor));
                        document.NewPage();

                        image.SetAbsolutePosition(0, 0);
                        content.AddImage(image);

                        if (this.AddWatermarktoPDF && !string.IsNullOrEmpty(dliName))
                        {
                            BaseFont baseFont = FontFactory.GetFont(FontFactory.COURIER).GetCalculatedBaseFont(false);
                                
                            content.BeginText();
                            content.SetFontAndSize(baseFont, 35);
                            content.ShowTextAligned(PdfContentByte.ALIGN_CENTER, dliName, image.Width / 2, 35, 0);
                            content.EndText();
                        }

                        int progress = this.CalculatePercentage(++numberOfFilesProcessed, totalNmberOfFiles);
                        this.progressBarBook.Invoke(new SetInt(SetBookProgress), progress);
                        this.statusListView.Invoke(new AddStatusItemDelegate(AddStatusItem), new object[] { file, "Added" });
                    }
                    catch (ThreadAbortException)
                    {
                    }
                    catch (Exception ex)
                    {
                        this.statusListView.Invoke(new AddStatusItemDelegate(AddStatusItem), new object[] { file, ex.Message });
                    }

                }

                document.Close();

                if (OpenPDFAfterCreation)
                {
                    OpenFile(arguments.OutputFilename);
                }

                if (deleteImagesAfterPDFCreationToolStripMenuItem.Checked)
                {
                    DeleteTemporaryFiles(arguments);
                }
            }
            catch (ThreadAbortException)
            {
                return;
            }
            catch (Exception e)
            {
                this.Invoke(new ShowException(ShowError), e);
            }
            finally
            {
                this.downloadButton.Invoke(new SetButtonStatusDelegate(SetButtonStatus), new object[] { this.downloadButton, true });
                this.allWorkerThreads.Clear();
            }

        }
Пример #21
0
        // sample usage: SpeedPdfMerge.exe -SOURCE "file1.pdf" "file2.pdf" -DEST "newfile.pdf"
        static int Main(string[] arrParams)
        {
            if (arrParams == null || arrParams.Length < 1)
            {
                Console.WriteLine("STATUS:ERROR - No files. Usage: SpeedPdfMerge.exe -SOURCE file1.pdf file2.pdf -DEST output.pdf");
                return 0;
            }

            List<string> listSourceFiles = new List<string>();

            string strDestFile = "";

            string strParamKey = "";
            foreach (string strParam in arrParams)
            {
                if (strParam == "-SOURCE")
                {
                    strParamKey = "source";
                    continue;
                }

                if (strParam == "-DEST")
                {
                    strParamKey = "dest";
                    continue;
                }

                if (strParamKey == "dest")
                {
                    strDestFile = strParam;
                    continue;
                }

                if (strParamKey == "source")
                {
                    listSourceFiles.Add(strParam);
                    continue;
                }
            }

            if (String.IsNullOrEmpty(strDestFile) == true)
            {
                Console.WriteLine("STATUS:ERROR - Destination file -DEST is required");
                return 0;
            }

            if (listSourceFiles.Count < 1)
            {
                Console.WriteLine("STATUS:ERROR - Source files -SOURCE is required");
                return 0;
            }

            // You can convert it back to an array if you would like to
            string[] arrFiles = listSourceFiles.ToArray();

            // statistic
            int numFiles = 0;
            int numPages = 0;
            DateTime dateStart = DateTime.Now;

            // ----
            Document document = new Document();
            MemoryStream output = new MemoryStream();
            try
            {
                try
                {
                    // Initialize pdf writer
                    PdfWriter writer = PdfWriter.GetInstance(document, output);
                    //writer.PageEvent = new PdfPageEvents();

                    // set pdf version
                    //writer.SetPdfVersion(iTextSharp.text.pdf.PdfWriter.PDF_VERSION_1_6);

                    // Open document to write
                    document.Open();
                    PdfContentByte content = writer.DirectContent;

                    // Iterate through all pdf documents
                    foreach (string strFilename in arrFiles)
                    {

                        if (System.IO.File.Exists(strFilename) == false)
                        {
                            if (document != null)
                            {
                                document.Close();
                            }

                            Console.WriteLine("STATUS:ERROR - File not found: " + strFilename);
                            return 0;
                        }

                        numFiles++;

                        // Create pdf reader
                        // File.ReadAllBytes(strFilename)
                        PdfReader reader = new PdfReader(strFilename);
                        int numberOfPages = reader.NumberOfPages;

                        // Iterate through all pages
                        for (int currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++)
                        {
                            numPages++;

                            // Determine page size for the current page
                            Rectangle psize = reader.GetPageSizeWithRotation(currentPageIndex);

                            document.SetPageSize(psize);

                            // Create page
                            document.NewPage();
                            PdfImportedPage importedPage = writer.GetImportedPage(reader, currentPageIndex);

                            switch (psize.Rotation)
                            {
                                case 0:
                                    content.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0);
                                    break;
                                case 90:
                                    content.AddTemplate(importedPage, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(1).Height);
                                    break;
                                case 180:
                                    content.AddTemplate(importedPage, -1f, 0, 0, -1f, 0, 0);
                                    break;
                                case 270:
                                    content.AddTemplate(importedPage, 0, 1.0F, -1.0F, 0, reader.GetPageSizeWithRotation(1).Width, 0);
                                    break;
                                default:
                                    break;
                            }

                            // This block is not working correctly
                            // Determine page orientation
                            //int pageOrientation = reader.GetPageRotation(currentPageIndex);
                            //if ((pageOrientation == 90) || (pageOrientation == 270))
                            //{
                            //content.AddTemplate(importedPage, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(currentPageIndex).Height);
                            //}
                            //else
                            //{
                            //content.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0);
                            //}
                        }
                    }
                }
                catch (Exception exception)
                {
                    throw new Exception("There has an unexpected exception occured during the pdf merging process.", exception);
                }
            }
            finally
            {
                if (document != null)
                {
                    document.Close();
                }

            }

            byte[] arrContent = output.ToArray();

            // Write out PDF from memory stream.
            using (FileStream fs = File.Create(strDestFile))
            {
                fs.Write(arrContent, 0, (int)arrContent.Length);
            }

            // ...and start a viewer.
            //Process.Start(strDestFile);

            // timer
            DateTime dateStop = DateTime.Now;
            long elapsedTicks = dateStop.Ticks - dateStart.Ticks;
            TimeSpan elapsedSpan = new TimeSpan(elapsedTicks);

            // write status to console
            Console.WriteLine("STATUS:OK");
            Console.WriteLine("OUTPUT:{0}", strDestFile);
            Console.WriteLine("FILES:{0}", numFiles);
            Console.WriteLine("PAGES:{0}", numPages);
            Console.WriteLine("TIME:{0}", elapsedSpan.TotalSeconds);

            return 1;
        }
Пример #22
0
 public string[] getChartNumbersFromAppointment(DateTime searchDate){
     string[] toReturn = {};
     List<Hashtable> appointments = appointmentSearch(searchDate, null);
     List<string> allChartNumbers = new List<string>();
     for (int i = 0; i < appointments.Count; i++)
     {
         MWPAT patient = (MWPAT) appointments[i]["patient"];
         allChartNumbers.Add(patient.ChartNumber);
     }
     toReturn = allChartNumbers.ToArray();
         return toReturn;
 }
        /// <summary>
        /// Crops the rectagles.
        /// </summary>
        /// <param name="rectangles">Coordinates for cropping.</param>
        /// <returns>Path of the saved images in array.</returns>
        private string[] CropAndSave(List<System.Drawing.Rectangle> rectangles)
        {
            int fileNameCount = 0;
            string currentWorkingDirectory = string.Empty;
            List<string> imageFilenames = new List<string>();

            string targetFolderName = Path.GetFileNameWithoutExtension(this.wmfPath);
            string targetDirectoryPath = string.Format(PathResolver.MapPath(@"Diagrams\Sliced\{0}"), targetFolderName);

            if (Directory.Exists(targetDirectoryPath))
            {
                Directory.Delete(targetDirectoryPath, true);
            }

            DirectoryInfo info = Directory.CreateDirectory(targetDirectoryPath);
            currentWorkingDirectory = info.FullName;

            foreach (System.Drawing.Rectangle rect in rectangles)
            {

                Bitmap croppedImage = (Bitmap)Crop(this.wmfPath, rect.Width, rect.Height, rect.X, rect.Y);

                fileNameCount++;

                string fullNamePath = string.Format(@"{0}\{1}.WMF", currentWorkingDirectory, fileNameCount);
                croppedImage.Save(fullNamePath, ImageFormat.Wmf);
                imageFilenames.Add(fullNamePath);
                croppedImage.Dispose();
            }
            return imageFilenames.ToArray();
        }
        private void DownloadChapter(ChapterInfo chapInfo, Downloader downloader)
        {
            if (chapInfo.Pages == null) return;

            SmartThreadPool smartThreadPool = new SmartThreadPool()
            {
                MaxThreads = Settings.UseMultiThreadToDownloadChapter?Settings.Threads:1
            };

            List<IWorkItemResult> workerItems = new List<IWorkItemResult>();

           CreateChapterFolder(chapInfo);

           this.Invoke(new MethodInvoker(delegate()
           {
               lblStatus.Text = "Downloading : " + chapInfo.Name + "[" + chapInfo.Url + "]";
           }));
            int count = 0;
            long size = 0;
            
            int toProcess = chapInfo.Pages.Count;
            int index = 1;
           
            foreach (string pageUrl in chapInfo.Pages)
            {
                IWorkItemResult wir1 = smartThreadPool.QueueWorkItem(new
                        WorkItemCallback(delegate(object state)
                        {

                            try
                            {
                                string filename = downloader.DownloadPage(state.ToString(), Settings.RenamePattern.Replace("{{PAGENUM}}", (index++).ToString("D2")), chapInfo.Folder, chapInfo.Url);

                                var file = File.Open(filename, FileMode.Open);

                                lock (updateUIObj)
                                {
                                    size += file.Length;
                                    //total += file.Length;
                                    file.Close();
                                    count++;
                                    chapInfo.Size = size;
                                    chapInfo.DownloadedCount = count;
                                    RefreshData(chapInfo);
                                }
                            }
                            catch{
                            }
                            finally
                            {
                                RefreshData(chapInfo);
                            }
                            return 0;
                        }), pageUrl);
                workerItems.Add(wir1);

            }

            bool success = SmartThreadPool.WaitAll(workerItems.ToArray());

            smartThreadPool.Shutdown();
        }
Пример #25
0
        public JsonResult RetrieveAllStudents()
        {
            if (IsAuthorized()) {
                Teacher user = VaKEGradeRepository.Instance.GetTeacher(((Teacher)Session["User"]).ID);
                Session["User"] = user;
                List<Database.Pupil> pupils = user.PrimaryClasses.First().Pupils.ToList();

                GridData gData = new GridData() { page = 1 };
                List<RowData> rows = new List<RowData>();

                foreach (Database.Pupil pupil in pupils)
                {
                    rows.Add(new RowData() { id = pupil.ID, cell = new string[] { pupil.LastName, pupil.FirstName, pupil.Religion, pupil.Birthdate.ToShortDateString(), pupil.Gender } });
                }

                gData.records = rows.Count();
                gData.total = rows.Count();
                gData.rows = rows.ToArray();
                return Json(gData, JsonRequestBehavior.AllowGet);
            }
            return null;
        }
Пример #26
0
        public void ExecuteCommand()
        {
           
            try
            {
                commandType = "[General Settings] ";
                LogHelper.Logger(commandType + "Saving logs at " + _logPath, _logPath);
                LogHelper.Logger(commandType + "Saving pdfs at " + _saveLocation, _logPath);
                var avianCommand = _helperAvian.Command;
                var seasonalCommand = _helperSeasonal.Command;
                var countryCommand = _helperCountry.Command;
                //add all temporary filenames in a list;
                var filenames = new List<string>();
                filenames.Add(_saveLocation + avianFilename + _filetype);
                filenames.Add(_saveLocation + seasonalFilename + _filetype);
                filenames.Add(_saveLocation + countryFilename + _filetype);
                commandType = "[PDF Generation] ";
                //LogHelper.Logger(commandType + avianCommand, _logPath);
                //LogHelper.Logger(commandType + seasonalCommand, _logPath);
                //LogHelper.Logger(commandType + countryCommand, _logPath);
                LogHelper.Logger(commandType + "Generating pdf.", _logPath);


                //avianCommand = "dir";
                try
                {
                    CommandHelper.ExecuteCommandSync(_tabserver, avianCommand);
                    CommandHelper.ExecuteCommandSync(_tabserver, seasonalCommand);
                    CommandHelper.ExecuteCommandSync(_tabserver, countryCommand);
                    
                }
                catch (Exception e)
                {
                    
                    LogHelper.Logger(commandType + e.Message, _logPath);
                }
                
                //Create Weekly PDF
                var yearnow = DateTime.Now.Year.ToString();
                var filename = yearnow + "-" + _weekNumber + _filetype;
                var targetPdf = _saveLocation + filename;
                
                
                try
                {

                    var tries = 0;
                    var NextRun = DateTime.Now;
                    var Now = DateTime.Now;
                    var exist = false;
                    while (!exist && tries < NO_OF_TRIES)
                    {
                        if (NextRun <= Now)
                        {
                            tries++;
                         
                            if (CheckIfExist(avianFilename) && CheckIfExist(seasonalFilename) && CheckIfExist(countryFilename))
                            {
                                LogHelper.Logger(commandType + "Merging pdf.", _logPath);
                                if (PdfMerger(filenames.ToArray(), targetPdf))
                                {
                                    LogHelper.Logger(commandType + " weekly PDF generation success.", _logPath);
                                    //Delete temporary files
                                    foreach (string file in filenames)
                                    {
                                        File.Delete(file);
                                    }
                                    //Create Yearly PDF
                                    filenames.Clear();
                                    LogHelper.Logger(commandType + " summary PDF generation.", _logPath);
                                    filenames.Add(targetPdf);
                                    var yearSummary = _saveLocation + yearnow + _filetype;
                                    if (PdfMerger(filenames.ToArray(), yearSummary))
                                    {
                                        LogHelper.Logger(commandType + " PDF generation success.", _logPath);
                                    }
                                    else
                                        LogHelper.Logger(commandType + " PDF generation failed.", _logPath);

                                }
                                else
                                    LogHelper.Logger(commandType + " PDF generation failed.", _logPath);

                                exist = true;
                                break;
                            }
                            else
                            {
                                NextRun = Now.AddMinutes(_waitingTime);
                                Console.WriteLine("Waiting for report to be generated");
                            }
                        }
                        Now = DateTime.Now;
                        Thread.Sleep(new TimeSpan(0,_waitingTime,0));
                     
                        var parameters = new Dictionary<string, object>();
                        parameters.Add("@flu_year", Now.Year);
                        parameters.Add("@flu_week", _weekNumber);
                        parameters.Add("@archive_id", 0);
                        parameters.Add("@new_id", 0);
                        dataBL.SaveData(StoredProcedure.ArchiveSave, parameters);
                    }

                    if(tries == 5 && !exist)
                        LogHelper.Logger(commandType + " PDF generation failed.", _logPath);
                    
                }
                catch (Exception e)
                {
                    LogHelper.Logger(commandType + e.Message, _logPath);
                }
              

               
            }
            catch (Exception e)
            {
                LogHelper.Logger(commandType + e.Message, _logPath);
            }
           

        }
Пример #27
0
        public static response_item_type[] FillForm(pdf_stamper_request request,string mapping_root_path,string template_root_path, string output_root_path, DataTable data, string fonts_root_path, bool force_unc) {
            lock (_lock) {
                try {

                    List<Item> items_with_path = new List<Item>();
                    mappings mapping = new mappings();
                    if (File.Exists(mapping_root_path))
                        mapping = File.ReadAllText(mapping_root_path).DeserializeXml2<mappings>();

                    FileInfo mapping_path  = new FileInfo(mapping_root_path);
                    /*
                    string fox_helper_path = Path.Combine(mapping_path.DirectoryName, "Fox.txt");
                    if (!File.Exists(fox_helper_path)) {
                        StringBuilder b = new StringBuilder();
                        b.Append(@"
DIMENSION laArray[30,2]
laArray[1,1] = 'Obrazac1'
laArray[2,1] = 'Obrazac2'
laArray[3,1] = 'Obrazac3'
laArray[4,1] = 'Obrazac4'
laArray[5,1] = 'Obrazac5'
laArray[6,1] = 'Obrazac6'
laArray[7,1] = 'Obrazac7'
laArray[8,1] = 'Obrazac8'
laArray[9,1] = 'Obrazac9'
laArray[10,1] ='Obrazac10'
laArray[11,1] = 'Obrazac11'
laArray[12,1] = 'Obrazac12'
laArray[13,1] = 'Obrazac13'
laArray[14,1] = 'Obrazac14'
laArray[15,1] = 'Obrazac15'
laArray[16,1] = 'Obrazac16'
laArray[17,1] = 'Obrazac17'
laArray[18,1] = 'Obrazac18'
laArray[19,1] = 'Obrazac19'
laArray[20,1] ='Obrazac20'
laArray[21,1] = 'Obrazac21'
laArray[22,1] = 'Obrazac22'
laArray[23,1] = 'Obrazac23'
laArray[24,1] = 'Obrazac24'
laArray[25,1] = 'Obrazac25'
laArray[26,1] = 'Obrazac26'
laArray[27,1] = 'Obrazac27'
laArray[28,1] = 'Obrazac28'
laArray[29,1] = 'Obrazac29'
laArray[30,1] ='Obrazac30'
");
                        int current_index = -1;
                        foreach (var item in mapping.mapping_item) {
                            current_index = Int32.Parse(item.pdf_template.ToString().Replace("Obrazac", ""));
                            string source_document_path = item.file_path.Replace("@root", template_root_path);
                            FileInfo info = new FileInfo(source_document_path);
                            string value = string.Format("laArray[{0},2] = '{1}'", current_index, info.Name.Replace(info.Extension,String.Empty));
                            b.AppendLine(value);                            
                        }
                        File.WriteAllText(fox_helper_path,b.ToString());     
                     
                    }
                    */
                    if (data.Rows.Count == 0) {
                        Logging.Singleton.WriteDebug("There is no data in the provided data table!");

                        foreach (var template in request.pdf_template_list) {
                            mapping_item_type selected = mapping.mapping_item.Where(p => p.pdf_template == template).First();

                            string source_document_path = selected.file_path.Replace("@root", template_root_path);
                            items_with_path.Add(new Item() { Path = source_document_path, PdfTemplate = template });
                        }
                        if (request.merge_output == true) {
                            string merged_document_path = Path.Combine(output_root_path, String.Format("{0}_{1}{2}", "merged", DateTime.Now.ToFileTimeUtc().ToString(), ".pdf"));

                            PdfMerge merge = new PdfMerge();
                            foreach (var item in items_with_path) {
                                merge.AddDocument(item.Path);
                            }
                            merge.EnablePagination = false;
                            merge.Merge(merged_document_path);
                            string result = Convert.ToBase64String(File.ReadAllBytes(merged_document_path));
                            return new response_item_type[] { new response_item_type() { pdf_template = template.MergedContent, data = force_unc? string.Empty : result, unc_path=merged_document_path } };
                        }
                        else {
                            List<response_item_type> items = new List<response_item_type>();
                            foreach (var item in items_with_path) {
                                var temp = new response_item_type() { pdf_template = item.PdfTemplate, data = force_unc ? string.Empty : Convert.ToBase64String(File.ReadAllBytes(item.Path)), unc_path = item.Path };
                                items.Add(temp);
                            }
                            return items.ToArray();
                        }
                    }
                    else {

                        DataRow row = data.Rows[0];
                        string id_pog = string.Empty;
                        if (data.Columns.Contains("id_pog"))
                            id_pog = row["id_pog"].ToString();

                        if (request.debug_mode) {
                            foreach (DataColumn column in data.Columns) {
                                Logging.Singleton.WriteDebugFormat("Data column [{0}] has a value [{1}]", column.ToString(), row[column].ToString());
                            }
                        }

                        foreach (var template in request.pdf_template_list) {
                            mapping_item_type selected = mapping.mapping_item.Where(p => p.pdf_template == template).First();

                            string source_document_path = selected.file_path.Replace("@root", template_root_path);
                            FileInfo f = new FileInfo(source_document_path);

                            string destination_document_path = Path.Combine(output_root_path,
                                String.Format("{0}_{1}_{2}{3}",
                                id_pog.Replace("/","-").Trim(),
                                f.Name.Replace(f.Extension, ""),
                                DateTime.Now.ToFileTimeUtc().ToString(),
                                f.Extension)
                                );

                            items_with_path.Add(new Item() { Path = destination_document_path, PdfTemplate = template });

                            PdfReader reader = new PdfReader(source_document_path);
                            using (PdfStamper stamper = new PdfStamper(reader, new FileStream(destination_document_path, FileMode.Create))) {
                                AcroFields fields = stamper.AcroFields;


                                //Full path to the Unicode Arial file
                                //string ARIALUNI_TFF = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");

                                //Create a base font object making sure to specify IDENTITY-H
                                //BaseFont bf = BaseFont.CreateFont(ARIALUNI_TFF, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

                                //Create a specific font object
                                //Font f = new Font(bf, 12, Font.NORMAL);
                                iTextSharp.text.pdf.BaseFont baseFont  = iTextSharp.text.pdf.BaseFont.CreateFont(Path.Combine(fonts_root_path,"arial.ttf"),"Windows-1250", true);

                                fields.AddSubstitutionFont(baseFont);
                                if (request.debug_mode) {
                                    foreach (var key in fields.Fields.Keys) {
                                        Logging.Singleton.WriteDebugFormat("Pdf field [{0}]. Data type [{1}]", key, fields.GetFieldType(key));
                                    }
                                }

                                foreach (var key in fields.Fields.Keys) {

                                    var items = selected.mapping.Where(p => p.data_field == key);
                                    if (items.Count() == 1) {
                                        var item = items.First();
                                        if (item.column_name == UNKNOWN)
                                            continue;
                                        if (data.Columns.Contains(item.column_name)) {
                                            string value = row[item.column_name].ToString();

                                            if (item.field_type == data_field_type.CheckBox) {
                                                int int_value = 0;
                                                bool boolean_value = false;
                                                if(Int32.TryParse(value, out int_value))
                                                {
                                                    value = int_value == 0? "No" : "Yes";
                                                }
                                                else if (Boolean.TryParse(value, out boolean_value))
                                                {
                                                    value = boolean_value == false? "No" : "Yes";
                                                }
                                                else
                                                {
                                                    throw new NotImplementedException(string.Format("Invalid Value [{0}] was provided for Check box type field!", value));
                                                }
                                            }
                                            fields.SetField(key, value);
                                        }
                                        else {
                                            Logging.Singleton.WriteDebugFormat("Column {0} does not belong to table {1}! Check your mappings for template {2}", item.column_name, data.TableName, template);
                                        }
                                    }
                                    else if (items.Count() == 0) {

                                        var current = selected.mapping.ToList();

                                        data_field_type field_type = data_field_type.Text;
                                        if (key.Contains("Check"))
                                            field_type = data_field_type.CheckBox;
                                        else if (key.Contains("Radio"))
                                            field_type = data_field_type.RadioButton;

                                        current.Add(new mapping_type() { column_name = UNKNOWN, data_field = key, field_type = field_type });

                                        selected.mapping = current.ToArray();

                                        File.WriteAllText(mapping_root_path, mapping.SerializeXml());
                                    }
                                    else {
                                        throw new NotImplementedException();
                                    }
                                }
                                // flatten form fields and close document
                                if (request.read_only || (request.merge_output && request.pdf_template_list.Length > 1)) {
                                    Logging.Singleton.WriteDebugFormat("Form flattening requested... Read only {0}, Merge output {1}, Template list count {2}", request.read_only, request.merge_output, request.pdf_template_list.Length);
                                    stamper.FormFlattening = true;
                                }

                                stamper.Close();
                            }
                        }
                        if (items_with_path.Count() == 1) {
                            string path = items_with_path.First().Path;
                            var bytes = File.ReadAllBytes(path);
                            string result = Convert.ToBase64String(bytes);
                            Logging.Singleton.WriteDebugFormat("Response lenght is {0} bytes", bytes.Length);
                            return new response_item_type[] { new response_item_type() { pdf_template = items_with_path.First().PdfTemplate, data = force_unc ? string.Empty : result, unc_path = path } };
                            //return new response_item_type[] { new response_item_type() { pdf_template = items_with_path.First().PdfTemplate, data = Convert.ToBase64String(new byte[] {1,2,3,4,5,6,7,8,9}) } };
                        }
                        else {
                            if (request.merge_output == true) {
                                string merged_document_path = Path.Combine(output_root_path, String.Format("{0}_{1}{2}{3}", id_pog.Replace("/","-").Trim(), "merged", DateTime.Now.ToFileTimeUtc().ToString(), ".pdf"));

                                //List<string> file_names = new List<string>();
                                //foreach (var item in items_with_path) {
                                //    file_names.Add(item.Path);
                                //}
                                //var path = MergePdfForms(file_names, merged_document_path);

                                PdfMerge merge = new PdfMerge();
                                foreach (var item in items_with_path) {
                                    merge.AddDocument(item.Path);
                                }



                                merge.EnablePagination = false;
                                merge.Merge(merged_document_path);
                                //using (FileStream file = new FileStream(merged_document_path, FileMode.Create, System.IO.FileAccess.Write)) {
                                //    byte[] bytes = new byte[stream.Length];
                                //    stream.Read(bytes, 0, (int)stream.Length);
                                //    file.Write(bytes, 0, bytes.Length);
                                //    stream.Close();
                                //}

                                var bytes = File.ReadAllBytes(merged_document_path);
                                string result = Convert.ToBase64String(bytes);
                                Logging.Singleton.WriteDebugFormat("Response lenght is {0} bytes", bytes.Length);
                                return new response_item_type[] { new response_item_type() { pdf_template = template.MergedContent, data = force_unc ? string.Empty : result, unc_path = merged_document_path } };
                            }
                            else {
                                List<response_item_type> items = new List<response_item_type>();
                                foreach (var item in items_with_path) {
                                    var bytes = File.ReadAllBytes(item.Path);
                                    string result = Convert.ToBase64String(bytes);
                                    Logging.Singleton.WriteDebugFormat("Response lenght is {0} bytes", bytes.Length);
                                    var temp = new response_item_type() { pdf_template = item.PdfTemplate, data = force_unc ? string.Empty : result, unc_path = item.Path };
                                    //var temp = new response_item_type() { pdf_template = item.PdfTemplate, data = Convert.ToBase64String(new byte[] {1,2,3,4,5,6,7,8,9}) };
                                    items.Add(temp);
                                }

                                return items.ToArray();
                            }
                        }
                    }                    
                }
                catch (Exception ex) {
                    string message = Logging.CreateExceptionMessage(ex);
                    Logging.Singleton.WriteDebug(message);
                    return null;
                }
            }
        }
Пример #28
0
        public BarcodeModule()
            : base("/api")
        {
            Get["/barcode/{issuedTo}/{issuedBy}/{airport}/{validFrom}/{validTo}/{count}"] = _ =>
            {
                var count = (int)_.count;
                var issuedTo = _.issuedTo;
                var validFrom = _.validFrom;
                var validTo = _.validTo;
                var airport = _.airport;

                Program.ProcessLog.Write(_.issuedBy  +" has generated " + count + " barcodes for " + issuedTo);
                var writer = new BarcodeWriter
                {
                    Format = BarcodeFormat.PDF_417,
                    Options = { Margin = 2 }
                };
                var barcodeList = new List<BarcodeGroup>();
                for (var i = 1; i <= count; i++)
                {
                   BarcodeGroup bg = Barcode.Generate(writer, airport, validFrom, validTo);
                   barcodeList.Add(bg);
                    var dateFrom = DateTime.ParseExact(validFrom, "yyyyMMdd", CultureInfo.InvariantCulture,
                        DateTimeStyles.None);
                    var dateTo = DateTime.ParseExact(validTo, "yyyyMMdd", CultureInfo.InvariantCulture,
                        DateTimeStyles.None);
                    if (!CovertBarcode.AddNew(issuedTo, _.issuedBy, bg.barcode, dateFrom, dateTo))
                    {
                        Console.WriteLine(CovertBarcode.LastError.ToString());
                    }
                    var chis = CovertBarcode.Load(bg.barcode);
                    bg.serial = chis.SerialNumber;
                    bg.from = validFrom;
                    bg.to = validTo;
                    if (!CovertBarcodeAction.AddNew(chis.RecordID, _.issuedBy))
                    {
                        Console.WriteLine(CovertBarcodeAction.LastError.ToString());
                    }
                    else
                    {
                        var caction = CovertBarcodeAction.LoadCovertBarcode(chis.RecordID);
                        if (!CovertBarcodeActionResult.AddNew(caction.RecordID))
                        {
                            Console.WriteLine(CovertBarcodeAction.LastError.ToString());
                        }
                    }

                }
                var response =
                    new Response();
                response.Headers.Add("Content-Disposition", "attachment; filename=GeneratedBarcodes" + DateTime.Now.ToString("dd MMM yyyy HH mm")+".pdf");
                var document = new Document(PageSize.A4,
                       MmToPoint(7.2),
                       MmToPoint(7.2),
                       MmToPoint(15.1),
                       MmToPoint(15.1));
                response.Contents = stream =>
                {
                    var msWriter = PdfWriter.GetInstance(document, stream);
                    document.Open();
                    var numOfCols = 5;
                    var tbl = new PdfPTable(numOfCols);
                    var colWidths = new List<float>();
                    for (var i = 1; i <= numOfCols; i++)
                    {
                        colWidths.Add(i%2 > 0 ? MmToPoint(63.5) : MmToPoint(2.5));
                    }
                    var w = PageSize.A4.Width - ( MmToPoint(7.2) +  MmToPoint(7.2));
                    var h = PageSize.A4.Height - ( MmToPoint(15.1) +  MmToPoint(15.1));
                    var size = new Rectangle(w, h);
                    tbl.SetWidthPercentage(colWidths.ToArray(), size);
                    var index = 0;
                    var div = Convert.ToDouble(count)/21.0;
                    var dbl = Math.Ceiling(div);
                    for (var i = 0; i < dbl; i++)
                    {
                         document.NewPage();
                        tbl = new PdfPTable(numOfCols);
                        tbl.SetWidthPercentage(colWidths.ToArray(), size);
                        for (var iRow = 0; iRow < 7; iRow++)
                        {
                            var rowCells = new List<PdfPCell>();
                            for (var iCol = 1; iCol <= numOfCols; iCol++)
                            {

                                if (iCol % 2 > 0)
                                {
                                    if (index < barcodeList.Count)
                                    {
                                        var cellContent = new Phrase();
                                        var img = barcodeList[index].image;
                                        var pic = Image.GetInstance(img, ImageFormat.Bmp);
                                        pic.ScaleAbsolute(MmToPoint(60), MmToPoint(24));
                                        var pdfImg = Image.GetInstance(pic);
                                        cellContent.Add(new Chunk(pdfImg, 0, -70f));
                                        cellContent.Add(new Chunk("\n"));
                                        cellContent.Add(new Chunk("\n"));
                                        cellContent.Add(new Chunk("\n"));
                                        cellContent.Add(new Chunk("\n"));
                                        cellContent.Add(new Chunk("\n"));
                                        cellContent.Add(new Chunk("\n"));
                                        var bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
                                        var f = new Font(bf, 5.0f, Font.NORMAL, BaseColor.BLACK);
                                        cellContent.Add(
                                            new Chunk(
                                                "\n" + barcodeList[index].serial.ToString().PadLeft(6, '0') +
                                                "                                                              " +
                                                barcodeList[index].from + " " + barcodeList[index].to, f));
                                        var cell = new PdfPCell(cellContent)
                                        {
                                            FixedHeight = MmToPoint(38.1),
                                            HorizontalAlignment = Element.ALIGN_CENTER,
                                            Border = false ? Rectangle.BOX : Rectangle.NO_BORDER
                                        };
                                        rowCells.Add(cell);
                                        index++;
                                    }
                                    else
                                    {
                                        var cellContent = new Phrase();
                                        var cell = new PdfPCell(cellContent)
                                        {
                                            FixedHeight = MmToPoint(38.1),
                                            HorizontalAlignment = Element.ALIGN_CENTER,
                                            Border = false ? Rectangle.BOX : Rectangle.NO_BORDER
                                        };
                                        rowCells.Add(cell);
                                        index++;
                                    }

                                }
                                else
                                {
                                    var gapCell = new PdfPCell
                                    {
                                        FixedHeight = MmToPoint(38.1),
                                        Border = Rectangle.NO_BORDER
                                    };
                                    rowCells.Add(gapCell);
                                }
                            }
                            tbl.Rows.Add(new PdfPRow(rowCells.ToArray()));
                        }
                          document.Add(tbl);

                    }
                    document.Close();
                };
                return response;
            };

            #region test
            //Get["/barcode/test"] = _ =>
            //{
            //    var writer = new BarcodeWriter
            //    {
            //        Format = BarcodeFormat.PDF_417,
            //        Options = { Margin = 2 }
            //    };
            //    var barcodeList = new List<BarcodeTest>();

            //    var a = new BarcodeTest
            //    {
            //        barcode = writer.Write("M1YARWOOD/A MR        E2CIPT2 MANFNCLS 0765 292Y501A0501 100"),
            //        text = "T1  LS765  09:15",
            //    };

            //    barcodeList.Add(a);
            //    var b = new BarcodeTest
            //    {
            //        barcode = writer.Write("M1A Yarwood/MR        E2AIEF2 MANFNCLS 0765 292Y502A0502 100"),
            //        text = "T1  LS765  09:15"
            //    };
            //    barcodeList.Add(b);

            //    var c = new BarcodeTest
            //    {
            //        barcode = writer.Write("M1YARWOOD/A MR        E2CIED2 MANVIELS 0959 292Y501A0501 100"),
            //        text = "T1  LS959  13:15"
            //    };
            //    barcodeList.Add(c);
            //    var d = new BarcodeTest
            //    {
            //        barcode = writer.Write("M1A Yarwood/MR        E2AIEB2 MANVIELS 0959 292Y502A0502 100"),
            //        text = "T1  LS959  13:15"
            //    };
            //    barcodeList.Add(d);

            //    var e = new BarcodeTest
            //    {
            //        barcode = writer.Write("M1YARWOOD/A MR        E2CIBA2 MANACETOM2126 292Y501A0501 100"),
            //        text = "T2  TOM2126  13:10"
            //    };
            //    barcodeList.Add(e);

            //    var j = new BarcodeTest
            //    {
            //        barcode = writer.Write("M1YARWOOD/A MR        E5CFED2 MANTFSFR 4332 292Y501A0501 100"),
            //        text = "T3  FR4332  13:10"
            //    };

            //    barcodeList.Add(j);

            //    var g = new BarcodeTest
            //    {
            //        barcode = writer.Write("M1A Yarwood/MR        E3AAEB2 MANTFSFR 4332 292Y502A0502 100"),
            //        text = "T3  FR4332  13:10"
            //    };
            //    barcodeList.Add(g);

            //    var response =
            //        new Response();
            //    response.Headers.Add("Content-Disposition", "attachment; filename=GeneratedBarcodes" + DateTime.Now.ToString("dd MMM yyyy HH mm") + ".pdf");
            //    var document = new Document(PageSize.A4,
            //           MmToPoint(7.2),
            //           MmToPoint(7.2),
            //           MmToPoint(15.1),
            //           MmToPoint(15.1));
            //    response.Contents = stream =>
            //    {
            //        var msWriter = PdfWriter.GetInstance(document, stream);
            //        document.Open();
            //        var numOfCols = 5;
            //        var tbl = new PdfPTable(numOfCols);
            //        var colWidths = new List<float>();
            //        for (var i = 1; i <= numOfCols; i++)
            //        {
            //            colWidths.Add(i % 2 > 0 ? MmToPoint(63.5) : MmToPoint(2.5));
            //        }
            //        var w = PageSize.A4.Width - (MmToPoint(7.2) + MmToPoint(7.2));
            //        var h = PageSize.A4.Height - (MmToPoint(15.1) + MmToPoint(15.1));
            //        var size = new Rectangle(w, h);
            //        tbl.SetWidthPercentage(colWidths.ToArray(), size);
            //        var index = 0;
            //        var div = Convert.ToDouble(7) / 21.0;
            //        var dbl = Math.Ceiling(div);
            //        for (var i = 0; i < dbl; i++)
            //        {
            //            document.NewPage();
            //            tbl = new PdfPTable(numOfCols);
            //            tbl.SetWidthPercentage(colWidths.ToArray(), size);
            //            for (var iRow = 0; iRow < 7; iRow++)
            //            {
            //                var rowCells = new List<PdfPCell>();
            //                for (var iCol = 1; iCol <= numOfCols; iCol++)
            //                {

            //                    if (iCol % 2 > 0)
            //                    {
            //                        if (index < barcodeList.Count)
            //                        {
            //                            var cellContent = new Phrase();
            //                            var img = barcodeList[index].barcode;
            //                            var pic = Image.GetInstance(img, ImageFormat.Bmp);
            //                            pic.ScaleAbsolute(MmToPoint(60), MmToPoint(24));
            //                            var pdfImg = Image.GetInstance(pic);
            //                            cellContent.Add(new Chunk(pdfImg, 0, -70f));
            //                            cellContent.Add(new Chunk("\n"));
            //                            cellContent.Add(new Chunk("\n"));
            //                            cellContent.Add(new Chunk("\n"));
            //                            cellContent.Add(new Chunk("\n"));
            //                            cellContent.Add(new Chunk("\n"));
            //                            cellContent.Add(new Chunk("\n"));
            //                            var bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
            //                            var f = new Font(bf, 3.0f, Font.NORMAL, BaseColor.BLACK);
            //                            cellContent.Add(
            //                                new Chunk(
            //                                    "\n" + barcodeList[index].text.ToString()));
            //                            var cell = new PdfPCell(cellContent)
            //                            {
            //                                FixedHeight = MmToPoint(38.1),
            //                                HorizontalAlignment = Element.ALIGN_CENTER,
            //                                Border = false ? Rectangle.BOX : Rectangle.NO_BORDER
            //                            };
            //                            rowCells.Add(cell);
            //                            index++;
            //                        }
            //                        else
            //                        {
            //                            var cellContent = new Phrase();
            //                            var cell = new PdfPCell(cellContent)
            //                            {
            //                                FixedHeight = MmToPoint(38.1),
            //                                HorizontalAlignment = Element.ALIGN_CENTER,
            //                                Border = false ? Rectangle.BOX : Rectangle.NO_BORDER
            //                            };
            //                            rowCells.Add(cell);
            //                            index++;
            //                        }

            //                    }
            //                    else
            //                    {
            //                        var gapCell = new PdfPCell
            //                        {
            //                            FixedHeight = MmToPoint(38.1),
            //                            Border = Rectangle.NO_BORDER
            //                        };
            //                        rowCells.Add(gapCell);
            //                    }
            //                }
            //                tbl.Rows.Add(new PdfPRow(rowCells.ToArray()));
            //            }
            //            document.Add(tbl);

            //        }
            //        document.Close();
            //    };
            //    return response;
            //};
            #endregion
        }
Пример #29
0
        public HttpResponseMessage Invoice(string date, string number, string total, string emails, string clientNumber, string matter, string description)
        {
            byte[] pdf = null;
            using (var ms = new MemoryStream())
            {
                using (var doc = new Document())
                {
                    doc.SetMargins(60, 60, 40, 40);
                    PdfWriter.GetInstance(doc, ms);
                    doc.Open();

                    #region Header
                    var table = new PdfPTable(4) { WidthPercentage = 100 };
                    var colSizes = new List<float> { 120f, 130f, 140f };
                    colSizes.Add(doc.PageSize.Width - colSizes.Sum());
                    table.SetWidths(colSizes.ToArray());
                    table.AddCell(new PdfPCell
                    {
                        Image = Image.GetInstance(HttpContext.Current.Request.MapPath("~\\App_Data\\Logo.jpg")),
                        BorderColorRight = BaseColor.WHITE,
                        Rowspan = 3
                    });

                    table.AddCell(new PdfPCell(CreatePhrase("950 E. State Hwy 114\nSuite 160\nSouthlake, TX 76092"))
                    {
                        HorizontalAlignment = Element.ALIGN_CENTER,
                        VerticalAlignment = Element.ALIGN_MIDDLE,
                        Rowspan = 3
                    });

                    table.AddCell(CreateCell("Invoice Date", Element.ALIGN_RIGHT));
                    table.AddCell(CreateCell(date, Element.ALIGN_CENTER));
                    table.AddCell(CreateCell("Invoice Number", Element.ALIGN_RIGHT));
                    table.AddCell(CreateCell(number, Element.ALIGN_CENTER));
                    table.AddCell(CreateCell("Invoice Total", Element.ALIGN_RIGHT));
                    table.AddCell(CreateCell(total, Element.ALIGN_CENTER));
                    doc.Add(table);
                    #endregion

                    #region Emails
                    doc.Add(CreatePhrase(" "));
                    table = new PdfPTable(1) { WidthPercentage = 100 };
                    table.AddCell(CreateCell($"Invoice for {emails}", Element.ALIGN_CENTER));
                    doc.Add(table);
                    #endregion

                    #region Matters
                    doc.Add(CreatePhrase(" "));
                    table = new PdfPTable(4) { WidthPercentage = 100 };
                    colSizes = new List<float> { 120f, 130f, 80f };
                    colSizes.Insert(2, doc.PageSize.Width - colSizes.Sum());
                    table.SetWidths(colSizes.ToArray());

                    var columns = new List<string> { "Client", "Matter", "Description", "Amount" };                    
                    columns.ForEach(c =>
                    {
                        var cell = new PdfPCell
                        {
                            Phrase = CreatePhrase(c, headerFont),
                            HorizontalAlignment = Element.ALIGN_CENTER                                                    
                        };
                        table.AddCell(cell);
                    });

                    columns = new List<string> { clientNumber, matter, description, total };
                    columns.ForEach(c =>
                    {
                        table.AddCell(CreateCell(c, Element.ALIGN_CENTER));
                    });
                    doc.Add(table);
                    #endregion

                    #region Footer
                    doc.Add(CreatePhrase("\nIf you have any questions, please contact us at [email protected].\n"));
                    doc.Add(CreatePhrase("\nThank you for using SyncIDS.com!"));
                    #endregion
                }
                pdf = ms.ToArray();
            }  

            var response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new ByteArrayContent(pdf);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
            return response;
        }
Пример #30
0
        /// <summary>
        /// 创建参数表格
        /// </summary>
        /// <param name="tableEle"></param>
        /// <param name="columnCount"></param>
        protected void CreateCompareTable2(XElement tableEle, int columnCount)
        {
            string remark = tableEle.Attribute("remark").Value;
            Paragraph parTableRemark = new Paragraph(remark, fontTableRemark);
            parTableRemark.IndentationLeft = 24;
            parTableRemark.SpacingBefore = 20;
            pdfDoc.Add(parTableRemark);

            PdfPTable table = new iTextSharp.text.pdf.PdfPTable(new float[] { 270, 80, 80, 80, 80, 80, 80 });
            List<PdfPRow> rowList = new List<iTextSharp.text.pdf.PdfPRow>();
            for (int i = 0; i < tableEle.Elements().Count(); i++)
            {
                XElement rowEle = tableEle.Elements().ElementAt(i);
                List<PdfPCell> cellList = new List<iTextSharp.text.pdf.PdfPCell>();
                foreach (XElement cellEle in rowEle.Elements())
                {
                    string label = cellEle.Attribute("label").Value;
                    if (label.Trim().Equals(""))
                    {
                        label = "/";
                    }
                    if (label.Trim().Equals("-"))
                    {
                        label = "";
                    }

                    iTextSharp.text.pdf.PdfPCell cellLabel = null;
                    if (i < 1)
                    {
                        cellLabel = new iTextSharp.text.pdf.PdfPCell(new Phrase(label, fontLabel));
                        cellLabel.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                    }
                    else
                    {
                        cellLabel = new iTextSharp.text.pdf.PdfPCell(new Phrase(label, fontContent));
                        cellLabel.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    }
                    cellLabel.FixedHeight = 24;
                    cellLabel.Padding = 4;

                    cellLabel.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;

                    XAttribute colSpanAtt = cellEle.Attribute("colspan");
                    if (colSpanAtt != null)
                    {
                        string colspan = colSpanAtt.Value;
                        if (colspan != "")
                        {
                            cellLabel.Colspan = int.Parse(colspan);
                        }
                    }
                    //XAttribute rowSpanAtt = cellEle.Attribute("rowspan");
                    //if (rowSpanAtt != null)
                    //{
                    //    string rowspan = rowSpanAtt.Value;
                    //    if (rowspan != "")
                    //    {
                    //        cellLabel.Rowspan = int.Parse(rowspan);
                    //    }
                    //}

                    cellList.Add(cellLabel);
                }
                PdfPRow row = new iTextSharp.text.pdf.PdfPRow(cellList.ToArray<PdfPCell>());
                rowList.Add(row);
            }
            table.Rows.AddRange(rowList);
            //table.KeepTogether = true;
            table.SpacingBefore = 10;
            table.TotalWidth = 750;

            table.LockedWidth = true;
            Paragraph pTable = new Paragraph();
            pTable.Add(table);
            pdfDoc.Add(pTable);
        }