A List contains several ListItems.
Inheritance: ITextElementArray, IIndentable
        public override byte[] CreatePdf(List<PdfContentParameter> contents, string[] images, int type)
        {
            var document = new Document();
            float docHeight = document.PageSize.Height - heightOffset;
            document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
            document.SetMargins(50, 50, 10, 40);

            var output = new MemoryStream();
            var writer = PdfWriter.GetInstance(document, output);

            writer.PageEvent = new HeaderFooterHandler(type);

            document.Open();

            document.Add(contents[0].Table);

            for (int i = 0; i < images.Length; i++)
            {
                document.NewPage();
                float subtrahend = document.PageSize.Height - heightOffset;
                iTextSharp.text.Image pool = iTextSharp.text.Image.GetInstance(images[i]);
                pool.Alignment = 3;
                pool.ScaleToFit(document.PageSize.Width - (document.RightMargin * 2), subtrahend);
                //pool.ScaleAbsolute(document.PageSize.Width - (document.RightMargin * 2), subtrahend);
                document.Add(pool);
            }

            document.Close();
            return output.ToArray();
        }
示例#2
1
        /*
         * (non-Javadoc)
         *
         * @see
         * com.itextpdf.tool.xml.ITagProcessor#content(com.itextpdf.tool.xml.Tag,
         * java.util.List, com.itextpdf.text.Document, java.lang.String)
         */
        public override IList<IElement> Content(IWorkerContext ctx, Tag tag, String content) {
            List<Chunk> sanitizedChunks = HTMLUtils.Sanitize(content, false);
		    List<IElement> l = new List<IElement>(1);
            foreach (Chunk sanitized in sanitizedChunks) {
                HtmlPipelineContext myctx;
                try {
                    myctx = GetHtmlPipelineContext(ctx);
                } catch (NoCustomContextException e) {
                    throw new RuntimeWorkerException(e);
                }
                if (tag.CSS.ContainsKey(CSS.Property.TAB_INTERVAL)) {
                    TabbedChunk tabbedChunk = new TabbedChunk(sanitized.Content);
                    if (null != GetLastChild(tag) && GetLastChild(tag).CSS.ContainsKey(CSS.Property.XFA_TAB_COUNT)) {
                        tabbedChunk.TabCount = int.Parse(GetLastChild(tag).CSS[CSS.Property.XFA_TAB_COUNT]);
                    }
                    l.Add(GetCssAppliers().Apply(tabbedChunk, tag,myctx));
                } else if (null != GetLastChild(tag) && GetLastChild(tag).CSS.ContainsKey(CSS.Property.XFA_TAB_COUNT)) {
                    TabbedChunk tabbedChunk = new TabbedChunk(sanitized.Content);
                    tabbedChunk.TabCount = int.Parse(GetLastChild(tag).CSS[CSS.Property.XFA_TAB_COUNT]);
                    l.Add(GetCssAppliers().Apply(tabbedChunk, tag, myctx));
                } else {
                    l.Add(GetCssAppliers().Apply(sanitized, tag, myctx));
                }
            }
            return l;
        }
        public static List<DayReport> GetDayReports()
        {
            var query = SessionState.db.Sales.Include("Supermarket").Include("Products").GroupBy(s => s.Date);
            List<DayReport> reports = new List<DayReport>();
            foreach (var saleDate in query)
            {
                DayReport dayReport = new DayReport();
                dayReport.Sales = new List<PdfSaleReport>();
                dayReport.FormattedDate = saleDate.Key.ToShortDateString();

                double totalSum = 0;
                foreach (var sale in saleDate)
                {
                    PdfSaleReport view = new PdfSaleReport();
                    var product = SessionState.db.Products.Find(sale.ProductId);
                    view.MeasureFormatted = string.Format("{0} {1}",
                                                          sale.Quantity, product.Measure.MeasureName);
                    view.ProductName = product.ProductName;
                    view.Sum = sale.Sum;
                    view.Supermarket = SessionState.db.Supermarkets.Find(sale.SupermarketId).Name; // workaround
                    view.UnitPrice = sale.UnitPrice;
                    totalSum += sale.Sum;
                    dayReport.Sales.Add(view);
                }

                dayReport.TotalSum = totalSum;
                reports.Add(dayReport);
            }

            return reports;
        }
示例#4
0
 public static void GeneratePdfSingleDataType(string filePath, string title, List<string> content)
 {
     try
     {
         Logger.LogI("GeneratePDF -> " + filePath);
         var doc = new Document(PageSize.A3, 36, 72, 72, 144);
         using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
         {
             PdfWriter.GetInstance(doc, fs);
             doc.Open();
             doc.AddTitle(title);
             doc.AddAuthor(Environment.MachineName);
             doc.Add(
                 new Paragraph("Title : " + title + Environment.NewLine + "ServerName : " +
                               Environment.MachineName +
                               Environment.NewLine + "Author : " + Environment.UserName));
             foreach (var para in content)
             {
                 doc.NewPage();
                 doc.Add(new Paragraph(para));
             }
             doc.Close();
         }
         //ApplyWaterMark(filePath);
     }
     catch (Exception ex)
     {
         Logger.LogE(ex.Source + " -> " + ex.Message + "\n" + ex.StackTrace);
     }
 }
示例#5
0
 public BatchPrint()
 {
     InitializeComponent();
     Control.CheckForIllegalCrossThreadCalls = false;
     if (!Directory.Exists(path))//判断是否存在
     {
         Directory.CreateDirectory(path);//创建新路径
     }
     List<string> printer = GetAllPrinter();
     foreach (var item in printer)
     {
         this.cmbPrinter.Items.Add(item);
     }
     m_SynFileInfoList = new List<string>();
     m_SynFileInfoList.AddRange(new string[]
     {"Z:\\20141229\\331286\\03169ad6-ad1e-464b-a300-193e66d99d75.jpg",
     "Z:\\20141229\\331286\\B.doc",
     "Z:\\20141229\\331286\\A.pdf"
     }
     );
        // m_SynFileInfoList.AddRange(new string[]
        // {@"file://///10.10.100.52/Resource/20141229/331286/03169ad6-ad1e-464b-a300-193e66d99d75.jpg",
        // @"file://///10.10.100.52/Resource/20141229/331286/B.doc",
        // @"file://///10.10.100.52/Resource/20141229/331286/A.pdf"
        // }
        //);
 }
        /// <summary>
        /// Slices the WMF image per pool.
        /// </summary>
        /// <returns>Returns an array of string with the path of sliced images.</returns>
        public string[] Slice()
        {
            if (string.IsNullOrEmpty(this.wmfPath))
            {
                throw new InvalidOperationException(GlobalStringResource.IMAGE_PATH_NOT_SUPPLIED);
            }

            List<int> whites = new List<int>();
            int x = 0;
            int width = 0;
            int height = 0;
            using (Bitmap baseImage = (Bitmap)Bitmap.FromFile(this.wmfPath))
            {
                height = baseImage.Height;
                width = baseImage.Width;
                for (int i = 0; i < baseImage.Height; i++)
                {
                    System.Drawing.Color c = baseImage.GetPixel(x, i);
                    if (c.A == 255 && c.B == 255 && c.R == 255 && c.G == 255)
                    {
                        if (i == 0) { continue; }
                        whites.Add(i);
                    }

                }
            }
            whites.Sort();
            List<System.Drawing.Rectangle> rectangles = CreateCoordinates(whites, width, height);
            return CropAndSave(rectangles);
        }
        public override ApiResponse ApiProviderViewPost(IRequest request)
        {
            var parentNodeId = new NodeIdentifier(
                   WebUtility.UrlDecode(request.PostArgs["parent_provider"]),
                   WebUtility.UrlDecode(request.PostArgs["parent_id"]));
            var parentNode = request.UnitOfWork.Nodes.FindById(parentNodeId);
            if (parentNode == null)
                return new BadRequestApiResponse();

            if (parentNode.User.Id != request.UserId)
                return new ForbiddenApiResponse();

            var results = new List<NodeWithRenderedLink>();
            if (string.IsNullOrEmpty(request.PostArgs["text"]))
                return new BadRequestApiResponse("Text is not specified");

            var newNode = new TextNode
            {
                DateAdded = DateTime.Now,
                Text = request.PostArgs["text"],
                User = request.User
            };

            request.UnitOfWork.Text.Save(newNode);
            results.Add(new NodeWithRenderedLink(newNode,
                Utilities.CreateLinkForNode(request, parentNode, newNode)));

            return new ApiResponse(results, 201, "Nodes added");
        }
 public override List<PdfContentParameter> BuildContent(EntityDTO dto)
 {
     dto.ExtractProperties();
     this.dto = dto;
     List<PdfContentParameter> contents = new List<PdfContentParameter>();
     contents.Add(base.CreateTitlePage(this.dto));
     contents.Add(base.CreateChangeHistory(this.dto));
     contents.Add(base.CreateReviewers(this.dto));
     contents.Add(base.CreateApprovers(this.dto));
     contents.Add(CreateTitle(GlobalStringResource.Report_Introduction));
     contents.Add(CreatePurpose());
     contents.Add(CreateProcessObjective());
     contents.Add(CreateStrategy());
     contents.Add(CreateStakeHolders());
     contents.Add(CreateProcessDescription());
     contents.Add(CreateProcessRelation());
     contents.Add(CreateSubProcessRelation());
     contents.Add(CreateTitle(GlobalStringResource.Report_References));
     contents.Add(CreateFrameworkReference());
     contents.Add(CreateInternalReference());
     contents.Add(CreateTitle(GlobalStringResource.Report_Appendices));
     contents.Add(CreateAcronyms());
     contents.Add(CreateDefintionOfTerms());
     contents.Add(CreateBookmarks());
     return contents;
 }
示例#9
0
        private void Assemble()
        {
            //headers
            document.Add(makeHeader("DISCUSSION SUPPORT SYSTEM"));
            document.Add(makeHeader("Discussion report"));

            InsertLine();

            //subject
            document.Add(makeHeader(discussion.Subject, true));

            InsertLine();

            //background
            Paragraph p = new Paragraph();
            ///p.Add(TextRefsAggregater.PlainifyRichText(discussion.Background));
            p.Add(new Chunk("\n"));
            document.Add(p);

            InsertLine();

            //sources
            backgroundSources();
            document.NewPage();

            //agreement blocks
            List<ArgPoint> agreed = new List<ArgPoint>();
            List<ArgPoint> disagreed = new List<ArgPoint>();
            List<ArgPoint> unsolved = new List<ArgPoint>();
            addBlockOfAgreement("Agreed", agreed);
            addBlockOfAgreement("Disagreed", disagreed);
            addBlockOfAgreement("Unsolved", unsolved);
        }
示例#10
0
        /* (non-Javadoc)
         * @see com.itextpdf.tool.xml.ITagProcessor#endElement(com.itextpdf.tool.xml.Tag, java.util.List, com.itextpdf.text.Document)
         */
        public override IList<IElement> End(IWorkerContext ctx, Tag tag, IList<IElement> currentContent) {
            List<IElement> l = new List<IElement>(1);
            if (currentContent.Count > 0) {
                IList<IElement> currentContentToParagraph = CurrentContentToParagraph(currentContent, true, true, tag, ctx);
                foreach (IElement p in currentContentToParagraph) {
                    ((Paragraph) p).Role = (getHeaderRole(GetLevel(tag)));
                }
                ParentTreeUtil pt = new ParentTreeUtil();
                try {
                    HtmlPipelineContext context = GetHtmlPipelineContext(ctx);
                    
                    bool oldBookmark = context.AutoBookmark();
                    if (pt.GetParentTree(tag).Contains(HTML.Tag.TD))
                        context.AutoBookmark(false);

                    if (context.AutoBookmark()) {
                        Paragraph title = new Paragraph();
                        foreach (IElement w in currentContentToParagraph) {
                                title.Add(w);
                        }

                        l.Add(new WriteH(context, tag, this, title));
                    }

                    context.AutoBookmark(oldBookmark);
                } catch (NoCustomContextException e) {
                    if (LOGGER.IsLogging(Level.ERROR)) {
                        LOGGER.Error(LocaleMessages.GetInstance().GetMessage(LocaleMessages.HEADER_BM_DISABLED), e);
                    }
                }
                l.AddRange(currentContentToParagraph);
            }
            return l;
        }
示例#11
0
// ---------------------------------------------------------------------------
    /**
     * Creates the PDF.
     * @return the bytes of a PDF file.
     */
    public byte[] CreatePdf() {
      using (MemoryStream ms = new MemoryStream()) {
        using (Document document = new Document()) {
          PdfWriter writer = PdfWriter.GetInstance(document, ms);
          document.Open();
          document.Add(new Paragraph(
            "This is a list of Kubrick movies available in DVD stores."
          ));
          IEnumerable<Movie> movies = PojoFactory.GetMovies(1)
            .Concat(PojoFactory.GetMovies(4))
          ;          
          List list = new List();
          string RESOURCE = Utility.ResourcePosters;
          foreach (Movie movie in movies) {
            PdfAnnotation annot = PdfAnnotation.CreateFileAttachment(
              writer, null, 
              movie.GetMovieTitle(false), null,
              Path.Combine(RESOURCE, movie.Imdb + ".jpg"),
              string.Format("{0}.jpg", movie.Imdb)              
            );
            ListItem item = new ListItem(movie.GetMovieTitle(false));
            item.Add("\u00a0\u00a0");
            Chunk chunk = new Chunk("\u00a0\u00a0\u00a0\u00a0");
            chunk.SetAnnotation(annot);
            item.Add(chunk);
            list.Add(item);
          }
          document.Add(list);
        }
        return ms.ToArray();
      }
    }    
示例#12
0
 /// <summary>
 /// 多图片生成PDF
 /// </summary>
 /// <param name="strImagePath">图片路径数据</param>
 /// <param name="FilePath">文件保存路径</param>
 /// <returns></returns>
 public static bool CreatePDF(List<string> strImagePath, string FilePath)
 {
     //创建Document对象,默认大小为A4
     Document pdfDocument = new Document();
     //打开并创建新的PDF文件
     PdfWriter.GetInstance(pdfDocument, new FileStream(FilePath, FileMode.Create));
     //打开上下文
     try
     {
         pdfDocument.Open();
         int iHeight = 460;//高度
         int iWidth = 480;//宽度
         foreach (string s in strImagePath)
         {
             // 获取image对象
             iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(new Uri(s));
             //设置图片对其方式
             img.Alignment = iTextSharp.text.Image.MIDDLE_ALIGN;
             //设置图片的相对大小,未超过指定高宽按原图尺寸
             if (img.ScaledHeight > iHeight && img.ScaledWidth > iWidth)
             {
                 img.ScaleAbsolute(iWidth, iHeight);
             }
             //添加新的文件
             pdfDocument.Add(img);
         }
         pdfDocument.Close();
         return true;
     }
     catch
     {
         return false;
     }
 }
示例#13
0
        public List<FilesToGrab> GetForms()
        {
            List<FilesToGrab> oList = new List<FilesToGrab>();

            FilesToGrab oAdd1 = new FilesToGrab() { _iPages = 26, _sFileName = "Adopt-200.pdf", _sFileURL = "http://www.monterey.courts.ca.gov/Documents/Forms/Court%20Packets/Adopt-200.pdf" };
            oList.Add(oAdd1);

            FilesToGrab oAdd2 = new FilesToGrab() { _iPages = 6, _sFileName = "ADR.pdf", _sFileURL = "http://www.monterey.courts.ca.gov/Documents/Forms/Court%20Packets/ADR.pdf" };
            oList.Add(oAdd2);

            FilesToGrab oAdd3 = new FilesToGrab() { _iPages = 14, _sFileName = "CR-180.pdf", _sFileURL = "http://www.monterey.courts.ca.gov/Documents/Forms/Court%20Packets/CR-180.pdf" };
            oList.Add(oAdd3);

            FilesToGrab oAdd4 = new FilesToGrab() { _iPages = 68, _sFileName = "DV-100.pdf", _sFileURL = "http://www.monterey.courts.ca.gov/Documents/Forms/Court%20Packets/DV-100.pdf" };
            oList.Add(oAdd4);

            FilesToGrab oAdd5 = new FilesToGrab() { _iPages = 12, _sFileName = "FW-001.pdf", _sFileURL = "http://www.monterey.courts.ca.gov/Documents/Forms/Court%20Packets/FW-001.pdf" };
            oList.Add(oAdd5);

            FilesToGrab oAdd6 = new FilesToGrab() { _iPages = 22, _sFileName = "SC-100.pdf", _sFileURL = "http://www.monterey.courts.ca.gov/Documents/Forms/Court%20Packets/SC-100.pdf" };
            oList.Add(oAdd6);

            FilesToGrab oAdd7 = new FilesToGrab() { _iPages = 42, _sFileName = "WV-100.pdf", _sFileURL = "http://www.monterey.courts.ca.gov/Documents/Forms/Court%20Packets/WV-100.pdf" };
            //FilesToGrab oAdd8 = new FilesToGrab() { _iPages = 30, _sFileName = "UD-100.pdf", _sFileURL = "http://www.monterey.courts.ca.gov/Documents/Forms/Court%20Packets/UD-100.pdf" };
            FilesToGrab oAdd9 = new FilesToGrab() { _iPages = 48, _sFileName = "CH-150.pdf", _sFileURL = "http://www.monterey.courts.ca.gov/Documents/Forms/Court%20Packets/CH-150.pdf" };
            FilesToGrab oAdd10 = new FilesToGrab() { _iPages = 58, _sFileName = "FL-800.pdf", _sFileURL = "http://www.monterey.courts.ca.gov/Documents/Forms/Court%20Packets/FL-800.pdf" };

            oList.Add(oAdd7);
            //oList.Add(oAdd8);
            oList.Add(oAdd9);
            oList.Add(oAdd10);
            return oList;
        }
        public ActionResult SystemHistoryTextual()
        {
            // Get the user
            var user = userRepository.GetUserByUsername(User.Identity.Name);
            //var allPolls = new List<Poll>();
            var allPolls = user.ManagedPolls;
            var unique = new List<Poll>();
            foreach (Poll poll in allPolls) { if (!unique.Contains(poll)) unique.Add(poll); }
            allPolls = unique;

            IDictionary<Poll, IList<User>> creatorList = new Dictionary<Poll, IList<User>>();
            IDictionary<Poll, int> attendanceList = new Dictionary<Poll, int>();
            foreach (var poll in allPolls)
            {
                // Get poll creators
                creatorList.Add(poll, userRepository.GetCreatorsOfPoll(poll));

                // Get poll attendance
                int attendance = 0;
                foreach (var participant in poll.participants)
                {
                    if (participant.attended)
                    {
                        attendance += 1;
                    }
                }
                attendanceList.Add(poll, attendance);
            }

            var viewModel = new PollReportViewModel(allPolls, creatorList, attendanceList);
            return View(viewModel);
        }
示例#15
0
        /* (non-Javadoc)
         * @see com.itextpdf.tool.xml.ITagProcessor#endElement(com.itextpdf.tool.xml.Tag, java.util.List, com.itextpdf.text.Document)
         */
        public override IList<IElement> End(IWorkerContext ctx, Tag tag, IList<IElement> currentContent) {
            TableRowElement row = null;
            IList<IElement> l = new List<IElement>(1);
            if (Util.EqualsIgnoreCase(tag.Parent.Name, HTML.Tag.THEAD)) {
                row = new TableRowElement(currentContent, TableRowElement.Place.HEADER);
            } else if (Util.EqualsIgnoreCase(tag.Parent.Name, HTML.Tag.TBODY)) {
                row = new TableRowElement(currentContent, TableRowElement.Place.BODY);
            } else if (Util.EqualsIgnoreCase(tag.Parent.Name, HTML.Tag.TFOOT)) {
                row = new TableRowElement(currentContent, TableRowElement.Place.FOOTER);
            } else {
                row = new TableRowElement(currentContent, TableRowElement.Place.BODY);
            }

            int direction = GetRunDirection(tag);

            if (direction != PdfWriter.RUN_DIRECTION_DEFAULT) {
                foreach (HtmlCell cell in row.Content) {
                    if (cell.RunDirection == PdfWriter.RUN_DIRECTION_DEFAULT) {
                        cell.RunDirection = direction;
                    }
                }
            }

            l.Add(row);
            return l;
        }
        /// <summary>
        /// Creates the coordinates for cropping.
        /// </summary>
        /// <param name="whites">Coordinates of white pixels at the edge of the image.</param>
        /// <param name="width">Width that will be cropped.</param>
        /// <param name="height">Height that will be cropped.</param>
        /// <returns>List of Coordinates.</returns>
        private List<System.Drawing.Rectangle> CreateCoordinates(List<int> whites, int width, int height)
        {
            List<System.Drawing.Rectangle> rectangles = new List<System.Drawing.Rectangle>();
            for (int i = 0; i < whites.Count; i++)
            {
                if (i == 0)
                {
                    rectangles.Add(new System.Drawing.Rectangle(0, i, width, whites[i]));
                }
                else
                {
                    if (whites[i] == whites.Last())
                    {
                        int croppedHeight = height - whites[i];
                        rectangles.Add(new System.Drawing.Rectangle(0, whites[i], width, croppedHeight));
                        continue;
                    }

                    if (((whites[i] - 1) == whites[i - 1]) && ((whites[i] + 1) == whites[i + 1]))
                    {
                        continue;
                    }
                    else
                    {
                        int croppedHeight = whites[i + 1] - whites[i];
                        rectangles.Add(new System.Drawing.Rectangle(0, whites[i], width, croppedHeight));
                        i++;
                    }
                }
            }
            return rectangles;
        }
 public void Initialize(SchoolPeriod schoolPeriod, IEnumerable<GradingTerm> gradingTerms, IEnumerable<GradingStandard> gradingStandards, byte[] templateData)
 {
     Template = templateData;
     Period = schoolPeriod;
     Terms = gradingTerms.ToList();
     Standards = gradingStandards.ToList();
 }
示例#18
0
// ---------------------------------------------------------------------------
    /**
     * Manipulates a PDF file src with the file dest as result
     * @param src the original PDF
     */
    public virtual byte[] ManipulatePdf(byte[] src) {
      locations = PojoFactory.GetLocations();
      // Create a reader
      PdfReader reader = new PdfReader(src);
      using (MemoryStream ms = new MemoryStream()) {
        // Create a stamper
        using (PdfStamper stamper = new PdfStamper(reader, ms)) {
          // Add the annotations
          int page = 1;
          Rectangle rect;
          PdfAnnotation annotation;
          Movie movie;
          foreach (string day in PojoFactory.GetDays()) {
            foreach (Screening screening in PojoFactory.GetScreenings(day)) {
              movie = screening.movie;
              rect = GetPosition(screening);
              annotation = PdfAnnotation.CreateText(
                stamper.Writer, rect, movie.MovieTitle,
                string.Format(INFO, movie.Year, movie.Duration),
                false, "Help"
              );
              annotation.Color = WebColors.GetRGBColor(
                "#" + movie.entry.category.color
              );
              stamper.AddAnnotation(annotation, page);
            }
            page++;
          }
        }
        return ms.ToArray();
      }
    }  
示例#19
0
        /// <summary>
        /// Tries to auto resize the specified table columns.
        /// </summary>
        /// <param name="table">pdf table</param>
        public static void AutoResizeTableColumns(this PdfGrid table)
        {
            if (table == null) return;
            var currentRowWidthsList = new List<float>();
            var previousRowWidthsList = new List<float>();

            foreach (var row in table.Rows)
            {
                currentRowWidthsList.Clear();
                currentRowWidthsList.AddRange(row.GetCells().Select(cell => cell.GetCellWidth()));

                if (!previousRowWidthsList.Any())
                {
                    previousRowWidthsList = new List<float>(currentRowWidthsList);
                }
                else
                {
                    for (int i = 0; i < previousRowWidthsList.Count; i++)
                    {
                        if (previousRowWidthsList[i] < currentRowWidthsList[i])
                            previousRowWidthsList[i] = currentRowWidthsList[i];
                    }
                }
            }

            if (previousRowWidthsList.Any())
                table.SetTotalWidth(previousRowWidthsList.ToArray());
        }
示例#20
0
 public static int CheckRevocation(PdfPKCS7 pkcs7, X509Certificate signCert, X509Certificate issuerCert, DateTime date)
 {
     List<BasicOcspResp> ocsps = new List<BasicOcspResp>();
     if (pkcs7.Ocsp != null)
         ocsps.Add(pkcs7.Ocsp);
     OcspVerifier ocspVerifier = new OcspVerifier(null, ocsps);
     List<VerificationOK> verification =
         ocspVerifier.Verify(signCert, issuerCert, date);
     if (verification.Count == 0)
     {
         List<X509Crl> crls = new List<X509Crl>();
         if (pkcs7.CRLs != null)
             foreach (X509Crl crl in pkcs7.CRLs)
                 crls.Add(crl);
         CrlVerifier crlVerifier = new CrlVerifier(null, crls);
         verification.AddRange(crlVerifier.Verify(signCert, issuerCert, date));
     }
     if (verification.Count == 0)
     {
         Console.WriteLine("No se pudo verificar estado de revocación del certificado por CRL ni OCSP");
         return CER_STATUS_NOT_VERIFIED;
     }
     else
     {
         foreach (VerificationOK v in verification)
             Console.WriteLine(v);
         return 0;
     }
 }
示例#21
0
        void Dn_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            domain_finalwords = new List<UniqueWords>();

            foreach (string w in _wordsfromtxtfile)
            {
                domain_finalwords.AddRange((uniqueWordList.FindAll(x => x.Term == w)));
            }

            myProgressBarDomain.Visible = false;    //setting progressbar invisible

            FileDialog fd = new SaveFileDialog();
            fd.Title = "Save your index";
            fd.Filter = "HTML(*.html)|*.html";

            if (fd.ShowDialog() == DialogResult.OK)
            {
                fn = fd.FileName;
                var bg = new BackgroundWorker();
                bg.DoWork += bg_DoWork;
                bg.RunWorkerCompleted += bg_RunWorkerCompleted;
                bg.RunWorkerAsync();

            }
        }
示例#22
0
        public List<FilesToGrab> GetJobs()
        {
            List<FilesToGrab> oListofJobs = new List<FilesToGrab>();

            FilesToGrab oAdd5 = new FilesToGrab() {  _iPages = 22, _iJobOrder = 0, _sFileName = "CRHC4985120211100829.pdf", _sFileURL = "http://dms/Criminal/2005/CRHC4985120211100829.pdf" };
            oListofJobs.Add(oAdd5);
            oAdd5 = null;

            FilesToGrab oAdd4 = new FilesToGrab() { _iPages = 12, _iJobOrder = 0, _sFileName = "CRHC4974120211100654.pdf", _sFileURL = "http://dms/Criminal/2005/CRHC4974120211100654.pdf" };
            oListofJobs.Add(oAdd4);
            oAdd4 = null;

            FilesToGrab oAdd3 = new FilesToGrab() { _iPages = 91, _iJobOrder = 2, _sFileName = "CRHC4975120211100656.pdf", _sFileURL = "http://dms/Criminal/2005/CRHC4975120211100656.pdf" };
            oListofJobs.Add(oAdd3);
            oAdd3 = null;

            FilesToGrab oAdd1 = new FilesToGrab() { _iPages = 8, _iJobOrder = 0, _sFileName = "CRCR1355121410120242.pdf", _sFileURL = "http://dms/Criminal/1968/CR-Confidential-1968/CRCR1355121410120242.pdf" };
            oListofJobs.Add(oAdd1);
            oAdd1 = null;

            FilesToGrab oAdd2 = new FilesToGrab() { _iPages = 64, _iJobOrder = 1, _sFileName = "CRMHC12011212092243.pdf", _sFileURL = "http://dms/Criminal/1980/CRMHC12011212092243.pdf" };
            oListofJobs.Add(oAdd2);
            oAdd2 = null;

            FilesToGrab oAdd8 = new FilesToGrab() { _iPages = 33, _iJobOrder = 1, _sFileName = "CRHC5639121611091133.pdf", _sFileURL = "http://dms/Criminal/2007/CRHC5639121611091133.pdf" };
            oListofJobs.Add(oAdd8);
            oAdd8 = null;

            FilesToGrab oAdd9 = new FilesToGrab() { _iPages = 89, _iJobOrder = 1, _sFileName = "CRHC5579121511042441.pdf", _sFileURL = "http://dms/Criminal/2007/CRHC5579121511042441.pdf" };
            oListofJobs.Add(oAdd9);
            oAdd9 = null;

            return oListofJobs;
        }
 // ---------------------------------------------------------------------------    
 /**
  * Manipulates a PDF file src with the file dest as result
  * @param src the original PDF
  */
 public byte[] ManipulatePdf(byte[] src)
 {
     // Create the reader
     PdfReader reader = new PdfReader(src);
     int n = reader.NumberOfPages;
     using (MemoryStream ms = new MemoryStream())
     {
         // Create the stamper
         using (PdfStamper stamper = new PdfStamper(reader, ms))
         {
             // Make a list with all the possible actions
             actions = new List<PdfAction>();
             PdfDestination d;
             for (int i = 0; i < n; )
             {
                 d = new PdfDestination(PdfDestination.FIT);
                 actions.Add(PdfAction.GotoLocalPage(++i, d, stamper.Writer));
             }
             // Add a navigation table to every page
             PdfContentByte canvas;
             for (int i = 0; i < n; )
             {
                 canvas = stamper.GetOverContent(++i);
                 CreateNavigationTable(i, n).WriteSelectedRows(0, -1, 696, 36, canvas);
             }
         }
         return ms.ToArray();
     }
 }
        protected override void LoadContents(IDbConnection connection, ref IDataReader reader)
        {
            try
            {
                var data_inicio = (DateTime)this.mParameters[0];
                var data_fim = (DateTime)this.mParameters[1];
                reader = DBAbstractDataLayer.DataAccessRules.MovimentoRule.Current.GetAllMovimentos(data_inicio, data_fim, connection);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                throw;
            }

            var mov = default(Movimento);
            movimentos = new List<Movimento>();

            while (reader.Read())
            {
                mov = new Movimento();
                mov.IDDocumento = reader.GetInt64(0);
                mov.CodDocumento = reader.GetString(1);
                mov.TituloDocumento = reader.GetString(2);
                mov.IDMovimento = reader.GetInt64(3);
                mov.TipoMovimento = reader.GetString(4);
                mov.DataMovimento = reader.GetValue(5).ToString();
                mov.Entidade = reader.GetString(6);

                movimentos.Add(mov);
                DoAddedEntries(1);
            }
        }
        public void GetPatientInformation(string voterId)
        {
            List<Voter> voterList = new List<Voter>();
            using (var client = new WebClient())
            {
                var url = "http://nerdcastlebd.com/web_service/voterdb/index.php/voters/all/format/json";
                var jsonString = client.DownloadString(url);
                var json = new JavaScriptSerializer().Deserialize<dynamic>(jsonString);
                foreach (Dictionary<string, object> voter in json["voters"])
                {
                    Voter aVoter = new Voter();
                    aVoter.Id = voter["id"].ToString();
                    aVoter.Name = voter["name"].ToString();
                    aVoter.Address = voter["address"].ToString();
                    voterList.Add(aVoter);
                }
            }

            //string jsonStringCollection = "[{\"id\":\"5644309456813\",\"name\":\"Rimi Khanom\",\"address\":\"House no: 12. Road no: 14. Dhanmondi, Dhaka\",\"date_of_birth\":\"1979-01-15\"},{\"id\":\"9509623450915\",\"name\":\"Asif Latif\",\"address\":\"House no: 98. Road no: 14. Katalgonj, Chittagong\",\"date_of_birth\":\"1988-07-11\"},{\"id\":\"1098789543218\",\"name\":\"Rakib Hasan\",\"address\":\"Vill. Shantinagar. Thana: Katalgonj, Faridpur\",\"date_of_birth\":\"1982-04-12\"},{\"id\":\"7865409458659\",\"name\":\"Rumon Sarker\",\"address\":\"Kishorginj\",\"date_of_birth\":\"1970-12-02\"},{\"id\":\"8909854343334\",\"name\":\"Gaji Salah Uddin\",\"address\":\"Chittagong\",\"date_of_birth\":\"1965-06-16\"}]";
            //List<Voter> voterList = new JavaScriptSerializer().Deserialize<List<Voter>>(jsonStringCollection);
            foreach (var voter in voterList)
            {

                if (voter.Id.Equals(voterId))
                {
                    nameTextBox.Text = voter.Name;
                    addressTextBox.Text = voter.Address;

                }
            }
        }
示例#26
0
 public ActionResult LastLogin(int? page, string searchTerm = null)
 {
     int pageNumber = (page ?? 1);
     var auditorList = _context.Users.OrderByDescending(s => s.LastLogin).
         Where(p => searchTerm == null || p.UserName.StartsWith(searchTerm));
     var indexViewModel = new List<UserReportModel>();
     foreach (var n in auditorList)
     {
         var mygroup = _repository.Find<Group>(n.GroupId);
         //var days = n.LastLogin.Subtract(DateTime.Now).Days;
         var days = DateTime.Now.Subtract(n.LastLogin).Days;
         var model = new UserReportModel
         {
             Fullnames = n.FirstName +' '+ n.LastName,
             Username = n.UserName,
             Lastlogin = n.LastLogin,
             DaysLastLogin = days,
             Enabled = n.Enabled,
             StatusOptions = n.Status
         };
         indexViewModel.Add(model);
     }
     _getVals.LogAudit(User.Identity.GetUserName(), "Viewed", Request.UserHostName, "Viewed Last Login Report ",
         "ISA", "UserManagement");
     return View(indexViewModel.ToPagedList(pageNumber, pageSize));
 }
示例#27
0
        public Section()
        {
            PosX = -1;
            PosY = -1;
            Width = -1;
            Height = -1;
            Rows = new Queue<Row>();

            RowSpace rs = new RowSpace(0);
            Rows.Enqueue(rs);

            Margins = new List<int>();

            Label = "";
            FontSize = 10;

            //Rounded = false;
            //Radius = (Rounded) ? 20.0F : 0.0F;
            Radius = 0.0F;

            StrokeSize = 1;

            Filled = true;
            Stroked = true;

            TextBody = "";
            TextHeader = "";
        }
示例#28
0
        /**
         * @param str the string to sanitize
         * @param trim to trim or not to trim
         * @return sanitized string
         */
        private static List<Chunk> Sanitize(String str, bool preserveWhiteSpace, bool replaceNonBreakableSpaces) {
		    StringBuilder builder = new StringBuilder();
            StringBuilder whitespaceBuilder = new StringBuilder();
            List<Chunk> chunkList = new List<Chunk>();
		    bool isWhitespace = str.Length > 0 ? IsWhiteSpace(str[0]) : true;
		    foreach (char c in str) {
			    if (isWhitespace && !IsWhiteSpace(c)) {
                    if (builder.Length == 0) {
                        chunkList.Add(Chunk.CreateWhitespace(whitespaceBuilder.ToString(), preserveWhiteSpace));
                    } else {
                        builder.Append(preserveWhiteSpace ? whitespaceBuilder : new StringBuilder(" "));
                    }
                    whitespaceBuilder = new StringBuilder();
                }

                isWhitespace = IsWhiteSpace(c);
                if (isWhitespace) {
                    whitespaceBuilder.Append(c);
                } else {
                    builder.Append(c);
                }
		    }

            if (builder.Length > 0) {
                chunkList.Add(new Chunk(replaceNonBreakableSpaces ? builder.ToString().Replace(Char.ConvertFromUtf32(0x00a0), " ") : builder.ToString()));
            }

            if (whitespaceBuilder.Length > 0) {
                chunkList.Add(Chunk.CreateWhitespace(whitespaceBuilder.ToString(), preserveWhiteSpace));
            }

		    return chunkList;
	    }
示例#29
0
 static List<string> GetSortedImagesFromDirectory(string directory)
 {
     string[] filenameArray = Directory.GetFiles(directory, "*.tif", SearchOption.TopDirectoryOnly);
     List<string> filenameList = new List<string>(filenameArray);
     filenameList.Sort(StringComparer.InvariantCultureIgnoreCase);
     return filenameList;
 }
示例#30
0
        /*
         * Explodes a pdf
         * */
        public static List<string> explodePdf(String inFile, String extractor, String repair)
        {

            FileInfo f = new FileInfo(inFile);
            inFile = f.FullName;
            List<string> theParts = new List<string>();

            try
            {
                CMDUtil cmd = new CMDUtil();
                UtilManager.repairPDF(inFile, repair);
                PdfReader reader = new PdfReader(inFile);
                int n = reader.NumberOfPages;
                String str;
                cmd.explode(inFile, extractor, "1-" + n);
                for (int i = 0; i < n; i++)
                {
                    str = f.FullName.Replace(".pdf", "-x" + (i + 1) + ".pdf");
                    UtilManager.repairPDF(str, repair);
                    theParts.Add(str);
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.StackTrace);
            }
            System.Diagnostics.Debug.WriteLine("Exploded: " + theParts);
            return theParts;
        }
示例#31
0
        virtual public void ListWithOneNoListMarginAndPadding()
        {
            ListItextSharp endList = (ListItextSharp)
                                     orderedUnorderedList.End(workerContextImpl, ul, listWithOne)[0];

            Assert.AreEqual(50f + 25f - 12f, ((ListItem)endList.Items[0]).SpacingBefore, 0f);
            Assert.AreEqual(50f + 25f, ((ListItem)endList.Items[0]).SpacingAfter, 0f);
        }
示例#32
0
        virtual public void ListWithOneWithListPaddingTop()
        {
            ul.CSS["margin-top"]  = "100pt";
            ul.CSS["padding-top"] = "25pt";
            ListItextSharp endList = (ListItextSharp)orderedUnorderedList.End(workerContextImpl, ul, listWithOne)[0];

            Assert.AreEqual(100f + 25f + 50f + 25f - 12f, ((ListItem)endList.Items[0]).SpacingBefore, 0f);
        }
示例#33
0
    public void BuildSimple(List <Hold> hold, string outputPath, string year)
    {
        var doc = new Document();

        PdfWriter.GetInstance(doc, new FileStream(outputPath, FileMode.Create));
        doc.Open();
        AddHeader(year, doc, true);
        int cnt = 0;

        iTextSharp.text.Font subHeader2 = FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.NORMAL, BaseColor.Black);
        Paragraph            p          = new Paragraph();

        p.Alignment = Element.ALIGN_LEFT;
        Chunk subChunk2 = new Chunk("Børnefritidsforeningen i sydhavnen udbyder fritidsaktiviteter for alle børn i og omkring sydhavnen. Sæsonen løber typisk fra medio september til ultimo april og tilmelding til foreningens aktiviteter åbnes start september\n\nI år udbydes følgende aktiviteter:\n\n", subHeader2);

        p.Add(subChunk2);


        iTextSharp.text.List list = new iTextSharp.text.List(iTextSharp.text.List.UNORDERED, 10f);
        list.SetListSymbol("\u2022");
        list.IndentationLeft = 20f;


        foreach (var team in hold.Where(h => h.Udskudt == false))
        {
            list.Add(team.Name + " for " + team.Age + " - " + team.WeekDay + " " + team.Time + " i " + team.Place);
        }
        p.Add(list);
        doc.Add(p);

        iTextSharp.text.Image img = null;

        string imgPath = Path.Combine(Directory.GetCurrentDirectory(), "images/" + "banner.png");

        if (File.Exists(imgPath))
        {
            img = iTextSharp.text.Image.GetInstance(imgPath);
            img.ScaleToFit(500, 180f);
            img.Alignment       = iTextSharp.text.Image.TEXTWRAP | iTextSharp.text.Image.ALIGN_CENTER;
            img.IndentationLeft = 1f;
            img.SpacingAfter    = 1f;
            img.BorderWidthTop  = 1f;
            img.BorderColorTop  = iTextSharp.text.BaseColor.White;
            doc.Add(img);
        }
        else
        {
            Console.WriteLine("Kan ikke finde billedet banner.png");
        }



        addFooter(doc);

        doc.Close();
    }
示例#34
0
        private List GetContacts(int pid)
        {
            var ctl = new CodeValueModel();
            var cts = ctl.ContactTypeCodes();

            var cq = from ce in DbUtil.Db.Contactees
                     where ce.PeopleId == pid
                     orderby ce.contact.ContactDate descending
                     select new
            {
                contact = ce.contact,
                madeby  = ce.contact.contactsMakers.FirstOrDefault().person,
            };
            var list = new iTextSharp.text.List(false, 10);

            list.ListSymbol = new Chunk("\u2022", font);
            var epip = (from p in DbUtil.Db.People
                        where p.PeopleId == pid
                        select new
            {
                ep = p.EntryPoint != null ? p.EntryPoint.Description : "",
                ip = p.InterestPoint != null ? p.InterestPoint.Description : ""
            }).Single();

            if (epip.ep.HasValue() || epip.ip.HasValue())
            {
                list.Add(new ListItem(1.2f * font.Size, "Entry, Interest: {0}, {1}".Fmt(epip.ep, epip.ip), font));
            }
            const int maxcontacts = 4;

            foreach (var pc in cq.Take(maxcontacts))
            {
                var cname = "unknown";
                if (pc.madeby != null)
                {
                    cname = pc.madeby.Name;
                }
                string ctype    = cts.Single(ct => ct.Id == pc.contact.ContactTypeId).Value;
                string comments = null;
                if (pc.contact.Comments.HasValue())
                {
                    comments = pc.contact.Comments.Replace("\r\n\r\n", "\r\n");
                }
                string s = "{0:d}: {1} by {2}\n{3}".Fmt(
                    pc.contact.ContactDate, ctype, cname, comments);
                list.Add(new iTextSharp.text.ListItem(1.2f * font.Size, s, font));
            }
            if (cq.Count() > maxcontacts)
            {
                list.Add(new ListItem(1.2f * font.Size, "(showing most recent 10 of {0})".Fmt(cq.Count()), font));
            }

            return(list);
        }
示例#35
0
        private List GetContacts(Person p)
        {
            var ctl = new CodeValueModel();
            var cts = ctl.ContactTypeCodes();

            var cq = from ce in DbUtil.Db.Contactees
                     where ce.PeopleId == p.PeopleId
                     where (ce.contact.LimitToRole ?? "") == ""
                     orderby ce.contact.ContactDate descending
                     select new
            {
                ce.contact,
                madeby = ce.contact.contactsMakers.FirstOrDefault().person,
            };
            var list = new iTextSharp.text.List(false, 10);

            list.ListSymbol = new Chunk("\u2022", font);
            var ep = p.EntryPoint != null ? p.EntryPoint.Description : "";
            var ip = p.InterestPoint != null ? p.InterestPoint.Description : "";

            if (ep.HasValue() || ip.HasValue())
            {
                list.Add(new iTextSharp.text.ListItem(1.2f * font.Size, "Entry, Interest: {0}, {1}".Fmt(ep, ip), font));
            }
            foreach (var pc in cq.Take(10))
            {
                var cname = "unknown";
                if (pc.madeby != null)
                {
                    cname = pc.madeby.Name;
                }
                string ctype    = cts.ItemValue(pc.contact.ContactTypeId);
                string comments = null;
                if (pc.contact.Comments.HasValue())
                {
                    comments = pc.contact.Comments.Replace("\r\n\r\n", "\r\n");
                    var lines = Regex.Split(comments, "\r\n");
                    comments = string.Join("\r\n", lines.Take(6));
                    if (lines.Length > 6)
                    {
                        comments += "... (see rest of comment online)";
                    }
                }
                string s = "{0:d}: {1} by {2}\n{3}".Fmt(
                    pc.contact.ContactDate, ctype, cname, comments);
                list.Add(new iTextSharp.text.ListItem(1.2f * font.Size, s, font));
            }
            if (cq.Count() > 10)
            {
                list.Add(new ListItem(1.2f * font.Size, "(showing most recent 10 of {0})".Fmt(cq.Count()), font));
            }
            return(list);
        }
示例#36
0
    private void addTeamSimple1(Hold team, Document doc, iTextSharp.text.List list)
    {
        iTextSharp.text.Font text = FontFactory.GetFont("Verdana", 12, iTextSharp.text.Font.NORMAL, BaseColor.Black);

        if (string.IsNullOrWhiteSpace(team.Status))
        {
            text = FontFactory.GetFont("Verdana", 12, iTextSharp.text.Font.NORMAL, BaseColor.Red);
        }

        Paragraph p = new Paragraph();

        p.Alignment = Element.ALIGN_LEFT;

        Chunk chunk = new Chunk(team.Name + " for " + team.Age + " " + team.WeekDay + " " + team.Time + " i " + team.Place + ", Pris " + team.Price + "\n\n", text);

        list.Add(chunk);
    }
示例#37
0
    public Document GetDocumentNotice(Document document, List <string> strList)
    {
        Font      font      = GetPdfFont();
        Paragraph paragraph = new Paragraph();

        paragraph.Alignment = Element.ALIGN_CENTER;
        // paragraph.Add(new Chunk("注:", font));
        iTextSharp.text.List list = new iTextSharp.text.List(true, 10);
        //list.Numbered = true;
        foreach (var str in strList)
        {
            list.Add(new iTextSharp.text.ListItem(str, font));
        }
        paragraph.Add(list);
        document.Add(paragraph);
        return(document);
    }
示例#38
0
        public void CreateTaggedPdf8()
        {
            InitializeDocument("8");

            ColumnText columnText = new ColumnText(writer.DirectContent);

            List list = new List(true);

            try {
                list = new List(true);
                ListItem listItem =
                    new ListItem(
                        new Chunk(
                            "Quick brown fox jumped over a lazy dog. A very long line appears here because we need new line."));
                list.Add(listItem);
                Image i = Image.GetInstance(RESOURCES + "img\\fox.bmp");
                Chunk c = new Chunk(i, 0, 0);
                c.SetAccessibleAttribute(PdfName.ALT, new PdfString("Fox image"));
                listItem = new ListItem(c);
                list.Add(listItem);
                listItem = new ListItem(new Chunk("jumped over a lazy"));
                list.Add(listItem);
                i = Image.GetInstance(RESOURCES + "img\\dog.bmp");
                c = new Chunk(i, 0, 0);
                c.SetAccessibleAttribute(PdfName.ALT, new PdfString("Dog image"));
                listItem = new ListItem(c);
                list.Add(listItem);
                listItem = new ListItem(new Paragraph(text));
                list.Add(listItem);
            }
            catch (Exception) {
            }
            columnText.SetSimpleColumn(36, 36, 400, 800);
            columnText.AddElement(h1);
            columnText.AddElement(list);
            columnText.Go();
            document.NewPage();
            columnText.SetSimpleColumn(36, 36, 400, 800);
            columnText.Go();
            document.Close();

            int[] nums = new int[] { 64, 35 };
            CheckNums(nums);
            CompareResults("8");
        }
示例#39
0
        private void WriteRequiredFiles(Document doc, Boolean forCompile, List <dtoCallSubmissionFile> requiredFiles, Dictionary <SubmissionTranslations, string> translations)
        {
            doc.Add(GetPageTitle(translations[SubmissionTranslations.SubmittedFilesTitle], GetFont(ItemType.Title)));

            iTextSharp.text.List files = new iTextSharp.text.List(false, 5);
            foreach (dtoCallSubmissionFile r in requiredFiles)
            {
                if (forCompile)
                {
                    files.Add(new iTextSharp.text.ListItem(r.FileToSubmit.Name, GetFont(ItemType.Paragraph)));
                }
                else
                {
                    files.Add(new iTextSharp.text.ListItem(r.FileToSubmit.Name + '(' + (r.Submitted != null && r.Submitted != null ? translations[SubmissionTranslations.FileSubmitted] : translations[SubmissionTranslations.FileNotSubmitted]) + ')', GetFont(ItemType.Paragraph)));
                }
            }
            doc.Add(files);
        }
示例#40
0
        //使用列表
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Document document = new Document();

            PdfWriter.GetInstance(document, new FileStream("列表.pdf", FileMode.Create));

            document.Open();
            //第一个参数表示是否排序
            List list = new List(true, 20);

            list.Add(new ListItem("First line."));
            list.Add(new ListItem(
                         "The second line is longer to see what happens once the end of the line is reached.Will it start on a new line"));
            list.Add(new ListItem(20, "Third Line."));
            document.Add(list);

            Paragraph p1 = new Paragraph(new Phrase("Test paragraph"));

            document.Add(p1);

            //无序列表
            List unsortedList = new List(false, 10);

            unsortedList.Add(new ListItem("This is an item"));
            unsortedList.Add("Another item");
            document.Add(unsortedList);

            //更改列表符号
            List symbolList = new List(true);

            symbolList.ListSymbol = new Chunk("*");
            symbolList.Add(new ListItem("Test1"));
            symbolList.Add(new ListItem("Test1"));
            symbolList.Add(new ListItem("Test3"));
            document.Add(symbolList);
            document.Close();

            Title = "使用列表";
        }
示例#41
0
        public void CreateTaggedPdf5()
        {
            InitializeDocument("5");
            List list = new List(true);

            try
            {
                list = new List(true);
                ListItem listItem =
                    new ListItem(
                        new Chunk(
                            "Quick brown fox jumped over a lazy dog. A very long line appears here because we need new line."));
                list.Add(listItem);
                Image i = Image.GetInstance(RESOURCES + "img\\fox.bmp");
                Chunk c = new Chunk(i, 0, 0);
                c.SetAccessibleAttribute(PdfName.ALT, new PdfString("Fox image"));
                listItem = new ListItem(c);
                list.Add(listItem);
                listItem = new ListItem(new Chunk("jumped over a lazy"));
                listItem.ListLabel.TagLabelContent = false;
                list.Add(listItem);
                i = Image.GetInstance(RESOURCES + "img\\dog.bmp");
                c = new Chunk(i, 0, 0);
                c.SetAccessibleAttribute(PdfName.ALT, new PdfString("Dog image"));
                listItem = new ListItem(c);
                listItem.ListLabel.TagLabelContent = false;
                list.Add(listItem);
            }
            catch (Exception)
            {
            }
            document.Add(h1);
            document.Add(list);
            document.Close();

            int[] nums = new int[] { 22 };
            CheckNums(nums);
            CompareResults("5");
        }
示例#42
0
        public static void PageList(Document pdf)
        {
            var list1 = new iTextSharp.text.List();

            list1.IndentationLeft = 12;
            list1.SetListSymbol("\u2022"); //Unicode Character 'BULLET'
            list1.Numbered = true;
            list1.Add(new ListItem("Value 1"));
            list1.Add(new ListItem("Value 2"));
            list1.Add(new ListItem("Value 3"));
            pdf.Add(list1);

            pdf.Add(new Chunk("\n")); //Tip to add Break Line

            list1 = new iTextSharp.text.List();
            list1.IndentationLeft = 20;
            list1.SetListSymbol("\u2022"); //Unicode Character 'BULLET'
            list1.Numbered = false;
            list1.Add(new ListItem("Value 1"));
            list1.Add(new ListItem("Value 2"));
            list1.Add(new ListItem("Value 3"));
            pdf.Add(list1);

            pdf.Add(new Chunk("\n")); //Tip to add Break Line


            Font _font = FontFactory.GetFont(BaseFont.ZAPFDINGBATS, 8f, Font.BOLD, BaseColor.Magenta);

            list1 = new iTextSharp.text.List();
            //list1.IndentationLeft = 18;
            list1.ListSymbol = new Chunk("H ", _font);
            list1.Numbered   = false;
            list1.Add(new ListItem("Value 1"));
            list1.Add(new ListItem("Value 2"));
            list1.Add(new ListItem("Value 3"));
            pdf.Add(list1);
        }
        public ActionResult GeneratePrizeLetter()
        {
            using (var db = new HomeworkHotlineEntities())
            {
                List <CallLog> callLogs = db.CallLogs
                                          .Where(m => m.PrizeGiven == null && m.PrizeID != null && m.PrizeStudentName != null)
                                          .ToList();

                const int pageMargin   = 50;
                var       doc          = new Document(PageSize.LETTER, pageMargin, pageMargin, pageMargin - 30, pageMargin);
                var       memoryStream = new MemoryStream();
                var       pdfWriter    = PdfWriter.GetInstance(doc, memoryStream);

                doc.Open();

                BaseFont baseFont              = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
                Font     font                  = new Font(baseFont, 10f);
                Font     font_bold             = new Font(baseFont, 10f, Font.BOLD);
                Font     large_font_bold       = new Font(baseFont, 12f, Font.BOLD);
                Font     large_green_font_bold = new Font(baseFont, 12f, Font.BOLD, BaseColor.GREEN);


                int i = 0;
                foreach (CallLog call in callLogs)
                {
                    #region Letter Construction
                    School school = call.Student.School;

                    Paragraph header = new Paragraph();
                    header.Add(Chunk.NEWLINE);
                    header.Add(new Chunk(string.Format("{0}\n", DateTime.Today.ToLongDateString()), font));
                    header.Add(Chunk.NEWLINE);
                    header.Add(new Chunk(string.Format("{0}\n", call.PrizeTeacherName), font));
                    header.Add(new Chunk(string.Format("{0} -- {1}\n", school.SchoolName, school.County.CountyName), font));
                    header.Add(new Chunk(string.Format("{0}\n", school.Address1), font));
                    if (school.Address2 != null)
                    {
                        header.Add(new Chunk(string.Format("{0}\n", school.Address2), font));
                    }
                    header.Add(new Chunk(string.Format("{0}, {1} {2}\n", school.City, school.State, school.Zip), font));

                    header.Add(Chunk.NEWLINE);
                    header.Add(new Chunk(string.Format("Dear {0} and Parent or Guardian,\n", call.PrizeStudentName), font));
                    header.Add(new Chunk("Thank you for calling Homework Hotline and working so hard!  We know homework can be difficult, but the best students are those who ask questions when they don't understand and who practice the skills and concepts they are learning.  You're doing both, and the teachers at Homework Hotline are proud of your efforts.  Keep up the great work and feel free to reach out to our certified teachers whenever you need help!  We hope you enjoy your prize!", font));
                    header.Add(Chunk.NEWLINE);

                    Paragraph letter = new Paragraph();
                    letter.Add(Chunk.NEWLINE);
                    letter.Add(new Chunk("Do your friends need help too?  Tell them to call ", font_bold));
                    letter.Add((new Chunk("615-298-6636", font_bold)).SetUnderline(1, -3));
                    letter.Add(new Chunk(" or chat with us through ", font_bold));
                    letter.Add((new Chunk("homeworkhotline.info", font_bold)).SetUnderline(1, -3));
                    letter.Add(new Chunk(" for help, and ", font_bold));
                    letter.Add((new Chunk("YOU", font_bold)).SetUnderline(1, -3));
                    letter.Add(new Chunk(" will receive an additional prize!", font_bold));
                    letter.Add(Chunk.NEWLINE);
                    letter.Alignment = iTextSharp.text.Image.ALIGN_CENTER;

                    Paragraph list = new Paragraph();
                    list.Add((new Chunk("Here's how:", font_bold)).SetUnderline(1, -3));
                    iTextSharp.text.List how_list = new iTextSharp.text.List(iTextSharp.text.List.ORDERED);
                    how_list.Add(new ListItem("Tell your friends to call or chat with Homework Hotline when they have homework questions or need tutoring.", font));
                    how_list.Add(new ListItem("Have them tell us your code name and that you told them to call us for help.", font));
                    how_list.Add(new ListItem("We will send you an extra prize the next time you call for tutoring.  Just tell us your friends called!", font));
                    list.Add(how_list);

                    list.Add(Chunk.NEWLINE);
                    list.Add(new Chunk("You should be proud of the work you are doing; we definitely are!", font));
                    list.Add(Chunk.NEWLINE);

                    Paragraph closing = new Paragraph();
                    closing.Add(Chunk.NEWLINE);
                    closing.Add(new Chunk(string.Format("{0}\n", "Sincerely yours,"), font));
                    Image signature = Image.GetInstance(Server.MapPath("~/Images/Signature.png"));
                    signature.ScalePercent(45);
                    closing.Add(signature);
                    closing.Add(new Chunk(string.Format("{0}\n", "Rebekah Vance"), font));
                    closing.Add(new Chunk(string.Format("{0}\n", "Executive Director"), font));
                    closing.Add(new Chunk(string.Format("{0}\n", "Homework Hotline"), font));
                    closing.Add(Chunk.NEWLINE);

                    Paragraph ps = new Paragraph();
                    ps.Add(new Chunk("P.S. If you enjoyed our services, we'd appreciate your review! Our teachers want to know how they're doing. To review us, Google: Homework Hotline. Then, on your phone you'll scroll and hit \"more about Homework Hotline.\"  You should see the stars to rate us.  Thank you!", font));
                    ps.Add(Chunk.NEWLINE);

                    Paragraph footer = new Paragraph();
                    footer.Add(Chunk.NEWLINE);
                    footer.Add(new Chunk("Homework Hotline is Tennessee’s source for FREE ", large_font_bold));
                    footer.Add(new Chunk("homework help", large_green_font_bold).SetUnderline(1, -3));
                    footer.Add(new Chunk(" and ", large_font_bold));
                    footer.Add(new Chunk("tutoring", large_green_font_bold).SetUnderline(1, -3));
                    footer.Add(new Chunk(" over the phone and online!", large_font_bold));
                    footer.Add(Chunk.NEWLINE);
                    footer.Alignment = iTextSharp.text.Image.ALIGN_CENTER;

                    PdfPTable codename_table = new PdfPTable(1);
                    codename_table.WidthPercentage    = 100f;
                    codename_table.DefaultCell.Border = 0;
                    PdfPCell cell = new PdfPCell();
                    cell.Border = 0;
                    Paragraph contents = new Paragraph();
                    contents.Alignment = Element.ALIGN_RIGHT;
                    contents.Add(new Chunk(call.Student.CodeName, font));
                    cell.AddElement(contents);
                    codename_table.AddCell(cell);

                    Image header_logo = Image.GetInstance(Server.MapPath("~/Images/hhLogo.png"));
                    header_logo.ScaleToFit(260f, 280f);
                    header_logo.Alignment = iTextSharp.text.Image.ALIGN_CENTER;

                    if (i > 0)
                    {
                        doc.NewPage();
                    }
                    doc.Add(header_logo);
                    doc.Add(header);
                    doc.Add(letter);
                    doc.Add(list);
                    doc.Add(closing);
                    doc.Add(ps);
                    doc.Add(footer);
                    doc.Add(codename_table);

                    call.PrizeGiven = DateTime.Now;

                    i++;
                    #endregion
                }

                db.SaveChanges();

                pdfWriter.CloseStream = false;
                doc.Close();
                memoryStream.Position = 0;
                string handle = Guid.NewGuid().ToString();
                TempData[handle] = memoryStream.ToArray();
                string filename = "PrizeLetters" + (DateTime.Now.ToShortDateString()).Replace("/", "") + ".pdf";
                return(new JsonResult()
                {
                    Data = new { FileGuid = handle, FileName = filename }
                });

                ////          Dictionary<string, string> _replacePatterns = new Dictionary<string, string>()
                ////            {
                ////// TODO: format CallDate

                ////      { "DATE", date },
                ////      { "TEACHER_NAME", clm.PrizeTeacherName },
                ////      { "SCHOOL_NAME", schoolModel.SchoolName },
                ////      { "COUNTY", schoolModel.CountyName },
                ////      { "ADDRESS", schoolModel.Address1 + " " + schoolModel.Address2 },
                ////      { "CITY", schoolModel.City },
                ////      { "STATE", schoolModel.State },
                ////      { "ZIP", schoolModel.Zip },
                ////      { "STUDENT_NAME", clm.PrizeStudentName },
                ////      { "CODE_NAME", student.CodeName },
                ////            };

                //string fileName = "PrizeLetter_Template.docx";
                //string fileDownloadName = "PrizeLetter_Template.docx";
                //var filepath = System.IO.Path.Combine(Server.MapPath("/Documents/"), fileName);
                //var fileDownloadPath = System.IO.Path.Combine(Server.MapPath("/Documents/"), fileName);
                ////     string fileDownloadName = String.Format("PrizeLetter_{0}.docx", student.CodeName);
                ////     var fileDownloadPath = System.IO.Path.Combine(Server.MapPath("/Documents/"), fileDownloadName);

                //// replace text in docx with above values
                //using (DocX document = DocX.Load(filepath))
                //{
                //    // Check if all the replace patterns are used in the loaded document.
                //    if (document.FindUniqueByPattern(@"<[\w \=]{4,}>", RegexOptions.IgnoreCase).Count == _replacePatterns.Count)
                //    {
                //        // Do the replacement
                //        for (int i = 0; i < _replacePatterns.Count; ++i)
                //        {
                //            document.ReplaceText("<(.*?)>", ReplaceFunc, false, RegexOptions.IgnoreCase, null, new Formatting());
                //        }

                //        // TODO: not saving....
                //        // Save this document to disk.
                //        document.SaveAs(fileDownloadPath);
                //        //     Console.WriteLine("\tCreated: ReplacedText.docx\n");
                //    }
                //}
                //// end replace text

                ////return File(filepath, MimeMapping.GetMimeMapping(filepath), fileDownloadName);
                //return File(fileDownloadPath, MimeMapping.GetMimeMapping(fileDownloadPath), fileDownloadName);
            }
        }
示例#44
0
        private void Btn_Listing_Click(object sender, EventArgs e)//Liste de la section en PDF
        {
            if (DGV_ActiviteSection.Rows.Count > 1)
            {
                //Liste des membres
                List <C_T_Membre>   lTmp_M = new G_T_Membre(S_Ch_Conn).Lire("ID");
                List <C_T_Activite> lTmp_A = new G_T_Activite(S_Ch_Conn).Lire("ID");
                List <C_T_Section>  lTmp_S = new G_T_Section(S_Ch_Conn).Lire("ID");
                DateTime            datetime = Convert.ToDateTime(DGV_ActiviteSection.SelectedRows[0].Cells["Date"].Value.ToString());
                string Section = "", Nom = DGV_ActiviteSection.SelectedRows[0].Cells["Nom"].Value.ToString().Trim();
                string Date   = datetime.ToShortDateString();
                int?   i      = 0;

                foreach (var Tmp in lTmp_A)
                {
                    if (int.Parse(DGV_Section.SelectedRows[0].Cells["ID"].Value.ToString()) == Tmp.Id_Activite)
                    {
                        i = Tmp.A_Section;
                    }
                }
                foreach (var Tmp in lTmp_S)
                {
                    if (i == Tmp.Id_Section)
                    {
                        Section = Tmp.S_Nom.Trim();
                    }
                }

                //Création du PDF
                var    PDF    = new Document();
                string Path   = @"C:\Users\juju_\source\repos\Projet_DB_Scout_JC";
                string Chemin = Path + "\\Liste_" + Section.Trim() + "_" + Nom + "_" + Date + ".pdf";
                PdfWriter.GetInstance(PDF, new FileStream(Chemin, FileMode.Create));
                PDF.Open();

                //Ecriture du titre + ajout logo
                iTextSharp.text.Image Pic1 = iTextSharp.text.Image.GetInstance(@"C:\Users\juju_\source\repos\Projet_DB_Scout_JC\packages\Scouts.png");
                Pic1.Alignment = iTextSharp.text.Image.TEXTWRAP | iTextSharp.text.Image.ALIGN_RIGHT;
                Pic1.ScaleAbsolute(50f, 50f);
                PDF.Add(Pic1);
                string    s1     = "Liste des présences à l'activité " + DGV_ActiviteSection.SelectedRows[0].Cells["Nom"].Value.ToString().Trim();
                Paragraph Texte1 = new Paragraph(s1)
                {
                    Alignment = Element.ALIGN_CENTER
                };
                PDF.Add(Texte1);

                //Récupération des noms des membres de la section + ajout au PDF
                iTextSharp.text.List Liste = new iTextSharp.text.List(iTextSharp.text.List.UNORDERED);
                string s = "";
                foreach (var Tmp in lTmp_M)
                {
                    if (Tmp.M_Section == Section)
                    {
                        string Membre = "0" + "      " + Tmp.M_Nom.Trim() + " " + Tmp.M_Prenom.Trim();
                        Liste.Add(Membre);
                    }
                }
                PDF.Add(Liste);
                PDF.Close();
                MessageBox.Show("Le fichier PDF a été généré dans le dossier " + Path);
            }
        }
示例#45
0
        public bool Convert(Inspection inspection)
        {
            var sf = new SaveFileDialog
            {
                FileName = $"{inspection.Checklist.Name}.pdf",
                Filter   = @"Pdf Files|*.pdf"
            };

            if (sf.ShowDialog() != DialogResult.OK)
            {
                return(false);
            }

            // Now here's our save folder
            var savePath = sf.FileName + (sf.FileName.EndsWith(".pdf") ? "" : ".pdf");

            const it.Font.FontFamily font = it.Font.FontFamily.TIMES_ROMAN;

            var header    = new it.Font(font, 22f);
            var title     = new it.Font(font, 18f);
            var subtitle  = new it.Font(font, 13f);
            var paragraph = new it.Font(font, 9f);

            var templateDocument = new it.Document(it.PageSize.A4);

            var pdfWriter = PdfWriter.GetInstance(templateDocument, new FileStream(savePath, FileMode.Create));

            pdfWriter.PageEvent = new ITextEvents();

            templateDocument.Open();

            var name     = new it.Paragraph(inspection.Checklist.Name, header);
            var datetime = new it.Paragraph(inspection.Checklist.DateTimeCreated.ToString(), subtitle);

            name.Alignment     = it.Element.ALIGN_CENTER;
            datetime.Alignment = it.Element.ALIGN_CENTER;

            templateDocument.Add(name);
            templateDocument.Add(datetime);
            templateDocument.Add(new it.Paragraph("Vragen:", header));
            //Load questions and convert to pdf format.

            //Assemble list of questions
            var questions = inspection.Answers.Select(a => a.Question).Distinct();

            foreach (var question in questions)
            {
                templateDocument.Add(new it.Paragraph(question.Text, title));
                templateDocument.Add(new it.Paragraph(question.QuestionType.Name, subtitle));

                if (!IncludeAnswers)
                {
                    continue;
                }

                //Place answers in an unordered(bullet point) list below the question title
                var list = new it.List(it.List.UNORDERED);

                list.SetListSymbol("\u2022"); //Set type to bulletpoint
                list.IndentationLeft = 30f;   //Neatly indent it

                foreach (var answer in question.Answers)
                {
                    list.Add(new it.ListItem($"{question.AnswerPrefix} {answer.Text} {question.AnswerSuffix}", paragraph));
                }

                templateDocument.Add(list);
            }

            templateDocument.Close();

            return(true);
        }
        public void NestedListAtTheEndOfAnotherNestedList()
        {
            String pdfFile = "nestedListAtTheEndOfAnotherNestedList.pdf";
            // step 1
            Document document = new Document();

            // step 2
            PdfWriter.GetInstance(document, File.Create(DEST_FOLDER + pdfFile));
            // step 3
            document.Open();
            // step 4
            PdfPTable table = new PdfPTable(1);
            PdfPCell  cell  = new PdfPCell();

            cell.BackgroundColor = BaseColor.ORANGE;

            RomanList romanlist = new RomanList(true, 20);

            romanlist.IndentationLeft = 10f;
            romanlist.Add("One");
            romanlist.Add("Two");
            romanlist.Add("Three");

            RomanList romanlist2 = new RomanList(true, 20);

            romanlist2.IndentationLeft = 10f;
            romanlist2.Add("One");
            romanlist2.Add("Two");
            romanlist2.Add("Three");

            romanlist.Add(romanlist2);
            //romanlist.add("Four");

            List list = new List(List.ORDERED, 20f);

            list.SetListSymbol("\u2022");
            list.IndentationLeft = 20f;
            list.Add("One");
            list.Add("Two");
            list.Add("Three");
            list.Add("Four");
            list.Add("Roman List");
            list.Add(romanlist);

            list.Add("Five");
            list.Add("Six");

            cell.AddElement(list);
            table.AddCell(cell);
            document.Add(table);
            // step 5
            document.Close();

            CompareTool compareTool = new CompareTool();
            String      error       = compareTool.CompareByContent(DEST_FOLDER + pdfFile, SOURCE_FOLDER + pdfFile, DEST_FOLDER, "diff_");

            if (error != null)
            {
                Assert.Fail(error);
            }
        }
示例#47
0
    private void AddTeam(Hold team, Document doc, bool addSeparator)
    {
        iTextSharp.text.Font  header   = FontFactory.GetFont("Arial", 16, iTextSharp.text.Font.BOLD, BaseColor.Black);
        iTextSharp.text.Font  boldText = FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.BOLD, BaseColor.Black);
        iTextSharp.text.Font  descFont = FontFactory.GetFont("Verdana", 12, iTextSharp.text.Font.NORMAL, BaseColor.DarkGray);
        iTextSharp.text.Font  text     = FontFactory.GetFont("Verdana", 12, iTextSharp.text.Font.NORMAL, BaseColor.Black);
        iTextSharp.text.Font  textRed  = FontFactory.GetFont("Verdana", 12, iTextSharp.text.Font.NORMAL, BaseColor.Red);
        iTextSharp.text.Image img      = null;

        if (string.IsNullOrEmpty(team.Image) == false)
        {
            string imgPath = Path.Combine(Directory.GetCurrentDirectory(), "images/" + team.Image);
            if (File.Exists(imgPath))
            {
                img = iTextSharp.text.Image.GetInstance(imgPath);
                img.ScaleToFit(120f, 120f);
                img.Alignment       = iTextSharp.text.Image.TEXTWRAP | iTextSharp.text.Image.ALIGN_RIGHT;
                img.IndentationLeft = 9f;
                img.SpacingAfter    = 9f;
                img.BorderWidthTop  = 16f;
                img.BorderColorTop  = iTextSharp.text.BaseColor.White;
            }
            else
            {
                Console.WriteLine("Kan ikke finde billedet " + team.Image);
            }
        }

        Paragraph p = new Paragraph();

        p.Alignment = Element.ALIGN_JUSTIFIED;

        Chunk nameChunk = new Chunk(team.Name, header);
        Chunk ageChunk  = new Chunk(" for " + team.Age + "\n\n", text);

        p.Add(nameChunk);
        p.Add(ageChunk);

        iTextSharp.text.List list = new iTextSharp.text.List(iTextSharp.text.List.UNORDERED, 10f);
        list.SetListSymbol("\u2022");
        list.IndentationLeft = 20f;
        list.Add("Ansvarlig Instruktør : " + team.Responsible);
        list.Add("Yderligere Instruktør(er) : " + team.Assistent);
        list.Add("Tidspunkt : " + team.WeekDay + " " + team.Time + " i " + team.Place);
        list.Add("Deltagere : " + team.Min + " til " + team.Max);
        list.Add("Pris : " + team.Price);
        list.Add("Opstart : " + team.StartDate);
        p.Add(list);


        Paragraph p1 = new Paragraph();

        Chunk descChunk = new Chunk("\n\n" + team.Description + "\n\n", descFont);

        p1.Add(descChunk);

        if (string.IsNullOrWhiteSpace(team.HalfSeason) == false && team.HalfSeason.ToLowerInvariant() != "nej")
        {
            Chunk halfSeason  = new Chunk("Bemærk", boldText);
            Chunk halfSeason2 = new Chunk(" Dette hold udbydes kun for en halv sæson og løber indtil " + team.HalfSeason, text);
            p1.Add(halfSeason);
            p1.Add(halfSeason2);
        }

        if (string.IsNullOrWhiteSpace(team.Status))
        {
            Chunk extraInfo = new Chunk("\nHoldet er endnu ikke helt på plads ( " + team.Comments + ")", textRed);

            p1.Add(extraInfo);
        }
        if (addSeparator)
        {
            p1.Add(new Chunk("\n\n"));
            DottedLineSeparator dottedline = new DottedLineSeparator();
            dottedline.Offset = 0;
            dottedline.Gap    = 2f;
            p1.Add(dottedline);
            p1.Add(new Chunk("\n\n"));
        }

        if (img != null)
        {
            doc.Add(img);
        }

        doc.Add(p);
        doc.Add(p1);
    }